From 993603d830d2d5edd3423a5678bf263b49f35a09 Mon Sep 17 00:00:00 2001 From: denn0x <55638248+denn0x@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:47:15 +0000 Subject: [PATCH] Integrate mesh translation, D3D12 submission and memory handling --- CMakeLists.txt | 382 +- src/era_heap.cpp | 5 +- src/era_query.cpp | 7 +- src/startup_stubs/bcpack_bc6h.h | 318 + src/startup_stubs/bcpack_decoder.h | 3 + src/startup_stubs/buffer_address_index.h | 76 + src/startup_stubs/chad.cpp | 29 +- src/startup_stubs/d3d12_capture.inl | 16 + src/startup_stubs/d3d12_cold_texture.inl | 70 + src/startup_stubs/d3d12_compute.inl | 1276 ++++ .../d3d12_compute_binding_trace.inl | 2 +- src/startup_stubs/d3d12_copy_buffer.inl | 80 + src/startup_stubs/d3d12_draw.inl | 2849 ++++++++- src/startup_stubs/d3d12_gpu_time.inl | 343 ++ src/startup_stubs/d3d12_indirect.inl | 759 +++ src/startup_stubs/d3d12_mem_counters.h | 55 + src/startup_stubs/d3d12_mem_counters.inl | 271 + src/startup_stubs/d3d12_memcut_alias.inl | 48 + src/startup_stubs/d3d12_memcut_release.inl | 361 ++ src/startup_stubs/d3d12_memory_srv.inl | 724 ++- src/startup_stubs/d3d12_mesh.inl | 1201 ++++ src/startup_stubs/d3d12_present.inl | 200 +- src/startup_stubs/d3d12_range_alias.inl | 125 + src/startup_stubs/d3d12_rawaddr.inl | 311 + src/startup_stubs/d3d12_record_trace.inl | 716 +++ src/startup_stubs/d3d12_regblob.inl | 520 ++ src/startup_stubs/d3d12_upload_ring.inl | 469 ++ src/startup_stubs/d3d12_vdesc.inl | 56 + src/startup_stubs/d3d12_xs_device.cpp | 2590 +++++++- src/startup_stubs/d3d12_xs_traps.cpp | 5 + src/startup_stubs/derived_blend.h | 19 +- src/startup_stubs/dstorage_status_stats.h | 210 + src/startup_stubs/gfx10_layout_equations.inc | 62 + src/startup_stubs/gfx10_layout_local.h | 237 + src/startup_stubs/gfx10_view_words.h | 324 + src/startup_stubs/local_log.h | 102 +- src/startup_stubs/log_cap.h | 33 + src/startup_stubs/overlay_window.h | 13 + src/startup_stubs/pipeline_state_decode.h | 314 +- src/startup_stubs/placed_pool.h | 88 + src/startup_stubs/rawaddr_table.h | 167 + src/startup_stubs/runtime_proxy.cpp | 103 +- src/startup_stubs/state_block_blend.h | 59 +- src/startup_stubs/title_composition.h | 48 + .../translated_sampler_bindings.h | 73 +- src/startup_stubs/trap.h | 40 + src/xmem_census.cpp | 484 ++ src/xmem_census.h | 26 + src/xmem_gpu_pool.cpp | 74 + src/xmem_gpu_pool.h | 11 + src/xmem_low.h | 42 + src/xmem_mapped_pages.cpp | 771 ++- src/xmem_shim.cpp | 3 +- src/xmem_shim.def | 21 +- tests/bcpack_bc6h_test.cpp | 127 + tests/bcpack_bc6h_vectors.inl | 193 + tests/bcpack_bcn_check.py | 267 + tests/bcpack_bcn_decode_test.cpp | 94 + tests/buffer_address_index_check.cpp | 112 + tests/desktop_gpu.h | 2 +- tests/gfx10_layout_check.cpp | 654 ++ tests/gfx10_layout_golden.txt | 40 + tests/mesh_clip_distance_check.py | 94 + tests/mesh_loop_state_check.py | 168 + tests/mesh_pc_table_check.py | 41 + tests/mesh_perlane_loop_check.py | 109 + tests/mesh_waterfall_check.py | 177 + tests/offscreen_check.cpp | 6 +- tests/startup_address_srv.cpp | 104 + tests/startup_bfm_absdiff_check.py | 60 + tests/startup_buffer_address_check.py | 11 +- tests/startup_buffer_heap_index_check.py | 100 + tests/startup_buffer_store_check.py | 136 + tests/startup_carry_dst_check.py | 38 + tests/startup_class_f16_sdwa_check.py | 95 + tests/startup_class_sdwa_check.py | 81 + tests/startup_clip_distance_check.py | 58 + tests/startup_cselect_vcc_lo_check.py | 52 + tests/startup_cx_async.cpp | 353 ++ tests/startup_cx_async.hlsl | 15 + tests/startup_draw_async_check.py | 79 + tests/startup_draw_fma_check.py | 106 + tests/startup_draw_heap_check.py | 75 + tests/startup_draw_heapwords_check.py | 70 + tests/startup_draw_lock_split_check.py | 135 + tests/startup_draw_lock_times.cpp | 76 + tests/startup_draw_srv_limit_check.py | 63 + tests/startup_draw_state.cpp | 295 + tests/startup_draw_state_check.py | 112 + tests/startup_draw_uav.cpp | 313 + tests/startup_draw_uav_check.py | 289 + tests/startup_dstorage_status_stats_check.cpp | 98 + tests/startup_execz_join_check.py | 51 + tests/startup_fmt_load_table_check.py | 169 + tests/startup_format_load_check.py | 111 + tests/startup_format_store_check.py | 105 + tests/startup_frame_copy.cpp | 112 +- tests/startup_frame_copy_check.py | 98 +- tests/startup_front_face_check.py | 126 + tests/startup_gfx10_view_words_check.cpp | 233 + tests/startup_gfx2hlsl_coverage_check.py | 685 +++ tests/startup_gfx2hlsl_f32_lg_local_check.py | 747 +++ tests/startup_gfx2hlsl_root_local_check.py | 83 + tests/startup_heap_texture_check.py | 75 + tests/startup_image_3d_check.py | 9 +- tests/startup_image_d16_check.py | 87 + tests/startup_image_get_lod_check.py | 116 + tests/startup_image_invariant_check.py | 99 + tests/startup_image_sample_b_local_check.py | 82 + tests/startup_image_sample_d_check.py | 78 + tests/startup_image_sample_l_check.py | 9 +- tests/startup_indirect_dispatch.hlsl | 19 + tests/startup_indirect_dispatch_local.cpp | 311 + tests/startup_int_three_operand_check.py | 68 + tests/startup_interp_f16_check.py | 193 + tests/startup_lane_invariant_check.py | 165 + tests/startup_lit64_check.py | 49 + tests/startup_literal_halves_check.py | 67 + tests/startup_log_cap_check.cpp | 71 + tests/startup_loop_carried_check.py | 117 + tests/startup_loop_regions_check.py | 169 + tests/startup_memory_srv_announced_check.py | 109 + tests/startup_memory_srv_detile_check.py | 174 + tests/startup_mesh_barrier_ranges_check.py | 76 + tests/startup_mesh_descword_check.py | 106 + tests/startup_mesh_dispatch.cpp | 1299 ++++ tests/startup_mesh_dispatch.hlsl | 117 + tests/startup_mesh_exec_lineage_check.py | 111 + tests/startup_mesh_exec_off_check.py | 257 + tests/startup_mesh_exec_restore_check.py | 251 + tests/startup_mesh_exec_walk_check.py | 94 + tests/startup_mesh_first_lane_check.py | 72 + tests/startup_mesh_heap_sampler_check.py | 187 + tests/startup_mesh_lane_scc_check.py | 399 ++ tests/startup_mesh_literal_flow_check.py | 99 + tests/startup_mesh_restored_scalar_check.py | 80 + tests/startup_mesh_rtv_variant_check.py | 188 + tests/startup_mesh_salu_check.py | 122 + tests/startup_mesh_spi_input_check.py | 116 + tests/startup_mesh_spill_check.py | 128 + tests/startup_mesh_vcc_data_check.py | 136 + tests/startup_mrt_wide_int_check.py | 59 + tests/startup_pack_f16_check.py | 87 + tests/startup_packed_position_check.py | 10 +- tests/startup_pipeline_state_local_check.cpp | 351 ++ tests/startup_placed_fast.cpp | 113 + tests/startup_present_producer.cpp | 22 + tests/startup_present_producer_check.py | 6 + tests/startup_probe_cache.cpp | 77 + tests/startup_quad_divergent_check.py | 86 + tests/startup_quad_dpp_check.py | 178 + tests/startup_quad_uniform_check.py | 105 + tests/startup_readfirstlane_chain_check.py | 145 + tests/startup_readfirstlane_exec_check.py | 124 + tests/startup_resource_retire_title.cpp | 99 +- tests/startup_root_cbv.cpp | 2 + tests/startup_root_srv_lazy_check.py | 38 + tests/startup_round_mode_check.py | 389 ++ tests/startup_rtv_bind_local.cpp | 215 + tests/startup_sample_c_border_check.py | 70 + tests/startup_sample_c_preclamp_check.py | 76 + tests/startup_sampler_comparison_check.cpp | 24 + tests/startup_sampler_x.cpp | 20 +- tests/startup_saveexec_same_reg_check.py | 58 + tests/startup_scalar_bits_check.py | 155 + tests/startup_scalar_complement_mask_check.py | 90 + tests/startup_scalar_const_fold_check.py | 63 + tests/startup_scalar_ff_check.py | 44 + tests/startup_scalar_nand_check.py | 70 + tests/startup_scalar_pack_hh_check.py | 98 + tests/startup_scmp_u64_check.py | 115 + tests/startup_sdwa_cvt_check.py | 68 + tests/startup_sdwa_mov_check.py | 101 + tests/startup_smem_overlap_mask_check.py | 76 + tests/startup_sopk_sign_check.py | 39 + tests/startup_spi_input_check.py | 96 + tests/startup_stream_check.py | 20 +- tests/startup_stream_consumer.cpp | 51 + tests/startup_stream_draw.cpp | 41 +- tests/startup_stream_setup.cpp | 2 +- tests/startup_tbuffer_uint_snorm_check.py | 122 + tests/startup_translator_check.py | 2 +- tests/startup_vopc_dpp_check.py | 63 + tests/startup_vsregs_state_check.py | 87 + tests/startup_vswap_check.py | 99 + tests/startup_waterfall_check.py | 223 + tests/tile_mapping_shared_heap_check.cpp | 205 + tests/xmem_scatter_refusal_check.py | 273 + tools/bcpack_bcn.py | 219 + tools/disasm_rdna2.py | 50 +- tools/startup/compute_harness.cpp | 363 ++ tools/startup/debug_launch.py | 3 + tools/startup/gfx2hlsl.py | 5440 +++++++++-------- tools/startup/gpu_slab_pool.py | 120 + tools/startup/mesh2hlsl.py | 3684 +++++++++++ tools/startup/mesh_harness.cpp | 536 ++ tools/startup/run.ps1 | 1 + tools/startup/window_status.py | 96 + 198 files changed, 42505 insertions(+), 3078 deletions(-) create mode 100644 src/startup_stubs/bcpack_bc6h.h create mode 100644 src/startup_stubs/buffer_address_index.h create mode 100644 src/startup_stubs/d3d12_cold_texture.inl create mode 100644 src/startup_stubs/d3d12_compute.inl create mode 100644 src/startup_stubs/d3d12_copy_buffer.inl create mode 100644 src/startup_stubs/d3d12_gpu_time.inl create mode 100644 src/startup_stubs/d3d12_indirect.inl create mode 100644 src/startup_stubs/d3d12_mem_counters.h create mode 100644 src/startup_stubs/d3d12_mem_counters.inl create mode 100644 src/startup_stubs/d3d12_memcut_alias.inl create mode 100644 src/startup_stubs/d3d12_memcut_release.inl create mode 100644 src/startup_stubs/d3d12_mesh.inl create mode 100644 src/startup_stubs/d3d12_range_alias.inl create mode 100644 src/startup_stubs/d3d12_rawaddr.inl create mode 100644 src/startup_stubs/d3d12_record_trace.inl create mode 100644 src/startup_stubs/d3d12_regblob.inl create mode 100644 src/startup_stubs/d3d12_upload_ring.inl create mode 100644 src/startup_stubs/d3d12_vdesc.inl create mode 100644 src/startup_stubs/d3d12_xs_traps.cpp create mode 100644 src/startup_stubs/dstorage_status_stats.h create mode 100644 src/startup_stubs/gfx10_layout_equations.inc create mode 100644 src/startup_stubs/gfx10_layout_local.h create mode 100644 src/startup_stubs/gfx10_view_words.h create mode 100644 src/startup_stubs/log_cap.h create mode 100644 src/startup_stubs/placed_pool.h create mode 100644 src/startup_stubs/rawaddr_table.h create mode 100644 src/startup_stubs/title_composition.h create mode 100644 src/xmem_census.cpp create mode 100644 src/xmem_census.h create mode 100644 src/xmem_gpu_pool.cpp create mode 100644 src/xmem_gpu_pool.h create mode 100644 src/xmem_low.h create mode 100644 tests/bcpack_bc6h_test.cpp create mode 100644 tests/bcpack_bc6h_vectors.inl create mode 100644 tests/bcpack_bcn_check.py create mode 100644 tests/bcpack_bcn_decode_test.cpp create mode 100644 tests/buffer_address_index_check.cpp create mode 100644 tests/gfx10_layout_check.cpp create mode 100644 tests/gfx10_layout_golden.txt create mode 100644 tests/mesh_clip_distance_check.py create mode 100644 tests/mesh_loop_state_check.py create mode 100644 tests/mesh_pc_table_check.py create mode 100644 tests/mesh_perlane_loop_check.py create mode 100644 tests/mesh_waterfall_check.py create mode 100644 tests/startup_bfm_absdiff_check.py create mode 100644 tests/startup_buffer_heap_index_check.py create mode 100644 tests/startup_buffer_store_check.py create mode 100644 tests/startup_carry_dst_check.py create mode 100644 tests/startup_class_f16_sdwa_check.py create mode 100644 tests/startup_class_sdwa_check.py create mode 100644 tests/startup_clip_distance_check.py create mode 100644 tests/startup_cselect_vcc_lo_check.py create mode 100644 tests/startup_cx_async.cpp create mode 100644 tests/startup_cx_async.hlsl create mode 100644 tests/startup_draw_async_check.py create mode 100644 tests/startup_draw_fma_check.py create mode 100644 tests/startup_draw_heap_check.py create mode 100644 tests/startup_draw_heapwords_check.py create mode 100644 tests/startup_draw_lock_split_check.py create mode 100644 tests/startup_draw_lock_times.cpp create mode 100644 tests/startup_draw_srv_limit_check.py create mode 100644 tests/startup_draw_state.cpp create mode 100644 tests/startup_draw_state_check.py create mode 100644 tests/startup_draw_uav.cpp create mode 100644 tests/startup_draw_uav_check.py create mode 100644 tests/startup_dstorage_status_stats_check.cpp create mode 100644 tests/startup_execz_join_check.py create mode 100644 tests/startup_fmt_load_table_check.py create mode 100644 tests/startup_format_load_check.py create mode 100644 tests/startup_format_store_check.py create mode 100644 tests/startup_front_face_check.py create mode 100644 tests/startup_gfx10_view_words_check.cpp create mode 100644 tests/startup_gfx2hlsl_coverage_check.py create mode 100644 tests/startup_gfx2hlsl_f32_lg_local_check.py create mode 100644 tests/startup_gfx2hlsl_root_local_check.py create mode 100644 tests/startup_heap_texture_check.py create mode 100644 tests/startup_image_d16_check.py create mode 100644 tests/startup_image_get_lod_check.py create mode 100644 tests/startup_image_invariant_check.py create mode 100644 tests/startup_image_sample_b_local_check.py create mode 100644 tests/startup_image_sample_d_check.py create mode 100644 tests/startup_indirect_dispatch.hlsl create mode 100644 tests/startup_indirect_dispatch_local.cpp create mode 100644 tests/startup_int_three_operand_check.py create mode 100644 tests/startup_interp_f16_check.py create mode 100644 tests/startup_lane_invariant_check.py create mode 100644 tests/startup_lit64_check.py create mode 100644 tests/startup_literal_halves_check.py create mode 100644 tests/startup_log_cap_check.cpp create mode 100644 tests/startup_loop_carried_check.py create mode 100644 tests/startup_loop_regions_check.py create mode 100644 tests/startup_memory_srv_announced_check.py create mode 100644 tests/startup_memory_srv_detile_check.py create mode 100644 tests/startup_mesh_barrier_ranges_check.py create mode 100644 tests/startup_mesh_descword_check.py create mode 100644 tests/startup_mesh_dispatch.cpp create mode 100644 tests/startup_mesh_dispatch.hlsl create mode 100644 tests/startup_mesh_exec_lineage_check.py create mode 100644 tests/startup_mesh_exec_off_check.py create mode 100644 tests/startup_mesh_exec_restore_check.py create mode 100644 tests/startup_mesh_exec_walk_check.py create mode 100644 tests/startup_mesh_first_lane_check.py create mode 100644 tests/startup_mesh_heap_sampler_check.py create mode 100644 tests/startup_mesh_lane_scc_check.py create mode 100644 tests/startup_mesh_literal_flow_check.py create mode 100644 tests/startup_mesh_restored_scalar_check.py create mode 100644 tests/startup_mesh_rtv_variant_check.py create mode 100644 tests/startup_mesh_salu_check.py create mode 100644 tests/startup_mesh_spi_input_check.py create mode 100644 tests/startup_mesh_spill_check.py create mode 100644 tests/startup_mesh_vcc_data_check.py create mode 100644 tests/startup_mrt_wide_int_check.py create mode 100644 tests/startup_pack_f16_check.py create mode 100644 tests/startup_pipeline_state_local_check.cpp create mode 100644 tests/startup_placed_fast.cpp create mode 100644 tests/startup_probe_cache.cpp create mode 100644 tests/startup_quad_divergent_check.py create mode 100644 tests/startup_quad_dpp_check.py create mode 100644 tests/startup_quad_uniform_check.py create mode 100644 tests/startup_readfirstlane_chain_check.py create mode 100644 tests/startup_readfirstlane_exec_check.py create mode 100644 tests/startup_root_srv_lazy_check.py create mode 100644 tests/startup_round_mode_check.py create mode 100644 tests/startup_rtv_bind_local.cpp create mode 100644 tests/startup_sample_c_border_check.py create mode 100644 tests/startup_sample_c_preclamp_check.py create mode 100644 tests/startup_saveexec_same_reg_check.py create mode 100644 tests/startup_scalar_bits_check.py create mode 100644 tests/startup_scalar_complement_mask_check.py create mode 100644 tests/startup_scalar_const_fold_check.py create mode 100644 tests/startup_scalar_ff_check.py create mode 100644 tests/startup_scalar_nand_check.py create mode 100644 tests/startup_scalar_pack_hh_check.py create mode 100644 tests/startup_scmp_u64_check.py create mode 100644 tests/startup_sdwa_cvt_check.py create mode 100644 tests/startup_sdwa_mov_check.py create mode 100644 tests/startup_smem_overlap_mask_check.py create mode 100644 tests/startup_sopk_sign_check.py create mode 100644 tests/startup_spi_input_check.py create mode 100644 tests/startup_tbuffer_uint_snorm_check.py create mode 100644 tests/startup_vopc_dpp_check.py create mode 100644 tests/startup_vsregs_state_check.py create mode 100644 tests/startup_vswap_check.py create mode 100644 tests/startup_waterfall_check.py create mode 100644 tests/tile_mapping_shared_heap_check.cpp create mode 100644 tests/xmem_scatter_refusal_check.py create mode 100644 tools/bcpack_bcn.py create mode 100644 tools/startup/compute_harness.cpp create mode 100644 tools/startup/gpu_slab_pool.py create mode 100644 tools/startup/mesh2hlsl.py create mode 100644 tools/startup/mesh_harness.cpp create mode 100644 tools/startup/window_status.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ef3e09517f..64d6f801ec 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -167,7 +167,8 @@ set_tests_properties(era_physical_owns_last_page_control PROPERTIES PASS_REGULAR # Desktop xmem.dll for native and mapped callers. add_library(xmem_shim SHARED src/xmem_shim.cpp src/xmem_shim.def src/xmem_gpu_usage.cpp src/adapter_identity.cpp src/era_heap.cpp src/era_query.cpp src/era_physical.cpp - src/era_title_gpu.cpp src/era_gpu_alias.cpp src/era_title_va.cpp src/xmem_mapped_pages.cpp) + src/era_title_gpu.cpp src/era_gpu_alias.cpp src/era_title_va.cpp src/xmem_mapped_pages.cpp src/xmem_census.cpp + src/xmem_gpu_pool.cpp) set_target_properties(xmem_shim PROPERTIES OUTPUT_NAME xmem) # LINK uses explicit export ordinals in the generated import library. Keep # those ordinals in the DLL and build the consumer library with names. @@ -381,7 +382,7 @@ target_compile_options(x2w_build_rev PRIVATE /Zl) # Desktop d3d12_xs.dll for the package DLLs' two named d3d12_xs root-signature imports. add_library(d3d12_xs_shim SHARED src/d3d12_xs_shim.cpp src/d3d12x_device_slots.cpp - src/d3d12_xs_iids.cpp src/d3d12_xs_shim.def src/startup_stubs/d3d12_xs_device.cpp) + src/d3d12_xs_iids.cpp src/d3d12_xs_shim.def src/startup_stubs/d3d12_xs_traps.cpp src/startup_stubs/d3d12_xs_device.cpp) 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) @@ -545,7 +546,7 @@ endif() # The DirectStorage heartbeat reports this process's peak commit (#1199). target_link_libraries(startup_stub_xcrdapi PRIVATE psapi) target_sources(startup_stub_gameinput PRIVATE src/startup_stubs/runtime_proxy.cpp) -target_link_libraries(d3d12_xs_shim PRIVATE user32 gdi32 d3dcompiler dxgi x2w_build_rev) +target_link_libraries(d3d12_xs_shim PRIVATE user32 gdi32 dcomp d3dcompiler dxgi x2w_build_rev) target_compile_options(d3d12_xs_shim PRIVATE /bigobj) set_target_properties(xmem_shim d3d12_xs_shim ${startup_stub_targets} PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") @@ -639,6 +640,10 @@ foreach(adapter IN ITEMS hardware warp) set_tests_properties(startup_view_heap_${adapter} PROPERTIES SKIP_RETURN_CODE 77) endforeach() add_executable(startup_stub_consumer tests/startup_stub_consumer.cpp) +# BCPack BC6H rebuild and its dictionary fallback on synthetic lane symbols (bcpack_bc6h.h). +add_executable(bcpack_bc6h_test tests/bcpack_bc6h_test.cpp) +target_compile_features(bcpack_bc6h_test PRIVATE cxx_std_17) +add_test(NAME bcpack_bc6h COMMAND bcpack_bc6h_test) add_executable(startup_gameinput_keys tests/startup_gameinput_keys.cpp) target_compile_features(startup_gameinput_keys PRIVATE cxx_std_17) add_test(NAME startup_gameinput_keys COMMAND startup_gameinput_keys "$") @@ -679,7 +684,10 @@ set_tests_properties(startup_present_signature_unheld_source_control_warp PROPER if(EXISTS "${INTAKE_PYTHON}") add_executable(startup_present_producer tests/startup_present_producer.cpp) target_compile_features(startup_present_producer PRIVATE cxx_std_17) - target_link_libraries(startup_present_producer PRIVATE d3d12_xs_shim d3d12 dxgi) + target_link_libraries(startup_present_producer PRIVATE d3d12_xs_shim d3d12 dxgi user32) + add_test(NAME startup_present_original_window_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_present_producer_check.py" warp "$" title-window) + set_tests_properties(startup_present_original_window_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) foreach(backend IN ITEMS warp hardware) add_test(NAME startup_present_producer_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_present_producer_check.py" "${backend}" "$") @@ -693,6 +701,20 @@ add_executable(startup_placement_alloc tests/startup_placement_alloc.cpp) target_compile_features(startup_placement_alloc PRIVATE cxx_std_17) target_include_directories(startup_placement_alloc PRIVATE src) add_test(NAME startup_placement_alloc COMMAND startup_placement_alloc) +# Log caps that never wrap (src/startup_stubs/log_cap.h); the old wrapping pattern is the negative control. +add_executable(startup_log_cap_check tests/startup_log_cap_check.cpp) +target_compile_features(startup_log_cap_check PRIVATE cxx_std_17) +target_include_directories(startup_log_cap_check PRIVATE src) +add_test(NAME startup_log_cap COMMAND startup_log_cap_check) +add_test(NAME startup_log_cap_wrap_control COMMAND startup_log_cap_check --mutate wrap) +set_tests_properties(startup_log_cap_wrap_control PROPERTIES WILL_FAIL TRUE) +# Status wait diagnostics of the DirectStorage stand-in (src/startup_stubs/dstorage_status_stats.h). +add_executable(startup_dstorage_status_stats_check tests/startup_dstorage_status_stats_check.cpp) +target_compile_features(startup_dstorage_status_stats_check PRIVATE cxx_std_17) +target_include_directories(startup_dstorage_status_stats_check PRIVATE src) +add_test(NAME startup_dstorage_status_stats COMMAND startup_dstorage_status_stats_check) +add_test(NAME startup_dstorage_status_stats_stale_control COMMAND startup_dstorage_status_stats_check --mutate no-stale) +set_tests_properties(startup_dstorage_status_stats_stale_control PROPERTIES WILL_FAIL TRUE) # The same registration under the lock held exclusively, and max_width kept at the widest record # (src/startup_stubs/placement_publish.h). The mutated run is the negative control. add_executable(startup_placement_publish_check tests/startup_placement_publish_check.cpp) @@ -1201,7 +1223,8 @@ add_test(NAME startup_typed_buffer_view COMMAND startup_typed_buffer_view) add_library(startup_stream_setup_obj OBJECT tests/startup_stream_setup.cpp) target_compile_features(startup_stream_setup_obj PRIVATE cxx_std_17) add_executable(startup_stream_consumer tests/startup_stream_consumer.cpp $ tests/startup_stream_draw.cpp - tests/startup_address_srv.cpp tests/startup_root_cbv.cpp tests/startup_root_heap.cpp) + tests/startup_address_srv.cpp tests/startup_root_cbv.cpp tests/startup_root_heap.cpp + tests/startup_draw_uav.cpp) target_compile_features(startup_stream_consumer PRIVATE cxx_std_17) target_link_libraries(startup_stream_consumer PRIVATE d3d12_xs_shim startup_stub_xg_xs d3d12 dxgi d3dcompiler) target_sources(startup_stream_consumer PRIVATE tests/startup_frame_copy.cpp) @@ -1221,6 +1244,10 @@ add_executable(startup_draw_depth_target tests/startup_draw_depth_target.cpp $) +target_compile_features(startup_draw_state PRIVATE cxx_std_17) +target_link_libraries(startup_draw_state PRIVATE d3d12_xs_shim d3d12 dxgi) add_executable(startup_stream_rasterizer tests/startup_stream_rasterizer.cpp $) target_compile_features(startup_stream_rasterizer PRIVATE cxx_std_17) target_link_libraries(startup_stream_rasterizer PRIVATE d3d12_xs_shim d3d12 dxgi) @@ -1244,9 +1271,9 @@ add_dependencies(startup_queue_page_batch xmem_shim) add_test(NAME startup_queue_page_batch_warp COMMAND startup_queue_page_batch "$") add_test(NAME startup_queue_page_batch_runs_warp COMMAND startup_queue_page_batch "$" runs) set_tests_properties(startup_queue_page_batch_warp PROPERTIES RUN_SERIAL TRUE TIMEOUT 90 - ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=0") + ENVIRONMENT "X2W_UPSTREAM_QUEUE_PAGE_BATCH=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=0") set_tests_properties(startup_queue_page_batch_runs_warp PROPERTIES RUN_SERIAL TRUE TIMEOUT 90 SKIP_RETURN_CODE 77 - ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=1") + ENVIRONMENT "X2W_UPSTREAM_QUEUE_PAGE_BATCH=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=1") # Closed lists stay submittable, also after their allocator's Reset (#1352). add_executable(startup_list_resubmit tests/startup_list_resubmit.cpp) @@ -1269,6 +1296,14 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_TEST_SUBMIT_FENCE_FAIL=1") endforeach() +add_executable(startup_rtv_bind_local tests/startup_rtv_bind_local.cpp) +target_compile_features(startup_rtv_bind_local PRIVATE cxx_std_17) +target_link_libraries(startup_rtv_bind_local PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_rtv_bind_local_${backend} COMMAND startup_rtv_bind_local ${backend}) + set_tests_properties(startup_rtv_bind_local_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") +endforeach() add_executable(startup_upload_arena tests/startup_upload_arena.cpp) target_compile_features(startup_upload_arena PRIVATE cxx_std_17) target_include_directories(startup_upload_arena PRIVATE src) @@ -1387,6 +1422,13 @@ endforeach() # X2W_D3D12_RELEASE_RETIRED_VIEWS=1 frees a released class texture that only tracked slot-18 descriptor slots keep alive by # replacing those slots with null descriptors. `keep` is the negative control (views switch off, or retire switch off). +add_test(NAME startup_cold_texture_priority_off_warp COMMAND startup_resource_retire_title warp cold-off) +set_tests_properties(startup_cold_texture_priority_off_warp PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_COLD_TEXTURE_PRIORITY=0;X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1") +add_test(NAME startup_cold_texture_priority_warp COMMAND startup_resource_retire_title warp cold) +set_tests_properties(startup_cold_texture_priority_warp PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_COLD_TEXTURE_PRIORITY=1;X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1") + add_executable(startup_resource_retire_views tests/startup_resource_retire_views.cpp) target_include_directories(startup_resource_retire_views PRIVATE src) target_compile_features(startup_resource_retire_views PRIVATE cxx_std_17) @@ -1419,7 +1461,8 @@ foreach(backend IN ITEMS warp hardware) add_test(NAME startup_indirect_dispatch_${backend} COMMAND startup_indirect_dispatch ${backend}) add_test(NAME startup_indirect_root_constants_${backend} COMMAND startup_indirect_dispatch ${backend} constants) add_test(NAME startup_indirect_count_${backend} COMMAND startup_indirect_dispatch ${backend} count) - set_tests_properties(startup_indirect_dispatch_${backend} startup_indirect_root_constants_${backend} startup_indirect_count_${backend} PROPERTIES TIMEOUT 30) + set_tests_properties(startup_indirect_dispatch_${backend} startup_indirect_root_constants_${backend} startup_indirect_count_${backend} PROPERTIES TIMEOUT 30 + ENVIRONMENT "X2W_UPSTREAM_EXECUTE_INDIRECT=1;X2W_UPSTREAM_COMPUTE_ROOT=1") endforeach() set_tests_properties(startup_indirect_dispatch_hardware startup_indirect_root_constants_hardware startup_indirect_count_hardware PROPERTIES SKIP_RETURN_CODE 77) @@ -1532,6 +1575,23 @@ foreach(backend IN ITEMS warp hardware) set_tests_properties(startup_rtv_bind_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") endforeach() +set(x2w_upstream_list_paths "X2W_UPSTREAM_EXECUTE_INDIRECT=set:1;X2W_UPSTREAM_COMPUTE_ROOT=set:1;X2W_LIST_UPLOAD_PAGES=set:1;X2W_UPSTREAM_MESH86_CACHE=set:1") +foreach(backend IN ITEMS warp hardware) + set(x2w_upstream_list_tests startup_slot148_acceptance_${backend} startup_slot148_acceptance_nodebug_${backend} + startup_resource_budget_${backend}_debug0 startup_resource_budget_${backend}_debug0_inline_control + startup_resource_budget_${backend}_debug1 startup_resource_budget_${backend}_debug1_inline_control + startup_indirect_mesh_request_${backend} startup_rtv_bind_${backend} + startup_slot148_acceptance_serialized_${backend} startup_slot148_acceptance_serialized_nodebug_${backend}) + foreach(mode IN ITEMS draw_indexed draw translated_draw copy_provenance copy_provenance_off translated_indexed + translated_indexed_upload translated_indexed_rect mesh mesh_console mesh_amplified + mesh_xmem_arguments mesh_xmem_arguments_skip_wait rectlist translated_refusal_census + other_refusal_census translated_indexed_alias translated_indexed_alias_off) + list(APPEND x2w_upstream_list_tests startup_indirect_${mode}_${backend}) + endforeach() + set_tests_properties(${x2w_upstream_list_tests} PROPERTIES ENVIRONMENT_MODIFICATION "${x2w_upstream_list_paths}") +endforeach() +set_tests_properties(startup_indirect_counts_control_warp startup_indirect_translated_refusal_census_control_warp + startup_indirect_other_refusal_census_control_warp PROPERTIES ENVIRONMENT_MODIFICATION "${x2w_upstream_list_paths}") # CopyResource, ResolveSubresource and CopyBufferRegion on a recording list (slots 17, 19 and 15). add_executable(startup_list_copy tests/startup_list_copy.cpp) @@ -1609,6 +1669,7 @@ add_test(NAME startup_slice_footprints COMMAND startup_slice_footprints_check) add_test(NAME startup_slice_footprints_padded_control COMMAND startup_slice_footprints_check --mutate padded-last-row) set_tests_properties(startup_slice_footprints_padded_control PROPERTIES WILL_FAIL TRUE) + find_program(DXC_EXECUTABLE dxc REQUIRED) foreach(stage mesh vertex pixel) if(stage STREQUAL mesh) @@ -1636,24 +1697,28 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$" warp "$" dual-trace-disabled) - set_tests_properties(startup_indirect_mesh_lease_warp_dual-trace-disabled PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + set_tests_properties(startup_indirect_mesh_lease_warp_dual-trace-disabled PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT_MODIFICATION "${x2w_upstream_list_paths}") foreach(backend IN ITEMS warp hardware) add_test(NAME startup_indirect_mesh_lease_${backend}_dual-trace COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$" ${backend} "$" dual-trace) - set_tests_properties(startup_indirect_mesh_lease_${backend}_dual-trace PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + set_tests_properties(startup_indirect_mesh_lease_${backend}_dual-trace PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT_MODIFICATION "${x2w_upstream_list_paths}") add_test(NAME startup_indirect_mesh_cache_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$" ${backend}) - set_tests_properties(startup_indirect_mesh_cache_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + set_tests_properties(startup_indirect_mesh_cache_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT_MODIFICATION "${x2w_upstream_list_paths}") foreach(mode IN ITEMS ordered_control skip-wait dual dual-skip-srv dual-skip-argument dual-init-only loose-root) set(test_name startup_indirect_mesh_lease_${backend}_${mode}) add_test(NAME ${test_name} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$" ${backend} "$" ${mode}) - set_tests_properties(${test_name} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + set_tests_properties(${test_name} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT_MODIFICATION "${x2w_upstream_list_paths}") endforeach() endforeach() endif() @@ -1679,6 +1744,166 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_MESH86_FIXTURE_XMEM=$") endforeach() get_filename_component(DXC_BIN_DIR "${DXC_EXECUTABLE}" DIRECTORY) + +set(startup_indirect_headers) +foreach(entry IN ITEMS Writer Counter) + string(TOLOWER "${entry}" entry_lower) + set(header "${CMAKE_CURRENT_BINARY_DIR}/startup_indirect_${entry_lower}.h") + add_custom_command(OUTPUT "${header}" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E ${entry} -Vn startup_indirect_${entry_lower} -Fh "${header}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_dispatch.hlsl" + DEPENDS tests/startup_indirect_dispatch.hlsl VERBATIM) + list(APPEND startup_indirect_headers "${header}") +endforeach() +add_executable(startup_indirect_dispatch_local tests/startup_indirect_dispatch_local.cpp ${startup_indirect_headers}) +target_include_directories(startup_indirect_dispatch_local PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") +target_compile_features(startup_indirect_dispatch_local PRIVATE cxx_std_17) +target_link_libraries(startup_indirect_dispatch_local PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS gpu no-writer zero off huge huge-product wrap wrap-legacy wrap-cap) + add_test(NAME startup_indirect_dispatch_${mode}_${backend} COMMAND startup_indirect_dispatch_local ${backend} ${mode}) + set(indirect_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") + if(mode STREQUAL "off") + set(indirect_env "${indirect_env};X2W_INDIRECT_OFF=1") + endif() + set_tests_properties(startup_indirect_dispatch_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${indirect_env}") + endforeach() + # gpu mode with the read-back copies recorded (X2W_INDIRECT_READBACK) under the debug layer. + add_test(NAME startup_indirect_dispatch_gpu-readback_${backend} COMMAND startup_indirect_dispatch_local ${backend} gpu) + set_tests_properties(startup_indirect_dispatch_gpu-readback_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_INDIRECT_READBACK=8") + foreach(mode IN ITEMS rectrace rectrace-off) + add_test(NAME startup_indirect_dispatch_${mode}_${backend} COMMAND startup_indirect_dispatch_local ${backend} ${mode}) + set(rectrace_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_D3D12_TRACE_ALL=1") + if(mode STREQUAL "rectrace") + set(rectrace_env "${rectrace_env};X2W_MESH_RECORD_TRACE=1") + endif() + set_tests_properties(startup_indirect_dispatch_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${rectrace_env}") + endforeach() +endforeach() + +set(startup_mesh_headers) +foreach(entry IN ITEMS "MeshMain;ms_6_5;ms" "MeshHeap;ms_6_5;heap_ms" "MeshDescword;ms_6_5;descword_ms" "PixelMain;ps_6_5;ps" "PixelSampler;ps_6_5;smp_ps" "PixelUint;ps_6_5;uint_ps" "PixelStore;ps_6_5;store_ps" "Writer;cs_6_0;writer") + list(GET entry 0 entry_name) + list(GET entry 1 entry_profile) + list(GET entry 2 entry_short) + set(header "${CMAKE_CURRENT_BINARY_DIR}/startup_mesh_${entry_short}.h") + add_custom_command(OUTPUT "${header}" + COMMAND "${DXC_EXECUTABLE}" -T ${entry_profile} -E ${entry_name} -Vn startup_mesh_${entry_short} -Fh "${header}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh_dispatch.hlsl" + DEPENDS tests/startup_mesh_dispatch.hlsl VERBATIM) + list(APPEND startup_mesh_headers "${header}") +endforeach() +add_executable(startup_mesh_dispatch tests/startup_mesh_dispatch.cpp ${startup_mesh_headers}) +target_include_directories(startup_mesh_dispatch PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") +target_compile_features(startup_mesh_dispatch PRIVATE cxx_std_17) +target_link_libraries(startup_mesh_dispatch PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS gpu derived zero huge off missing depth words16 words32 wordsraw fmaprecise fmabad notargets rtvuint smpheap smpheapswap + statez statezge statezoff statecull stateculloff statedepth statecullflip statecullnone statezrepeat statezuncleared statezlateclear async asyncone rtvvariant uavtex uavtexnoflag rtvnops wordsoob stateclip stateclipon stateclipkeep + descword descwordoff) + add_test(NAME startup_mesh_dispatch_${mode}_${backend} COMMAND startup_mesh_dispatch ${backend} ${mode}) + set(mesh_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") + if(NOT mode STREQUAL "off") + set(mesh_env "${mesh_env};X2W_MESH=1") + endif() + set_tests_properties(startup_mesh_dispatch_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${mesh_env}") + endforeach() + foreach(mode IN ITEMS statez notargets zero statecull stateculloff rectrace rectraceapart) + add_test(NAME startup_mesh_dispatch_trace_${mode}_${backend} COMMAND startup_mesh_dispatch ${backend} ${mode}) + set_tests_properties(startup_mesh_dispatch_trace_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_MESH=1;X2W_D3D12_TRACE_ALL=1;X2W_D3D12_TRACE_TARGETS=1") + endforeach() + foreach(mode IN ITEMS statez zero) + add_test(NAME startup_mesh_dispatch_dump_${mode}_${backend} COMMAND startup_mesh_dispatch ${backend} ${mode}) + set_tests_properties(startup_mesh_dispatch_dump_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_MESH=1;X2W_TEST_MESH_DUMP=1") + endforeach() + foreach(mode IN ITEMS gpu zero) + add_test(NAME startup_mesh_dispatch_framestats_${mode}_${backend} COMMAND startup_mesh_dispatch ${backend} ${mode}) + set_tests_properties(startup_mesh_dispatch_framestats_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_MESH=1;X2W_MESH_STATS_FRAMES=1") + add_test(NAME startup_mesh_dispatch_framestatsmulti_${mode}_${backend} COMMAND startup_mesh_dispatch ${backend} ${mode}) + set_tests_properties(startup_mesh_dispatch_framestatsmulti_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_MESH=1;X2W_MESH_STATS_FRAMES=2;X2W_TEST_FS_MULTI=1") + endforeach() +endforeach() + +add_executable(startup_placed_fast tests/startup_placed_fast.cpp) +target_compile_features(startup_placed_fast PRIVATE cxx_std_17) +target_link_libraries(startup_placed_fast PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS fast walk) + add_test(NAME startup_placed_fast_${mode}_${backend} COMMAND startup_placed_fast ${backend} ${mode}) + set(placed_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1") + if(mode STREQUAL "fast") + set(placed_env "${placed_env};X2W_PLACED_FAST=1") + endif() + set_tests_properties(startup_placed_fast_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "${placed_env}") + endforeach() +endforeach() + +add_executable(startup_probe_cache tests/startup_probe_cache.cpp) +target_include_directories(startup_probe_cache PRIVATE src) +target_compile_features(startup_probe_cache PRIVATE cxx_std_17) +add_test(NAME startup_probe_cache_cache COMMAND startup_probe_cache cache) +set_tests_properties(startup_probe_cache_cache PROPERTIES TIMEOUT 60 ENVIRONMENT "X2W_PROBE_CACHE=1;X2W_PROBE_CACHE_MS=100") +add_test(NAME startup_probe_cache_nocache COMMAND startup_probe_cache nocache) +set_tests_properties(startup_probe_cache_nocache PROPERTIES TIMEOUT 60) + +add_executable(startup_draw_lock_times tests/startup_draw_lock_times.cpp) +target_compile_features(startup_draw_lock_times PRIVATE cxx_std_17) +add_dependencies(startup_draw_lock_times d3d12_xs_shim) +foreach(mode IN ITEMS on off) + add_test(NAME startup_draw_lock_times_${mode} COMMAND startup_draw_lock_times ${mode}) + set(lock_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1") + if(mode STREQUAL "on") + set(lock_env "${lock_env};X2W_DRAW_LOCK_TIMES=1") + endif() + set_tests_properties(startup_draw_lock_times_${mode} PROPERTIES TIMEOUT 60 ENVIRONMENT "${lock_env}") +endforeach() + +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_async_cs.h" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E CountMain -Vn startup_cx_async_cs -Fh "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_async_cs.h" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_cx_async.hlsl" + DEPENDS tests/startup_cx_async.hlsl VERBATIM) +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_cs.h" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E HeapMain -Vn startup_cx_heap_cs -Fh "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_cs.h" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_cx_async.hlsl" + DEPENDS tests/startup_cx_async.hlsl VERBATIM) +add_executable(startup_cx_async tests/startup_cx_async.cpp "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_async_cs.h" + "${CMAKE_CURRENT_BINARY_DIR}/startup_cx_heap_cs.h") +target_include_directories(startup_cx_async PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") +target_compile_features(startup_cx_async PRIVATE cxx_std_17) +target_link_libraries(startup_cx_async PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS async sync known seen heap) + add_test(NAME startup_cx_async_${mode}_${backend} COMMAND startup_cx_async ${backend} ${mode}) + set(cx_async_env "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") + if(mode STREQUAL "async") + set(cx_async_env "${cx_async_env};X2W_CX_ASYNC=1") + elseif(mode STREQUAL "known" OR mode STREQUAL "seen") + set(cx_async_env "${cx_async_env};X2W_CX_ASYNC=1;X2W_CX_PREWARM_ALL=1") + endif() + set_tests_properties(startup_cx_async_${mode}_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77 + ENVIRONMENT "${cx_async_env}") + endforeach() +endforeach() + +add_executable(tile_mapping_shared_heap_check tests/tile_mapping_shared_heap_check.cpp) +target_compile_features(tile_mapping_shared_heap_check PRIVATE cxx_std_17) +target_link_libraries(tile_mapping_shared_heap_check PRIVATE d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS plain shared) + add_test(NAME tile_mapping_${mode}_heap_${backend} COMMAND tile_mapping_shared_heap_check ${backend} ${mode}) + add_test(NAME tile_mapping_${mode}_heap_nodebug_${backend} COMMAND tile_mapping_shared_heap_check ${backend} ${mode} nodebug) + set_tests_properties(tile_mapping_${mode}_heap_${backend} tile_mapping_${mode}_heap_nodebug_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() +endforeach() + 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) @@ -1732,7 +1957,7 @@ if(NOT OFFSCREEN_AGILITY_620_DIR) else() target_sources(offscreen_check PRIVATE src/startup_stubs/d3d12_xs_device.cpp) endif() -target_link_libraries(offscreen_check PRIVATE d3d12 dxgi dxguid d3dcompiler user32 gdi32 x2w_build_rev) +target_link_libraries(offscreen_check PRIVATE d3d12 dxgi dxguid d3dcompiler user32 gdi32 dcomp x2w_build_rev) target_include_directories(offscreen_check PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") if(OFFSCREEN_AGILITY_620_DIR) if(EXISTS "${OFFSCREEN_AGILITY_620_DIR}/sdk.nupkg") @@ -1926,6 +2151,14 @@ add_executable(startup_sampler_comparison_check tests/startup_sampler_comparison target_include_directories(startup_sampler_comparison_check PRIVATE src) target_compile_features(startup_sampler_comparison_check PRIVATE cxx_std_17) add_test(NAME startup_sampler_comparison COMMAND startup_sampler_comparison_check) +add_executable(startup_gfx10_view_words_check tests/startup_gfx10_view_words_check.cpp) +target_include_directories(startup_gfx10_view_words_check PRIVATE src) +target_compile_features(startup_gfx10_view_words_check PRIVATE cxx_std_17) +add_test(NAME startup_gfx10_view_words COMMAND startup_gfx10_view_words_check) +foreach(mutation IN ITEMS legacy width order uint) + add_test(NAME startup_gfx10_view_words_${mutation}_control COMMAND startup_gfx10_view_words_check --mutate ${mutation}) + set_tests_properties(startup_gfx10_view_words_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() # Diagnostic line for a refused device slot 70 call (src/startup_stubs/memory_srv_report.h). add_executable(startup_memory_srv_report_check tests/startup_memory_srv_report_check.cpp) target_include_directories(startup_memory_srv_report_check PRIVATE src) @@ -2111,6 +2344,13 @@ target_compile_features(startup_depth_state_check PRIVATE cxx_std_17) add_test(NAME startup_depth_state COMMAND startup_depth_state_check) add_test(NAME startup_depth_state_switch_control COMMAND startup_depth_state_check --mutate switch) set_tests_properties(startup_depth_state_switch_control PROPERTIES WILL_FAIL TRUE) +add_executable(startup_pipeline_state_local_check tests/startup_pipeline_state_local_check.cpp) +target_include_directories(startup_pipeline_state_local_check PRIVATE src) +target_compile_features(startup_pipeline_state_local_check PRIVATE cxx_std_17) +add_test(NAME startup_pipeline_state_local COMMAND startup_pipeline_state_local_check) +add_test(NAME startup_pipeline_state_local_winding_control COMMAND startup_pipeline_state_local_check --mutate winding) +add_test(NAME startup_pipeline_state_local_mesh_shift_control COMMAND startup_pipeline_state_local_check --mutate mesh-shift) +set_tests_properties(startup_pipeline_state_local_winding_control startup_pipeline_state_local_mesh_shift_control PROPERTIES WILL_FAIL TRUE) # Root table handles resolved against a logical view heap, and the records a translated draw reads # from the window (src/startup_stubs/logical_view_table.h). add_executable(startup_logical_view_table_check tests/startup_logical_view_table_check.cpp) @@ -2707,6 +2947,26 @@ if(XBOX2WINDOWS_ADDRLIB_DIR) else() message(STATUS "xg_swizzle_select: addrlib not configured, the test will skip (77)") endif() +add_executable(gfx10_layout_check tests/gfx10_layout_check.cpp) +target_compile_features(gfx10_layout_check PRIVATE cxx_std_17) +target_include_directories(gfx10_layout_check PRIVATE src) +if(XBOX2WINDOWS_ADDRLIB_DIR) + target_link_libraries(gfx10_layout_check PRIVATE xbw_addrlib) + target_compile_definitions(gfx10_layout_check PRIVATE XBOX2WINDOWS_HAVE_ADDRLIB) +endif() +set(_gfx10_golden "${CMAKE_CURRENT_SOURCE_DIR}/tests/gfx10_layout_golden.txt") +add_test(NAME gfx10_layout_golden COMMAND gfx10_layout_check "${_gfx10_golden}") +add_test(NAME gfx10_layout_floor_control COMMAND gfx10_layout_check "${_gfx10_golden}" --mutate floor) +add_test(NAME gfx10_layout_tail_control COMMAND gfx10_layout_check "${_gfx10_golden}" --mutate tail) +set_tests_properties(gfx10_layout_floor_control gfx10_layout_tail_control PROPERTIES WILL_FAIL TRUE) +add_test(NAME gfx10_layout_addrlib COMMAND gfx10_layout_check --addrlib) +set_tests_properties(gfx10_layout_addrlib PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) +add_executable(buffer_address_index_check tests/buffer_address_index_check.cpp) +target_compile_features(buffer_address_index_check PRIVATE cxx_std_17) +target_include_directories(buffer_address_index_check PRIVATE src) +add_test(NAME buffer_address_index COMMAND buffer_address_index_check) +add_test(NAME buffer_address_index_control COMMAND buffer_address_index_check --mutate) +set_tests_properties(buffer_address_index_control PROPERTIES WILL_FAIL TRUE) add_test(NAME xg_bc64_tiling_reference COMMAND xg_swizzle_select_check --bc64-tiling) set_tests_properties(xg_bc64_tiling_reference PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) # 4 KiB allocation answers for small 2D textures (src/startup_stubs/small_texture_4k.h): literal sizes and @@ -2915,6 +3175,11 @@ foreach(adapter IN ITEMS hardware warp) PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) set_tests_properties(startup_sampler_x_swapped_${adapter} PROPERTIES FAIL_REGULAR_EXPRESSION "startup_sampler_x swapped=0") + add_test(NAME startup_sampler_lod_words_${adapter} COMMAND offscreen_check ${adapter} --startup-sampler-x-words) + add_test(NAME startup_sampler_lod_words_dropped_${adapter} COMMAND offscreen_check ${adapter} --startup-sampler-x-words-dropped) + set_tests_properties(startup_sampler_lod_words_${adapter} startup_sampler_lod_words_dropped_${adapter} + PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) + set_tests_properties(startup_sampler_lod_words_dropped_${adapter} PROPERTIES WILL_FAIL TRUE) # The dropped control resets the decoded LOD limits and must read the wrong mip for both entries. add_test(NAME startup_sampler_lod_${adapter} COMMAND offscreen_check ${adapter} --startup-sampler-lod) add_test(NAME startup_sampler_lod_dropped_${adapter} COMMAND offscreen_check ${adapter} --startup-sampler-lod-dropped) @@ -3076,6 +3341,12 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_buffer_atomics_check.py") add_test(NAME startup_image_sample_c COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_c_check.py") + # Pixel-stage lowerings of mesh pairs (gfx2hlsl): translation checks with negative controls. + foreach(check IN ITEMS scalar_pack_hh quad_dpp spi_input mesh_spi_input image_sample_b image_sample_d interp_f16 round_mode front_face quad_divergent scalar_const_fold sample_c_preclamp sample_c_border vopc_dpp image_get_lod) + add_test(NAME startup_${check} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_${check}_check.py") + set_tests_properties(startup_${check} PROPERTIES TIMEOUT 120) + endforeach() add_test(NAME startup_image_gather_c_lz COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_gather_c_lz_check.py") # image_sample_b (#1996): translation controls, then a desktop draw whose mip level the bias selects. @@ -3500,6 +3771,21 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_flat_param_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_flat_param_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + # binary16 interpolation (v_interp_p2_f16) on the same one-pixel renderer + add_test(NAME startup_interp_f16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_interp_f16_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_interp_f16_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + # s_round_mode 0xc: binary16 results rounded toward zero, on the same renderer + add_test(NAME startup_round_mode_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_round_mode_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_round_mode_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + # FRONT_FACE as SV_IsFrontFace (+1.0 / -1.0), on the same renderer + add_test(NAME startup_front_face_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_front_face_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_front_face_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME raster_winding_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/raster_winding_reference.py" "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -3840,7 +4126,8 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_compute_binding_trace_warp COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_binding_trace_check.py" "$") - set_tests_properties(startup_compute_binding_trace_warp PROPERTIES TIMEOUT 30) + set_tests_properties(startup_compute_binding_trace_warp PROPERTIES TIMEOUT 30 + ENVIRONMENT "X2W_UPSTREAM_COMPUTE_ROOT=1;X2W_LIST_UPLOAD_PAGES=1") add_test(NAME startup_compute_request_warp COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_request_check.py" "$") add_test(NAME startup_compute_request_disabled_control COMMAND "${INTAKE_PYTHON}" -B @@ -3872,6 +4159,18 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_draw_check.py" "$" "${backend}") set_tests_properties(startup_stream_draw_${backend} PROPERTIES TIMEOUT 90) + foreach(mode IN ITEMS async sync) + add_test(NAME startup_draw_async_${mode}_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_async_check.py" + "$" "${backend}" "${mode}") + set_tests_properties(startup_draw_async_${mode}_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() + foreach(mode IN ITEMS split copy below locked) + add_test(NAME startup_draw_lock_split_${mode}_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_lock_split_check.py" + "$" "${backend}" "${mode}") + set_tests_properties(startup_draw_lock_split_${mode}_${backend} PROPERTIES TIMEOUT 150 SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_stream_viewport_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_viewport_check.py" "$" "${backend}") @@ -3879,7 +4178,8 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_stream_fetch_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_fetch_check.py" "$" "${backend}") - set_tests_properties(startup_stream_fetch_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + set_tests_properties(startup_stream_fetch_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_UPSTREAM_STREAM_LAYOUT=1") add_test(NAME startup_stream_interface_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_interface_check.py" "$" "${backend}") @@ -3887,7 +4187,12 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_stream_depth_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_depth_check.py" "$" "${backend}") - set_tests_properties(startup_stream_depth_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + set_tests_properties(startup_stream_depth_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_UPSTREAM_STENCIL_REF=1") + add_test(NAME startup_draw_state_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_state_check.py" + "$" "${backend}") + set_tests_properties(startup_draw_state_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_stream_rasterizer_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" "$" "${backend}") @@ -3941,6 +4246,12 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_requests_check.py" "$" "${backend}") set_tests_properties(startup_indirect_requests_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + if(backend STREQUAL "warp") + add_test(NAME startup_draw_srv_limit_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_srv_limit_check.py" + "$" "${STARTUP_FXC}") + set_tests_properties(startup_draw_srv_limit_warp PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endif() add_test(NAME startup_formatted_view_draw_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_formatted_view_draw_check.py" "$" "${backend}" "${STARTUP_FXC}") @@ -3961,14 +4272,27 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_root_cbv_check.py" "$" ${backend}) set_tests_properties(startup_root_cbv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_root_srv_lazy_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_root_srv_lazy_check.py" + "$" ${backend}) + set_tests_properties(startup_root_srv_lazy_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_root_heap_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_root_heap_check.py" "$" ${backend}) - set_tests_properties(startup_root_heap_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + set_tests_properties(startup_root_heap_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_DEFER_HEAP_ROOTS=1") add_test(NAME startup_address_srv_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_srv_check.py" "$" "${backend}") set_tests_properties(startup_address_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_memory_srv_announced_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_memory_srv_announced_check.py" + "$" "${backend}") + set_tests_properties(startup_memory_srv_announced_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_memory_srv_detile_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_memory_srv_detile_check.py" + "$" "${backend}" "$") + set_tests_properties(startup_memory_srv_detile_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) if(backend STREQUAL "warp") # Negative control for X2W_RESOURCE_INDEX_CHECK: mode 2 skips the index inserts, so the check must # report the first live resource it does not find (the run passes only on that report). @@ -3994,7 +4318,8 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_address_single_element_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_single_element_srv_check.py" "$" "${backend}") - set_tests_properties(startup_address_single_element_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + set_tests_properties(startup_address_single_element_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_UPSTREAM_CONSOLE_SRV=1") add_test(NAME startup_address_buffer_srv_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_buffer_srv_check.py" "$" "${backend}") @@ -4015,6 +4340,18 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_frame_copy_check.py" "$" ${backend}) set_tests_properties(startup_frame_copy_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_draw_uav_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_uav_check.py" + "$" "${backend}") + set_tests_properties(startup_draw_uav_${backend} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + add_test(NAME startup_heap_texture_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_heap_texture_check.py" + "$" "${backend}" "$") + set_tests_properties(startup_heap_texture_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_buffer_heap_index_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_buffer_heap_index_check.py" + "$" "${backend}") + set_tests_properties(startup_buffer_heap_index_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_placed_vertex_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_placed_vertex_check.py" "$" "${backend}") @@ -4026,7 +4363,8 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_address_console_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_console_check.py" "$" "${backend}") - set_tests_properties(startup_address_console_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + set_tests_properties(startup_address_console_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_UPSTREAM_CONSOLE_SRV=1") # Uploads of by-address textures recorded while the queue waits on a fence keep their bytes until the # queue has run them. The ring control fills them from the shared upload ring and must lose the first. foreach(gate IN ITEMS gate gate-ring) @@ -4034,7 +4372,11 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_address_console_${gate_name}_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_console_check.py" "$" "${backend}" "${gate}") - set_tests_properties(startup_address_console_${gate_name}_${backend} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + set_tests_properties(startup_address_console_${gate_name}_${backend} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_UPSTREAM_CONSOLE_SRV=1") + if(gate STREQUAL "gate-ring") + set_tests_properties(startup_address_console_${gate_name}_${backend} PROPERTIES ENVIRONMENT "X2W_UPSTREAM_CONSOLE_SRV=1;X2W_UPLOAD_RING=legacy") + endif() endforeach() add_test(NAME startup_xg_bc_chain_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_xg_bc_chain_check.py" diff --git a/src/era_heap.cpp b/src/era_heap.cpp index 25520fc730..3662d8b130 100644 --- a/src/era_heap.cpp +++ b/src/era_heap.cpp @@ -13,6 +13,7 @@ #define NOMINMAX #endif #include +#include "xmem_low.h" namespace era_heap { namespace { @@ -52,7 +53,7 @@ void* allocate_pages(std::size_t bytes, std::size_t alignment) noexcept const auto page = geometry().page; const auto committed = (bytes + page - 1) & ~(page - 1); for (int attempt = 0; attempt < 8; ++attempt) { - auto* probe = VirtualAlloc(nullptr, committed + alignment, MEM_RESERVE, PAGE_NOACCESS); + auto* probe = x2w_low::alloc(committed + alignment, MEM_RESERVE, PAGE_NOACCESS); if (!probe) { return nullptr; } @@ -117,7 +118,7 @@ void* allocate(std::size_t bytes, std::uint64_t attributes) noexcept return nullptr; } // Committed pages are zero-filled by the system. - return VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + return x2w_low::alloc(bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); } // Physical memory types need title physical pages, which this experiment does not model. diff --git a/src/era_query.cpp b/src/era_query.cpp index 703bcefe3a..40dfc64de9 100644 --- a/src/era_query.cpp +++ b/src/era_query.cpp @@ -80,7 +80,12 @@ std::size_t query(void* process, const void* address, void* buffer, std::size_t // Desktop policy, not a Scarlett field: mark addresses in registered GPU-intended regions. const bool registered = is_current_process(process) && is_registered(reinterpret_cast(address)); - static_cast(buffer)[tail_offset] = registered ? tail_registered : 0; + static const bool readable_policy = GetEnvironmentVariableA("X2W_XMEM_QUERY_READABLE", nullptr, 0) != 0; + const DWORD readable = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | + PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; + const bool cpu_readable = readable_policy && info.State == MEM_COMMIT && (info.Protect & readable) && + !(info.Protect & (PAGE_GUARD | PAGE_NOACCESS)); + static_cast(buffer)[tail_offset] = registered || cpu_readable ? tail_registered : 0; } return sizeof(info); } diff --git a/src/startup_stubs/bcpack_bc6h.h b/src/startup_stubs/bcpack_bc6h.h new file mode 100644 index 0000000000..efa39fcfcf --- /dev/null +++ b/src/startup_stubs/bcpack_bc6h.h @@ -0,0 +1,318 @@ +#pragma once + +#include +#include +#include + +#include "bcpack_decoder.h" + +namespace x2w_bcpack { +namespace bc6h { + +struct Mode { + uint8_t code, code_bits, base_bits, delta_bits[3]; + bool transformed, two_regions; +}; + +// Spec modes 1..14, in the order lane 15 (E) numbers them. +inline constexpr Mode MODES[14] = { + { 0x00, 2, 10, { 5, 5, 5 }, true, true }, + { 0x01, 2, 7, { 6, 6, 6 }, true, true }, + { 0x02, 5, 11, { 5, 4, 4 }, true, true }, + { 0x06, 5, 11, { 4, 5, 4 }, true, true }, + { 0x0a, 5, 11, { 4, 4, 5 }, true, true }, + { 0x0e, 5, 9, { 5, 5, 5 }, true, true }, + { 0x12, 5, 8, { 6, 5, 5 }, true, true }, + { 0x16, 5, 8, { 5, 6, 5 }, true, true }, + { 0x1a, 5, 8, { 5, 5, 6 }, true, true }, + { 0x1e, 5, 6, { 6, 6, 6 }, false, true }, + { 0x03, 5, 10, { 10, 10, 10 }, false, false }, + { 0x07, 5, 11, { 9, 9, 9 }, true, false }, + { 0x0b, 5, 12, { 8, 8, 8 }, true, false }, + { 0x0f, 5, 16, { 4, 4, 4 }, true, false }, +}; + +// Endpoint bits after the mode bits, low to high: (endpoint << 6) | (channel << 4) | bit, endpoints +// w x y z = 0..3, channels R G B = 0..2. From the BC6H block layout; checked (UF16) against an +// independent decoder on random blocks of every mode. +inline constexpr uint8_t LAYOUT_BITS[14] = { 75, 75, 72, 72, 72, 72, 72, 72, 72, 72, 60, 60, 60, 60 }; +inline constexpr uint8_t LAYOUT[14][75] = { + { 0x94, 0xa4, 0xe4, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, + 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x40, 0x41, 0x42, 0x43, 0x44, 0xd4, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, + 0xe0, 0xd0, 0xd1, 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0xe1, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, + 0x81, 0x82, 0x83, 0x84, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xe3 }, + { 0x95, 0xd4, 0xd5, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xe0, 0xe1, 0xa4, 0x10, 0x11, 0x12, + 0x13, 0x14, 0x15, 0x16, 0xa5, 0xe2, 0x94, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0xe3, 0xe5, + 0xe4, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, + 0x55, 0xd0, 0xd1, 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, + 0x81, 0x82, 0x83, 0x84, 0x85, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x0a, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x1a, 0xe0, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x2a, 0xe1, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0x84, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xe3 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x0a, 0xd4, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, 0x1a, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x2a, 0xe1, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0xe0, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0x94, 0xe3 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x0a, 0xa4, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x1a, 0xe0, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0x2a, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0xe1, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0xe4, 0xe3 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0xa4, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x94, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0xe4, 0x40, 0x41, + 0x42, 0x43, 0x44, 0xd4, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, 0xe0, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0xe1, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0x84, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xe3 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xd4, 0xa4, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0xe2, 0x94, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0xe3, 0xe4, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x45, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, 0xe0, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0xe1, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0x84, 0x85, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xe0, 0xa4, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x95, 0x94, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0xd5, 0xe4, 0x40, 0x41, + 0x42, 0x43, 0x44, 0xd4, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0xe1, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0x84, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xe3 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xe1, 0xa4, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0xa5, 0x94, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0xe5, 0xe4, 0x40, 0x41, + 0x42, 0x43, 0x44, 0xd4, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, 0xe0, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0x84, 0xe2, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xe3 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0xd4, 0xe0, 0xe1, 0xa4, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x95, 0xa5, 0xe2, 0x94, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0xd5, 0xe3, 0xe5, 0xe4, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x45, 0x90, 0x91, 0x92, 0x93, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0xd0, 0xd1, + 0xd2, 0xd3, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0xa0, 0xa1, 0xa2, 0xa3, 0x80, 0x81, 0x82, 0x83, + 0x84, 0x85, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x58, 0x59, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69 }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x0a, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x58, 0x1a, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x2a }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x0b, 0x0a, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x1b, 0x1a, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x2b, 0x2a }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x40, 0x41, + 0x42, 0x43, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x50, 0x51, 0x52, 0x53, 0x1f, 0x1e, 0x1d, 0x1c, + 0x1b, 0x1a, 0x60, 0x61, 0x62, 0x63, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a }, +}; + +// Second anchor of the 32 two-region partitions (the first 32 of BC7's ANCHOR_2). +inline uint8_t anchor2(uint8_t part) { return ANCHOR_2[part & 31]; } + +struct Fields { + uint8_t mode = 0, part = 0; + uint16_t ep[4][3] = {}; // field values as the BC6H spec numbers their bits (LAYOUT places them) + uint8_t idx[16] = {}; +}; + +inline uint8_t field_bits(const Mode& m, int e, int c) { + return (e == 0 || !m.transformed) ? m.base_bits : m.delta_bits[c]; +} + +inline void pack(const Fields& f, uint8_t* out) { + const Mode& m = MODES[f.mode]; + BitWriter128 w; + w.put(m.code, m.code_bits); + for (int k = 0; k < LAYOUT_BITS[f.mode]; ++k) { + const uint8_t t = LAYOUT[f.mode][k]; + w.put((f.ep[t >> 6][(t >> 4) & 3] >> (t & 15)) & 1u, 1); + } + if (m.two_regions) { + w.put(f.part & 31u, 5); + const uint8_t a2 = anchor2(f.part); + for (int p = 0; p < 16; ++p) w.put(f.idx[p], (p == 0 || p == a2) ? 2 : 3); + } else { + for (int p = 0; p < 16; ++p) w.put(f.idx[p], p == 0 ? 3 : 4); + } + w.write_to(out); +} + +struct State { + uint16_t ep[4][3]; + uint8_t ix[16]; +}; + +// Optional dictionary (255 slots; slot = reference - block - 1 for a reference past the stream +// start). A null pointer or a false *_known entry means unknown. None ships in the tree. +struct Dictionary { + const uint16_t (*ep)[4][3] = nullptr; + const bool* ep_known = nullptr; + const uint8_t (*ix)[16] = nullptr; + const bool* ix_known = nullptr; +}; + +struct Stats { + size_t blocks = 0; + size_t exact = 0; // both chains known + size_t endpoints_only = 0; // endpoints known, flat indices + size_t copied = 0; // endpoints from the nearest known block, flat indices + size_t constant = 0; // stream without any known endpoints +}; + +inline uint32_t il8(uint16_t e, uint16_t o) { + uint32_t v = 0; + for (int k = 0; k < 8; ++k) v |= ((e >> k) & 1u) << (2 * k) | ((o >> k) & 1u) << (2 * k + 1); + return v; +} + +inline uint32_t rev_hi(uint32_t v, uint32_t bits) { + if (bits <= 11) return v; + const uint32_t k = bits - 10, hi = (v >> 10) & ((1u << k) - 1); + uint32_t r = 0; + for (uint32_t j = 0; j < k; ++j) r |= ((hi >> j) & 1u) << (k - 1 - j); + return (v & 1023u) | (r << 10); +} + +inline uint32_t wrap(int32_t v, uint32_t bits) { return static_cast(v) & ((1u << bits) - 1); } + +// UF16 half 0x2000 (2^-7) as a mode-13 base; the same bits read as SF16 give 2.0. +inline constexpr uint16_t DEFAULT_FILL_BASE = 16913; + +// fill_base: mode-13 base value for the constant block (0 = zero block). copy_known = false sends every +// unknown-endpoint block to the constant block instead of copying a known block's endpoints. +// Returns false only on a malformed symbol stream (a mode code outside 0..13). +inline bool decode_blocks(const std::vector& symbols, size_t nb, uint8_t* out, size_t cap, + Stats* stats, const Dictionary* dict = nullptr, uint16_t fill_base = DEFAULT_FILL_BASE, + bool copy_known = true) { + if (cap < nb * 16) return false; + const size_t t = nb * 2; + auto sym = [&](int lane, size_t i, int h) -> uint16_t { return symbols[lane * t + 2 * i + h]; }; + std::vector st(nb); + std::vector fl(nb); + std::vector kep(nb), kix(nb); + static constexpr State HALF = { { { 0x8000, 0x8000, 0x8000 }, { 0x8000, 0x8000, 0x8000 }, + { 0x8000, 0x8000, 0x8000 }, { 0x8000, 0x8000, 0x8000 } }, + { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 } }; + for (size_t i = 0; i < nb; ++i) { + const size_t x = interleave(sym(1, i, 0), sym(1, i, 1)); + const size_t er = static_cast((static_cast(x) + unzigzag(interleave(sym(0, i, 0), sym(0, i, 1)))) & 0xFF); + const size_t xr = x; + const uint16_t (*pe)[3] = HALF.ep; + const uint8_t* pq = HALF.ix; + bool ke = true, kx = true; + if (er != 0 && er <= i) { pe = st[i - er].ep; ke = kep[i - er]; } + else if (er > i) { + const size_t s = er - i - 1; + if (dict && dict->ep && dict->ep_known && dict->ep_known[s]) pe = dict->ep[s]; + else ke = false; + } + if (xr != 0 && xr <= i) { pq = st[i - xr].ix; kx = kix[i - xr]; } + else if (xr > i) { + const size_t s = xr - i - 1; + if (dict && dict->ix && dict->ix_known && dict->ix_known[s]) pq = dict->ix[s]; + else kx = false; + } + const uint16_t mode = sym(15, i, 0); + if (mode >= 14) return false; + const Mode& m = MODES[mode]; + Fields& f = fl[i]; + State& s = st[i]; + std::memcpy(s.ep, pe, sizeof s.ep); + f.mode = static_cast(mode); + f.part = m.two_regions ? static_cast(sym(15, i, 1) & 31) : 0; + const int ne = m.two_regions ? 4 : 2; + for (int e = 0; e < ne; ++e) { + for (int c = 0; c < 3; ++c) { + const uint32_t w = field_bits(m, e, c); + const uint32_t raw = e < 2 ? il8(sym(2 + 3 * e + c, i, 0), sym(2 + 3 * e + c, i, 1)) + : sym(8 + c, i, e - 2); + const uint32_t v = wrap(static_cast(pe[e][c] >> (16 - w)) + unzigzag(static_cast(raw)), w); + s.ep[e][c] = static_cast(v << (16 - w)); + f.ep[e][c] = static_cast(e == 0 ? rev_hi(v, m.base_bits) : v); + } + } + if (!m.two_regions) { + for (int c = 0; c < 3; ++c) { + s.ep[2][c] = m.transformed + ? static_cast(((static_cast(s.ep[0][c] >> (16 - m.base_bits)) << (16 - m.delta_bits[c])) & 0xFFFF) ^ 0x8000) + : s.ep[0][c]; + s.ep[3][c] = s.ep[1][c]; + } + } + const uint32_t ib = m.two_regions ? 3 : 4; + for (int k = 0; k < 4; ++k) { + for (int h = 0; h < 2; ++h) { + const uint16_t sv = sym(11 + k, i, h); + uint32_t ev = 0, od = 0; + for (uint32_t j = 0; j < ib; ++j) { + ev |= ((sv >> (2 * j)) & 1u) << j; + od |= ((sv >> (2 * j + 1)) & 1u) << j; + } + const uint32_t left = k < 3 ? od : ev, right = k < 3 ? ev : od; + const int p0 = 4 * k + 2 * h; + const uint32_t d[2] = { left, right }; + for (int q = 0; q < 2; ++q) { + const uint32_t v = wrap(static_cast(pq[p0 + q] >> (4 - ib)) + unzigzag(static_cast(d[q])), ib); + s.ix[p0 + q] = static_cast(v << (4 - ib)); + f.idx[p0 + q] = static_cast(v); + } + } + } + kep[i] = ke; + kix[i] = kx; + } + + Stats local; + local.blocks = nb; + auto flat = [](Fields& f) { + const uint8_t v = MODES[f.mode].two_regions ? 3 : 7; // anchors stay legal + std::memset(f.idx, v, sizeof f.idx); + }; + // nearest endpoint-known block in stream order (a tie takes the earlier one) + std::vector nearest(nb, -1); + int64_t last = -1; + for (size_t i = 0; i < nb; ++i) { if (kep[i]) last = static_cast(i); nearest[i] = last; } + last = -1; + for (size_t i = nb; i-- > 0;) { + if (kep[i]) last = static_cast(i); + const int64_t at = static_cast(i); + if (last >= 0 && (nearest[i] < 0 || last - at < at - nearest[i])) nearest[i] = last; + } + for (size_t i = 0; i < nb; ++i) { + Fields f = fl[i]; + if (kep[i] && kix[i]) { + ++local.exact; + } else if (kep[i]) { + flat(f); + ++local.endpoints_only; + } else if (copy_known && nearest[i] >= 0) { + f = fl[static_cast(nearest[i])]; + flat(f); + ++local.copied; + } else { + f = Fields{}; + f.mode = 13; + for (int c = 0; c < 3; ++c) f.ep[0][c] = fill_base; // x = 0: both endpoints equal + ++local.constant; + } + pack(f, out + i * 16); + } + if (stats) *stats = local; + return true; +} + +// The whole BCPack BC6H stream: lanes, then rebuild. False when the lanes do not decode. +inline bool decode_stream(const unsigned char* input, size_t input_size, unsigned char* output, size_t output_size, + size_t* produced, Stats* stats, const Dictionary* dict = nullptr, + uint16_t fill_base = DEFAULT_FILL_BASE, bool copy_known = true) { + if (!input || !output || !produced || input_size == 0 || output_size == 0 || output_size % 16) return false; + const size_t nb = output_size / 16; + static constexpr uint8_t ab[16] = { 3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4 }; + std::vector symbols; + if (!decode_lanes(input, input_size, ab, 16, nb * 2, symbols)) return false; + if (!decode_blocks(symbols, nb, output, output_size, stats, dict, fill_base, copy_known)) return false; + *produced = output_size; + return true; +} + +} // namespace bc6h +} // namespace x2w_bcpack diff --git a/src/startup_stubs/bcpack_decoder.h b/src/startup_stubs/bcpack_decoder.h index e255040f50..48a36b06d5 100644 --- a/src/startup_stubs/bcpack_decoder.h +++ b/src/startup_stubs/bcpack_decoder.h @@ -19,6 +19,8 @@ namespace x2w_bcpack { +// (The BC3/BC4/BC5 rank tables and dictionaries come from bcpack_tables.h, which includes bcpack_tables_bcn.inl.) + inline void model_forward(uint8_t eab, uint8_t q, uint16_t sym, uint32_t& f, uint32_t& cf) { uint32_t s = sym; unsigned long seg = 0; @@ -1161,6 +1163,7 @@ inline bool decode_bc1_blocks(const std::vector& symbols, size_t targe return true; } + inline constexpr uint8_t ALPHA_CODE[8] = { 0, 2, 3, 4, 5, 6, 7, 1 }; inline constexpr uint8_t COLOUR_CODE[4] = { 0, 2, 3, 1 }; diff --git a/src/startup_stubs/buffer_address_index.h b/src/startup_stubs/buffer_address_index.h new file mode 100644 index 0000000000..71d8344924 --- /dev/null +++ b/src/startup_stubs/buffer_address_index.h @@ -0,0 +1,76 @@ +#pragma once +#include +#include +#include +#include +#include + +namespace x2w_startup { + +template class BufferAddressIndex { +public: + enum class Mutation { none, exact_start }; // exact_start: the test's negative control (ignores the window) + explicit BufferAddressIndex(Mutation m = Mutation::none) : mutation_(m) {} + + void insert(Key key, std::uint64_t base, std::uint64_t width) + { + erase(key); + if (!width || width > ~std::uint64_t{} - base) return; + Group& g = groups_[class_of(width)]; + g.by_start.emplace(base, Entry{key, width}); + if (width > g.max_width) g.max_width = width; + where_[key] = {base, width}; + } + bool erase(Key key) + { + const auto found = where_.find(key); + if (found == where_.end()) return false; + const auto [base, width] = found->second; + Group& g = groups_[class_of(width)]; + const auto [first, last] = g.by_start.equal_range(base); + for (auto it = first; it != last; ++it) + if (it->second.key == key) { + g.by_start.erase(it); + break; + } + where_.erase(found); + return true; + } + // visit(key, base, width) for every range that contains [address, address + bytes) (bytes >= 1); visit returns + // false to stop. Order: by class, then by start. + template void containing(std::uint64_t address, std::uint64_t bytes, Visit&& visit) const + { + if (!bytes || bytes > ~std::uint64_t{} - address) return; + for (const Group& g : groups_) { + if (g.by_start.empty()) continue; + const std::uint64_t earliest = mutation_ == Mutation::exact_start ? address + : address >= g.max_width ? address - g.max_width + 1 : 0; + for (auto it = g.by_start.lower_bound(earliest); it != g.by_start.end() && it->first <= address; ++it) { + const std::uint64_t base = it->first, width = it->second.width; + if (address - base >= width || bytes > width - (address - base)) continue; + if (!visit(it->second.key, base, width)) return; + } + } + } + std::size_t size() const { return where_.size(); } + +private: + struct Entry { + Key key; + std::uint64_t width; + }; + struct Group { + std::multimap by_start; + std::uint64_t max_width = 0; + }; + static std::size_t class_of(std::uint64_t width) + { + return width <= (std::uint64_t{1} << 16) ? 0 : width <= (std::uint64_t{1} << 20) ? 1 : width <= (std::uint64_t{1} << 24) ? 2 + : width <= (std::uint64_t{1} << 28) ? 3 : 4; + } + std::array groups_; + std::unordered_map> where_; + Mutation mutation_; +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/chad.cpp b/src/startup_stubs/chad.cpp index 93149cce43..6b62592c71 100644 --- a/src/startup_stubs/chad.cpp +++ b/src/startup_stubs/chad.cpp @@ -47,27 +47,22 @@ long release_handle(const char* name, unsigned index, u64 rcx, u64 rdx, u64 r8, } } // namespace +// XDspActivate(connection, parameters, &state, &handle): the caller keeps both outputs next to each +// other in its effect object and later reads the state block (+0x4 compared with its own counter, +// +0xc tested for zero). Each activation gets its own zeroed 256-byte state block and a handle. extern "C" __declspec(noinline) long XDspActivate(u64 rcx, u64 rdx, u64 r8, u64 r9) { static LONG calls; - accept("XDspActivate", 0, rcx, rdx, r8, r9, _ReturnAddress(), calls); - // XDspActivate(client, params, XDspStatus** status, XDspStreamHandle* stream). No XDSP device exists - // under this stand-in, so the call fails the way the documented code says instead of returning success - // with both outputs untouched: validate them, clear them, then report the failure. - auto** status_out = reinterpret_cast(static_cast(r8)); - auto** stream_out = reinterpret_cast(static_cast(r9)); - if (!status_out || !x2w_local::writable(status_out, sizeof(void*)) || - !stream_out || !x2w_local::writable(stream_out, sizeof(void*))) { - x2w_local::logf("x2w-audio XDspActivate status_out=%p stream_out=%p -> E_POINTER", - static_cast(status_out), static_cast(stream_out)); - return hr_pointer; + const long result = accept("XDspActivate", 0, rcx, rdx, r8, r9, _ReturnAddress(), calls); + static unsigned char* blocks = static_cast(VirtualAlloc(nullptr, 1u << 20, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + static LONG used; + const LONG index = InterlockedIncrement(&used) - 1; + if (blocks && index < 4096) { + void* state = blocks + static_cast(index) * 256; + if (r8 && x2w_local::writable(reinterpret_cast(r8), sizeof(void*))) *reinterpret_cast(r8) = state; + if (r9 && x2w_local::writable(reinterpret_cast(r9), sizeof(u64))) *reinterpret_cast(r9) = 0x58325344ull << 32 | (index + 1); } - *status_out = nullptr; - *stream_out = nullptr; - x2w_local::logf("x2w-audio XDspActivate status_out=%p stream_out=%p -> 0x8AC810A2 " - "(XDSP_E_NO_DEVICE_RESOURCES)", - static_cast(status_out), static_cast(stream_out)); - return hr_no_device_resources; + return result; } extern "C" __declspec(noinline) long XDspConnectWithMaximumStreamLimit(u64 rcx, u64 rdx, u64 r8, u64 r9, u64 flag, void** handle) diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 6f92733f06..7808915c80 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -176,6 +176,19 @@ PlacementIndex& placement_group(u64 width) return placement_index[width > D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT]; } +x2w_startup::BufferAddressIndex& buffer_address_index() +{ + static x2w_startup::BufferAddressIndex index; + return index; +} +void index_buffer_record(const Wrapper* w, const ResourceInfo& info) // note_lock exclusive held +{ + const u64 base = reinterpret_cast(w->own().title_memory); + if (info.placement == Placement::none && info.console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && base) + buffer_address_index().insert(w, base, info.console.Width); + else + buffer_address_index().erase(w); +} // Resources by the title memory they start at (note_lock held), for the memory SRV lookups. An entry stays // as long as the resource's record in resource_infos does (never pruned); every lookup applies its own // live-reference filter, so a released resource is skipped there and found again if it is referenced again. @@ -211,6 +224,7 @@ void note_resource(Wrapper* w, const D3D12_RESOURCE_DESC* console, u64 bytes) // Record and index change together or not at all (store_indexed); mode 2 leaves the index out. x2w_startup::store_indexed(resource_address_index(), resource_infos(), static_cast(w), resource_index_check_mode() == 2 ? 0 : reinterpret_cast(w->own().title_memory), resource_index_extent(info), info); + index_buffer_record(w, resource_infos().at(w)); } void retire_placement(Wrapper* w) { @@ -227,6 +241,7 @@ void retire_placement(Wrapper* w) } } found->second.placement = Placement::none; + index_buffer_record(w, found->second); } ReleaseSRWLockExclusive(¬e_lock); } @@ -282,6 +297,7 @@ void note_heap(Wrapper* w, UINT type, UINT count, UINT logical_count, UINT incre void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_t desc_bytes, u64 dest_title, u64 dest_desktop, bool materialized = true) { + if (const Wrapper* r = as_wrapper(reinterpret_cast(resource)); r && r->own().refs <= 0) x2w_memcut::note_after_release(false); ViewRecord record{}; record.slot = static_cast(slot); record.resource = resource; diff --git a/src/startup_stubs/d3d12_cold_texture.inl b/src/startup_stubs/d3d12_cold_texture.inl new file mode 100644 index 0000000000..420423dc76 --- /dev/null +++ b/src/startup_stubs/d3d12_cold_texture.inl @@ -0,0 +1,70 @@ +// Residency hints only. The committed object and its descriptors keep their normal lifetime. +// A title that samples a persistent descriptor without a shim call can still use a low-priority texture. +enum { priority_untracked, priority_normal, priority_low }; +SRWLOCK cold_texture_lock = SRWLOCK_INIT; +unsigned long long cold_texture_count, cold_texture_bytes, warmed_texture_count, warmed_texture_bytes, cold_texture_failures; + +bool cold_textures_enabled() +{ + static const bool on = x2w_local::env_on("X2W_D3D12_COLD_TEXTURE_PRIORITY") && + !x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED") && !x2w_local::env_on("X2W_MEMCUT_RELEASE"); + return on; +} + +void update_texture_priority(Wrapper* wrapper, bool cool) +{ + AcquireSRWLockExclusive(&cold_texture_lock); + auto& w = wrapper->own(); + const LONG previous = cool ? priority_normal : priority_low; + const LONG state = ReadNoFence(&w.cold_texture_state); + if (!cool && state == priority_normal) { + // A bind at zero guest refs, or the AddRef from zero, reached this lock before the final + // Release could lower the priority. Keep the resource warm when that Release arrives. + InterlockedExchange(&w.cold_texture_state, priority_untracked); + } else if (state == previous && + (!cool || InterlockedCompareExchange(&w.refs, 0, 0) == 0)) { + auto* resource = static_cast(w.real); + ID3D12Device1* device = nullptr; + HRESULT hr = resource->GetDevice(IID_PPV_ARGS(&device)); + unsigned long long bytes = 0; + if (SUCCEEDED(hr)) { + const auto desc = resource->GetDesc(); + bytes = device->GetResourceAllocationInfo(0, 1, &desc).SizeInBytes; + const auto priority = cool ? D3D12_RESIDENCY_PRIORITY_LOW : D3D12_RESIDENCY_PRIORITY_NORMAL; + ID3D12Pageable* object = resource; + hr = device->SetResidencyPriority(1, &object, &priority); + device->Release(); + } + if (SUCCEEDED(hr)) { + // Keep a texture warm permanently once we see its reuse, including a bind at zero guest refs. + InterlockedExchange(&w.cold_texture_state, cool ? priority_low : priority_untracked); + if (cool) { + ++cold_texture_count; + cold_texture_bytes += bytes; + } else { + ++warmed_texture_count; + warmed_texture_bytes += bytes; + } + } else { + ++cold_texture_failures; + if (cool) InterlockedExchange(&w.cold_texture_state, priority_untracked); + if (cold_texture_failures <= 3) log("x2w-cold texture: %s failed 0x%08lx", cool ? "lowering priority" : "restoring priority", hr); + } + } + ReleaseSRWLockExclusive(&cold_texture_lock); +} + +void warm_texture(Wrapper* wrapper, bool reacquired = false) +{ + if (!wrapper) return; + const auto& w = wrapper->own(); + const LONG state = ReadNoFence(&w.cold_texture_state); + if (state == priority_low || (state == priority_normal && (reacquired || !ReadNoFence(&w.refs)))) + update_texture_priority(wrapper, false); +} + +void cool_texture(Wrapper* wrapper) +{ + if (ReadNoFence(&wrapper->own().cold_texture_state) == priority_normal) + update_texture_priority(wrapper, true); +} diff --git a/src/startup_stubs/d3d12_compute.inl b/src/startup_stubs/d3d12_compute.inl new file mode 100644 index 0000000000..c238c1023e --- /dev/null +++ b/src/startup_stubs/d3d12_compute.inl @@ -0,0 +1,1276 @@ + +struct WindowSpan { D3D12_GPU_VIRTUAL_ADDRESS va; u64 size; ID3D12Resource* buffer; }; +SRWLOCK window_span_lock = SRWLOCK_INIT; +std::vector& window_spans() +{ + static std::vector spans; + return spans; +} +void note_window(ID3D12Resource* buffer) +{ + if (!buffer) return; + AcquireSRWLockExclusive(&window_span_lock); + window_spans().push_back({buffer->GetGPUVirtualAddress(), buffer->GetDesc().Width, buffer}); + ReleaseSRWLockExclusive(&window_span_lock); +} + +LONG range_split, range_unmapped, range_ok; +bool range_alias_on(); +bool range_alias_split(u64 address, u64 bytes); +void range_alias_repeat(); +// The desktop window buffer and byte offset that address [address, address + bytes) of title memory, +// when the range is contiguous in one window. Results are cached for the frame. +bool desktop_range(u64 address, u64 bytes, ID3D12Resource** buffer, u64* offset) +{ + Timed timed(time_cx_desktop_range); + struct Hit { ID3D12Resource* buffer; u64 offset; bool chunk_split = false; }; + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_map cache; + static LONG cache_frame = -1; + if (!address || !bytes) return false; + const u64 key = address * 1099511628211ull ^ bytes; + AcquireSRWLockExclusive(&lock); + if (cache_frame != frame_number) { + cache.clear(); + cache_frame = frame_number; + } + if (const auto found = cache.find(key); found != cache.end()) { + *buffer = found->second.buffer; + *offset = found->second.offset; + const bool chunk_split = found->second.chunk_split; + ReleaseSRWLockExclusive(&lock); + if (chunk_split) range_alias_repeat(); + return *buffer != nullptr; + } + ReleaseSRWLockExclusive(&lock); + Hit hit{nullptr, 0}; + const D3D12_GPU_VIRTUAL_ADDRESS va = desktop_va(address); + if (!va) { + InterlockedIncrement(&range_unmapped); + } else { + AcquireSRWLockShared(&window_span_lock); + for (const WindowSpan& s : window_spans()) + if (va >= s.va && va + bytes <= s.va + s.size) { + hit = {s.buffer, va - s.va}; + break; + } + ReleaseSRWLockShared(&window_span_lock); + MEMORY_BASIC_INFORMATION info{}; + u64 known_base = 0, known_end = 0; + if (hit.buffer && known_private(address, &known_base, &known_end)) { + // A private allocation opened as a heap: the range is one allocation when it ends inside it. + if (address + bytes > known_end) hit.buffer = nullptr; + if (!hit.buffer) InterlockedIncrement(&range_split); + } else if (hit.buffer && timed_query(reinterpret_cast(address), &info) == sizeof(info)) { + if (info.Type == MEM_MAPPED) { + using Location = BOOL(WINAPI*)(const void*, HANDLE*, ULONG64*); + static const Location location = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_gpu_location")) : nullptr; + }(); + HANDLE first_section = nullptr; + ULONG64 first_at = 0; + if (!location || !location(reinterpret_cast(address), &first_section, &first_at)) { + for (u64 at = (address | 0xffff) + 1; at < address + bytes; at += 0x10000) + if (desktop_va(at) != va + (at - address)) { + hit.buffer = nullptr; + break; + } + } else { + for (u64 at = (address | 0xffff) + 1; at < address + bytes; at += 0x10000) { + HANDLE section = nullptr; + ULONG64 where = 0; + if (!location(reinterpret_cast(at), §ion, &where) || section != first_section || + where != first_at + (at - address)) { + hit.buffer = nullptr; + break; + } + } + if (!hit.buffer && range_alias_on()) { + range_alias_split(address, bytes); // never an alias today: described, counted, NULL + hit.chunk_split = true; + } + } + } else { + MEMORY_BASIC_INFORMATION last{}; + if (timed_query(reinterpret_cast(address + bytes - 1), &last) != sizeof(last) || + last.AllocationBase != info.AllocationBase) + hit.buffer = nullptr; + } + if (!hit.buffer) InterlockedIncrement(&range_split); + } + } + if (hit.buffer) InterlockedIncrement(&range_ok); + AcquireSRWLockExclusive(&lock); + cache[key] = hit; + ReleaseSRWLockExclusive(&lock); + *buffer = hit.buffer; + *offset = hit.offset; + return hit.buffer != nullptr; +} + +struct ComputeTranslation { + struct Res { bool uav; int kind, source, a, b; bool integer = false; }; // kind 0 buffer, 1 2D, 2 2D array, 3 3D, 4 1D; source 0 table(param a, byte b), 2 root a + // integer: R32_UINT texture UAV (manifest kinds tex2du, tex3du) + struct Ud { int kind, a, b; }; // 3 root constant(param a, word b), 4 stride of res a, 5 word 3 of res a, 6 base of res a, + // 7 descriptor dword at byte b of table param a (descword) + int state = 0; // 1 ready, 2 unavailable + std::vector res; + std::vector uds; + std::vector> samplers; + std::uint32_t compare_samplers = 0; + ID3D12RootSignature* root = nullptr; + ID3D12PipelineState* pso = nullptr; + UINT threads[3] = {}; + bool heap = false; // indexes the title's resource heap (SM 6.6 ResourceDescriptorHeap) + bool heap_views_logged = false; + LONG logged = 0; + LONG entry_logged = 0; // X2W_CX_ENTRY_LOG lines written +}; +std::unordered_map& compute_translations() { static std::unordered_map m; return m; } +LONG cx_ready, cx_missing, cx_dispatched, cx_null_res, cx_bad_uav; +volatile LONG64 cx_compile_ms; + +void load_compute(u64 key, ComputeTranslation& tr) +{ + tr.state = 2; + test_hold("x2w-cx", key); + wchar_t path[MAX_PATH]; + std::string manifest; + if (!cache_path(path, L"", key, L".cs.txt") || !read_text(path, manifest)) { + InterlockedIncrement(&cx_missing); + return; + } + for (std::size_t at = 0; at < manifest.size();) { + std::size_t end = manifest.find('\n', at); + if (end == std::string::npos) end = manifest.size(); + const std::string line = manifest.substr(at, end - at); + at = end + 1; + int i = 0, x = 0, y = 0, z = 0; + char kind[16] = "", source[16] = "", view[8] = ""; + unsigned w[4] = {}; + if (std::sscanf(line.c_str(), "cs %d %d %d", &x, &y, &z) == 3) { + tr.threads[0] = x, tr.threads[1] = y, tr.threads[2] = z; + } else if (line.rfind("heap 1", 0) == 0) { + tr.heap = true; + } else if (std::sscanf(line.c_str(), "udsrc %d %15s %d %d", &i, source, &x, &y) >= 2) { + ComputeTranslation::Ud ud{-1, x, y}; + if (!std::strcmp(source, "rootconst")) ud.kind = 3; + else if (!std::strcmp(source, "stride")) ud.kind = 4; + else if (!std::strcmp(source, "bufword3")) ud.kind = 5; + else if (!std::strcmp(source, "bufbase")) ud.kind = 6; + else if (!std::strcmp(source, "descword")) ud.kind = 7; + if (ud.kind < 0 || static_cast(i) != tr.uds.size()) { + log("x2w-cx %016llx: entry value %d from %s not supported", key, i, source); + return; + } + tr.uds.push_back(ud); + } else if (std::sscanf(line.c_str(), "%7s %d %15s %15s %d %d", view, &i, kind, source, &x, &y) >= 5 && + (!std::strcmp(view, "srv") || !std::strcmp(view, "uav"))) { + ComputeTranslation::Res r{view[0] == 'u', !std::strcmp(kind, "tex2d") ? 1 : !std::strcmp(kind, "tex2da") ? 2 : !std::strcmp(kind, "tex3d") ? 3 : !std::strcmp(kind, "tex1d") ? 4 : 0, + !std::strcmp(source, "root") ? 2 : 0, x, y}; + if (!std::strcmp(kind, "tex2du") || !std::strcmp(kind, "tex3du")) { + r.kind = kind[3] == '2' ? 1 : 3; + r.integer = true; + if (!r.uav) { + log("x2w-cx %016llx: integer texture kind %s only as a uav", key, kind); + return; + } + } + if (static_cast(i) != tr.res.size()) return; + tr.res.push_back(r); + } else if (std::sscanf(line.c_str(), "smp %d %x %x %x %x", &i, &w[0], &w[1], &w[2], &w[3]) == 5) { + tr.samplers.push_back({w[0], w[1], w[2], w[3]}); + } else if (std::sscanf(line.c_str(), "smpcmp %d", &i) == 1 && i >= 0 && i < 32) { + tr.compare_samplers |= 1u << i; + } + } + if (tr.uds.size() > 60 || tr.res.size() > 64) return; + ID3DBlob* code = nullptr; + if (!cache_path(path, L"", key, L".cs.cso") || FAILED(D3DReadFileToBlob(path, &code))) return; + const UINT n = static_cast(tr.res.size()); + D3D12_ROOT_PARAMETER parameters[2]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameters[0].Constants.Num32BitValues = tr.uds.empty() ? 1u : static_cast(tr.uds.size()); + D3D12_DESCRIPTOR_RANGE ranges[2] = {{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, n, 0, 0, 0}, {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, n, 0, 0, n}}; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[1].DescriptorTable = {2, ranges}; + std::vector samplers; + for (std::size_t i = 0; i < tr.samplers.size(); ++i) samplers.push_back(x2w_startup::decode_sampler(tr.samplers[i], static_cast(i), (tr.compare_samplers >> i) & 1)); + ID3DBlob* blob = nullptr; + ID3DBlob* errors = nullptr; + HRESULT hr = E_FAIL; + if (!tr.heap) { + D3D12_ROOT_SIGNATURE_DESC desc{n ? 2u : 1u, parameters, static_cast(samplers.size()), samplers.data(), D3D12_ROOT_SIGNATURE_FLAG_NONE}; + hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, &errors); + } else { + // [0] constants, [1] t0 space1 = the title heap's memory, [2] t1 space1 = per-view info, [3] the table + D3D12_DESCRIPTOR_RANGE1 ranges1[2] = {{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, n, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, n, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, n}}; + const D3D12_DESCRIPTOR_RANGE1 bounded1[2] = { + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 1, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 1, 1, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, 0}}; + D3D12_ROOT_PARAMETER1 p1[4]{}; + p1[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + p1[0].Constants.Num32BitValues = parameters[0].Constants.Num32BitValues; + p1[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + p1[1].DescriptorTable = {1, &bounded1[0]}; + p1[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + p1[2].DescriptorTable = {1, &bounded1[1]}; + p1[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + p1[3].DescriptorTable = {2, ranges1}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC vd{}; + vd.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + vd.Desc_1_1 = {n ? 4u : 3u, p1, static_cast(samplers.size()), samplers.data(), D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED}; + hr = D3D12SerializeVersionedRootSignature(&vd, &blob, &errors); + if (FAILED(hr) && errors) log("x2w-cx %016llx root signature: %.300s", key, static_cast(errors->GetBufferPointer())); + } + if (SUCCEEDED(hr)) hr = device_of(the_device)->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&tr.root)); + if (blob) blob->Release(); + if (errors) errors->Release(); + LARGE_INTEGER compile_start{}, compile_end{}, frequency{}; + QueryPerformanceCounter(&compile_start); + if (SUCCEEDED(hr)) { + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = tr.root; + pd.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + hr = device_of(the_device)->CreateComputePipelineState(&pd, IID_PPV_ARGS(&tr.pso)); + } + QueryPerformanceCounter(&compile_end); + QueryPerformanceFrequency(&frequency); + const SIZE_T code_bytes = code->GetBufferSize(); + code->Release(); + InterlockedAdd64(&cx_compile_ms, (compile_end.QuadPart - compile_start.QuadPart) * 1000 / frequency.QuadPart); + log("x2w-cx %016llx translated: %zu entry values, %u resources, %zu samplers, group %ux%ux%u -> 0x%08lx (%zu bytes, compiled in %lld ms)", + key, tr.uds.size(), n, tr.samplers.size(), tr.threads[0], tr.threads[1], tr.threads[2], static_cast(hr), code_bytes, + static_cast((compile_end.QuadPart - compile_start.QuadPart) * 1000 / frequency.QuadPart)); + if (FAILED(hr)) return; + tr.state = 1; + InterlockedIncrement(&cx_ready); +} + +DXGI_FORMAT typeless_to_float(DXGI_FORMAT f) +{ + switch (f) { + case DXGI_FORMAT_R8G8B8A8_TYPELESS: return DXGI_FORMAT_R8G8B8A8_UNORM; + case DXGI_FORMAT_B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_UNORM; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: return DXGI_FORMAT_R16G16B16A16_FLOAT; + case DXGI_FORMAT_R32G32B32A32_TYPELESS: return DXGI_FORMAT_R32G32B32A32_FLOAT; + case DXGI_FORMAT_R16G16_TYPELESS: return DXGI_FORMAT_R16G16_FLOAT; + case DXGI_FORMAT_R32G32_TYPELESS: return DXGI_FORMAT_R32G32_FLOAT; + case DXGI_FORMAT_R16_TYPELESS: return DXGI_FORMAT_R16_FLOAT; + case DXGI_FORMAT_R32_TYPELESS: return DXGI_FORMAT_R32_FLOAT; + case DXGI_FORMAT_R8_TYPELESS: return DXGI_FORMAT_R8_UNORM; + case DXGI_FORMAT_R8G8_TYPELESS: return DXGI_FORMAT_R8G8_UNORM; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: return DXGI_FORMAT_R10G10B10A2_UNORM; + case DXGI_FORMAT_R24G8_TYPELESS: return DXGI_FORMAT_R24_UNORM_X8_TYPELESS; + case DXGI_FORMAT_R32G8X24_TYPELESS: return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; + default: return f; + } +} +bool float_format(DXGI_FORMAT f) +{ + switch (f) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R11G11B10_FLOAT: + case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R8_UNORM: + return true; + default: + return false; + } +} + +// Writes a null view of the right shape for resource r. +void null_view(const ComputeTranslation::Res& r, D3D12_CPU_DESCRIPTOR_HANDLE dest, bool uav) +{ + InterlockedIncrement(&cx_null_res); + if (uav) { + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = r.integer ? DXGI_FORMAT_R32_UINT : r.kind ? DXGI_FORMAT_R8G8B8A8_UNORM : DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = r.kind == 1 ? D3D12_UAV_DIMENSION_TEXTURE2D : r.kind == 2 ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY + : r.kind == 3 ? D3D12_UAV_DIMENSION_TEXTURE3D : r.kind == 4 ? D3D12_UAV_DIMENSION_TEXTURE1D : D3D12_UAV_DIMENSION_BUFFER; + if (!r.kind) { + d.Buffer.NumElements = 1; + d.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + } + if (r.kind == 2) d.Texture2DArray.ArraySize = 1; + if (r.kind == 3) d.Texture3D.WSize = 1; + device_of(the_device)->CreateUnorderedAccessView(nullptr, nullptr, &d, dest); + } else { + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = r.kind ? DXGI_FORMAT_R8G8B8A8_UNORM : DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = r.kind == 1 ? D3D12_SRV_DIMENSION_TEXTURE2D : r.kind == 2 ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY + : r.kind == 3 ? D3D12_SRV_DIMENSION_TEXTURE3D : r.kind == 4 ? D3D12_SRV_DIMENSION_TEXTURE1D : D3D12_SRV_DIMENSION_BUFFER; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (!r.kind) { + d.Buffer.NumElements = 1; + d.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + } else { + d.Texture2D.MipLevels = 1; + if (r.kind == 2) d.Texture2DArray.ArraySize = 1; + } + device_of(the_device)->CreateShaderResourceView(nullptr, &d, dest); + } +} + +LONG cxu_bound, cxu_refused; +void note_integer_uav(bool bound, DXGI_FORMAT resource_format, UINT flags) +{ + InterlockedIncrement(bound ? &cxu_bound : &cxu_refused); + static LONG logged_bound, logged_refused; + if (bound ? first_calls(logged_bound, 1) : first_calls(logged_refused, 6)) + log("x2w-cx integer texture uav %s: resource format %u flags 0x%x%s", bound ? "bound as R32_UINT" : "REFUSED (null R32_UINT view)", + resource_format, flags, bound ? "" : " (needs ALLOW_UNORDERED_ACCESS and an R32_TYPELESS or R32_UINT resource)"); +} + +// Binds a texture behind a view record as SRV or UAV (true when a real view was written). +// prepare: also upload a plain texture and move it to the view's state (false for the bulk heap fill). +bool texture_view(Wrapper* self, const ComputeTranslation::Res& r, const ViewRecord& record, D3D12_CPU_DESCRIPTOR_HANDLE dest, bool prepare = true) +{ + Timed timed(time_cx_texture); + Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + if (prepare) warm_texture(resource); + if (prepare && resource && resource->own().kind == resource_kind) memcut_revive(resource); + ID3D12Resource* texture = resource && resource->own().kind == resource_kind ? static_cast(resource->own().real) : nullptr; + if (!texture || record.desc_bytes < 24) return false; + if (resource->own().refs <= 0) x2w_memcut::note_after_release(true); + const D3D12_RESOURCE_DESC rd = texture->GetDesc(); + const int dim = rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 3 : rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D ? 4 + : rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D ? (rd.DepthOrArraySize > 1 ? 2 : 1) : 0; + if (!dim || (dim != r.kind && !(dim == 2 && r.kind == 1) && !(dim == 1 && r.kind == 2))) return false; + // The view's format and first mip / slice from the title's view description. + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + UINT mip = 0, slice = 0; + std::memcpy(&format, record.desc, 4); + format = typeless_to_float(desktop_format(format ? format : rd.Format)); + if (record.slot == 19) { + std::memcpy(&mip, record.desc + 8, 4); + if (r.kind == 2 || r.kind == 3) std::memcpy(&slice, record.desc + 12, 4); + } else if (record.slot == 18) { + std::memcpy(&mip, record.desc + 16, 4); // MostDetailedMip + } + if (mip >= rd.MipLevels) mip = 0; + if (r.uav) { + if (r.integer) format = x2w_startup::integer_uav_format(rd.Format); + if (!(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) || (r.integer ? format == DXGI_FORMAT_UNKNOWN : !float_format(format))) { + InterlockedIncrement(&cx_bad_uav); + if (r.integer) note_integer_uav(false, rd.Format, rd.Flags); + return false; + } + if (r.integer) note_integer_uav(true, rd.Format, rd.Flags); + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = format; + if (r.kind == 1) { d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; d.Texture2D.MipSlice = mip; } + else if (r.kind == 2) { d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; d.Texture2DArray = {mip, slice < rd.DepthOrArraySize ? slice : 0, rd.DepthOrArraySize - (slice < rd.DepthOrArraySize ? slice : 0), 0}; } + else if (r.kind == 3) { d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; d.Texture3D = {mip, 0, UINT(-1)}; } + else { d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; d.Texture1D.MipSlice = mip; } + if (prepare) require_state(self, texture, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + device_of(the_device)->CreateUnorderedAccessView(texture, nullptr, &d, dest); + return true; + } + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = format; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (r.kind == 1) { d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; d.Texture2D.MostDetailedMip = mip; d.Texture2D.MipLevels = UINT(-1); } + else if (r.kind == 2) { d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; d.Texture2DArray.MostDetailedMip = mip; d.Texture2DArray.MipLevels = UINT(-1); d.Texture2DArray.ArraySize = rd.DepthOrArraySize; } + else if (r.kind == 3) { d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; d.Texture3D.MostDetailedMip = mip; d.Texture3D.MipLevels = UINT(-1); } + else { d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; d.Texture1D.MostDetailedMip = mip; d.Texture1D.MipLevels = UINT(-1); } + if (prepare && record.slot != 19 && !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && + !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) + upload_texture(self, resource, texture); + if (prepare) require_state(self, texture, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + fix_srv(d, texture); + device_of(the_device)->CreateShaderResourceView(texture, &d, dest); + return true; +} + +// The view-id region of the shader-visible heap: 8 views per title view id i at +// draw_heap_size + 8 + 8 * i (0 Texture2D, 1 Texture2DArray, 2 Texture3D, 3 Texture1D, 4 raw buffer SRV, +// 5 RWTexture2D, 6 RWTexture2DArray, 7 raw buffer UAV), empty views of each kind at draw_heap_size. +// vinfo (an upload buffer, 16 bytes per id): word 0 the index stride in bytes (structured: the structure stride, +// typed: the element size, raw: 0), word 1 the GFX10_FORMAT code of a typed view (0: raw, structured or unmapped). +// Filled up to the newest record. +constexpr UINT view_ids_max = 90000; +UINT views_filled; +ID3D12Resource* vinfo_buffer; +std::uint32_t* vinfo_words; +LONG views_bound, views_null; +bool typed_views_off() +{ + static const bool off = x2w_local::env_on("X2W_CX_TYPED_OFF"); + return off; +} +LONG cxv_typed_heap, cxv_typed_table, cxv_misaligned, cxv_word3; // heap: views filled; table: bindings +LONG cxd_image, cxd_buffer, cxd_title, cxd_null, cxd_unmapped; // descword values by source +LONG cxe_rootconst, cxe_descword, cxe_null_res; // entry values: unset root constant, unbound descword table, of a null resource +bool cx_entry_log(u64 key) +{ + static bool all = false; + static const std::vector keys = [] { + std::vector out; + char value[2048]{}; + const DWORD n = GetEnvironmentVariableA("X2W_CX_ENTRY_LOG", value, sizeof(value)); + if (!n || n >= sizeof(value)) return out; + if (!std::strcmp(value, "1")) { + all = true; + log("x2w-cx X2W_CX_ENTRY_LOG: every key, first 4 dispatches each"); + return out; + } + for (const char* p = value; *p;) { + char* end = nullptr; + const u64 k = std::strtoull(p, &end, 16); + if (end == p) { + ++p; + continue; + } + out.push_back(k); + p = end; + } + log("x2w-cx X2W_CX_ENTRY_LOG: %zu keys, first 4 dispatches each", out.size()); + return out; + }(); + return all || (!keys.empty() && std::find(keys.begin(), keys.end(), key) != keys.end()); +} +void note_typed_view(const x2w_startup::BufferViewLayout& l, const ViewRecord& record, bool heap) +{ + if (l.kind != x2w_startup::BufferViewKind::typed) return; + InterlockedIncrement(heap ? &cxv_typed_heap : &cxv_typed_table); + static LONG logged; + if (first_calls(logged, 6)) { + std::uint32_t format = 0; + std::memcpy(&format, record.desc, 4); + log("x2w-cx typed buffer view %u (%s): format %u -> gfx10 format %u, %u-byte elements from byte %llu, %llu bytes%s", record.id, heap ? "heap" : "table", format, + l.format.code, l.index_stride, static_cast(l.offset), static_cast(l.bytes), + typed_views_off() ? " (X2W_CX_TYPED_OFF)" : ""); + } +} +// Called every 300 frames (render mode): view facts handed to translated programs since the last report. +void report_cx_views() +{ + log("x2w-cx view facts (300 frames): typed buffer views heap %ld table %ld (heap misaligned %ld), bufword3 synthesized %ld%s; " + "descword values image %ld buffer %ld title %ld null %ld (unmapped format %ld); integer texture uavs bound %ld refused %ld", + InterlockedExchange(&cxv_typed_heap, 0), InterlockedExchange(&cxv_typed_table, 0), InterlockedExchange(&cxv_misaligned, 0), + InterlockedExchange(&cxv_word3, 0), typed_views_off() ? " (X2W_CX_TYPED_OFF)" : "", InterlockedExchange(&cxd_image, 0), + InterlockedExchange(&cxd_buffer, 0), InterlockedExchange(&cxd_title, 0), InterlockedExchange(&cxd_null, 0), InterlockedExchange(&cxd_unmapped, 0), + InterlockedExchange(&cxu_bound, 0), InterlockedExchange(&cxu_refused, 0)); + log("x2w-cx entry values (300 frames): root constant not set %ld, descword table not bound %ld (these dispatches %s), " + "of a null resource %ld (run); SetComputeRootSignature same %ld changed %ld%s", + InterlockedExchange(&cxe_rootconst, 0), InterlockedExchange(&cxe_descword, 0), + x2w_local::env_on("X2W_CX_UNRESOLVED_RUN") ? "run, X2W_CX_UNRESOLVED_RUN" : "skipped", InterlockedExchange(&cxe_null_res, 0), + InterlockedExchange(&compute_root_same, 0), InterlockedExchange(&compute_root_changed, 0), + x2w_local::env_on("X2W_CX_ROOT_RESET") ? " (X2W_CX_ROOT_RESET: both clear)" : ""); +} +void vdesc_fill(const ViewRecord& record); +void fill_view_kinds(Wrapper* self, UINT base, const ViewRecord* record) +{ + if (record) vdesc_fill(*record); + const SIZE_T inc = draw_heap_increment; + auto at = [&](UINT k) { return D3D12_CPU_DESCRIPTOR_HANDLE{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{base + k} * inc}; }; + static const ComputeTranslation::Res kinds[8] = {{false, 1, 0, 0, 0}, {false, 2, 0, 0, 0}, {false, 3, 0, 0, 0}, {false, 4, 0, 0, 0}, + {false, 0, 0, 0, 0}, {true, 1, 0, 0, 0}, {true, 2, 0, 0, 0}, {true, 0, 0, 0, 0}}; + bool done[8] = {}; + if (record) { + Wrapper* resource = as_wrapper(reinterpret_cast(record->resource)); + ID3D12Resource* real = resource && resource->own().kind == resource_kind ? static_cast(resource->own().real) : nullptr; + const bool buffer_view = record->slot == 17 || (real && real->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER); + if (!buffer_view && real) { + for (UINT k : {0u, 1u, 2u, 3u, 5u, 6u}) done[k] = texture_view(self, kinds[k], *record, at(k), false); + } else if (buffer_view) { + u64 address = 0; + std::size_t bytes = 0; + std::uint32_t stride = 0, format_code = 0; + bool typed = false; + if (record->slot == 17 && record->desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(&address, record->desc, 8); + std::memcpy(&size, record->desc + 8, 4); + bytes = size; + } else if ((record->slot == 18 || record->slot == 19) && record->desc_bytes >= 24 && resource && resource->own().title_memory) { + x2w_startup::BufferViewLayout l; + if (x2w_startup::buffer_view_layout_from_desc(record->slot == 19, record->desc, record->desc_bytes, l, typed_views_off())) { + address = reinterpret_cast(resource->own().title_memory) + l.offset; + bytes = static_cast(l.bytes); + stride = l.index_stride; + format_code = l.format.code; + note_typed_view(l, *record, true); + typed = l.kind == x2w_startup::BufferViewKind::typed; + } + } + if (bytes > (256u << 20)) bytes = 256u << 20; + ID3D12Resource* window = nullptr; + u64 offset = 0; + const bool in_window = address && bytes && desktop_range(address, bytes, &window, &offset); + if (in_window && (offset & 15) && typed) InterlockedIncrement(&cxv_misaligned); // raw views must start 16-aligned + if (in_window && (offset & 15) == 0) { + D3D12_SHADER_RESOURCE_VIEW_DESC sd{}; + sd.Format = DXGI_FORMAT_R32_TYPELESS; + sd.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + sd.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + sd.Buffer.FirstElement = offset / 4; + sd.Buffer.NumElements = static_cast((bytes + 3) / 4); + sd.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device_of(the_device)->CreateShaderResourceView(window, &sd, at(4)); + D3D12_UNORDERED_ACCESS_VIEW_DESC ud{}; + ud.Format = DXGI_FORMAT_R32_TYPELESS; + ud.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + ud.Buffer.FirstElement = offset / 4; + ud.Buffer.NumElements = sd.Buffer.NumElements; + ud.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device_of(the_device)->CreateUnorderedAccessView(window, nullptr, &ud, at(7)); + done[4] = done[7] = true; + } + if (vinfo_words && record->id < view_ids_max) { + vinfo_words[record->id * 4] = stride; + vinfo_words[record->id * 4 + 1] = format_code; + } + } + } + for (UINT k = 0; k < 8; ++k) { + if (done[k]) { + InterlockedIncrement(&views_bound); + continue; + } + null_view(kinds[k], at(k), kinds[k].uav); + InterlockedDecrement(&cx_null_res); + if (record) InterlockedIncrement(&views_null); + } +} +// draw_lock held. +void fill_views(Wrapper* self) +{ + Timed timed(time_cx_fill_views); + if (!vinfo_buffer) { + D3D12_HEAP_PROPERTIES up{D3D12_HEAP_TYPE_UPLOAD}; + D3D12_RESOURCE_DESC rd{}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rd.Width = u64{view_ids_max} * 16; + rd.Height = rd.DepthOrArraySize = rd.MipLevels = 1; + rd.SampleDesc.Count = 1; + rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (FAILED(device_of(the_device)->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&vinfo_buffer)))) + return; + vinfo_buffer->Map(0, nullptr, reinterpret_cast(&vinfo_words)); + std::memset(vinfo_words, 0, u64{view_ids_max} * 16); + fill_view_kinds(self, draw_heap_size, nullptr); // the empty views + } + AcquireSRWLockShared(¬e_lock); + const UINT count = static_cast(view_records().size() < view_ids_max ? view_records().size() : view_ids_max); + ReleaseSRWLockShared(¬e_lock); + const UINT from = views_filled; + for (UINT i = views_filled; i < count; ++i) { + AcquireSRWLockShared(¬e_lock); + const ViewRecord record = view_records()[i]; + ReleaseSRWLockShared(¬e_lock); + fill_view_kinds(self, draw_heap_size + 8 + 8 * i, &record); + note_heap_texture(record); + } + views_filled = count; + if (count != from) { + static LONG logged; + if (first_calls(logged, 12)) log("x2w-cx views %u..%u filled; bound %ld, empty %ld", from, count, views_bound, views_null); + } +} + +// The title heap behind the bound compute tables (else the newest shader-visible view heap). +bool title_view_heap(const Pass& pass, u64* address, u64* bytes) +{ + AcquireSRWLockShared(¬e_lock); + const HeapInfo* best = nullptr; + for (const HeapInfo& h : heap_infos()) { + if (h.type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || !h.title_cpu || !h.desktop_gpu) continue; + for (UINT i = 0; i < 16; ++i) + if (pass.compute_kind[i] == 5 && pass.compute_address[i] >= h.title_cpu && pass.compute_address[i] < h.title_cpu + u64{h.count} * h.increment) + best = &h; + if (!best) best = &h; + } + if (best) { + *address = best->title_cpu; + *bytes = u64{best->logical_count} * best->increment; + } + ReleaseSRWLockShared(¬e_lock); + return best != nullptr; +} + +// The 8 gfx10 descriptor words the console would hold for a view the title created (gfx10_view_words.h): a CBV +// or buffer view gives the V# (raw for a CBV), a texture view the T# from the view and its resource. False: no +// words (unknown slot, unreadable desc, texture view of an unknown resource). Used by descword and vdesc +// (meshrt, `heapwords 1`); no counters here. +bool view_record_words(const ViewRecord& record, std::uint32_t out[8], bool* image, bool* unmapped) +{ + std::memset(out, 0, 32); + *image = *unmapped = false; + Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + ID3D12Resource* real = resource && resource->own().kind == resource_kind ? static_cast(resource->own().real) : nullptr; + x2w_startup::BufferViewLayout l; + if (record.slot == 17 && record.desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(&size, record.desc + 8, 4); + l = x2w_startup::buffer_view_layout(DXGI_FORMAT_R32_TYPELESS, 0, size / 4, 0, 1); // a CBV reads as a raw buffer + } else if ((record.slot == 18 || record.slot == 19) && + x2w_startup::buffer_view_layout_from_desc(record.slot == 19, record.desc, record.desc_bytes, l, typed_views_off())) { + } else if (real && (record.slot == 18 || record.slot == 19)) { + x2w_startup::ImageViewFacts v; + if (!x2w_startup::image_view_from_desc(record.slot == 19, record.desc, record.desc_bytes, v)) return false; + const D3D12_RESOURCE_DESC rd = real->GetDesc(); + v.dimension = rd.Dimension; + v.width = rd.Width; + v.height = rd.Height; + v.depth_or_array = rd.DepthOrArraySize; + v.mip_levels = rd.MipLevels; + v.format = typeless_to_float(desktop_format(v.format ? v.format : rd.Format)); + return *image = x2w_startup::gfx10_image_words(v, out, unmapped); + } else { + return false; + } + x2w_startup::gfx10_buffer_words(l, out); + return true; +} + +std::uint32_t descword_value(const Pass& pass, int param, int offset, u64 key, bool* resolved = nullptr) +{ + if (resolved) *resolved = false; + if (param < 0 || param >= 16 || offset < 0 || pass.compute_kind[param] != 5 || !pass.compute_address[param]) { + static LONG logged; + if (first_calls(logged, 4)) + log("x2w-cx %016llx descword %d %d: root parameter is not a bound descriptor table (kind %d): value 0", key, param, offset, + param >= 0 && param < 16 ? pass.compute_kind[param] : -1); + InterlockedIncrement(&cxd_null); + return 0; + } + const u64 entry = pass.compute_address[param] + (static_cast(offset) & ~31ull); + const int word = (offset & 31) / 4; + std::uint32_t words[8] = {}; + if (!x2w_local::readable(reinterpret_cast(entry), 32)) { + InterlockedIncrement(&cxd_null); + return 0; + } + std::memcpy(words, reinterpret_cast(entry), 32); + if (resolved) *resolved = true; + if (words[0] != view_token_magic) { + InterlockedIncrement(words[word] ? &cxd_title : &cxd_null); + return words[word]; + } + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + std::uint32_t out[8] = {}; + bool image = false, unmapped = false; + const bool made = known && view_record_words(record, out, &image, &unmapped); + if (made && unmapped) { + InterlockedIncrement(&cxd_unmapped); + static LONG logged; + if (first_calls(logged, 8)) log("x2w-cx descword: view %u has no gfx10 format here: FORMAT 0 (word 1 may then read as a null view)", record.id); + } + if (!made) { + InterlockedIncrement(&cxd_null); + return 0; + } + InterlockedIncrement(image ? &cxd_image : &cxd_buffer); + static LONG logged_image, logged_buffer; + if (first_calls(image ? logged_image : logged_buffer, 1)) + log("%s", image ? "x2w-cx descword: image views give T# FORMAT, WIDTH, HEIGHT, DST_SEL, BASE_LEVEL, LAST_LEVEL, TYPE, DEPTH, BASE_ARRAY, " + "ARRAY_PITCH, MAX_MIP; left 0: base address, MIN_LOD, RESOURCE_LEVEL, SW_MODE, BC_SWIZZLE, PERF_MOD, words 6-7" + : "x2w-cx descword: buffer views give V# STRIDE, NUM_RECORDS, DST_SEL, FORMAT, OOB_SELECT; left 0: base address, " + "SWIZZLE_ENABLE, CACHE_SWIZZLE, INDEX_STRIDE, ADD_TID_ENABLE, RESOURCE_LEVEL, words 4-7"); + static LONG logged_value; + if (first_calls(logged_value, 8)) + log("x2w-cx %016llx descword %d %d: view %u slot %u %s word %d = %08x", key, param, offset, record.id, record.slot, image ? "T#" : "V#", word, out[word]); + return out[word]; +} + +SRWLOCK compute_load_lock = SRWLOCK_INIT; +CONDITION_VARIABLE compute_loaded = CONDITION_VARIABLE_INIT; +ComputeTranslation& loaded_compute(u64 key) +{ + AcquireSRWLockExclusive(&compute_load_lock); + ComputeTranslation& tr = compute_translations()[key]; // element references survive rehashing + while (tr.state == 3) SleepConditionVariableSRW(&compute_loaded, &compute_load_lock, INFINITE, 0); + if (tr.state != 0) { + ReleaseSRWLockExclusive(&compute_load_lock); + return tr; + } + tr.state = 3; + ReleaseSRWLockExclusive(&compute_load_lock); + ComputeTranslation loaded; + load_compute(key, loaded); + AcquireSRWLockExclusive(&compute_load_lock); + tr = loaded; // final state (1 ready, 2 unavailable) and the objects; nobody reads tr while it is 3 + ReleaseSRWLockExclusive(&compute_load_lock); + WakeAllConditionVariable(&compute_loaded); + return tr; +} + +SRWLOCK prewarm_lock = SRWLOCK_INIT; +CONDITION_VARIABLE prewarm_wanted = CONDITION_VARIABLE_INIT; +std::deque& prewarm_queue() +{ + static std::deque q; + return q; +} +std::unordered_set& prewarm_keys() // every key ever queued (prewarm_lock): each is queued once +{ + static std::unordered_set s; + return s; +} +LONG cx_prewarm_queued, cx_prewarm_done; +struct CxAsync { + LONG skipped = 0; // since the run started + LONG since_report = 0; // since the last report_cx_async + ULONGLONG first_skip = 0; // GetTickCount64 of the first skip +}; +std::unordered_map& cx_async_keys() +{ + static std::unordered_map m; + return m; +} +bool cx_async() +{ + static const bool on = x2w_local::env_on("X2W_CX_ASYNC") && !x2w_local::env_on("X2W_CX_COMPILE_LOCKED"); + return on; +} +std::unordered_set& known_keys() +{ + static std::unordered_set s; + return s; +} +LONG cx_known_done; +ULONGLONG cx_known_started; +// The prewarm workers. A key with skipped dispatches logs when it is ready. +DWORD WINAPI prewarm_thread(void*) +{ + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + for (;;) { + AcquireSRWLockExclusive(&prewarm_lock); + while (prewarm_queue().empty()) SleepConditionVariableSRW(&prewarm_wanted, &prewarm_lock, INFINITE, 0); + const u64 key = prewarm_queue().front(); + prewarm_queue().pop_front(); + ReleaseSRWLockExclusive(&prewarm_lock); + const int state = loaded_compute(key).state; + const LONG n = InterlockedIncrement(&cx_prewarm_done); + if (n <= 4 || n % 200 == 0) log("x2w-cx prewarm %ld of %ld queued pipelines loaded (latest %016llx)", n, cx_prewarm_queued, key); + if (known_keys().count(key)) { + const LONG done = InterlockedIncrement(&cx_known_done); + if (done == static_cast(known_keys().size())) + log("x2w-cx prewarm: all %ld known pipelines loaded %.1f s after the device was made (X2W_CX_PREWARM_ALL); " + "driver compile time of all translations so far %.1f s", done, (GetTickCount64() - cx_known_started) / 1000.0, + static_cast(cx_compile_ms) / 1000.0); + } + if (cx_async()) { + AcquireSRWLockExclusive(&compute_load_lock); + const auto found = cx_async_keys().find(key); + const CxAsync seen = found != cx_async_keys().end() ? found->second : CxAsync{}; + ReleaseSRWLockExclusive(&compute_load_lock); + if (seen.skipped) + log("x2w-cx %016llx %s (X2W_CX_ASYNC) %llu ms after its first skipped dispatch; %ld dispatches skipped while compiling", + key, state == 1 ? "ready" : "unavailable", static_cast(GetTickCount64() - seen.first_skip), seen.skipped); + } + } +} +bool prewarm_enabled() +{ + static const bool off = x2w_local::env_on("X2W_CX_PREWARM_OFF") || x2w_local::env_on("X2W_CX_COMPILE_LOCKED") || + x2w_local::env_on("X2W_CX_OFF") || x2w_local::env_on("X2W_COMPUTE_OFF"); + return !off; +} +// Queues `key` for the workers once. `front`: a dispatch needs it now (X2W_CX_ASYNC); a key still waiting in the +// queue moves to the front. With X2W_CX_ASYNC the workers run even under X2W_CX_PREWARM_OFF (then only demanded +// keys are queued). False: the key cannot be queued (prewarm off, or not a loadable slot-67 key). +bool prewarm_compute(u64 key, bool front) +{ + if ((!prewarm_enabled() && !(front && cx_async())) || (key >> 56) != 0x67 || !(key & 0x00ffffffffffffffull)) return false; + static const int threads = [] { + char value[4]{}; + const DWORD n = GetEnvironmentVariableA("X2W_CX_PREWARM_THREADS", value, sizeof(value)); + int count = n && n < sizeof(value) ? std::atoi(value) : x2w_local::env_on("X2W_CX_PREWARM_ALL") ? 3 : 2; + count = count < 1 ? 1 : count > 4 ? 4 : count; + for (int i = 0; i < count; ++i) + if (const HANDLE t = CreateThread(nullptr, 0, prewarm_thread, nullptr, 0, nullptr)) CloseHandle(t); + log("x2w-cx prewarm: %d background threads%s", count, + cx_async() ? "; X2W_CX_ASYNC=1: a dispatch of a pipeline not loaded yet is skipped, never compiled or waited for on its thread" : ""); + return count; + }(); + (void)threads; + AcquireSRWLockExclusive(&prewarm_lock); + const bool fresh = prewarm_keys().insert(key).second; + if (fresh) { + ++cx_prewarm_queued; + if (front) prewarm_queue().push_front(key); + else prewarm_queue().push_back(key); + } else if (front) { + std::deque& q = prewarm_queue(); + for (auto it = q.begin(); it != q.end(); ++it) + if (*it == key) { + q.erase(it); + q.push_front(key); + break; + } // not in the queue: a worker is loading it or has loaded it + } + ReleaseSRWLockExclusive(&prewarm_lock); + if (fresh) WakeConditionVariable(&prewarm_wanted); + return true; +} +// X2W_CX_ASYNC: the translation of `key` if its load has finished (state 1 ready or 2 unavailable), else nullptr +// after counting the skip and queueing the key at the front. A key the workers cannot take is loaded here as before. +ComputeTranslation* ready_compute(u64 key) +{ + AcquireSRWLockExclusive(&compute_load_lock); + ComputeTranslation& tr = compute_translations()[key]; + if (tr.state == 1 || tr.state == 2) { + ReleaseSRWLockExclusive(&compute_load_lock); + return &tr; + } + CxAsync& a = cx_async_keys()[key]; + const bool first = !a.skipped; + if (first) a.first_skip = GetTickCount64(); + ++a.skipped; + ++a.since_report; + ReleaseSRWLockExclusive(&compute_load_lock); + if (!prewarm_compute(key, true)) { + AcquireSRWLockExclusive(&compute_load_lock); + --a.skipped, --a.since_report; // element references survive rehashing + ReleaseSRWLockExclusive(&compute_load_lock); + return &loaded_compute(key); + } + static LONG logged; + if (first && first_calls(logged, 32)) + log("x2w-cx %016llx: pipeline not loaded yet, dispatch skipped and the key queued first for the prewarm workers (X2W_CX_ASYNC)", key); + return nullptr; +} +// Heartbeat (every 5 s): the dispatches skipped while compiling since the last report, per key. +void report_cx_async() +{ + if (!cx_async()) return; + std::vector> keys; + LONG total = 0, all_time = 0; + AcquireSRWLockExclusive(&compute_load_lock); + for (auto& entry : cx_async_keys()) { + all_time += entry.second.skipped; + if (!entry.second.since_report) continue; + keys.push_back({entry.first, entry.second.since_report}); + total += entry.second.since_report; + entry.second.since_report = 0; + } + ReleaseSRWLockExclusive(&compute_load_lock); + AcquireSRWLockShared(&prewarm_lock); + const std::size_t waiting = prewarm_queue().size(); + ReleaseSRWLockShared(&prewarm_lock); + if (!total) return; + std::sort(keys.begin(), keys.end(), [](const auto& a, const auto& b) { return a.second > b.second; }); + char line[1400]; + int n = std::snprintf(line, sizeof(line), "x2w-cx dispatches skipped while compiling since the last report (X2W_CX_ASYNC): %ld over %zu keys " + "(%ld this run; %zu keys waiting in the prewarm queue):", total, keys.size(), all_time, waiting); + for (const auto& k : keys) { + if (n > static_cast(sizeof(line)) - 40) { + n += std::snprintf(line + n, sizeof(line) - n, " ..."); + break; + } + n += std::snprintf(line + n, sizeof(line) - n, " %016llx=%ld", k.first, k.second); + } + log("%s", line); +} + +bool prewarm_all() +{ + static const bool on = x2w_local::env_on("X2W_CX_PREWARM_ALL") && prewarm_enabled(); + return on; +} +SRWLOCK keys_seen_lock = SRWLOCK_INIT; +std::unordered_set& keys_seen() // keys_seen_lock: the file's keys and the keys dispatched this run +{ + static std::unordered_set s; + return s; +} +LONG keys_seen_changed; +bool keys_seen_path(wchar_t* out) +{ + DWORD n = GetEnvironmentVariableW(L"X2W_CX_KEYS_SEEN", out, MAX_PATH); + if (n && n < MAX_PATH) return true; + wchar_t dir[MAX_PATH]; + n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); + if (!n || n >= MAX_PATH) return false; + swprintf(out, MAX_PATH, L"%s\\cx_keys_seen.lst", dir); + return true; +} +// execute_translated: the key was dispatched (every dispatch; a shared lookup once the key is known). +void note_key_seen(u64 key) +{ + if (!prewarm_all()) return; + AcquireSRWLockShared(&keys_seen_lock); + const bool known = keys_seen().count(key) != 0; + ReleaseSRWLockShared(&keys_seen_lock); + if (known) return; + AcquireSRWLockExclusive(&keys_seen_lock); + if (keys_seen().insert(key).second) InterlockedIncrement(&keys_seen_changed); + ReleaseSRWLockExclusive(&keys_seen_lock); +} +DWORD WINAPI keys_seen_writer(void*) +{ + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + wchar_t path[MAX_PATH], temp[MAX_PATH]; + if (!keys_seen_path(path)) return 0; + swprintf(temp, MAX_PATH, L"%s.%lu.tmp", path, GetCurrentProcessId()); + for (;;) { + Sleep(10000); + if (!InterlockedExchange(&keys_seen_changed, 0)) continue; + std::string text; + AcquireSRWLockShared(&keys_seen_lock); + std::vector keys(keys_seen().begin(), keys_seen().end()); + ReleaseSRWLockShared(&keys_seen_lock); + std::sort(keys.begin(), keys.end()); + for (const u64 key : keys) { + char line[24]; + std::snprintf(line, sizeof(line), "%016llx\n", key); + text += line; + } + const HANDLE file = CreateFileW(temp, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) continue; + DWORD written = 0; + const bool ok = WriteFile(file, text.data(), static_cast(text.size()), &written, nullptr) && written == text.size(); + CloseHandle(file); + const bool moved = ok && MoveFileExW(temp, path, MOVEFILE_REPLACE_EXISTING); + if (!moved) DeleteFileW(temp); + static LONG logged; + if (first_calls(logged, 4) || !moved) log("x2w-cx keys seen: %zu keys written to %ls%s", keys.size(), path, moved ? "" : " FAILED"); + } +} +// attach_device, after the_device is set. +void prewarm_known_start() +{ + if (!prewarm_all()) return; + cx_known_started = GetTickCount64(); + wchar_t path[MAX_PATH], dir[MAX_PATH]; + const DWORD dn = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); + if (!dn || dn >= MAX_PATH) return; + std::string text; + const bool have_file = keys_seen_path(path) && read_text(path, text); + std::size_t file_keys = 0; + AcquireSRWLockExclusive(&keys_seen_lock); + for (std::size_t at = 0; have_file && at < text.size();) { + std::size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + const u64 key = std::strtoull(text.substr(at, end - at).c_str(), nullptr, 16); + if ((key >> 56) == 0x67 && keys_seen().insert(key).second) ++file_keys; + at = end + 1; + } + ReleaseSRWLockExclusive(&keys_seen_lock); + // The cached translations, smallest first. + std::vector> cached; // (size, key) + wchar_t pattern[MAX_PATH]; + swprintf(pattern, MAX_PATH, L"%s\\67*.cs.cso", dir); + WIN32_FIND_DATAW found{}; + const HANDLE find = FindFirstFileW(pattern, &found); + if (find != INVALID_HANDLE_VALUE) { + do { + wchar_t* tail = nullptr; + const u64 key = std::wcstoull(found.cFileName, &tail, 16); + if (!tail || tail - found.cFileName != 16 || _wcsicmp(tail, L".cs.cso") != 0) continue; + if (have_file && !keys_seen().count(key)) continue; // keys_seen is not written by another thread yet + cached.push_back({(static_cast(found.nFileSizeHigh) << 32) | found.nFileSizeLow, key}); + } while (FindNextFileW(find, &found)); + FindClose(find); + } + std::sort(cached.begin(), cached.end()); + for (const auto& c : cached) known_keys().insert(c.second); + if (have_file) + log("x2w-cx prewarm: %zu known pipelines queued (X2W_CX_PREWARM_ALL; keys seen file %ls: %zu keys, %zu with a translation), smallest first", + cached.size(), path, file_keys, cached.size()); + else + log("x2w-cx prewarm: %zu known pipelines queued (X2W_CX_PREWARM_ALL; no keys seen file: every cached translation), smallest first", + cached.size()); + for (const auto& c : cached) prewarm_compute(c.second); + if (const HANDLE t = CreateThread(nullptr, 0, keys_seen_writer, nullptr, 0, nullptr)) CloseHandle(t); +} +// Heartbeat, and the first translated dispatch: how many of the known pipelines are loaded. +void report_prewarm_known(const char* when) +{ + static LONG complete_logged; + if (!prewarm_all() || known_keys().empty() || complete_logged) return; + const LONG done = cx_known_done; + if (done == static_cast(known_keys().size())) InterlockedExchange(&complete_logged, 1); + log("x2w-cx prewarm: %ld of %zu pipelines ready %s, %.1f s after the device was made; driver compile time so far %.1f s", + done, known_keys().size(), when, (GetTickCount64() - cx_known_started) / 1000.0, static_cast(cx_compile_ms) / 1000.0); +} + +// Runs a dispatch through the translation of compute key `key`. False: not translated (or no list). +bool execute_translated(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, UINT x, UINT y, UINT z) +{ + static const bool enabled = !x2w_local::env_on("X2W_CX_OFF"); + if (!enabled || !list || (key >> 56) != 0x67) { + dispatch_outcome = !enabled ? co_c67_off : list ? co_c67_other_key : co_not_run; + return false; + } + Timed timed(time_cx_execute); + Pass& pass = pass_of(self); + static const bool compile_locked = x2w_local::env_on("X2W_CX_COMPILE_LOCKED"); + note_key_seen(key); + static LONG first_dispatch; + if (!first_dispatch && !InterlockedExchange(&first_dispatch, 1)) report_prewarm_known("at the first translated dispatch"); + ComputeTranslation* ready = compile_locked ? nullptr : cx_async() ? ready_compute(key) : &loaded_compute(key); + if (!compile_locked && !ready) { + dispatch_outcome = co_c67_compiling; + return false; + } + lock_draw(200000 + __LINE__); + if (!ready) { + ready = &compute_translations()[key]; + if (!ready->state) load_compute(key, *ready); + } + ComputeTranslation& tr = *ready; + if (tr.state != 1 || !ensure_draw_heap(the_device)) { + dispatch_outcome = tr.state != 1 ? co_c67_untranslated : co_c67_heap; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + TitleHeapView heap_view; + if (tr.heap) { + u64 heap_address = 0, heap_bytes = 0; + static LONG logged_heap; + const char* why = draw_heap_increment != 32 ? "increment not 32" + : !title_view_heap(pass, &heap_address, &heap_bytes) ? "title view heap not reachable" + : bounded_title_heap(heap_address, heap_bytes, heap_view); + if (why) { + if (first_calls(logged_heap, 4)) log("x2w-cx %016llx: heap dispatch skipped: %s (increment %u)", key, why, draw_heap_increment); + dispatch_outcome = co_c67_heap; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + fill_views(self); + upload_heap_textures(self); + if (!vinfo_buffer) { + dispatch_outcome = co_c67_heap; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + } + const UINT n = static_cast(tr.res.size()); + const UINT hv = tr.heap ? 2u : 0u; + UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(2 * n + hv))) % draw_heap_size; + if (first + 2 * n + hv > draw_heap_size) { + first = 0; + InterlockedExchange(&draw_heap_cursor, static_cast(2 * n + hv)); + } + std::uint32_t strides[64] = {}, word3[64] = {}, bases[64] = {}; + bool bound_res[64] = {}; + u64 res_address[64] = {}; // title address of a bound buffer (X2W_CX_ENTRY_LOG) + std::size_t res_bytes[64] = {}; + const bool show = x2w_local::first_calls(tr.logged, 2); + for (UINT i = 0; i < n; ++i) { + const ComputeTranslation::Res& r = tr.res[i]; + const SIZE_T inc = draw_heap_increment; + const D3D12_CPU_DESCRIPTOR_HANDLE srv{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + i} * inc}; + const D3D12_CPU_DESCRIPTOR_HANDLE uav{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + n + i} * inc}; + // the unused half of each pair stays null + null_view(r, r.uav ? srv : uav, !r.uav); + InterlockedDecrement(&cx_null_res); + const D3D12_CPU_DESCRIPTOR_HANDLE dest = r.uav ? uav : srv; + u64 entry = 0, address = 0; + std::size_t bytes = 0; + if (r.source == 0 && r.a < 16 && pass.compute_kind[r.a] == 5 && pass.compute_address[r.a]) entry = pass.compute_address[r.a] + static_cast(r.b); + if (r.source == 2 && r.a < 16 && pass.compute_kind[r.a] >= 2 && pass.compute_kind[r.a] <= 4) { + address = pass.compute_address[r.a]; + bytes = readable_window(address, 1u << 20); + } + std::uint32_t words[8] = {}; + if (entry && x2w_local::readable(reinterpret_cast(entry), 32)) std::memcpy(words, reinterpret_cast(entry), 32); + ViewRecord record{}; + bool known = false; + if (words[0] == view_token_magic) { + AcquireSRWLockShared(¬e_lock); + known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + } else if (entry) { + word3[i] = words[3]; + } + bool bound = false; + if (r.kind) { + bound = known && texture_view(self, r, record, dest); + } else { + if (known && record.slot == 17 && record.desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(&address, record.desc, 8); + std::memcpy(&size, record.desc + 8, 4); + bytes = size; + } else if (known && (record.slot == 18 || record.slot == 19) && record.desc_bytes >= 24) { + Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + D3D12_SRV_DIMENSION dim{}; + std::memcpy(&dim, record.desc + 4, 4); + x2w_startup::BufferViewLayout l; + if (dim == 1 /* BUFFER in both SRV and UAV enums */ && resource && resource->own().title_memory && + x2w_startup::buffer_view_layout_from_desc(record.slot == 19, record.desc, record.desc_bytes, l, typed_views_off())) { + address = reinterpret_cast(resource->own().title_memory) + l.offset; + bytes = static_cast(l.bytes); + strides[i] = l.index_stride; + note_typed_view(l, record, false); + if (!typed_views_off() && l.kind == x2w_startup::BufferViewKind::typed) { + // word 3 of the V# the console holds for this typed view (format, swizzle), for bufword3 entry + // values; raw and structured views keep 0 (the translator's raw-words fallback) + std::uint32_t v[8]; + x2w_startup::gfx10_buffer_words(l, v); + word3[i] = v[3]; + InterlockedIncrement(&cxv_word3); + } + } + } else if (entry && words[0] != view_token_magic) { + address = words[0] | (static_cast(words[1] & 0xffff) << 32); + strides[i] = (words[1] >> 16) & 0x3fff; + bytes = static_cast(strides[i] ? strides[i] : 1) * words[2]; + } + if (bytes > (256u << 20)) bytes = 256u << 20; + ID3D12Resource* window = nullptr; + u64 offset = 0; + if (address && bytes && desktop_range(address, bytes, &window, &offset)) { + const u64 aligned = offset & ~15ull; + bases[i] = static_cast(offset - aligned); + const UINT elements = static_cast((bytes + bases[i] + 3) / 4); + if (r.uav) { + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d.Buffer.FirstElement = aligned / 4; + d.Buffer.NumElements = elements; + d.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device_of(the_device)->CreateUnorderedAccessView(window, nullptr, &d, dest); + } else { + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + d.Buffer.FirstElement = aligned / 4; + d.Buffer.NumElements = elements; + d.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device_of(the_device)->CreateShaderResourceView(window, &d, dest); + } + bound = true; + res_address[i] = address; + res_bytes[i] = bytes; + static const bool uav_written = x2w_local::env_on("X2W_CX_UAV_WRITTEN"); + if (r.uav && uav_written) { + static LONG registered, too_wide; + const bool wide = bytes > (1u << 20); + if (!wide) note_gpu_written(address, bytes); + const LONG n = InterlockedIncrement(wide ? &too_wide : ®istered); + if ((n & (n - 1)) == 0) + log("x2w-cx X2W_CX_UAV_WRITTEN: %s %ld (latest %016llx uav %u 0x%llx, %zu bytes)", wide ? "not registered (> 1 MiB)" : "registered", + n, key, i, address, bytes); + } + } + if (const int rw = range_watch_hit(address, bytes); rw >= 0) { + if (range_watch_line(rw)) + log("x2w-watch 0x%llx: compute %016llx %s %u 0x%llx (%zu bytes) frame %ld: %s", range_watch_address(rw), key, r.uav ? "uav" : "srv", + i, address, bytes, frame_number, bound ? "bound" : "NULL"); + range_watch_sample("compute-bind", key); + } + } + if (!bound) null_view(r, dest, r.uav); + bound_res[i] = bound; + if (show) + log("x2w-cx %016llx %s %u kind %d source %d(%d,%d): entry 0x%llx words %08x %08x %08x %08x -> address 0x%llx %zu bytes stride %u: %s", + key, r.uav ? "uav" : "srv", i, r.kind, r.source, r.a, r.b, entry, words[0], words[1], words[2], words[3], address, bytes, + strides[i], bound ? "bound" : "NULL"); + } + std::uint32_t values[64] = {}; + char state[64] = {}; // 0 resolved, 'u' unresolved (skips), 'n' of a null resource + int unresolved = -1; + for (std::size_t i = 0; i < tr.uds.size(); ++i) { + const ComputeTranslation::Ud& ud = tr.uds[i]; + const bool in = ud.a >= 0 && ud.a < 64; + values[i] = ud.kind == 3 ? ((ud.a < 16 && ud.b < 16) ? pass.compute_constants[ud.a][ud.b] : 0) + : ud.kind == 4 ? (in ? strides[ud.a] : 0) : ud.kind == 5 ? (in ? word3[ud.a] : 0) : (in ? bases[ud.a] : 0); + if (ud.kind == 3) { + const bool set = ud.a >= 0 && ud.a < 16 && ud.b >= 0 && ud.b < 16 && pass.compute_kind[ud.a] == 1 && + ((pass.compute_set[ud.a] >> ud.b) & 1); + if (!set) state[i] = 'u'; + } else if (ud.kind == 7) { + bool resolved = false; + values[i] = descword_value(pass, ud.a, ud.b, key, &resolved); + if (!resolved) state[i] = 'u'; + } else if (!in || static_cast(ud.a) >= n || !bound_res[ud.a]) { + state[i] = 'n'; + } + if (state[i] == 'u' && unresolved < 0) unresolved = static_cast(i); + if (state[i]) InterlockedIncrement(state[i] == 'u' ? (ud.kind == 3 ? &cxe_rootconst : &cxe_descword) : &cxe_null_res); + } + static const bool run_unresolved = x2w_local::env_on("X2W_CX_UNRESOLVED_RUN"); + if (cx_entry_log(key) && x2w_local::first_calls(tr.entry_logged, 4)) { + char text[1600]; + int used = std::snprintf(text, sizeof(text), "x2w-cx entry %016llx dispatch (%u, %u, %u):", key, x, y, z); + for (std::size_t i = 0; i < tr.uds.size() && used < static_cast(sizeof(text)) - 80; ++i) { + const ComputeTranslation::Ud& ud = tr.uds[i]; + static const char* const names[] = {"?", "?", "?", "rootconst", "stride", "bufword3", "bufbase", "descword"}; + const char* name = ud.kind >= 0 && ud.kind <= 7 ? names[ud.kind] : "?"; + used += std::snprintf(text + used, sizeof(text) - used, " ud%zu=%08x %s(%d,%d)%s", i, values[i], name, ud.a, ud.b, + state[i] == 'u' ? " UNRESOLVED" : state[i] == 'n' ? " null-res" : ""); + } + log("%s", text); + // The first words of each small bound buffer, as the CPU sees the title's memory now. The GPU reads the same + // pages in place (desktop_range) when the list executes, so a later title write can still change them. + for (UINT i = 0; i < n; ++i) { + if (!res_address[i] || !res_bytes[i] || res_bytes[i] > 256) continue; + std::uint32_t w[8] = {}; + const std::size_t count = res_bytes[i] / 4 < 8 ? res_bytes[i] / 4 : 8; + if (!count || !x2w_local::readable(reinterpret_cast(res_address[i]), count * 4)) continue; + std::memcpy(w, reinterpret_cast(res_address[i]), count * 4); + log("x2w-cx entry %016llx res %u at 0x%llx (%zu bytes): %08x %08x %08x %08x %08x %08x %08x %08x", key, i, res_address[i], + res_bytes[i], w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]); + } + } + if (unresolved >= 0) { + const ComputeTranslation::Ud& ud = tr.uds[unresolved]; + static LONG logged; + if (first_calls(logged, 12)) + log("x2w-cx %016llx: entry value %d (%s %d %d) unresolved: kind %d, words set %04x%s", key, unresolved, + ud.kind == 3 ? "rootconst" : "descword", ud.a, ud.b, ud.a >= 0 && ud.a < 16 ? pass.compute_kind[ud.a] : -1, + ud.a >= 0 && ud.a < 16 ? pass.compute_set[ud.a] : 0, run_unresolved ? "; run anyway (X2W_CX_UNRESOLVED_RUN)" : "; dispatch skipped"); + if (!run_unresolved) { + dispatch_outcome = co_c67_unresolved; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + } + list->SetPipelineState(tr.pso); + if (!pass.heap_set) { + list->SetDescriptorHeaps(1, &draw_heap); + pass.heap_set = true; + pass.bound_sampler_heap = nullptr; // this call unbinds any sampler heap a draw bound + } + list->SetComputeRootSignature(tr.root); + list->SetComputeRoot32BitConstants(0, tr.uds.empty() ? 1u : static_cast(tr.uds.size()), values, 0); + if (tr.heap) { + const UINT h0 = first + 2 * n; + const SIZE_T cpu0 = draw_heap->GetCPUDescriptorHandleForHeapStart().ptr; + const u64 gpu0 = draw_heap->GetGPUDescriptorHandleForHeapStart().ptr; + const u64 vinfo_bytes = vinfo_buffer->GetDesc().Width; + bounded_raw_srv(heap_view.window, heap_view.offset, heap_view.bytes, D3D12_CPU_DESCRIPTOR_HANDLE{cpu0 + SIZE_T{h0} * draw_heap_increment}); + bounded_raw_srv(vinfo_buffer, 0, vinfo_bytes, D3D12_CPU_DESCRIPTOR_HANDLE{cpu0 + SIZE_T{h0 + 1} * draw_heap_increment}); + list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu0 + u64{h0} * draw_heap_increment}); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu0 + u64{h0 + 1} * draw_heap_increment}); + if (!tr.heap_views_logged) { + tr.heap_views_logged = true; // once per key (draw_lock held) + static LONG shown; + if (first_calls(shown, 256)) + log("x2w-cx %016llx: bounded heap views: heapmem %llu bytes (title heap %llu), vinfo %llu", key, heap_view.bytes, heap_view.heap_bytes, + vinfo_bytes); + } + if (n) list->SetComputeRootDescriptorTable(3, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + } else if (n) { + list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + } + ReleaseSRWLockExclusive(&draw_lock); + gpu_time::dispatch(self, list, key, false); + indirect_dispatch(self, list, x, y, z); + gpu_time::dispatch(self, list, key, true); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + const LONG done = InterlockedIncrement(&cx_dispatched); + dispatch_outcome = co_c67_run; + if (x2w_local::first_of(done, 8) || done % 5000 == 0) + log("x2w-cx dispatch %ld: %016llx (%u, %u, %u); ready %ld missing %ld null %ld bad-uav %ld; ranges ok %ld split %ld unmapped %ld", done, key, x, y, z, + cx_ready, cx_missing, cx_null_res, cx_bad_uav, range_ok, range_split, range_unmapped); + if ((done & 63) == 1) check_device("translated dispatch", 0); + return true; +} diff --git a/src/startup_stubs/d3d12_compute_binding_trace.inl b/src/startup_stubs/d3d12_compute_binding_trace.inl index f40e41078c..7231499ea1 100644 --- a/src/startup_stubs/d3d12_compute_binding_trace.inl +++ b/src/startup_stubs/d3d12_compute_binding_trace.inl @@ -74,7 +74,7 @@ void trace_compute_dispatch(Wrapper* list, const Pass& pass, UINT x, UINT y, UIN bindings += item; } x2w_local::logf("x2w-compute-bindings key=%016llx Dispatch=%ux%ux%u root=%s desktop-root=%u desktop-pso=%u params=%zu%s", - pipeline.compute_trace_key, x, y, z, root_match, pass.compute_root != nullptr, pass.compute_pipeline, + pipeline.compute_trace_key, x, y, z, root_match, pass.compute_root_desktop != nullptr, pass.compute_pipeline, params ? params->size() : 0, bindings.c_str()); } diff --git a/src/startup_stubs/d3d12_copy_buffer.inl b/src/startup_stubs/d3d12_copy_buffer.inl new file mode 100644 index 0000000000..bc740f93b7 --- /dev/null +++ b/src/startup_stubs/d3d12_copy_buffer.inl @@ -0,0 +1,80 @@ + +LONG buffer_copies_done, buffer_copies_skipped; + +int copy_buffer_mode() +{ + static const int mode = [] { + char value[8]{}; + const DWORD saved = GetLastError(); + const DWORD length = GetEnvironmentVariableA("X2W_D3D12_COPY_BUFFER", value, sizeof(value)); + SetLastError(saved); + if (!length || value[0] == '0') return 0; + return value[0] == '1' ? 2 : (value[0] == 'l' || value[0] == 'L') ? 1 : (value[0] == 'g' || value[0] == 'G') ? 3 : 0; + }(); + return mode; +} + +bool copy_title_bytes(unsigned char* dest, const unsigned char* source, std::size_t bytes) noexcept +{ + __try { + std::memmove(dest, source, bytes); + return true; + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } +} + +void __stdcall list_copy_buffer(Wrapper* self, Wrapper* dest, u64 dest_offset, Wrapper* source, u64 source_offset, u64 bytes) +{ + (void)self; + const int mode = copy_buffer_mode(); + auto* const to = dest && dest->own().kind == resource_kind ? static_cast(dest->own().title_memory) : nullptr; + auto* const from = source && source->own().kind == resource_kind ? static_cast(source->own().title_memory) : nullptr; + const char* outcome = "copied"; + bool done = false; + if (!to || !from) { + outcome = !to ? "skipped: destination has no title memory" : "skipped: source has no title memory"; + } else if (!bytes || bytes > (u64{256} << 20) || dest_offset > (u64{1} << 40) || source_offset > (u64{1} << 40)) { + outcome = "skipped: size or offset out of range"; + } else if (!x2w_local::readable(from + source_offset, static_cast(bytes))) { + outcome = "skipped: source unreadable"; + } else if (mode < 2) { + outcome = "not copied (X2W_D3D12_COPY_BUFFER=log)"; + } else if (!copy_title_bytes(to + dest_offset, from + source_offset, static_cast(bytes))) { + outcome = "skipped: destination not writable"; + } else { + done = true; + } + InterlockedIncrement(done ? &buffer_copies_done : &buffer_copies_skipped); + copy_watch_note("record-time", to ? reinterpret_cast(to) + dest_offset : 0, from ? reinterpret_cast(from) + source_offset : 0, + bytes, outcome); + static SRWLOCK seen_lock = SRWLOCK_INIT; + static std::unordered_set* seen = new std::unordered_set; + const u64 where = to ? reinterpret_cast(to) + dest_offset : reinterpret_cast(dest) ^ (dest_offset << 1); + AcquireSRWLockExclusive(&seen_lock); + const bool fresh = seen->size() < 4096 && seen->insert(where).second; + ReleaseSRWLockExclusive(&seen_lock); + static LONG shown_small, shown_long; + if (fresh && first_calls(bytes && bytes <= 0x100 ? shown_small : shown_long, 256)) { + const std::size_t dumped = bytes && bytes <= 0x100 ? static_cast(bytes) : 16; + char head[3 * 0x100 + 1] = ""; + if (from && x2w_local::readable(from + source_offset, dumped)) hex_text(from + source_offset, dumped, head, sizeof(head)); + log("x2w-copy CopyBufferRegion dest %p+0x%llx (title %p) source %p+0x%llx (title %p) bytes 0x%llx: %s; source [%s]", + static_cast(dest), dest_offset, to ? static_cast(to + dest_offset) : nullptr, static_cast(source), + source_offset, from ? static_cast(from + source_offset) : nullptr, bytes, outcome, head); + } + static LONG reports; + const LONG total = buffer_copies_done + buffer_copies_skipped; + if (total % 1000 == 0 && first_calls(reports, 40)) + log("x2w-copy CopyBufferRegion totals: copied %ld, skipped %ld", buffer_copies_done, buffer_copies_skipped); +} + +// Installs slot 15 when the switch asks for it; one line says which mode is in effect. +void install_copy_buffer(ListTyped* typed) +{ + const int mode = copy_buffer_mode(); + if (!mode) return; + typed[15] = mode == 3 ? reinterpret_cast(&list_copy_buffer_gpu) : reinterpret_cast(&list_copy_buffer); + log("x2w-copy X2W_D3D12_COPY_BUFFER=%s: command-list slot 15 (CopyBufferRegion) %s", mode == 3 ? "gpu" : mode == 2 ? "1" : "log", + mode == 3 ? "runs on the GPU in list order (record-time copy as fallback)" : mode == 2 ? "copies title memory at record time" : "is logged only"); +} diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 16aa47bd07..af1d36a629 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -9,19 +9,31 @@ // buffers named by the hardware descriptors in its tables, textures behind view tokens) into an // upload ring / a private descriptor heap. +constexpr int draw_srv_limit = 64; + struct Translation { struct Srv { int kind, source, a, b; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture; source 0 table(param a, byte b), 1 vertex stream a, 2 root parameter a - enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; + enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, buf_word3, uav_word3, uav_base, uav_stride, d16_unorm16, desc_word3, desc_word }; struct Ud { int kind, a, b; }; + struct Uav { int kind, source, a, b; }; int state = 0; // 1 ready, 2 unavailable ULONGLONG retry_manifest_at = 0; // Only an absent manifest can become ready on a later draw. std::vector srvs; std::vector uds; + std::vector uavs; // u0.. in their own table (root parameter uav_parameter) + unsigned uav_base_wanted = 0; // bit per uav that has a `udsrc uavbase` value: a misaligned view may start below it + UINT uav_parameter = 0; + bool heap = false; // `heap 1`: heapmem, vinfo and the view-id region (root parameters heap_parameter..+2) + UINT heap_parameter = 0; + bool heap_views_logged = false; + bool heapwords = false; + UINT vdesc_parameter = 0; x2w_startup::TranslatedSamplers samplers; x2w_startup::ExportWriteMasks write_masks; // manifest 'wmask': channels each export leaves unwritten (#1674) x2w_startup::D16ImageSrvs d16_srvs; // manifest 'd16srv': texture views that must match proven D16 formats (#2023) ID3DBlob* vs = nullptr; ID3DBlob* ps = nullptr; + ID3DBlob* ms = nullptr; ID3D12RootSignature* root = nullptr; std::optional independent_indirect_entry; std::optional indexed_indirect_entry; @@ -49,7 +61,67 @@ struct BoundPipeline { D3D12_RASTERIZER_DESC rasterizer{}; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; std::unordered_map pipelines; // by target formats + bool has_words = false; // state block A read (ds / rs / masked_blend valid where .ok) + bool mesh_layout = false; // A+0x004 == 6: the fields sit 0x54 later (read_words handled it) + bool blend_overridden = false; // a slot 55 blend patch or a stream blend subobject replaces the register words + bool derived_ds = false, derived_rs = false; // a slot 55 depth-stencil / rasterizer part replaces A's + x2w_pipeline_state::DepthStencil ds; + x2w_pipeline_state::Raster rs; + x2w_pipeline_state::Blend masked_blend; + D3D12_DEPTH_STENCIL_DESC patch_ds{}; + D3D12_RASTERIZER_DESC patch_rs{}; + std::uint32_t raw_mode = 0, raw_clip = 0; +}; + +namespace draw_state { +enum Counter { + decoded, decoded_mesh, class_depth_off, class_depth_read, class_depth_write, class_stencil, class_cull, class_blend, class_masked, + class_dual, refused_depth, refused_raster, refused_blend, derived_ds, derived_rs, derived_invalid, depth_bounds_ignored, + stencil_masks_differ, clip_split, bias_rounded, conservative_dropped, pso_new, pso_failed_fallback, pso_failed_both, + draws_depth_no_target, draws_stencil_no_plane, draws_read_only, draws_rect_cull_off, dual_multi_target, draws_depth_uncleared, count }; +LONG n[count]; +void add(Counter c) { InterlockedIncrement(&n[c]); } +const x2w_pipeline_state::Switches& switches() +{ + static const x2w_pipeline_state::Switches s = [] { + const auto v = x2w_pipeline_state::switches_from_env(); + log("x2w-draw-state switches: depth %d cull %d (flip %d) blend masks %d depth clears %d depth clip %d (X2W_DRAW_STATE_DEPTH / " + "_CULL / _CULL_FLIP / _BLEND / _DEPTH_CLEAR / _DEPTHCLIP, X2W_DRAW_STATE=0 all off)", v.depth, v.cull, v.flip, v.blend, + v.depth_clear, v.depthclip); + return v; + }(); + return s; +} +} // namespace draw_state + +// One line per 300 frames (counters reset here). +void report_draw_state() +{ + using namespace draw_state; + LONG v[count]; + for (int i = 0; i < count; ++i) v[i] = InterlockedExchange(&n[i], 0); + const auto& s = switches(); + log("x2w-draw-state 300 frames (depth %d cull %d flip %d masks %d): pipelines decoded %ld (mesh layout %ld) [depth off %ld, read %ld, " + "write %ld, stencil %ld, cull %ld, blend %ld, masked %ld, dual-source %ld]; refused depth %ld raster %ld blend %ld; derived parts " + "depth-stencil %ld rasterizer %ld invalid %ld; flagged: depth bounds ignored %ld, stencil back masks differ %ld, one zclip " + "%ld, bias rounded %ld, conservative dropped %ld; PSOs new-state %ld, failed->old state %ld, failed both %ld; draws: depth/" + "stencil test without depth target %ld, stencil without plane %ld, read-only target writes off %ld, rect list cull off %ld, " + "dual-source with >1 target %ld, depth/stencil test on a never-cleared depth target off %ld", + s.depth, s.cull, s.flip, s.blend, v[decoded], v[decoded_mesh], v[class_depth_off], v[class_depth_read], v[class_depth_write], + v[class_stencil], v[class_cull], v[class_blend], v[class_masked], v[class_dual], v[refused_depth], v[refused_raster], + v[refused_blend], v[derived_ds], v[derived_rs], v[derived_invalid], v[depth_bounds_ignored], v[stencil_masks_differ], + v[clip_split], v[bias_rounded], v[conservative_dropped], v[pso_new], v[pso_failed_fallback], v[pso_failed_both], + v[draws_depth_no_target], v[draws_stencil_no_plane], v[draws_read_only], v[draws_rect_cull_off], v[dual_multi_target], + v[draws_depth_uncleared]); + if (s.depth_clear) + log("x2w-draw-state 300 frames: depth clears (slot 51) forwarded %ld; dropped: list not open %ld, not a depth view %ld, depth " + "outside [0, 1] %ld, nothing to clear %ld", InterlockedExchange(&depth_clears[0], 0), InterlockedExchange(&depth_clears[1], 0), + InterlockedExchange(&depth_clears[2], 0), InterlockedExchange(&depth_clears[3], 0), InterlockedExchange(&depth_clears[4], 0)); +} +int load_mesh_stages(Translation& tr, const std::string& manifest); +bool mesh_issue_active(Wrapper* self); +ID3D12PipelineState* mesh_pso_for(const Translation& tr); // Looks for a desktop-layout D3D12_BLEND_DESC inside a state block: two flags, then eight render // target entries whose fields are all inside their enumerations. @@ -76,11 +148,340 @@ bool find_blend(const std::vector& block, D3D12_BLEND_DESC* out, } SRWLOCK draw_lock = SRWLOCK_INIT; +void log_thread_stack(DWORD thread_id, const char* what) +{ + HANDLE thread = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, thread_id); + if (!thread) return; + DWORD64 frames[40] = {}; + int depth = 0; + if (SuspendThread(thread) != static_cast(-1)) { + CONTEXT context{}; + context.ContextFlags = CONTEXT_FULL; + if (GetThreadContext(thread, &context)) { + for (; depth < 40 && context.Rip; ++depth) { + frames[depth] = context.Rip; + DWORD64 image = 0; + PRUNTIME_FUNCTION function = RtlLookupFunctionEntry(context.Rip, &image, nullptr); + if (!function) { + // A leaf function: the return address is at rsp. + if (IsBadReadPtr(reinterpret_cast(context.Rsp), 8)) break; + context.Rip = *reinterpret_cast(context.Rsp); + context.Rsp += 8; + continue; + } + void* handler_data = nullptr; + DWORD64 establisher = 0; + RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, context.Rip, function, &context, &handler_data, &establisher, nullptr); + } + } + ResumeThread(thread); + } + CloseHandle(thread); + char text[2400]; + int at = 0; + for (int i = 0; i < depth && at < static_cast(sizeof(text)) - 80; ++i) { + HMODULE module = nullptr; + char name[MAX_PATH] = "?"; + if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(frames[i]), &module) && module) { + GetModuleFileNameA(module, name, MAX_PATH); + const char* slash = std::strrchr(name, '\\'); + at += std::snprintf(text + at, sizeof(text) - at, " %s+0x%llx", slash ? slash + 1 : name, + static_cast(frames[i] - reinterpret_cast(module))); + } else { + at += std::snprintf(text + at, sizeof(text) - at, " 0x%llx", static_cast(frames[i])); + } + } + log("x2w-draw %s thread %lu stack:%s", what, thread_id, text); +} +volatile LONG draw_lock_line, draw_lock_thread; +volatile LONG64 draw_lock_since; +void draw_lock_taken(int line) +{ + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + draw_lock_line = line; + draw_lock_thread = static_cast(GetCurrentThreadId()); + draw_lock_since = now.QuadPart; + static const HANDLE monitor = CreateThread(nullptr, 0, [](void*) -> DWORD { + LARGE_INTEGER frequency; + QueryPerformanceFrequency(&frequency); + LONG64 reported = 0; + for (;;) { + Sleep(5000); + if (TryAcquireSRWLockExclusive(&draw_lock)) { + ReleaseSRWLockExclusive(&draw_lock); + continue; + } + const LONG64 since = draw_lock_since; + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + const double held = static_cast(now.QuadPart - since) / static_cast(frequency.QuadPart); + // Two more looks 5 s apart show whether the holder is moving. + static int looks; + if (held >= 10.0 && since == reported && looks < 2) { + ++looks; + log_thread_stack(static_cast(draw_lock_thread), "draw_lock holder (again)"); + } + if (held >= 10.0 && since != reported) { + looks = 0; + reported = since; + log("x2w-draw draw_lock held %.1f s by thread %ld (taken at line %ld)", held, draw_lock_thread, draw_lock_line); + log_thread_stack(static_cast(draw_lock_thread), "draw_lock holder"); + } + } + }, nullptr, 0, nullptr); + (void)monitor; +} +namespace draw_lock_times { +struct Site { + volatile LONG id; + volatile LONG64 holds, hold_ticks, hold_max, waits, wait_ticks, wait_max; +}; +constexpr int site_count = 128; +Site sites[site_count]; +volatile LONG overflow; // acquisitions whose site found no free slot +volatile LONG hold_open; // written by the holder only: draw_lock_taken ran and the release has not been counted +bool on() +{ + static const bool value = x2w_local::env_on("X2W_DRAW_LOCK_TIMES"); + return value; +} +Site* site(LONG id) +{ + const unsigned start = static_cast(id) * 2654435761u; + for (int i = 0; i < site_count; ++i) { + Site& s = sites[(start + static_cast(i)) % site_count]; + LONG seen = s.id; + if (seen == id) return &s; + if (seen == 0) { + seen = InterlockedCompareExchange(&s.id, id, 0); + if (seen == 0 || seen == id) return &s; + } + } + InterlockedIncrement(&overflow); + return nullptr; +} +void raise_max(volatile LONG64& max, LONG64 value) +{ + for (LONG64 seen = max; value > seen;) { + const LONG64 before = InterlockedCompareExchange64(&max, value, seen); + if (before == seen) break; + seen = before; + } +} +void note_wait(LONG id, LONG64 ticks) +{ + if (Site* s = site(id)) { + InterlockedIncrement64(&s->waits); + InterlockedAdd64(&s->wait_ticks, ticks); + raise_max(s->wait_max, ticks); + } +} +const char* file_of(LONG id) +{ + switch (id / 100000) { + case 0: return "xs_device"; + case 1: return "draw"; + case 2: return "compute"; + case 3: return "mesh"; + case 4: return "rawaddr"; + case 9: return id >= 999000 ? "fixture" : "memcut_release"; + default: return "?"; + } +} +// Every 300 frames (queue_present) and from the fixture export: sites by hold time, then reset. +void report(const char* when) +{ + if (!on()) return; + static LONG64 frequency = [] { + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + return f.QuadPart; + }(); + struct Row { LONG id; LONG64 holds, hold_ticks, hold_max, waits, wait_ticks, wait_max; }; + Row rows[site_count]; + int count = 0; + for (Site& s : sites) { + if (!s.id) continue; + rows[count++] = {s.id, InterlockedExchange64(&s.holds, 0), InterlockedExchange64(&s.hold_ticks, 0), InterlockedExchange64(&s.hold_max, 0), + InterlockedExchange64(&s.waits, 0), InterlockedExchange64(&s.wait_ticks, 0), InterlockedExchange64(&s.wait_max, 0)}; + if (!rows[count - 1].holds && !rows[count - 1].waits) --count; + } + std::sort(rows, rows + count, [](const Row& a, const Row& b) { return a.hold_ticks > b.hold_ticks; }); + const auto ms = [](LONG64 ticks) { return static_cast(ticks) * 1000.0 / static_cast(frequency); }; + LONG64 hold_total = 0, wait_total = 0; + for (int i = 0; i < count; ++i) hold_total += rows[i].hold_ticks, wait_total += rows[i].wait_ticks; + char line[3072]; + int n = std::snprintf(line, sizeof(line), "x2w-draw lock times (%s, X2W_DRAW_LOCK_TIMES): held %.1f ms, waited %.1f ms over %d sites%s; " + "site id file holds/total ms/max ms, waits/total ms/max ms:", when, ms(hold_total), ms(wait_total), count, + overflow ? " (site table full: some not counted)" : ""); + for (int i = 0; i < count && n < static_cast(sizeof(line)) - 160; ++i) { + const Row& r = rows[i]; + n += std::snprintf(line + n, sizeof(line) - n, " %ld %s %lld/%.1f/%.2f, %lld/%.1f/%.2f;", r.id, file_of(r.id), r.holds, ms(r.hold_ticks), + ms(r.hold_max), r.waits, ms(r.wait_ticks), ms(r.wait_max)); + } + log("%s", line); +} +} // namespace draw_lock_times +void lock_draw(int line) +{ + if (!TryAcquireSRWLockExclusive(&draw_lock)) { + Timed waited(time_draw_lock_wait); + if (draw_lock_times::on()) { + LARGE_INTEGER before, after; + QueryPerformanceCounter(&before); + AcquireSRWLockExclusive(&draw_lock); + QueryPerformanceCounter(&after); + draw_lock_times::note_wait(line, after.QuadPart - before.QuadPart); + } else { + AcquireSRWLockExclusive(&draw_lock); + } + } + draw_lock_taken(line); + if (draw_lock_times::on()) draw_lock_times::hold_open = 1; +} +void release_exclusive_timed(PSRWLOCK lock) +{ + if (lock == &draw_lock && draw_lock_times::on() && draw_lock_times::hold_open && + draw_lock_thread == static_cast(GetCurrentThreadId())) { + draw_lock_times::hold_open = 0; + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + const LONG64 ticks = now.QuadPart - draw_lock_since; + if (draw_lock_times::Site* s = draw_lock_times::site(draw_lock_line)) { + InterlockedIncrement64(&s->holds); + InterlockedAdd64(&s->hold_ticks, ticks); + draw_lock_times::raise_max(s->hold_max, ticks); + } + } + ReleaseSRWLockExclusive(lock); +} +#define ReleaseSRWLockExclusive(lock) release_exclusive_timed(lock) +bool draw_lock_split() +{ + static const bool on = x2w_local::env_on("X2W_DRAW_LOCK_SPLIT"); + return on; +} +// Takes draw_lock for its scope when `split` (the lock is not held then); nothing otherwise (it is held). +struct SplitRelock { + bool split; + SplitRelock(bool s, int line) : split(s) { if (split) lock_draw(line); } + ~SplitRelock() { if (split) ReleaseSRWLockExclusive(&draw_lock); } + SplitRelock(const SplitRelock&) = delete; + SplitRelock& operator=(const SplitRelock&) = delete; +}; +// Fixture hook (startup_draw_lock_times): op 0 takes draw_lock at site 999000 + b, holds it a microseconds (spin) +// and releases it; op 1 writes the report now ("fixture"). +extern "C" __declspec(dllexport) u64 WINAPI x2w_draw_lock_times_test(int op, u64 a, u64 b) +{ + if (op == 1) { + draw_lock_times::report("fixture"); + return draw_lock_times::on() ? 1 : 0; + } + if (op != 0) return 0; + lock_draw(999000 + static_cast(b)); + LARGE_INTEGER start, now, frequency; + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&start); + do QueryPerformanceCounter(&now); + while (static_cast(now.QuadPart - start.QuadPart) * 1000000ull < a * static_cast(frequency.QuadPart)); + ReleaseSRWLockExclusive(&draw_lock); + return 1; +} std::unordered_map& translation_by_pipeline() { static std::unordered_map m; return m; } std::unordered_map& translation_by_key() { static std::unordered_map m; return m; } LONG translated_draws, untranslated_draws, translation_ready, translation_missing, null_bindings; LONG formatted_draws_refused; // draws whose formatted buffer load had no resolved descriptor word 3 (also untranslated) LONG null_by_cause[x2w_local::null_cause_count]; // null_bindings split by cause; the parts add up to it +LONG rt_loaded_word3, rt_loaded_uav, rt_loaded_heap; +LONG rt_word3_set, rt_word3_zero; +LONG rt_uav_draws, rt_uav_buf_bound, rt_uav_buf_unresolved, rt_uav_buf_misaligned, rt_srv_in_place, rt_srv_stale_copy; +LONG rt_heap_draws, rt_heap_skipped; +LONG rt_uav_tex[6]; // texture uavs: [0] bound; [1..5] draws skipped (unresolved, flag, shape, format, typed store) +LONG rt_written_evicted; // GPU-written ranges dropped (registry full) +// GPU-ordered CopyBufferRegion (slot 15, X2W_D3D12_COPY_BUFFER=gpu): copies run on the GPU, and record-time +// fallbacks by reason (the record-time copy of d3d12_copy_buffer.inl). +enum CopyFallback { cf_no_list, cf_no_title_memory, cf_range, cf_unaligned, cf_overlap, cf_dest_unresolved, cf_source_unresolved, + cf_no_pipeline, cf_copy_list_same, cf_reasons }; +const char* const copy_fallback_names[cf_reasons] = {"list not recording", "no title memory", "size or offset out of range", + "offset or size not a multiple of 4", "overlapping ranges in one window", "destination not in one window", + "source not in one window", "copy pipeline unavailable", "copy-type list, source and destination in one window"}; +LONG cg_gpu, cg_same_window, cg_copy_list, cg_record_too, cg_fallback[cf_reasons]; +LONG64 cg_bytes; +std::size_t gpu_written_count(); // draw_lock held +LONG rt_report_frame = -1; +void report_texture_census(); +void report_draw_rt() // draw_lock held +{ + report_texture_census(); + if (frame_number % 300 || frame_number == rt_report_frame) return; + LONG fallbacks = 0; + for (LONG f : cg_fallback) fallbacks += f; + if (cg_gpu || fallbacks) { + rt_report_frame = frame_number; + log("x2w-copy-gpu totals: frame %ld; on the GPU %ld (same window %ld, copy-type lists %ld, %lld KiB; also copied at record time %ld); " + "record-time fallback %ld (list %ld, title memory %ld, range %ld, unaligned %ld, overlap %ld, dest unresolved %ld, source unresolved %ld, " + "pipeline %ld, copy list same window %ld); gpu-written ranges %zu evicted %ld", + frame_number, cg_gpu, cg_same_window, cg_copy_list, cg_bytes >> 10, cg_record_too, fallbacks, cg_fallback[0], cg_fallback[1], + cg_fallback[2], cg_fallback[3], cg_fallback[4], cg_fallback[5], cg_fallback[6], cg_fallback[7], cg_fallback[8], gpu_written_count(), + rt_written_evicted); + } + if (!(rt_loaded_word3 | rt_loaded_uav | rt_loaded_heap)) return; + rt_report_frame = frame_number; + log("x2w-draw-rt totals: frame %ld; loaded bufword3 %ld uav %ld heap %ld; bufword3 values set %ld zero %ld; " + "uav draws %ld, buffer uavs bound %ld null (unresolved %ld misaligned %ld); srvs in place %ld stale copy %ld; " + "texture uavs bound %ld, draws skipped (unresolved %ld flag %ld shape %ld format %ld store %ld); heap draws %ld skipped %ld", + frame_number, rt_loaded_word3, rt_loaded_uav, rt_loaded_heap, rt_word3_set, rt_word3_zero, + rt_uav_draws, rt_uav_buf_bound, rt_uav_buf_unresolved, rt_uav_buf_misaligned, rt_srv_in_place, rt_srv_stale_copy, + rt_uav_tex[0], rt_uav_tex[1], rt_uav_tex[2], rt_uav_tex[3], rt_uav_tex[4], rt_uav_tex[5], rt_heap_draws, rt_heap_skipped); +} + +bool texture_census_on(); +bool census_every_event(); +void report_memory_srv_census(long frame); +enum TextureSource { ts_linear_srv, ts_tiled_address, ts_other, ts_detiled, ts_count }; +LONG64 census_real[ts_count], census_null[x2w_local::null_cause_count], census_real_format[128]; +LONG census_report_frame = -1; +void log_texture_census(const char* when); +void census_texture_binding(Wrapper* resource, ID3D12Resource* texture, x2w_local::NullCause cause) +{ + if (!texture_census_on()) return; + if (!texture) { + InterlockedIncrement64(&census_null[static_cast(cause)]); + } else { + const int source = resource && resource->own().detiled_memory_srv ? ts_detiled + : resource && resource->own().linear_memory_srv ? ts_linear_srv + : resource && resource->own().tiled_address_srv ? ts_tiled_address : ts_other; + InterlockedIncrement64(&census_real[source]); + InterlockedIncrement64(&census_real_format[static_cast(texture->GetDesc().Format) & 127]); + } + if (census_every_event()) log_texture_census("binding"); +} +void report_texture_census() // draw_lock held +{ + if (!texture_census_on() || frame_number % 300 || frame_number == census_report_frame) return; + census_report_frame = frame_number; + char when[32]; + std::snprintf(when, sizeof(when), "frame %ld", frame_number); + log_texture_census(when); + report_memory_srv_census(frame_number); +} +void log_texture_census(const char* when) +{ + char formats[512] = ""; + int used = 0; + for (int f = 0; f < 128 && used < 480; ++f) + if (census_real_format[f]) used += std::snprintf(formats + used, sizeof(formats) - used, " %d:%lld", f, census_real_format[f]); + char nulls[256] = ""; + used = 0; + for (int c = 0; c < x2w_local::null_cause_count && used < 230; ++c) + if (census_null[c]) used += std::snprintf(nulls + used, sizeof(nulls) - used, " cause%d:%lld", c, census_null[c]); + log("x2w-texcensus draw textures %s (cumulative): real %lld (linear memory srv %lld, tiled address %lld, other %lld, detiled %lld), " + "null%s; real by format%s", + when, census_real[0] + census_real[1] + census_real[2] + census_real[3], census_real[0], census_real[1], census_real[2], + census_real[3], nulls, formats); +} void count_null_binding(x2w_local::NullCause cause) { @@ -88,8 +489,304 @@ void count_null_binding(x2w_local::NullCause cause) InterlockedIncrement(&null_bindings); InterlockedIncrement(&null_by_cause[static_cast(cause)]); } +struct WatchedSlot { u64 at, key, slot; UINT srv; std::uint32_t words[8]; LONG since; bool reported; }; +SRWLOCK watch_lock = SRWLOCK_INIT; +std::vector& watched_slots() { static std::vector v; return v; } +extern LONG frame_number; +void watch_descriptor(u64 at, const std::uint32_t* words, u64 key, UINT srv, u64 slot) +{ + AcquireSRWLockExclusive(&watch_lock); + if (watched_slots().size() < 64) { + WatchedSlot w{at, key, slot, srv, {}, frame_number, false}; + std::memcpy(w.words, words, sizeof(w.words)); + watched_slots().push_back(w); + } + ReleaseSRWLockExclusive(&watch_lock); +} +void note_descriptor_watch(LONG frame) +{ + AcquireSRWLockExclusive(&watch_lock); + for (WatchedSlot& w : watched_slots()) { + if (w.reported) continue; + std::uint32_t now[8]{}; + if (!x2w_local::readable(reinterpret_cast(w.at), sizeof(now))) continue; + std::memcpy(now, reinterpret_cast(w.at), sizeof(now)); + if (!std::memcmp(now, w.words, sizeof(now))) continue; + w.reported = true; + log("x2w-draw watched slot 0x%llx (for %016llx srv %u, watched since frame %ld) changed at frame %ld: %08x %08x %08x %08x %08x %08x %08x %08x", + w.slot, w.key, w.srv, w.since, frame, now[0], now[1], now[2], now[3], now[4], now[5], now[6], now[7]); + } + ReleaseSRWLockExclusive(&watch_lock); +} + +bool refused_marker_description(const std::uint32_t* w, char* out, std::size_t size); // below +void note_null_texture(u64 key, UINT srv, u64 entry, const std::uint32_t* words, x2w_local::NullCause cause) +{ + static const bool on = [] { + const bool value = x2w_local::env_on("X2W_DRAW_NULL_TEXTURE_LOG"); + if (value) log("x2w-draw X2W_DRAW_NULL_TEXTURE_LOG=1: null texture bindings are logged per pipeline key and srv"); + return value; + }(); + if (!on || cause == x2w_local::NullCause::none) return; + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_set* seen = new std::unordered_set; + static LONG lines; + AcquireSRWLockExclusive(&lock); + const bool fresh = seen->insert(key * 31 + srv).second; + ReleaseSRWLockExclusive(&lock); + if (!fresh || !first_calls(lines, 96)) return; + log("x2w-draw null texture %016llx srv %u cause %s frame %ld: entry 0x%llx words %08x %08x %08x %08x %08x %08x %08x %08x", key, srv, + x2w_local::null_cause_names[static_cast(cause)], frame_number, entry, words[0], words[1], words[2], words[3], words[4], + words[5], words[6], words[7]); + if (char marker[256]; refused_marker_description(words, marker, sizeof marker)) { + log("x2w-draw null texture %016llx srv %u: %s", key, srv, marker); + return; + } + bool rest_zero = true; + for (int i = 1; i < 8; ++i) rest_zero = rest_zero && words[i] == 0; + const bool link = words[0] && words[0] != view_token_magic && rest_zero; + // A token whose first word the title replaced (a freed slot that still names a view). + const bool clobbered = words[0] != view_token_magic && words[2] >= 17 && words[2] <= 22 && (words[4] || words[5]); + if (!link && !clobbered) return; + AcquireSRWLockShared(¬e_lock); + const std::vector heaps = heap_infos(); + ViewRecord named{}; + const bool named_known = clobbered && words[1] < view_records().size(); + if (named_known) named = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + if (clobbered) + log("x2w-draw null texture %016llx srv %u: looks like a freed token: first word 0x%x, view id %u slot %u resource 0x%08x%08x; view %s%s", + key, srv, words[0], words[1], words[2], words[5], words[4], named_known ? "known" : "UNKNOWN", + named_known && named.resource == (u64{words[5]} << 32 | words[4]) ? ", resource matches" : named_known ? ", resource DIFFERS" : ""); + bool in_heap = false; + for (std::size_t h = 0; h < heaps.size(); ++h) { + const HeapInfo& heap = heaps[h]; + if (!heap.title_cpu) continue; + const UINT stride = title_descriptor_stride(heap.title_cpu, heap.increment); + if (entry < heap.title_cpu || entry >= heap.title_cpu + u64{heap.count} * stride) continue; + in_heap = true; + const u64 index = (entry - heap.title_cpu) / stride; + log("x2w-draw null texture %016llx srv %u: entry 0x%llx is index 0x%llx of heap %zu (type %u, count %u, title 0x%llx, stride %u); shadow id %u", + key, srv, entry, index, h, heap.type, heap.count, heap.title_cpu, stride, heap.shadow ? heap.shadow[index] : 0u); + if (!link) break; + for (int d = -1; d <= 0; ++d) { + const u64 slot = u64{words[0]} + d; + if (slot >= heap.count) continue; + const u64 at = heap.title_cpu + slot * stride; + std::uint32_t there[8]{}; + const bool readable = x2w_local::readable(reinterpret_cast(at), sizeof(there)); + if (readable) std::memcpy(there, reinterpret_cast(at), sizeof(there)); + const std::uint32_t shadow = heap.shadow ? heap.shadow[slot] : 0; + log("x2w-draw null texture %016llx srv %u: heap %zu slot 0x%llx (N%s): %s words %08x %08x %08x %08x %08x %08x; shadow id %u%s", + key, srv, h, slot, d ? "-1" : "", readable ? (there[0] == view_token_magic ? "token" : "no token") : "unreadable", there[0], there[1], + there[2], there[3], there[4], there[5], shadow, shadow ? "" : " (no view ever created there)"); + if (d == -1 && readable) watch_descriptor(at, there, key, srv, slot); + } + break; + } + if (!in_heap) log("x2w-draw null texture %016llx srv %u: entry 0x%llx is in no title descriptor heap", key, srv, entry); +} LONG frame_number; +LONG heap_index_checks, heap_index_restored, heap_index_slot_token, heap_index_shadow, heap_index_unresolved; +void resolve_heap_index(u64 key, UINT srv, u64 entry, std::uint32_t* words) +{ + static const bool on = [] { + const bool value = x2w_local::env_on("X2W_DRAW_TEXTURE_HEAP_INDEX"); + if (value) log("x2w-draw X2W_DRAW_TEXTURE_HEAP_INDEX=1: freed or free-slot texture descriptors are resolved (slot N-1 / view id)"); + return value; + }(); + if (!on || words[0] == view_token_magic) return; + bool rest_zero = true; + for (int i = 1; i < 8; ++i) rest_zero = rest_zero && words[i] == 0; + const bool link = words[0] && rest_zero; + const bool clobbered = words[2] >= 17 && words[2] <= 22 && (words[4] || words[5]); + if (!link && !clobbered) return; + const LONG checks = InterlockedIncrement(&heap_index_checks); + std::uint32_t out[8]{}; + const char* how = nullptr; + AcquireSRWLockShared(¬e_lock); + if (clobbered) { + if (words[1] < view_records().size() && view_records()[words[1]].resource == (u64{words[5]} << 32 | words[4])) { + std::memcpy(out, words, sizeof(out)); + out[0] = view_token_magic; + how = "restored token"; + } + } else { + for (const HeapInfo& heap : heap_infos()) { + if (!heap.title_cpu || words[0] > heap.count) continue; + const UINT stride = title_descriptor_stride(heap.title_cpu, heap.increment); + if (entry < heap.title_cpu || entry >= heap.title_cpu + u64{heap.count} * stride) continue; + const u64 slot = u64{words[0]} - 1; + const u64 at = heap.title_cpu + slot * stride; + if (x2w_local::readable(reinterpret_cast(at), sizeof(out))) { + std::memcpy(out, reinterpret_cast(at), sizeof(out)); + if (out[0] == view_token_magic && out[1] < view_records().size()) how = "slot N-1 token"; + } + const std::uint32_t shadow = heap.shadow ? heap.shadow[slot] : 0; + if (!how && shadow && shadow - 1 < view_records().size()) { + const ViewRecord& r = view_records()[shadow - 1]; + const std::uint32_t token[8] = {view_token_magic, shadow - 1, r.slot, 0, static_cast(r.resource), + static_cast(r.resource >> 32), 0, 0}; + std::memcpy(out, token, sizeof(out)); + how = "slot N-1 shadow id"; + } + break; + } + } + ReleaseSRWLockShared(¬e_lock); + InterlockedIncrement(!how ? &heap_index_unresolved : how[0] == 'r' ? &heap_index_restored : how[9] == 't' ? &heap_index_slot_token + : &heap_index_shadow); + static LONG reports; + if ((checks & 4095) == 0 && first_calls(reports, 40)) + log("x2w-draw texture heap index totals: checks %ld, restored tokens %ld, slot N-1 tokens %ld, slot N-1 shadow ids %ld, unresolved %ld", checks, + heap_index_restored, heap_index_slot_token, heap_index_shadow, heap_index_unresolved); + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_set* seen = new std::unordered_set; + AcquireSRWLockExclusive(&lock); + const bool fresh = seen->size() < 4096 && seen->insert(key * 31 + srv).second; + ReleaseSRWLockExclusive(&lock); + static LONG lines; + if (fresh && first_calls(lines, 48)) + log("x2w-draw texture heap index %016llx srv %u frame %ld: entry 0x%llx words %08x %08x %08x -> %s%s (view id %u slot %u)", key, srv, + frame_number, entry, words[0], words[1], words[2], how ? how : "unresolved", how ? "" : ", left null", how ? out[1] : 0u, how ? out[2] : 0u); + if (how) std::memcpy(words, out, sizeof(out)); +} + +bool buffer_heap_index_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_BUFFER_HEAP_INDEX"); + if (v) log("x2w-draw X2W_BUFFER_HEAP_INDEX=1: slot-70 buffers without a resource get a stand-in; free-list buffer entries bind null"); + return v; + }(); + return on; +} +LONG buffer_links, buffer_links_nulled, buffer_refused_views; +// With the switch, a slot-70 call that is refused writes this marker and its reason's code into its destination +// (mark_refused_destination, d3d12_memory_srv.inl), so an entry copied from it names the refusal instead of a link. +constexpr std::uint32_t refused_view_magic = 0x52463258; // "X2FR" +SRWLOCK refusal_names_lock = SRWLOCK_INIT; +const char* refusal_names[64]; +std::uint32_t refusal_code(const char* reason) +{ + AcquireSRWLockExclusive(&refusal_names_lock); + std::uint32_t code = 0; + while (code < 63 && refusal_names[code] && std::strcmp(refusal_names[code], reason)) ++code; + if (!refusal_names[code]) refusal_names[code] = reason; // reasons are string literals + ReleaseSRWLockExclusive(&refusal_names_lock); + return code; +} +const char* refusal_name(std::uint32_t code) +{ + AcquireSRWLockShared(&refusal_names_lock); + const char* name = code < 64 && refusal_names[code] ? refusal_names[code] : "unknown"; + ReleaseSRWLockShared(&refusal_names_lock); + return name; +} +// Why X2W_MEMORY_SRV_DETILE did not take a refused texture call (d3d12_memory_srv.inl detile_decline); 0 = not asked +// (switch off, or not a texture description). +const char* const detile_declines[] = {"-", "not console-swizzled", "a tiled path's form", "announced", "view form", + "layout or element size", "(6: bc mip chain, retired)", "over 1 GiB", "unreadable", "destination", "publish failed", "would detile"}; +// The marker's description words (mark_refused_destination): word 2 = bit 31 | format | layout << 8 | dimension << 17 | +// min(mips, 15) << 20 | detile decline << 24, word 3 = width, word 4 = height, word 5 = depth or array size | first 256 +// bytes readable << 16 | nonzero << 17, words 6/7 = the address. Bit 31 keeps word 2 out of the token slot range. +void describe_marker(const std::uint32_t* w, char* out, std::size_t size) +{ + if (!(w[2] >> 31)) { + std::snprintf(out, size, "no description"); + return; + } + const unsigned decline = (w[2] >> 24) & 15; + std::snprintf(out, size, "fmt %u layout 0x%x dim %u mips %u %ux%ux%u address 0x%llx %s, detile: %s", w[2] & 0xff, (w[2] >> 8) & 0x1ff, + (w[2] >> 17) & 7, (w[2] >> 20) & 15, w[3], w[4], w[5] & 0xffff, u64{w[7]} << 32 | w[6], + !((w[5] >> 16) & 1) ? "unreadable" : (w[5] >> 17) & 1 ? "nonzero" : "zero", + decline < std::size(detile_declines) ? detile_declines[decline] : "?"); +} +bool refused_marker_description(const std::uint32_t* w, char* out, std::size_t size) +{ + if (w[0] != refused_view_magic) return false; + char d[160]; + describe_marker(w, d, sizeof d); + std::snprintf(out, size, "refused: %s; %s", refusal_name(w[1]), d); + return true; +} +LONG marker_rewrites; +bool marker_rewrite_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_MARKER_REWRITE_LOG"); + if (v) log("x2w-draw X2W_MARKER_REWRITE_LOG=1: table entries holding a refused-view marker whose first word was rewritten are counted and logged"); + return v; + }(); + return on; +} +// The description's fixed shape (describe_marker): bit 31 set, bits 28-30 clear, a decline in range, a dimension +// 1-4, a nonzero width, word 5 bits 18-31 clear; and word 0 neither the marker nor a token. +bool rewritten_marker_words(const std::uint32_t* w) +{ + const unsigned dim = (w[2] >> 17) & 7; + return w[0] != refused_view_magic && w[0] != view_token_magic && (w[2] >> 31) && !((w[2] >> 28) & 7) && + ((w[2] >> 24) & 15) < std::size(detile_declines) && dim >= 1 && dim <= 4 && w[3] && !(w[5] >> 18); +} +void note_rewritten_marker(u64 key, UINT srv, u64 entry, const std::uint32_t* w) +{ + if (!marker_rewrite_on() || !rewritten_marker_words(w)) return; + const LONG n = InterlockedIncrement(&marker_rewrites); + if ((n & (n - 1)) == 0) log("x2w-draw rewritten refused-view markers %ld", n); + static LONG shown; + if (!first_calls(shown, 8)) return; + char d[160]; + describe_marker(w, d, sizeof d); + log("x2w-draw rewritten refused-view marker %016llx srv %u frame %ld: entry 0x%llx words %08x %08x %08x %08x %08x %08x %08x %08x; " + "described as %s; reason code %u if word 1 is intact; base as a T# 0x%llx, as a V# 0x%llx", key, srv, frame_number, entry, w[0], w[1], w[2], + w[3], w[4], w[5], w[6], w[7], d, w[1], (u64{w[0]} | u64{w[1] & 0xff} << 32) << 8, u64{w[0]} | u64{w[1] & 0xffff} << 32); +} +bool free_link_words(const std::uint32_t* w) +{ + if (w[0] == refused_view_magic) return true; + if (!w[0] || w[0] == view_token_magic || w[3]) return false; + return (!w[1] && !w[2]) || (w[2] >= 17 && w[2] <= 22); +} +void log_buffer_link(u64 key, UINT srv, u64 entry, const std::uint32_t* words) +{ + AcquireSRWLockShared(¬e_lock); + const std::vector heaps = heap_infos(); + ReleaseSRWLockShared(¬e_lock); + char where[96] = "in no title descriptor heap"; + char slots[2][160] = {"", ""}; + for (std::size_t h = 0; h < heaps.size(); ++h) { + const HeapInfo& heap = heaps[h]; + if (!heap.title_cpu) continue; + const UINT stride = title_descriptor_stride(heap.title_cpu, heap.increment); + if (entry < heap.title_cpu || entry >= heap.title_cpu + u64{heap.count} * stride) continue; + std::snprintf(where, sizeof where, "index 0x%llx of heap %zu (count %u)", (entry - heap.title_cpu) / stride, h, heap.count); + for (int d = -1; d <= 0; ++d) { + const u64 slot = u64{words[0]} + d; + if (slot >= heap.count) continue; + const u64 at = heap.title_cpu + slot * stride; + std::uint32_t there[6]{}; + const bool readable = x2w_local::readable(reinterpret_cast(at), sizeof(there)); + if (readable) std::memcpy(there, reinterpret_cast(at), sizeof(there)); + std::snprintf(slots[d + 1], sizeof slots[0], "slot %s 0x%llx %s %08x %08x %08x %08x %08x %08x shadow %u", d ? "N-1" : "N", slot, + readable ? (there[0] == view_token_magic ? "token" : "words") : "unreadable", there[0], there[1], there[2], there[3], + there[4], there[5], heap.shadow ? heap.shadow[slot] : 0u); + } + break; + } + char kind[80], described[192] = ""; + if (words[0] == refused_view_magic) { + std::snprintf(kind, sizeof kind, "refused: %s", refusal_name(words[1])); + char d[160]; + describe_marker(words, d, sizeof d); + std::snprintf(described, sizeof described, "; refused view: %s", d); + } else { + std::snprintf(kind, sizeof kind, "%s", words[1] || words[2] ? "freed token" : "free link"); + } + log("x2w-frame srv-heapbuf %016llx %u frame %ld: entry 0x%llx words %08x %08x %08x %08x (%s) is %s; %s; %s; bound null%s", key, srv, frame_number, + entry, words[0], words[1], words[2], words[3], kind, where, slots[0], slots[1], described); +} + u64 fnv_bytes(const void* data, std::size_t bytes, u64 hash = 1469598103934665603ull) { for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ static_cast(data)[i]) * 1099511628211ull; @@ -134,6 +831,181 @@ bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std:: return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; } +HRESULT create_draw_root(Translation& tr) +{ + const UINT n = static_cast(tr.srvs.size()), m = static_cast(tr.uavs.size()); + if (!m && !tr.heap) + return x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.size()), n, tr.samplers, &tr.root); + D3D12_ROOT_PARAMETER parameters[9]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameters[0].Constants.Num32BitValues = static_cast(tr.uds.size()); + const D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, n, 0, 0, 0}; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[1].DescriptorTable = {1, &srv_range}; + const D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, x2w_startup::translated_sampler_count, 0, + x2w_startup::translated_sampler_space, 0}; + UINT count = x2w_startup::sampler_root_parameter(n); + if (tr.samplers.heap) { + parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[count].DescriptorTable = {1, &sampler_range}; + ++count; + } + const D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, m, 0, 0, 0}; + if (m) { + tr.uav_parameter = count; + parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[count].DescriptorTable = {1, &uav_range}; + ++count; + } + D3D12_DESCRIPTOR_RANGE heap_ranges[5]{}; + const D3D12_DESCRIPTOR_RANGE bounded_ranges[3] = {{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 1, 0}, {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 1, 1, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 2, 1, 0}}; + if (tr.heap) { + tr.heap_parameter = count; + parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[count].DescriptorTable = {1, &bounded_ranges[0]}; + parameters[count + 1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[count + 1].DescriptorTable = {1, &bounded_ranges[1]}; + for (UINT k = 0; k < 5; ++k) heap_ranges[k] = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, UINT_MAX, 0, 2 + k, 0}; + parameters[count + 2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[count + 2].DescriptorTable = {5, heap_ranges}; + count += 3; + } + if (tr.heap && tr.heapwords) { + tr.vdesc_parameter = count; + parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[count++].DescriptorTable = {1, &bounded_ranges[2]}; + } + const auto statics = x2w_startup::decode_statics(tr.samplers); + const D3D12_ROOT_SIGNATURE_DESC desc{count, parameters, static_cast(statics.size()), statics.data(), D3D12_ROOT_SIGNATURE_FLAG_NONE}; + x2w_startup::ComPtr blob, errors; + HRESULT hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, &errors); + if (FAILED(hr) && errors) log("x2w-draw-rt %016llx root signature: %.300s", tr.key, static_cast(errors->GetBufferPointer())); + if (SUCCEEDED(hr)) hr = device_of(the_device)->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&tr.root)); + return hr; +} + +struct ManifestWatch { + SRWLOCK lock = SRWLOCK_INIT; + std::vector> missing; // translation, its rtv request +}; +ManifestWatch& manifest_watch() { static ManifestWatch w; return w; } +std::unordered_map& manifest_seen() { static std::unordered_map m; return m; } +bool manifest_poll() { static const bool on = x2w_local::env_on("X2W_MANIFEST_POLL"); return on; } + +void manifest_check(const wchar_t* dir, const wchar_t* name) +{ + std::vector> look; + AcquireSRWLockShared(&manifest_watch().lock); + look = manifest_watch().missing; + ReleaseSRWLockShared(&manifest_watch().lock); + if (look.empty() || (!name && !dir[0])) return; + std::unordered_set present; + if (!name) { + std::wstring pattern = std::wstring(dir) + L"\\*.txt"; + WIN32_FIND_DATAW found{}; + const HANDLE find = FindFirstFileExW(pattern.c_str(), FindExInfoBasic, &found, FindExSearchNameMatch, nullptr, + FIND_FIRST_EX_LARGE_FETCH); + if (find == INVALID_HANDLE_VALUE) return; + do { + std::wstring file(found.cFileName); + for (wchar_t& c : file) c = static_cast(towlower(c)); + present.insert(std::move(file)); + } while (FindNextFileW(find, &found)); + FindClose(find); + } + for (const auto& [tr, request] : look) { + wchar_t path[MAX_PATH]; + if (!cache_path(path, L"", tr->key, L".txt")) continue; + const wchar_t* slash = std::wcsrchr(path, L'\\'); + std::wstring file(slash ? slash + 1 : path); + for (wchar_t& c : file) c = static_cast(towlower(c)); + if (name ? _wcsicmp(file.c_str(), name) != 0 : !present.count(file)) continue; + AcquireSRWLockExclusive(&manifest_watch().lock); + auto& m = manifest_watch().missing; + m.erase(std::remove_if(m.begin(), m.end(), [&](const auto& e) { return e.first == tr; }), m.end()); + InterlockedExchange(&manifest_seen()[tr], 1); + ReleaseSRWLockExclusive(&manifest_watch().lock); + log("x2w-draw manifest for %016llx appeared: reloaded at its next draw", tr->key); + } +} + +DWORD WINAPI manifest_watcher(void*) +{ + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + wchar_t dir[MAX_PATH] = L""; + HANDLE handle = INVALID_HANDLE_VALUE; + if (cache_path(dir, L"", 0, L".txt")) { + if (wchar_t* slash = std::wcsrchr(dir, L'\\')) *slash = 0; + handle = CreateFileW(dir, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, nullptr); + } + log("x2w-draw manifest watcher: %s", handle != INVALID_HANDLE_VALUE ? "directory change records" : "30 s rescans"); + alignas(DWORD) static unsigned char buffer[64 * 1024]; + OVERLAPPED overlapped{}; + overlapped.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); + bool pending = false; + bool scan = true; // first pass: a manifest published before the watch started + for (;;) { + // File names only: the stand-in itself writes req_* files here; a manifest is published by rename + // or creation, both name changes, and the record names the file, so no query is needed. The read + // is armed before any scan, so a file named during the scan is still recorded. + if (!pending && handle != INVALID_HANDLE_VALUE && overlapped.hEvent) { + ResetEvent(overlapped.hEvent); + pending = ReadDirectoryChangesW(handle, buffer, sizeof(buffer), FALSE, FILE_NOTIFY_CHANGE_FILE_NAME, nullptr, + &overlapped, nullptr) != FALSE; + } + if (scan) manifest_check(dir, nullptr); + scan = true; + // 30 s rescan: a manifest published between a failed open and its registration has no record. + if (!pending) { + Sleep(30000); + continue; + } + if (WaitForSingleObject(overlapped.hEvent, 30000) != WAIT_OBJECT_0) continue; + pending = false; + DWORD bytes = 0; + if (!GetOverlappedResult(handle, &overlapped, &bytes, FALSE) || bytes == 0) continue; // overflow: names lost + scan = false; + for (DWORD at = 0;;) { + const auto* record = reinterpret_cast(buffer + at); + if (record->Action == FILE_ACTION_ADDED || record->Action == FILE_ACTION_RENAMED_NEW_NAME) { + wchar_t name[MAX_PATH]; + const std::size_t chars = record->FileNameLength / sizeof(wchar_t); + if (chars < MAX_PATH) { + std::wmemcpy(name, record->FileName, chars); + name[chars] = 0; + if (chars > 4 && _wcsicmp(name + chars - 4, L".txt") == 0) manifest_check(dir, name); + } + } + if (!record->NextEntryOffset) break; + at += record->NextEntryOffset; + } + } +} + +void watch_missing_manifest(Translation& tr, const std::string& request) +{ + static const HANDLE thread = CreateThread(nullptr, 0, manifest_watcher, nullptr, 0, nullptr); + (void)thread; + AcquireSRWLockExclusive(&manifest_watch().lock); + manifest_watch().missing.emplace_back(&tr, request); + manifest_seen()[&tr] = 0; + ReleaseSRWLockExclusive(&manifest_watch().lock); +} + +// draw_lock held: true when the translation's absent manifest should be read again now. +bool manifest_retry_due(Translation& tr) +{ + if (!tr.retry_manifest_at) return false; + if (manifest_poll()) return GetTickCount64() >= tr.retry_manifest_at; + AcquireSRWLockShared(&manifest_watch().lock); + const auto found = manifest_seen().find(&tr); + const bool seen = found != manifest_seen().end() && InterlockedExchange(&found->second, 0) != 0; + ReleaseSRWLockShared(&manifest_watch().lock); + return seen; +} + void load_translation(Translation& tr, const std::string& rtv_request = {}) { tr.state = 2; @@ -148,6 +1020,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) log("x2w-draw no translation for pipeline %016llx", tr.key); } tr.retry_manifest_at = GetTickCount64() + 1000; + if (!manifest_poll()) watch_missing_manifest(tr, rtv_request); return; } // The writer publishes this marker last. A malformed published result stays rejected. @@ -173,9 +1046,6 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) // so it must not draw a translation whose stores it would silently skip (#1723). log("x2w-draw unsupported manifest version for %016llx", tr.key); return; - } else if (line.compare(0, 4, "uav ") == 0) { - log("x2w-draw unsupported uav line for %016llx", tr.key); - return; } else if (std::sscanf(line.c_str(), "udsrc %d %15s %d %d", &i, source, &x, &y) >= 2) { Translation::Ud ud{-1, x, y}; if (!std::strcmp(source, "rect")) ud.kind = Translation::rect; @@ -186,12 +1056,41 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) else if (!std::strcmp(source, "d16unorm16") && x >= 0 && x < 32) ud.kind = Translation::d16_unorm16; else if (!std::strcmp(source, "descword3")) ud.kind = Translation::desc_word3; else if (!std::strcmp(source, "mrtbits") && !rtv_request.empty()) ud.kind = Translation::mrt_bits; + else if (!std::strcmp(source, "bufword3")) ud.kind = Translation::buf_word3; // word 3 of srv a's descriptor + else if (!std::strcmp(source, "uavword3")) ud.kind = Translation::uav_word3; // word 3 of uav a's descriptor + else if (!std::strcmp(source, "uavstride") && x >= 0 && x < 8) ud.kind = Translation::uav_stride; + else if (!std::strcmp(source, "uavbase") && x >= 0 && x < 8) { + ud.kind = Translation::uav_base; + tr.uav_base_wanted |= 1u << x; + } else if (!std::strcmp(source, "descword")) { + static const bool descword_on = x2w_local::env_on("X2W_MESH_DESCWORD"); + if (!descword_on || x < 0 || x >= 16 || y < 0) { + static LONG logged; + if (first_calls(logged, 8)) + log("x2w-draw %016llx: `udsrc %d descword %d %d` %s: translation refused", tr.key, i, x, y, + descword_on ? "out of range" : "needs X2W_MESH_DESCWORD=1"); + return; + } + ud.kind = Translation::desc_word; + } if (static_cast(i) == tr.uds.size() && ud.kind >= 0) tr.uds.push_back(ud); + } else if (std::sscanf(line.c_str(), "uav %d %15s %15s %d %d", &i, kind, source, &x, &y) >= 4) { + const int uav_kind = !std::strcmp(kind, "buf") ? 0 : !std::strcmp(kind, "tex2d") && !std::strcmp(source, "table") ? 1 : -1; + const int uav_source = !std::strcmp(source, "table") ? 0 : !std::strcmp(source, "root") ? 2 : -1; + if (uav_kind < 0 || uav_source < 0 || static_cast(i) != tr.uavs.size() || tr.uavs.size() >= 8) { + log("x2w-draw-rt %016llx: unsupported manifest line \"%s\"", tr.key, line.c_str()); + return; + } + tr.uavs.push_back({uav_kind, uav_source, x, y}); } else if (std::sscanf(line.c_str(), "srv %d %15s %15s %d %d", &i, kind, source, &x, &y) >= 4) { const int texture_kind = !std::strcmp(kind, "tex2d") ? 1 : !std::strcmp(kind, "tex2da") ? 2 : !std::strcmp(kind, "tex3d") ? 3 : !std::strcmp(kind, "tex1d") ? 4 : 0; Translation::Srv srv{texture_kind, !std::strcmp(source, "vb") ? 1 : !std::strcmp(source, "root") ? 2 : 0, x, y}; if (static_cast(i) == tr.srvs.size()) tr.srvs.push_back(srv); + } else if (line == "heap 1") { + tr.heap = true; + } else if (line == "heapwords 1") { + tr.heapwords = true; } else if (line.compare(0, 6, "wmask ") == 0) { if (!tr.write_masks.read_manifest_line(line)) { log("x2w-draw invalid write mask manifest line for %016llx: %s", tr.key, line.c_str()); @@ -217,36 +1116,61 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) log("x2w-draw RTV manifest missing for %016llx", tr.key); return; } - if (tr.uds.empty() || tr.uds.size() > 32 || tr.srvs.size() > 32 || !tr.d16_srvs.valid_for_srvs(tr.srvs)) return; + if (tr.uds.empty() || tr.uds.size() > 32 || tr.srvs.size() > draw_srv_limit || !tr.d16_srvs.valid_for_srvs(tr.srvs)) return; for (const Translation::Ud& ud : tr.uds) { if (ud.kind == Translation::d16_unorm16 && (ud.a < 0 || static_cast(ud.a) >= tr.srvs.size() || !tr.d16_srvs.requires_exact(static_cast(ud.a)))) return; } - if (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs))) return; - if (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps))) return; - const HRESULT hr = x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.size()), - static_cast(tr.srvs.size()), tr.samplers, &tr.root); + if (tr.heapwords && !tr.heap) return log("x2w-vdesc %016llx: `heapwords 1` without `heap 1`: translation refused", tr.key); + static const bool rt_off = x2w_local::env_on("X2W_DRAW_RT_OFF"); + if (rt_off && (!tr.uavs.empty() || tr.heap || std::any_of(tr.uds.begin(), tr.uds.end(), [](const Translation::Ud& ud) { + return ud.kind == Translation::buf_word3 || ud.kind == Translation::uav_word3 || ud.kind == Translation::uav_base || + ud.kind == Translation::uav_stride; }))) { + log("x2w-draw-rt %016llx: not used (X2W_DRAW_RT_OFF)", tr.key); + return; + } + const int mesh_stage = load_mesh_stages(tr, manifest); + if (mesh_stage < 0 || (!mesh_stage && (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs))))) return; + if (!mesh_stage && (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps)))) return; + const HRESULT hr = create_draw_root(tr); if (FAILED(hr)) { log("x2w-draw root signature for %016llx failed 0x%08lx", tr.key, static_cast(hr)); return; } tr.state = 1; + if (std::any_of(tr.uds.begin(), tr.uds.end(), [](const Translation::Ud& ud) { return ud.kind == Translation::buf_word3; })) + InterlockedIncrement(&rt_loaded_word3); + if (!tr.uavs.empty()) { + InterlockedIncrement(&rt_loaded_uav); + log("x2w-draw-rt pipeline %016llx: %zu uavs in root parameter %u", tr.key, tr.uavs.size(), tr.uav_parameter); + } + if (tr.heap) { + InterlockedIncrement(&rt_loaded_heap); + log("x2w-draw-rt pipeline %016llx: heap 1 in root parameters %u..%u", tr.key, tr.heap_parameter, tr.heap_parameter + 2); + if (tr.heapwords) log("x2w-vdesc pipeline %016llx: heapwords 1, vdesc in root parameter %u", tr.key, tr.vdesc_parameter); + } if (previously_missing) InterlockedDecrement(&translation_missing); InterlockedIncrement(&translation_ready); log("x2w-draw pipeline %016llx translated: %zu entry values, %zu resources, %zu static samplers, sampler_heap=%u", tr.key, tr.uds.size(), tr.srvs.size(), tr.samplers.statics.size(), tr.samplers.heap ? 1u : 0u); } -// draw_lock held. Both pipeline forms use the same request writer and shader cache. -Translation* cached_translation(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes, - const std::vector& root_blob, const std::string& layout = {}) +u64 pipeline_key(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes, + const std::vector& root_blob) { // Keep pre-fix desktop bytecode and manifests out of this ABI's cache. // tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL. - constexpr char revision[] = "x2w-startup-shader-17"; + constexpr char revision[] = "x2w-startup-shader-3"; const u64 seed = fnv_bytes(revision, sizeof(revision) - 1); - u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); + return fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); +} + +// draw_lock held. Both pipeline forms use the same request writer and shader cache. +Translation* cached_translation(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes, + const std::vector& root_blob, const std::string& layout = {}) +{ + u64 key = pipeline_key(a, a_bytes, b, b_bytes, root_blob); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. if (!layout.empty()) key = fnv_bytes(layout.data(), layout.size(), key); auto& entry = translation_by_key()[key]; @@ -364,7 +1288,7 @@ void publish_compute_request(const void* desc) std::vector fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-17cs"; // tools/startup/gfx2hlsl.py compute_key + constexpr char compute_revision[] = "x2w-startup-shader-3cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); @@ -427,7 +1351,7 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo return copy_title_bytes(out.data(), pointer, out.size()); }; if (!copy_stage(13, true, mesh) || !copy_stage(5, false, pixel)) return; - constexpr char revision[] = "x2w-startup-mesh-57-2"; + constexpr char revision[] = "x2w-startup-mesh-57-1"; const u64 key = fnv_part(root_blob, fnv_part(pixel, fnv_part(mesh, fnv_bytes(revision, sizeof(revision) - 1)))); static SRWLOCK request_lock = SRWLOCK_INIT; static std::unordered_set written; @@ -541,8 +1465,9 @@ Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3 if (bounds) return nullptr; } } else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT) { + static const bool upstream_layout = x2w_local::env_on("X2W_UPSTREAM_STREAM_LAYOUT"); // Unreadable: translate without it; gfx2hlsl refuses a vertex shader that needs it. - if (!stream_input_layout(stream + at, layout)) { + if (upstream_layout && !stream_input_layout(stream + at, layout)) { layout.clear(); log("x2w-draw stream input layout unreadable; requesting the translation without it"); } @@ -576,13 +1501,61 @@ Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3 if (found != root_blobs().end()) root_blob = found->second; ReleaseSRWLockShared(¬e_lock); if (root_blob.empty()) return nullptr; - AcquireSRWLockExclusive(&draw_lock); + lock_draw(100000 + __LINE__); auto* result = cached_translation(stages[0].pShaderBytecode, stages[0].BytecodeLength, stages[1].pShaderBytecode, stages[1].BytecodeLength, root_blob, layout); ReleaseSRWLockExclusive(&draw_lock); return result; } +void decode_draw_state(BoundPipeline& bound, Wrapper* pipeline, const PipelineInfo* info) +{ + using namespace x2w_pipeline_state; + Words words; + if (!info || info->path != 57 || !read_words(info->state_a.data(), info->state_a.size(), words)) return; + bound.has_words = true; + bound.mesh_layout = words.mesh; + bound.ds = decode_depth_stencil(words.depth, words.stencil, words.refmask, words.refmask_bf); + bound.rs = decode_rasterizer(words.mode, words.clip, words.bias_clamp, words.bias_scale, words.bias_offset, draw_state::switches().flip); + bound.raw_mode = words.mode; + bound.raw_clip = words.clip; + bound.masked_blend = decode_blend(words.blend, words.target_mask, words.shader_mask, true, false); + const D3D12_DEPTH_STENCIL_DESC& d = bound.derived_ds ? bound.patch_ds : bound.ds.desc; + const bool ds_known = bound.derived_ds || bound.ds.ok; + draw_state::add(draw_state::decoded); + if (words.mesh) draw_state::add(draw_state::decoded_mesh); + if (ds_known) + draw_state::add(!d.DepthEnable ? draw_state::class_depth_off : d.DepthWriteMask ? draw_state::class_depth_write : draw_state::class_depth_read); + if (ds_known && d.StencilEnable) draw_state::add(draw_state::class_stencil); + if (bound.rs.ok && bound.rs.desc.CullMode != D3D12_CULL_MODE_NONE) draw_state::add(draw_state::class_cull); + if (bound.masked_blend.ok && bound.masked_blend.desc.RenderTarget[0].BlendEnable) draw_state::add(draw_state::class_blend); + if (bound.masked_blend.masked_targets) draw_state::add(draw_state::class_masked); + if (bound.masked_blend.dual_source) draw_state::add(draw_state::class_dual); + if (!bound.ds.ok) draw_state::add(draw_state::refused_depth); + if (!bound.rs.ok) draw_state::add(draw_state::refused_raster); + if (!bound.masked_blend.ok) draw_state::add(draw_state::refused_blend); + if (bound.ds.depth_bounds) draw_state::add(draw_state::depth_bounds_ignored); + if (bound.ds.masks_differ) draw_state::add(draw_state::stencil_masks_differ); + if (bound.rs.clip_split) draw_state::add(draw_state::clip_split); + if (bound.rs.bias_rounded) draw_state::add(draw_state::bias_rounded); + static LONG logged_state; + if (first_calls(logged_state, 16)) { + const auto& r = bound.rs.desc; + char derived_rs[96] = ""; + if (bound.derived_rs) // the slot 55 rasterizer part replaces the register state under _CULL + std::snprintf(derived_rs, sizeof(derived_rs), " (derived part wins: fill %d cull %d ccw %d clip %d)", bound.patch_rs.FillMode, + bound.patch_rs.CullMode, bound.patch_rs.FrontCounterClockwise, bound.patch_rs.DepthClipEnable); + log("x2w-draw-state pipeline %p%s: DB_DEPTH_CONTROL %08x STENCIL %08x REFMASK %08x/%08x -> %s depth %d write %d func %d " + "stencil %d%s; MODE %08x CLIP %08x bias %g/%g/%g -> %s cull %d ccw %d bias %d/%g/%g clip %d%s; masks %08x & %08x -> " + "rt0 0x%x%s%s", static_cast(pipeline), words.mesh ? " (mesh layout)" : "", words.depth, words.stencil, words.refmask, + words.refmask_bf, bound.ds.ok ? "ok" : bound.ds.reason, d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, + bound.derived_ds ? " (derived part)" : "", words.mode, words.clip, words.bias_clamp, words.bias_scale, words.bias_offset, + bound.rs.ok ? "ok" : bound.rs.reason, r.CullMode, r.FrontCounterClockwise, r.DepthBias, r.DepthBiasClamp, r.SlopeScaledDepthBias, + r.DepthClipEnable, derived_rs, words.target_mask, words.shader_mask, bound.masked_blend.desc.RenderTarget[0].RenderTargetWriteMask, + bound.masked_blend.dual_source ? " dual-source" : "", bound.masked_blend.ok ? "" : " (blend refused)"); + } +} + // draw_lock held. BoundPipeline* translation_for(Wrapper* pipeline) { @@ -604,8 +1577,20 @@ BoundPipeline* translation_for(Wrapper* pipeline) from = "derived blend patch"; bound->has_blend = true; } + using namespace x2w_pipeline_state; + const unsigned char* records = info->desc.data(); + const std::size_t record_bytes = info->desc.size(); + if (!bound->derived_ds && last_part(records, record_bytes, part_depth_stencil) != SIZE_MAX) { + bound->derived_ds = derived_depth_stencil(records, record_bytes, bound->patch_ds); + draw_state::add(bound->derived_ds ? draw_state::derived_ds : draw_state::derived_invalid); + } + if (!bound->derived_rs && last_part(records, record_bytes, part_rasterizer) != SIZE_MAX) { + bound->derived_rs = derived_rasterizer(records, record_bytes, bound->patch_rs); + draw_state::add(bound->derived_rs ? draw_state::derived_rs : draw_state::derived_invalid); + } info = pipeline_info(info->base); } + bound->blend_overridden = bound->has_blend || (info && info->has_stream_blend); if (!bound->has_blend && info && info->has_stream_blend) { from = "stream blend subobject"; bound->blend = info->stream_blend; @@ -617,6 +1602,7 @@ BoundPipeline* translation_for(Wrapper* pipeline) } else if (!bound->has_blend && info && find_blend(info->state_a, &bound->blend, &where)) from = "state block A"; else if (!bound->has_blend && info && find_blend(info->state_b, &bound->blend, &where)) from = "state block B"; bound->has_blend = from[0] != 'n'; + decode_draw_state(*bound, pipeline, info); static LONG logged; if (first_calls(logged, 24)) { const auto& t = bound->blend.RenderTarget[0]; @@ -760,8 +1746,9 @@ bool needs_rtv_variant(DXGI_FORMAT format) Translation* translation_for_targets(Translation* base, const Pass& pass) { if (!base) return nullptr; - if (std::none_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant)) { - if (base->retry_manifest_at && GetTickCount64() >= base->retry_manifest_at) + const bool no_pixel_output = base->state == 1 && base->ms && !base->ps; + if (no_pixel_output || std::none_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant)) { + if (manifest_retry_due(*base)) load_translation(*base); return base; } @@ -778,20 +1765,273 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) publish_shader_request(key, L".rtv", request.data(), request.size()); log("x2w-draw no RTV translation for %016llx (%s)", key, request.c_str()); } - } else if (entry->retry_manifest_at && GetTickCount64() >= entry->retry_manifest_at) { + } else if (manifest_retry_due(*entry)) { load_translation(*entry, request); } return entry; } +bool apply_draw_state(const BoundPipeline& bound, const Pass& pass, D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, + const x2w_pipeline_state::Switches& s) +{ + using namespace x2w_pipeline_state; + const DXGI_FORMAT dsv_format = desc.DSVFormat; + bool changed = false; + if (s.blend && bound.has_words && !bound.blend_overridden && bound.masked_blend.ok) { + desc.BlendState = bound.masked_blend.desc; + if (bound.masked_blend.dual_source) { + // D3D12 blends two colours only into target 0; the words are the same for every target then. + desc.BlendState.IndependentBlendEnable = FALSE; + if (pass.target_count > 1) draw_state::add(draw_state::dual_multi_target); + } + changed = true; + } + if (s.depth && !bound.has_depth_stencil && (bound.derived_ds || (bound.has_words && bound.ds.ok))) { + D3D12_DEPTH_STENCIL_DESC d = bound.derived_ds ? bound.patch_ds : bound.ds.desc; + // A depth target no forwarded slot 51 clear has initialised holds undefined depth: no test against it + // (unless X2W_DRAW_STATE_DEPTH_UNCLEARED=1); the draw keeps depth and stencil off, as before. + const bool target = dsv_format != DXGI_FORMAT_UNKNOWN; + const bool uncleared = target && !s.uncleared && !depth_target_cleared(pass.dsv_resource); + if (uncleared && (d.DepthEnable || d.StencilEnable)) draw_state::add(draw_state::draws_depth_uncleared); + const unsigned adjusted = adjust_for_target(d, target && !uncleared, format_has_stencil(dsv_format), pass.dsv_read_only); + if ((adjusted & adjust_no_target) && !uncleared) draw_state::add(draw_state::draws_depth_no_target); + if (adjusted & adjust_no_stencil) draw_state::add(draw_state::draws_stencil_no_plane); + if (adjusted & adjust_read_only) draw_state::add(draw_state::draws_read_only); + desc.DepthStencilState = d; + changed = true; + } + if (s.cull && (bound.derived_rs || (bound.has_words && bound.rs.ok))) { + D3D12_RASTERIZER_DESC r = bound.derived_rs ? bound.patch_rs : bound.rs.desc; + if (bound.derived_rs && s.flip) r.FrontCounterClockwise = !r.FrontCounterClockwise; + if (r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF) { + r.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; // tier not checked + draw_state::add(draw_state::conservative_dropped); + } + r.MultisampleEnable = FALSE; // single-sample targets only (desc.SampleDesc.Count = 1) + r.ForcedSampleCount = 0; + // A rectangle list is drawn as two triangles per rectangle; the console rasterizes it as a + // rectangle, which is taken as never culled (assumed). + if (pass.topology == 0x11 && r.CullMode != D3D12_CULL_MODE_NONE) { + r.CullMode = D3D12_CULL_MODE_NONE; + draw_state::add(draw_state::draws_rect_cull_off); + } + desc.RasterizerState = r; + changed = true; + } else if (s.depthclip && (bound.derived_rs || (bound.has_words && bound.rs.ok))) { + const BOOL clip = (bound.derived_rs ? bound.patch_rs : bound.rs.desc).DepthClipEnable ? TRUE : FALSE; + if (desc.RasterizerState.DepthClipEnable != clip) { + desc.RasterizerState.DepthClipEnable = clip; + changed = true; + } + } + return changed; +} + +HRESULT draw_state_fallback(u64 translation, HRESULT first, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& decoded, + const D3D12_GRAPHICS_PIPELINE_STATE_DESC& fallback, ID3D12PipelineState*& pipeline) +{ + if (SUCCEEDED(first)) { + draw_state::add(draw_state::pso_new); + return first; + } + pipeline = nullptr; + const HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&fallback, IID_PPV_ARGS(&pipeline)); + draw_state::add(SUCCEEDED(hr) ? draw_state::pso_failed_fallback : draw_state::pso_failed_both); + static LONG logged_failure; + if (first_calls(logged_failure, 16)) { + const auto& b = decoded.BlendState.RenderTarget[0]; + const auto& d = decoded.DepthStencilState; + const auto& r = decoded.RasterizerState; + log("x2w-draw-state decoded state refused for %016llx (0x%08lx): blend rt0 %d/%d/%d mask 0x%x independent %d, depth %d write %d " + "func %d stencil %d, cull %d ccw %d bias %d/%g/%g clip %d; old state -> 0x%08lx", translation, static_cast(first), + b.BlendEnable, b.SrcBlend, b.DestBlend, b.RenderTargetWriteMask, decoded.BlendState.IndependentBlendEnable, d.DepthEnable, + d.DepthWriteMask, d.DepthFunc, d.StencilEnable, r.CullMode, r.FrontCounterClockwise, r.DepthBias, r.DepthBiasClamp, + r.SlopeScaledDepthBias, r.DepthClipEnable, static_cast(hr)); + } + return hr; +} + +struct PsoBuild { + BoundPipeline* bound = nullptr; // never freed (translation_by_pipeline keeps them) + u64 key = 0; // pipeline_for's key in bound->pipelines + u64 translation = 0; // for the log + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; // points at the translation's blobs and root signature, which are never freed + bool has_fallback = false; + D3D12_GRAPHICS_PIPELINE_STATE_DESC fallback{}; +}; +struct PsoSlot { + int state = 0; // 1 compiling, 2 done, 3 queued for an X2W_DRAW_ASYNC worker + ID3D12PipelineState* pipeline = nullptr; +}; +SRWLOCK pso_build_lock = SRWLOCK_INIT; // inside draw_lock when both are held +CONDITION_VARIABLE pso_built = CONDITION_VARIABLE_INIT; +// Slots are never erased: a thread that missed before another installed the pipeline finds it done. +std::map, PsoSlot>& pso_slots() +{ + static std::map, PsoSlot> m; + return m; +} + +void test_hold(const char* what, u64 key) +{ + wchar_t hold[128]; + const DWORD n = GetEnvironmentVariableW(L"X2W_CX_TEST_HOLD_EVENT", hold, 128); + if (!n || n >= 128) return; + if (const HANDLE event = OpenEventW(SYNCHRONIZE, FALSE, hold)) { + const DWORD waited = WaitForSingleObject(event, 20000); + CloseHandle(event); + log("%s %016llx: load held by X2W_CX_TEST_HOLD_EVENT (%s)", what, key, waited == WAIT_OBJECT_0 ? "released" : "timed out"); + } +} + +bool draw_async() +{ + static const bool on = !x2w_local::env_on("X2W_DRAW_PSO_LOCKED") && + (x2w_local::env_on("X2W_DRAW_ASYNC") || (x2w_local::env_on("X2W_CX_ASYNC") && !x2w_local::env_on("X2W_DRAW_ASYNC_OFF"))); + return on; +} +struct DrawAsync { + LONG skipped = 0, since_report = 0; +}; +std::unordered_map& draw_async_keys() // pso_build_lock; by translation key +{ + static std::unordered_map m; + return m; +} // The depth format a translated draw uses: the pass's own view, else the one the pipeline was created with. inline DXGI_FORMAT pass_dsv_format(const BoundPipeline& bound, const Pass& pass) { return pass.dsv_format != DXGI_FORMAT_UNKNOWN ? pass.dsv_format : bound.dsv_format; } -ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const Pass& pass, bool indexed_rect) +std::deque& pso_queue() // pso_build_lock +{ + static std::deque q; + return q; +} +CONDITION_VARIABLE pso_wanted = CONDITION_VARIABLE_INIT; + +void compile_pso(const PsoBuild& build, PsoSlot& slot); +DWORD WINAPI pso_thread(void*) { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + for (;;) { + AcquireSRWLockExclusive(&pso_build_lock); + while (pso_queue().empty()) SleepConditionVariableSRW(&pso_wanted, &pso_build_lock, INFINITE, 0); + const PsoBuild build = pso_queue().front(); + pso_queue().pop_front(); + PsoSlot& slot = pso_slots()[{build.bound, build.key}]; + const bool mine = slot.state == 3; // else another thread claimed it + if (mine) slot.state = 1; + ReleaseSRWLockExclusive(&pso_build_lock); + if (mine) compile_pso(build, slot); + } +} +// draw_translated without draw_lock: queues `build` unless it is queued, compiling or built; counts the skip. +void queue_pso_build(const PsoBuild& build) +{ + static const bool started = [] { + for (int i = 0; i < 2; ++i) + if (const HANDLE t = CreateThread(nullptr, 0, pso_thread, nullptr, 0, nullptr)) CloseHandle(t); + log("x2w-draw X2W_DRAW_ASYNC: 2 pipeline build threads; a draw whose desktop pipeline is not built yet is skipped"); + return true; + }(); + (void)started; + AcquireSRWLockExclusive(&pso_build_lock); + PsoSlot& slot = pso_slots()[{build.bound, build.key}]; + const bool queue = slot.state == 0; + if (queue) { + slot.state = 3; + pso_queue().push_back(build); + } + DrawAsync& a = draw_async_keys()[build.translation]; + const bool first = !a.skipped; + ++a.skipped, ++a.since_report; + ReleaseSRWLockExclusive(&pso_build_lock); + if (queue) WakeConditionVariable(&pso_wanted); + static LONG logged; + if (first && first_calls(logged, 32)) + log("x2w-draw %016llx: desktop pipeline not built yet, draw skipped and the build queued (X2W_DRAW_ASYNC)", build.translation); +} +// Heartbeat: draws skipped while their pipeline compiled, since the last report, per translation key. +void report_draw_async() +{ + if (!draw_async()) return; + std::vector> keys; + LONG total = 0, all_time = 0; + AcquireSRWLockExclusive(&pso_build_lock); + for (auto& entry : draw_async_keys()) { + all_time += entry.second.skipped; + if (!entry.second.since_report) continue; + keys.push_back({entry.first, entry.second.since_report}); + total += entry.second.since_report; + entry.second.since_report = 0; + } + const std::size_t waiting = pso_queue().size(); + ReleaseSRWLockExclusive(&pso_build_lock); + if (!total) return; + std::sort(keys.begin(), keys.end(), [](const auto& a, const auto& b) { return a.second > b.second; }); + char line[1400]; + int n = std::snprintf(line, sizeof(line), "x2w-draw draws skipped while compiling since the last report (X2W_DRAW_ASYNC): %ld over %zu keys " + "(%ld this run; %zu builds waiting):", total, keys.size(), all_time, waiting); + for (const auto& k : keys) { + if (n > static_cast(sizeof(line)) - 40) { + n += std::snprintf(line + n, sizeof(line) - n, " ..."); + break; + } + n += std::snprintf(line + n, sizeof(line) - n, " %016llx=%ld", k.first, k.second); + } + log("%s", line); +} + +void build_pipeline(const PsoBuild& build) +{ + AcquireSRWLockExclusive(&pso_build_lock); + PsoSlot& slot = pso_slots()[{build.bound, build.key}]; // std::map references stay valid + while (slot.state == 1) SleepConditionVariableSRW(&pso_built, &pso_build_lock, INFINITE, 0); + if (slot.state == 2) { + ReleaseSRWLockExclusive(&pso_build_lock); + return; + } + slot.state = 1; // from 0, or 3 (queued for a worker: claimed here) + ReleaseSRWLockExclusive(&pso_build_lock); + compile_pso(build, slot); +} +void compile_pso(const PsoBuild& build, PsoSlot& slot) +{ + test_hold("x2w-draw", build.translation); + LARGE_INTEGER start, end, frequency; + QueryPerformanceCounter(&start); + ID3D12PipelineState* pipeline = nullptr; + HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&build.desc, IID_PPV_ARGS(&pipeline)); + if (build.has_fallback) hr = draw_state_fallback(build.translation, hr, build.desc, build.fallback, pipeline); + QueryPerformanceCounter(&end); + QueryPerformanceFrequency(&frequency); + log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d%s), compiled in %lld ms outside draw_lock", + build.translation, build.desc.NumRenderTargets, build.desc.NumRenderTargets ? build.desc.RTVFormats[0] : 0, + static_cast(hr), static_cast(build.desc.DSVFormat), build.desc.DepthStencilState.DepthEnable ? 1 : 0, + build.has_fallback ? ", decoded state" : "", static_cast((end.QuadPart - start.QuadPart) * 1000 / frequency.QuadPart)); + check_device("translated CreateGraphicsPipelineState", 0); + AcquireSRWLockExclusive(&pso_build_lock); + slot.pipeline = pipeline; + slot.state = 2; + LONG skipped = 0; + if (draw_async()) + if (const auto found = draw_async_keys().find(build.translation); found != draw_async_keys().end()) skipped = found->second.skipped; + ReleaseSRWLockExclusive(&pso_build_lock); + WakeAllConditionVariable(&pso_built); + if (skipped) log("x2w-draw %016llx ready (X2W_DRAW_ASYNC); %ld draws skipped while compiling", build.translation, skipped); +} + +bool pipeline_desc(const BoundPipeline& bound, Translation& tr, const Pass& pass, DXGI_FORMAT dsv_format, + D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, bool indexed_rect = false); + +// draw_lock held. With `deferred`, a pipeline not built yet is described there and nullptr is returned. +// indexed_rect (upstream #2259): the draw is an indexed rectangle list, expanded by a geometry stage. +ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const Pass& pass, PsoBuild* deferred = nullptr, + bool indexed_rect = false) +{ + if (tr.ms) return mesh_pso_for(tr); const DXGI_FORMAT dsv_format = pass_dsv_format(bound, pass); u64 key = pass.target_count; for (UINT i = 0; i < pass.target_count; ++i) key = key * 131 + static_cast(pass.target_formats[i]); @@ -801,9 +2041,65 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P if (use_depth_stencil) key = fnv_bytes(&bound.depth_stencil, sizeof(bound.depth_stencil), key); if (bound.has_rasterizer) key = fnv_bytes(&bound.rasterizer, sizeof(bound.rasterizer), key); key = fnv_bytes(&indexed_rect, sizeof(indexed_rect), key); + D3D12_GRAPHICS_PIPELINE_STATE_DESC decoded{}; + bool changed = false; + const auto& state_switches = draw_state::switches(); + if (state_switches.depth || state_switches.cull || state_switches.blend || state_switches.depthclip) { + if (!pipeline_desc(bound, tr, pass, dsv_format, decoded, indexed_rect)) { + bound.pipelines[key] = nullptr; + return nullptr; + } + changed = apply_draw_state(bound, pass, decoded, state_switches); + if (changed) { + key = fnv_bytes(&decoded.BlendState, sizeof(decoded.BlendState), key); + key = fnv_bytes(&decoded.DepthStencilState, sizeof(decoded.DepthStencilState), key); + key = fnv_bytes(&decoded.RasterizerState, sizeof(decoded.RasterizerState), key); + } + } const auto found = bound.pipelines.find(key); if (found != bound.pipelines.end()) return found->second; + { + AcquireSRWLockShared(&pso_build_lock); + const auto built = pso_slots().find({&bound, key}); + const bool done = built != pso_slots().end() && built->second.state == 2; + ID3D12PipelineState* const ready = done ? built->second.pipeline : nullptr; + ReleaseSRWLockShared(&pso_build_lock); + if (done) { + bound.pipelines[key] = ready; + return ready; + } + } D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + if (!pipeline_desc(bound, tr, pass, dsv_format, desc, indexed_rect)) { + bound.pipelines[key] = nullptr; + return nullptr; + } + if (deferred) { + deferred->bound = &bound; + deferred->key = key; + deferred->translation = tr.key; + deferred->desc = changed ? decoded : desc; + deferred->has_fallback = changed; + if (changed) deferred->fallback = desc; + return nullptr; + } + ID3D12PipelineState* pipeline = nullptr; + HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(changed ? &decoded : &desc, IID_PPV_ARGS(&pipeline)); + if (changed) hr = draw_state_fallback(tr.key, hr, decoded, desc, pipeline); + log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d%s)", tr.key, + pass.target_count, pass.target_count ? pass.target_formats[0] : 0, static_cast(hr), + static_cast(dsv_format), (changed ? decoded : desc).DepthStencilState.DepthEnable ? 1 : 0, changed ? ", decoded state" : ""); + check_device("translated CreateGraphicsPipelineState", 0); + bound.pipelines[key] = pipeline; + return pipeline; +} + +// The desktop PSO description of a translated (vertex) draw with the state of before: blend found in the +// state block, depth-stencil from a stream PSO, no culling. +bool pipeline_desc(const BoundPipeline& bound, Translation& tr, const Pass& pass, DXGI_FORMAT dsv_format, + D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, bool indexed_rect) +{ + desc = {}; desc.pRootSignature = tr.root; desc.VS = {tr.vs->GetBufferPointer(), tr.vs->GetBufferSize()}; desc.PS = {tr.ps->GetBufferPointer(), tr.ps->GetBufferSize()}; @@ -816,7 +2112,7 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P log("x2w-draw %016llx: indexed rectangle geometry unavailable (0x%08lx) %s", tr.key, static_cast(hr), errors ? static_cast(errors->GetBufferPointer()) : ""); } - if (!tr.indexed_rect_geometry) return nullptr; + if (!tr.indexed_rect_geometry) return false; desc.GS = {tr.indexed_rect_geometry->GetBufferPointer(), tr.indexed_rect_geometry->GetBufferSize()}; } // Blend state as found in the pipeline's state block, else opaque. Depth-stencil state and @@ -826,12 +2122,18 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P target = {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}; if (bound.has_blend) desc.BlendState = bound.blend; + static const bool default_blend = x2w_local::env_on("X2W_DRAW_DEFAULT_BLEND"); + if (!bound.has_blend && default_blend) + for (auto& target : desc.BlendState.RenderTarget) + target = {TRUE, FALSE, D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, + D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; // Channels the translated exports leave unwritten stay out of the write mask (#1674). if (!x2w_startup::apply_export_write_masks(desc.BlendState, tr.write_masks, pass.target_count)) { log("x2w-draw export write masks incompatible with shared logic op for %016llx", tr.key); - bound.pipelines[key] = nullptr; - return nullptr; + return false; } + // A state decoded from registers needs a depth view to act on; with none bound the pass keeps the desktop default. + const bool use_depth_stencil = bound.has_depth_stencil && (!bound.depth_from_registers || dsv_format != DXGI_FORMAT_UNKNOWN); if (use_depth_stencil) desc.DepthStencilState = bound.depth_stencil; desc.SampleMask = ~0u; if (bound.has_rasterizer) { @@ -846,15 +2148,7 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P for (UINT i = 0; i < pass.target_count; ++i) desc.RTVFormats[i] = pass.target_formats[i]; desc.DSVFormat = dsv_format; desc.SampleDesc.Count = 1; - ID3D12PipelineState* pipeline = nullptr; - X2W_ZONE("desktop pipeline creation"); - const HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); - log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d)", tr.key, - pass.target_count, pass.target_count ? pass.target_formats[0] : 0, static_cast(hr), - static_cast(dsv_format), desc.DepthStencilState.DepthEnable ? 1 : 0); - check_device("translated CreateGraphicsPipelineState", 0); - bound.pipelines[key] = pipeline; - return pipeline; + return true; } // Private shader-visible heap for the translated draws' tables, used as a ring. @@ -870,7 +2164,7 @@ bool ensure_draw_heap(Wrapper* device) // startup render device. A list from another device cannot use this heap. if (!device || device != the_device) return false; if (draw_heap) return device == draw_heap_device; - const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, draw_heap_size, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, draw_heap_size + 8 + 8 * 90000, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; if (FAILED(device_of(the_device)->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&draw_heap)))) return false; draw_heap_device = device; draw_heap_increment = device_of(the_device)->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); @@ -889,7 +2183,7 @@ std::vector submitted_draw_sampler_heaps; void discard_draw_sampler_heaps(ID3D12CommandList* list) { - AcquireSRWLockExclusive(&draw_lock); + lock_draw(100000 + __LINE__); recorded_draw_sampler_heaps.erase(list); ReleaseSRWLockExclusive(&draw_lock); } @@ -1090,46 +2384,199 @@ bool prepare_draw_sampler_heap(Pass& pass, ID3D12GraphicsCommandList* list, bool struct FrameCopy { u64 address = 0; u64 offset = 0; - std::vector content; + ID3D12Resource* buffer = nullptr; + RingTag tag; + std::shared_ptr> content; }; std::unordered_map& frame_copies() { static std::unordered_map m; return m; } LONG frame_copies_frame = -1; +enum { srvc_compared, srvc_copied, srvc_in_place, srvc_kinds }; +volatile LONG64 srvc_bytes[4][srvc_kinds], srvc_calls[4][srvc_kinds]; +// Over the threshold but copied as before: [class][0] no single desktop window (desktop_range), [1] not 16-aligned. +volatile LONG64 srvc_in_place_missed[4][2]; +thread_local int frame_copy_class; +void srvc_note(int cls, int kind, std::size_t bytes) +{ + InterlockedAdd64(&srvc_bytes[cls][kind], static_cast(bytes)); + InterlockedIncrement64(&srvc_calls[cls][kind]); +} +// X2W_DRAW_SRV_IN_PLACE= (off by default; 0 or unset = off). +std::size_t srv_in_place_min() +{ + static const std::size_t min = [] { + char value[24]{}; + const DWORD n = GetEnvironmentVariableA("X2W_DRAW_SRV_IN_PLACE", value, sizeof(value)); + return n && n < sizeof(value) ? static_cast(std::strtoull(value, nullptr, 0)) : std::size_t{0}; + }(); + return min; +} +// Positive byte threshold for comparing direct-draw snapshots outside draw_lock (opt-in). +std::size_t draw_copy_split_min() +{ + static const std::size_t min = [] { + char mode[16]{}; + GetEnvironmentVariableA("X2W_UPLOAD_RING", mode, sizeof(mode)); + if (!std::strcmp(mode, "legacy") || ring_env("X2W_UPLOAD_RING_TEST_NO_REPIN", 0)) return std::size_t{0}; + char value[24]{}; + const DWORD n = GetEnvironmentVariableA("X2W_DRAW_COPY_SPLIT_MIN", value, sizeof(value)); + return n && n < sizeof(value) ? static_cast(std::strtoull(value, nullptr, 0)) : std::size_t{0}; + }(); + return min; +} +bool srv_in_place_all() +{ + static const bool all = x2w_local::env_on("X2W_DRAW_SRV_IN_PLACE_ALL"); + return all; +} +void report_srv_copies() // the 5 s report (d3d12_xs_device.cpp) +{ + static const bool on = srv_in_place_min() || x2w_local::env_on("X2W_DRAW_SRV_STATS"); + if (!on) return; + char text[960]; + int used = 0; + static const char* const names[4] = {"other", "draw", "mesh", "table V#"}; + for (int c = 0; c < 4; ++c) { + LONG64 b[srvc_kinds], n[srvc_kinds]; + for (int k = 0; k < srvc_kinds; ++k) b[k] = InterlockedExchange64(&srvc_bytes[c][k], 0), n[k] = InterlockedExchange64(&srvc_calls[c][k], 0); + const LONG64 no_window = InterlockedExchange64(&srvc_in_place_missed[c][0], 0), unaligned = InterlockedExchange64(&srvc_in_place_missed[c][1], 0); + used += std::snprintf(text + used, sizeof(text) - used, + "%s%s: compared %lld MiB/%lld, copied %lld MiB/%lld, in place %lld MiB/%lld, in-place misses no window %lld unaligned %lld", + c ? "; " : "", names[c], b[srvc_compared] >> 20, n[srvc_compared], b[srvc_copied] >> 20, n[srvc_copied], + b[srvc_in_place] >> 20, n[srvc_in_place], no_window, unaligned); + if (used >= static_cast(sizeof(text))) used = static_cast(sizeof(text)) - 1; + } + log("x2w-draw srv copies since the last report (X2W_DRAW_SRV_IN_PLACE=%zu%s): %s", srv_in_place_min(), + srv_in_place_all() ? ", _ALL: plain draws too" : ", mesh calls only", text); +} + +bool compare_draw_copy(u64 address, std::size_t bytes, u64* offset, ID3D12Resource** buffer) +{ + if (frame_copies_frame != frame_number) return false; + const u64 key = address * 1099511628211ull ^ bytes; + FrameCopy seen; + { + const auto found = frame_copies().find(key); + if (found == frame_copies().end() || found->second.address != address || !found->second.content || + found->second.content->size() != bytes) return false; + seen = found->second; + } + const LONG frame = frame_number; + ReleaseSRWLockExclusive(&draw_lock); + const bool equal = std::memcmp(seen.content->data(), reinterpret_cast(address), bytes) == 0; + lock_draw(100000 + __LINE__); + if (!equal || frame != frame_number) return false; + const auto current = frame_copies().find(key); + if (current == frame_copies().end() || current->second.content != seen.content || !ring_touch(seen.tag)) return false; + srvc_note(frame_copy_class, srvc_compared, bytes); + *offset = seen.offset; + *buffer = seen.buffer; + return true; +} // Callers have just probed that [address, address + bytes) is readable (readable_window), and draw_lock is held. -bool frame_copy(u64 address, std::size_t bytes, u64* offset) +bool frame_copy(u64 address, std::size_t bytes, u64* offset, ID3D12Resource** buffer) +{ + if (frame_copies_frame != frame_number) { + frame_copies().clear(); + frame_copies_frame = frame_number; + } + const u64 key = address * 1099511628211ull ^ bytes; + const auto* title = reinterpret_cast(address); + const auto found = frame_copies().find(key); + const bool known = found != frame_copies().end() && found->second.address == address && found->second.content && + found->second.content->size() == bytes; + if (known && std::memcmp(found->second.content->data(), title, bytes) == 0 && ring_touch(found->second.tag)) { + srvc_note(frame_copy_class, srvc_compared, bytes); + *offset = found->second.offset; + *buffer = found->second.buffer; + return true; + } + u64 fresh = 0; + ID3D12Resource* chunk = nullptr; + RingTag tag; + auto* ring = reserve_upload_ring(bytes, &fresh, &chunk, &tag); + if (!ring) return false; + srvc_note(frame_copy_class, srvc_copied, bytes); + // Cache insertion and snapshot allocation are optional. Fill the ring directly if they fail. + const unsigned char* source = title; + try { + auto content = std::make_shared>(title, title + bytes); + // Use the stored snapshot to fill the ring so the GPU bytes and subsequent comparisons agree. + auto entry = frame_copies().insert_or_assign(key, FrameCopy{address, fresh, chunk, tag, std::move(content)}); + source = entry.first->second.content->data(); + } catch (const std::bad_alloc&) { + // The ring slice is already reserved. The draw can proceed without another CPU allocation. + } + std::memcpy(ring, source, bytes); + x2w_memcut::note_copy(frame_number, bytes); + if (known) { + static LONG refreshed; + if (first_calls(refreshed, 4)) + log("x2w-draw frame copy of 0x%llx (%zu bytes) refreshed: the title changed it since an earlier draw of this frame", address, bytes); + } + *offset = fresh; + *buffer = chunk; + return true; +} +bool frame_copy_unlocked(u64 address, std::size_t bytes, u64* offset, ID3D12Resource** buffer, int lookup_line, int commit_line) { + const u64 key = address * 1099511628211ull ^ bytes; + const auto* title = reinterpret_cast(address); + std::shared_ptr> seen; + u64 seen_offset = 0; + ID3D12Resource* seen_buffer = nullptr; + RingTag seen_tag; + lock_draw(lookup_line); if (frame_copies_frame != frame_number) { frame_copies().clear(); frame_copies_frame = frame_number; } - const u64 key = address * 1099511628211ull ^ bytes; - const auto* title = reinterpret_cast(address); - const auto found = frame_copies().find(key); - const bool known = found != frame_copies().end() && found->second.address == address && found->second.content.size() == bytes; - if (known && std::memcmp(found->second.content.data(), title, bytes) == 0) { - *offset = found->second.offset; + const LONG frame = frame_copies_frame; + if (const auto found = frame_copies().find(key); found != frame_copies().end() && found->second.address == address && + found->second.content && found->second.content->size() == bytes) { + seen = found->second.content; + seen_offset = found->second.offset; + seen_buffer = found->second.buffer; + seen_tag = found->second.tag; + } + ReleaseSRWLockExclusive(&draw_lock); + if (seen && std::memcmp(seen->data(), title, bytes) == 0 && ring_touch(seen_tag)) { + srvc_note(frame_copy_class, srvc_compared, bytes); + *offset = seen_offset; + *buffer = seen_buffer; return true; } u64 fresh = 0; - auto* ring = reserve_upload_ring(bytes, &fresh); + ID3D12Resource* chunk = nullptr; + RingTag tag; + auto* ring = reserve_upload_ring(bytes, &fresh, &chunk, &tag); if (!ring) return false; - // Cache insertion and snapshot allocation are optional. Fill the ring directly if they fail. - const unsigned char* source = title; + srvc_note(frame_copy_class, srvc_copied, bytes); + std::shared_ptr> content; try { - std::vector content(title, title + bytes); - // Use the stored snapshot to fill the ring so the GPU bytes and subsequent comparisons agree. - auto entry = frame_copies().insert_or_assign(key, FrameCopy{address, fresh, std::move(content)}); - source = entry.first->second.content.data(); + content = std::make_shared>(title, title + bytes); } catch (const std::bad_alloc&) { - // The ring slice is already reserved. The draw can proceed without another CPU allocation. + // The ring slice is already reserved: fill it from the title memory and keep no entry. } - std::memcpy(ring, source, bytes); - if (known) { + std::memcpy(ring, content ? content->data() : title, bytes); + x2w_memcut::note_copy(frame_number, bytes); + if (content) { + lock_draw(commit_line); + if (frame_copies_frame == frame) { + try { + frame_copies().insert_or_assign(key, FrameCopy{address, fresh, chunk, tag, std::move(content)}); + } catch (const std::bad_alloc&) { + } + } + ReleaseSRWLockExclusive(&draw_lock); + } + if (seen) { static LONG refreshed; if (first_calls(refreshed, 4)) log("x2w-draw frame copy of 0x%llx (%zu bytes) refreshed: the title changed it since an earlier draw of this frame", address, bytes); } *offset = fresh; + *buffer = chunk; return true; } @@ -1161,10 +2608,12 @@ u64 hash_memory(const unsigned char* data, std::size_t bytes) for (std::size_t i = words * 8; i < bytes; ++i) h = (h ^ data[i]) * 0x100000001b3ull; return h; } +x2w_startup::gfx10_local::Layout detile_layout(const D3D12_RESOURCE_DESC& r); // d3d12_memory_srv.inl (X2W_MEMORY_SRV_DETILE) bool list_wrote(Wrapper* list, ID3D12Resource* resource); // list_copy.inl bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) { auto* const memory = static_cast(resource->own().title_memory); + if (InterlockedCompareExchange(&resource->own().refs, 0, 0) <= 0) x2w_memcut::note_after_release(true); auto* list = recording(self); const D3D12_RESOURCE_DESC desc = texture->GetDesc(); const auto* original = resource_info(resource); @@ -1173,9 +2622,11 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) const bool dedicated = console && !address_uploads_from_ring(); // An address-only single-element texture (2D or 3D) uploads its one texel through the footprint path. const bool single = resource->own().tiled_address_srv && x2w_startup::single_element_bytes(desc) != 0; + const bool linear_srv = resource->own().linear_memory_srv; + const bool volume = linear_srv && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool uploadable = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D || single || - (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc.DepthOrArraySize == 1 && desc.Height == 1); + (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc.Height == 1 && (desc.DepthOrArraySize == 1 || linear_srv)); { static LONG reasons; if ((!memory || (desc.Flags & 0x7) || !uploadable) && !texture_uploads().count(texture) && @@ -1215,6 +2666,9 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) // (gfx10_layout.h, address_texture.h). const bool tiled_bc7 = !tiled_chain && !tiled_address && written.bc7_width != 0; const bool tiled = tiled_bc7 || tiled_address || tiled_chain; + const bool detiled = resource->own().detiled_memory_srv && original; + const x2w_startup::gfx10_local::Layout console_layout_local = detiled ? detile_layout(original->console) : x2w_startup::gfx10_local::Layout(~0u, false, 0, 0, 0, 0, 0); + if (resource->own().detiled_memory_srv && !console_layout_local.valid) return !console; std::optional console_layout; if (console) console_layout.emplace(original->console); const auto generation = written.generation; @@ -1246,7 +2700,8 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) rows_match = compact.level[i].rows == plan.rows[i] && compact.level[i].row_bytes == plan.row_bytes[i]; if (!rows_match) return true; } - const u64 total = tiled_chain ? x2w_startup::bc64::Chain(original->console).bytes() : console ? console_layout->bytes() + const u64 total = detiled ? console_layout_local.size + : tiled_chain ? x2w_startup::bc64::Chain(original->console).bytes() : console ? console_layout->bytes() : tiled && !single ? surface.size() : is_compact ? compact.bytes : stride * (slices - 1) + slice_total; const bool announced = state.generation != generation; const UINT elapsed = static_cast(frame_number) - static_cast(state.checked_frame); @@ -1287,16 +2742,44 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) } state.staged = false; require_state(self, texture, D3D12_RESOURCE_STATE_COPY_DEST); - if (console) { + if (detiled) { + // Each element of each level, array slice or volume depth from its console address into the desktop + // footprint. Element extents are the desktop ones (rows and row bytes of the footprint), which addrlib's + // ceiling level extents contain. + const UINT eb = 1u << console_layout_local.elem_log2; + for (UINT s = 0; s < slices; ++s) + for (UINT i = 0; i < mips; ++i) { + const auto& fp = plan.placed[i]; + const u64 bytes = plan.bytes(i); + u64 offset = 0; + ID3D12Resource* chunk = nullptr; + // One reservation per level and slice (at most one ring chunk, 64 MiB; a larger level is refused + // by the ring, and the texture is retried later). + auto* rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, nullptr); + if (!rows) { + state.done = false; + return !console; + } + const UINT columns = static_cast(plan.row_bytes[i] / eb), depth = fp.Footprint.Depth ? fp.Footprint.Depth : 1; + for (UINT z = 0; z < depth; ++z) + for (UINT y = 0; y < plan.rows[i]; ++y) { + auto* row = rows + (u64{z} * plan.rows[i] + y) * fp.Footprint.RowPitch; + for (UINT x = 0; x < columns; ++x) + std::memcpy(row + u64{x} * eb, memory + console_layout_local.address(i, x, y, volume ? z : s), eb); + } + plan.upload(list, texture, chunk, mips, slices, s, i, offset); + } + } else if (console) { for (UINT slice = 0; slice < slices; ++slice) { for (UINT i = 0; i < mips; ++i) { const u64 bytes = plan.bytes(i); u64 offset = owned.cursor; + ID3D12Resource* chunk = nullptr; unsigned char* rows = owned.cpu ? owned.cpu + offset : nullptr; if (owned.cpu) { owned.cursor += (bytes + placement - 1) & ~(placement - 1); } else { - rows = reserve_upload_ring(static_cast(bytes), &offset); + rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, nullptr); if (!rows) { state.done = false; return false; @@ -1304,7 +2787,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) std::memset(rows, 0, static_cast(bytes)); } console_layout->detile(i, slice, memory, rows, plan.placed[i].Footprint.RowPitch); - plan.upload(list, texture, owned.cpu ? owned.resource.Get() : upload_ring, mips, slices, slice, i, offset); + plan.upload(list, texture, owned.cpu ? owned.resource.Get() : chunk, mips, slices, slice, i, offset); } } if (dedicated) { @@ -1317,35 +2800,38 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) for (UINT i = 0; i < mips; ++i) { const u64 bytes = plan.bytes(i); u64 offset = 0; - auto* rows = reserve_upload_ring(static_cast(bytes), &offset); + ID3D12Resource* chunk = nullptr; + auto* rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, nullptr); if (!rows) { state.done = false; return true; } std::memset(rows, 0, static_cast(bytes)); chain.copy(i, slice, rows, memory, plan.placed[i].Footprint.RowPitch); - plan.upload(list, texture, upload_ring, mips, slices, slice, i, offset); + plan.upload(list, texture, chunk, mips, slices, slice, i, offset); } } } else if (tiled && !single) { u64 offset = 0; + ID3D12Resource* chunk = nullptr; const auto bytes = plan.bytes(0); - auto* rows = reserve_upload_ring(static_cast(bytes), &offset); + auto* rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, nullptr); if (!rows) { state.done = false; return true; } std::memset(rows, 0, static_cast(bytes)); surface.detile(memory, rows, plan.placed[0].Footprint.RowPitch); - plan.upload(list, texture, upload_ring, 1, 1, 0, 0, offset); + plan.upload(list, texture, chunk, 1, 1, 0, 0, offset); } else { for (UINT s = 0; s < slices; ++s) for (UINT i = 0; i < plan.count; ++i) { const auto& fp = plan.placed[i]; const u64 bytes = plan.bytes(i); u64 offset = 0; + ID3D12Resource* chunk = nullptr; if (is_compact) { - auto* const rows = reserve_upload_ring(static_cast(bytes), &offset); + auto* const rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, nullptr); if (!rows) { state.done = false; return true; @@ -1354,11 +2840,11 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) for (u64 y = 0; y < level.rows; ++y) std::memcpy(rows + y * fp.Footprint.RowPitch, memory + level.offset + y * level.row_bytes, static_cast(level.row_bytes)); - } else if (!ring_copy(reinterpret_cast(memory) + stride * s + fp.Offset, static_cast(bytes), &offset)) { + } else if (!ring_copy(reinterpret_cast(memory) + stride * s + fp.Offset, static_cast(bytes), &offset, &chunk)) { state.done = false; return true; } - plan.upload(list, texture, upload_ring, mips, slices, s, i, offset); + plan.upload(list, texture, chunk, mips, slices, s, i, offset); } } state.hash = hash; @@ -1377,17 +2863,89 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) return true; } +bool heap_texture_upload_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_HEAP_TEXTURE_UPLOAD"); + if (v) log("x2w-draw X2W_HEAP_TEXTURE_UPLOAD=1: textures referenced by heap views are uploaded (budgeted, once a frame)"); + return v; + }(); + return on; +} +std::vector heap_textures; +std::unordered_set heap_texture_set; +std::size_t heap_texture_cursor; +LONG heap_texture_frame = -1; +LONG heap_textures_uploaded; +void note_heap_texture(const ViewRecord& record) +{ + if (!heap_texture_upload_on() || record.slot != 18) return; + Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + if (!resource || resource->own().kind != resource_kind || !resource->own().real || !resource->own().title_memory) return; + const D3D12_RESOURCE_DESC desc = static_cast(resource->own().real)->GetDesc(); + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) return; + if (heap_texture_set.insert(resource).second) heap_textures.push_back(resource); +} +void upload_heap_textures(Wrapper* self) +{ + if (!heap_texture_upload_on() || heap_textures.empty() || heap_texture_frame == frame_number || !recording(self)) return; + heap_texture_frame = frame_number; + static const LONG budget_kib = [] { + char value[16]{}; + const LONG v = GetEnvironmentVariableA("X2W_HEAP_TEXTURE_BUDGET_KIB", value, sizeof value) ? std::atol(value) : 0L; + return v > 0 ? v : 65536L; + }(); + // Time as well as bytes: upload_texture also rehashes unchanged CPU-backed textures on its recheck schedule + // (up to 32 MiB each), which the byte budget does not see. X2W_HEAP_TEXTURE_BUDGET_US (default 2000) bounds the + // whole visit under draw_lock; the first texture is always visited. + static const LONG budget_us = [] { + char value[16]{}; + const LONG v = GetEnvironmentVariableA("X2W_HEAP_TEXTURE_BUDGET_US", value, sizeof value) ? std::atol(value) : 0L; + return v > 0 ? v : 2000L; + }(); + LARGE_INTEGER frequency{}, begin{}, now{}; + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&begin); + const LONG start_kib = texture_bytes_uploaded; + UINT uploaded = 0; + std::size_t visited = 0; + for (; visited < heap_textures.size() && visited < 512 && texture_bytes_uploaded - start_kib < budget_kib; ++visited) { + if (visited) { + QueryPerformanceCounter(&now); + if ((now.QuadPart - begin.QuadPart) * 1000000 / frequency.QuadPart >= budget_us) break; + } + Wrapper* resource = heap_textures[heap_texture_cursor++ % heap_textures.size()]; + // Revalidated each visit (wrappers are never freed today; this keeps it safe if that changes). + if (as_wrapper(resource) != resource || !resource->own().real) continue; + if (InterlockedCompareExchange(&resource->own().refs, 0, 0) <= 0) continue; // released: left alone + auto* texture = static_cast(resource->own().real); + const LONG before = textures_uploaded; + upload_texture(self, resource, texture); + if (textures_uploaded == before) continue; + require_state(self, texture, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE); + ++uploaded; + } + if (!uploaded) return; + const LONG n = InterlockedExchangeAdd(&heap_textures_uploaded, static_cast(uploaded)) + static_cast(uploaded); + static LONG shown; + if (first_calls(shown, 8)) + log("x2w-draw heap textures: frame %ld uploaded %u (%ld KiB), visited %zu of %zu listed; %ld uploaded so far", frame_number, + uploaded, texture_bytes_uploaded - start_kib, visited, heap_textures.size(), n); +} + // Per-draw dumps (X2W_DRAW_DUMP_FRAME=, X2W_DRAW_DUMP_DIR=): during that frame, render // target 0 is copied to a readback buffer after each translated draw (at most 48). // Poll the fence of the queue that actually executed the recording before writing its image. using x2w_startup::DrawDump; +LONG quiet_dump_frame; LONG draw_dump_frame() { static const LONG frame = [] { char value[16]{}; return GetEnvironmentVariableA("X2W_DRAW_DUMP_FRAME", value, sizeof(value)) ? std::atol(value) : 0L; }(); - return frame; + return frame ? frame : quiet_dump_frame; } void draw_dump_after(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, UINT count) { @@ -1457,6 +3015,445 @@ void draw_dump_flush() log("x2w-draw per-draw dump: %d of %zu completed target copies written to %s", written, completed.size(), folder); } +D3D12_GPU_VIRTUAL_ADDRESS desktop_va(u64 address); +bool desktop_range(u64 address, u64 bytes, ID3D12Resource** buffer, u64* offset); +void fill_views(Wrapper* self); +bool title_view_heap(const Pass& pass, u64* address, u64* bytes); +extern ID3D12Resource* vinfo_buffer; +extern UINT views_filled; +extern ID3D12Resource* vdesc_buffer; +bool ensure_vdesc(); + +struct TitleHeapView { + D3D12_GPU_VIRTUAL_ADDRESS va = 0; // the base's desktop address (log only) + ID3D12Resource* window = nullptr; // the view: window + offset, bytes + u64 offset = 0, bytes = 0, heap_bytes = 0; +}; +LONG rt_heap_clamped; // views shortened to the end of the base's window (counted once per frame and heap) +const char* bounded_title_heap(u64 address, u64 bytes, TitleHeapView& out); +const char* draw_title_heap(const Pass& pass, TitleHeapView& out) +{ + u64 address = 0, bytes = 0; + if (pass.source_view_heap) { + AcquireSRWLockShared(¬e_lock); + for (const HeapInfo& h : heap_infos()) + if (h.wrapper == pass.source_view_heap && h.title_cpu) { + address = h.title_cpu; + bytes = u64{h.logical_count} * h.increment; // the title's count (count may be the driver-clamped one) + } + ReleaseSRWLockShared(¬e_lock); + } + if (!address && !title_view_heap(pass, &address, &bytes)) return "title view heap not reachable"; + return bounded_title_heap(address, bytes, out); +} + +// The bounded view over the title heap [address, address + bytes), for draws and translated dispatches +// (d3d12_compute.inl). Cached per frame and heap; draw_lock held. +const char* bounded_title_heap(u64 address, u64 bytes, TitleHeapView& out) +{ + static u64 last_address, last_bytes; + static TitleHeapView last; + static const char* last_why; + static LONG last_frame = -1; + if (address != last_address || bytes != last_bytes || last_frame != frame_number) { + last_address = address; + last_bytes = bytes; + last_frame = frame_number; + last = {}; + last.heap_bytes = bytes; + last.va = desktop_va(address); + last_why = nullptr; + ID3D12Resource* window = nullptr; + u64 offset = 0, view_bytes = bytes; + if (!last.va) { + last_why = "title view heap not reachable"; + } else if (!bytes) { + last_why = "title view heap size unknown"; + } else if (!desktop_range(address, bytes, &window, &offset)) { + // The heap runs past the window that holds its base: the view ends at that window's end. + window = nullptr; + if (desktop_range(address, 16, &window, &offset)) { + const u64 width = window->GetDesc().Width; + view_bytes = width > offset ? width - offset : 0; + InterlockedIncrement(&rt_heap_clamped); + static LONG shown; + if (first_calls(shown, 4)) + log("x2w-draw-rt title heap 0x%llx (%llu bytes) runs past its window: view clamped to %llu bytes", address, bytes, view_bytes); + } else { + window = nullptr; + } + } + if (!last_why && (!window || view_bytes < 4)) last_why = "title view heap not in a desktop window"; + else if (!last_why && (offset & 15)) last_why = "title view heap base not 16-byte aligned (bounded raw view)"; + if (!last_why) { + last.window = window; + last.offset = offset; + last.bytes = view_bytes & ~u64{3}; + } + } + out = last; + return last_why; +} + +void bounded_raw_srv(ID3D12Resource* buffer, u64 offset, u64 bytes, D3D12_CPU_DESCRIPTOR_HANDLE dest) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + d.Buffer.FirstElement = offset / 4; + d.Buffer.NumElements = static_cast(bytes / 4 < UINT_MAX ? bytes / 4 : UINT_MAX); + d.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device_of(the_device)->CreateShaderResourceView(buffer, &d, dest); +} + +// gfx10 SQ_BUF_RSRC_WORD3 for a buffer view the title created (udsrc bufword3 / uavword3 of a view token): the +// word gfx10_view_words.h synthesizes, the same value compute hands to compute programs (d3d12_compute.inl): typed +// views only (FORMAT, DST_SEL, OOB_SELECT); raw, structured, constant-buffer and unmapped views: 0. +bool typed_views_off(); +std::uint32_t view_buffer_word3(const ViewRecord& record) +{ + if ((record.slot != 18 && record.slot != 19) || typed_views_off()) return 0; + x2w_startup::BufferViewLayout l; + if (!x2w_startup::buffer_view_layout_from_desc(record.slot == 19, record.desc, record.desc_bytes, l) || + l.kind != x2w_startup::BufferViewKind::typed) + return 0; + std::uint32_t v[8]; + x2w_startup::gfx10_buffer_words(l, v); + return v[3]; +} + +// Title ranges the GPU writes: translated-draw UAVs and GPU-ordered CopyBufferRegion destinations (slot 15, +// X2W_D3D12_COPY_BUFFER=gpu). Raw srvs overlapping one are bound in place instead of copied at record time, so a +// later draw reads what the GPU stored. Disjoint merged ranges, begin -> end; at most gpu_written_max, the lowest +// other range is dropped beyond that (counted: rt_written_evicted). draw_lock held. +std::map& gpu_written() { static std::map m; return m; } +SRWLOCK gpu_written_lock = SRWLOCK_INIT; +constexpr std::size_t gpu_written_max = 16384; +void note_gpu_written_locked(u64 address, u64 bytes); +void note_gpu_written(u64 address, u64 bytes) +{ + AcquireSRWLockExclusive(&gpu_written_lock); + note_gpu_written_locked(address, bytes); + ReleaseSRWLockExclusive(&gpu_written_lock); +} +void note_gpu_written_locked(u64 address, u64 bytes) +{ + auto& m = gpu_written(); + u64 begin = address, end = address + bytes; + auto it = m.upper_bound(begin); + if (it != m.begin()) { + const auto before = std::prev(it); + if (before->second >= begin) { + begin = before->first; + if (before->second > end) end = before->second; + it = m.erase(before); + } + } + while (it != m.end() && it->first <= end) { + if (it->second > end) end = it->second; + it = m.erase(it); + } + if (m.size() >= gpu_written_max) { + m.erase(m.begin()); + InterlockedIncrement(&rt_written_evicted); + } + m.emplace(begin, end); +} +bool gpu_written_overlaps(u64 address, u64 bytes) +{ + AcquireSRWLockShared(&gpu_written_lock); + const auto& m = gpu_written(); + auto it = m.lower_bound(address + bytes); + const bool overlaps = it != m.begin() && (--it)->second > address; + ReleaseSRWLockShared(&gpu_written_lock); + return overlaps; +} +std::size_t gpu_written_count() +{ + AcquireSRWLockShared(&gpu_written_lock); + const std::size_t n = gpu_written().size(); + ReleaseSRWLockShared(&gpu_written_lock); + return n; +} +// An in-place srv on a window: shader-resource state in this list's tracked states, except when this list already +// holds the window as UAV (the same 256 MiB window often carries the draw's own uav: one state cannot be both; +// it stays UAV, as before this tracking existed). +void window_read_state(Wrapper* self, ID3D12Resource* window) +{ + for (const auto& known : pass_of(self).states) + if (known.first == window && known.second == D3D12_RESOURCE_STATE_UNORDERED_ACCESS) return; + require_state(self, window, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); +} + +void null_uav(D3D12_CPU_DESCRIPTOR_HANDLE dest, int kind) +{ + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + if (kind == 1) { + d.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + } else { + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d.Buffer.NumElements = 1; + d.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + } + device_of(the_device)->CreateUnorderedAccessView(nullptr, nullptr, &d, dest); +} + +// The 32-byte title descriptor table entry uav j was read from (0: none). words gets its contents. +u64 uav_entry(const Pass& pass, const Translation::Uav& uav, std::uint32_t (&words)[8]) +{ + const u64 entry = uav.source == 0 && uav.a >= 0 && uav.a < 16 && uav.b >= 0 ? pass.view_tables[uav.a].record(static_cast(uav.b), 32) : 0; + if (!entry || !x2w_local::readable(reinterpret_cast(entry), 32)) return 0; + std::memcpy(words, reinterpret_cast(entry), 32); + return entry; +} + +void bind_uav_buffer(const Pass& pass, const Translation& tr, UINT j, D3D12_CPU_DESCRIPTOR_HANDLE dest, std::uint32_t* word3, std::uint32_t* base, + ID3D12Resource** bound_window, std::uint32_t* record_stride) +{ + const Translation::Uav& uav = tr.uavs[j]; + std::uint32_t words[8] = {}; + const u64 entry = uav_entry(pass, uav, words); + u64 address = 0; + std::size_t bytes = 0; + const char* from = "none"; + if (uav.source == 2 && uav.a >= 0 && uav.a < 16) { + address = pass.root_address[uav.a]; + bytes = address ? readable_window(address, 1u << 20) : 0; + from = "root"; + } else if (entry && words[0] == view_token_magic) { + // A view the title created: a CBV names its memory, a buffer SRV / UAV a range of its resource's title memory. + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + from = "view"; + if (known) *word3 = view_buffer_word3(record); + if (known && record.slot == 17 && record.desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(&address, record.desc, 8); + std::memcpy(&size, record.desc + 8, 4); + bytes = size; + } else if (known && (record.slot == 18 || record.slot == 19) && record.desc_bytes >= 36) { + DXGI_FORMAT format{}; + std::uint32_t dimension = 0, count = 0, stride = 0, flags = 0; + u64 first_element = 0; + const std::size_t at = record.slot == 18 ? 16 : 8; // Buffer member of the SRV / UAV description + std::memcpy(&format, record.desc, 4); + std::memcpy(&dimension, record.desc + 4, 4); + std::memcpy(&first_element, record.desc + at, 8); + std::memcpy(&count, record.desc + at + 8, 4); + std::memcpy(&stride, record.desc + at + 12, 4); + std::memcpy(&flags, record.desc + 32, 4); // Flags: +32 in both descriptions + Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + const bool raw = (flags & 1) || format == DXGI_FORMAT_R32_TYPELESS; + const UINT element = stride ? stride : raw || format == DXGI_FORMAT_UNKNOWN ? 4 : x2w_startup::typed_buffer_format_bytes(format); + // A structured view's stride, or a typed view's element size; a raw view has no record stride. + *record_stride = stride ? stride : raw || format == DXGI_FORMAT_UNKNOWN ? 0 : element; + if (dimension == 1 && element && resource && resource->own().title_memory) { + address = reinterpret_cast(resource->own().title_memory) + first_element * element; + bytes = std::size_t{count} * element; + } + } + } else if (entry) { + // A hardware buffer descriptor the title wrote itself: base address, stride and record count. + address = words[0] | (static_cast(words[1] & 0xffff) << 32); + const std::uint32_t stride = (words[1] >> 16) & 0x3fff; + bytes = static_cast(stride ? stride : 1) * words[2]; + *word3 = words[3]; + *record_stride = stride; + from = "descriptor"; + } + if (bytes > (256u << 20)) bytes = 256u << 20; + ID3D12Resource* window = nullptr; + u64 offset = 0; + bool found = address && bytes && desktop_range(address, bytes, &window, &offset); + // A root UAV has no size: shrink the readable guess until it sits in one window. + for (std::size_t smaller = bytes; !found && uav.source == 2 && address && smaller > 4096;) { + smaller = smaller > (64u << 10) ? (64u << 10) : 4096; + if ((found = desktop_range(address, smaller, &window, &offset))) bytes = smaller; + } + const u64 aligned = offset & ~u64{15}; + const char* result = "bound"; + if (!found) { + result = "NULL (no desktop window)"; + InterlockedIncrement(&rt_uav_buf_unresolved); + null_uav(dest, 0); + } else if (aligned != offset && !(tr.uav_base_wanted & (1u << j))) { + result = "NULL (not 16-byte aligned, no uavbase)"; + InterlockedIncrement(&rt_uav_buf_misaligned); + null_uav(dest, 0); + } else { + *base = static_cast(offset - aligned); + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d.Buffer.FirstElement = aligned / 4; + d.Buffer.NumElements = static_cast((bytes + *base + 3) / 4); + d.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device_of(the_device)->CreateUnorderedAccessView(window, nullptr, &d, dest); + *bound_window = window; + note_gpu_written(address, bytes); + InterlockedIncrement(&rt_uav_buf_bound); + } + static LONG shown; + if (first_calls(shown, 8)) + log("x2w-draw-rt %016llx uav %u buffer source %d(%d,%d) from %s: entry 0x%llx words %08x %08x %08x %08x -> address 0x%llx, %zu bytes, " + "window %p +0x%llx: %s", tr.key, j, uav.source, uav.a, uav.b, from, entry, words[0], words[1], words[2], words[3], address, bytes, + static_cast(window), offset, result); +} + +// Texture uav j (`uav tex2d`): a typed Texture2D UAV in the format and at the mip of the view the title +// created. The draw is skipped, not bound to a mismatched view, when any check fails. draw_lock held. +DXGI_FORMAT typeless_to_float(DXGI_FORMAT f); +bool float_format(DXGI_FORMAT f); +enum UavTextureSkip { tex_ok, tex_unresolved, tex_no_uav_flag, tex_shape, tex_format, tex_typed_store, tex_skip_count }; +const char* const uav_texture_skip_names[tex_skip_count] = {"bound", "unresolved view", "texture without ALLOW_UNORDERED_ACCESS", + "not a single-slice 2D texture at a valid mip", "format not a float/unorm format of the texture", "no typed UAV store for the format"}; +static_assert(tex_skip_count == std::size(rt_uav_tex), "one counter per texture uav outcome"); + +bool typed_store_supported(DXGI_FORMAT format) +{ + static signed char known[256]; // 0 not asked, 1 supported, -1 not + const auto i = static_cast(format); + if (i >= 256) return false; + if (!known[i]) { + D3D12_FEATURE_DATA_FORMAT_SUPPORT query{format}; + const bool yes = SUCCEEDED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &query, sizeof(query))) && + (query.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) && (query.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE); + known[i] = yes ? 1 : -1; + log("x2w-draw-rt format %d: typed UAV store %s", static_cast(format), yes ? "supported" : "NOT supported"); + } + return known[i] > 0; +} + +UavTextureSkip bind_uav_texture(const Pass& pass, const Translation& tr, UINT j, D3D12_CPU_DESCRIPTOR_HANDLE dest, ID3D12Resource** out) +{ + std::uint32_t words[8] = {}; + const u64 entry = uav_entry(pass, tr.uavs[j], words); + ViewRecord record{}; + bool known = false; + if (entry && words[0] == view_token_magic) { + AcquireSRWLockShared(¬e_lock); + known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + } + Wrapper* resource = known ? as_wrapper(reinterpret_cast(record.resource)) : nullptr; + ID3D12Resource* texture = resource && resource->own().kind == resource_kind ? static_cast(resource->own().real) : nullptr; + if (!texture || (record.slot != 18 && record.slot != 19) || record.desc_bytes < 24) return tex_unresolved; + const D3D12_RESOURCE_DESC rd = texture->GetDesc(); + if (!(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return tex_no_uav_flag; + DXGI_FORMAT format{}; + std::uint32_t dimension = 0, mip = 0; + std::memcpy(&format, record.desc, 4); + std::memcpy(&dimension, record.desc + 4, 4); + std::memcpy(&mip, record.desc + (record.slot == 19 ? 8 : 16), 4); // UAV MipSlice / SRV MostDetailedMip + // TEXTURE2D is 4 in both the SRV and the UAV dimension enumerations. + if (rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || rd.DepthOrArraySize != 1 || rd.SampleDesc.Count != 1 || dimension != 4 || + mip >= rd.MipLevels) return tex_shape; + format = typeless_to_float(desktop_format(format ? format : rd.Format)); + if (!float_format(format) || (format != rd.Format && format != typeless_to_float(rd.Format))) return tex_format; + if (!typed_store_supported(format)) return tex_typed_store; + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = format; + d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + d.Texture2D.MipSlice = mip; + device_of(the_device)->CreateUnorderedAccessView(texture, nullptr, &d, dest); + *out = texture; + static LONG shown; + if (first_calls(shown, 4)) + log("x2w-draw-rt %016llx uav %u texture: entry 0x%llx view %u -> %p %llux%u format %d mip %u: bound", tr.key, j, entry, words[1], + static_cast(texture), rd.Width, rd.Height, static_cast(format), mip); + return tex_ok; +} + +struct MeshDumpKeys { + u64 keys[16] = {}; + unsigned count = 0; +}; +const MeshDumpKeys& mesh_dump_keys() +{ + static const MeshDumpKeys list = [] { + MeshDumpKeys out; + char value[16 * 20 + 16]{}; + if (!GetEnvironmentVariableA("X2W_MESH_DUMP_INPUTS", value, sizeof(value))) return out; + for (char* p = value; *p && out.count < 16;) { + while (*p == ',' || *p == ' ' || *p == ';') ++p; + char* end = nullptr; + const u64 key = _strtoui64(p, &end, 16); + if (end == p) break; + if (key) out.keys[out.count++] = key; + p = end; + } + log("x2w-mesh X2W_MESH_DUMP_INPUTS: %u key(s)", out.count); + return out; + }(); + return list; +} +u64 mesh_dump_key() { return mesh_dump_keys().count ? mesh_dump_keys().keys[0] : 0; } // non-zero: any key wanted +LONG mesh_dump_claimed[16]; // one dump per listed key +LONG mesh_dump_done; // keys dumped +// Any listed key not dumped yet (then the indirect stage reads each mesh call's record, in any frame). +bool mesh_dump_pending() { return mesh_dump_keys().count && mesh_dump_done < static_cast(mesh_dump_keys().count); } +// X2W_MESH_DUMP_FROM_FRAME= (default 0): no dump before present n (to skip the start-up pages if needed). +LONG mesh_dump_from_frame() +{ + static const LONG n = [] { + char v[16]{}; + return GetEnvironmentVariableA("X2W_MESH_DUMP_FROM_FRAME", v, sizeof(v)) ? std::atol(v) : 0L; + }(); + return n; +} +thread_local std::string mesh_dump_dir; // non-empty: this call is being dumped (folder with trailing backslash) +bool mesh_dump_record_groups(std::uint32_t (&xyz)[3]); +bool mesh_dump_begin(u64 key) +{ + mesh_dump_dir.clear(); + const MeshDumpKeys& list = mesh_dump_keys(); + unsigned at = 0; + while (at < list.count && list.keys[at] != key) ++at; + if (!key || at == list.count || mesh_dump_claimed[at] || frame_number < mesh_dump_from_frame()) return false; + std::uint32_t xyz[3] = {}; + if (!mesh_dump_record_groups(xyz) || !xyz[0] || !xyz[1] || !xyz[2]) return false; + if (InterlockedCompareExchange(&mesh_dump_claimed[at], 1, 0) != 0) return false; + InterlockedIncrement(&mesh_dump_done); + char log_path[MAX_PATH]{}; + std::string dir; + if (GetEnvironmentVariableA("X2W_TRAP_LOG", log_path, sizeof(log_path))) { + dir = log_path; + const std::size_t slash = dir.find_last_of("\\/"); + dir = slash == std::string::npos ? std::string() : dir.substr(0, slash + 1); + } + char name[48]; + std::snprintf(name, sizeof(name), "mesh_dump_%016llx\\", static_cast(key)); + dir += name; + CreateDirectoryA(dir.c_str(), nullptr); + mesh_dump_dir = dir; + log("x2w-mesh dump %016llx: inputs of the first call with groups (record %u %u %u, frame %ld%s) to %s", static_cast(key), + xyz[0], xyz[1], xyz[2], frame_number, trace_frame_active ? ", traced" : "", dir.c_str()); + return true; +} +void mesh_dump_file(const char* file, const void* data, std::size_t bytes, const char* note) +{ + if (mesh_dump_dir.empty()) return; + const std::string path = mesh_dump_dir + file; + bool written = false; + if (FILE* f = std::fopen(path.c_str(), "wb")) { + written = (!bytes || !data || std::fwrite(data, 1, bytes, f) == bytes); + std::fclose(f); + } + if (FILE* index = std::fopen((mesh_dump_dir + "index.txt").c_str(), "ab")) { + std::fprintf(index, "%s %zu bytes%s: %s\n", file, bytes, written ? "" : " (WRITE FAILED)", note); + std::fclose(index); + } +} + +thread_local u64 last_draw_key; +thread_local const char* last_draw_why; bool d16_srvs_ready(const Translation& tr, const Pass& pass, std::uint32_t (&d16_unorm16)[32]) { if (!tr.d16_srvs.any()) return true; @@ -1832,7 +3829,7 @@ struct FormattedBufferDescriptor { std::uint32_t words[8] = {}; }; -bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedBufferDescriptor (&descriptors)[32]) +bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedBufferDescriptor (&descriptors)[draw_srv_limit]) { const auto refuse = [&](int slot, const char* reason, std::uint32_t detail = 0) { InterlockedIncrement(&formatted_draws_refused); @@ -1843,7 +3840,7 @@ bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedB }; for (const auto& ud : tr.uds) { if (ud.kind != Translation::desc_word3) continue; - if (ud.a < 0 || ud.a >= 32 || static_cast(ud.a) >= tr.srvs.size()) + if (ud.a < 0 || ud.a >= draw_srv_limit || static_cast(ud.a) >= tr.srvs.size()) return refuse(ud.a, "invalid SRV index"); auto& descriptor = descriptors[ud.a]; if (descriptor.entry) continue; @@ -1878,29 +3875,106 @@ bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedB return true; } +bool view_record_words(const ViewRecord& record, std::uint32_t out[8], bool* image, bool* unmapped); // d3d12_compute.inl + +LONG rt_descword_title, rt_descword_view, rt_descword_null; +std::uint32_t draw_descword_value(const Pass& pass, int param, int offset, u64 key) +{ + const u64 entry = param >= 0 && param < 16 && offset >= 0 ? pass.view_tables[param].record(static_cast(offset) & ~31ull, 32) : 0; + const int word = (offset & 31) / 4; + std::uint32_t words[8] = {}, value = 0; + const char* what = "table not bound or entry out of range"; + if (entry && x2w_local::readable(reinterpret_cast(entry), 32)) { + std::memcpy(words, reinterpret_cast(entry), 32); + if (words[0] == refused_view_magic) { + what = "refused-view marker: 0"; // the stand-in's marker words are not the console's descriptor + } else if (words[0] != view_token_magic) { + value = words[word]; + what = "title word"; + } else { + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + std::uint32_t out[8] = {}; + bool image = false, unmapped = false; + if (known && view_record_words(record, out, &image, &unmapped)) { + value = out[word]; + what = image ? (unmapped ? "T# word (no gfx10 format: FORMAT 0)" : "T# word") : "V# word"; + } else { + what = "unknown view: 0"; + } + } + } else if (entry) { + what = "entry unreadable: 0"; + } + InterlockedIncrement(what[0] == 't' && what[1] == 'i' ? &rt_descword_title : what[1] == '#' ? &rt_descword_view : &rt_descword_null); + static LONG shown; + if (first_calls(shown, 4)) + log("x2w-draw-rt %016llx descword %d %d: entry 0x%llx %s = 0x%08x", key, param, offset, entry, what, value); + return value; +} + bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance, TranslatedIndirectDraw* indirect) { auto* list = recording(self); Pass& pass = pass_of(self); - const bool rect = pass.topology == 0x11; + const u64 ring_refusals_at_start = ring_cap_refusals; + const bool mesh = mesh_issue_active(self); + const bool rect = !mesh && pass.topology == 0x11; + // Upstream #2259: an indexed rectangle list is drawn only through an indirect draw (geometry-stage expansion). const bool indexed_rect = rect && indexed && indirect; - if (!list || !pass.pipeline || !pass.targets_bound || !(rect || pass.topology == 4 || pass.topology == 5) || - (rect && indexed && !indexed_rect)) return false; - AcquireSRWLockExclusive(&draw_lock); - BoundPipeline* bound = translation_for(pass.pipeline); - Translation* tr = bound ? translation_for_targets(bound->translation, pass) : nullptr; + last_draw_key = 0; + last_draw_why = nullptr; + if (list && pass.pipeline && !pass.targets_bound) InterlockedIncrement(&draws_without_targets); + if (!list || !pass.pipeline || !pass.targets_bound || !(mesh || rect || pass.topology == 4 || pass.topology == 5) || (rect && indexed && !indexed_rect)) { + last_draw_why = !list ? "not recording" : !pass.pipeline ? "no pipeline" : !pass.targets_bound ? "no targets" + : (rect && indexed && !indexed_rect) ? "indexed rectangle list" : "topology"; + return false; + } + lock_draw(100000 + __LINE__); + report_draw_rt(); + static const bool pso_locked = x2w_local::env_on("X2W_DRAW_PSO_LOCKED"); + BoundPipeline* bound = nullptr; + Translation* tr = nullptr; + ID3D12PipelineState* pipeline = nullptr; + for (int attempt = 0;; ++attempt) { + // A second attempt finds the pipeline build_pipeline made (pipeline_for installs it). + bound = translation_for(pass.pipeline); + tr = bound ? translation_for_targets(bound->translation, pass) : nullptr; + PsoBuild build; + pipeline = tr && tr->state == 1 && ensure_draw_heap(self->own().list_device) + ? pipeline_for(*bound, *tr, pass, pso_locked || attempt ? nullptr : &build, indexed_rect) : nullptr; + if (pipeline || !build.bound) break; + ReleaseSRWLockExclusive(&draw_lock); + if (draw_async()) { + queue_pso_build(build); + last_draw_key = tr->key; + last_draw_why = "desktop pipeline compiling (X2W_DRAW_ASYNC)"; + return false; + } + build_pipeline(build); + lock_draw(100000 + __LINE__); + } + if (bound && bound->translation) last_draw_key = bound->translation->key; + // Upstream indirect draws (#2232 .. #2262): reached only through draw_translated(..., indirect), the + // X2W_TRANSLATED_INDIRECT path in d3d12_xs_device.cpp. A plain draw passes nullptr and skips all of it. if (indirect && tr) indirect->shader_key = tr->key; std::uint32_t d16_unorm16[32] = {}; - FormattedBufferDescriptor formatted_buffers[32] = {}; - const bool translation_ok = tr && tr->state == 1; - const bool d16_ok = translation_ok && d16_srvs_ready(*tr, pass, d16_unorm16); - const bool formatted_ok = d16_ok && formatted_buffers_ready(*tr, pass, formatted_buffers); - if (!formatted_ok) { - if (indirect && tr) - indirect->refusal_code = !translation_ok ? indirect_refusal_code::translation_not_ready - : !d16_ok ? indirect_refusal_code::d16_srv_not_ready - : indirect_refusal_code::formatted_buffer_not_ready; + if (tr && tr->state == 1 && !d16_srvs_ready(*tr, pass, d16_unorm16)) { + last_draw_why = "d16 exact srv refused"; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + FormattedBufferDescriptor formatted_buffers[draw_srv_limit] = {}; // upstream #2138 (udsrc descword3) + if (tr && tr->state == 1 && !formatted_buffers_ready(*tr, pass, formatted_buffers)) { + last_draw_why = "formatted buffer refused"; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + if (indirect && (!bound || !tr || tr->state != 1)) { ReleaseSRWLockExclusive(&draw_lock); return false; } @@ -1940,25 +4014,65 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return false; } } - ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass, indexed_rect) : nullptr; - if (indirect && indexed_rect && !pipeline) { - indirect->set_refusal("translated indexed rectangle geometry unavailable", - indirect_refusal_code::indexed_rect_unavailable); - } + if (indexed_rect && !pipeline) indirect->refusal = "translated indexed rectangle geometry unavailable"; if (!pipeline || (tr->samplers.heap && !prepare_draw_sampler_heap(pass, list, tr->samplers.reserved_fallback))) { - if (indirect && !(indexed_rect && !pipeline)) - indirect->refusal_code = !pipeline ? indirect_refusal_code::pipeline_unavailable - : indirect_refusal_code::sampler_heap_unavailable; + last_draw_why = !bound || !bound->translation ? "no translation record" + : !tr ? "no translation for the bound targets (rtv variant)" + : tr->state != 1 ? "no translation" : !pipeline ? "no desktop pipeline" : "sampler heap"; ReleaseSRWLockExclusive(&draw_lock); return false; } + TitleHeapView heap_view; + if (tr->heap) { + const char* reason = draw_heap_increment != 32 ? "descriptor increment is not 32" : draw_title_heap(pass, heap_view); + if (!reason) { + fill_views(self); + upload_heap_textures(self); + if (!vinfo_buffer) reason = "no per-view info buffer"; + else if (tr->heapwords && !ensure_vdesc()) reason = "no view descriptor (vdesc) buffer"; + } + if (reason) { + InterlockedIncrement(&rt_heap_skipped); + static LONG shown; + if (first_calls(shown, 4)) log("x2w-draw-rt %016llx: heap draw skipped: %s", tr->key, reason); + last_draw_why = reason; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + } const UINT n = static_cast(tr->srvs.size()); - UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(n))) % draw_heap_size; - if (first + n > draw_heap_size) { + const UINT m = static_cast(tr->uavs.size()); + const UINT hv = tr->heap ? (tr->heapwords ? 3u : 2u) : 0u; + UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(n + m + hv))) % draw_heap_size; + if (first + n + m + hv > draw_heap_size) { first = 0; - InterlockedExchange(&draw_heap_cursor, static_cast(n)); + InterlockedExchange(&draw_heap_cursor, static_cast(n + m + hv)); + } + std::uint32_t uav_word3[8] = {}, uav_bases[8] = {}, uav_strides[8] = {}; + ID3D12Resource* uav_textures[8] = {}; + ID3D12Resource* uav_windows[8] = {}; + UavTextureSkip skip = tex_ok; + for (UINT j = 0; j < m && skip == tex_ok; ++j) { + const D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + n + j} * draw_heap_increment}; + if (tr->uavs[j].kind == 0) bind_uav_buffer(pass, *tr, j, dest, &uav_word3[j], &uav_bases[j], &uav_windows[j], &uav_strides[j]); + else skip = bind_uav_texture(pass, *tr, j, dest, &uav_textures[j]); + if (tr->uavs[j].kind == 1) InterlockedIncrement(&rt_uav_tex[skip]); + } + // Windows bound as UAV are tracked in this list's states (moved back to COMMON at Close), so a GPU copy or an + // in-place srv after this draw names the right before-state. + if (skip == tex_ok) + for (ID3D12Resource* w : uav_windows) + if (w) require_state(self, w, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (skip != tex_ok) { + static LONG shown[tex_skip_count]; + if (first_calls(shown[skip], 2)) log("x2w-draw-rt %016llx: draw skipped: texture uav: %s", tr->key, uav_texture_skip_names[skip]); + last_draw_why = uav_texture_skip_names[skip]; + ReleaseSRWLockExclusive(&draw_lock); + return false; } - std::uint32_t strides[32] = {}; + const bool split = draw_lock_split() && !indirect; + if (split) ReleaseSRWLockExclusive(&draw_lock); + std::uint32_t strides[draw_srv_limit] = {}, word3[draw_srv_limit] = {}; // Only the vertices this draw can reference are copied: [vertex_first, vertex_first + vertex_count). // The shader adds the "base vertex" entry value to the vertex index, so that value is biased by // -vertex_first and each stream's view starts at vertex_first. @@ -1982,6 +4096,11 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } } if (vertex_first < 0) vertex_first = 0; + bool dumping = false; + if (mesh && mesh_dump_pending()) { // any frame (the first call with groups of each listed key) + SplitRelock relock(split, 100000 + __LINE__); + dumping = mesh_dump_begin(tr->key); + } UINT indexed_vertices = UINT_MAX; for (UINT i = 0; i < n; ++i) { const Translation::Srv& srv = tr->srvs[i]; @@ -2009,14 +4128,17 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI (srv.source == 0 && srv.a >= 0 && srv.a < 16 && srv.b >= 0 ? pass.view_tables[srv.a].record(static_cast(srv.b), 32) : 0); std::uint32_t words[8] = {}; - const bool entry_ok = formatted.entry || - (entry && x2w_local::readable(reinterpret_cast(entry), 32)); - if (entry_ok) std::memcpy(words, formatted.entry ? formatted.words : reinterpret_cast(entry), 32); + const bool entry_ok = entry && x2w_local::readable(reinterpret_cast(entry), 32); + if (entry_ok) std::memcpy(words, reinterpret_cast(entry), 32); + if (entry_ok && words[0] != view_token_magic) word3[i] = words[3]; // run-time buffer format (udsrc bufword3) bool buffer_token_known = false; if (srv.kind >= 1 && srv.kind <= 4) { const auto dimension = srv.kind == 1 ? D3D12_SRV_DIMENSION_TEXTURE2D : srv.kind == 2 ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : srv.kind == 4 ? D3D12_SRV_DIMENSION_TEXTURE1D : D3D12_SRV_DIMENSION_TEXTURE3D; + if (entry_ok) note_rewritten_marker(tr->key, i, entry, words); + SplitRelock relock(split, 100000 + __LINE__); // the rest of the texture bind (memcut revive, uploads, counters) + if (entry_ok && words[0] != view_token_magic) resolve_heap_index(tr->key, i, entry, words); // A texture: the title's descriptor memory carries the id of the view it created there. ViewRecord record{}; bool known = false; @@ -2075,6 +4197,11 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (first_calls(shown, 6)) log("x2w-draw %016llx srv %u texture: table entry 0x%llx words %08x %08x -> view %s, resource %p, desc %u bytes format %d", tr->key, i, entry, words[0], words[1], known ? "known" : "UNKNOWN", static_cast(texture), record.desc_bytes, desc.Format); + if (trace_frame_active) { + const D3D12_RESOURCE_DESC td = texture ? texture->GetDesc() : D3D12_RESOURCE_DESC{}; + log("x2w-frame srv %016llx %u texture %p %llux%u fmt %d (view fmt %d)", tr->key, i, static_cast(texture), + static_cast(td.Width), td.Height, td.Format, desc.Format); + } const bool wrong_1d_resource = texture && srv.kind == 4 && (texture->GetDesc().Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D || texture->GetDesc().DepthOrArraySize != 1); if (texture && ((record.desc_bytes >= 40 && desc.ViewDimension != dimension) || wrong_1d_resource)) { @@ -2108,9 +4235,30 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI x2w_startup::report_token_entry(line, sizeof(line), tr->key, i, entry, words); log("%s", line); } - device_of(the_device)->CreateShaderResourceView(texture, texture && record.desc_bytes < 40 ? nullptr : &desc, dest); + census_texture_binding(resource, texture, x2w_local::classify_null_binding(facts)); + note_null_texture(tr->key, i, entry, words, x2w_local::classify_null_binding(facts)); + D3D12_SHADER_RESOURCE_VIEW_DESC depth_default{}; + const bool no_desc = texture && record.desc_bytes < 40; + const bool depth_desc = no_desc && default_depth_srv(texture, depth_default); + if (texture && !no_desc) fix_srv(desc, texture); + device_of(the_device)->CreateShaderResourceView(texture, depth_desc ? &depth_default : no_desc ? nullptr : &desc, dest); continue; } + if (srv.source == 0 && entry_ok) note_rewritten_marker(tr->key, i, entry, words); + const bool buffer_link = srv.source == 0 && entry_ok && free_link_words(words); + if (buffer_link) { + InterlockedIncrement(words[0] == refused_view_magic ? &buffer_refused_views : &buffer_links); + if (buffer_heap_index_on()) { + static LONG link_lines; + if (trace_frame_active || first_calls(link_lines, 32)) { + SplitRelock relock(split, 100000 + __LINE__); // reads heap shadow arrays outside note_lock + log_buffer_link(tr->key, i, entry, words); + } + InterlockedIncrement(&buffer_links_nulled); + std::memset(words, 0, sizeof(words)); + word3[i] = 0; + } + } if (indirect) { IndirectBufferView view{}; if (srv.source == 1 && indexed) { @@ -2148,6 +4296,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI buffer_token_known = words[1] < view_records().size(); if (buffer_token_known) record = view_records()[words[1]]; ReleaseSRWLockShared(¬e_lock); + if (buffer_token_known) word3[i] = view_buffer_word3(record); if (record.slot == 17 && record.desc_bytes >= 12) { std::uint32_t size = 0; std::memcpy(&address, record.desc, 8); @@ -2173,17 +4322,34 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI strides[i] = (words[1] >> 16) & 0x3fff; bytes = static_cast(strides[i] ? strides[i] : 1) * words[2]; } - if (bytes > (16u << 20)) { - bytes = 16u << 20; - // Formatted loads past the copy would read zeros on the desktop; refuse the draw instead. - if (formatted.entry) { - InterlockedIncrement(&formatted_draws_refused); - static LONG refused; - if (first_calls(refused, 6)) - log("x2w-draw %016llx srv %u: formatted buffer refused (buffer larger than the 16 MiB draw copy)", tr->key, i); - ReleaseSRWLockExclusive(&draw_lock); - return false; - } + const std::size_t full_bytes = bytes; + if (mesh && trace_frame_active) record_trace_mesh_read(tr->key, i, srv.source, srv.a, srv.b, address, full_bytes); + if (bytes > (16u << 20)) bytes = 16u << 20; + if (dumping) { + char file[16], note[240]; + std::snprintf(file, sizeof(file), "srv%u.bin", i); + // A root srv has no size (the binding takes up to 64 KiB): the dump takes the readable window up to 16 MiB. + // Any range is cut to its readable part (the note says so) instead of dropped. + const std::size_t wanted = srv.source == 2 ? (16u << 20) : full_bytes > (256u << 20) ? (256u << 20) : full_bytes; + const std::size_t dump_bytes = address && wanted ? static_cast(readable_window(address, wanted)) : 0; + const bool readable_range = dump_bytes != 0; + std::snprintf(note, sizeof(note), "srv %u source %d(%d,%d) entry 0x%llx words %08x %08x %08x %08x address 0x%llx stride %u bound %zu%s%s%s", i, + srv.source, srv.a, srv.b, static_cast(entry), words[0], words[1], words[2], words[3], + static_cast(address), strides[i], bytes, readable_range ? "" : " (range not readable: no bytes)", + placed.reject ? " (placed: rejected, bound null)" : "", + srv.source == 2 ? " (root srv: readable window up to 16 MiB)" + : dump_bytes && dump_bytes < wanted ? " (cut to the readable part)" + : dump_bytes != bytes ? " (binding clamped to 16 MiB; dump has the full range up to 256 MiB)" : ""); + SplitRelock relock(split, 100000 + __LINE__); + mesh_dump_file(file, readable_range ? reinterpret_cast(address) : nullptr, readable_range ? dump_bytes : 0, note); + } + if (const int r = range_watch_hit(address, bytes); r >= 0) { + SplitRelock relock(split, 100000 + __LINE__); + static LONG shown; + if (first_calls(shown, 16) && range_watch_line(r)) + log("x2w-watch 0x%llx: draw %016llx srv %u reads 0x%llx (%zu bytes) frame %ld", range_watch_address(r), tr->key, i, address, bytes, + frame_number); + range_watch_sample("draw-bind", tr->key); } // A buffer binding that ends up without a readable range counts as a null binding with its cause. const auto count_buffer = [&](bool bound) { @@ -2193,7 +4359,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI buffer_facts.token_magic = entry_ok && words[0] == view_token_magic; buffer_facts.token_known = buffer_token_known; buffer_facts.bound = bound; - count_null_binding(x2w_local::classify_null_binding(buffer_facts)); + count_null_binding(x2w_local::classify_null_binding(buffer_facts)); // interlocked counters: no draw_lock needed }; if (placed.reject || (placed.owner && !InterlockedCompareExchange(&placed.owner->own().refs, 0, 0))) { buffer_view(dest, nullptr, 0, 0); @@ -2204,12 +4370,13 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI // Preserve tight byte-sized streams. The desktop raw view is rounded // to a DWORD, so initialise its final padding without reading the guest. const auto padded = (bytes + 3) & ~std::size_t{3}; - auto* target = readable_window(address, bytes) >= bytes ? reserve_upload_ring(padded, &offset) : nullptr; + ID3D12Resource* chunk = nullptr; + auto* target = readable_window(address, bytes) >= bytes ? reserve_upload_ring(padded, &offset, &chunk, nullptr) : nullptr; if (target) { std::memcpy(target, reinterpret_cast(address), bytes); std::memset(target + bytes, 0, padded - bytes); } - buffer_view(dest, target ? upload_ring : nullptr, offset, padded); + buffer_view(dest, target ? chunk : nullptr, offset, padded); count_buffer(target != nullptr); continue; } @@ -2218,7 +4385,62 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI buffer_view(dest, placed.alias, address - reinterpret_cast(placed.owner->own().title_memory), bytes); continue; } - bool have = address && bytes && readable_window(address, bytes) >= bytes && frame_copy(address, bytes, &offset); + if (address && srv_in_place_min() && bytes >= srv_in_place_min() && (mesh || srv_in_place_all())) { + ID3D12Resource* window = nullptr; + u64 at = 0; + const bool in_window = desktop_range(address, bytes, &window, &at); + if (in_window && at % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT == 0) { + // States: only a window this list already tracks is transitioned (window_read_state). An untracked window + // gets no barrier, as translated compute binds windows in place (implicit buffer promotion): the indirect + // stage and compute may have it promoted to UNORDERED_ACCESS, which a COMMON-based barrier would contradict. + bool tracked = false; + for (const auto& known : pass.states) tracked |= known.first == window; + if (tracked) window_read_state(self, window); + buffer_view(dest, window, at, bytes); + count_buffer(true); + srvc_note(mesh ? 2 : 1, srvc_in_place, bytes); + static LONG shown; + if (first_calls(shown, 4)) + log("x2w-draw %016llx srv %u: 0x%llx (%zu bytes) bound in place at window %p +0x%llx (X2W_DRAW_SRV_IN_PLACE)", tr->key, i, + address, bytes, static_cast(window), at); + continue; + } + InterlockedIncrement64(&srvc_in_place_missed[mesh ? 2 : 1][in_window ? 1 : 0]); + static LONG missed_shown; + if (first_calls(missed_shown, 8)) + log("x2w-draw %016llx srv %u: 0x%llx (%zu bytes) not bound in place: %s; copied as before", tr->key, i, address, bytes, + in_window ? "window offset not 16-aligned" : "no single desktop window (desktop_range)"); + } + const bool gpu_written_range = address && bytes && gpu_written_overlaps(address, bytes); // its own lock + if (gpu_written_range) { + ID3D12Resource* window = nullptr; + u64 at = 0; + if (desktop_range(address, bytes, &window, &at) && at % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT == 0) { + window_read_state(self, window); + buffer_view(dest, window, at, bytes); + count_buffer(true); + InterlockedIncrement(&rt_srv_in_place); + static LONG shown; + if (first_calls(shown, 4)) + log("x2w-draw-rt %016llx srv %u: 0x%llx (%zu bytes) is written on the GPU (draw uav or copy); bound in place at window %p +0x%llx", + tr->key, i, address, bytes, static_cast(window), at); + continue; + } + InterlockedIncrement(&rt_srv_stale_copy); + } + frame_copy_class = srv.source == 0 && entry && words[0] && words[0] != view_token_magic ? 3 : mesh ? 2 : 1; + ID3D12Resource* chunk = nullptr; + bool have = false; + if (address && bytes && readable_window(address, bytes) >= bytes) { + const std::size_t min_bytes = draw_copy_split_min(); + const bool split_copy = !split && min_bytes && bytes >= min_bytes && !mesh && !indirect && !indirect_pending(self); + if (split) { + have = frame_copy_unlocked(address, bytes, &offset, &chunk, 100000 + __LINE__, 100001 + __LINE__); + } else { + have = (split_copy && compare_draw_copy(address, bytes, &offset, &chunk)) || frame_copy(address, bytes, &offset, &chunk); + } + } + frame_copy_class = 0; // thread_local: no lock needed // Experiment (X2W_DRAW_NULL_IDENTITY=1): an empty buffer slot reads as repeated identity // matrices instead of zeros. The start-up screen's last pass takes its world matrix from a // slot the title leaves empty here; why is not known yet. @@ -2232,24 +4454,36 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return false; } if (!have && identity_for_null) { + SplitRelock relock(split, 100000 + __LINE__); // the shared identity array is rewritten here static float identity[64]; for (int k = 0; k < 64; ++k) identity[k] = (k % 16) % 5 == 0 ? 1.0f : 0.0f; address = reinterpret_cast(identity); bytes = sizeof(identity); - have = frame_copy(address, bytes, &offset); + have = frame_copy(address, bytes, &offset, &chunk); } - buffer_view(dest, have ? upload_ring : nullptr, offset, bytes); + buffer_view(dest, have ? chunk : nullptr, offset, bytes); count_buffer(have); - if (first_calls(tr->logged_bindings, 8)) { + if (x2w_local::first_calls(tr->logged_bindings, 8) || trace_frame_active) { char head[3 * 48 + 1] = ""; if (have) hex_text(reinterpret_cast(address), bytes < 48 ? bytes : 48, head, sizeof(head)); log("x2w-draw %016llx srv %u buffer source %d(%d,%d): entry 0x%llx words %08x %08x %08x %08x -> address 0x%llx, %zu bytes, stride %u: %s [%s]", tr->key, i, srv.source, srv.a, srv.b, entry, words[0], words[1], words[2], words[3], address, bytes, strides[i], have ? "bound" : "NULL", head); } + if (trace_frame_active && have && bytes > 48) { + for (std::size_t at = 0; at < bytes && at < 512; at += 256) { // 256 bytes per line (log lines hold 1.5 KiB) + char part[3 * 256 + 4] = ""; + const std::size_t n = bytes - at < 256 ? bytes - at : 256; + hex_text(reinterpret_cast(address + at), n, part, sizeof(part)); + log("x2w-frame srv-bytes %016llx %u +%zu of %zu: %s", tr->key, i, at, bytes, part); + } + } } static LONG checks; - if ((InterlockedIncrement(&checks) & 63) == 1) check_device("translated draw views", 0); + if ((InterlockedIncrement(&checks) & 63) == 1) { + SplitRelock relock(split, 100000 + __LINE__); + check_device("translated draw views", 0); + } std::uint32_t values[32] = {}; for (std::size_t i = 0; i < tr->uds.size(); ++i) { const Translation::Ud& ud = tr->uds[i]; @@ -2257,9 +4491,115 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI : ud.kind == Translation::base_vertex ? static_cast((indexed ? base_vertex : static_cast(start)) - vertex_first) : ud.kind == Translation::start_instance ? start_instance : ud.kind == Translation::root_constant ? ((ud.a >= 0 && ud.a < 16 && ud.b >= 0 && ud.b < 8) ? pass.constants[ud.a][ud.b] : 0) - : ud.kind == Translation::stride && ud.a >= 0 && ud.a < 32 ? strides[ud.a] + : ud.kind == Translation::stride && ud.a >= 0 && ud.a < draw_srv_limit ? strides[ud.a] + : ud.kind == Translation::buf_word3 && ud.a >= 0 && ud.a < draw_srv_limit ? word3[ud.a] + : ud.kind == Translation::uav_word3 && ud.a >= 0 && ud.a < 8 ? uav_word3[ud.a] + : ud.kind == Translation::uav_base && ud.a >= 0 && ud.a < 8 ? uav_bases[ud.a] + : ud.kind == Translation::uav_stride && ud.a >= 0 && ud.a < 8 ? uav_strides[ud.a] : ud.kind == Translation::d16_unorm16 && ud.a >= 0 && ud.a < 32 ? d16_unorm16[ud.a] - : ud.kind == Translation::desc_word3 ? formatted_buffers[ud.a].words[3] : 0; + : ud.kind == Translation::desc_word3 && ud.a >= 0 && ud.a < draw_srv_limit ? formatted_buffers[ud.a].words[3] + : ud.kind == Translation::desc_word ? draw_descword_value(pass, ud.a, ud.b, tr->key) : 0; + if (ud.kind == Translation::buf_word3) { + InterlockedIncrement(values[i] ? &rt_word3_set : &rt_word3_zero); + static LONG shown; + if (first_calls(shown, 1)) + log("x2w-draw-rt bufword3 first use: pipeline %016llx entry value %zu = word 3 of srv %d = 0x%08x", tr->key, i, ud.a, values[i]); + } + } + if (mesh && trace_frame_active) record_trace_mesh_heap(self, *tr); + if (dumping) { + SplitRelock relock(split, 100000 + __LINE__); + char note[600]; + int used = std::snprintf(note, sizeof(note), "entry constants (root parameter 0), kind(a,b) per value:"); + for (std::size_t i = 0; i < tr->uds.size() && used > 0 && used < static_cast(sizeof(note)) - 24; ++i) + used += std::snprintf(note + used, sizeof(note) - used, " %d(%d,%d)", static_cast(tr->uds[i].kind), tr->uds[i].a, tr->uds[i].b); + mesh_dump_file("entry.bin", values, tr->uds.size() * sizeof(values[0]), note); + mesh_dump_file("root_constants.bin", pass.constants, sizeof(pass.constants), + "the list's 32-bit root constants as set by the title, [parameter 0-15][word 0-7] u32"); + // The heap buffers a key reads through a root constant (mesh 063500: bit 28 set = the meshlet index comes from + // a heap buffer whose descriptor index is bits 0-9). Each root constant the translation reads (a `udsrc .. + // rootconst p w` entry) with bit 28 set is taken as such a reference (ASSUMED; a word that is really something + // else gives one extra file); other root-constant words are not scanned (floats near 1 have bit 28 set). + // heap_desc.bin is the 32-byte title descriptor, heap.bin the buffer it names (its readable + // part, up to 256 MiB). + u64 heap_address = 0, heap_bytes = 0; + if (pass.source_view_heap) { + AcquireSRWLockShared(¬e_lock); + for (const HeapInfo& h : heap_infos()) + if (h.wrapper == pass.source_view_heap && h.title_cpu) heap_address = h.title_cpu, heap_bytes = u64{h.logical_count} * h.increment; + ReleaseSRWLockShared(¬e_lock); + } + if (!heap_address) title_view_heap(pass, &heap_address, &heap_bytes); + std::uint32_t done_index[16]; + unsigned done = 0; + for (std::size_t u = 0; u < tr->uds.size() && done < 16; ++u) { + const Translation::Ud& ud = tr->uds[u]; + if (ud.kind != Translation::root_constant || ud.a < 0 || ud.a >= 16 || ud.b < 0 || ud.b >= 8) continue; + const int p = ud.a, w = ud.b; + const std::uint32_t c = pass.constants[p][w]; + if (!(c & (1u << 28))) continue; + const std::uint32_t index = c & 0x3ff; + bool again = false; + for (unsigned k = 0; k < done; ++k) again |= done_index[k] == index; + if (again) continue; + done_index[done++] = index; + char file[32], note[300]; + const u64 slot = heap_address + u64{index} * 32; + const bool slot_ok = heap_address && u64{index} * 32 + 32 <= heap_bytes && readable_window(slot, 32) >= 32; + std::uint32_t d[8] = {}; + if (slot_ok) std::memcpy(d, reinterpret_cast(slot), sizeof(d)); + std::snprintf(file, sizeof(file), "heap%u_desc.bin", index); + std::snprintf(note, sizeof(note), "title heap descriptor %u (root constant [%d][%d] = 0x%08x) at 0x%llx, heap 0x%llx %llu bytes%s", index, + p, w, c, static_cast(slot), static_cast(heap_address), + static_cast(heap_bytes), slot_ok ? "" : " (not readable: no bytes)"); + mesh_dump_file(file, slot_ok ? d : nullptr, slot_ok ? sizeof(d) : 0, note); + if (!slot_ok) continue; + u64 at = 0; + std::size_t n = 0; + UINT stride = 0; + const char* how = "hardware buffer descriptor"; + if (d[0] == view_token_magic) { // a view the title created (as the srv table path resolves it) + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = d[1] < view_records().size(); + if (known) record = view_records()[d[1]]; + ReleaseSRWLockShared(¬e_lock); + how = known ? "view token" : "view token, unknown view"; + if (known && record.slot == 17 && record.desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(&at, record.desc, 8); + std::memcpy(&size, record.desc + 8, 4); + n = size; + how = "view token: constant buffer view"; + } else if (known && record.slot == 18 && record.desc_bytes >= 40) { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + std::memcpy(&view, record.desc, 40); + Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + if (view.ViewDimension == D3D12_SRV_DIMENSION_BUFFER && resource && resource->own().title_memory) { + const bool typed_view = !view.Buffer.StructureByteStride && view.Format != DXGI_FORMAT_R32_TYPELESS; + const UINT element = view.Buffer.StructureByteStride ? view.Buffer.StructureByteStride + : typed_view ? x2w_startup::typed_buffer_format_bytes(view.Format) : 4; + at = reinterpret_cast(resource->own().title_memory) + view.Buffer.FirstElement * element; + n = std::size_t{view.Buffer.NumElements} * element; + stride = element; + how = typed_view ? "view token: typed buffer view" : "view token: buffer view"; + } else { + how = "view token: not a buffer view of title memory"; + } + } + } else { + at = d[0] | (static_cast(d[1] & 0xffff) << 32); + stride = (d[1] >> 16) & 0x3fff; + n = static_cast(stride ? stride : 1) * d[2]; + } + if (n > (256u << 20)) n = 256u << 20; + if (at && n) n = static_cast(readable_window(at, n)); // the readable part + const bool range_ok = at && n; + std::snprintf(file, sizeof(file), "heap%u.bin", index); + std::snprintf(note, sizeof(note), "buffer of title heap descriptor %u (%s): words %08x %08x %08x %08x, address 0x%llx stride %u%s", index, + how, d[0], d[1], d[2], d[3], static_cast(at), stride, range_ok ? "" : " (range not readable: no bytes)"); + mesh_dump_file(file, range_ok ? reinterpret_cast(at) : nullptr, range_ok ? n : 0, note); + } } // A desktop list with no viewport or scissor draws nothing: cover the first render target unless the title set its own. if (pass.target0 && (!pass.viewport_set || !pass.scissor_set)) { @@ -2278,6 +4618,9 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI pass.default_scissor_h = target.Height; } } + if (split) lock_draw(100000 + __LINE__); + for (UINT j = 0; j < m; ++j) + if (uav_textures[j]) require_state(self, uav_textures[j], D3D12_RESOURCE_STATE_UNORDERED_ACCESS); ID3D12Resource* validated = nullptr; if (indirect && indexed) { validated = validate_indexed_arguments(self, list, *tr, *indirect, indexed_vertices); @@ -2295,19 +4638,50 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI pass_dsv_format(*bound, pass) != DXGI_FORMAT_UNKNOWN && bound->stencil_ref != pass.stencil_reference; if (scoped_stencil_ref) list->OMSetStencilRef(bound->stencil_ref); - list->SetGraphicsRootSignature(tr->root); + // Heaps before the root signature: a directly-indexed root signature set with no heap bound is an + // error on the desktop (#1419). ID3D12DescriptorHeap* samplers = tr->samplers.heap ? pass.sampler_heap.Get() : nullptr; if (!pass.heap_set || pass.bound_sampler_heap != samplers) { x2w_startup::bind_translated_heaps(list, draw_heap, samplers); pass.heap_set = true; pass.bound_sampler_heap = samplers; } + list->SetGraphicsRootSignature(tr->root); list->SetGraphicsRoot32BitConstants(0, static_cast(tr->uds.size()), values, 0); if (n) list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); if (samplers) list->SetGraphicsRootDescriptorTable(x2w_startup::sampler_root_parameter(n), samplers->GetGPUDescriptorHandleForHeapStart()); + if (m) list->SetGraphicsRootDescriptorTable(tr->uav_parameter, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first + n} * draw_heap_increment}); + if (tr->heap) { + const UINT h0 = first + n + m; + const auto cpu = [&](UINT k) { return D3D12_CPU_DESCRIPTOR_HANDLE{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{h0 + k} * draw_heap_increment}; }; + const auto gpu = [&](UINT k) { return D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{h0 + k} * draw_heap_increment}; }; + const u64 vinfo_bytes = vinfo_buffer->GetDesc().Width; + const u64 vdesc_bytes = tr->heapwords ? vdesc_buffer->GetDesc().Width : 0; + bounded_raw_srv(heap_view.window, heap_view.offset, heap_view.bytes, cpu(0)); + bounded_raw_srv(vinfo_buffer, 0, vinfo_bytes, cpu(1)); + if (tr->heapwords) bounded_raw_srv(vdesc_buffer, 0, vdesc_bytes, cpu(2)); + list->SetGraphicsRootDescriptorTable(tr->heap_parameter, gpu(0)); + list->SetGraphicsRootDescriptorTable(tr->heap_parameter + 1, gpu(1)); + if (tr->heapwords) list->SetGraphicsRootDescriptorTable(tr->vdesc_parameter, gpu(2)); + if (!tr->heap_views_logged) { + tr->heap_views_logged = true; // once per key (draw_lock held) + static LONG shown; + if (first_calls(shown, 256)) + log("x2w-draw-rt %016llx: bounded heap views: heapmem %llu bytes (title heap %llu), vinfo %llu, vdesc %llu", tr->key, + heap_view.bytes, heap_view.heap_bytes, vinfo_bytes, vdesc_bytes); + } + // The region starts at the 8 empty views before id 0 (d3d12_compute.inl fill_views). + list->SetGraphicsRootDescriptorTable(tr->heap_parameter + 2, + D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{draw_heap_size} * draw_heap_increment}); + if (InterlockedIncrement(&rt_heap_draws) == 1) + log("x2w-draw-rt first heap draw: pipeline %016llx, title heap at desktop 0x%llx, views filled %u", tr->key, heap_view.va, views_filled); + } list->IASetPrimitiveTopology(pass.topology == 5 ? D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP : D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); bool drawn = false; - if (indirect) { + gpu_time::mark(self, list, gpu_time::c_draw, tr->key, false); + if (ring_cap_refusals != ring_refusals_at_start) { + ring_draw_refused(tr->key); + } else if (indirect) { // upstream translated indirect draw (see the head of this function) if (validated) { list->IASetIndexBuffer(&indirect->indices.view); list->ExecuteIndirect(tr->indexed_signature.Get(), 1, validated, 4, validated, 0); @@ -2319,12 +4693,13 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (pass.graphics_root) list->SetGraphicsRootSignature(pass.graphics_root); pass.srv_bound = 0; drawn = true; - } else if (indexed) { + } else if (indirect_pending(self)) { drawn = indirect_draw_issue(self, list, indexed); } else if (indexed) { u64 offset = 0; const u64 address = index_address; const std::size_t bytes = index_total; - if (indices_ok && frame_copy(address, bytes, &offset)) { - const D3D12_INDEX_BUFFER_VIEW view{upload_ring->GetGPUVirtualAddress() + offset, static_cast(bytes), + ID3D12Resource* chunk = nullptr; + if (indices_ok && frame_copy(address, bytes, &offset, &chunk)) { + const D3D12_INDEX_BUFFER_VIEW view{chunk->GetGPUVirtualAddress() + offset, static_cast(bytes), index_bytes == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; list->IASetIndexBuffer(&view); const auto red_samples = red_producer_draw_before(self, list, "translated-draw", tr->key); @@ -2338,11 +4713,24 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI red_producer_draw_after(self, red_samples); drawn = true; } + gpu_time::mark(self, list, gpu_time::c_draw, tr->key, true, !drawn); + if (drawn && m) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + if (InterlockedIncrement(&rt_uav_draws) == 1) + log("x2w-draw-rt first draw with uavs: pipeline %016llx, %u uavs, %u srvs", tr->key, m, n); + } if (scoped_stencil_ref) list->OMSetStencilRef(pass.stencil_reference); if (drawn && !indirect) draw_dump_after(self, list, tr->key, count); ReleaseSRWLockExclusive(&draw_lock); if (indirect) return drawn; - if (first_calls(tr->logged_draws, 10) || (count > 100 && first_calls(tr->logged_large, 12))) { + if (trace_frame_active && pass.target0) { + const D3D12_RESOURCE_DESC target = pass.target0->GetDesc(); + log("x2w-frame translated draw %016llx count %u: target0 %p %llux%u format %d, %u targets", tr->key, count, + static_cast(pass.target0), target.Width, target.Height, target.Format, pass.target_count); + } + if (x2w_local::first_calls(tr->logged_draws, 10) || trace_frame_active || (count > 100 && x2w_local::first_calls(tr->logged_large, 12))) { char indices[3 * 24 + 1] = ""; if (indexed && pass.ib.BufferLocation) hex_text(reinterpret_cast(pass.ib.BufferLocation + u64{start} * 2), 24, indices, sizeof(indices)); log("x2w-draw %s(%u, %u, start %u, base %d) pipeline %016llx topology 0x%x -> %s; entry [%x %x %x %x %x %x]; ib 0x%llx+%u fmt %d [%s]; " @@ -2351,6 +4739,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI pass.ib.SizeInBytes, pass.ib.Format, indices, pass.vb[0].BufferLocation, pass.vb[0].SizeInBytes, pass.vb[0].StrideInBytes, pass.target_count); } + if (!drawn) last_draw_why = "skipped (index data)"; return drawn; } @@ -2437,7 +4826,7 @@ void __stdcall list_table(Wrapper* self, UINT parameter, u64 gpu_handle) } // List slot 35 (desktop 31 + 4), SetComputeRootDescriptorTable(parameter, GPU handle). Recorded only for a later // Dispatch; slot 33 keeps the desktop compute root bind. -void __stdcall list_compute_table(Wrapper* self, UINT parameter, u64 gpu_handle) +void __stdcall list_compute_table_desktop(Wrapper* self, UINT parameter, u64 gpu_handle) { static LONG dropped; if (!self->own().list_open) return; @@ -2461,6 +4850,10 @@ void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, co count <= 8 - offset && offset + count <= (*pass.root)[parameter].constants_count) pass.constant_words_bound[parameter] |= static_cast(((1u << count) - 1) << offset); } +void __stdcall list_root_uav(Wrapper* self, UINT parameter, u64 address) +{ + if (parameter < 16) pass_of(self).root_address[parameter] = address; +} // List slot 47 (desktop 43 + 4), IASetIndexBuffer(view). void __stdcall list_index_buffer(Wrapper* self, const D3D12_INDEX_BUFFER_VIEW* view) { @@ -2480,5 +4873,203 @@ void __stdcall list_vertex_buffers(Wrapper* self, UINT start, UINT count, const // List slot 13, DrawIndexedInstanced(index count, instances, start index, base vertex, start instance). void __stdcall list_draw_indexed(Wrapper* self, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance) { - InterlockedIncrement(draw_translated(self, true, count, instances, start, base_vertex, start_instance) ? &translated_draws : &untranslated_draws); + const bool done = draw_translated(self, true, count, instances, start, base_vertex, start_instance); + InterlockedIncrement(done ? &translated_draws : &untranslated_draws); + if (trace_frame_active) { + const Pass& pass = pass_of(self); + note_traced_target(self, pass.target0, done); + const D3D12_RESOURCE_DESC rd = pass.target0 ? pass.target0->GetDesc() : D3D12_RESOURCE_DESC{}; + log("x2w-frame draw-indexed %u %s target %p %llux%u fmt %d key %016llx %s", count, done ? "drawn" : "NOT drawn", + static_cast(pass.target0), static_cast(rd.Width), rd.Height, rd.Format, last_draw_key, + done ? "" : (last_draw_why ? last_draw_why : "draw failed")); + } +} + +void __stdcall list_copy_buffer(Wrapper* self, Wrapper* dest, u64 dest_offset, Wrapper* source, u64 source_offset, u64 bytes); + +void copy_watch_note(const char* path, u64 to, u64 from, u64 bytes, const char* outcome) +{ + static u64 watched[4]; + static int count = [] { + char text[128]{}; + int n = 0; + if (GetEnvironmentVariableA("X2W_D3D12_COPY_WATCH", text, sizeof(text))) { + for (char* at = text; *at && n < 4;) { + char* end = nullptr; + const u64 value = std::strtoull(at, &end, 16); + if (end == at) break; + if (value) watched[n++] = value; + at = *end == ',' ? end + 1 : end; + } + log("x2w-copy X2W_D3D12_COPY_WATCH: %d address(es) watched (%s)", n, text); + } + return n; + }(); + static LONG lines[4]; + for (int i = 0; i < count; ++i) + if (to && bytes && to < watched[i] + 0x100 && watched[i] < to + bytes && first_calls(lines[i], 64)) { + unsigned char head[32]{}; + char text[3 * 32 + 1] = ""; + if (from && x2w_local::readable(reinterpret_cast(from), bytes < 32 ? bytes : 32)) { + std::memcpy(head, reinterpret_cast(from), bytes < 32 ? bytes : 32); + hex_text(head, bytes < 32 ? bytes : 32, text, sizeof(text)); + } + log("x2w-copy watch 0x%llx: %s copy to 0x%llx from 0x%llx bytes 0x%llx frame %ld: %s; source [%s]", watched[i], path, to, from, + bytes, frame_number, outcome, text); + } +} +bool copy_title_bytes(unsigned char* dest, const unsigned char* source, std::size_t bytes) noexcept; // d3d12_copy_buffer.inl +void note_issued_dispatch(ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z, bool indirect); // d3d12_xs_device.cpp (DRED report) +extern thread_local u64 cx_issue_key; +extern thread_local char cx_issue_path; +constexpr char copy_gpu_source[] = R"( +RWByteAddressBuffer from : register(u0); +RWByteAddressBuffer to : register(u1); +cbuffer c : register(b0) { uint from_at; uint to_at; uint words; uint step; }; +[numthreads(64, 1, 1)] void cs(uint3 id : SV_DispatchThreadID) +{ + for (uint i = id.x; i < words; i += step) to.Store(to_at + i * 4, from.Load(from_at + i * 4)); +} +)"; +ID3D12RootSignature* copy_gpu_root; +ID3D12PipelineState* copy_gpu_pso; +bool ensure_copy_gpu() +{ + static SRWLOCK lock = SRWLOCK_INIT; + static bool failed; + if (copy_gpu_pso) return true; + AcquireSRWLockExclusive(&lock); + if (!copy_gpu_pso && !failed) { + ID3D12Device* device = device_of(the_device); + ID3DBlob *code = nullptr, *errors = nullptr, *serialized = nullptr; + HRESULT hr = D3DCompile(copy_gpu_source, sizeof(copy_gpu_source) - 1, "copy_gpu", nullptr, nullptr, "cs", "cs_5_0", + D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, &code, &errors); + if (FAILED(hr) && errors) log("x2w-copy-gpu compile: %.400s", static_cast(errors->GetBufferPointer())); + D3D12_ROOT_PARAMETER params[3]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[0].Descriptor.ShaderRegister = 0; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor.ShaderRegister = 1; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[2].Constants.Num32BitValues = 4; + for (auto& p : params) p.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC root_desc{3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + if (SUCCEEDED(hr)) hr = D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, nullptr); + ID3D12RootSignature* root = nullptr; + if (SUCCEEDED(hr)) hr = device->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), IID_PPV_ARGS(&root)); + ID3D12PipelineState* pso = nullptr; + if (SUCCEEDED(hr)) { + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root; + desc.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + hr = device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso)); + } + if (code) code->Release(); + if (errors) errors->Release(); + if (serialized) serialized->Release(); + if (SUCCEEDED(hr)) { + copy_gpu_root = root; + copy_gpu_pso = pso; + } else { + if (root) root->Release(); + failed = true; + } + log("x2w-copy-gpu copy pipeline: 0x%08lx", static_cast(hr)); + } + ReleaseSRWLockExclusive(&lock); + return copy_gpu_pso != nullptr; +} + +void __stdcall list_copy_buffer_gpu(Wrapper* self, Wrapper* dest, u64 dest_offset, Wrapper* source, u64 source_offset, u64 bytes) +{ + auto* const to = dest && dest->own().kind == resource_kind ? static_cast(dest->own().title_memory) : nullptr; + auto* const from = source && source->own().kind == resource_kind ? static_cast(source->own().title_memory) : nullptr; + ID3D12GraphicsCommandList* list = recording(self); + const u64 to_address = to ? reinterpret_cast(to) + dest_offset : 0; + const u64 from_address = from ? reinterpret_cast(from) + source_offset : 0; + ID3D12Resource *to_window = nullptr, *from_window = nullptr; + u64 to_at = 0, from_at = 0; + int reason = -1; + if (!list) reason = cf_no_list; + else if (!to || !from) reason = cf_no_title_memory; + else if (!bytes || bytes > (u64{256} << 20) || dest_offset > (u64{1} << 40) || source_offset > (u64{1} << 40)) reason = cf_range; + else if ((to_address | from_address | bytes) & 3) reason = cf_unaligned; + else if (!desktop_range(to_address, bytes, &to_window, &to_at)) reason = cf_dest_unresolved; + else if (!desktop_range(from_address, bytes, &from_window, &from_at)) reason = cf_source_unresolved; + else if (to_window == from_window && to_at < from_at + bytes && from_at < to_at + bytes) reason = cf_overlap; + const bool copy_list = list && list->GetType() == D3D12_COMMAND_LIST_TYPE_COPY; + if (reason < 0 && copy_list && to_window == from_window) reason = cf_copy_list_same; + else if (reason < 0 && !copy_list && !ensure_copy_gpu()) reason = cf_no_pipeline; + static LONG shown; + if (reason >= 0) { + InterlockedIncrement(&cg_fallback[reason]); + if (first_calls(shown, 16)) + log("x2w-copy-gpu CopyBufferRegion title %p <- %p bytes 0x%llx: record-time fallback: %s", static_cast(to ? to + dest_offset : nullptr), + static_cast(from ? from + source_offset : nullptr), bytes, copy_fallback_names[reason]); + list_copy_buffer(self, dest, dest_offset, source, source_offset, bytes); + return; + } + // A source the GPU never wrote (CPU-filled upload memory) is also copied at record time, so the paths that read + // the destination's title memory when the title records (vertex/index ring copies, misaligned srvs, texture + // uploads) see what X2W_D3D12_COPY_BUFFER=1 gave them; the GPU copy then writes the same bytes in list order. + lock_draw(100000 + __LINE__); + const bool source_gpu_written = gpu_written_overlaps(from_address, bytes); + ReleaseSRWLockExclusive(&draw_lock); + copy_watch_note("gpu", to_address, from_address, bytes, source_gpu_written ? "GPU copy (source GPU-written)" : "GPU copy + record-time copy"); + if (!source_gpu_written && x2w_local::readable(from + source_offset, static_cast(bytes)) && + copy_title_bytes(to + dest_offset, from + source_offset, static_cast(bytes))) + InterlockedIncrement(&cg_record_too); + if (copy_list) { + // A copy-type list holds no compute or draw work: windows there are only ever moved by these copies, so the + // tracked states are exact (back to COMMON at Close). + require_state(self, from_window, D3D12_RESOURCE_STATE_COPY_SOURCE); + require_state(self, to_window, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(to_window, to_at, from_window, from_at, bytes); + InterlockedIncrement(&cg_copy_list); + } else { + // Both windows in UNORDERED_ACCESS in this list's tracked states (from whatever this list's draws and copies + // left them in; moved back to COMMON at Close). + require_state(self, from_window, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + require_state(self, to_window, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + // Root UAVs at 256-byte steps inside the windows; the remainder goes to the shader as byte offsets. + const u64 to_base = to_at & ~u64{255}, from_base = from_at & ~u64{255}; + const std::uint32_t words = static_cast(bytes / 4); + const UINT groups = words / 64 + 1 > 4096 ? 4096 : words / 64 + 1; + const std::uint32_t values[4] = {static_cast(from_at - from_base), static_cast(to_at - to_base), words, groups * 64}; + D3D12_RESOURCE_BARRIER uav{}; + uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &uav); + list->SetPipelineState(copy_gpu_pso); + list->SetComputeRootSignature(copy_gpu_root); + list->SetComputeRootUnorderedAccessView(0, from_window->GetGPUVirtualAddress() + from_base); + list->SetComputeRootUnorderedAccessView(1, to_window->GetGPUVirtualAddress() + to_base); + list->SetComputeRoot32BitConstants(2, 4, values, 0); + // The copy pass is a Dispatch op in DRED too; record it (path 'b', key 0) so the report's Dispatch op count matches. + const u64 issue_key = cx_issue_key; + const char issue_path = cx_issue_path; + cx_issue_key = 0; + cx_issue_path = 'b'; + note_issued_dispatch(list, groups, 1, 1, false); + cx_issue_key = issue_key; + cx_issue_path = issue_path; + gpu_time::mark(self, list, gpu_time::c_copy, bytes, false); + list->Dispatch(groups, 1, 1); + gpu_time::mark(self, list, gpu_time::c_copy, bytes, true); + list->ResourceBarrier(1, &uav); + // Graphics work after this point: a title pipeline with a desktop pipeline expects its state back (translated + // draws and compute set theirs on every call). + const Pass& pass = pass_of(self); + if (pass.pipeline_real && pass.pipeline) list->SetPipelineState(static_cast(pass.pipeline->own().real)); + } + lock_draw(100000 + __LINE__); + note_gpu_written(to_address, bytes); + report_draw_rt(); + ReleaseSRWLockExclusive(&draw_lock); + InterlockedIncrement(&cg_gpu); + if (to_window == from_window) InterlockedIncrement(&cg_same_window); + InterlockedAdd64(&cg_bytes, static_cast(bytes)); + if (first_calls(shown, 16)) + log("x2w-copy-gpu CopyBufferRegion title %p <- %p bytes 0x%llx: on the GPU, window %p +0x%llx <- window %p +0x%llx", + static_cast(to + dest_offset), static_cast(from + source_offset), bytes, static_cast(to_window), to_at, + static_cast(from_window), from_at); } diff --git a/src/startup_stubs/d3d12_gpu_time.inl b/src/startup_stubs/d3d12_gpu_time.inl new file mode 100644 index 0000000000..b29edb4ebf --- /dev/null +++ b/src/startup_stubs/d3d12_gpu_time.inl @@ -0,0 +1,343 @@ + +namespace gpu_time { +// enum Class (c_cx, c_draw, c_c62, c_copy, c_list, c_count) is declared with the forward declarations in d3d12_xs_device.cpp +const char* const class_names[c_count] = {"cx", "draw", "c62", "copy", "list"}; +struct Item { u64 key; int cls; }; +struct ListState { + ID3D12QueryHeap* heap = nullptr; + ID3D12Resource* readback[2] = {}; + std::vector items; // this recording, in query order (item i: queries 2i, 2i + 1) + int open = -1; // the item whose end is still missing (cx, draw, c62, copy) + int open_list = -1; // the recording span whose end is still missing + int slot = 0; // readback buffer of this recording + int type = 0; // desktop list type (direct 0, compute 2) + bool resolved = false; // resolved at Close, not yet submitted + struct Pending { + std::vector items; + ID3D12Fence* fence = nullptr; + UINT64 value = 0, frequency = 0; + int slot = 0; + int type = 0; + }; + Pending pending[2]; // per readback buffer + bool has_pending[2] = {}; + bool failed = false; +}; +struct QueueFence { ID3D12Fence* fence = nullptr; UINT64 value = 0; }; +struct KeyTime { double total_ms = 0, max_ms = 0; LONG64 calls = 0, over_1ms = 0; }; + +SRWLOCK lock = SRWLOCK_INIT; +std::unordered_map& lists() { static std::unordered_map m; return m; } +std::unordered_map& fences() { static std::unordered_map m; return m; } +std::unordered_map& times(int cls) { static std::unordered_map m[c_count]; return m[cls]; } +double untimed_ms[4], span_ms[4], cx_ms[4]; // by list type (direct 0, bundle 1, compute 2, copy 3) +LONG64 spans[4], cx_calls[4]; +LONG timed, over_cap, overwritten, harvested, failures; + +bool classes() +{ + static const bool enabled = [] { + const bool e = x2w_local::env_on("X2W_GPU_TIME_CLASSES"); + if (e) log("x2w-gpu time X2W_GPU_TIME_CLASSES: also timing translated draws, slot-62 dispatches, GPU copies and list spans"); + return e; + }(); + return enabled; +} +bool on() +{ + static const bool enabled = [] { + const bool e = x2w_local::env_on("X2W_CX_GPU_TIME") || classes(); + if (e) log("x2w-cx X2W_CX_GPU_TIME: timestamps around translated dispatches, read back after the queue's fence passes"); + return e; + }(); + return enabled; +} +UINT cap() { return classes() ? 4096 : 2048; } // items per recording + +bool ensure(ListState& s, ID3D12GraphicsCommandList* list) +{ + if (s.heap) return true; + if (s.failed) return false; + const D3D12_COMMAND_LIST_TYPE type = list->GetType(); + ID3D12Device* device = device_of(the_device); + D3D12_QUERY_HEAP_DESC qd{D3D12_QUERY_HEAP_TYPE_TIMESTAMP, 2 * cap(), 0}; + HRESULT hr = (type == D3D12_COMMAND_LIST_TYPE_DIRECT || type == D3D12_COMMAND_LIST_TYPE_COMPUTE) + ? device->CreateQueryHeap(&qd, IID_PPV_ARGS(&s.heap)) : E_NOTIMPL; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = u64{2} * cap() * 8; + buffer.Height = 1; + buffer.DepthOrArraySize = 1; + buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + for (int i = 0; i < 2 && SUCCEEDED(hr); ++i) + hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&s.readback[i])); + if (SUCCEEDED(hr)) { + s.type = static_cast(type) & 3; + return true; + } + if (s.heap) s.heap->Release(), s.heap = nullptr; + for (auto*& r : s.readback) + if (r) r->Release(), r = nullptr; + s.failed = true; + InterlockedIncrement(&failures); + static LONG logged; + if (first_calls(logged, 4)) log("x2w-cx gpu time: query heap or readback for a list type %d failed 0x%08lx", static_cast(type), static_cast(hr)); + return false; +} + +void add(int cls, u64 key, double ms) +{ + KeyTime& t = times(cls)[key]; + t.total_ms += ms; + ++t.calls; + if (ms > 1.0) ++t.over_1ms; + if (ms > t.max_ms) t.max_ms = ms; +} + +// Reads every pending result whose fence has passed (lock held). +void harvest_locked() +{ + for (auto& entry : lists()) { + ListState& s = entry.second; + for (int b = 0; b < 2; ++b) { + if (!s.has_pending[b]) continue; + ListState::Pending& p = s.pending[b]; + if (p.fence->GetCompletedValue() < p.value) continue; + s.has_pending[b] = false; + const std::size_t n = p.items.size(); + const D3D12_RANGE range{0, n * 16}; + void* mapped = nullptr; + if (n && p.frequency && SUCCEEDED(s.readback[b]->Map(0, &range, &mapped))) { + const auto* ticks = static_cast(mapped); + double inside = 0, span = -1; + int type = 0; + for (std::size_t i = 0; i < n; ++i) { + if (ticks[2 * i + 1] < ticks[2 * i]) continue; // not written or wrapped + const double ms = static_cast(ticks[2 * i + 1] - ticks[2 * i]) * 1000.0 / static_cast(p.frequency); + add(p.items[i].cls, p.items[i].key, ms); + if (p.items[i].cls == c_list) span = ms, type = static_cast(p.items[i].key & 3); + else inside += ms; + if (p.items[i].cls == c_cx) cx_ms[p.type] += ms, ++cx_calls[p.type]; + } + if (span >= 0) { + span_ms[type] += span; + untimed_ms[type] += span > inside ? span - inside : 0; + ++spans[type]; + } + const D3D12_RANGE none{0, 0}; + s.readback[b]->Unmap(0, &none); + InterlockedIncrement(&harvested); + } + } + } +} + +// Opens (after == false) or closes the item of class `cls`; `drop` on the close forgets the item (nothing was +// recorded between the two marks). +void mark(Wrapper* self, ID3D12GraphicsCommandList* list, int cls, u64 key, bool after, bool drop) +{ + if (!on() || (cls != c_cx && !classes()) || !list) return; + AcquireSRWLockExclusive(&lock); + ListState& s = lists()[self]; + if (!after) { + if (s.open >= 0) { + // an item without its end (should not happen): forget it + if (s.open == static_cast(s.items.size()) - 1) s.items.pop_back(); + s.open = -1; + } + if (s.items.size() >= cap()) { + InterlockedIncrement(&over_cap); + } else if (ensure(s, list)) { + list->EndQuery(s.heap, D3D12_QUERY_TYPE_TIMESTAMP, static_cast(2 * s.items.size())); + s.open = static_cast(s.items.size()); + s.items.push_back({key, cls}); + } + } else if (s.open >= 0 && s.items[s.open].cls == cls) { + if (drop && s.open == static_cast(s.items.size()) - 1) { + s.items.pop_back(); // its begin query index is reused by the next item + } else { + list->EndQuery(s.heap, D3D12_QUERY_TYPE_TIMESTAMP, static_cast(2 * s.open + 1)); + InterlockedIncrement(&timed); + } + s.open = -1; + } + ReleaseSRWLockExclusive(&lock); +} + +// Around the Dispatch of execute_translated (d3d12_compute.inl). +void dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, bool after) { mark(self, list, c_cx, key, after, false); } + +// list_reset, after the desktop Reset: the recording span begins (X2W_GPU_TIME_CLASSES). +void list_begin(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + if (!on() || !classes() || !list) return; + const D3D12_COMMAND_LIST_TYPE type = list->GetType(); + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_COMPUTE) return; + AcquireSRWLockExclusive(&lock); + ListState& s = lists()[self]; + if (s.items.empty() && ensure(s, list)) { + list->EndQuery(s.heap, D3D12_QUERY_TYPE_TIMESTAMP, 0); + s.open_list = 0; + s.items.push_back({static_cast(type), c_list}); + } + ReleaseSRWLockExclusive(&lock); +} + +// list_close, before the desktop Close. +void close(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + if (!on()) return; + AcquireSRWLockExclusive(&lock); + const auto found = lists().find(self); + if (found != lists().end() && found->second.heap) { + ListState& s = found->second; + if (s.open >= 0) { // a begin without its end + if (s.open == static_cast(s.items.size()) - 1) s.items.pop_back(); + s.open = -1; + } + if (s.open_list >= 0) { + list->EndQuery(s.heap, D3D12_QUERY_TYPE_TIMESTAMP, static_cast(2 * s.open_list + 1)); + s.open_list = -1; + } + if (!s.items.empty()) { + s.slot = s.has_pending[0] && !s.has_pending[1] ? 1 : 0; + list->ResolveQueryData(s.heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, static_cast(2 * s.items.size()), s.readback[s.slot], 0); + s.resolved = true; + } + } + ReleaseSRWLockExclusive(&lock); +} + +// queue_execute, after the desktop ExecuteCommandLists. +void submitted(ID3D12CommandQueue* queue, const std::vector& wrappers) +{ + if (!on()) return; + AcquireSRWLockExclusive(&lock); + std::vector marked; + for (Wrapper* w : wrappers) { + const auto found = lists().find(w); + if (found != lists().end() && found->second.resolved && !found->second.items.empty()) marked.push_back(&found->second); + } + if (!marked.empty()) { + QueueFence& f = fences()[queue]; + if (!f.fence && FAILED(device_of(the_device)->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&f.fence)))) f.fence = nullptr; + UINT64 frequency = 0; + if (f.fence && SUCCEEDED(queue->GetTimestampFrequency(&frequency)) && SUCCEEDED(queue->Signal(f.fence, ++f.value))) { + for (ListState* s : marked) { + const int b = s->slot; + if (s->has_pending[b]) InterlockedIncrement(&overwritten); + s->pending[b] = {s->items, f.fence, f.value, frequency, b, s->type}; + s->has_pending[b] = true; + } + } else { + InterlockedIncrement(&failures); + } + } + harvest_locked(); + ReleaseSRWLockExclusive(&lock); + // Test knob (off by default): X2W_GPU_TIME_REPORT_SUBMITS= also writes the report every n submissions, for + // fixtures that never present. It first waits (at most 5 s) for this queue's timing fence so the report holds + // this submission's results; that wait is why the knob is for fixtures only. + static const LONG every = [] { + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_GPU_TIME_REPORT_SUBMITS", value, sizeof(value)); + return n && n < sizeof(value) ? static_cast(std::atoi(value)) : 0L; + }(); + static LONG submits; + if (every > 0 && InterlockedIncrement(&submits) % every == 0) { + AcquireSRWLockExclusive(&lock); + const auto found = fences().find(queue); + ID3D12Fence* fence = found != fences().end() ? found->second.fence : nullptr; + const UINT64 value = fence ? found->second.value : 0; + ReleaseSRWLockExclusive(&lock); + if (fence && fence->GetCompletedValue() < value) { + if (HANDLE done = CreateEventA(nullptr, FALSE, FALSE, nullptr)) { + if (SUCCEEDED(fence->SetEventOnCompletion(value, done))) WaitForSingleObject(done, 5000); + CloseHandle(done); + } + } + report(); + } +} + +// list_reset: a new recording. +void reset(Wrapper* self) +{ + if (!on()) return; + AcquireSRWLockExclusive(&lock); + harvest_locked(); + const auto found = lists().find(self); + if (found != lists().end()) { + found->second.items.clear(); + found->second.open = found->second.open_list = -1; + found->second.resolved = false; + } + ReleaseSRWLockExclusive(&lock); +} + +std::vector> sorted(std::unordered_map& m) +{ + std::vector> all(m.begin(), m.end()); + m.clear(); + std::sort(all.begin(), all.end(), [](const auto& a, const auto& b) { return a.second.total_ms > b.second.total_ms; }); + return all; +} + +// Every 300 frames. +void report() +{ + if (!on()) return; + std::vector> all[c_count]; + double untimed[4], span[4], cx_by_type[4]; + LONG64 span_count[4], cx_count_by_type[4]; + AcquireSRWLockExclusive(&lock); + harvest_locked(); + for (int c = 0; c < c_count; ++c) all[c] = sorted(times(c)); + for (int t = 0; t < 4; ++t) { + untimed[t] = untimed_ms[t], span[t] = span_ms[t], span_count[t] = spans[t], untimed_ms[t] = span_ms[t] = 0, spans[t] = 0; + cx_by_type[t] = cx_ms[t], cx_count_by_type[t] = cx_calls[t], cx_ms[t] = 0, cx_calls[t] = 0; + } + ReleaseSRWLockExclusive(&lock); + double total = 0; + LONG64 calls = 0; + for (const auto& entry : all[c_cx]) total += entry.second.total_ms, calls += entry.second.calls; + char line[2048]; + int n = std::snprintf(line, sizeof(line), "x2w-cx gpu time (300 frames): %.1f ms in %lld timed dispatches of %zu keys; top:", total, calls, + all[c_cx].size()); + for (std::size_t i = 0; i < all[c_cx].size() && i < 10; ++i) + n += std::snprintf(line + n, sizeof(line) - n, " %016llx %.2f ms/%lld (max %.3f)", all[c_cx][i].first, all[c_cx][i].second.total_ms, + all[c_cx][i].second.calls, all[c_cx][i].second.max_ms); + log("%s", line); + log("x2w-cx gpu time counters: timed %ld, over %u per list %ld, results read %ld, overwritten before read %ld, failures %ld", + InterlockedExchange(&timed, 0), cap(), InterlockedExchange(&over_cap, 0), InterlockedExchange(&harvested, 0), + InterlockedExchange(&overwritten, 0), InterlockedExchange(&failures, 0)); + log("x2w-cx gpu time by list type: direct %.1f ms/%lld, compute %.1f ms/%lld", cx_by_type[0], cx_count_by_type[0], cx_by_type[2], + cx_count_by_type[2]); + if (!classes()) return; + n = std::snprintf(line, sizeof(line), "x2w-gpu time (300 frames) by class:"); + for (int c = 0; c < c_list; ++c) { + double t = 0, over = 0; + LONG64 k = 0; + for (const auto& entry : all[c]) t += entry.second.total_ms, k += entry.second.calls, over += static_cast(entry.second.over_1ms); + n += std::snprintf(line + n, sizeof(line) - n, " %s %.1f ms/%lld (%.0f over 1 ms, %zu keys);", class_names[c], t, k, over, all[c].size()); + } + static const char* const type_names[4] = {"direct", "bundle", "compute", "copy"}; + for (int t = 0; t < 4; ++t) + if (span_count[t]) + n += std::snprintf(line + n, sizeof(line) - n, " %s lists %.1f ms/%lld spans, untimed inside %.1f ms;", type_names[t], span[t], span_count[t], + untimed[t]); + log("%s", line); + for (int c = 0; c < c_list; ++c) { + if (all[c].empty()) continue; + n = std::snprintf(line, sizeof(line), "x2w-gpu time %s top (ms/calls, max, over 1 ms):", class_names[c]); + for (std::size_t i = 0; i < all[c].size() && i < 10; ++i) + n += std::snprintf(line + n, sizeof(line) - n, " %016llx %.2f/%lld (max %.3f, %lld)", all[c][i].first, all[c][i].second.total_ms, + all[c][i].second.calls, all[c][i].second.max_ms, all[c][i].second.over_1ms); + log("%s", line); + } +} +} // namespace gpu_time diff --git a/src/startup_stubs/d3d12_indirect.inl b/src/startup_stubs/d3d12_indirect.inl new file mode 100644 index 0000000000..84c3c7e08f --- /dev/null +++ b/src/startup_stubs/d3d12_indirect.inl @@ -0,0 +1,759 @@ + +// Signature type index for counters: 0 Draw, 1 DrawIndexed, 2 Dispatch, 3 DispatchMesh, 4 other. +enum IndirectType { itype_draw, itype_indexed, itype_dispatch, itype_mesh, itype_other, itype_types }; +constexpr const char* indirect_type_names[itype_types] = {"draw", "indexed", "dispatch", "mesh", "other"}; +int indirect_type_of(UINT argument_type) +{ + switch (argument_type) { + case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: return itype_draw; + case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: return itype_indexed; + case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: return itype_dispatch; + case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH: return itype_mesh; + default: return itype_other; + } +} + +// Why a call was not executed. "not-implemented": no execution path exists yet for the type. +enum IndirectSkip { + skip_not_recording, // the list is not recording a desktop list (not render mode, or closed) + skip_unknown_signature, // the signature was not created through device slot 41 + skip_not_implemented, // no execution path for this type (yet) + skip_switched_off, // the type's env switch is off + skip_no_pipeline, // the bound pipeline has no desktop translation (or the path refused the call) + skip_unresolved_buffer, // argument or count buffer has no in-place desktop window (or no index data) + skip_zero_count, // max count 0 + skip_topology, // a draw with a console-only topology (rect list) + skip_no_ring, // the private argument ring could not be created or the record is too large + skip_no_guard, // the argument guard pass could not be created (calls are never executed unguarded) + skip_reasons +}; +constexpr const char* indirect_skip_names[skip_reasons] = {"not-recording", "unknown-signature", "not-implemented", "off", + "no-pipeline", "unresolved-buffer", "zero-count", "unsupported-topology", + "no-ring", "no-guard"}; + +struct IndirectCounters { + LONG calls[itype_types]; + LONG executed[itype_types]; + LONG skipped[skip_reasons][itype_types]; + LONG with_count_buffer; // calls that pass a count resource + LONG max_count_above_one; // calls with max count > 1 + LONG max_count_max; // largest max count seen +}; +IndirectCounters indirect_counts; + +void indirect_skip(int type, IndirectSkip why) { InterlockedIncrement(&indirect_counts.skipped[why][type]); } + +// The signature's stride and last argument type, through a one-entry per-thread cache in front of the +// shared signature table (about 5000 calls a frame use five signatures). +bool indirect_signature(const void* signature, UINT* stride, UINT* argument_type) +{ + thread_local const void* last = nullptr; + thread_local UINT last_stride = 0, last_type = 0; + if (signature && signature == last) { + *stride = last_stride; + *argument_type = last_type; + return true; + } + bool found = false; + AcquireSRWLockShared(&signature_lock); + const auto it = signature_infos().find(signature); + if (it != signature_infos().end() && !it->second.args.empty()) { + *stride = it->second.stride; + *argument_type = static_cast(it->second.args.back().Type); + found = true; + } + ReleaseSRWLockShared(&signature_lock); + if (found) { + last = signature; + last_stride = *stride; + last_type = *argument_type; + } + return found; +} + +void max_count_seen(UINT max_count) +{ + if (max_count > 1) InterlockedIncrement(&indirect_counts.max_count_above_one); + LONG seen = indirect_counts.max_count_max; + while (static_cast(max_count) > seen) { + const LONG previous = InterlockedCompareExchange(&indirect_counts.max_count_max, static_cast(max_count), seen); + if (previous == seen) break; + seen = previous; + } +} + +// ---- Execution ------------------------------------------------------------------------------- +// +// Per call: the argument record (and count dword) is copied from the window over the title's memory +// into a private argument ring, and ExecuteIndirect reads the ring (DESIGN.md section 3): +// window UAV -> COPY_SOURCE, ring COMMON -> COPY_DEST; copy; window -> UAV, ring -> INDIRECT_ARGUMENT; +// ExecuteIndirect; [read-back copy]; ring -> COMMON. +// A window rests in COMMON or UAV-promoted (compute binds it as UAV); UAV is a valid BeforeState for both. + +// X2W_INDIRECT_OFF=1: nothing executed. X2W_INDIRECT_DISPATCH=0 / X2W_INDIRECT_MESH=0: per type (default on). +// Draw/DrawIndexed: default OFF until a test or run has exercised it; X2W_INDIRECT_DRAW=1 turns it on. +// X2W_INDIRECT_READBACK=: read back the first n executed records per report. +bool indirect_env_zero(const char* name) +{ + char value[8]{}; + return GetEnvironmentVariableA(name, value, sizeof(value)) && value[0] == '0'; +} +bool indirect_type_enabled(int type) +{ + static const bool off = x2w_local::env_on("X2W_INDIRECT_OFF"); + static const bool dispatch = !indirect_env_zero("X2W_INDIRECT_DISPATCH"); + static const bool draw = x2w_local::env_on("X2W_INDIRECT_DRAW"); + static const bool mesh = !indirect_env_zero("X2W_INDIRECT_MESH"); + if (off) return false; + return type == itype_dispatch ? dispatch : type == itype_draw || type == itype_indexed ? draw : type == itype_mesh ? mesh : false; +} +LONG indirect_readback_wanted() +{ + static const LONG wanted = [] { + char value[16]{}; + const LONG n = GetEnvironmentVariableA("X2W_INDIRECT_READBACK", value, sizeof(value)) ? std::atol(value) : 0L; + return n < 0 ? 0L : n > 4096 ? 4096L : n; + }(); + return wanted; +} + +// Mesh pipelines (agent mesh): binds the translated mesh pipeline and root state on list `self`, then +// calls indirect_issue(self, list) and returns true when it issued. Null until mesh provides one. +using IndirectMeshHook = bool (*)(Wrapper* self, ID3D12GraphicsCommandList* list); +IndirectMeshHook indirect_mesh_hook = nullptr; +bool mesh_prepare(Wrapper* self, ID3D12GraphicsCommandList* list); +void mesh_trace_call(Wrapper* self, bool drawn, const Translation* tr, const char* why); + +constexpr u64 indirect_ring_max_take = u64{1} << 20; // one call's record + count, as before (a sixteenth of 16 MiB) +// The chunk holding `bytes` (whole 256-byte slots) at *offset, or nullptr when refused (too large, or the cap). +ID3D12Resource* indirect_ring_take(u64 bytes, u64* offset) +{ + return bytes && bytes <= indirect_ring_max_take ? reserve_indirect_ring(bytes, offset) : nullptr; +} + +// ---- Argument guard ---------------------------------------------------------------------------- +// +// GPU-written records may be garbage while the shaders that produce them are wrong or untranslated, and +// a Dispatch with huge group counts hangs the GPU (device removed). Every record copied into the ring is +// checked ON THE GPU by one tiny compute pass before ExecuteIndirect reads it; a record over the bounds +// is zeroed (a zero-group dispatch / zero-count draw does nothing) and counted in a CPU-visible counter +// that report_indirect reads once per report. No CPU read-back per call. +// Dispatch / DispatchMesh {x, y, z}: each <= X2W_INDIRECT_MAX_GROUPS (default 65535, the desktop limit) +// and x*y*z <= X2W_INDIRECT_MAX_GROUP_PRODUCT (default 2^24; DispatchMesh also <= 2^22, the desktop limit). +// Draw {vertices, instances, ..} / DrawIndexed {indices, instances, ..}: count <= X2W_INDIRECT_MAX_VERTICES +// (default 2^24), instances <= X2W_INDIRECT_MAX_INSTANCES (default 2^16), count*instances <= +// X2W_INDIRECT_MAX_DRAW_PRODUCT (default 2^26). +// X2W_INDIRECT_GUARD=0 executes unguarded (debugging only). When the guard cannot be created, calls are +// skipped ("no-guard"), never executed unguarded. +// Not covered: a record within the bounds can still make a shader loop or fault (wrong root data, +// out-of-range addresses); start offsets (StartIndex, BaseVertex, StartInstance) are not checked +// (index fetches are bounds-checked by the desktop); the count dword is not checked (ExecuteIndirect +// already takes min(count, max count)). +UINT indirect_env_u32(const char* name, UINT fallback) +{ + char value[16]{}; + if (!GetEnvironmentVariableA(name, value, sizeof(value)) || !value[0]) return fallback; + const unsigned long long n = std::strtoull(value, nullptr, 0); + return n && n <= 0xffffffffull ? static_cast(n) : fallback; +} +struct IndirectBounds { + UINT groups, group_product, mesh_product, vertices, instances, draw_product; +}; +const IndirectBounds& indirect_bounds() +{ + static const IndirectBounds b = [] { + IndirectBounds v{}; + v.groups = indirect_env_u32("X2W_INDIRECT_MAX_GROUPS", 65535); + v.group_product = indirect_env_u32("X2W_INDIRECT_MAX_GROUP_PRODUCT", 1u << 24); + v.mesh_product = v.group_product < (1u << 22) ? v.group_product : (1u << 22); + v.vertices = indirect_env_u32("X2W_INDIRECT_MAX_VERTICES", 1u << 24); + v.instances = indirect_env_u32("X2W_INDIRECT_MAX_INSTANCES", 1u << 16); + v.draw_product = indirect_env_u32("X2W_INDIRECT_MAX_DRAW_PRODUCT", 1u << 26); + return v; + }(); + return b; +} +bool indirect_guard_wanted() +{ + static const bool wanted = !indirect_env_zero("X2W_INDIRECT_GUARD"); + return wanted; +} + +constexpr char indirect_guard_source[] = R"( +RWByteAddressBuffer ring : register(u0); +RWByteAddressBuffer zeroed : register(u1); +cbuffer Bounds : register(b0) { uint stride; uint records; uint kind; uint counter; uint each; uint product; uint each2; uint unused; }; +[numthreads(64, 1, 1)] +void cs(uint3 id : SV_DispatchThreadID) +{ + if (id.x >= records) return; + const uint at = id.x * stride; + bool bad = false; + if (kind == 0) { + const uint3 g = ring.Load3(at); + bad = g.x > each || g.y > each || g.z > each; + if (!bad && g.x != 0 && g.y > product / g.x) bad = true; + const uint xy = g.x * g.y; + if (!bad && xy != 0 && g.z > product / xy) bad = true; + if (bad) ring.Store3(at, uint3(0, 0, 0)); + } else { + const uint2 d = ring.Load2(at); + bad = d.x > each || d.y > each2 || (d.x != 0 && d.y > product / d.x); + if (bad) ring.Store2(at, uint2(0, 0)); + } + if (bad) { + uint previous; + zeroed.InterlockedAdd(counter * 4, 1, previous); + } +} +)"; +ID3D12RootSignature* indirect_guard_root; +ID3D12PipelineState* indirect_guard_pso; +ID3D12Resource* indirect_guard_counter; // 8 dwords: records zeroed, by counter type +const volatile std::uint32_t* indirect_guard_words; // mapped (CPU-visible custom heap), or null +std::uint32_t indirect_guard_reported[itype_types]; +bool ensure_indirect_guard() +{ + static SRWLOCK lock = SRWLOCK_INIT; + static bool failed; + if (indirect_guard_pso) return true; + AcquireSRWLockExclusive(&lock); + if (!indirect_guard_pso && !failed) { + ID3D12Device* device = device_of(the_device); + ID3DBlob *code = nullptr, *errors = nullptr, *serialized = nullptr; + HRESULT hr = D3DCompile(indirect_guard_source, sizeof(indirect_guard_source) - 1, "indirect_guard", nullptr, nullptr, "cs", + "cs_5_0", D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, &code, &errors); + if (FAILED(hr) && errors) log("x2w-indirect guard compile: %.400s", static_cast(errors->GetBufferPointer())); + D3D12_ROOT_PARAMETER params[3]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[0].Descriptor.ShaderRegister = 0; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor.ShaderRegister = 1; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[2].Constants.Num32BitValues = 8; + for (auto& p : params) p.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC root_desc{3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + if (SUCCEEDED(hr)) hr = D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, nullptr); + ID3D12RootSignature* root = nullptr; + if (SUCCEEDED(hr)) + hr = device->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), IID_PPV_ARGS(&root)); + ID3D12PipelineState* pso = nullptr; + if (SUCCEEDED(hr)) { + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root; + desc.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + hr = device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso)); + } + // The counter: a CPU-visible custom heap (write-back, system memory) so a report reads it without a + // copy; if the adapter refuses, a default-heap counter (the guard still runs, counts are not shown). + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 64; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + ID3D12Resource* counter = nullptr; + void* mapped = nullptr; + HRESULT counter_hr = E_FAIL; + if (SUCCEEDED(hr)) { + const D3D12_HEAP_PROPERTIES visible{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0}; + counter_hr = device->CreateCommittedResource(&visible, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&counter)); + if (SUCCEEDED(counter_hr) && SUCCEEDED(counter->Map(0, nullptr, &mapped))) { + std::memset(mapped, 0, 64); + } else { + mapped = nullptr; + if (counter) counter->Release(), counter = nullptr; + const D3D12_HEAP_PROPERTIES local{D3D12_HEAP_TYPE_DEFAULT}; + hr = device->CreateCommittedResource(&local, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&counter)); + } + } + const IndirectBounds& b = indirect_bounds(); + log("x2w-indirect argument guard -> 0x%08lx (counter %s 0x%08lx): groups <= %u each, product <= %u (mesh %u); draws count <= %u, " + "instances <= %u, product <= %u", + static_cast(hr), mapped ? "visible" : "not visible", static_cast(counter_hr), b.groups, + b.group_product, b.mesh_product, b.vertices, b.instances, b.draw_product); + if (code) code->Release(); + if (errors) errors->Release(); + if (serialized) serialized->Release(); + if (SUCCEEDED(hr) && pso && root && counter) { + indirect_guard_root = root; + indirect_guard_counter = counter; + indirect_guard_words = static_cast(mapped); + indirect_guard_pso = pso; + } else { + if (pso) pso->Release(); + if (root) root->Release(); + if (counter) counter->Release(); + failed = true; + } + } + ReleaseSRWLockExclusive(&lock); + return indirect_guard_pso != nullptr; +} +// Records the guard pass over `records` records at ring offset `slot` (ring in UNORDERED_ACCESS). +void indirect_guard(ID3D12GraphicsCommandList* list, ID3D12Resource* ring, int type, u64 slot, UINT stride, UINT records) +{ + const IndirectBounds& b = indirect_bounds(); + const bool groups = type == itype_dispatch || type == itype_mesh; + const UINT constants[8] = {stride, records, groups ? 0u : 1u, static_cast(type), + groups ? b.groups : b.vertices, groups ? (type == itype_mesh ? b.mesh_product : b.group_product) : b.draw_product, + b.instances, 0}; + list->SetPipelineState(indirect_guard_pso); + list->SetComputeRootSignature(indirect_guard_root); + list->SetComputeRootUnorderedAccessView(0, ring->GetGPUVirtualAddress() + slot); + list->SetComputeRootUnorderedAccessView(1, indirect_guard_counter->GetGPUVirtualAddress()); + list->SetComputeRoot32BitConstants(2, 8, constants, 0); + const u64 issue_key = cx_issue_key; + const char issue_path = cx_issue_path; + cx_issue_key = 0; + cx_issue_path = 'g'; + note_issued_dispatch(list, (records + 63) / 64, 1, 1, false); + cx_issue_key = issue_key; + cx_issue_path = issue_path; + list->Dispatch((records + 63) / 64, 1, 1); +} + +// Read-back of executed records (X2W_INDIRECT_READBACK): 32-byte slots, [0] marker copied from the upload +// ring after the record, [1..7] the first 28 bytes of the record as ExecuteIndirect read it. +constexpr UINT indirect_readback_slots = 4096; +ID3D12Resource* indirect_readback; +const std::uint32_t* indirect_readback_words; +volatile LONG indirect_readback_used; +LONG indirect_readback_generation = 1; +unsigned char indirect_readback_type[indirect_readback_slots]; +bool ensure_indirect_readback() +{ + static SRWLOCK lock = SRWLOCK_INIT; + static bool failed; + if (indirect_readback_words) return true; + AcquireSRWLockExclusive(&lock); + if (!indirect_readback_words && !failed) { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = u64{indirect_readback_slots} * 32; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ID3D12Resource* created = nullptr; + void* mapped = nullptr; + HRESULT hr = device_of(the_device)->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&created)); + if (SUCCEEDED(hr)) hr = created->Map(0, nullptr, &mapped); + log("x2w-indirect read-back buffer (%u records) -> 0x%08lx", indirect_readback_slots, static_cast(hr)); + if (SUCCEEDED(hr)) { + indirect_readback = created; + indirect_readback_words = static_cast(mapped); + } else { + failed = true; + } + } + ReleaseSRWLockExclusive(&lock); + return indirect_readback_words != nullptr; +} + +// The window and window offset of [offset, offset + bytes) of a buffer wrapper's title memory. The +// lookup is keyed on the wrapper's whole range (cached per frame by desktop_range), so the thousands +// of records a frame do not each miss the cache. +bool indirect_window(Wrapper* resource, u64 offset, u64 bytes, ID3D12Resource** window, u64* at) +{ + if (!resource || resource->own().kind != resource_kind || !resource->own().title_memory) return false; + const u64 base = reinterpret_cast(resource->own().title_memory); + u64 width = 0; + if (auto* real = static_cast(resource->own().real)) { + const D3D12_RESOURCE_DESC desc = real->GetDesc(); + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) width = desc.Width; + } + if (width && offset <= width && bytes <= width - offset && desktop_range(base, width, window, at)) { + *at += offset; + return true; + } + return desktop_range(base + offset, bytes, window, at); +} + +// The call being executed on this thread, handed to the dispatch / draw / mesh path, which binds the +// pipeline and then calls indirect_issue instead of its direct Dispatch / Draw. +struct IndirectPending { + Wrapper* list; + int type; + ID3D12CommandSignature* signature; + UINT stride, max_count; + ID3D12Resource* args_window; + u64 args_at; + ID3D12Resource* count_window; // null: no count buffer + u64 count_at; + bool issued; + IndirectSkip refused; // set by an issue path that refused the call + // Set by indirect_stage: the record (and count) sit in the ring at `slot`, checked by the guard; the + // ring is in `ring_state` on this list until indirect_issue / indirect_unstage returns it to COMMON. + bool staged; + ID3D12Resource* ring; + u64 slot, ring_count_at; + D3D12_RESOURCE_STATES ring_state; +}; +thread_local IndirectPending* indirect_current; +thread_local const unsigned char* mesh_trace_record; +thread_local UINT mesh_trace_stride, mesh_trace_max; +// Also outside the traced frame while an X2W_MESH_DUMP_INPUTS key is not dumped yet or X2W_MESH_STATS_FRAMES collects +// (d3d12_mesh.inl): both select by the record's group counts. +bool mesh_fs_collecting(); +bool mesh_record_wanted() { return trace_frame_active || mesh_dump_pending() || mesh_fs_collecting(); } + +bool indirect_pending(Wrapper* self) { return indirect_current && !indirect_current->issued && indirect_current->list == self; } + +void indirect_transition(D3D12_RESOURCE_BARRIER& b, ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) +{ + b = {}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition.pResource = resource; + b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + b.Transition.StateBefore = from; + b.Transition.StateAfter = to; +} + +// Records, BEFORE the dispatch / draw / mesh path binds its pipeline and root state (the guard pass binds +// its own compute pipeline): the copy of the record into the ring, the guard pass over it and the +// barriers that leave the ring readable as indirect arguments. A forwarded title pipeline (pipeline_real) +// is bound again afterwards. Returns false (p->refused set) when nothing was recorded. +bool indirect_stage(Wrapper* self, ID3D12GraphicsCommandList* list, IndirectPending* p) +{ + const bool guard = indirect_guard_wanted(); + if (guard && !ensure_indirect_guard()) { + p->refused = skip_no_guard; + return false; + } + const u64 record_bytes = u64{p->stride} * p->max_count; + const u64 count_at = (record_bytes + 15) & ~u64{15}; + u64 slot = 0; + ID3D12Resource* const indirect_ring = indirect_ring_take(count_at + (p->count_window ? 16 : 0), &slot); + if (!indirect_ring) { + p->refused = skip_no_ring; + return false; + } + const bool readback = indirect_readback_wanted() && indirect_readback_used < indirect_readback_wanted() && ensure_indirect_readback(); + D3D12_RESOURCE_BARRIER b[3]; + UINT n = 0; + indirect_transition(b[n++], p->args_window, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + if (p->count_window && p->count_window != p->args_window) + indirect_transition(b[n++], p->count_window, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + indirect_transition(b[n++], indirect_ring, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->ResourceBarrier(n, b); + list->CopyBufferRegion(indirect_ring, slot, p->args_window, p->args_at, record_bytes); + if (p->count_window) list->CopyBufferRegion(indirect_ring, slot + count_at, p->count_window, p->count_at, 4); + const D3D12_RESOURCE_STATES ring_state = readback ? D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_COPY_SOURCE + : D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + for (UINT i = 0; i < n; ++i) std::swap(b[i].Transition.StateBefore, b[i].Transition.StateAfter); + b[n - 1].Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; + b[n - 1].Transition.StateAfter = guard ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS : ring_state; + list->ResourceBarrier(n, b); + if (guard) { + indirect_guard(list, indirect_ring, p->type, slot, p->stride, p->max_count); + D3D12_RESOURCE_BARRIER after; + indirect_transition(after, indirect_ring, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, ring_state); + list->ResourceBarrier(1, &after); + const Pass& pass = pass_of(self); + if (pass.pipeline_real && pass.pipeline) list->SetPipelineState(static_cast(pass.pipeline->own().real)); + } + p->staged = true; + p->ring = indirect_ring; + p->slot = slot; + p->ring_count_at = count_at; + p->ring_state = ring_state; + return true; +} +// A staged call that no path issued: the ring goes back to COMMON on this list. +void indirect_unstage(ID3D12GraphicsCommandList* list, IndirectPending* p) +{ + if (!p->staged) return; + D3D12_RESOURCE_BARRIER b; + indirect_transition(b, p->ring, p->ring_state, D3D12_RESOURCE_STATE_COMMON); + list->ResourceBarrier(1, &b); + p->staged = false; +} + +// Records the ExecuteIndirect for the pending (staged) call. The pipeline and root state must already be +// bound on `list`. +bool indirect_issue(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + IndirectPending* p = indirect_current; + if (!p || p->issued || !p->staged || p->list != self || !list) return false; + const u64 record_bytes = u64{p->stride} * p->max_count; + const u64 slot = p->slot, count_at = p->ring_count_at; + ID3D12Resource* const indirect_ring = p->ring; + const D3D12_RESOURCE_STATES ring_state = p->ring_state; + const bool readback = (ring_state & D3D12_RESOURCE_STATE_COPY_SOURCE) != 0; + list->ExecuteIndirect(p->signature, p->max_count, indirect_ring, slot, p->count_window ? indirect_ring : nullptr, + p->count_window ? slot + count_at : 0); + if (readback) { + const LONG index = InterlockedIncrement(&indirect_readback_used) - 1; + u64 marker_at = 0; + ID3D12Resource* marker_chunk = nullptr; + auto* marker = index < indirect_readback_wanted() ? reserve_upload_ring(4, &marker_at, &marker_chunk, nullptr) : nullptr; + if (marker) { + const std::uint32_t value = 0x1d000000u | (static_cast(indirect_readback_generation & 0xff) << 16) | + static_cast(index); + std::memcpy(marker, &value, 4); + indirect_readback_type[index] = static_cast(p->type); + const u64 dest = u64{static_cast(index)} * 32; + list->CopyBufferRegion(indirect_readback, dest + 4, indirect_ring, slot, record_bytes < 28 ? record_bytes : 28); + list->CopyBufferRegion(indirect_readback, dest, marker_chunk, marker_at, 4); + } + } + D3D12_RESOURCE_BARRIER rest; + indirect_transition(rest, indirect_ring, ring_state, D3D12_RESOURCE_STATE_COMMON); + list->ResourceBarrier(1, &rest); + p->staged = false; + p->issued = true; + return true; +} + +// Hook for the final Dispatch of both dispatch paths (d3d12_compute.inl execute_translated, +// d3d12_xs_device.cpp execute_dispatch): the indirect call when one is pending on this list. +void indirect_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z) +{ + if (indirect_pending(self)) { + note_issued_dispatch(list, x, y, z, true); + indirect_issue(self, list); + return; + } + note_issued_dispatch(list, x, y, z, false); + list->Dispatch(x, y, z); +} + +// Hook for the issue point of draw_translated (d3d12_draw.inl): the whole index buffer view goes to +// the upload ring (as the direct path copies its index range), then the indirect call. +bool indirect_draw_issue(Wrapper* self, ID3D12GraphicsCommandList* list, bool indexed) +{ + if (!indirect_pending(self)) return false; + if (indexed) { + const Pass& pass = pass_of(self); + const std::size_t bytes = pass.ib.SizeInBytes < (16u << 20) ? pass.ib.SizeInBytes : (16u << 20); + u64 offset = 0; + ID3D12Resource* chunk = nullptr; + if (!pass.ib.BufferLocation || !bytes || readable_window(pass.ib.BufferLocation, bytes) < bytes || + !frame_copy(pass.ib.BufferLocation, bytes, &offset, &chunk)) { + indirect_current->refused = skip_unresolved_buffer; + return false; + } + const D3D12_INDEX_BUFFER_VIEW view{chunk->GetGPUVirtualAddress() + offset, static_cast(bytes), + pass.ib.Format == DXGI_FORMAT_R16_UINT ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; + list->IASetIndexBuffer(&view); + } + return indirect_issue(self, list); +} + +u64 compute_key_of(Wrapper* self); +bool execute_dispatch(Wrapper* self, UINT x, UINT y, UINT z, u64 key); + +void indirect_announce() +{ + static LONG once; + if (InterlockedExchange(&once, 1)) return; + D3D12_FEATURE_DATA_D3D12_OPTIONS7 options7{}; + const HRESULT hr = device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &options7, sizeof(options7)); + log("x2w-indirect execution: dispatch %s, draw %s, mesh %s (hook %s), guard %s, read-back %ld records per report; MeshShaderTier %d (0x%08lx)", + indirect_type_enabled(itype_dispatch) ? "on" : "off", indirect_type_enabled(itype_draw) ? "on" : "off", + indirect_type_enabled(itype_mesh) ? "on" : "off", indirect_mesh_hook ? "set" : "absent", + indirect_guard_wanted() ? "on" : "OFF (X2W_INDIRECT_GUARD=0)", indirect_readback_wanted(), + SUCCEEDED(hr) ? static_cast(options7.MeshShaderTier) : -1, static_cast(hr)); +} + +// Read-back of a call that is NOT executed (no path or no pipeline): the record as the GPU sees it at +// that point of the list, copied straight from the window. Slot type = counter type | 0x80. +void indirect_probe(ID3D12GraphicsCommandList* list, int type, ID3D12Resource* window, u64 at, u64 bytes) +{ + if (!indirect_readback_wanted() || indirect_readback_used >= indirect_readback_wanted() || !ensure_indirect_readback()) return; + const LONG index = InterlockedIncrement(&indirect_readback_used) - 1; + u64 marker_at = 0; + ID3D12Resource* marker_chunk = nullptr; + auto* marker = index < indirect_readback_wanted() ? reserve_upload_ring(4, &marker_at, &marker_chunk, nullptr) : nullptr; + if (!marker) return; + const std::uint32_t value = 0x1d000000u | (static_cast(indirect_readback_generation & 0xff) << 16) | + static_cast(index); + std::memcpy(marker, &value, 4); + indirect_readback_type[index] = static_cast(type | 0x80); + const u64 dest = u64{static_cast(index)} * 32; + D3D12_RESOURCE_BARRIER b; + indirect_transition(b, window, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &b); + list->CopyBufferRegion(indirect_readback, dest + 4, window, at, bytes < 28 ? bytes : 28); + std::swap(b.Transition.StateBefore, b.Transition.StateAfter); + list->ResourceBarrier(1, &b); + list->CopyBufferRegion(indirect_readback, dest, marker_chunk, marker_at, 4); +} + +void indirect_run(Wrapper* self, ID3D12GraphicsCommandList* list, int type, Wrapper* signature, UINT stride, UINT max_count, + Wrapper* arguments, u64 offset, Wrapper* count_resource, u64 count_offset) +{ + indirect_announce(); + if (type == itype_other || (type == itype_mesh && !indirect_mesh_hook)) { + ID3D12Resource* window = nullptr; + u64 at = 0; + if (indirect_readback_wanted() && indirect_window(arguments, offset, u64{stride} * max_count, &window, &at)) + indirect_probe(list, type, window, at, u64{stride} * max_count); + return indirect_skip(type, skip_not_implemented); + } + if (!indirect_type_enabled(type)) return indirect_skip(type, skip_switched_off); + auto* desktop_signature = static_cast(signature->own().real); + if (!desktop_signature) return indirect_skip(type, skip_unknown_signature); + if (type == itype_draw || type == itype_indexed) { + if (pass_of(self).topology == 0x11) return indirect_skip(type, skip_topology); + } + IndirectPending p{}; + p.list = self; + p.type = type; + p.signature = desktop_signature; + p.stride = stride; + p.max_count = max_count; + p.refused = skip_no_pipeline; + if (!indirect_window(arguments, offset, u64{stride} * max_count, &p.args_window, &p.args_at) || + (count_resource && !indirect_window(count_resource, count_offset, 4, &p.count_window, &p.count_at))) + return indirect_skip(type, skip_unresolved_buffer); + mesh_trace_record = nullptr; + if (type == itype_mesh && mesh_record_wanted()) { + mesh_trace_record = arguments->own().kind == resource_kind && arguments->own().title_memory + ? static_cast(arguments->own().title_memory) + offset : nullptr; + mesh_trace_stride = stride; + mesh_trace_max = max_count; + } + if (type == itype_mesh && !mesh_prepare(self, list)) return indirect_skip(type, skip_no_pipeline); + if (!indirect_stage(self, list, &p)) { + if (type == itype_mesh && trace_frame_active) mesh_trace_call(self, false, nullptr, indirect_skip_names[p.refused]); + return indirect_skip(type, p.refused); + } + indirect_current = &p; + if (type == itype_dispatch) execute_dispatch(self, 0, 0, 0, compute_key_of(self)); + else if (type == itype_mesh) indirect_mesh_hook(self, list); + else draw_translated(self, type == itype_indexed, 0, 0, 0, 0, 0); + indirect_current = nullptr; + indirect_unstage(list, &p); + if (p.issued) { + InterlockedIncrement(&indirect_counts.executed[type]); + } else { + indirect_probe(list, type, p.args_window, p.args_at, u64{stride} * max_count); + indirect_skip(type, p.refused); + } +} + +// List slot 61 (called from list_execute_indirect before its frame trace). +void indirect_execute(Wrapper* self, void* signature, UINT max_count, Wrapper* arguments, u64 offset, Wrapper* count_resource, + u64 count_offset) +{ + UINT stride = 0, argument_type = ~0u; + const bool known = indirect_signature(signature, &stride, &argument_type); + const int type = known ? indirect_type_of(argument_type) : itype_other; + InterlockedIncrement(&indirect_counts.calls[type]); + if (count_resource) InterlockedIncrement(&indirect_counts.with_count_buffer); + max_count_seen(max_count); + static LONG described; + if (first_calls(described, 16)) { + const void* args_memory = arguments && arguments->own().kind == resource_kind ? arguments->own().title_memory : nullptr; + const void* count_memory = count_resource && count_resource->own().kind == resource_kind ? count_resource->own().title_memory : nullptr; + log("x2w-indirect call: signature %p type %u stride %u, max count %u, arguments %p (title %p) + 0x%llx, count %p (title %p) + 0x%llx", + signature, argument_type, stride, max_count, static_cast(arguments), args_memory, offset, + static_cast(count_resource), count_memory, count_offset); + } + auto* list = recording(self); + if (!list) return indirect_skip(type, skip_not_recording); + if (!known) return indirect_skip(type, skip_unknown_signature); + if (!max_count) return indirect_skip(type, skip_zero_count); + indirect_run(self, list, type, static_cast(signature), stride, max_count, arguments, offset, count_resource, count_offset); +} + +// The records read back since the last report: how many the GPU copied (marker present), how many were +// non-zero, how many break the v1 draw assumption (entry values 0: indexed BaseVertex and StartInstance, +// draw StartInstance), and up to 6 samples. Then a new generation starts. +void report_indirect_readback() +{ + if (!indirect_readback_wanted() || !indirect_readback_words) return; + const LONG used = InterlockedExchange(&indirect_readback_used, indirect_readback_wanted()); // no new copies while reading + const LONG count = used < indirect_readback_wanted() ? used : indirect_readback_wanted(); + // [0] executed calls (record as ExecuteIndirect read it), [1] calls not executed (record at that point of the list) + LONG arrived[2] = {}, records[2][itype_types] = {}, nonzero[2][itype_types] = {}, broken = 0; + char samples[640] = ""; + int at = 0, shown = 0; + for (LONG i = 0; i < count; ++i) { + const std::uint32_t* w = indirect_readback_words + u64{static_cast(i)} * 8; + const std::uint32_t expected = 0x1d000000u | (static_cast(indirect_readback_generation & 0xff) << 16) | + static_cast(i); + if (w[0] != expected) continue; + const int probed = indirect_readback_type[i] & 0x80 ? 1 : 0; + const int type = (indirect_readback_type[i] & 0x7f) < itype_types ? (indirect_readback_type[i] & 0x7f) : itype_other; + ++arrived[probed]; + ++records[probed][type]; + const bool any = w[1] | w[2] | w[3] | w[4] | w[5]; + if (any) ++nonzero[probed][type]; + if (!probed && ((type == itype_indexed && (w[4] || w[5])) || (type == itype_draw && w[4]))) ++broken; + if (any && shown < 8 && at < static_cast(sizeof(samples)) - 80) { + at += std::snprintf(samples + at, sizeof(samples) - at, "%s%s%s %u %u %u %u %u", shown ? "; " : "", indirect_type_names[type], + probed ? "(not run)" : "", w[1], w[2], w[3], w[4], w[5]); + ++shown; + } + } + const auto sum = [](const LONG* v) { return v[0] + v[1] + v[2] + v[3] + v[4]; }; + log("x2w-indirect read-back: %ld slots; executed: %ld arrived, non-zero %ld (draw %ld/%ld, indexed %ld/%ld, dispatch %ld/%ld, mesh %ld/%ld, " + "other %ld/%ld); not executed: %ld arrived, non-zero %ld (draw %ld/%ld, indexed %ld/%ld, dispatch %ld/%ld, mesh %ld/%ld, other %ld/%ld); " + "executed draws with base vertex / start instance not 0: %ld; samples: %s", + count, arrived[0], sum(nonzero[0]), nonzero[0][0], records[0][0], nonzero[0][1], records[0][1], nonzero[0][2], records[0][2], + nonzero[0][3], records[0][3], nonzero[0][4], records[0][4], arrived[1], sum(nonzero[1]), nonzero[1][0], records[1][0], + nonzero[1][1], records[1][1], nonzero[1][2], records[1][2], nonzero[1][3], records[1][3], nonzero[1][4], records[1][4], broken, + shown ? samples : "none"); + ++indirect_readback_generation; + InterlockedExchange(&indirect_readback_used, 0); +} + +// Every 300 frames (queue_present): one line with the calls by type, the executed calls and the +// skipped calls by reason (each reason with its non-zero types). Counters restart after each line. +void report_indirect(LONG frames) +{ + IndirectCounters c{}; + for (int t = 0; t < itype_types; ++t) { + c.calls[t] = InterlockedExchange(&indirect_counts.calls[t], 0); + c.executed[t] = InterlockedExchange(&indirect_counts.executed[t], 0); + for (int r = 0; r < skip_reasons; ++r) c.skipped[r][t] = InterlockedExchange(&indirect_counts.skipped[r][t], 0); + } + c.with_count_buffer = InterlockedExchange(&indirect_counts.with_count_buffer, 0); + c.max_count_above_one = InterlockedExchange(&indirect_counts.max_count_above_one, 0); + c.max_count_max = InterlockedExchange(&indirect_counts.max_count_max, 0); + LONG calls = 0, executed = 0; + for (int t = 0; t < itype_types; ++t) calls += c.calls[t], executed += c.executed[t]; + char skipped[768] = ""; + int at = 0; + for (int r = 0; r < skip_reasons; ++r) { + LONG total = 0; + for (int t = 0; t < itype_types; ++t) total += c.skipped[r][t]; + if (!total || at >= static_cast(sizeof(skipped)) - 96) continue; + at += std::snprintf(skipped + at, sizeof(skipped) - at, "%s%s %ld [", at ? ", " : "", indirect_skip_names[r], total); + bool first = true; + for (int t = 0; t < itype_types; ++t) + if (c.skipped[r][t]) { + at += std::snprintf(skipped + at, sizeof(skipped) - at, "%s%s %ld", first ? "" : " ", indirect_type_names[t], c.skipped[r][t]); + first = false; + } + at += std::snprintf(skipped + at, sizeof(skipped) - at, "]"); + } + log("x2w-indirect %ld frames: calls %ld by type (draw %ld, indexed %ld, dispatch %ld, mesh %ld, other %ld); executed %ld " + "(draw %ld, indexed %ld, dispatch %ld, mesh %ld, other %ld); skipped by reason (%s); count buffer %ld, max count > 1 %ld, largest %ld", + frames, calls, c.calls[0], c.calls[1], c.calls[2], c.calls[3], c.calls[4], executed, c.executed[0], c.executed[1], c.executed[2], + c.executed[3], c.executed[4], at ? skipped : "none", c.with_count_buffer, c.max_count_above_one, c.max_count_max); + // Records the guard zeroed since the last report (the GPU adds to the counter; values of lists still in + // flight arrive in a later report). + if (indirect_guard_pso && executed) { + if (indirect_guard_words) { + std::uint32_t zeroed[itype_types]; + for (int t = 0; t < itype_types; ++t) { + const std::uint32_t now = indirect_guard_words[t]; + zeroed[t] = now - indirect_guard_reported[t]; + indirect_guard_reported[t] = now; + } + log("x2w-indirect guard: zeroed %u records over the bounds (draw %u, indexed %u, dispatch %u, mesh %u)", + zeroed[0] + zeroed[1] + zeroed[2] + zeroed[3], zeroed[0], zeroed[1], zeroed[2], zeroed[3]); + } else { + log("x2w-indirect guard: active, zeroed count not visible (default-heap counter)"); + } + } + report_indirect_readback(); +} diff --git a/src/startup_stubs/d3d12_mem_counters.h b/src/startup_stubs/d3d12_mem_counters.h new file mode 100644 index 0000000000..d0c332e388 --- /dev/null +++ b/src/startup_stubs/d3d12_mem_counters.h @@ -0,0 +1,55 @@ +#pragma once +#include +#include +#include + +namespace x2w_memcut { +struct Counters { + volatile LONG64 ring_bytes; // upload-ring bytes reserved since the start (rounded to 512) + volatile LONG64 ring_frame_bytes; // ... in the frame being recorded + volatile LONG64 ring_frame_peak; // ... largest finished frame so far + volatile LONG ring_frame; + volatile LONG64 ring_refused; // requests over the per-copy cap (ring / 4) or without a ring + volatile LONG64 copy_frame_bytes; // frame_copy snapshots (CPU heap) in the frame being recorded + volatile LONG64 copy_frame_peak; + volatile LONG copy_frame; + volatile LONG64 bound_after_release; // textures bound for a draw after the title released them + volatile LONG64 viewed_after_release; // views created on a resource the title had released +}; +inline Counters& counters() +{ + static Counters c; + return c; +} +// Adds bytes to the current frame's sum; the first note of a new frame folds the old sum into peak. +// Approximate under races (a statistic, never used for a decision). +inline void per_frame(volatile LONG64& now, volatile LONG64& peak, volatile LONG& frame, LONG current, LONG64 bytes) +{ + if (InterlockedExchange(&frame, current) != current) { + const LONG64 last = InterlockedExchange64(&now, 0); + LONG64 seen = peak; + while (last > seen) { + const LONG64 previous = InterlockedCompareExchange64(&peak, last, seen); + if (previous == seen) break; + seen = previous; + } + } + InterlockedAdd64(&now, bytes); +} +inline void note_ring(LONG frame, std::uint64_t bytes) +{ + Counters& c = counters(); + InterlockedAdd64(&c.ring_bytes, static_cast(bytes)); + per_frame(c.ring_frame_bytes, c.ring_frame_peak, c.ring_frame, frame, static_cast(bytes)); +} +inline void note_ring_refused() { InterlockedIncrement64(&counters().ring_refused); } +inline void note_copy(LONG frame, std::uint64_t bytes) +{ + Counters& c = counters(); + per_frame(c.copy_frame_bytes, c.copy_frame_peak, c.copy_frame, frame, static_cast(bytes)); +} +inline void note_after_release(bool bound) +{ + InterlockedIncrement64(bound ? &counters().bound_after_release : &counters().viewed_after_release); +} +} // namespace x2w_memcut diff --git a/src/startup_stubs/d3d12_mem_counters.inl b/src/startup_stubs/d3d12_mem_counters.inl new file mode 100644 index 0000000000..6e79abe4ac --- /dev/null +++ b/src/startup_stubs/d3d12_mem_counters.inl @@ -0,0 +1,271 @@ +namespace { +enum MemcutClass : int { mc_tex_target, mc_tex_uav, mc_tex, mc_buf_copied, mc_buf_aliased, mc_buf, mc_tiled, mc_heap, mc_count }; +const char* const memcut_class_names[mc_count] = {"tex-target", "tex-uav", "tex", "buf-copied", "buf-aliased", "buf", "tiled-srv", "heap"}; +struct MemcutEntry { + const void* real; // the desktop object classified (reclassify if the wrapper now holds another) + u64 bytes; + u64 title; // the title address the resource stands for, or 0 + int cls; + bool system; // not a default (video-memory) heap + bool placement_known; + signed char mapped; // title address in MEM_MAPPED memory: -1 not asked yet, 0 no, 1 yes + DXGI_FORMAT format; + bool reserved; // a reserved resource (no memory of its own): counted with 0 bytes, not as unsized +}; +struct MemcutTotals { + u64 bytes[mc_count][2][2]{}; // [class][system][dead] + u64 count[mc_count][2][2]{}; + u64 tex_size_bytes[4]{}, tex_size_count[4]{}; + std::unordered_map format_bytes; + std::vector> spans; + u64 span_mapped = 0; + u64 wrappers = 0, unsized = 0; +}; +std::mutex memcut_mutex; +std::unordered_map& memcut_cache() +{ + static std::unordered_map m; + return m; +} + +bool memcut_system_heap(ID3D12Resource* resource) +{ + D3D12_HEAP_PROPERTIES props{}; + D3D12_HEAP_FLAGS flags{}; + if (FAILED(resource->GetHeapProperties(&props, &flags))) return false; // reserved: no own memory + if (props.Type == D3D12_HEAP_TYPE_DEFAULT) return false; + if (props.Type == D3D12_HEAP_TYPE_CUSTOM) return props.MemoryPoolPreference != D3D12_MEMORY_POOL_L1; + return true; +} + +MemcutEntry memcut_classify(ID3D12Resource* resource, void* title) +{ + MemcutEntry e{}; + e.real = resource; + e.mapped = -1; + const D3D12_RESOURCE_DESC desc = resource->GetDesc(); + const D3D12_RESOURCE_ALLOCATION_INFO info = device_of(the_device)->GetResourceAllocationInfo(0, 1, &desc); + e.bytes = info.SizeInBytes == ~0ull ? 0 : info.SizeInBytes; + D3D12_HEAP_PROPERTIES props{}; + D3D12_HEAP_FLAGS flags{}; + e.reserved = FAILED(resource->GetHeapProperties(&props, &flags)); // reserved (X2W_MEMCUT_RELEASE placeholder): no memory + if (e.reserved) e.bytes = 0; + e.system = memcut_system_heap(resource); + e.format = desc.Format; + e.title = reinterpret_cast(title); + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { + e.cls = mc_buf; // refined after the registry lock (memcut_placements) + } else { + e.placement_known = true; + e.cls = desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) ? mc_tex_target + : desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS ? mc_tex_uav : mc_tex; + } + return e; +} + +MemcutEntry memcut_heap(ID3D12Heap* heap) +{ + MemcutEntry e{}; + e.real = heap; + e.mapped = 0; + e.placement_known = true; + const D3D12_HEAP_DESC desc = heap->GetDesc(); + e.bytes = desc.SizeInBytes; + e.cls = mc_heap; + e.system = desc.Properties.Type == D3D12_HEAP_TYPE_UPLOAD || desc.Properties.Type == D3D12_HEAP_TYPE_READBACK || + (desc.Properties.Type == D3D12_HEAP_TYPE_CUSTOM && desc.Properties.MemoryPoolPreference != D3D12_MEMORY_POOL_L1); + return e; +} + +bool memcut_texture(int cls) { return cls == mc_tex || cls == mc_tex_target || cls == mc_tex_uav || cls == mc_tiled; } + +void memcut_add(MemcutTotals& t, const MemcutEntry& e, bool dead) +{ + if (!e.bytes && !e.reserved) ++t.unsized; + t.bytes[e.cls][e.system][dead] += e.bytes; + ++t.count[e.cls][e.system][dead]; + if (!dead && !e.system && memcut_texture(e.cls)) { + const u64 m = e.bytes >> 20; + const int s = m < 1 ? 0 : m < 16 ? 1 : m < 64 ? 2 : 3; + t.tex_size_bytes[s] += e.bytes; + ++t.tex_size_count[s]; + t.format_bytes[static_cast(e.format)] += e.bytes; + if (e.title) { + t.spans.emplace_back(e.title, e.title + e.bytes); + if (e.mapped == 1) t.span_mapped += e.bytes; + } + } +} + +// Buffer placements (note lock) and title-memory kinds (VirtualQuery, slow here) for new entries, +// outside the registry lock. Keys are only looked up, never dereferenced. +void memcut_refine(const std::vector& fresh) +{ + auto& cache = memcut_cache(); + for (const void* p : fresh) { + MemcutEntry& e = cache.at(p); + if (!e.placement_known) { + Placement placement = Placement::none; + AcquireSRWLockShared(¬e_lock); + if (const auto found = resource_infos().find(static_cast(p)); found != resource_infos().end()) + placement = found->second.placement; + ReleaseSRWLockShared(¬e_lock); + // A placement retired before this first look reads as none: such a buffer counts as "buf". + e.cls = placement == Placement::aliased_buffer ? mc_buf_aliased : placement == Placement::copied_buffer ? mc_buf_copied : mc_buf; + e.placement_known = true; + } + if (e.mapped < 0 && e.title && memcut_texture(e.cls)) { + u64 base = 0, end = 0; + MEMORY_BASIC_INFORMATION info{}; + if (known_private(e.title, &base, &end)) e.mapped = 0; + else e.mapped = timed_query(reinterpret_cast(e.title), &info) == sizeof(info) && info.Type == MEM_MAPPED; + } + } +} + +void memcut_collect(MemcutTotals& t) +{ + std::lock_guard guard(memcut_mutex); + auto& cache = memcut_cache(); + std::vector> seen; + std::vector fresh; + AcquireSRWLockShared(®istry_lock); + t.wrappers = registry().size(); + for (const void* p : registry()) { + auto* w = const_cast(static_cast(p)); + const Kind kind = w->own().kind; + IUnknown* const real = w->own().real; + if (!real || (kind != resource_kind && kind != heap_kind)) continue; + auto found = cache.find(p); + if (found == cache.end() || found->second.real != real) { + const MemcutEntry e = kind == heap_kind ? memcut_heap(static_cast(static_cast(real))) + : memcut_classify(static_cast(static_cast(real)), w->own().title_memory); + found = cache.insert_or_assign(p, e).first; + fresh.push_back(p); + } + seen.emplace_back(p, InterlockedCompareExchange(&w->own().refs, 0, 0)); + } + ReleaseSRWLockShared(®istry_lock); + memcut_refine(fresh); + for (const auto& [p, refs] : seen) memcut_add(t, cache.at(p), refs <= 0); + + struct Tiled { Wrapper* wrapper; ID3D12Resource* desktop; LONG refs; }; + std::vector tiled; + { + std::lock_guard lock(tiled_srv_mutex); // entries are never erased; desktop textures never released + for (auto& [wrapper, texture] : tiled_srv_textures) + if (texture.desktop) tiled.push_back({wrapper, texture.desktop.Get(), InterlockedCompareExchange(&wrapper->own().refs, 0, 0)}); + } + for (const Tiled& x : tiled) { + auto found = cache.find(x.desktop); + if (found == cache.end()) { + MemcutEntry e = memcut_classify(x.desktop, x.wrapper->own().title_memory); + e.cls = mc_tiled; + e.placement_known = true; + found = cache.emplace(x.desktop, e).first; + memcut_refine({x.desktop}); + } + memcut_add(t, found->second, x.refs <= 0); + } +} + +u64 memcut_union(std::vector>& spans) +{ + std::sort(spans.begin(), spans.end()); + u64 total = 0, start = 0, end = 0; + for (const auto& [a, b] : spans) { + if (a > end) { + total += end - start; + start = a; + end = b; + } else if (b > end) { + end = b; + } + } + return total + (end - start); +} + +int memcut_text(char* text, int capacity) +{ + if (!the_device || !text || capacity < 64) return 0; + const ULONGLONG began = GetTickCount64(); + MemcutTotals t; + memcut_collect(t); + const ULONGLONG took = GetTickCount64() - began; + constexpr u64 mib = 1ull << 20; + u64 local = 0, system = 0, dead_bytes = 0, dead_count = 0; + for (int c = 0; c < mc_count; ++c) { + local += t.bytes[c][0][0] + t.bytes[c][0][1]; + system += t.bytes[c][1][0] + t.bytes[c][1][1]; + dead_bytes += t.bytes[c][0][1] + t.bytes[c][1][1]; + dead_count += t.count[c][0][1] + t.count[c][1][1]; + } + PROCESS_MEMORY_COUNTERS_EX process{}; + process.cb = sizeof(process); + GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&process), sizeof(process)); + PERFORMANCE_INFORMATION perf{}; + perf.cb = sizeof(perf); + GetPerformanceInfo(&perf, sizeof(perf)); + const auto& k = x2w_memcut::counters(); + auto live = [&](int c) { return (t.bytes[c][0][0] + t.bytes[c][1][0]) / mib; }; + auto live_n = [&](int c) { return t.count[c][0][0] + t.count[c][1][0]; }; + int n = std::snprintf(text, static_cast(capacity), + "memcut MiB/count: local %llu system %llu; tex %llu/%llu target %llu/%llu uav %llu/%llu tiled-srv %llu/%llu " + "buf-copied %llu/%llu buf-aliased %llu/%llu buf %llu/%llu heap %llu/%llu; released-held %llu/%llu; ring %llu " + "peak %llu refused %lld; copy peak %llu; used-after-release bound %lld viewed %lld; ws %llu avail-phys %llu", + local / mib, system / mib, live(mc_tex), live_n(mc_tex), live(mc_tex_target), live_n(mc_tex_target), + live(mc_tex_uav), live_n(mc_tex_uav), live(mc_tiled), live_n(mc_tiled), live(mc_buf_copied), live_n(mc_buf_copied), + live(mc_buf_aliased), live_n(mc_buf_aliased), live(mc_buf), live_n(mc_buf), live(mc_heap), live_n(mc_heap), + dead_bytes / mib, dead_count, + static_cast(k.ring_bytes) / mib, static_cast(k.ring_frame_peak) / mib, k.ring_refused, + static_cast(k.copy_frame_peak) / mib, k.bound_after_release, k.viewed_after_release, + static_cast(process.WorkingSetSize) / mib, static_cast(perf.PhysicalAvailable) * perf.PageSize / mib); + if (n < 0) return 0; + if (n >= capacity) n = capacity - 1; + if (cold_textures_enabled() && n < capacity - 1) { + AcquireSRWLockShared(&cold_texture_lock); + const int added = std::snprintf(text + n, static_cast(capacity - n), + "; cold-priority bytes/count %llu/%llu, restored %llu/%llu, failures %llu", + cold_texture_bytes - warmed_texture_bytes, cold_texture_count - warmed_texture_count, + warmed_texture_bytes, warmed_texture_count, cold_texture_failures); + ReleaseSRWLockShared(&cold_texture_lock); + if (added > 0) n += (std::min)(added, capacity - 1 - n); + } + static ULONGLONG last_detail; + if (began - last_detail >= 10000) { + last_detail = began; + u64 span_sum = 0; + for (const auto& [a, b] : t.spans) span_sum += b - a; + const u64 span_union = memcut_union(t.spans); + char line[1400]; + int at = std::snprintf(line, sizeof(line), "x2w-memcut detail (%llu wrappers, %llu ms, %llu unsized): live local textures by size " + "<1M %llu/%llu <16M %llu/%llu <64M %llu/%llu >=64M %llu/%llu MiB/count; their title spans sum %llu union %llu " + "in mapped %llu MiB;", + t.wrappers, took, t.unsized, t.tex_size_bytes[0] / mib, t.tex_size_count[0], t.tex_size_bytes[1] / mib, + t.tex_size_count[1], t.tex_size_bytes[2] / mib, t.tex_size_count[2], t.tex_size_bytes[3] / mib, + t.tex_size_count[3], span_sum / mib, span_union / mib, t.span_mapped / mib); + std::vector> formats; + for (const auto& [format, bytes] : t.format_bytes) formats.emplace_back(bytes, format); + std::sort(formats.rbegin(), formats.rend()); + if (at > 0 && at < static_cast(sizeof(line))) at += std::snprintf(line + at, sizeof(line) - at, " top formats"); + for (std::size_t i = 0; i < formats.size() && i < 8 && at > 0 && at < static_cast(sizeof(line)); ++i) + at += std::snprintf(line + at, sizeof(line) - at, " %d:%llu", formats[i].second, formats[i].first / mib); + for (int c = 0; c < mc_count && at > 0 && at < static_cast(sizeof(line)); ++c) + at += std::snprintf(line + at, sizeof(line) - at, "; %s local %llu/%llu system %llu/%llu released local %llu/%llu system %llu/%llu", + memcut_class_names[c], t.bytes[c][0][0] / mib, t.count[c][0][0], t.bytes[c][1][0] / mib, t.count[c][1][0], + t.bytes[c][0][1] / mib, t.count[c][0][1], t.bytes[c][1][1] / mib, t.count[c][1][1]); + log("%s", line); + } + return n; +} +} // namespace + +// xmem_census.h: "name= ..." text for the x2w-mem line. +extern "C" __declspec(dllexport) int WINAPI x2w_memory_counters(char* text, int capacity) +{ + try { + return memcut_text(text, capacity); + } catch (...) { + return 0; // out of memory while counting: no text this time + } +} diff --git a/src/startup_stubs/d3d12_memcut_alias.inl b/src/startup_stubs/d3d12_memcut_alias.inl new file mode 100644 index 0000000000..d148bf57f1 --- /dev/null +++ b/src/startup_stubs/d3d12_memcut_alias.inl @@ -0,0 +1,48 @@ +namespace { +bool memcut_alias_slabs() +{ + static const bool on = x2w_local::env_on("X2W_MEMCUT_ALIAS_SLABS"); + return on; +} +LONG memcut_alias_done, memcut_alias_refused; +LONG64 memcut_alias_bytes, memcut_alias_refused_bytes; + +ID3D12Heap* memcut_slab_heap(void* address, UINT64 bytes, UINT64* offset) +{ + if (!memcut_alias_slabs() || !bytes) return nullptr; + using PoolRun = BOOL(WINAPI*)(const void*, SIZE_T, HANDLE*, ULONG64*); + static const PoolRun run = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + const auto f = xmem ? reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_pool_run")) : nullptr; + log("x2w-memcut alias slabs: X2W_MEMCUT_ALIAS_SLABS=1, xmem x2w_xmem_pool_run %s", f ? "found" : "MISSING (off)"); + return f; + }(); + HANDLE section = nullptr; + ULONG64 at = 0; + ID3D12Heap* heap = nullptr; + if (run && run(address, static_cast(bytes), §ion, &at)) heap = section_heap(section); + if (heap && at + bytes > heap->GetDesc().SizeInBytes) heap = nullptr; + const LONG n = heap ? InterlockedIncrement(&memcut_alias_done) : InterlockedIncrement(&memcut_alias_refused); + InterlockedAdd64(heap ? &memcut_alias_bytes : &memcut_alias_refused_bytes, static_cast(bytes)); + if (x2w_local::first_of(n, 8) || n % 256 == 0) + log("x2w-memcut alias slabs: buffer %p width 0x%llx %s (aliased %ld = %lld MiB, refused %ld = %lld MiB)", address, bytes, + heap ? "placed on its pool section" : "not one pool section run: copied as before", memcut_alias_done, memcut_alias_bytes >> 20, + memcut_alias_refused, memcut_alias_refused_bytes >> 20); + if (heap) *offset = at; + return heap; +} + +// Slot 133: CreatePlacedResource on the slab heap failed (the buffer falls back to a copy). Moves it from the aliased +// count to the refused one, so the counters say what was placed. +void memcut_slab_failed(void* address, UINT64 bytes, HRESULT hr) +{ + InterlockedDecrement(&memcut_alias_done); + InterlockedAdd64(&memcut_alias_bytes, -static_cast(bytes)); + const LONG n = InterlockedIncrement(&memcut_alias_refused); + InterlockedAdd64(&memcut_alias_refused_bytes, static_cast(bytes)); + static LONG shown; + if (x2w_local::first_of(InterlockedIncrement(&shown), 8) || n % 256 == 0) + log("x2w-memcut alias slabs: buffer %p width 0x%llx: placing on the pool section failed 0x%08lx, copied as before", address, bytes, + static_cast(hr)); +} +} // namespace diff --git a/src/startup_stubs/d3d12_memcut_release.inl b/src/startup_stubs/d3d12_memcut_release.inl new file mode 100644 index 0000000000..60100236f0 --- /dev/null +++ b/src/startup_stubs/d3d12_memcut_release.inl @@ -0,0 +1,361 @@ +#include + +namespace { +struct MemcutHollow { + D3D12_RESOURCE_DESC desc; + D3D12_HEAP_PROPERTIES props; + D3D12_HEAP_FLAGS flags; + DXGI_FORMAT packed; // packed_stand_in_tag of the original, or UNKNOWN + u64 bytes; +}; +struct MemcutRetiring { + ID3D12Resource* object; + u64 epoch; + u64 bytes; + bool snapped; + std::vector> waits; +}; +struct MemcutRelease { + SRWLOCK lock = SRWLOCK_INIT; + std::unordered_map pending; // wrapper -> frame of its release or last bind + std::unordered_map hollow; // wrappers whose real is a placeholder now + std::unordered_map list_epochs; // list -> epoch at its last Reset + std::unordered_set refused; // no placeholder could be made, or revived once: never again + std::vector retiring; + std::vector> test_waits; // fixtures: extra fences, as note_submits would add + volatile LONG64 epoch = 0; + volatile LONG active = 0; // anything pending or hollow: the bind hook's fast path + LONG last_hollow_frame = -1, last_report_frame = 0, lowest_frame = -1; + u64 lowest = 0; // lowest list Reset epoch, computed at lowest_frame + u64 hollowed = 0, freed = 0, freed_bytes = 0, revived = 0, refused_count = 0, blocked = 0; + u64 reported_freed = 0, window_us = 0, window_max_us = 0; // report bookkeeping, reaper cost since the last line +}; +MemcutRelease& memcut_release_state() +{ + static MemcutRelease s; + return s; +} +bool memcut_release_on() +{ + static const bool on = x2w_local::env_on("X2W_MEMCUT_RELEASE"); + return on; +} +LONG memcut_release_frames() +{ + static const LONG frames = [] { + char v[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_MEMCUT_RELEASE_FRAMES", v, sizeof(v)); + const long f = n && n < sizeof(v) ? std::atol(v) : 8; + return static_cast(f >= 1 ? f : 1); + }(); + return frames; +} +bool memcut_release_immediate() +{ + static const bool on = x2w_local::env_on("X2W_MEMCUT_RELEASE_TEST_IMMEDIATE"); + return on; +} +// Reads of unmapped tiles of a reserved resource return 0 from tier 2 on; below that the placeholder +// would not be safe, so the cut stays off. +bool memcut_tiles_safe() +{ + static const bool ok = [] { + D3D12_FEATURE_DATA_D3D12_OPTIONS o{}; + const bool got = the_device && SUCCEEDED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &o, sizeof(o))); + log("x2w-memcut release: X2W_MEMCUT_RELEASE=1, tiled resources tier %d%s, grace %ld frames%s", got ? static_cast(o.TiledResourcesTier) : -1, + got && o.TiledResourcesTier >= D3D12_TILED_RESOURCES_TIER_2 ? "" : " (below 2: OFF)", memcut_release_frames(), + memcut_release_immediate() ? ", TEST IMMEDIATE (no fence wait)" : ""); + return got && o.TiledResourcesTier >= D3D12_TILED_RESOURCES_TIER_2; + }(); + return ok; +} +DXGI_FORMAT memcut_packed_of(ID3D12Resource* r) { return x2w_startup::packed_stand_in_of(r); } +void memcut_copy_packed(ID3D12Resource* to, DXGI_FORMAT packed) +{ + if (to && packed != DXGI_FORMAT_UNKNOWN) to->SetPrivateData(x2w_startup::packed_stand_in_tag, sizeof(packed), &packed); +} + +// Writes the persistent view-id descriptors (translated compute) of every record that names one of these +// wrappers again, from its current desktop object: one pass over the records. draw_lock held. +void memcut_refill_views(const std::vector& wrappers) +{ + if (!draw_heap || wrappers.empty()) return; + std::unordered_set names; + for (Wrapper* w : wrappers) names.insert(reinterpret_cast(w)); + std::vector> found; + AcquireSRWLockShared(¬e_lock); + const UINT filled = views_filled < view_records().size() ? views_filled : static_cast(view_records().size()); + for (UINT i = 0; i < filled; ++i) + if (view_records()[i].resource && names.count(view_records()[i].resource)) found.emplace_back(i, view_records()[i]); + ReleaseSRWLockShared(¬e_lock); + for (const auto& [i, record] : found) fill_view_kinds(nullptr, draw_heap_size + 8 + 8 * i, &record); +} + +void memcut_swap_real(Wrapper* w, ID3D12Resource* to) +{ + AcquireSRWLockExclusive(®istry_lock); + w->own().real = to; + ReleaseSRWLockExclusive(®istry_lock); +} + +// Release hook: refs just reached 0. +void memcut_released(Wrapper* self) +{ + if (!memcut_release_on() || self->own().kind != resource_kind || !self->own().title_memory || self->own().tiled_address_srv || + self->own().linear_memory_srv) + return; + auto* real = static_cast(self->own().real); + if (!real) return; + const D3D12_RESOURCE_DESC desc = real->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1 || + (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | + D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS))) + return; + D3D12_HEAP_PROPERTIES props{}; + D3D12_HEAP_FLAGS flags{}; + if (FAILED(real->GetHeapProperties(&props, &flags)) || props.Type != D3D12_HEAP_TYPE_DEFAULT) return; + MemcutRelease& s = memcut_release_state(); + AcquireSRWLockExclusive(&s.lock); + if (!s.refused.count(self) && !s.hollow.count(self)) { + s.pending[self] = frame_number; + InterlockedExchange(&s.active, 1); + } + ReleaseSRWLockExclusive(&s.lock); +} + +// List Reset hook (after a successful Reset). +void memcut_list_reset(Wrapper* list) +{ + if (!memcut_release_on()) return; + MemcutRelease& s = memcut_release_state(); + AcquireSRWLockExclusive(&s.lock); + s.list_epochs[list] = static_cast(InterlockedCompareExchange64(&s.epoch, 0, 0)); + ReleaseSRWLockExclusive(&s.lock); +} + +// Bind hook (draw_lock held): a hollow texture is made again; a pending one counts as used now. +void memcut_revive(Wrapper* w) +{ + if (!w || !memcut_release_on()) return; + MemcutRelease& s = memcut_release_state(); + if (!InterlockedCompareExchange(&s.active, 0, 0)) return; + AcquireSRWLockExclusive(&s.lock); + if (auto p = s.pending.find(w); p != s.pending.end()) { + p->second = frame_number; + ReleaseSRWLockExclusive(&s.lock); + return; + } + const auto h = s.hollow.find(w); + if (h == s.hollow.end()) { + ReleaseSRWLockExclusive(&s.lock); + return; + } + const MemcutHollow hollow = h->second; + ID3D12Resource* created = nullptr; + const HRESULT hr = device_of(the_device)->CreateCommittedResource(&hollow.props, hollow.flags, &hollow.desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&created)); + if (FAILED(hr)) { + ReleaseSRWLockExclusive(&s.lock); + static LONG failures; + if (first_calls(failures, 6)) log("x2w-memcut release: revive of %p failed 0x%08lx (it stays a placeholder: reads zero)", static_cast(w), hr); + return; + } + memcut_copy_packed(created, hollow.packed); + auto* placeholder = static_cast(w->own().real); + memcut_swap_real(w, created); + texture_uploads().erase(placeholder); + s.hollow.erase(h); + const u64 e = static_cast(InterlockedIncrement64(&s.epoch)); + s.lowest_frame = -1; // as in memcut_reap: the next list check comes after this swap + s.retiring.push_back({placeholder, e, 0, false, {}}); + // A texture bound after it was freed is one the title still draws: never hollow it again (no hollow/revive + // cycle, each of which would be a re-upload under draw_lock). + s.refused.insert(w); + ++s.revived; + ReleaseSRWLockExclusive(&s.lock); + memcut_refill_views({w}); + static LONG shown; + if (first_calls(shown, 8)) + log("x2w-memcut release: revived %p (%llux%u fmt %d, %llu KiB): bound after it was freed; uploaded again from title memory", + static_cast(w), hollow.desc.Width, hollow.desc.Height, hollow.desc.Format, hollow.bytes >> 10); +} + +// s.lock held. The lowest Reset epoch over the live command lists (0 for a list never Reset). +u64 memcut_min_list_epoch(MemcutRelease& s, u64* live) +{ + u64 lowest = ~0ull; + *live = 0; + AcquireSRWLockShared(®istry_lock); + for (const void* p : registry()) { + auto* w = const_cast(static_cast(p)); + if (w->own().kind != list_kind || InterlockedCompareExchange(&w->own().refs, 0, 0) <= 0) continue; + ++*live; + const auto found = s.list_epochs.find(w); + const u64 e = found == s.list_epochs.end() ? 0 : found->second; + if (e < lowest) lowest = e; + } + ReleaseSRWLockShared(®istry_lock); + return lowest; +} + +// At a submit (draw_lock held), after note_submits. +void memcut_reap() +{ + if (!memcut_release_on()) return; + MemcutRelease& s = memcut_release_state(); + if (!InterlockedCompareExchange(&s.active, 0, 0) && s.retiring.empty()) return; + if (!memcut_tiles_safe()) return; + LARGE_INTEGER started{}; + QueryPerformanceCounter(&started); + AcquireSRWLockExclusive(&s.lock); + const LONG frame = frame_number; + // 2. Hollow, once per frame. + if (frame != s.last_hollow_frame && !s.pending.empty()) { + s.last_hollow_frame = frame; + std::vector due; + for (auto it = s.pending.begin(); it != s.pending.end();) { + if (InterlockedCompareExchange(&it->first->own().refs, 0, 0) > 0) { it = s.pending.erase(it); continue; } + if (frame - it->second >= memcut_release_frames() && due.size() < 256) due.push_back(it->first); + ++it; + } + const u64 e = due.empty() ? 0 : static_cast(InterlockedIncrement64(&s.epoch)); + if (!due.empty()) s.lowest_frame = -1; // the list check for epoch e must look at the lists after this hollow + for (Wrapper* w : due) { + s.pending.erase(w); + auto* old = static_cast(w->own().real); + // As device slot 133 / 127 create them: a default heap, no heap flags (the implicit heap's own flags, + // e.g. DENY_BUFFERS, are refused by CreateCommittedResource). + MemcutHollow h{old->GetDesc(), D3D12_HEAP_PROPERTIES{D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, memcut_packed_of(old), 0}; + const D3D12_RESOURCE_ALLOCATION_INFO info = device_of(the_device)->GetResourceAllocationInfo(0, 1, &h.desc); + h.bytes = info.SizeInBytes == ~0ull ? 0 : info.SizeInBytes; + D3D12_RESOURCE_DESC reserved = h.desc; + reserved.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; + reserved.Alignment = 0; + ID3D12Resource* placeholder = nullptr; + if (FAILED(device_of(the_device)->CreateReservedResource(&reserved, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&placeholder)))) { + s.refused.insert(w); + ++s.refused_count; + static LONG failures; + if (first_calls(failures, 6)) + log("x2w-memcut release: no placeholder for %p (%llux%u mips %u fmt %d): kept", static_cast(w), h.desc.Width, h.desc.Height, + h.desc.MipLevels, h.desc.Format); + continue; + } + memcut_copy_packed(placeholder, h.packed); + memcut_swap_real(w, placeholder); + texture_uploads().erase(old); + s.hollow[w] = h; + ++s.hollowed; + if (memcut_release_immediate()) { // fixtures only: the negative control + old->Release(); + ++s.freed; + s.freed_bytes += h.bytes; + } else { + s.retiring.push_back({old, e, h.bytes, false, {}}); + } + } + ReleaseSRWLockExclusive(&s.lock); + memcut_refill_views(due); // a refused one rewrites its own views: harmless + AcquireSRWLockExclusive(&s.lock); + } + // 3. Free what no list and no queue can still reach. + if (!s.retiring.empty()) { + bool unsnapped = false; + for (const MemcutRetiring& r : s.retiring) unsnapped |= !r.snapped; + if (unsnapped && frame != s.lowest_frame) { + u64 live = 0; + s.lowest = memcut_min_list_epoch(s, &live); + s.lowest_frame = frame; + } + const u64 lowest = s.lowest; + std::vector> now; + bool now_taken = false; + u64 blocked = 0; + for (auto it = s.retiring.begin(); it != s.retiring.end();) { + MemcutRetiring& r = *it; + if (!r.snapped) { + if (lowest < r.epoch) { ++blocked; ++it; continue; } + if (!now_taken) { + AcquireSRWLockShared(&allocator_lock); + for (const auto& [queue, submit] : queue_submits) + if (submit.first) now.push_back(submit); + ReleaseSRWLockShared(&allocator_lock); + now.insert(now.end(), s.test_waits.begin(), s.test_waits.end()); + now_taken = true; + } + r.waits = now; + r.snapped = true; + } + bool passed = true; + for (const auto& [fence, value] : r.waits) + if (fence->GetCompletedValue() < value) passed = false; + if (!passed) { ++it; continue; } + r.object->Release(); + ++s.freed; + s.freed_bytes += r.bytes; + it = s.retiring.erase(it); + } + s.blocked = blocked; + } + if (s.pending.empty() && s.hollow.empty()) InterlockedExchange(&s.active, 0); + else InterlockedExchange(&s.active, 1); + // Cost under draw_lock (this call, including the lock wait): max and total since the last report. + LARGE_INTEGER ended{}, hz{}; + QueryPerformanceCounter(&ended); + QueryPerformanceFrequency(&hz); + const u64 us = static_cast((ended.QuadPart - started.QuadPart) * 1000000 / (hz.QuadPart ? hz.QuadPart : 1)); + s.window_us += us; + if (us > s.window_max_us) s.window_max_us = us; + // Every 300 frames, and at each of the first 4 frees (once per new free, not at every submit). + const bool early = s.freed && s.freed <= 4 && s.freed != s.reported_freed; + const bool report = frame - s.last_report_frame >= 300 || early; + const u64 window_us = s.window_us, window_max_us = s.window_max_us; + if (report) s.last_report_frame = frame, s.reported_freed = s.freed, s.window_us = 0, s.window_max_us = 0; + const u64 pending = s.pending.size(), hollow = s.hollow.size(), retiring = s.retiring.size(); + const u64 hollowed = s.hollowed, freed = s.freed, freed_mib = s.freed_bytes >> 20, revived = s.revived, refused = s.refused_count, blocked = s.blocked; + ReleaseSRWLockExclusive(&s.lock); + static LONG reports; + if (report && first_calls(reports, 400)) + log("x2w-memcut release (frame %ld): pending %llu, hollow %llu, retiring %llu (%llu waiting for a list Reset), hollowed %llu, freed %llu = %llu MiB, " + "revived %llu, refused %llu; reaper under draw_lock since the last line: total %llu.%03llu ms, max %llu.%03llu ms", + frame, pending, hollow, retiring, blocked, hollowed, freed, freed_mib, revived, refused, window_us / 1000, window_us % 1000, + window_max_us / 1000, window_max_us % 1000); +} +} // namespace + +// Fixtures (memcut_release_check): op 0 the wrapper's desktop object; 1 add fence (a, value b) to the waits a +// snapshot takes; 2 advance frame_number by b and run the reaper as a submit would; 3 bind wrapper a (revive); +// 4 state of wrapper a: 0 none, 1 pending, 2 hollow, 3 refused; 5 freed count; 6 Reset epoch hook for list a. +extern "C" __declspec(dllexport) u64 WINAPI x2w_memcut_release_test(int op, void* a, u64 b) +{ + MemcutRelease& s = memcut_release_state(); + Wrapper* w = as_wrapper(a); + switch (op) { + case 0: return w ? reinterpret_cast(w->own().real) : 0; + case 1: + AcquireSRWLockExclusive(&s.lock); + s.test_waits.emplace_back(static_cast(a), b); + ReleaseSRWLockExclusive(&s.lock); + return 1; + case 2: + lock_draw(900000 + __LINE__); + frame_number += static_cast(b); + memcut_reap(); + ReleaseSRWLockExclusive(&draw_lock); + return 1; + case 3: + lock_draw(900000 + __LINE__); + memcut_revive(w); + ReleaseSRWLockExclusive(&draw_lock); + return w ? reinterpret_cast(w->own().real) : 0; + case 4: { + AcquireSRWLockShared(&s.lock); + const u64 state = s.pending.count(w) ? 1 : s.hollow.count(w) ? 2 : s.refused.count(w) ? 3 : 0; + ReleaseSRWLockShared(&s.lock); + return state; + } + case 5: return s.freed; + case 6: memcut_list_reset(w); return 1; + default: return 0; + } +} diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 673084c388..468ac6c6c4 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -13,8 +13,32 @@ bool same_texture_description(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE a.SampleDesc.Quality == b.SampleDesc.Quality && a.Layout == b.Layout && a.Flags == b.Flags; } +bool tiled_any_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_MEMORY_SRV_TILED_ANY"); + if (v) log("x2w-memsrv X2W_MEMORY_SRV_TILED_ANY=1: single-mip tiled memory SRVs of any 16-byte BC format and size"); + return v; + }(); + return on; +} +bool bc16_format(DXGI_FORMAT f) +{ + switch (f) { + case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: + return true; + default: + return false; + } +} bool tiled_bc_srv(const D3D12_RESOURCE_DESC& r) { + if (tiled_any_on() && bc16_format(r.Format) && static_cast(r.Layout) == 0x105 && r.Alignment == 0 && + (r.Flags == D3D12_RESOURCE_FLAG_NONE || static_cast(r.Flags) == 0x300000) && r.Width && r.Height && + r.Width <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && r.Height <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) + return true; return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && r.DepthOrArraySize == 1 && r.MipLevels == 1 && r.SampleDesc.Count == 1 && r.SampleDesc.Quality == 0 && (r.Format == DXGI_FORMAT_BC3_UNORM || r.Format == DXGI_FORMAT_BC7_UNORM) && @@ -60,6 +84,11 @@ u64 xg_reported_bytes(Wrapper* device, const D3D12_RESOURCE_DESC& desc) } bool supports_placed_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v); +bool upstream_console_srv_on() +{ + static const bool on = x2w_local::env_on("X2W_UPSTREAM_CONSOLE_SRV"); + return on; +} // The shapes slot 70 took before address_texture.h, or a texture in a console layout gfx10_layout.h // addresses with a view that stays inside it. bool supports_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) @@ -233,10 +262,47 @@ Wrapper* existing_memory_buffer(Wrapper* device, u64 address, u64 bytes) return nullptr; return const_cast(placed.owner); } + static const int index_mode = [] { + char v[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_BUFFER_ADDRESS_INDEX", v, sizeof(v)); + const int mode = n && n < sizeof(v) ? (std::strcmp(v, "1") == 0 ? 1 : std::strcmp(v, "check") == 0 ? 2 : 0) : 0; + if (mode) log("x2w-memsrv X2W_BUFFER_ADDRESS_INDEX=%s: memory buffer lookups use the address index%s", v, + mode == 2 ? ", checked against the walk on every call" : ""); + return mode; + }(); + // The walk's filters, applied to each candidate either way. + const auto eligible = [](const Wrapper* wrapper, const ResourceInfo& info) { + return !(!wrapper->own().real && info.console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) && + info.placement == Placement::none && info.console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && + !(info.console.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && + InterlockedCompareExchange(&const_cast(wrapper)->own().refs, 0, 0) > 0; + }; + Wrapper* indexed = nullptr; + if (index_mode) { + AcquireSRWLockShared(¬e_lock); + bool ambiguous = false; + buffer_address_index().containing(address, bytes, [&](const Wrapper* wrapper, u64 base, u64) { + const auto found = resource_infos().find(wrapper); + if (found == resource_infos().end() || !eligible(wrapper, found->second)) return true; + // As the walk: the record's current base and width decide (the index holds them as noted). + const u64 now = reinterpret_cast(wrapper->own().title_memory), width = found->second.console.Width; + if (now != base || address < now || address - now >= width || bytes > width - (address - now)) return true; + if (indexed) { + ambiguous = true; + return false; + } + indexed = const_cast(wrapper); + return true; + }); + ReleaseSRWLockShared(¬e_lock); + if (ambiguous) indexed = nullptr; + if (index_mode == 1) return indexed; + } Wrapper* match = nullptr; AcquireSRWLockShared(¬e_lock); resource_address_index().for_each_reaching(address, 1, [&](const Wrapper* wrapper) { const auto& info = resource_infos().at(wrapper); + if (!wrapper->own().real && info.console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return false; if (info.placement != Placement::none || info.console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (info.console.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || @@ -254,6 +320,17 @@ Wrapper* existing_memory_buffer(Wrapper* device, u64 address, u64 bytes) return false; }); ReleaseSRWLockShared(¬e_lock); + if (index_mode == 2) { + static LONG64 checked, differed; + const LONG64 n = InterlockedIncrement64(&checked); + const bool same = indexed == match; + const LONG64 d = same ? differed : InterlockedIncrement64(&differed); + static LONG shown; + if (!same && first_calls(shown, 8)) + log("x2w-memsrv buffer address index DIFFERS at 0x%llx (%llu bytes): index %p, walk %p", address, bytes, static_cast(indexed), + static_cast(match)); + if ((n & (n - 1)) == 0) log("x2w-memsrv buffer address index checked %lld lookups against the walk: %lld differ", n, d); + } return match; } @@ -467,7 +544,7 @@ bool latest_texture_write_is_rows(u64 address) // (the single texel, the 0x105 BC3/BC7 surface and the 0x109 BC chains keep their own paths). bool console_layout_srv(const D3D12_RESOURCE_DESC& desc) { - return x2w_startup::console_address_texture(desc) && !x2w_startup::single_element_bytes(desc) && + return upstream_console_srv_on() && x2w_startup::console_address_texture(desc) && !x2w_startup::single_element_bytes(desc) && !tiled_bc_srv(desc) && !x2w_startup::bc64::supports(desc); } @@ -549,6 +626,8 @@ Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURC ID3D12Resource* sampled_address_texture(Wrapper* resource) { if (!resource || resource->own().kind != resource_kind) return nullptr; + warm_texture(resource); + memcut_revive(resource); if (!resource->own().tiled_address_srv) return static_cast(resource->own().real); std::lock_guard lock(tiled_srv_mutex); auto& sampled = tiled_srv_textures.at(resource); @@ -572,6 +651,468 @@ ID3D12Resource* sampled_address_texture(Wrapper* resource) return sampled.desktop.Get(); } +bool memory_srv_linear_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_MEMORY_SRV_LINEAR"); + if (v) log("x2w-memsrv X2W_MEMORY_SRV_LINEAR=1: plain 2D memory SRVs get a desktop texture uploaded from the view address"); + return v; + }(); + return on; +} +// view_slot does not check mip, array or plane ranges, and desktop removes the device on a view it +// rejects, so the range is checked here (MipLevels ~0u means "all from the most detailed mip"). +bool linear_view_in_range(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) +{ + const UINT mips = r.MipLevels, slices = r.DepthOrArraySize; + const auto mip_range = [&](UINT most, UINT count, float clamp) { + return most < mips && (count == ~0u || (count > 0 && count <= mips - most)) && clamp >= 0.0f && clamp <= static_cast(mips); + }; + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D) + return mip_range(v.Texture2D.MostDetailedMip, v.Texture2D.MipLevels, v.Texture2D.ResourceMinLODClamp) && v.Texture2D.PlaneSlice == 0; + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY) { + const auto& a = v.Texture2DArray; + return mip_range(a.MostDetailedMip, a.MipLevels, a.ResourceMinLODClamp) && a.PlaneSlice == 0 && a.FirstArraySlice < slices && + a.ArraySize > 0 && a.ArraySize <= slices - a.FirstArraySlice; + } + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBE) + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && r.Width == r.Height && slices == 6 && + mip_range(v.TextureCube.MostDetailedMip, v.TextureCube.MipLevels, v.TextureCube.ResourceMinLODClamp); + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBEARRAY) { + const auto& c = v.TextureCubeArray; + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && r.Width == r.Height && slices % 6 == 0 && c.NumCubes > 0 && + c.First2DArrayFace < slices && u64{c.NumCubes} * 6 <= u64{slices} - c.First2DArrayFace && + mip_range(c.MostDetailedMip, c.MipLevels, c.ResourceMinLODClamp); + } + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE1D) + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && + mip_range(v.Texture1D.MostDetailedMip, v.Texture1D.MipLevels, v.Texture1D.ResourceMinLODClamp); + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE1DARRAY) { + const auto& a = v.Texture1DArray; + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && mip_range(a.MostDetailedMip, a.MipLevels, a.ResourceMinLODClamp) && + a.FirstArraySlice < slices && a.ArraySize > 0 && a.ArraySize <= slices - a.FirstArraySlice; + } + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE3D) + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && + mip_range(v.Texture3D.MostDetailedMip, v.Texture3D.MipLevels, v.Texture3D.ResourceMinLODClamp); + return false; +} +// Which description forms the linear and stand-in paths wrote, one counter each. +enum LinearForm { lf_2d, lf_2d_array, lf_cube, lf_cube_array, lf_1d, lf_1d_array, lf_3d, lf_buffer_srv, lf_buffer_uav, lf_count }; +const char* const linear_form_names[lf_count] = {"2d", "2d-array", "cube", "cube-array", "1d", "1d-array", "3d", "buffer-srv", "buffer-uav"}; +LONG64 linear_forms[lf_count]; +int linear_form(D3D12_SRV_DIMENSION d) +{ + switch (d) { + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: return lf_2d_array; + case D3D12_SRV_DIMENSION_TEXTURECUBE: return lf_cube; + case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: return lf_cube_array; + case D3D12_SRV_DIMENSION_TEXTURE1D: return lf_1d; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: return lf_1d_array; + case D3D12_SRV_DIMENSION_TEXTURE3D: return lf_3d; + default: return lf_2d; + } +} +void note_linear_form(int form, u64 destination) +{ + const LONG64 n = InterlockedIncrement64(&linear_forms[form]); + if ((n & (n - 1)) == 0) + log("x2w-memsrv form %s: %lld views written (latest destination 0x%llx)", linear_form_names[form], n, destination); +} +bool linear_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) +{ + const bool sized = r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + ? r.Width <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && r.Height <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION + : r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D + ? r.Width <= D3D12_REQ_TEXTURE1D_U_DIMENSION && r.Height == 1 && r.DepthOrArraySize <= D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION + : r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && + r.Width <= D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION && r.Height <= D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION && + r.DepthOrArraySize <= D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION; + return sized && r.Width && r.Height && + r.DepthOrArraySize >= 1 && r.MipLevels >= 1 && r.MipLevels <= 15 && r.SampleDesc.Count == 1 && + static_cast(r.Layout) == 0 && !tiled_bc_srv(r) && !x2w_startup::bc64::supports(r) && + !(r.Flags & (D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE | D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) && + v.Format == r.Format && linear_view_in_range(r, v); +} +bool memory_srv_announced_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_MEMORY_SRV_ANNOUNCED"); + if (v) log("x2w-memsrv X2W_MEMORY_SRV_ANNOUNCED=1: console-swizzled memory SRVs at XG-announced addresses take the linear path"); + return v; + }(); + return on; +} +bool xg_announced(u64 address) +{ + AcquireSRWLockShared(&written_lock); + const auto found = written_textures().find(address); + const bool announced = found != written_textures().end() && !found->second.bc7_width; + ReleaseSRWLockShared(&written_lock); + return announced; +} +bool console_swizzle(const D3D12_RESOURCE_DESC& r) +{ + const UINT layout = static_cast(r.Layout); + return layout >= 0x100 && layout <= 0x1ff; +} +bool announced_linear_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v, u64 address) +{ + if (!console_swizzle(r) || tiled_bc_srv(r) || x2w_startup::bc64::supports(r) || !xg_announced(address)) return false; + D3D12_RESOURCE_DESC as_linear = r; + as_linear.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + return linear_memory_srv(as_linear, v); +} +std::mutex linear_srv_mutex; +std::unordered_multimap> linear_srv_textures; +u64 linear_srv_bytes; // desktop allocation size of the textures above (GetResourceAllocationInfo) +// detiled: the memory is console-swizzled (X2W_MEMORY_SRV_DETILE); a separate texture from a linear one with the +// same description, so one desktop copy per (address, description, form). +Wrapper* publish_linear_texture(Wrapper* device, u64 address, const D3D12_RESOURCE_DESC& desc, bool detiled = false) +{ + std::lock_guard lock(linear_srv_mutex); + const auto [first, last] = linear_srv_textures.equal_range(address); + for (auto it = first; it != last; ++it) + if (same_texture_description(it->second.first, desc) && it->second.second->own().detiled_memory_srv == detiled) + return it->second.second; + const D3D12_RESOURCE_DESC texture = sanitized(desc); + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + ID3D12Resource* created = nullptr; + const HRESULT hr = device_of(device)->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &texture, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&created)); + static LONG shown, failures; + if (first_calls(shown, 16) || (FAILED(hr) && first_calls(failures, 16))) + log("x2w-memsrv linear texture at 0x%llx: %llux%ux%u mips %u fmt %d flags 0x%x -> 0x%08lx (%zu so far)", address, desc.Width, + desc.Height, desc.DepthOrArraySize, desc.MipLevels, desc.Format, static_cast(desc.Flags), + static_cast(hr), linear_srv_textures.size() + 1); + if (FAILED(hr)) return nullptr; + x2w_startup::mark_packed_stand_in(created, desktop_format(desc.Format)); + Wrapper* w = wrap(created, resource_kind); + w->own().title_memory = reinterpret_cast(address); + w->own().linear_memory_srv = true; + w->own().detiled_memory_srv = detiled; + note_resource(w, &desc, 0); + linear_srv_bytes += device_of(device)->GetResourceAllocationInfo(0, 1, &texture).SizeInBytes; + linear_srv_textures.emplace(address, std::make_pair(desc, w)); + return w; +} + +bool memory_srv_detile_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_MEMORY_SRV_DETILE"); + if (v) log("x2w-memsrv X2W_MEMORY_SRV_DETILE=1: unannounced console-swizzled memory SRVs are detiled (GFX10 layout)"); + return v; + }(); + return on; +} +// Bytes per element (per 4x4 block for BC); 0 when the format is not detiled (not a power of two, depth, video). +UINT detile_element_bytes(DXGI_FORMAT f, bool& bc) +{ + bc = true; + switch (f) { + case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB: + case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM: + return 8; + case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: + case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: + case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: + case DXGI_FORMAT_BC6H_TYPELESS: case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16: + case DXGI_FORMAT_BC7_TYPELESS: case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: + return 16; + default: + break; + } + bc = false; + switch (f) { + case DXGI_FORMAT_R32G32B32A32_TYPELESS: return 16; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: case DXGI_FORMAT_R32G32_TYPELESS: return 8; + case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8A8_TYPELESS: + case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R16G16_TYPELESS: case DXGI_FORMAT_R32_TYPELESS: + case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: + return 4; + case DXGI_FORMAT_R8G8_TYPELESS: case DXGI_FORMAT_R16_TYPELESS: case DXGI_FORMAT_B5G6R5_UNORM: + case DXGI_FORMAT_B5G5R5A1_UNORM: case DXGI_FORMAT_B4G4R4A4_UNORM: + return 2; + case DXGI_FORMAT_R8_TYPELESS: case DXGI_FORMAT_A8_UNORM: return 1; + default: { + const UINT n = x2w_startup::typed_buffer_format_bytes(f); + return n == 12 ? 0 : n; + } + } +} +x2w_startup::gfx10_local::Layout detile_layout(const D3D12_RESOURCE_DESC& r) +{ + bool bc = false; + const UINT bytes = detile_element_bytes(r.Format, bc); + const UINT layout = static_cast(r.Layout); + // The D modes (0x106, 0x10a) are taken for 1-, 2-, 8- and 16-byte elements (BC blocks are 8 or 16), whose + // equations addrlib gives the same on Navi1x and Navi21. For 4-byte elements they are left out: there addrlib's + // equation differs between Navi1x and Navi21 (RB+), and which one the console uses is not known + // (tests/gfx10_layout_check.cpp --addrlib). Thick D has no equation (gfx10_layout.h), so a 3D D-mode is invalid. + const bool d_mode = layout == 0x106 || layout == 0x10a; + const bool known = layout == 0x100 || layout == 0x105 || layout == 0x109 || (d_mode && bytes != 4); + const bool dim = r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D || r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + if (!bytes || !known || !dim || r.Width > 0xffffffffull) + return x2w_startup::gfx10_local::Layout(~0u, false, 0, 0, 0, 0, 0); // invalid + const UINT w = static_cast(r.Width), h = r.Height; + return x2w_startup::gfx10_local::Layout(layout - 0x100, r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D, bytes, + bc ? (w + 3) / 4 : w, bc ? (h + 3) / 4 : h, r.DepthOrArraySize, r.MipLevels ? r.MipLevels : 1); +} +// Why detile_srv does not take the call, as an index into detile_declines (d3d12_draw.inl); 0 when it does. +// check_memory false (a null address): the description alone, 11 ("would detile") when it passes. +unsigned detile_decline(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v, u64 address, bool check_memory = true) +{ + if (!console_swizzle(r)) return 1; + if (supports_placed_memory_srv(r, v)) return 2; + if (check_memory && xg_announced(address)) return 3; + D3D12_RESOURCE_DESC as_linear = r; + as_linear.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // (tiled_bc_srv / bc64 need a console layout: false here) + if (!linear_memory_srv(as_linear, v)) return 4; + const auto l = detile_layout(r); + if (!l.valid) return 5; + if (l.size > (1ull << 30)) return 7; + if (!check_memory) return 11; + if (!x2w_local::readable(reinterpret_cast(address), static_cast(l.size))) return 8; + return 0; +} + +bool memory_srv_buffer_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_MEMORY_SRV_BUFFER"); + if (v) log("x2w-memsrv X2W_MEMORY_SRV_BUFFER=1: memory buffer SRVs/UAVs without a buffer resource get a stand-in at the address"); + return v; + }(); + return on; +} +std::mutex standin_buffer_mutex; +std::unordered_map> standin_buffers; // address -> (bytes, wrapper) +Wrapper* standin_memory_buffer(u64 address, const D3D12_RESOURCE_DESC& desc, u64 span) +{ + if (!address || !span || span > (u64{256} << 20) || desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || + !x2w_local::readable(reinterpret_cast(address), 1)) + return nullptr; + const u64 bytes = desc.Width > span ? desc.Width : span; + std::lock_guard lock(standin_buffer_mutex); + if (const auto found = standin_buffers.find(address); found != standin_buffers.end() && found->second.first >= bytes) + return found->second.second; + D3D12_RESOURCE_DESC console = desc; + console.Width = bytes; + Wrapper* w = wrap(nullptr, resource_kind); + w->own().title_memory = reinterpret_cast(address); + note_resource(w, &console, bytes); + standin_buffers[address] = {bytes, w}; + static LONG shown; + const std::size_t count = standin_buffers.size(); + if (first_calls(shown, 16) || (count & (count - 1)) == 0) + log("x2w-memsrv stand-in buffer at 0x%llx: %llu bytes (%zu stand-ins)", address, bytes, count); + return w; +} + +struct MemoryUnorderedAccessView { + D3D12_UNORDERED_ACCESS_VIEW_DESC view; + u64 address; +}; +static_assert(offsetof(MemoryUnorderedAccessView, address) == 0x28); +void __stdcall device_memory_uav(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const MemoryUnorderedAccessView* input, u64 destination) +{ + static LONG refused; + const char* reason = nullptr; + if (!destination) reason = "null_destination"; + else if (!x2w_local::readable(resource, sizeof(*resource))) reason = "unreadable_resource"; + else if (!x2w_local::readable(input, sizeof(*input))) reason = "unreadable_view"; + else if (!input->address) reason = "null_address"; + else if (resource->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || input->view.ViewDimension != D3D12_UAV_DIMENSION_BUFFER) + reason = "not_a_buffer"; + else if (!memory_srv_destination(destination)) reason = "destination_outside_view_heaps"; + u64 span = 0; + if (!reason) { + const auto& b = input->view.Buffer; + const bool raw = (b.Flags & D3D12_BUFFER_UAV_FLAG_RAW) != 0; + const UINT element = b.StructureByteStride ? b.StructureByteStride : raw ? 4 : x2w_startup::typed_buffer_format_bytes(input->view.Format); + if (b.CounterOffsetInBytes) reason = "counter"; + else if (raw && (input->view.Format != DXGI_FORMAT_R32_TYPELESS || b.StructureByteStride)) reason = "bad_raw_view"; + else if (b.StructureByteStride && input->view.Format != DXGI_FORMAT_UNKNOWN) reason = "bad_structured_view"; + else if (!element || !b.NumElements) reason = "bad_element"; + else if ((span = (b.FirstElement + b.NumElements) * element) > resource->Width) reason = "view_past_resource"; + } + Wrapper* standin = reason ? nullptr : standin_memory_buffer(input->address, *resource, span); + if (!reason && !standin) reason = "no_stand_in"; + if (reason) { + if (first_calls(refused, noop_census_enabled() ? 512 : 8)) + log("x2w-memsrv Device::slot71 memory UAV refused: reason=%s res{dim=%d width=%llu} view{dim=%d fmt=%d} dest=0x%llx", reason, + x2w_local::readable(resource, sizeof(*resource)) ? resource->Dimension : -1, + x2w_local::readable(resource, sizeof(*resource)) ? resource->Width : 0ull, + x2w_local::readable(input, sizeof(*input)) ? input->view.ViewDimension : -1, + x2w_local::readable(input, sizeof(*input)) ? input->view.Format : -1, destination); + return; + } + note_linear_form(lf_buffer_uav, destination); + view_slot<19, 3>(self, reinterpret_cast(standin), 0, reinterpret_cast(&input->view), destination); +} + +enum MemorySrvOutcome { mso_linear, mso_announced, mso_tiled, mso_buffer, mso_standin, mso_refused, mso_detiled, mso_descriptor, mso_count }; +const char* const memory_srv_outcome_names[mso_count] = {"linear", "announced-linear", "tiled/bc64", "buffer", "stand-in buffer", "refused", "detiled", "buffer descriptor"}; +LONG64 memory_srv_outcomes[mso_count]; +std::mutex refusal_census_mutex; +std::unordered_map refusal_census; +LONG64 refusal_census_total; +const char* const census_reasons[] = {"null_destination", "unreadable_resource", "unreadable_view", "null_address", + "unsupported_description", "destination_outside_view_heaps", "buffer_unavailable", "texture_unavailable"}; +bool census_every_event(); +bool texture_census_on() +{ + static const bool on = [] { + const bool v = x2w_local::env_on("X2W_TEXTURE_CENSUS"); + if (v) log("x2w-texcensus X2W_TEXTURE_CENSUS=1: slot-70 outcomes and refusal classes, draw texture bindings real/null; " + "all cumulative, every 300 frames%s", census_every_event() ? " and after every event (X2W_TEXTURE_CENSUS_EVERY=1)" : ""); + return v; + }(); + return on; +} +// X2W_TEXTURE_CENSUS_EVERY=1 (tests): the cumulative lines after every counted event instead of at the thresholds. +bool census_every_event() +{ + static const bool on = x2w_local::env_on("X2W_TEXTURE_CENSUS_EVERY"); + return on; +} +void log_memory_srv_outcomes(const char* when) +{ + LONG64 total = 0; + for (LONG64 n : memory_srv_outcomes) total += n; + log("x2w-texcensus slot70 calls %lld (%s, cumulative): linear %lld, announced-linear %lld, tiled/bc64 %lld, buffer %lld, stand-in buffer %lld, " + "detiled %lld, refused %lld, buffer descriptor %lld", total, when, memory_srv_outcomes[0], memory_srv_outcomes[1], memory_srv_outcomes[2], memory_srv_outcomes[3], + memory_srv_outcomes[4], memory_srv_outcomes[6], memory_srv_outcomes[5], memory_srv_outcomes[7]); +} +void log_refusal_classes(const char* when) // refusal_census_mutex held +{ + std::vector> sorted; + for (const auto& [k, n] : refusal_census) sorted.emplace_back(n, k); + std::sort(sorted.begin(), sorted.end(), std::greater<>()); + log("x2w-texcensus slot70 refusals %lld (%s, cumulative), %zu classes, top classes:", refusal_census_total, when, sorted.size()); + for (std::size_t i = 0; i < sorted.size() && i < 24; ++i) { + const u64 k = sorted[i].second; + const u64 decline = (k >> 31) & 15; + char why[48] = ""; + if (decline) std::snprintf(why, sizeof why, " detile: %s", decline < std::size(detile_declines) ? detile_declines[decline] : "?"); + log("x2w-texcensus %lld x %s dim %llu layout 0x%llx fmt %llu %s %s %s%s", sorted[i].first, + (k & 15) < std::size(census_reasons) ? census_reasons[k & 15] : "other", (k >> 4) & 15, (k >> 8) & 0x1ff, (k >> 20) & 0xff, + (k >> 28) & 1 ? "mips>1" : "mips=1", (k >> 29) & 1 ? "announced" : "not-announced", + !((k >> 35) & 1) ? "unreadable" : (k >> 30) & 1 ? "nonzero" : "zero", why); + } +} +// Called with the 300-frame draw census line (d3d12_draw.inl), so a title run's scene window is the difference of +// two reports. +void report_memory_srv_census(long frame) +{ + if (!texture_census_on()) return; + char when[32]; + std::snprintf(when, sizeof(when), "frame %ld", frame); + log_memory_srv_outcomes(when); + std::lock_guard lock(refusal_census_mutex); + log_refusal_classes(when); +} +void census_memory_srv_outcome(int outcome) +{ + if (!texture_census_on()) return; + InterlockedIncrement64(&memory_srv_outcomes[outcome]); + LONG64 total = 0; + for (LONG64 n : memory_srv_outcomes) total += n; + if (census_every_event() || (total >= 1024 && (total & (total - 1)) == 0)) log_memory_srv_outcomes("threshold"); +} +// The memory at a refused call's address: its first 256 bytes readable, and any of them nonzero. +struct RefusedMemory { + bool readable = false, nonzero = false; +}; +RefusedMemory refused_memory(u64 address) +{ + RefusedMemory m; + if (address && x2w_local::readable(reinterpret_cast(address), 256)) { + m.readable = true; + const auto* bytes = reinterpret_cast(address); + for (int i = 0; i < 256 && !m.nonzero; ++i) m.nonzero = bytes[i] != 0; + } + return m; +} +LONG64 detile_decline_counts[std::size(detile_declines)]; +// decline: detile_decline's verdict (detile_declines, d3d12_draw.inl; 0 = not asked). Key bits: reason 0-3, dimension +// 4-7, layout 8-16, format 20-27, mips > 1 28, announced 29, nonzero 30, decline 31-34, first 256 bytes readable 35. +// The memory of a refused call, read once for the census and the marker (and not at all when both are off). +RefusedMemory refused_call_memory(const MemoryShaderResourceView* input) +{ + if (!texture_census_on() && !buffer_heap_index_on()) return {}; + return x2w_local::readable(input, sizeof(*input)) ? refused_memory(input->address) : RefusedMemory{}; +} +void census_refusal(const char* reason, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, unsigned decline, + const RefusedMemory& memory) +{ + if (!texture_census_on()) return; + census_memory_srv_outcome(mso_refused); + u64 r = 0; + while (r < std::size(census_reasons) && std::strcmp(census_reasons[r], reason) != 0) ++r; + const bool resource_ok = x2w_local::readable(resource, sizeof(*resource)); + const bool input_ok = x2w_local::readable(input, sizeof(*input)); + const u64 address = input_ok ? input->address : 0; + if (decline >= std::size(detile_declines)) decline = 0; + const u64 dim = resource_ok && resource->Dimension >= 0 && resource->Dimension <= 4 ? resource->Dimension : 7; + const u64 layout = resource_ok ? (static_cast(resource->Layout) & 0x1ff) : 0x1ff; + const u64 format = resource_ok ? (static_cast(resource->Format) & 0xff) : 0xff; + const u64 chain = resource_ok && resource->MipLevels > 1; + const u64 key = r | dim << 4 | layout << 8 | format << 20 | chain << 28 | u64{address && xg_announced(address)} << 29 | + u64{memory.nonzero} << 30 | u64{decline} << 31 | u64{memory.readable} << 35; + if (decline) { + InterlockedIncrement64(&detile_decline_counts[decline]); + LONG64 n = 0; + for (LONG64 c : detile_decline_counts) n += c; + if (census_every_event() || (n & (n - 1)) == 0) { + char parts[512]; + int used = 0; + for (std::size_t i = 1; i < std::size(detile_declines); ++i) + used += std::snprintf(parts + used, sizeof(parts) - used, "%s%s %lld", i > 1 ? ", " : "", detile_declines[i], detile_decline_counts[i]); + log("x2w-texcensus detile declines of refused texture calls %lld (X2W_MEMORY_SRV_DETILE): %s", n, parts); + } + } + std::lock_guard lock(refusal_census_mutex); + const bool fresh = ++refusal_census[key] == 1; + const LONG64 total = ++refusal_census_total; + // The first call of each class (at most 96 classes): every field, the layout's size and how much of it is readable. + static LONG described_classes; + if (fresh && resource_ok && input_ok && first_calls(described_classes, 96)) { + char resource_text[224], view_text[256]; + x2w_startup::report_resource(resource_text, sizeof(resource_text), resource); + x2w_startup::report_view(view_text, sizeof(view_text), &input->view); + const auto l = detile_layout(*resource); + const std::size_t want = l.valid ? static_cast((std::min)(l.size, u64{1} << 30)) : 0; + log("x2w-texcensus new refusal class: %s res{%s} view{%s} address 0x%llx; detile: %s; memory %s; console layout %llu bytes, %zu " + "readable from the address", reason, resource_text, view_text, address, detile_declines[decline], + !memory.readable ? "unreadable" : memory.nonzero ? "nonzero" : "zero", l.valid ? l.size : 0ull, + want && address ? readable_window(address, want) : 0); + } + if (census_every_event() || (total >= 256 && (total & (total - 1)) == 0)) log_refusal_classes("threshold"); +} + +u64 __stdcall device_slot61_census(Wrapper* self, u64 rdx, u64 r8, u64 r9) +{ + if (noop_census_enabled()) { // what the no-op it replaces still reports + const u64 args[8] = {reinterpret_cast(self), rdx, r8, r9, 0, 0, 0, 0}; + noop_census_note(device_kind, 61, args, reinterpret_cast(_ReturnAddress()) - reinterpret_cast(GetModuleHandleW(nullptr))); + } + static LONG calls; + if (first_calls(calls, 16)) { + char hex[200] = "unreadable"; + if (x2w_local::readable(reinterpret_cast(rdx), 64)) { + const auto* w = reinterpret_cast(rdx); + int used = 0; + for (int i = 0; i < 16; ++i) used += std::snprintf(hex + used, sizeof(hex) - used, "%08x ", w[i]); + } + log("x2w-texcensus Device::slot61 (sampler?) rdx=0x%llx r8=0x%llx r9=0x%llx words %s", rdx, r8, r9, hex); + } + return 0; +} + // The first check that refuses a call, in the order the checks run; null when every check passes. const char* memory_srv_refusal(const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { @@ -606,12 +1147,103 @@ void log_refused_memory_srv(const char* what, const char* reason, const D3D12_RE log("%s", line); } +void mark_refused_destination(u64 destination, const char* reason, const D3D12_RESOURCE_DESC* resource, + const MemoryShaderResourceView* input, unsigned decline, const RefusedMemory& memory) +{ + if (!buffer_heap_index_on() || !destination || !title_backed(destination, 32) || !x2w_local::writable(reinterpret_cast(destination), 32)) + return; + std::uint32_t marker[8] = {refused_view_magic, refusal_code(reason), 1u << 31, 0, 0, 0, 0, 0}; + if (x2w_local::readable(resource, sizeof(*resource))) { + const auto& r = *resource; + marker[2] |= (static_cast(r.Format) & 0xff) | (static_cast(r.Layout) & 0x1ff) << 8 | + (static_cast(r.Dimension) & 7) << 17 | (r.MipLevels < 15 ? r.MipLevels : 15u) << 20 | (decline & 15) << 24; + marker[3] = r.Width > 0xffffffffull ? 0xffffffffu : static_cast(r.Width); + marker[4] = r.Height; + marker[5] = r.DepthOrArraySize; + } + if (x2w_local::readable(input, sizeof(*input))) { + marker[5] |= std::uint32_t{memory.readable} << 16 | std::uint32_t{memory.nonzero} << 17; + marker[6] = static_cast(input->address); + marker[7] = static_cast(input->address >> 32); + } + std::memcpy(reinterpret_cast(destination), marker, sizeof(marker)); + if (const u64 desktop = desktop_cpu_handle(destination)) { + AcquireSRWLockExclusive(¬e_lock); + if (std::uint32_t* slot = shadow_slot(desktop)) *slot = 0; + ReleaseSRWLockExclusive(¬e_lock); + } +} +LONG64 vdesc_no_buffer, vdesc_unaligned, vdesc_no_destination, vdesc_layout, vdesc_ticks[3], vdesc_lock_taken; +LONG64 qpc_now() +{ + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return t.QuadPart; +} +bool write_buffer_descriptor(u64 destination, const MemoryShaderResourceView* input, bool found_buffer, LONG64 lookup_ticks) +{ + if (!buffer_heap_index_on()) return false; + const auto counted = [](LONG64& which) { + InterlockedIncrement64(&which); + const LONG64 n = vdesc_no_buffer + vdesc_unaligned + vdesc_no_destination + vdesc_layout; + if ((n & (n - 1)) == 0) { + static const double us_per_tick = [] { + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + return 1e6 / static_cast(f.QuadPart); + }(); + const double written = static_cast((std::max)(1ll, vdesc_no_buffer + vdesc_unaligned)); + log("x2w-memsrv buffer descriptors: written %lld (no buffer %lld, buffer at an offset the view cannot name %lld), not written: " + "destination not title memory %lld, view not encodable %lld; per written call: buffer lookup %.2f us, destination checks " + "%.2f us, shadow clear %.2f us (lock taken %lld)", vdesc_no_buffer + vdesc_unaligned, vdesc_no_buffer, vdesc_unaligned, + vdesc_no_destination, vdesc_layout, vdesc_ticks[0] * us_per_tick / written, vdesc_ticks[1] * us_per_tick / written, + vdesc_ticks[2] * us_per_tick / written, vdesc_lock_taken); + } + }; + const LONG64 t0 = qpc_now(); + if (!destination || !title_backed(destination, 32) || !x2w_local::writable(reinterpret_cast(destination), 32)) { + counted(vdesc_no_destination); + return false; + } + const LONG64 t1 = qpc_now(); + x2w_startup::BufferViewLayout l; + if (!x2w_startup::buffer_view_layout_from_desc(false, reinterpret_cast(&input->view), 40, l) || + l.kind == x2w_startup::BufferViewKind::unknown || !l.num_records || ((input->address + l.offset) >> 48)) { + counted(vdesc_layout); + return false; + } + std::uint32_t words[8]; + x2w_startup::gfx10_buffer_words(l, words); + const u64 base = input->address + l.offset; + words[0] = static_cast(base); + words[1] |= static_cast(base >> 32) & 0xffff; + std::memcpy(reinterpret_cast(destination), words, sizeof(words)); + if (const u64 desktop = desktop_cpu_handle(destination)) { + // Most slots hold no id (the title rewrites the same slots with V#s): look under the shared lock first. + if (shadow_id(desktop)) { + InterlockedIncrement64(&vdesc_lock_taken); + AcquireSRWLockExclusive(¬e_lock); + if (std::uint32_t* slot = shadow_slot(desktop)) *slot = 0; + ReleaseSRWLockExclusive(¬e_lock); + } + } + const LONG64 t2 = qpc_now(); + InterlockedAdd64(&vdesc_ticks[0], lookup_ticks); + InterlockedAdd64(&vdesc_ticks[1], t1 - t0); + InterlockedAdd64(&vdesc_ticks[2], t2 - t1); + counted(found_buffer ? vdesc_unaligned : vdesc_no_buffer); + static LONG shown; + if (first_calls(shown, 8)) + log("x2w-memsrv buffer descriptor written at 0x%llx (X2W_BUFFER_HEAP_INDEX): base 0x%llx, stride %u, records %u, word 3 0x%08x%s", destination, + base, l.index_stride, l.num_records, words[3], found_buffer ? " (a buffer is there, at an offset the view cannot name)" : ""); + return true; +} // Counts a refusal (memory_srv_census) and logs its line while the first 8 refusals last, and also for // the first refusal of each of the first few distinct shapes (MemorySrvCensus::detail_shapes). void refuse_memory_srv(LONG& refused, const char* what, const char* reason, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { - const bool within_limit = first_calls(refused, 8); + const bool within_limit = first_calls(refused, noop_census_enabled() ? 2048 : 8); const bool new_shape = memory_srv_census.note(reason, x2w_local::readable(resource, sizeof(*resource)) ? resource : nullptr); if (within_limit || new_shape) log_refused_memory_srv(what, reason, resource, input, destination); } @@ -672,12 +1304,73 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou X2W_ZONE("device_memory_srv"); static LONG refused; check_resource_address_index(); + if (noop_census_enabled()) { + static LONG64 calls; + const LONG64 n = InterlockedIncrement64(&calls); + CensusHeap h{}; + const bool in_heap = noop_census_heap_index(destination, &h); + if (n <= 8 || (n & (n - 1)) == 0) + log("x2w-noop-census memory SRV call %lld: destination 0x%llx = %s index 0x%llx of the heap at 0x%llx", n, destination, + in_heap ? (h.desktop ? "DESKTOP" : "title") : "no heap", h.index, h.base); + } + const bool described = destination && x2w_local::readable(resource, sizeof(*resource)) && + x2w_local::readable(input, sizeof(*input)) && input->address; + const bool plain = described && memory_srv_linear_on() && linear_memory_srv(*resource, input->view); + if ((plain || (described && memory_srv_announced_on() && announced_linear_srv(*resource, input->view, input->address))) && + memory_srv_destination(destination)) { + Wrapper* texture = existing_memory_texture(input->address, *resource); + if (!texture) texture = publish_linear_texture(self, input->address, *resource); + if (texture) { + static LONG64 linear_views; + const LONG64 n = InterlockedIncrement64(&linear_views); + if ((n & (n - 1)) == 0) { + std::size_t textures; + u64 bytes; + { + std::lock_guard lock(linear_srv_mutex); + textures = linear_srv_textures.size(); + bytes = linear_srv_bytes; + } + log("x2w-memsrv linear memory SRVs written: %lld, %zu textures, %llu KiB (latest destination 0x%llx)", n, textures, + bytes >> 10, destination); + } + note_linear_form(linear_form(input->view.ViewDimension), destination); + census_memory_srv_outcome(plain ? mso_linear : mso_announced); + view_slot<18, 2>(self, reinterpret_cast(texture), reinterpret_cast(&input->view), destination, 0); + return; + } + } + unsigned decline = 0; + if (memory_srv_detile_on() && destination && x2w_local::readable(resource, sizeof(*resource)) && + x2w_local::readable(input, sizeof(*input)) && resource->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { + decline = detile_decline(*resource, input->view, input->address, input->address != 0); + if (!decline && !memory_srv_destination(destination)) decline = 9; + } + if (described && memory_srv_detile_on() && resource->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && !decline) { + Wrapper* texture = existing_memory_texture(input->address, *resource); + if (!texture) texture = publish_linear_texture(self, input->address, *resource, true); + if (!texture) decline = 10; + if (texture) { + static LONG shown; + if (first_calls(shown, 16)) + log("x2w-memsrv detiled memory SRV at 0x%llx: %llux%ux%u mips %u fmt %d layout 0x%x dim %d", input->address, + resource->Width, resource->Height, resource->DepthOrArraySize, resource->MipLevels, resource->Format, + static_cast(resource->Layout), resource->Dimension); + note_linear_form(linear_form(input->view.ViewDimension), destination); + census_memory_srv_outcome(mso_detiled); + view_slot<18, 2>(self, reinterpret_cast(texture), reinterpret_cast(&input->view), destination, 0); + return; + } + } if (const char* reason = memory_srv_refusal(resource, input, destination)) { refuse_memory_srv(refused, "unsupported memory SRV arguments", reason, resource, input, destination); + const RefusedMemory memory = refused_call_memory(input); + census_refusal(reason, resource, input, decline, memory); + mark_refused_destination(destination, reason, resource, input, decline, memory); return; } // A single-element texture is published by address like a tiled view: its texel is read at offset 0. - if (x2w_startup::supports_single_element_srv(*resource, input->view)) { + if (upstream_console_srv_on() && x2w_startup::supports_single_element_srv(*resource, input->view)) { if (gpu_written_overlap(input->address, x2w_startup::single_element_bytes(*resource))) { refuse_memory_srv(refused, "GPU-written resource at the supplied address", "gpu_written_resource", resource, input, destination); @@ -697,19 +1390,34 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou if (resource->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { const u64 elem_bytes = x2w_startup::buffer_srv_element_bytes(input->view); const u64 span_bytes = (input->view.Buffer.FirstElement + input->view.Buffer.NumElements) * elem_bytes; + const LONG64 lookup_start = buffer_heap_index_on() ? qpc_now() : 0; Wrapper* buffer = existing_memory_buffer(self, input->address, span_bytes); - if (!buffer) { - buffer = unplaced_memory_buffer(self, input->address, span_bytes, *resource); - } + const LONG64 lookup_ticks = buffer_heap_index_on() ? qpc_now() - lookup_start : 0; const ResourceInfo* info = buffer ? resource_info(buffer) : nullptr; D3D12_SHADER_RESOURCE_VIEW_DESC adjusted{}; + if ((!buffer || !info) && memory_srv_buffer_on()) { + if (Wrapper* standin = standin_memory_buffer(input->address, *resource, span_bytes)) { + note_linear_form(lf_buffer_srv, destination); + census_memory_srv_outcome(mso_standin); + view_slot<18, 2>(self, reinterpret_cast(standin), reinterpret_cast(&input->view), destination, 0); + return; + } + } if (!buffer || !info || !x2w_startup::resolve_buffer_srv_desc(reinterpret_cast(buffer->own().title_memory), info->console.Width, input->address, input->view, adjusted)) { + if (write_buffer_descriptor(destination, input, buffer && info, lookup_ticks)) { + census_memory_srv_outcome(mso_descriptor); + return; + } refuse_memory_srv(refused, "unavailable buffer at the supplied address", "buffer_unavailable", resource, input, destination); + const RefusedMemory memory = refused_call_memory(input); + census_refusal("buffer_unavailable", resource, input, 0, memory); + mark_refused_destination(destination, "buffer_unavailable", resource, input, 0, memory); return; } + census_memory_srv_outcome(mso_buffer); view_slot<18, 2>(self, reinterpret_cast(buffer), reinterpret_cast(&adjusted), destination, 0); note_memory_srv_write(resource, input, destination); return; @@ -751,8 +1459,12 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou if (!texture) { refuse_memory_srv(refused, "unavailable texture at the supplied base and layout", held ? held : "texture_unavailable", resource, input, destination); + const RefusedMemory memory = refused_call_memory(input); + census_refusal("texture_unavailable", resource, input, decline, memory); + mark_refused_destination(destination, "texture_unavailable", resource, input, decline, memory); return; } + census_memory_srv_outcome(mso_tiled); view_slot<18, 2>(self, reinterpret_cast(texture), reinterpret_cast(&input->view), destination, 0); note_memory_srv_write(resource, input, destination); } diff --git a/src/startup_stubs/d3d12_mesh.inl b/src/startup_stubs/d3d12_mesh.inl new file mode 100644 index 0000000000..d46200cb66 --- /dev/null +++ b/src/startup_stubs/d3d12_mesh.inl @@ -0,0 +1,1201 @@ + +bool mesh_enabled() +{ + static const bool on = x2w_local::env_on("X2W_MESH"); + return on; +} + +enum MeshSkip { mesh_no_translation, mesh_failed, mesh_no_pso, mesh_no_targets, mesh_tier, mesh_no_record, mesh_rtv_variant, mesh_bind, mesh_compiling, mesh_skips }; +LONG mesh_calls, mesh_issued, mesh_skipped[mesh_skips]; +thread_local int mesh_last_skip = -1; +void mesh_skip(MeshSkip why) { InterlockedIncrement(&mesh_skipped[why]); mesh_last_skip = why; } +constexpr const char* mesh_skip_names[mesh_skips] = {"no translation", "translation failed", "no PSO", "no targets", "tier", + "no mesh record", "rtv variant", "bind refused", "PSO compiling"}; + +// ---- Keys, at slot-57 creation -------------------------------------------------------------------------------- + +struct MeshRecordKey { + u64 key = 0; + bool keyed = false; // false: a mesh record without a key (no root blob, unreadable pixel code) +}; +SRWLOCK mesh_key_lock = SRWLOCK_INIT; +std::unordered_map& mesh_record_keys() { static std::unordered_map m; return m; } +LONG mesh_records_keyed, mesh_records_unkeyed; + +// Device slot 57, after note_pipeline (X2W_MESH=1 only). The code blobs are hashed while the title still holds them. +void mesh_note57(const void* desc, const Wrapper* self) +{ + if (!mesh_enabled() || !desc || !self || readable_window(reinterpret_cast(desc), 0x80) < 0x80) return; + u64 w[16]; + std::memcpy(w, desc, sizeof(w)); + if (w[9] && w[10]) return; // vertex code: the draw key (translation_for) + const auto* b = reinterpret_cast(w[13]); + const std::size_t b_bytes = static_cast(w[14]); + if (!b || !b_bytes || b_bytes > (1u << 20) || !x2w_local::readable(b, b_bytes)) return; + MeshRecordKey k; + std::vector root_blob; + if (Wrapper* root = as_wrapper(reinterpret_cast(w[0]))) { + AcquireSRWLockShared(¬e_lock); + const auto found = root_blobs().find(root); + if (found != root_blobs().end()) root_blob = found->second; + ReleaseSRWLockShared(¬e_lock); + } + const auto* a = reinterpret_cast(w[5]); + std::size_t a_bytes = static_cast(w[6]); + bool a_ok = true; + if (!a || !a_bytes) a = nullptr, a_bytes = 0; // depth-only: empty a + else a_ok = a_bytes <= (1u << 20) && x2w_local::readable(a, a_bytes); + if (!root_blob.empty() && a_ok) { + k.key = pipeline_key(a, a_bytes, b, b_bytes, root_blob); + k.keyed = true; + } + InterlockedIncrement(k.keyed ? &mesh_records_keyed : &mesh_records_unkeyed); + static LONG shown; + if (first_calls(shown, 4)) + log("x2w-mesh slot 57 pipeline %p: mesh record, pixel code %zu bytes, mesh code %zu bytes, root %zu bytes -> %s %016llx", + static_cast(self), a_bytes, b_bytes, root_blob.size(), k.keyed ? "key" : "NO KEY", k.key); + AcquireSRWLockExclusive(&mesh_key_lock); + mesh_record_keys()[self] = k; + ReleaseSRWLockExclusive(&mesh_key_lock); +} + +// The mesh key of a bound pipeline: its own slot-57 record, else the base chain of slot-55 pipelines (depth 8). +bool mesh_key_of(const Wrapper* pipeline, MeshRecordKey* out) +{ + for (int depth = 0; pipeline && depth < 8; ++depth) { + bool found = false; + AcquireSRWLockShared(&mesh_key_lock); + const auto it = mesh_record_keys().find(pipeline); + if (it != mesh_record_keys().end()) *out = it->second, found = true; + ReleaseSRWLockShared(&mesh_key_lock); + if (found) return true; + const PipelineInfo* info = pipeline_info(pipeline); + pipeline = info && info->path == 55 ? info->base : nullptr; + } + return false; +} + +// ---- Translations, per key (off draw_lock) ------------------------------------------------------------------ + +enum MeshFma { mesh_fma_exact, mesh_fma_precise, mesh_fma_unstated, mesh_fma_rules }; +LONG mesh_fma_loaded[mesh_fma_rules]; +const char* const mesh_fma_names[mesh_fma_rules] = {"exact", "precise", "unstated"}; + +bool mesh_double_ops() +{ + static const bool ok = [] { + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + const HRESULT hr = device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)); + const bool doubles = SUCCEEDED(hr) && options.DoublePrecisionFloatShaderOps; + log("x2w-mesh DoublePrecisionFloatShaderOps %d (0x%08lx): `fma exact` translations %s", doubles ? 1 : 0, static_cast(hr), + doubles ? "allowed" : "refused"); + return doubles; + }(); + return ok; +} + +// load_translation's stage hook (d3d12_draw.inl): 0 not a mesh manifest, 1 `stage mesh` with .ms.cso (and the +// optional .ps.cso) loaded, -1 a mesh manifest whose stage files cannot be read or whose fma rule cannot run here. +int load_mesh_stages(Translation& tr, const std::string& manifest) +{ + bool mesh = false; + unsigned threads = 0, vertices = 0, primitives = 0; + int fma = mesh_fma_unstated; + std::string fma_text; + for (std::size_t at = 0; at < manifest.size();) { + std::size_t end = manifest.find('\n', at); + if (end == std::string::npos) end = manifest.size(); + std::string line = manifest.substr(at, end - at); + if (!line.empty() && line.back() == '\r') line.pop_back(); + at = end + 1; + if (line == "stage mesh") mesh = true; + else if (line.compare(0, 4, "fma ") == 0) fma_text = line.substr(4), fma = fma_text == "exact" ? mesh_fma_exact : fma_text == "precise" ? mesh_fma_precise : -1; + else std::sscanf(line.c_str(), "ms %u %u %u", &threads, &vertices, &primitives); + } + if (!mesh) return 0; + if (fma < 0) { + log("x2w-mesh pipeline %016llx: translation failed (unknown fma rule \"%s\")", tr.key, fma_text.c_str()); + return -1; + } + if (fma != mesh_fma_precise && !mesh_double_ops()) { + log("x2w-mesh pipeline %016llx: translation failed (fma %s needs DoublePrecisionFloatShaderOps)", tr.key, mesh_fma_names[fma]); + return -1; + } + wchar_t path[MAX_PATH]; + if (!cache_path(path, L"", tr.key, L".ms.cso") || FAILED(D3DReadFileToBlob(path, &tr.ms))) { + log("x2w-mesh pipeline %016llx: translation failed (no readable .ms.cso)", tr.key); + return -1; + } + if (cache_path(path, L"", tr.key, L".ps.cso") && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES && FAILED(D3DReadFileToBlob(path, &tr.ps))) { + log("x2w-mesh pipeline %016llx: translation failed (.ps.cso present but unreadable)", tr.key); + return -1; + } + log("x2w-mesh pipeline %016llx: mesh stage %zu bytes (ms %u threads, %u vertices, %u primitives), pixel stage %s, fma %s", tr.key, + tr.ms->GetBufferSize(), threads, vertices, primitives, tr.ps ? "yes" : "none (depth-only)", mesh_fma_names[fma]); + InterlockedIncrement(&mesh_fma_loaded[fma]); + int rules = 0; + for (LONG& n : mesh_fma_loaded) rules += InterlockedCompareExchange(&n, 0, 0) != 0; + static LONG mixed; + if (rules > 1 && InterlockedExchange(&mixed, 1) == 0) + log("x2w-mesh shader cache mixes fma rules (from %016llx): exact %ld, precise %ld, unstated %ld loaded so far; positions may differ " + "between pipelines (not refused)", tr.key, mesh_fma_loaded[mesh_fma_exact], mesh_fma_loaded[mesh_fma_precise], mesh_fma_loaded[mesh_fma_unstated]); + return 1; +} + +struct MeshPso { + int state = 0; // 0 new, 3 compiling, 1 ready, 2 failed (never retried) + ID3D12PipelineState* pso = nullptr; +}; +struct MeshEntry { + volatile int state = 0; // 0 new, 3 loading, 1 ready, 2 failed (never retried), 4 no manifest (checked again after 5 s) + volatile ULONGLONG retry_at = 0; + Translation* tr = nullptr; + std::unordered_map psos; // by target formats, DSV format and fixed-function state + bool issued_once = false; + unsigned refusals_logged = 0; // bit per MeshSkip: its "call refused" line was written (mesh_lock) + volatile LONG uses = 0; // keyed calls since the last report (report_mesh_keys), counted without a lock + volatile LONG seen = 0; // 1 once the "first bound" line was written +}; +SRWLOCK mesh_lock = SRWLOCK_INIT; +CONDITION_VARIABLE mesh_loaded = CONDITION_VARIABLE_INIT; +std::unordered_map& mesh_entries() { static std::unordered_map m; return m; } // node-based: references stay valid + +// The entry of `key` in its final state for now (1, 2 or 4). One thread loads a key; others wait for that key only. +MeshEntry& loaded_mesh(u64 key) +{ + AcquireSRWLockExclusive(&mesh_lock); + MeshEntry& e = mesh_entries()[key]; + while (e.state == 3) SleepConditionVariableSRW(&mesh_loaded, &mesh_lock, INFINITE, 0); + if (e.state == 1 || e.state == 2 || (e.state == 4 && GetTickCount64() < e.retry_at)) { + ReleaseSRWLockExclusive(&mesh_lock); + return e; + } + const bool first = e.state == 0; + e.state = 3; + ReleaseSRWLockExclusive(&mesh_lock); + int state = 4; + Translation* tr = nullptr; + wchar_t path[MAX_PATH]; + if (cache_path(path, L"", key, L".txt") && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) { + tr = new Translation; + tr->key = key; + load_translation(*tr); + if (tr->state == 1 && tr->ms) { + state = 1; + } else { + log("x2w-mesh pipeline %016llx: translation failed (%s)", key, + tr->state == 1 ? "manifest has no `stage mesh`" : "manifest, stage files or root signature rejected"); + state = 2; + } + } else { + static LONG shown; + if (first && first_calls(shown, 1024)) log("x2w-mesh pipeline %016llx: no translation", key); + } + AcquireSRWLockExclusive(&mesh_lock); + // tr and retry_at before state: mesh_prepare reads a kept entry's state without mesh_lock. + e.tr = state == 1 ? tr : nullptr; + e.retry_at = state == 4 ? GetTickCount64() + 5000 : 0; + MemoryBarrier(); + e.state = state; + ReleaseSRWLockExclusive(&mesh_lock); + WakeAllConditionVariable(&mesh_loaded); + return e; // a failed Translation is kept (leaked) like draw translations: never retried +} + +// Once per key and reason (first 4096 lines PER REASON, so keys refused for one reason cannot use up the lines of +// another): "x2w-mesh pipeline K: call refused ()", for the refusals that have no per-key line of their own +// (no targets, rtv variant, no PSO, translation taken, bind refused). "no translation" and "translation failed (...)" +// are written once per key by loaded_mesh / load_mesh_stages. +// A refused call of a key whose line is out pays no lock (a racy read of the bit: at worst the lock is taken once more). +bool mesh_refusal_logged(const MeshEntry& e, MeshSkip why) { return (e.refusals_logged & (1u << why)) != 0; } +void mesh_refusal_line(MeshEntry& e, u64 key, MeshSkip why, const char* detail) +{ + if (mesh_refusal_logged(e, why)) return; + AcquireSRWLockExclusive(&mesh_lock); + const bool first = (e.refusals_logged & (1u << why)) == 0; + e.refusals_logged |= 1u << why; + ReleaseSRWLockExclusive(&mesh_lock); + static LONG shown[mesh_skips]; + if (first && first_calls(shown[why], 4096)) log("x2w-mesh pipeline %016llx: call refused (%s)", key, detail); +} + + +// Every mesh call with a keyed record, after its translation lookup (state: 1 ok, 2 fail, 4 missing). Counted in the +// key's entry without a lock (the entry map is node-based; report_mesh_keys collects the counts). +void mesh_note_use(MeshEntry& e, u64 key) +{ + InterlockedIncrement(&e.uses); + if (e.seen || InterlockedExchange(&e.seen, 1)) return; + static LONG shown; + if (first_calls(shown, 4096)) + log("x2w-mesh key %016llx first bound frame %ld (cache: %s)", key, frame_number, e.state == 1 ? "ok" : e.state == 2 ? "fail" : "missing"); +} + +void report_mesh_keys(LONG frames) +{ + std::vector> uses; + std::size_t seen = 0; + AcquireSRWLockShared(&mesh_lock); + for (auto& [key, e] : mesh_entries()) { + if (const LONG n = InterlockedExchange(&e.uses, 0)) uses.emplace_back(key, n); + if (e.seen) ++seen; + } + ReleaseSRWLockShared(&mesh_lock); + LONG calls = 0; + for (const auto& u : uses) calls += u.second; + std::sort(uses.begin(), uses.end(), [](const auto& x, const auto& y) { return x.second != y.second ? x.second > y.second : x.first < y.first; }); + const std::size_t top = uses.size() < 64 ? uses.size() : 64; + if (top <= 32) { + char line[1100]; + int n = 0; + for (std::size_t i = 0; i < top; ++i) n += std::snprintf(line + n, sizeof(line) - n, " %016llx:%ld", uses[i].first, uses[i].second); + log("x2w-mesh %ld frames: keys %zu distinct, calls %ld; top:%s (keys seen since start %zu)", frames, uses.size(), calls, top ? line : " none", seen); + return; + } + log("x2w-mesh %ld frames: keys %zu distinct, calls %ld; top: 64 keys on the next 2 lines (keys seen since start %zu)", frames, uses.size(), calls, seen); + for (std::size_t from = 0; from < top; from += 32) { + const std::size_t to = top < from + 32 ? top : from + 32; + char line[1100]; + int n = 0; + for (std::size_t i = from; i < to; ++i) n += std::snprintf(line + n, sizeof(line) - n, " %016llx:%ld", uses[i].first, uses[i].second); + log("x2w-mesh %ld frames top %zu-%zu:%s", frames, from + 1, to, line); + } +} + +// ---- Desktop pipeline --------------------------------------------------------------------------------------- + +bool mesh_dump_record_groups(std::uint32_t (&xyz)[3]) +{ + if (!mesh_trace_record || mesh_trace_stride < 12 || !x2w_local::readable(mesh_trace_record, 12)) return false; + std::memcpy(xyz, mesh_trace_record, 12); + return true; +} +bool mesh_cull_flip() +{ + static const bool flip = x2w_local::env_on("X2W_MESH_STATE_CULL_FLIP"); + return flip; +} +const x2w_pipeline_state::Switches& mesh_switches() +{ + static const x2w_pipeline_state::Switches s = [] { + x2w_pipeline_state::Switches v; + if (x2w_local::env_on("X2W_MESH_STATE")) v.depth = v.cull = v.blend = true; + // Without a rebuild: X2W_MESH_STATE_NOCULL=1 keeps the default rasterizer (cull none); + // X2W_MESH_STATE_CULL_FLIP=1 inverts the decoded front face (apply_draw_state's flip covers slot-55 patches only). + if (v.cull && x2w_local::env_on("X2W_MESH_STATE_NOCULL")) v.cull = false; + // X2W_DRAW_STATE_DEPTHCLIP=1: the decoded depth clip alone (also without X2W_MESH_STATE); cull includes it. + v.depthclip = draw_state::switches().depthclip; // parsed with the others: X2W_DRAW_STATE=0 turns it off too + if (v.depthclip) log("x2w-mesh X2W_DRAW_STATE_DEPTHCLIP=1: mesh PSOs take depth clip from the pipeline's rasterizer state"); + if (v.depth) + log("x2w-mesh X2W_MESH_STATE=1: mesh PSOs take depth-stencil, %sblend from the pipeline's state block%s", v.cull ? "rasterizer and " : "", + !v.cull ? " (X2W_MESH_STATE_NOCULL: rasterizer default)" : mesh_cull_flip() ? " (X2W_MESH_STATE_CULL_FLIP: front face inverted)" : ""); + return v; + }(); + return s; +} +LONG mesh_state_changed, mesh_state_fallback; // PSOs whose decoded state differs from the default; created with the default after a failure +void mesh_state_desc(const BoundPipeline& bound, const Pass& pass, D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, u64& key, + bool* decoded = nullptr, D3D12_GRAPHICS_PIPELINE_STATE_DESC* fallback = nullptr) +{ + const DXGI_FORMAT dsv_format = pass.dsv_format != DXGI_FORMAT_UNKNOWN ? pass.dsv_format : bound.dsv_format; + desc = {}; + for (auto& target : desc.BlendState.RenderTarget) + target = {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}; + static const bool default_blend = x2w_local::env_on("X2W_DRAW_DEFAULT_BLEND"); + if (default_blend) + for (auto& target : desc.BlendState.RenderTarget) + target = {TRUE, FALSE, D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, + D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; + if (bound.has_depth_stencil) desc.DepthStencilState = bound.depth_stencil; + desc.SampleMask = ~0u; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.NumRenderTargets = pass.target_count; + for (UINT i = 0; i < pass.target_count; ++i) desc.RTVFormats[i] = pass.target_formats[i]; + desc.DSVFormat = dsv_format; + desc.SampleDesc.Count = 1; + const auto& s = mesh_switches(); + if (s.depth || s.cull || s.blend || s.depthclip) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC before = desc; + const bool changed = apply_draw_state(bound, pass, desc, s); + if (s.cull && mesh_cull_flip() && std::memcmp(&before.RasterizerState, &desc.RasterizerState, sizeof(desc.RasterizerState)) != 0) + desc.RasterizerState.FrontCounterClockwise = !desc.RasterizerState.FrontCounterClockwise; + if (decoded) *decoded = changed; + if (changed && fallback) *fallback = before; + } + key = pass.target_count; + for (UINT i = 0; i < pass.target_count; ++i) key = key * 131 + static_cast(pass.target_formats[i]); + key = fnv_bytes(&dsv_format, sizeof(dsv_format), key); + const auto mix = [&key](u64 v) { key = fnv_bytes(&v, sizeof(v), key); }; + const auto& b = desc.BlendState; + mix(b.AlphaToCoverageEnable), mix(b.IndependentBlendEnable); + for (const auto& t : b.RenderTarget) { + mix(t.BlendEnable), mix(t.LogicOpEnable), mix(t.SrcBlend), mix(t.DestBlend), mix(t.BlendOp), mix(t.SrcBlendAlpha); + mix(t.DestBlendAlpha), mix(t.BlendOpAlpha), mix(t.LogicOp), mix(t.RenderTargetWriteMask); + } + const auto& d = desc.DepthStencilState; + mix(d.DepthEnable), mix(d.DepthWriteMask), mix(d.DepthFunc), mix(d.StencilEnable), mix(d.StencilReadMask), mix(d.StencilWriteMask); + for (const auto* f : {&d.FrontFace, &d.BackFace}) + mix(f->StencilFailOp), mix(f->StencilDepthFailOp), mix(f->StencilPassOp), mix(f->StencilFunc); + const auto& r = desc.RasterizerState; + mix(r.FillMode), mix(r.CullMode), mix(r.FrontCounterClockwise), mix(static_cast(static_cast(r.DepthBias))); + std::uint32_t bits; + std::memcpy(&bits, &r.DepthBiasClamp, 4), mix(bits); + std::memcpy(&bits, &r.SlopeScaledDepthBias, 4), mix(bits); + mix(r.DepthClipEnable), mix(r.MultisampleEnable), mix(r.AntialiasedLineEnable), mix(r.ForcedSampleCount), mix(r.ConservativeRaster); +} + +template +struct alignas(void*) MeshSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = Type; + Value value{}; +}; +struct MeshStream { + MeshSubobject root; + MeshSubobject ms; + MeshSubobject ps; + MeshSubobject blend; + MeshSubobject sample_mask; + MeshSubobject rasterizer; + MeshSubobject depth_stencil; + MeshSubobject dsv_format; + MeshSubobject rtv_formats; + MeshSubobject sample; +}; + +ID3D12PipelineState* create_mesh_pso(const Translation& tr, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& d, HRESULT* result) +{ + static ID3D12Device2* device2 = [] { + ID3D12Device2* d2 = nullptr; + device_of(the_device)->QueryInterface(IID_PPV_ARGS(&d2)); + return d2; + }(); + *result = E_NOINTERFACE; + if (!device2) return nullptr; + MeshStream s; + s.root.value = tr.root; + s.ms.value = {tr.ms->GetBufferPointer(), tr.ms->GetBufferSize()}; + if (tr.ps) s.ps.value = {tr.ps->GetBufferPointer(), tr.ps->GetBufferSize()}; + s.blend.value = d.BlendState; + s.sample_mask.value = d.SampleMask; + s.rasterizer.value = d.RasterizerState; + s.depth_stencil.value = d.DepthStencilState; + s.dsv_format.value = d.DSVFormat; + s.rtv_formats.value.NumRenderTargets = d.NumRenderTargets; + for (UINT i = 0; i < 8; ++i) s.rtv_formats.value.RTFormats[i] = d.RTVFormats[i]; + s.sample.value = d.SampleDesc; + const D3D12_PIPELINE_STATE_STREAM_DESC stream{sizeof(s), &s}; + ID3D12PipelineState* pso = nullptr; + *result = device2->CreatePipelineState(&stream, IID_PPV_ARGS(&pso)); + return SUCCEEDED(*result) ? pso : nullptr; +} + +void mesh_pso_compile(const Translation& tr, MeshPso& slot, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, + const D3D12_GRAPHICS_PIPELINE_STATE_DESC& fallback, bool decoded, UINT target_count, DXGI_FORMAT format0, bool async) +{ + LARGE_INTEGER t0, t1, f; + QueryPerformanceCounter(&t0); + HRESULT hr = E_FAIL; + ID3D12PipelineState* pso = create_mesh_pso(tr, desc, &hr); + QueryPerformanceCounter(&t1); + QueryPerformanceFrequency(&f); + const auto& d = desc.DepthStencilState; + const auto& ms = mesh_switches(); + log("x2w-mesh desktop pipeline for %016llx: %u targets (format %d), dsv %d, depth %d, pixel stage %s -> 0x%08lx; state %s: depth func %d " + "write %d stencil %d, cull %d ccw %d depthclip %d, blend rt0 %d mask 0x%x; compiled in %lld ms%s", tr.key, target_count, static_cast(format0), + static_cast(desc.DSVFormat), d.DepthEnable ? 1 : 0, tr.ps ? "yes" : "none", static_cast(hr), + !decoded ? "default" : (ms.depth || ms.cull || ms.blend) ? "decoded (X2W_MESH_STATE)" : "default + depth clip decoded (X2W_DRAW_STATE_DEPTHCLIP)", + d.DepthFunc, d.DepthWriteMask, d.StencilEnable, desc.RasterizerState.CullMode, desc.RasterizerState.FrontCounterClockwise, + desc.RasterizerState.DepthClipEnable, desc.BlendState.RenderTarget[0].BlendEnable, desc.BlendState.RenderTarget[0].RenderTargetWriteMask, + static_cast((t1.QuadPart - t0.QuadPart) * 1000 / f.QuadPart), async ? " (X2W_MESH_ASYNC worker)" : ""); + if (decoded) InterlockedIncrement(&mesh_state_changed); + if (!pso && decoded) { + // The decoded state was refused by the runtime: the default state instead (NOT exercised by a test). + pso = create_mesh_pso(tr, fallback, &hr); + InterlockedIncrement(&mesh_state_fallback); + log("x2w-mesh desktop pipeline for %016llx: decoded state refused, default state -> 0x%08lx", tr.key, static_cast(hr)); + } + check_device("translated mesh CreatePipelineState", 0); + AcquireSRWLockExclusive(&mesh_lock); + slot.pso = pso; + slot.state = pso ? 1 : 2; + ReleaseSRWLockExclusive(&mesh_lock); + WakeAllConditionVariable(&mesh_loaded); +} + +// X2W_MESH_ASYNC=1: a call whose PSO is not compiled yet hands the compile to a thread-pool worker and is skipped +// ("compiling"); the recording thread never compiles and never waits for a compile. Default off: compile in the call. +bool mesh_async() +{ + static const bool on = [] { + // Also on with stall's X2W_CX_ASYNC=1 (compute and draws), unless X2W_MESH_ASYNC_OFF=1. + const bool v = x2w_local::env_on("X2W_MESH_ASYNC") || (x2w_local::env_on("X2W_CX_ASYNC") && !x2w_local::env_on("X2W_MESH_ASYNC_OFF")); + if (v) log("x2w-mesh X2W_MESH_ASYNC=1: mesh PSOs compile on a worker; calls are skipped until their PSO is ready"); + return v; + }(); + return on; +} +struct MeshPsoJob { + const Translation* tr; + MeshPso* slot; + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc, fallback; + bool decoded; + UINT target_count; + DXGI_FORMAT format0; +}; +DWORD WINAPI mesh_pso_worker(void* p) +{ + MeshPsoJob* job = static_cast(p); + mesh_pso_compile(*job->tr, *job->slot, job->desc, job->fallback, job->decoded, job->target_count, job->format0, true); + delete job; + return 0; +} + +// The PSO for (entry, translation, state of this call), compiled once per key without draw_lock (failures are kept). +// tr is the entry's translation or its RTV variant (translation_for_targets). With X2W_MESH_ASYNC, null + *compiling +// while a worker compiles it. +ID3D12PipelineState* mesh_pso(MeshEntry& e, const Translation& tr, const BoundPipeline& bound, const Pass& pass, bool* compiling = nullptr) +{ + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc, fallback; + u64 key = 0; + bool decoded = false; + mesh_state_desc(bound, pass, desc, key, &decoded, &fallback); + key = fnv_bytes(&tr.key, sizeof(tr.key), key); // a variant's PSOs never share a slot with the base's + const bool async = mesh_async(); + AcquireSRWLockExclusive(&mesh_lock); + MeshPso& slot = e.psos[key]; + if (async && slot.state == 3) { + ReleaseSRWLockExclusive(&mesh_lock); + if (compiling) *compiling = true; + return nullptr; + } + while (slot.state == 3) SleepConditionVariableSRW(&mesh_loaded, &mesh_lock, INFINITE, 0); + if (slot.state == 1 || slot.state == 2) { + ID3D12PipelineState* pso = slot.pso; + ReleaseSRWLockExclusive(&mesh_lock); + return pso; + } + slot.state = 3; + ReleaseSRWLockExclusive(&mesh_lock); + const DXGI_FORMAT format0 = pass.target_count ? pass.target_formats[0] : DXGI_FORMAT_UNKNOWN; + if (async) { + auto* job = new MeshPsoJob{&tr, &slot, desc, fallback, decoded, pass.target_count, format0}; + if (QueueUserWorkItem(mesh_pso_worker, job, WT_EXECUTELONGFUNCTION)) { + if (compiling) *compiling = true; + return nullptr; + } + delete job; // no worker: compile here + } + mesh_pso_compile(tr, slot, desc, fallback, decoded, pass.target_count, format0, false); + AcquireSRWLockShared(&mesh_lock); + ID3D12PipelineState* pso = slot.pso; + ReleaseSRWLockShared(&mesh_lock); + return pso; +} + +// ---- Per call -------------------------------------------------------------------------------------------------- + +// Bound title pipeline -> its BoundPipeline (translation_for) with the mesh translation attached. +struct MeshBinding { + MeshRecordKey key; + bool mesh = false; + BoundPipeline* bound = nullptr; + Translation* attached = nullptr; + MeshEntry* entry = nullptr; // the key's entry once it is final (ready or failed): no loaded_mesh per call + u64 pso_signature = 0; // mesh_pass_signature of the pass pso was made for + ID3D12PipelineState* pso = nullptr; // the last PSO of this pipeline: no state desc, hash or mesh_lock per call + Translation* pso_tr = nullptr; // the translation pso was made from (the entry's, or its RTV variant) + u64 variant_wait_signature = 0; // RTV variant not ready for this pass signature: no draw_lock lookup ... + ULONGLONG variant_wait_until = 0; // ... until this tick (1 s) +}; + +// Everything of the pass that mesh_state_desc / apply_draw_state read: targets, DSV format, read-only DSV, rect +// topology. Equal signatures give the same PSO key for the same title pipeline (its BoundPipeline state is fixed). +u64 mesh_pass_signature(const Pass& pass) +{ + u64 s = 0x9e3779b97f4a7c15ull ^ pass.target_count; + for (UINT i = 0; i < pass.target_count; ++i) s = s * 1099511628211ull + static_cast(pass.target_formats[i]); + s = s * 1099511628211ull + static_cast(pass.dsv_format); + s = s * 1099511628211ull + (pass.dsv_read_only ? 1u : 0u) + (pass.topology == 0x11 ? 2u : 0u); + // renderstate 7c0d4cae: apply_draw_state keeps depth / stencil off on a depth target no forwarded slot 51 clear + // has initialised, so whether the bound target is cleared is part of the PSO (one shared-lock lookup, X2W_MESH_STATE only). + if (mesh_switches().depth && pass.dsv_resource && depth_target_cleared(pass.dsv_resource)) s = s * 1099511628211ull + 4u; + return s | 1; // never 0 (0 = no PSO cached) +} + +volatile LONG64 mesh_prepare_ticks, mesh_bind_ticks, mesh_bind_calls; +LONG64 mesh_now() +{ + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return t.QuadPart; +} +std::unordered_map& mesh_bindings() { static std::unordered_map m; return m; } + +bool mesh_tier_ok() +{ + static const bool ok = [] { + D3D12_FEATURE_DATA_D3D12_OPTIONS7 options7{}; + const HRESULT hr7 = device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &options7, sizeof(options7)); + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_5}; + const HRESULT hrm = device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model)); + const bool tier = SUCCEEDED(hr7) && options7.MeshShaderTier >= D3D12_MESH_SHADER_TIER_1; + const bool sm = SUCCEEDED(hrm) && model.HighestShaderModel >= D3D_SHADER_MODEL_6_5; + log("x2w-mesh X2W_MESH=1: MeshShaderTier %d (0x%08lx), highest shader model 0x%x (0x%08lx) -> mesh path %s", + SUCCEEDED(hr7) ? static_cast(options7.MeshShaderTier) : -1, static_cast(hr7), + SUCCEEDED(hrm) ? static_cast(model.HighestShaderModel) : 0u, static_cast(hrm), + tier && sm ? "ON" : "OFF (needs tier 1 and shader model 6.5)"); + return tier && sm; + }(); + return ok; +} + +// What mesh_prepare found for the call indirect is about to stage on this thread. +struct MeshReady { + Wrapper* list = nullptr; + Translation* tr = nullptr; + ID3D12PipelineState* pso = nullptr; + MeshEntry* entry = nullptr; +}; +thread_local MeshReady mesh_ready; +thread_local bool mesh_binding_now; // inside draw_translated for the mesh call + +thread_local u64 mesh_trace_key; // the binding's key for this call (0: none yet) +thread_local const BoundPipeline* mesh_trace_bound; +thread_local LONG mesh_trace_query = -1; // this call's pipeline statistics slot, or -1 + +struct MeshStats { + ID3D12QueryHeap* heap = nullptr; + ID3D12Resource* readback = nullptr; + bool v1 = false; // PIPELINE_STATISTICS1 + bool failed = false; + UINT capacity = 0; +}; +SRWLOCK mesh_stats_lock = SRWLOCK_INIT; +MeshStats mesh_stats; +LONG mesh_stats_next; // slots handed out since the last report +LONG mesh_stats_due; // frame at which to report (0: none pending) +u64 mesh_stats_keys[4096]; +bool mesh_stats_ready() +{ + AcquireSRWLockShared(&mesh_stats_lock); + const bool ready = mesh_stats.heap != nullptr, failed = mesh_stats.failed; + ReleaseSRWLockShared(&mesh_stats_lock); + if (ready || failed) return ready; + AcquireSRWLockExclusive(&mesh_stats_lock); + if (!mesh_stats.heap && !mesh_stats.failed) { + ID3D12Device* device = device_of(the_device); + D3D12_FEATURE_DATA_D3D12_OPTIONS9 options9{}; + mesh_stats.v1 = SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS9, &options9, sizeof(options9))) && + options9.MeshShaderPipelineStatsSupported; + mesh_stats.capacity = 4096; + const D3D12_QUERY_HEAP_DESC desc{mesh_stats.v1 ? D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS1 : D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, + mesh_stats.capacity, 0}; + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, u64{mesh_stats.capacity} * sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS1), + 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + const HRESULT hq = device->CreateQueryHeap(&desc, IID_PPV_ARGS(&mesh_stats.heap)); + const HRESULT hb = SUCCEEDED(hq) ? device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&mesh_stats.readback)) : hq; + if (FAILED(hb)) { + if (mesh_stats.heap) mesh_stats.heap->Release(); + mesh_stats.heap = nullptr; + mesh_stats.failed = true; + } + log("x2w-mesh pipeline statistics for traced mesh calls: %s (MeshShaderPipelineStatsSupported %d) -> 0x%08lx / 0x%08lx", + mesh_stats.failed ? "unavailable" : mesh_stats.v1 ? "PIPELINE_STATISTICS1" : "PIPELINE_STATISTICS (no MS counts)", mesh_stats.v1 ? 1 : 0, + static_cast(hq), static_cast(hb)); + } + const bool made = mesh_stats.heap != nullptr; + ReleaseSRWLockExclusive(&mesh_stats_lock); + return made; +} +D3D12_QUERY_TYPE mesh_stats_type() { return mesh_stats.v1 ? D3D12_QUERY_TYPE_PIPELINE_STATISTICS1 : D3D12_QUERY_TYPE_PIPELINE_STATISTICS; } +UINT mesh_stats_size() { return mesh_stats.v1 ? sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS1) : sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS); } +// Prints every slot's numbers and frees the slots. The GPU work of those calls must be complete. +void mesh_stats_report() +{ + const LONG used = InterlockedExchange(&mesh_stats_next, 0); + InterlockedExchange(&mesh_stats_due, 0); + if (!mesh_stats.readback || used <= 0) return; + const LONG count = used < static_cast(mesh_stats.capacity) ? used : static_cast(mesh_stats.capacity); + void* mapped = nullptr; + const D3D12_RANGE range{0, static_cast(count) * mesh_stats_size()}; + if (FAILED(mesh_stats.readback->Map(0, &range, &mapped))) return; + std::uint64_t sums[5] = {}, zero_ps = 0, zero_clip = 0; + for (LONG i = 0; i < count; ++i) { + D3D12_QUERY_DATA_PIPELINE_STATISTICS1 s{}; + std::memcpy(&s, static_cast(mapped) + std::size_t(i) * mesh_stats_size(), mesh_stats_size()); + if (mesh_stats.v1) + log("x2w-frame mesh stats #%ld key %016llx: MS invocations %llu primitives %llu, clipper invocations %llu primitives %llu, PS invocations %llu", + i, static_cast(mesh_stats_keys[i]), s.MSInvocations, s.MSPrimitives, s.CInvocations, s.CPrimitives, s.PSInvocations); + else + log("x2w-frame mesh stats #%ld key %016llx: (no MS counts) clipper invocations %llu primitives %llu, PS invocations %llu", + i, static_cast(mesh_stats_keys[i]), s.CInvocations, s.CPrimitives, s.PSInvocations); + const std::uint64_t v[5] = {s.MSInvocations, s.MSPrimitives, s.CInvocations, s.CPrimitives, s.PSInvocations}; + for (int k = 0; k < 5; ++k) sums[k] += v[k]; + zero_clip += s.CPrimitives == 0; + zero_ps += s.PSInvocations == 0; + } + const D3D12_RANGE none{0, 0}; + mesh_stats.readback->Unmap(0, &none); + log("x2w-frame mesh stats total over %ld calls (%ld asked): MS invocations %llu primitives %llu, clipper invocations %llu primitives %llu, " + "PS invocations %llu; calls with 0 clipper primitives %llu, with 0 PS invocations %llu", count, used, sums[0], sums[1], sums[2], sums[3], + sums[4], zero_clip, zero_ps); +} +// queue_present, every present: the traced frame has ended (trace_frame_active 0) -> report 8 presents later. +void mesh_stats_present(LONG frame) +{ + if (trace_frame_active || !mesh_stats_next) return; + const LONG due = mesh_stats_due; + if (!due) InterlockedCompareExchange(&mesh_stats_due, frame + 8, 0); + else if (frame >= due) mesh_stats_report(); +} +extern "C" __declspec(dllexport) void x2w_d3d12_mesh_stats_report() { mesh_stats_report(); } // fixtures, after their fence + +struct MeshFrameSlot { + LONG frame = -1; // the frame id collected in this slot (-1: free) + LONG used = 0; // calls handed a query + LONG groups = 0; // calls with a record with groups (X, Y, Z > 0 at record time) + LONG xpos = 0; // calls with a record with X > 0 at record time: the frame counts when > 0 + LONG due = 0; // present count at which to read + bool closed = false; // the frame has ended (due is set) +}; +constexpr UINT mesh_fs_slots = 16, mesh_fs_calls = 2048; +struct MeshFrameCall { + u64 set = 0; // target-set hash + bool groups = false; // the record had X, Y, Z > 0 at record time +}; +SRWLOCK mesh_fs_lock = SRWLOCK_INIT; +ID3D12QueryHeap* mesh_fs_heap; +ID3D12Resource* mesh_fs_readback; +bool mesh_fs_failed; +MeshFrameSlot mesh_fs_slot[mesh_fs_slots]; +std::vector& mesh_fs_calls_of() { static std::vector v(mesh_fs_slots * mesh_fs_calls); return v; } +std::map& mesh_fs_sets() { static std::map m; return m; } // under mesh_fs_lock +LONG mesh_fs_current; // the frame id being collected +LONG mesh_fs_presents; // presents seen +LONG mesh_fs_counted; // frames counted so far +LONG mesh_fs_reported; // counted frames reported +LONG mesh_fs_skipped_lines; +LONG mesh_fs_wanted() +{ + static const LONG n = [] { + char v[16]{}; + const LONG k = GetEnvironmentVariableA("X2W_MESH_STATS_FRAMES", v, sizeof(v)) ? std::atol(v) : 0; + if (k > 0) log("x2w-mesh X2W_MESH_STATS_FRAMES=%ld: mesh calls carry statistics queries until %ld frames with groups are counted", k, k); + return k > 0 ? k : 0; + }(); + return n; +} +bool mesh_fs_collecting() { return mesh_fs_wanted() && mesh_fs_counted < mesh_fs_wanted() && !mesh_fs_failed; } +bool mesh_fs_ready() +{ + if (!mesh_stats_ready()) return false; // the query type (v1 or not) is chosen there + AcquireSRWLockExclusive(&mesh_fs_lock); + if (!mesh_fs_heap && !mesh_fs_failed) { + ID3D12Device* device = device_of(the_device); + const UINT count = mesh_fs_slots * mesh_fs_calls; + const D3D12_QUERY_HEAP_DESC desc{mesh_stats.v1 ? D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS1 : D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, count, 0}; + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, u64{count} * sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS1), 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + const HRESULT hq = device->CreateQueryHeap(&desc, IID_PPV_ARGS(&mesh_fs_heap)); + const HRESULT hb = SUCCEEDED(hq) ? device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&mesh_fs_readback)) : hq; + if (FAILED(hb)) { + if (mesh_fs_heap) mesh_fs_heap->Release(); + mesh_fs_heap = nullptr; + mesh_fs_failed = true; + } + mesh_fs_calls_of(); + mesh_fs_slot[0].frame = mesh_fs_current; + log("x2w-mesh X2W_MESH_STATS_FRAMES query heap (%u queries) -> 0x%08lx / 0x%08lx", count, static_cast(hq), + static_cast(hb)); + } + const bool made = mesh_fs_heap != nullptr; + ReleaseSRWLockExclusive(&mesh_fs_lock); + return made; +} +// The target set of this call: hash, and its text the first time it is seen. +u64 mesh_fs_set(const Pass& pass) +{ + u64 h = fnv_bytes(&pass.target_count, sizeof(pass.target_count), 1469598103934665603ull); + for (UINT i = 0; i < pass.target_count; ++i) h = fnv_bytes(&pass.targets[i], sizeof(pass.targets[i]), h); + h = fnv_bytes(&pass.dsv_resource, sizeof(pass.dsv_resource), h); + AcquireSRWLockShared(&mesh_fs_lock); + const bool known = mesh_fs_sets().count(h) != 0; + ReleaseSRWLockShared(&mesh_fs_lock); + if (known) return h; + char text[600]; + int n = std::snprintf(text, sizeof(text), "targets %u", pass.target_count); + std::string res = "; resources"; + char part[64]; + for (UINT i = 0; i < pass.target_count && n > 0 && n < 480; ++i) { + const D3D12_RESOURCE_DESC rd = pass.targets[i] ? pass.targets[i]->GetDesc() : D3D12_RESOURCE_DESC{}; + n += std::snprintf(text + n, sizeof(text) - n, " [fmt %d %llux%u]", static_cast(pass.target_formats[i]), + static_cast(rd.Width), rd.Height); + std::snprintf(part, sizeof(part), " rt%u %p", i, static_cast(pass.targets[i])); + res += part; + } + if (pass.dsv_resource && n > 0 && n < 540) { + const D3D12_RESOURCE_DESC dd = pass.dsv_resource->GetDesc(); + std::snprintf(text + n, sizeof(text) - n, " dsv fmt %d %llux%u", static_cast(pass.dsv_format), static_cast(dd.Width), + dd.Height); + std::snprintf(part, sizeof(part), " dsv %p", static_cast(pass.dsv_resource)); + res += part; + } else if (n > 0 && n < 540) { + std::snprintf(text + n, sizeof(text) - n, " dsv none"); + } + AcquireSRWLockExclusive(&mesh_fs_lock); + mesh_fs_sets().emplace(h, std::string(text) + '\x1f' + res); + ReleaseSRWLockExclusive(&mesh_fs_lock); + return h; +} +// mesh_hook: a query index for this call, or -1. The current frame's slot. The claim holds mesh_fs_lock shared, so +// it cannot straddle a present's close (exclusive) or a slot's release; the counters are interlocked for concurrent +// recording threads. +LONG mesh_fs_begin(const Pass& pass, bool groups, bool xpos) +{ + if (!mesh_fs_collecting() || !mesh_fs_ready()) return -1; + const u64 set = mesh_fs_set(pass); // takes mesh_fs_lock itself: before the claim + AcquireSRWLockShared(&mesh_fs_lock); + const LONG frame = mesh_fs_current; + const UINT s = static_cast(frame) % mesh_fs_slots; + MeshFrameSlot& slot = mesh_fs_slot[s]; + LONG i = -1; + if (slot.frame == frame && !slot.closed) { // else: the slot is still being read, or collection has stopped + i = InterlockedIncrement(&slot.used) - 1; + if (i < static_cast(mesh_fs_calls)) { + if (groups) InterlockedIncrement(&slot.groups); + if (xpos) InterlockedIncrement(&slot.xpos); + MeshFrameCall& call = mesh_fs_calls_of()[s * mesh_fs_calls + static_cast(i)]; + call.set = set; + call.groups = groups; + } else { + i = -1; + } + } + ReleaseSRWLockShared(&mesh_fs_lock); + return i < 0 ? -1 : static_cast(s * mesh_fs_calls) + i; +} +void mesh_fs_read(UINT s) +{ + MeshFrameSlot& slot = mesh_fs_slot[s]; + const LONG used = slot.used < static_cast(mesh_fs_calls) ? slot.used : static_cast(mesh_fs_calls); + const bool counted = slot.xpos > 0; + if (counted && used > 0 && mesh_fs_readback) { + struct Sum { + LONG calls = 0, groups = 0; + std::uint64_t v[5] = {}; + }; + std::map sums; + Sum all; + void* mapped = nullptr; + const SIZE_T base = SIZE_T{s} * mesh_fs_calls * mesh_stats_size(); + const D3D12_RANGE range{base, base + static_cast(used) * mesh_stats_size()}; + if (SUCCEEDED(mesh_fs_readback->Map(0, &range, &mapped))) { + for (LONG i = 0; i < used; ++i) { + D3D12_QUERY_DATA_PIPELINE_STATISTICS1 q{}; + std::memcpy(&q, static_cast(mapped) + base + std::size_t(i) * mesh_stats_size(), mesh_stats_size()); + const MeshFrameCall& call = mesh_fs_calls_of()[s * mesh_fs_calls + static_cast(i)]; + const std::uint64_t v[5] = {q.MSInvocations, q.MSPrimitives, q.CInvocations, q.CPrimitives, q.PSInvocations}; + for (Sum* sum : {&sums[call.set], &all}) { + ++sum->calls; + sum->groups += call.groups; + for (int k = 0; k < 5; ++k) sum->v[k] += v[k]; + } + } + const D3D12_RANGE none{0, 0}; + mesh_fs_readback->Unmap(0, &none); + } + const LONG number = InterlockedIncrement(&mesh_fs_reported); + for (const auto& [set, sum] : sums) { + AcquireSRWLockShared(&mesh_fs_lock); + const auto found = mesh_fs_sets().find(set); + const std::string text = found == mesh_fs_sets().end() ? std::string("?\x1f") : found->second; + ReleaseSRWLockShared(&mesh_fs_lock); + const std::size_t cut = text.find('\x1f'); + if (mesh_stats.v1) + log("x2w-mesh stats frame %ld set %s: calls %ld (%ld with groups), MS invocations %llu primitives %llu, clipper invocations %llu " + "primitives %llu, PS invocations %llu%s", slot.frame, text.substr(0, cut).c_str(), sum.calls, sum.groups, sum.v[0], sum.v[1], + sum.v[2], sum.v[3], sum.v[4], text.substr(cut + 1).c_str()); + else + log("x2w-mesh stats frame %ld set %s: calls %ld (%ld with groups), (no MS counts) clipper invocations %llu primitives %llu, PS " + "invocations %llu%s", slot.frame, text.substr(0, cut).c_str(), sum.calls, sum.groups, sum.v[2], sum.v[3], sum.v[4], + text.substr(cut + 1).c_str()); + } + log("x2w-mesh stats frames total %ld of %ld frames (frame %ld): %zu target sets, calls %ld (%ld with groups%s), MS invocations %llu " + "primitives %llu, clipper invocations %llu primitives %llu, PS invocations %llu", number, mesh_fs_wanted(), slot.frame, sums.size(), + all.calls, all.groups, slot.used > static_cast(mesh_fs_calls) ? "; calls past 2048 had no query" : "", all.v[0], all.v[1], all.v[2], + all.v[3], all.v[4]); + } else if (first_calls(mesh_fs_skipped_lines, 8)) { + log("x2w-mesh stats frame %ld not counted (no record with X > 0 at record time; %ld mesh calls)", slot.frame, slot.used); + } + AcquireSRWLockExclusive(&mesh_fs_lock); // the release: mesh_fs_close may reuse the slot for a later frame + slot.used = slot.groups = slot.xpos = 0; + slot.due = 0; + slot.closed = false; + slot.frame = -1; + ReleaseSRWLockExclusive(&mesh_fs_lock); +} +// Ends the frame being collected: it counts if a call had a record with X > 0; its results are read `delay` presents +// later. +void mesh_fs_close(LONG delay) +{ + AcquireSRWLockExclusive(&mesh_fs_lock); + const LONG frame = mesh_fs_current; + MeshFrameSlot& slot = mesh_fs_slot[static_cast(frame) % mesh_fs_slots]; + if (slot.frame == frame) { + if (slot.xpos > 0) ++mesh_fs_counted; + slot.due = mesh_fs_presents + delay; + slot.closed = true; + } + mesh_fs_current = frame + 1; + MeshFrameSlot& next = mesh_fs_slot[static_cast(frame + 1) % mesh_fs_slots]; + if (next.frame == -1 && mesh_fs_counted < mesh_fs_wanted()) next.frame = frame + 1; + ReleaseSRWLockExclusive(&mesh_fs_lock); +} +void mesh_fs_present() +{ + if (!mesh_fs_wanted() || !mesh_fs_heap) return; + const LONG now = InterlockedIncrement(&mesh_fs_presents); + mesh_fs_close(8); + for (UINT s = 0; s < mesh_fs_slots; ++s) + if (mesh_fs_slot[s].frame >= 0 && mesh_fs_slot[s].closed && now >= mesh_fs_slot[s].due) mesh_fs_read(s); +} +// Fixtures (after their fence): ends the current frame and reads every closed slot now. +extern "C" __declspec(dllexport) void x2w_d3d12_mesh_frame_stats_report() +{ + if (!mesh_fs_heap) return; + mesh_fs_close(0); + for (UINT s = 0; s < mesh_fs_slots; ++s) + if (mesh_fs_slot[s].frame >= 0 && mesh_fs_slot[s].closed) mesh_fs_read(s); +} +// Fixtures: what queue_present does for X2W_MESH_STATS_FRAMES (the fixture has no swap chain present). +extern "C" __declspec(dllexport) void x2w_d3d12_mesh_frame_stats_present() { mesh_fs_present(); } +void mesh_trace_call(Wrapper* self, bool drawn, const Translation* tr, const char* why) +{ + const Pass& pass = pass_of(self); + for (UINT i = 0; i < pass.target_count; ++i) note_traced_target(self, pass.targets[i], drawn); + if (pass.dsv_resource) + note_traced_target(self, pass.dsv_resource, drawn && !pass.dsv_read_only, + pass.dsv_read_only ? D3D12_RESOURCE_STATE_DEPTH_READ : D3D12_RESOURCE_STATE_DEPTH_WRITE); + char text[900]; + int n = 0; + const auto add = [&](const char* format, auto... args) { + if (n >= 0 && n < static_cast(sizeof(text))) n += std::snprintf(text + n, sizeof(text) - n, format, args...); + }; + add("x2w-frame mesh %s key %016llx", drawn ? "drawn" : "NOT drawn", static_cast(mesh_trace_key)); + if (tr && tr->key != mesh_trace_key) add(" variant %016llx", static_cast(tr->key)); + add(" targets %u", pass.target_count); + for (UINT i = 0; i < pass.target_count; ++i) { + const D3D12_RESOURCE_DESC rd = pass.targets[i] ? pass.targets[i]->GetDesc() : D3D12_RESOURCE_DESC{}; + add(" [%u %p %llux%u fmt %d]", i, static_cast(pass.targets[i]), static_cast(rd.Width), rd.Height, + static_cast(pass.target_formats[i])); + } + add(" dsv %p fmt %d%s", static_cast(pass.dsv_resource), static_cast(pass.dsv_format), pass.dsv_read_only ? " read-only" : ""); + if (pass.dsv_resource) { + DepthClearValue clear; + const D3D12_RESOURCE_DESC dd = pass.dsv_resource->GetDesc(); + add(" (%llux%u res fmt %d", static_cast(dd.Width), dd.Height, static_cast(dd.Format)); + if (last_depth_clear(pass.dsv_resource, &clear)) + add(", last clear depth %g stencil %u flags 0x%x frame %ld)", clear.depth, clear.stencil, clear.flags, clear.frame); + else + add(", no forwarded clear)"); + } + if (mesh_trace_query >= 0) add(" query #%ld", mesh_trace_query); + if (pass.viewport_set) + add(" viewport %.1f %.1f %.1f %.1f depth %.2f-%.2f", pass.viewport0.TopLeftX, pass.viewport0.TopLeftY, pass.viewport0.Width, + pass.viewport0.Height, pass.viewport0.MinDepth, pass.viewport0.MaxDepth); + else + add(" viewport none"); + if (pass.scissor_set) + add(" scissor %ld %ld %ld %ld", pass.scissor0.left, pass.scissor0.top, pass.scissor0.right, pass.scissor0.bottom); + else + add(" scissor none"); + if (mesh_trace_bound) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc; + u64 key = 0; + bool decoded = false; + mesh_state_desc(*mesh_trace_bound, pass, desc, key, &decoded); + const auto& d = desc.DepthStencilState; + add(" depth %d func %d write %d stencil %d", d.DepthEnable, static_cast(d.DepthFunc), d.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ALL, + d.StencilEnable); + // The PSO's rasterizer (the desc mesh_pso creates; a failed creation falls back to the default state, see the + // desktop-pipeline line) and the title's words it is decoded from. D3D12 cull: 1 none, 2 front, 3 back. + const auto& r = desc.RasterizerState; + const BoundPipeline& b = *mesh_trace_bound; + const bool title_rs = b.derived_rs || (b.has_words && b.rs.ok); + add(" raster cull %d ccw %d depthclip %d bias %d/%g/%g fill %d (%s", static_cast(r.CullMode), r.FrontCounterClockwise, r.DepthClipEnable, + r.DepthBias, r.DepthBiasClamp, r.SlopeScaledDepthBias, static_cast(r.FillMode), + mesh_switches().cull ? (title_rs ? "from the title" : "default: title rasterizer not decoded") + : mesh_switches().depthclip && title_rs ? "default, depth clip from the title (X2W_DRAW_STATE_DEPTHCLIP)" + : "default: X2W_MESH_STATE off or NOCULL"); + (void)decoded; + if (b.derived_rs) + add("; title: slot 55 rasterizer part"); + else if (b.has_words) + add("; title PA_SU_SC_MODE_CNTL %08x PA_CL_CLIP_CNTL %08x%s%s%s", b.raw_mode, b.raw_clip, b.mesh_layout ? " mesh layout" : " vertex layout", + b.rs.ok ? "" : ", refused: ", b.rs.ok ? "" : (b.rs.reason ? b.rs.reason : "?")); + else + add("; no title state words"); + if (title_rs) { // what the title's words decode to, whether applied or not (FACE 0 = counter-clockwise front) + const D3D12_RASTERIZER_DESC& t = b.derived_rs ? b.patch_rs : b.rs.desc; + add(" -> decoded cull %d ccw %d depthclip %d bias %d", static_cast(t.CullMode), t.FrontCounterClockwise, t.DepthClipEnable, t.DepthBias); + } + add("%s)", mesh_cull_flip() ? "; X2W_MESH_STATE_CULL_FLIP" : ""); + } + if (mesh_trace_record) { + const UINT words = mesh_trace_stride / 4 < 8 ? mesh_trace_stride / 4 : 8; + if (words && x2w_local::readable(mesh_trace_record, words * 4)) { + add(" record (max count %u, stride %u):", mesh_trace_max, mesh_trace_stride); + for (UINT i = 0; i < words; ++i) { + std::uint32_t w; + std::memcpy(&w, mesh_trace_record + 4 * i, 4); + add(" %08x", w); + } + } else { + add(" record unreadable"); + } + } + if (!drawn) add(": %s", why ? why : "not issued"); + log("%s", text); +} + +// indirect_run (d3d12_indirect.inl), type DispatchMesh, before the record is staged. False: skip the call (counted +// here by reason; indirect counts it as no-pipeline). No draw_lock held on entry. +bool mesh_prepare_body(Wrapper* self, ID3D12GraphicsCommandList* list); +bool mesh_prepare(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + const LONG64 t0 = mesh_now(); + if (trace_frame_active) mesh_trace_key = 0, mesh_trace_bound = nullptr, mesh_last_skip = -1; + const bool ok = mesh_prepare_body(self, list); + InterlockedAdd64(&mesh_prepare_ticks, mesh_now() - t0); + if (!ok && trace_frame_active) mesh_trace_call(self, false, nullptr, mesh_last_skip >= 0 ? mesh_skip_names[mesh_last_skip] : "refused"); + return ok; +} +bool mesh_prepare_body(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + mesh_ready = {}; + InterlockedIncrement(&mesh_calls); + if (!list || !mesh_tier_ok()) return mesh_skip(mesh_tier), false; + Pass& pass = pass_of(self); + if (!pass.pipeline) return mesh_skip(mesh_no_record), false; + AcquireSRWLockShared(&mesh_key_lock); + const auto found = mesh_bindings().find(pass.pipeline); + MeshBinding binding = found != mesh_bindings().end() ? found->second : MeshBinding{}; + const bool known = found != mesh_bindings().end(); + ReleaseSRWLockShared(&mesh_key_lock); + if (!known) { + binding.mesh = mesh_key_of(pass.pipeline, &binding.key); + lock_draw(300000 + __LINE__); + binding.bound = translation_for(pass.pipeline); + ReleaseSRWLockExclusive(&draw_lock); + AcquireSRWLockExclusive(&mesh_key_lock); + mesh_bindings()[pass.pipeline] = binding; + ReleaseSRWLockExclusive(&mesh_key_lock); + } + if (!binding.mesh || !binding.key.keyed || !binding.bound) return mesh_skip(mesh_no_record), false; + if (trace_frame_active) mesh_trace_key = binding.key.key, mesh_trace_bound = binding.bound; + // The key's entry is kept with the binding (map nodes do not move): loaded_mesh (mesh_lock + lookup) only for the + // first call and, for a key without a translation, when its 5 s retry is due (racy reads of state / retry_at: at + // worst one extra loaded_mesh). + MeshEntry* entry = binding.entry; + if (!entry || (entry->state != 1 && entry->state != 2 && GetTickCount64() >= entry->retry_at)) { + entry = &loaded_mesh(binding.key.key); + if (!binding.entry) { + AcquireSRWLockExclusive(&mesh_key_lock); + mesh_bindings()[pass.pipeline].entry = entry; + ReleaseSRWLockExclusive(&mesh_key_lock); + } + } + MeshEntry& e = *entry; + mesh_note_use(e, binding.key.key); // every keyed call, whatever is refused below (coverage) + if (!pass.targets_bound) { + mesh_refusal_line(e, binding.key.key, mesh_no_targets, "no targets: no render target or depth view bound by the list"); + return mesh_skip(mesh_no_targets), false; + } + // A depth-only pipeline (no pixel stage) needs no variant (translation_for_targets takes the base for it). + const bool rtv_variant = e.tr && e.tr->ps && std::any_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant); + if (e.state == 4) return mesh_skip(mesh_no_translation), false; + if (e.state != 1) return mesh_skip(mesh_failed), false; + if (binding.attached != e.tr) { + // The mesh translation becomes this pipeline's translation, so draw_translated finds it (translation_for leaves + // it null for a record without vertex code). Only a ready translation is attached. + lock_draw(300000 + __LINE__); + const bool free = !binding.bound->translation || binding.bound->translation == e.tr; + if (free) binding.bound->translation = e.tr; + ReleaseSRWLockExclusive(&draw_lock); + if (!free) { + mesh_refusal_line(e, binding.key.key, mesh_failed, "translation taken: the bound pipeline already has another translation"); + return mesh_skip(mesh_failed), false; + } + AcquireSRWLockExclusive(&mesh_key_lock); + mesh_bindings()[pass.pipeline].attached = e.tr; + ReleaseSRWLockExclusive(&mesh_key_lock); + } + const u64 signature = mesh_pass_signature(pass); + ID3D12PipelineState* pso = binding.pso && binding.pso_signature == signature ? binding.pso : nullptr; + Translation* tr = pso ? binding.pso_tr : e.tr; + if (!pso && rtv_variant) { + // Integer / 32-bit float targets: the pixel stage's RTV variant, the same contract as ordinary draws + // (translation_for_targets: key fnv("rtv1 "), request req_.rtv, manifest with the + // rtv1 line). draw_translated resolves the same variant entry for this call. A variant that is not ready is + // looked up again (under draw_lock) at most once a second per binding and pass signature. + if (binding.variant_wait_signature == signature && GetTickCount64() < binding.variant_wait_until) return mesh_skip(mesh_rtv_variant), false; + lock_draw(300000 + __LINE__); + tr = translation_for_targets(e.tr, pass); + const bool ready = tr && tr->state == 1 && tr->ms; + ReleaseSRWLockExclusive(&draw_lock); + if (!ready) { + AcquireSRWLockExclusive(&mesh_key_lock); + MeshBinding& kept = mesh_bindings()[pass.pipeline]; + kept.variant_wait_signature = signature; + kept.variant_wait_until = GetTickCount64() + 1000; + ReleaseSRWLockExclusive(&mesh_key_lock); + if (!mesh_refusal_logged(e, mesh_rtv_variant)) { + char detail[200]; + int n = std::snprintf(detail, sizeof(detail), "rtv variant: target formats"); + for (UINT i = 0; i < pass.target_count && n < 120; ++i) + n += std::snprintf(detail + n, sizeof(detail) - n, " %d", static_cast(pass.target_formats[i])); + std::snprintf(detail + n, sizeof(detail) - n, "; variant %016llx %s", tr ? static_cast(tr->key) : 0ull, + tr && tr->state == 1 ? "has no mesh stage" : "not translated yet (req_.rtv published)"); + mesh_refusal_line(e, binding.key.key, mesh_rtv_variant, detail); + } + return mesh_skip(mesh_rtv_variant), false; + } + static LONG variants_logged; + if (first_calls(variants_logged, 256)) + log("x2w-mesh pipeline %016llx: RTV variant %016llx for target formats %d%s (pixel stage %s)", static_cast(binding.key.key), + static_cast(tr->key), static_cast(pass.target_formats[0]), pass.target_count > 1 ? " ..." : "", tr->ps ? "yes" : "none"); + } + static volatile LONG reuse_logged; // once per process: the first call served by the PSO kept with the binding + if (pso && !reuse_logged && InterlockedExchange(&reuse_logged, 1) == 0) + log("x2w-mesh pipeline %016llx: PSO kept with the binding reused (no state desc, hash or mesh_lock for this call; logged once)", + static_cast(binding.key.key)); + if (!pso) { + bool compiling = false; + pso = mesh_pso(e, *tr, *binding.bound, pass, &compiling); + if (compiling) return mesh_skip(mesh_compiling), false; + if (pso) { + AcquireSRWLockExclusive(&mesh_key_lock); + MeshBinding& kept = mesh_bindings()[pass.pipeline]; + kept.pso = pso; + kept.pso_tr = tr; + kept.pso_signature = signature; + ReleaseSRWLockExclusive(&mesh_key_lock); + } + } + if (!pso) { + mesh_refusal_line(e, binding.key.key, mesh_no_pso, "no PSO: CreatePipelineState failed, see its desktop pipeline line"); + return mesh_skip(mesh_no_pso), false; + } + mesh_ready = {self, tr, pso, &e}; + return true; +} + +// indirect_mesh_hook: the call is staged (copy + guard). Binds through draw_translated, whose issue point calls +// indirect_issue. True only when the ExecuteIndirect was recorded. +bool mesh_hook(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + if (mesh_ready.list != self || !mesh_ready.pso || !list) return false; + mesh_binding_now = true; + const LONG64 t0 = mesh_now(); + mesh_trace_query = -1; + if (trace_frame_active && mesh_stats_ready()) { + const LONG slot = InterlockedIncrement(&mesh_stats_next) - 1; + if (slot < static_cast(mesh_stats.capacity)) { + mesh_trace_query = slot; + mesh_stats_keys[slot] = mesh_trace_key; + list->BeginQuery(mesh_stats.heap, mesh_stats_type(), static_cast(slot)); + } + } + LONG fs_query = -1; + if (!trace_frame_active && mesh_fs_collecting()) { + std::uint32_t xyz[3] = {}; + const bool readable = mesh_dump_record_groups(xyz); + const bool groups = readable && xyz[0] && xyz[1] && xyz[2]; // "with groups" on the lines + const bool xpos = readable && xyz[0]; // the frame counts (the request: X > 0) + fs_query = mesh_fs_begin(pass_of(self), groups, xpos); + if (fs_query >= 0) list->BeginQuery(mesh_fs_heap, mesh_stats_type(), static_cast(fs_query)); + } + const bool issued = draw_translated(self, false, 0, 0, 0, 0, 0); + if (fs_query >= 0) { + list->EndQuery(mesh_fs_heap, mesh_stats_type(), static_cast(fs_query)); + list->ResolveQueryData(mesh_fs_heap, mesh_stats_type(), static_cast(fs_query), 1, mesh_fs_readback, + u64{static_cast(fs_query)} * mesh_stats_size()); + } + if (mesh_trace_query >= 0) { + list->EndQuery(mesh_stats.heap, mesh_stats_type(), static_cast(mesh_trace_query)); + list->ResolveQueryData(mesh_stats.heap, mesh_stats_type(), static_cast(mesh_trace_query), 1, mesh_stats.readback, + u64{static_cast(mesh_trace_query)} * mesh_stats_size()); + } + InterlockedAdd64(&mesh_bind_ticks, mesh_now() - t0); + InterlockedIncrement64(&mesh_bind_calls); + mesh_binding_now = false; + if (trace_frame_active) mesh_trace_call(self, issued, mesh_ready.tr, "bind refused by draw_translated"); + if (!mesh_dump_dir.empty()) { + const UINT bytes = mesh_trace_stride * (mesh_trace_max ? mesh_trace_max : 1); + const bool readable_record = mesh_trace_record && bytes && bytes <= 65536 && x2w_local::readable(mesh_trace_record, bytes); + char note[160]; + std::snprintf(note, sizeof(note), "indirect record(s) in title memory at record time: max count %u, stride %u; call %s", mesh_trace_max, + mesh_trace_stride, issued ? "issued" : "NOT issued (bind refused)"); + mesh_dump_file("record.bin", readable_record ? mesh_trace_record : nullptr, readable_record ? bytes : 0, note); + mesh_dump_dir.clear(); + } + MeshEntry* e = mesh_ready.entry; + mesh_ready = {}; + if (!issued) { + if (e) mesh_refusal_line(*e, e->tr->key, mesh_bind, "bind refused by draw_translated; heap / vinfo / vdesc refusals also have an x2w-draw-rt line, others none"); + return mesh_skip(mesh_bind), false; + } + InterlockedIncrement(&mesh_issued); + if (e && !e->issued_once) { + e->issued_once = true; // a benign race: at worst two lines + static LONG shown; + if (first_calls(shown, 1024)) log("x2w-mesh pipeline %016llx: first call issued", e->tr->key); + } + return true; +} + +// d3d12_draw.inl hooks: draw_translated binds a mesh call (topology gate off, no rect entry value) ... +bool mesh_issue_active(Wrapper* self) { return mesh_binding_now && mesh_ready.list == self && indirect_pending(self); } +// ... and pipeline_for returns the pre-built mesh PSO for a mesh translation (null outside a mesh call: a plain +// draw with a mesh pipeline bound draws nothing). +ID3D12PipelineState* mesh_pso_for(const Translation& tr) { return mesh_binding_now && mesh_ready.tr == &tr ? mesh_ready.pso : nullptr; } + +const bool mesh_hook_installed = [] { + if (mesh_enabled()) indirect_mesh_hook = &mesh_hook; + return mesh_enabled(); +}(); + +// Every 300 frames (queue_present), X2W_MESH=1 only. Counters restart after each line. +void report_mesh(LONG frames) +{ + if (!mesh_enabled()) return; + LONG s[mesh_skips]; + for (int i = 0; i < mesh_skips; ++i) s[i] = InterlockedExchange(&mesh_skipped[i], 0); + const LONG calls = InterlockedExchange(&mesh_calls, 0), issued = InterlockedExchange(&mesh_issued, 0); + LONG accounted = issued; + for (LONG v : s) accounted += v; + log("x2w-mesh %ld frames: calls %ld issued %ld; skipped: no translation %ld, translation failed %ld, no PSO %ld, no targets %ld, " + "tier %ld; also no mesh record %ld, rtv variant %ld, bind refused %ld, refused by indirect after prepare %ld, PSO compiling " + "(X2W_MESH_ASYNC) %ld; records keyed %ld unkeyed %ld (total)", + frames, calls, issued, s[mesh_no_translation], s[mesh_failed], s[mesh_no_pso], s[mesh_no_targets], s[mesh_tier], s[mesh_no_record], + s[mesh_rtv_variant], s[mesh_bind], calls - accounted, s[mesh_compiling], mesh_records_keyed, mesh_records_unkeyed); + static const double us_per_tick = [] { + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + return 1e6 / static_cast(f.QuadPart); + }(); + const LONG64 prepare = InterlockedExchange64(&mesh_prepare_ticks, 0), bind = InterlockedExchange64(&mesh_bind_ticks, 0); + const LONG64 binds = InterlockedExchange64(&mesh_bind_calls, 0); + log("x2w-mesh %ld frames cpu: prepare %.1f us/call over %ld calls (%.0f ms), bind %.1f us/call over %lld binds (%.0f ms; draw_translated " + "including its draw_lock wait); PSOs with decoded state %ld, of them on the default state after a refusal %ld (total)", frames, + calls ? prepare * us_per_tick / calls : 0.0, calls, prepare * us_per_tick / 1000.0, binds ? bind * us_per_tick / binds : 0.0, + static_cast(binds), bind * us_per_tick / 1000.0, mesh_state_changed, mesh_state_fallback); + report_mesh_keys(frames); +} diff --git a/src/startup_stubs/d3d12_present.inl b/src/startup_stubs/d3d12_present.inl index 58bec8cf4b..e176af63f2 100644 --- a/src/startup_stubs/d3d12_present.inl +++ b/src/startup_stubs/d3d12_present.inl @@ -11,8 +11,11 @@ struct WindowPresenter { ID3D12DescriptorHeap* targets = nullptr; ID3D12DescriptorHeap* textures = nullptr; ID3D12Resource* buffers[2] = {}; - ID3D12CommandAllocator* allocator = nullptr; - ID3D12GraphicsCommandList* list = nullptr; + ID3D12CommandAllocator* allocators[2] = {}; + ID3D12GraphicsCommandList* lists[2] = {}; + UINT64 slot_values[2] = {}; + UINT next_slot = 0; + LONG skipped = 0; ID3D12RootSignature* root = nullptr; ID3D12PipelineState* pipeline = nullptr; ID3D12Fence* fence = nullptr; @@ -22,6 +25,12 @@ struct WindowPresenter { bool failed = false; }; WindowPresenter window_presenter; +x2w_startup::TitleComposition title_composition; +bool present_in_title_window() +{ + static const bool enabled = x2w_local::env_on("X2W_PRESENT_IN_TITLE_WINDOW"); + return enabled; +} LONG window_presents; // The output window belongs to this layer and has its own thread and message loop; the title's @@ -117,14 +126,21 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; desc.BufferCount = 2; desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; - hr = factory->CreateSwapChainForHwnd(queue, window, &desc, nullptr, nullptr, &chain1); - if (SUCCEEDED(hr)) factory->MakeWindowAssociation(window, DXGI_MWA_NO_ALT_ENTER); + if (present_in_title_window()) { + desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; + desc.Scaling = DXGI_SCALING_STRETCH; + desc.AlphaMode = DXGI_ALPHA_MODE_IGNORE; + hr = factory->CreateSwapChainForComposition(queue, &desc, nullptr, &chain1); + } else { + hr = factory->CreateSwapChainForHwnd(queue, window, &desc, nullptr, nullptr, &chain1); + if (SUCCEEDED(hr)) factory->MakeWindowAssociation(window, DXGI_MWA_NO_ALT_ENTER); + } } if (SUCCEEDED(hr)) hr = chain1->QueryInterface(IID_PPV_ARGS(&p.chain)); if (chain1) chain1->Release(); if (factory) factory->Release(); const D3D12_DESCRIPTOR_HEAP_DESC target_heap{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - const D3D12_DESCRIPTOR_HEAP_DESC texture_heap{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + const D3D12_DESCRIPTOR_HEAP_DESC texture_heap{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; // one view per copy slot if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&target_heap, IID_PPV_ARGS(&p.targets)); if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&texture_heap, IID_PPV_ARGS(&p.textures)); const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); @@ -133,9 +149,11 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) if (SUCCEEDED(hr)) device->CreateRenderTargetView(p.buffers[i], nullptr, D3D12_CPU_DESCRIPTOR_HANDLE{p.targets->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{i} * step}); } - if (SUCCEEDED(hr)) hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&p.allocator)); - if (SUCCEEDED(hr)) hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, p.allocator, nullptr, IID_PPV_ARGS(&p.list)); - if (SUCCEEDED(hr)) hr = p.list->Close(); + for (int i = 0; i < 2; ++i) { + if (SUCCEEDED(hr)) hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&p.allocators[i])); + if (SUCCEEDED(hr)) hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, p.allocators[i], nullptr, IID_PPV_ARGS(&p.lists[i])); + if (SUCCEEDED(hr)) hr = p.lists[i]->Close(); + } if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&p.fence)); p.reached = CreateEventW(nullptr, FALSE, FALSE, nullptr); static const char source[] = @@ -186,6 +204,99 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) return SUCCEEDED(hr); } +void note_present_planes(LONG frame, UINT planes, const void* plane_parameters, const void* present_parameters) +{ + static const bool on = [] { + const bool value = x2w_local::env_on("X2W_PRESENT_PLANES_LOG"); + if (value) log("x2w-present X2W_PRESENT_PLANES_LOG=1: plane changes and one line per 300 frames are logged"); + return value; + }(); + if (!on) return; + static UINT last_planes = ~0u; + static u64 last_count = ~0ull, last_shape = ~0ull; + static u64 known[8]; + static UINT known_count, flips_since, extra_planes_since; + static u64 last_surface; + static LONG lines, summaries; + const auto* words = static_cast(plane_parameters); + const bool header = planes && words && x2w_local::readable(words, 0x18); + const u64 count = header ? words[1] : 0; + u64 surface = 0, shape = 0; + if (header && count >= 1 && x2w_local::readable(reinterpret_cast(words[2]), 8)) { + surface = *reinterpret_cast(words[2]); + Wrapper* wrapper = as_wrapper(reinterpret_cast(surface)); + if (wrapper && wrapper->own().kind == resource_kind && wrapper->own().real) { + const D3D12_RESOURCE_DESC desc = static_cast(wrapper->own().real)->GetDesc(); + shape = (desc.Width & 0xFFFFF) | (u64{desc.Height & 0xFFFFF} << 20) | (u64{static_cast(desc.Format) & 0xFFF} << 40); + } + } + // Called from queue_present only, one thread at a time per queue; the statics are diagnostics. + if (surface != last_surface) ++flips_since; + last_surface = surface; + if (planes > 1 || count > 1) ++extra_planes_since; + bool fresh = false; + if (surface) { + UINT i = 0; + while (i < known_count && known[i] != surface) ++i; + if (i == known_count && known_count < 8) { + known[known_count++] = surface; + fresh = true; + } + } + if (frame % 300 == 0 && first_calls(summaries, 200)) { + log("x2w-present planes summary frame %ld: planes=%u resources=%llu %llux%llu format %llu; surfaces seen %u; surface changes %u and " + "presents with more than one plane or resource %u in the last 300 frames", + frame, planes, count, shape & 0xFFFFF, (shape >> 20) & 0xFFFFF, (shape >> 40) & 0xFFF, known_count, flips_since, extra_planes_since); + flips_since = extra_planes_since = 0; + } + if (planes == last_planes && count == last_count && shape == last_shape && !fresh) return; + last_planes = planes; + last_count = count; + last_shape = shape; + if (!first_calls(lines, 32)) return; + char a[3 * 0x60 + 1] = "", b[3 * 0x40 + 1] = ""; + if (plane_parameters && x2w_local::readable(plane_parameters, 0x60)) hex_text(plane_parameters, 0x60, a, sizeof(a)); + if (present_parameters && x2w_local::readable(present_parameters, 0x40)) hex_text(present_parameters, 0x40, b, sizeof(b)); + log("x2w-present planes frame %ld: planes=%u resources=%llu surface=0x%llx %llux%llu format %llu; plane=[%s] present=[%s]", frame, planes, + count, surface, shape & 0xFFFFF, (shape >> 20) & 0xFFFFF, (shape >> 40) & 0xFFF, a, b); +} + +void note_quiet_frame(LONG frame) +{ + static const LONG wanted = [] { + char value[16]{}; + const LONG n = GetEnvironmentVariableA("X2W_D3D12_TRACE_QUIET", value, sizeof(value)) ? std::atol(value) : 0L; + if (n > 0) log("x2w-frame X2W_D3D12_TRACE_QUIET=%ld: one frame is traced after %ld quiet frames (1-8 translated draws) past a busy one", n, n); + return n > 0 ? n : 0L; + }(); + if (!wanted) return; + static const bool dump_dir = GetEnvironmentVariableA("X2W_DRAW_DUMP_DIR", nullptr, 0) != 0; + static LONG last_total, quiet_run, end_frame, next_allowed, traces; + static bool armed; + const LONG total = translated_draws; + const LONG drawn = total - last_total; + last_total = total; + if (end_frame && frame == end_frame) { + InterlockedExchange(&trace_frame_active, 0); + log("x2w-frame ---- end quiet frame %ld (%ld translated draws)", frame, drawn); + summarise_indirect_calls(); + end_frame = 0; + return; + } + static LONG busy_frames; + if (drawn >= 20 && ++busy_frames >= 300) armed = true; + quiet_run = armed && drawn >= 1 && drawn <= 8 ? quiet_run + 1 : 0; + if (end_frame || quiet_run < wanted || frame < next_allowed || traces >= 3) return; + ++traces; + quiet_run = 0; + next_allowed = frame + 3000; + end_frame = frame + 1; + if (dump_dir && !draw_dump_frame()) InterlockedExchange(&quiet_dump_frame, frame); + log("x2w-frame ---- begin quiet frame %ld (previous frame: %ld translated draws, %ld quiet frames)%s", frame + 1, drawn, wanted, + quiet_dump_frame == frame ? "; per-draw target dumps on" : ""); + InterlockedExchange(&trace_frame_active, 1); +} + // Draws `surface` (resting in COMMON) into the window and flips. Returns false if not shown. bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) { @@ -200,12 +311,29 @@ bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) desc.Dimension, desc.SampleDesc.Count, desc.Flags, desc.Format); return false; } - HWND window = output_window(); + HWND window = present_in_title_window() ? title_composition.window : output_window(); + if (present_in_title_window() && !IsWindow(window)) window = x2w_startup::title_picture_window(); if (!window) return false; if (!p.chain && !create_window_presenter(queue, window)) { p.failed = true; return false; } + if (present_in_title_window()) { + const HRESULT attached = title_composition.show(window, p.chain, p.width, p.height); + if (attached != S_OK) { + static LONG failures; + if (FAILED(attached) && first_calls(failures, 3)) + log("x2w-present title composition failed: 0x%08lx", static_cast(attached)); + return false; + } + } + static const bool wait_each = x2w_local::env_on("X2W_PRESENT_WAIT"); + const UINT slot = wait_each ? 0 : p.next_slot; + if (!wait_each && p.fence->GetCompletedValue() < p.slot_values[slot]) { + const LONG n = InterlockedIncrement(&p.skipped); + if (n <= 4 || n % 500 == 0) log("x2w-present window copy skipped %ld times (previous copies still queued)", n); + return true; // the window keeps its last picture + } ID3D12Device* device = device_of(the_device); const DXGI_FORMAT view_format = x2w_startup::present_view_format(desc.Format); D3D12_SHADER_RESOURCE_VIEW_DESC view{}; @@ -213,36 +341,48 @@ bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; view.Texture2D.MipLevels = 1; - device->CreateShaderResourceView(surface, &view, p.textures->GetCPUDescriptorHandleForHeapStart()); + const UINT view_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + device->CreateShaderResourceView(surface, &view, D3D12_CPU_DESCRIPTOR_HANDLE{p.textures->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{slot} * view_step}); const UINT index = p.chain->GetCurrentBackBufferIndex(); const D3D12_CPU_DESCRIPTOR_HANDLE target{p.targets->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{index} * device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)}; - if (FAILED(p.allocator->Reset()) || FAILED(p.list->Reset(p.allocator, p.pipeline))) return false; - transition(p.list, surface, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); - transition(p.list, p.buffers[index], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); + ID3D12GraphicsCommandList* list = p.lists[slot]; + if (FAILED(p.allocators[slot]->Reset()) || FAILED(list->Reset(p.allocators[slot], p.pipeline))) return false; + transition(list, surface, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + transition(list, p.buffers[index], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); const D3D12_VIEWPORT viewport{0, 0, static_cast(p.width), static_cast(p.height), 0, 1}; const D3D12_RECT scissor{0, 0, static_cast(p.width), static_cast(p.height)}; - p.list->SetGraphicsRootSignature(p.root); - p.list->SetDescriptorHeaps(1, &p.textures); - p.list->SetGraphicsRootDescriptorTable(0, p.textures->GetGPUDescriptorHandleForHeapStart()); - p.list->RSSetViewports(1, &viewport); - p.list->RSSetScissorRects(1, &scissor); - p.list->OMSetRenderTargets(1, &target, FALSE, nullptr); - p.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - p.list->DrawInstanced(3, 1, 0, 0); - transition(p.list, p.buffers[index], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); - transition(p.list, surface, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); - if (FAILED(p.list->Close())) { + list->SetGraphicsRootSignature(p.root); + list->SetDescriptorHeaps(1, &p.textures); + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{p.textures->GetGPUDescriptorHandleForHeapStart().ptr + UINT64{slot} * view_step}); + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &target, FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + transition(list, p.buffers[index], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); + transition(list, surface, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + if (FAILED(list->Close())) { p.failed = true; return false; } - ID3D12CommandList* lists[] = {p.list}; + ID3D12CommandList* lists[] = {list}; queue->ExecuteCommandLists(1, lists); - const HRESULT hr = p.chain->Present(0, 0); - // The allocator is reused next frame: wait until this frame's commands are done. - if (SUCCEEDED(queue->Signal(p.fence, ++p.fence_value)) && p.fence->GetCompletedValue() < p.fence_value && - SUCCEEDED(p.fence->SetEventOnCompletion(p.fence_value, p.reached))) - WaitForSingleObject(p.reached, 2000); + // Without the wait, DO_NOT_WAIT: a full flip queue drops this window frame instead of blocking. + HRESULT hr = p.chain->Present(0, wait_each ? 0 : DXGI_PRESENT_DO_NOT_WAIT); + if (hr == S_OK && present_in_title_window()) { + static LONG reports; + if (first_calls(reports, 1)) log("x2w-present first flip on the original window"); + } + if (hr == DXGI_ERROR_WAS_STILL_DRAWING) { + const LONG n = InterlockedIncrement(&p.skipped); + if (n <= 4 || n % 500 == 0) log("x2w-present window flip skipped %ld times (flip queue full)", n); + hr = S_OK; + } + if (SUCCEEDED(queue->Signal(p.fence, ++p.fence_value))) p.slot_values[slot] = p.fence_value; + p.next_slot = (slot + 1) % 2; + if (wait_each && p.fence->GetCompletedValue() < p.fence_value && SUCCEEDED(p.fence->SetEventOnCompletion(p.fence_value, p.reached))) + WaitForSingleObject(p.reached, 2000); // the allocator is reused next frame static LONG failures; if (FAILED(hr) && first_calls(failures, 4)) log("x2w-present Present failed 0x%08lx", static_cast(hr)); check_device("window present", 0); diff --git a/src/startup_stubs/d3d12_range_alias.inl b/src/startup_stubs/d3d12_range_alias.inl new file mode 100644 index 0000000000..90fd69183d --- /dev/null +++ b/src/startup_stubs/d3d12_range_alias.inl @@ -0,0 +1,125 @@ +bool range_alias_on() +{ + static const bool on = x2w_local::env_on("X2W_RANGE_ALIAS"); + return on; +} + +LONG range_alias_built, range_alias_reused, range_alias_failed, range_alias_ranges; + +namespace range_alias { +using Location = BOOL(WINAPI*)(const void*, HANDLE*, ULONG64*); +Location location() +{ + static const Location f = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_gpu_location")) : nullptr; + }(); + return f; +} + +// The gate, checked once (on the first split range). The reason text goes on every refusal line. +const char* refusal(HANDLE first_section) +{ + static const char* reason = nullptr; + static SRWLOCK lock = SRWLOCK_INIT; + AcquireSRWLockExclusive(&lock); + if (!reason) { + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + const HRESULT got = device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)); + ID3D12Heap* heap = first_section ? section_heap(first_section) : nullptr; + const D3D12_HEAP_FLAGS flags = heap ? heap->GetDesc().Flags : D3D12_HEAP_FLAG_NONE; + if (FAILED(got) || options.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_1) + reason = "no tiled resources (tier below 1)"; + else if (!heap) + reason = "the section has no desktop heap"; + else if (flags & D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER) + reason = "section heaps are cross-adapter shared: UpdateTileMappings onto them removes the device " + "(tests/tile_mapping_shared_heap_check)"; + else + reason = "section heap is not cross-adapter, but this build has no alias builder"; + log("x2w-range-alias: X2W_RANGE_ALIAS=1; tiled resources tier %d (0x%08lx), section heap %p flags 0x%x; xmem location %s: " + "REFUSED (%s). Split ranges stay NULL, as without the switch.", + SUCCEEDED(got) ? static_cast(options.TiledResourcesTier) : -1, static_cast(got), static_cast(heap), + static_cast(flags), location() ? "found" : "MISSING", reason); + } + ReleaseSRWLockExclusive(&lock); + return reason; +} + +void summary() +{ + log("x2w-range-alias: built %ld, reused %ld, failed %ld bindings over %ld distinct ranges (frame %ld)", range_alias_built, range_alias_reused, + range_alias_failed, range_alias_ranges, static_cast(frame_number)); +} + +void note_failed() +{ + const LONG n = InterlockedIncrement(&range_alias_failed); + if ((n & (n - 1)) == 0 && n >= 64) summary(); // 64, 128, 256, ... +} +} // namespace range_alias + +// desktop_range: a binding of a frame-cached split range (counted, no line). +void range_alias_repeat() +{ + range_alias::note_failed(); +} + +// desktop_range: [address, address + bytes) is chunk pages whose base has a window and which failed the per-page +// check. Describes the range (first sighting, capped), refuses, counts. Always returns false (no alias). +bool range_alias_split(u64 address, u64 bytes) +{ + const range_alias::Location location = range_alias::location(); + HANDLE first_section = nullptr; + ULONG64 first_at = 0; + if (location) location(reinterpret_cast(address), &first_section, &first_at); + const char* reason = range_alias::refusal(first_section); + range_alias::note_failed(); + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_set seen; + const u64 key = address * 1099511628211ull ^ bytes; + AcquireSRWLockExclusive(&lock); + const bool fresh = seen.size() < 4096 && seen.insert(key).second; + ReleaseSRWLockExclusive(&lock); + if (!fresh) return false; + const LONG distinct = InterlockedIncrement(&range_alias_ranges); + if (!x2w_local::first_of(distinct, 48) || !location) return false; + // The page walk: one location per 64 KiB page (as desktop_range's check), from the range's first page. + const u64 first_page = address & ~0xffffull, end = address + bytes; + std::vector sections; + unsigned long pages = 0, runs = 0, missing = 0; + long first_break = -1; + const char* break_kind = ""; + long long jump = 0; + HANDLE previous = nullptr; + ULONG64 previous_at = 0; + for (u64 at = first_page; at < end; at += 0x10000, ++pages) { + HANDLE section = nullptr; + ULONG64 where = 0; + if (!location(reinterpret_cast(at), §ion, &where)) { + ++missing; + previous = nullptr; + continue; + } + where &= ~0xffffull; + const bool linear = previous && section == previous && where == previous_at + 0x10000; + if (!linear) { + ++runs; + if (previous && first_break < 0) { + first_break = static_cast(pages); + break_kind = section != previous ? "section change" : "offset jump"; + jump = static_cast(where) - static_cast(previous_at + 0x10000); + } + } + if (std::find(sections.begin(), sections.end(), section) == sections.end()) sections.push_back(section); + previous = section; + previous_at = where; + } + char where_broken[96] = "none"; + if (first_break >= 0) + std::snprintf(where_broken, sizeof(where_broken), "page %ld, %s %s0x%llx", first_break, break_kind, jump < 0 ? "-" : "+", + static_cast(jump < 0 ? -jump : jump)); + log("x2w-range-alias range 0x%llx %llu bytes (frame %ld): %lu pages, %lu linear runs, %zu sections, %lu unmapped; first break: %s: NULL (%s)", + address, static_cast(bytes), static_cast(frame_number), pages, runs, sections.size(), missing, where_broken, reason); + return false; +} diff --git a/src/startup_stubs/d3d12_rawaddr.inl b/src/startup_stubs/d3d12_rawaddr.inl new file mode 100644 index 0000000000..00f54425ef --- /dev/null +++ b/src/startup_stubs/d3d12_rawaddr.inl @@ -0,0 +1,311 @@ + +namespace ra = x2w_startup::rawaddr; + +struct RawKey { + u64 key = 0; + std::vector seeds; + std::vector learned; // addresses missed by earlier dispatches (page start), at most 4 + UINT slot = 0; // statistics slot in rawaddr_stats + LONG dispatches = 0, resolved = 0, unresolved = 0, overflow = 0, skipped = 0, shown = 0; + LONG reported_dispatches = 0; + std::uint32_t seen_misses = 0; +}; +struct RawPipeline { + RawKey* key; + ID3D12RootSignature* root; + ID3D12PipelineState* pso; + UINT first_extra; +}; +SRWLOCK rawaddr_lock = SRWLOCK_INIT; +std::unordered_map& rawaddr_keys() { static std::unordered_map m; return m; } +std::unordered_map& rawaddr_pipelines() { static std::unordered_map m; return m; } +constexpr UINT rawaddr_stats_slots = 256; +ID3D12Resource* rawaddr_stats; +volatile std::uint32_t* rawaddr_stats_words; // CPU view of the custom-heap statistics buffer +LONG rawaddr_stats_failed; + +// Opt-in: the raw-address shaders have not run on title data yet, so a published sidecar stays inert +// unless X2W_RAWADDR=1 (X2W_RAWADDR_OFF=1 still wins). +bool rawaddr_enabled() +{ + static const bool enabled = x2w_local::env_on("X2W_RAWADDR") && !x2w_local::env_on("X2W_RAWADDR_OFF"); + return enabled; +} + +// One CPU-readable buffer (custom heap, write-back, L0) with a 128-byte statistics slot per key. +void rawaddr_ensure_stats() +{ + if (rawaddr_stats || rawaddr_stats_failed) return; + D3D12_HEAP_PROPERTIES hp{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0}; + D3D12_RESOURCE_DESC rd{}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rd.Width = u64{rawaddr_stats_slots} * ra::kStatsBytes; + rd.Height = rd.DepthOrArraySize = rd.MipLevels = 1; + rd.SampleDesc.Count = 1; + rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + HRESULT hr = device_of(the_device)->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&rawaddr_stats)); + void* words = nullptr; + if (SUCCEEDED(hr)) hr = rawaddr_stats->Map(0, nullptr, &words); + if (FAILED(hr)) { + rawaddr_stats_failed = 1; + if (rawaddr_stats) rawaddr_stats->Release(); + rawaddr_stats = nullptr; + log("x2w-rawaddr statistics buffer failed 0x%08lx: GPU misses are not counted", static_cast(hr)); + return; + } + std::memset(words, 0, static_cast(rd.Width)); + rawaddr_stats_words = static_cast(words); +} + +// Device slot 62 hook: builds the raw-address pipeline for key when its sidecar exists. True when the +// key has a sidecar (whether or not the pipeline could be built): the plain .cs.dxbc path is then skipped. +bool rawaddr_pipeline(u64 key, Wrapper* root, Wrapper* pipeline) +{ + if (!key || !pipeline) return false; + wchar_t path[MAX_PATH]; + std::string sidecar; + if (!cache_path(path, L"", key, L".rawaddr.txt") || !read_text(path, sidecar)) return false; + if (!rawaddr_enabled()) { + static LONG logged; + if (first_calls(logged, 4)) log("x2w-rawaddr %016llx: sidecar present, path off (needs X2W_RAWADDR=1, no X2W_RAWADDR_OFF): no pipeline", key); + return true; + } + std::vector seeds; + if (!ra::parse_sidecar(sidecar, seeds)) { + log("x2w-rawaddr %016llx: sidecar not understood (version / table shape): no pipeline", key); + return true; + } + std::vector blob; + AcquireSRWLockShared(¬e_lock); + if (const auto found = root_blobs().find(root); found != root_blobs().end()) blob = found->second; + ReleaseSRWLockShared(¬e_lock); + ID3DBlob* code = nullptr; + const char* error = nullptr; + UINT first = 0; + ID3DBlob* augmented = blob.empty() ? nullptr : ra::augmented_root(blob.data(), blob.size(), &first, &error); + ID3D12RootSignature* signature = nullptr; + ID3D12PipelineState* pso = nullptr; + HRESULT hr = augmented ? S_OK : E_FAIL; + if (blob.empty()) error = "no title root blob"; + if (SUCCEEDED(hr)) hr = device_of(the_device)->CreateRootSignature(0, augmented->GetBufferPointer(), augmented->GetBufferSize(), IID_PPV_ARGS(&signature)); + if (augmented) augmented->Release(); + if (SUCCEEDED(hr) && (!cache_path(path, L"", key, L".rawaddr.dxbc") || FAILED(D3DReadFileToBlob(path, &code)))) { + hr = E_FAIL; + error = "no .rawaddr.dxbc"; + } + if (SUCCEEDED(hr)) { + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = signature; + pd.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + hr = device_of(the_device)->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pso)); + if (FAILED(hr)) error = "CreateComputePipelineState"; + } + if (code) code->Release(); + log("x2w-rawaddr %016llx pipeline: title root params %u + 2, %zu seeds -> 0x%08lx%s%s", key, first, seeds.size(), + static_cast(hr), error ? " " : "", error ? error : ""); + if (FAILED(hr)) { + if (signature) signature->Release(); + return true; + } + AcquireSRWLockExclusive(&rawaddr_lock); + RawKey*& k = rawaddr_keys()[key]; + if (!k) { + k = new RawKey; + k->key = key; + k->seeds = seeds; + k->slot = static_cast(rawaddr_keys().size() - 1) % rawaddr_stats_slots; + } + rawaddr_pipelines()[pipeline] = {k, signature, pso, first}; + ReleaseSRWLockExclusive(&rawaddr_lock); + return true; +} + +// The largest span [address, address + span) contiguous in one desktop window, up to X2W_RAWADDR_SPAN_MIB +// (default 16 MiB), to 64 KiB granularity: the cap, then quarters until one fits, then a binary search +// between that span and the failing one above it. At least the 4 KiB page, else unresolved. +bool rawaddr_region(u64 address, ra::Region* region, ID3D12Resource** window) +{ + static const u64 cap = [] { + char text[16] = ""; + const DWORD n = GetEnvironmentVariableA("X2W_RAWADDR_SPAN_MIB", text, sizeof(text)); + const unsigned long mib = n && n < sizeof(text) ? std::strtoul(text, nullptr, 10) : 0; + return u64{mib >= 1 && mib <= 192 ? mib : 16} << 20; + }(); + u64 offset = 0, good = 0, bad = 0; + ID3D12Resource* w = nullptr; + for (u64 span = cap; span >= 0x10000; span >>= 2) { + if (desktop_range(address, span, &w, &offset)) { + good = span; + break; + } + bad = span; + } + if (!good) { + if (!desktop_range(address, 0x1000, &w, &offset)) return false; // at least the page + *window = w; + *region = ra::make_region(address, 0x1000, offset); + return true; + } + u64 good_offset = offset; + ID3D12Resource* good_window = w; + while (bad && bad - good > 0x10000) { + const u64 mid = (good + (bad - good) / 2) & ~0xffffull; + if (mid <= good) break; + if (desktop_range(address, mid, &w, &offset)) { + good = mid; + good_offset = offset; + good_window = w; + } else { + bad = mid; + } + } + *window = good_window; + *region = ra::make_region(address, good, good_offset); + return true; +} + +// execute_dispatch hook: runs the dispatch when the bound pipeline is a raw-address pipeline. False when +// it is not one (or a title argument cannot be bound: the dispatch is then skipped by the caller). +bool rawaddr_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z) +{ + Pass& pass = pass_of(self); + AcquireSRWLockShared(&rawaddr_lock); + const auto found = rawaddr_pipelines().find(pass.pipeline); + const RawPipeline rp = found != rawaddr_pipelines().end() ? found->second : RawPipeline{}; + ReleaseSRWLockShared(&rawaddr_lock); + if (!rp.pso || !pass.compute_root) return false; + RawKey& key = *rp.key; + // the title's own parameters, replayed as execute_dispatch does + D3D12_GPU_VIRTUAL_ADDRESS addresses[16] = {}; + for (UINT i = 0; i < 16; ++i) { + const int kind = pass.compute_kind[i]; + if (kind == 5 || (kind >= 2 && kind <= 4 && pass.compute_address[i] && !(addresses[i] = desktop_va(pass.compute_address[i])))) { + if (x2w_local::first_of(InterlockedIncrement(&key.skipped), 4)) log("x2w-rawaddr %016llx: title parameter %u (kind %d) not bindable: dispatch skipped", key.key, i, kind); + return false; + } + } + // learned seeds: addresses this key missed before (statistics slot, written by the GPU) + AcquireSRWLockExclusive(&rawaddr_lock); + rawaddr_ensure_stats(); // lists record on several threads: created under the lock + if (rawaddr_stats_words) { + const volatile std::uint32_t* s = rawaddr_stats_words + key.slot * (ra::kStatsBytes / 4); + const std::uint32_t misses = s[0]; + if (misses != key.seen_misses) { + for (UINT i = 0; i < ra::kStatsRing && i < misses - key.seen_misses && key.learned.size() < 4; ++i) { + const u64 a = (s[4 + 2 * i] | (u64{s[5 + 2 * i]} << 32)) & ~0xffffull; + if (a && std::find(key.learned.begin(), key.learned.end(), a) == key.learned.end()) key.learned.push_back(a); + } + key.seen_misses = misses; + } + } + std::vector learned = key.learned; + ReleaseSRWLockExclusive(&rawaddr_lock); + // seeds -> regions: root constants first, then learned, then root descriptors + ra::Region regions[ra::kRegions]{}; + ID3D12Resource* windows[ra::kRegions] = {}; + UINT count = 0, resolved = 0, unresolved = 0, overflow = 0; + std::vector forget; // learned addresses that do not resolve: dropped so they free their place + const bool show = x2w_local::first_calls(key.shown, 2); + auto add = [&](u64 address, const char* what) { + if (!address) return; + for (UINT k = 0; k < count; ++k) + if (ra::region_contains(regions[k], address)) return; + if (count >= ra::kRegions) { + ++overflow; + if (show) log("x2w-rawaddr %016llx seed %s 0x%llx -> DROPPED (table full)", key.key, what, address); + return; + } + if (rawaddr_region(address, ®ions[count], &windows[count])) { + ++resolved; + if (show) log("x2w-rawaddr %016llx seed %s 0x%llx -> region %u, %u bytes", key.key, what, address, count, regions[count].size); + ++count; + } else { + ++unresolved; + if (what[0] == 'l') forget.push_back(address); + if (show) log("x2w-rawaddr %016llx seed %s 0x%llx -> UNRESOLVED", key.key, what, address); + } + }; + for (const ra::Seed& s : key.seeds) + if (s.kind != ra::SeedKind::rootdesc) add(ra::seed_address(s, pass.compute_kind, pass.compute_constants, pass.compute_address), "rootconst"); + for (u64 a : learned) add(a, "learned"); + for (const ra::Seed& s : key.seeds) + if (s.kind == ra::SeedKind::rootdesc) add(ra::seed_address(s, pass.compute_kind, pass.compute_constants, pass.compute_address), "rootdesc"); + InterlockedExchangeAdd(&key.resolved, static_cast(resolved)); + InterlockedExchangeAdd(&key.unresolved, static_cast(unresolved)); + InterlockedExchangeAdd(&key.overflow, static_cast(overflow)); + if (!forget.empty()) { + AcquireSRWLockExclusive(&rawaddr_lock); + for (u64 a : forget) key.learned.erase(std::remove(key.learned.begin(), key.learned.end(), a), key.learned.end()); + ReleaseSRWLockExclusive(&rawaddr_lock); + } + std::uint32_t table[ra::kTableDwords]; + ra::fill_table(regions, count, table); + + lock_draw(400000 + __LINE__); + if (!ensure_draw_heap(the_device)) { + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(ra::kSlots))) % draw_heap_size; + if (first + ra::kSlots > draw_heap_size) { + first = 0; + InterlockedExchange(&draw_heap_cursor, static_cast(ra::kSlots)); + } + auto raw_uav = [&](ID3D12Resource* buffer, u64 offset, UINT bytes, UINT slot) { + D3D12_UNORDERED_ACCESS_VIEW_DESC d{}; + d.Format = DXGI_FORMAT_R32_TYPELESS; + d.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + d.Buffer.FirstElement = offset / 4; + d.Buffer.NumElements = buffer ? (bytes + 3) / 4 : 1; + d.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + const D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + slot} * draw_heap_increment}; + device_of(the_device)->CreateUnorderedAccessView(buffer, nullptr, &d, dest); + }; + for (UINT k = 0; k < ra::kRegions; ++k) raw_uav(k < count ? windows[k] : nullptr, regions[k].view_offset, regions[k].size, k); + raw_uav(nullptr, 0, 0, ra::kNullSlot); + raw_uav(rawaddr_stats, u64{key.slot} * ra::kStatsBytes, ra::kStatsBytes, ra::kStatsSlot); + list->SetPipelineState(rp.pso); + if (!pass.heap_set) { + list->SetDescriptorHeaps(1, &draw_heap); + pass.heap_set = true; + pass.bound_sampler_heap = nullptr; // this call unbinds any sampler heap a draw bound + } + list->SetComputeRootSignature(rp.root); + for (UINT i = 0; i < 16 && i < rp.first_extra; ++i) { + switch (pass.compute_kind[i]) { + case 1: list->SetComputeRoot32BitConstants(i, pass.compute_count[i], pass.compute_constants[i], 0); break; + case 2: list->SetComputeRootConstantBufferView(i, addresses[i]); break; + case 3: list->SetComputeRootShaderResourceView(i, addresses[i]); break; + case 4: list->SetComputeRootUnorderedAccessView(i, addresses[i]); break; + default: break; + } + } + list->SetComputeRoot32BitConstants(rp.first_extra, ra::kTableDwords, table, 0); + list->SetComputeRootDescriptorTable(rp.first_extra + 1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + ReleaseSRWLockExclusive(&draw_lock); + indirect_dispatch(self, list, x, y, z); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + const LONG done = InterlockedIncrement(&key.dispatches); + if (x2w_local::first_of(done, 2)) log("x2w-rawaddr %016llx dispatch %ld (%u, %u, %u): regions %u, seeds resolved %u unresolved %u", key.key, done, x, y, z, count, resolved, unresolved); + if ((done & 63) == 1) check_device("raw-address dispatch", 0); + return true; +} + +// Heartbeat: one line per key dispatched since the last report. +void rawaddr_report() +{ + AcquireSRWLockShared(&rawaddr_lock); + for (const auto& [id, k] : rawaddr_keys()) { + const LONG d = k->dispatches; + if (d == k->reported_dispatches) continue; + const std::uint32_t misses = rawaddr_stats_words ? rawaddr_stats_words[k->slot * (ra::kStatsBytes / 4)] : 0; + log("x2w-rawaddr %016llx: dispatches %ld (+%ld), seeds resolved %ld unresolved %ld dropped %ld, gpu misses %u%s, learned %zu, skipped %ld", + id, d, d - k->reported_dispatches, k->resolved, k->unresolved, k->overflow, misses, rawaddr_stats_words ? "" : " (not counted)", + k->learned.size(), k->skipped); + k->reported_dispatches = d; + } + ReleaseSRWLockShared(&rawaddr_lock); +} diff --git a/src/startup_stubs/d3d12_record_trace.inl b/src/startup_stubs/d3d12_record_trace.inl new file mode 100644 index 0000000000..18c1bdbb32 --- /dev/null +++ b/src/startup_stubs/d3d12_record_trace.inl @@ -0,0 +1,716 @@ + +bool record_trace_on() +{ + static const bool on = x2w_local::env_on("X2W_MESH_RECORD_TRACE"); + return on; +} + +struct TracedRecord { + LONG seq = 0; + UINT type = 0; // D3D12_INDIRECT_ARGUMENT_TYPE of the signature's last argument (10 = DispatchMesh) + UINT stride = 0, max_count = 0; + u64 key = 0; + const void* list = nullptr; + const void* dsv = nullptr; + const void* wrapper = nullptr; + const unsigned char* base = nullptr; // title memory of the argument buffer + u64 offset = 0; + UINT words = 0; + std::uint32_t at_record[4] = {}; +}; +struct TracedRange { + LONG seq = 0; // the dispatch's number in the traced frame + u64 key = 0; + const void* pipeline = nullptr; + char label = '?'; + int param = 0, offset = 0; + u64 lo = 0, hi = 0; + const char* state = ""; + LONG order = 0; // record order shared with the mesh reads + bool executed = false; +}; +// (f) one buffer a traced mesh call reads: kind 'S' srv i (source a b), 'H' heap descriptor `slot` (root constant p w). +struct TracedMeshRead { + u64 key = 0; + char kind = 'S'; + int slot = 0, source = 0, a = 0, b = 0; + u64 lo = 0, hi = 0; + LONG order = 0; +}; +SRWLOCK record_trace_lock = SRWLOCK_INIT; +std::vector& traced_records() { static std::vector v; return v; } +std::vector& traced_ranges() { static std::vector v; return v; } +std::vector& traced_mesh_reads() { static std::vector v; return v; } +// (d) texture UAVs bound by this frame's dispatches so far: title wrapper -> "key K #n state". +std::map& traced_image_writers() { static std::map m; return m; } +// (d) raw T# base -> (first resource starting there, how many): one resource walk per base per traced frame. +std::map>& traced_tsharp_bases() { static std::map> m; return m; } +LONG record_trace_seq, dispatch_trace_seq, record_trace_order; +thread_local bool record_trace_dispatch_noted; // set by record_trace_dispatch inside an indirect call + +const char* record_trace_outcome(int outcome) +{ + static const char* const names[] = {"run (c62)", "skipped: c62 table argument", "skipped: c62 unmapped", "run", + "skipped: X2W_CX_OFF", "skipped: not a slot-67 key", "skipped: no translation", + "skipped: heap", "skipped: not run", "skipped: X2W_CX_SKIP", "run (rawaddr)", + "skipped: entry value unresolved", "skipped: compiling (X2W_CX_ASYNC)"}; + static_assert(sizeof(names) / sizeof(names[0]) == co_count, "one name per ComputeOutcome"); + return outcome >= 0 && outcome < co_count ? names[outcome] : "skipped: ?"; +} + +bool record_trace_entry(const std::uint32_t* w, u64* address, u64* bytes) +{ + *address = 0, *bytes = 0; + if (w[0] == view_token_magic) { + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = w[1] < view_records().size(); + if (known) record = view_records()[w[1]]; + ReleaseSRWLockShared(¬e_lock); + if (!known) return false; + if (record.slot == 17 && record.desc_bytes >= 12) { + std::uint32_t size = 0; + std::memcpy(address, record.desc, 8); + std::memcpy(&size, record.desc + 8, 4); + *bytes = size; + } else if ((record.slot == 18 || record.slot == 19) && record.desc_bytes >= 24) { + Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + x2w_startup::BufferViewLayout l; + if (!resource || !resource->own().title_memory || + !x2w_startup::buffer_view_layout_from_desc(record.slot == 19, record.desc, record.desc_bytes, l, typed_views_off())) + return false; + *address = reinterpret_cast(resource->own().title_memory) + l.offset; + *bytes = l.bytes; + } + } else if (w[0] != 0x52463258u /* refused-view marker */ && (w[3] >> 30) == 0) { + *address = w[0] | (static_cast(w[1] & 0xffff) << 32); + const std::uint32_t stride = (w[1] >> 16) & 0x3fff; + *bytes = u64{stride ? stride : 1u} * w[2]; + } + if (*bytes > (256ull << 20)) *bytes = 256ull << 20; + return *address && *bytes; +} + +// (d) The resource half of an image line: wrapper, title memory, desktop resource and what this frame did to it. +// No side effects (no memcut revive, no tiled stand-in made): a released resource says so. +void record_trace_resource_text(Wrapper* resource, char* text, std::size_t room) +{ + if (!resource || resource->own().kind != resource_kind) { + std::snprintf(text, room, "resource unknown"); + return; + } + const bool live = InterlockedCompareExchange(&resource->own().refs, 0, 0) > 0; + auto* desktop = static_cast(resource->own().real); + int n = std::snprintf(text, room, "res %p title 0x%llx desktop %p%s", static_cast(resource), + static_cast(reinterpret_cast(resource->own().title_memory)), static_cast(desktop), + resource->own().tiled_address_srv ? " (tiled address srv: sampled through a stand-in)" : ""); + if (desktop && live) { + const D3D12_RESOURCE_DESC d = desktop->GetDesc(); + n += std::snprintf(text + n, room - n, " %llux%ux%u mips %u fmt %d flags 0x%x", static_cast(d.Width), d.Height, + d.DepthOrArraySize, d.MipLevels, static_cast(d.Format), static_cast(d.Flags)); + } else { + n += std::snprintf(text + n, room - n, " (%s)", live ? "no desktop resource" : "released"); + } + // Content: this frame's writers before now. + int drawn = -1; + if (desktop) { + AcquireSRWLockShared(&traced_lock); + for (const auto& t : traced_targets()) + if (t.first == desktop) drawn = t.second; + ReleaseSRWLockShared(&traced_lock); + } + std::string uav; + AcquireSRWLockShared(&record_trace_lock); + const auto found = traced_image_writers().find(resource); + if (found != traced_image_writers().end()) uav = found->second; + ReleaseSRWLockShared(&record_trace_lock); + if (drawn < 0 && uav.empty()) { + std::snprintf(text + n, room - n, "; content: no writer seen in this frame before this dispatch%s", + desktop && live && !(desktop->GetDesc().Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + ? " (no GPU-write flags: uploaded from title memory)" : ""); + return; + } + n += std::snprintf(text + n, room - n, "; content:"); + if (drawn >= 0) n += std::snprintf(text + n, room - n, " render/depth target of this frame, %d drawn draws so far;", drawn); + if (!uav.empty()) std::snprintf(text + n, room - n, " texture uav of %s", uav.c_str()); +} + +// (d) A 32-byte entry as an image: a view token of a texture view, or a raw gfx10 T#. Fills `text` and returns the +// title wrapper (or null); *uav: a UAV view (slot 19). False: not an image entry. +bool record_trace_image(const std::uint32_t* w, char* text, std::size_t room, Wrapper** wrapper_out, bool* uav) +{ + *wrapper_out = nullptr, *uav = false; + char res[400]; + if (w[0] == view_token_magic) { + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = w[1] < view_records().size(); + if (known) record = view_records()[w[1]]; + ReleaseSRWLockShared(¬e_lock); + if (!known || (record.slot != 18 && record.slot != 19) || record.desc_bytes < 12) return false; + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; + UINT dimension = 0, mip = 0; + std::memcpy(&format, record.desc, 4); + std::memcpy(&dimension, record.desc + 4, 4); + // SRV: ViewDimension 1 = buffer; UAV: 1 = buffer. Both: the first mip at +16 (SRV MostDetailedMip) / +8 (UAV MipSlice). + if (dimension == 1 || dimension == 0) return false; + if (record.slot == 18 && record.desc_bytes >= 20) std::memcpy(&mip, record.desc + 16, 4); + if (record.slot == 19 && record.desc_bytes >= 12) std::memcpy(&mip, record.desc + 8, 4); + Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + record_trace_resource_text(resource, res, sizeof(res)); + std::snprintf(text, room, "view %u (%s) dim %u fmt %d mip %u; %s", w[1], record.slot == 19 ? "uav" : "srv", dimension, + static_cast(format), mip, res); + *wrapper_out = resource; + *uav = record.slot == 19; + return true; + } + const std::uint32_t type = w[3] >> 28; + if (w[0] == 0x52463258u || type < 8 || type > 13) return false; + const u64 address = (static_cast(w[0]) | (static_cast(w[1] & 0xff) << 32)) << 8; + const std::uint32_t width = (((w[1] >> 30) & 3) | ((w[2] & 0xfff) << 2)) + 1, height = ((w[2] >> 14) & 0x3fff) + 1; + // The resource whose title memory starts at the T# base (a texture; several: the first, counted). + // One walk of the resources per distinct base in the traced frame (the cache is emptied at the report). + Wrapper* resource = nullptr; + int matches = 0; + bool cached = false; + AcquireSRWLockShared(&record_trace_lock); + if (const auto hit = traced_tsharp_bases().find(address); hit != traced_tsharp_bases().end()) + cached = true, resource = hit->second.first, matches = hit->second.second; + ReleaseSRWLockShared(&record_trace_lock); + if (address && !cached) { + AcquireSRWLockShared(¬e_lock); + for (const auto& [wrapper, info] : resource_infos()) + if (reinterpret_cast(wrapper->own().title_memory) == address && info.console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && + InterlockedCompareExchange(&wrapper->own().refs, 0, 0) > 0) { + if (!resource) resource = const_cast(wrapper); + ++matches; + } + ReleaseSRWLockShared(¬e_lock); + AcquireSRWLockExclusive(&record_trace_lock); + traced_tsharp_bases()[address] = {resource, matches}; + ReleaseSRWLockExclusive(&record_trace_lock); + } + if (resource) record_trace_resource_text(resource, res, sizeof(res)); + else std::snprintf(res, sizeof(res), "no resource starts at the base"); + std::snprintf(text, room, "T# 0x%llx %ux%u depth %u fmt %u levels %u-%u type %u sw %u; %s%s", static_cast(address), width, + height, (w[4] & 0x1fff) + 1, (w[1] >> 20) & 0x1ff, (w[3] >> 12) & 15, (w[3] >> 16) & 15, type, (w[3] >> 20) & 0x1f, res, + matches > 1 ? " (several resources start there: the first)" : ""); + *wrapper_out = resource; + return true; +} + +// (e) The title CBV_SRV_UAV heap of a list: the bound one (SetDescriptorHeaps), else the one holding a bound compute +// table, else the newest (title_view_heap's rule). +struct TraceHeap { + u64 base = 0, bytes = 0; + UINT increment = 32, count = 0; +}; +TraceHeap record_trace_heap(const Pass& pass) +{ + TraceHeap out; + AcquireSRWLockShared(¬e_lock); + const HeapInfo* best = nullptr; + for (const HeapInfo& h : heap_infos()) { + if (h.type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || !h.title_cpu || !h.increment) continue; + if (pass.source_view_heap && h.wrapper == pass.source_view_heap) { + best = &h; + break; + } + for (UINT i = 0; i < 16; ++i) + if (pass.compute_kind[i] == 5 && pass.compute_address[i] >= h.title_cpu && pass.compute_address[i] < h.title_cpu + u64{h.count} * h.increment) + best = &h; + if (!best) best = &h; + } + if (best) out.base = best->title_cpu, out.increment = best->increment, out.count = best->logical_count ? best->logical_count : best->count, + out.bytes = u64{out.count} * best->increment; + ReleaseSRWLockShared(¬e_lock); + return out; +} +// (e) The descriptor at heap index `index`: a buffer range (true, *address / *bytes) or text for anything else. +bool record_trace_heap_slot(const TraceHeap& heap, std::uint32_t index, u64* address, u64* bytes, char* text, std::size_t room, Wrapper** image) +{ + *address = 0, *bytes = 0, *image = nullptr; + text[0] = 0; + const u64 slot = heap.base + u64{index} * heap.increment; + std::uint32_t w[8] = {}; + if (!heap.base || index >= heap.count || !x2w_local::readable(reinterpret_cast(slot), 32)) { + std::snprintf(text, room, "slot 0x%llx not readable", static_cast(slot)); + return false; + } + std::memcpy(w, reinterpret_cast(slot), 32); + if (record_trace_entry(w, address, bytes)) return true; + bool uav = false; + char image_text[700]; + if (record_trace_image(w, image_text, sizeof(image_text), image, &uav)) { + std::snprintf(text, room, "image: %s", image_text); + return false; + } + std::snprintf(text, room, "other: words %08x %08x %08x %08x", w[0], w[1], w[2], w[3]); + return false; +} + +// (c) execute_dispatch, every dispatch on this thread (direct, and indirect through indirect_run). +void record_trace_dispatch(Wrapper* self, u64 key, UINT x, UINT y, UINT z, bool executed, int outcome) +{ + if (!trace_frame_active || !record_trace_on()) return; + const bool indirect = indirect_current != nullptr; + if (indirect) record_trace_dispatch_noted = true; + const LONG seq = InterlockedIncrement(&dispatch_trace_seq); + const char* state = executed ? "run" : record_trace_outcome(outcome); + const Pass& pass = pass_of(self); + // The manifest's buffer resources, when the key is translated (state 1). + struct Res { bool uav; int kind, source, a, b; }; + std::vector manifest; + bool have_manifest = false; + if ((key >> 56) == 0x67) { + bool locked = false; + for (int i = 0; i < 200 && !(locked = TryAcquireSRWLockExclusive(&draw_lock)); ++i) Sleep(0); + if (locked) { + const auto found = compute_translations().find(key); + if (found != compute_translations().end() && found->second.state == 1) { + have_manifest = true; + for (const auto& r : found->second.res) manifest.push_back({r.uav, r.kind, r.source, r.a, r.b}); + } + ReleaseSRWLockExclusive(&draw_lock); + } + } + const LONG order = InterlockedIncrement(&record_trace_order); + std::vector ranges; + const auto add = [&](char label, int param, int offset, u64 address, u64 bytes) { + TracedRange r; + r.seq = seq, r.key = key, r.pipeline = pass.pipeline, r.label = label, r.param = param, r.offset = offset, r.lo = address, r.hi = address + bytes, r.state = state; + r.order = order, r.executed = executed; + ranges.push_back(r); + }; + // (d) image entries: logged after the cx-uav line; texture UAVs become writers once this dispatch is logged. + std::vector image_lines; + std::vector uav_images; + const auto image_at = [&](char label, int param, int offset, const std::uint32_t* w) { + if (image_lines.size() >= 16) return; + Wrapper* resource = nullptr; + bool uav_view = false; + char text[900]; + if (!record_trace_image(w, text, sizeof(text), &resource, &uav_view)) { + // Neither buffer nor image (refused-view marker, a view token without a usable desc, an "integer + 7 zero + // words" heap-index entry, a sampler, a neighbouring table's bytes): the raw words, so no entry is silent. + bool any = false; + for (int k = 0; k < 8; ++k) any |= w[k] != 0; + if (!any) return; + int n = std::snprintf(text, sizeof(text), "other: words %08x %08x %08x %08x %08x %08x %08x %08x", w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]); + if (w[0] == view_token_magic) { + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = w[1] < view_records().size(); + if (known) record = view_records()[w[1]]; + ReleaseSRWLockShared(¬e_lock); + if (known) std::snprintf(text + n, sizeof(text) - n, " (view token: slot %u, desc %u bytes, resource 0x%llx)", record.slot, record.desc_bytes, + static_cast(record.resource)); + else std::snprintf(text + n, sizeof(text) - n, " (view token: unknown view)"); + } else if (w[0] == 0x52463258u) { + std::snprintf(text + n, sizeof(text) - n, " (refused-view marker)"); + } else if (w[0] && !(w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7])) { + std::snprintf(text + n, sizeof(text) - n, " (integer + 7 zero words: a heap index?)"); + } + } + const bool uav = uav_view || label == 'U'; + char line[1100]; + std::snprintf(line, sizeof(line), "x2w-frame cx-img #%ld key %016llx %c p%d+0x%x%s: %s", seq, static_cast(key), label, param, + offset, uav ? " (uav)" : "", text); + image_lines.push_back(line); + if (uav && resource) uav_images.push_back(resource); + }; + for (int p = 0; p < 16; ++p) { + const int kind = pass.compute_kind[p]; + const u64 address = pass.compute_address[p]; + if ((kind == 3 || kind == 4) && address) { + add('R', p, 0, address, readable_window(address, 1u << 20)); + } else if (kind == 5 && address) { + const auto entry_at = [&](char label, int offset) { + const u64 entry = address + static_cast(offset); + std::uint32_t w[8]; + if (!x2w_local::readable(reinterpret_cast(entry), 32)) return false; + std::memcpy(w, reinterpret_cast(entry), 32); + u64 at = 0, bytes = 0; + if (record_trace_entry(w, &at, &bytes)) add(label, p, offset, at, bytes); + else image_at(label == 'S' ? 'T' : label, p, offset, w); // (d) + return true; + }; + if (have_manifest) { // translated: exactly the manifest's buffers (and, d, images) in this table + for (const Res& r : manifest) + if (r.source == 0 && r.a == p && r.b >= 0) entry_at(r.uav ? 'U' : 'S', r.b); + } else { // not translated: every buffer-shaped (and image) entry of the first 64 + for (int e = 0; e < 64 && entry_at('?', e * 32); ++e) { + } + } + } + } + // (e) heap descriptors named by root constants (ASSUMED rule, see the head of this file). + std::vector heap_lines; + { + const TraceHeap heap = record_trace_heap(pass); + // Skipped dispatches: the raw root arguments and the heap used, so the index / base mapping can be checked + // offline (a constant equal to the heap's low 32 bits, or to a table's, is marked). + if (!executed) { + char line[1400]; + int n = std::snprintf(line, sizeof(line), "x2w-frame cx-root #%ld key %016llx: heap 0x%llx (low 0x%08x) count %u increment %u;", seq, + static_cast(key), static_cast(heap.base), static_cast(heap.base), + heap.count, heap.increment); + for (int p = 0; p < 16 && n < static_cast(sizeof(line)) - 160; ++p) { + const int kind = pass.compute_kind[p]; + if (!kind) continue; + if (kind != 1) { + n += std::snprintf(line + n, sizeof(line) - n, " p%d kind %d 0x%llx (low 0x%08x);", p, kind, + static_cast(pass.compute_address[p]), static_cast(pass.compute_address[p])); + continue; + } + n += std::snprintf(line + n, sizeof(line) - n, " p%d constants %u:", p, pass.compute_count[p]); + for (UINT w = 0; w < pass.compute_count[p] && w < 16 && n < static_cast(sizeof(line)) - 40; ++w) { + const std::uint32_t c = pass.compute_constants[p][w]; + bool table_low = false; + for (int q = 0; q < 16; ++q) table_low |= pass.compute_kind[q] == 5 && c && c == static_cast(pass.compute_address[q]); + n += std::snprintf(line + n, sizeof(line) - n, " %08x%s", c, + heap.base && c == static_cast(heap.base) ? "(=heap low)" : table_low ? "(=table low)" : ""); + } + n += std::snprintf(line + n, sizeof(line) - n, ";"); + } + heap_lines.push_back(line); + } + unsigned looked = 0; + std::uint32_t seen[8]; + for (int p = 0; p < 16 && heap.base && looked < 8; ++p) { + if (pass.compute_kind[p] != 1) continue; + for (UINT w = 0; w < pass.compute_count[p] && w < 16 && looked < 8; ++w) { + const std::uint32_t c = pass.compute_constants[p][w]; + const std::uint32_t index = c < heap.count ? c : (c & (1u << 28)) && (c & 0x3ff) < heap.count ? (c & 0x3ff) : 0xffffffffu; + if (index == 0xffffffffu) continue; + bool again = false; + for (unsigned k = 0; k < looked; ++k) again |= seen[k] == index; + if (again) continue; + seen[looked++] = index; + u64 at = 0, bytes = 0; + Wrapper* image = nullptr; + char text[800]; + const bool buffer = record_trace_heap_slot(heap, index, &at, &bytes, text, sizeof(text), &image); + if (buffer) { + add('H', p, static_cast(w * 4), at, bytes); + std::snprintf(text, sizeof(text), "buffer 0x%llx %llu bytes", static_cast(at), static_cast(bytes)); + } + char line[1100]; + std::snprintf(line, sizeof(line), "x2w-frame cx-heap #%ld key %016llx root constant p%d w%u = 0x%08x -> heap 0x%llx index %u (count %u, increment %u): %s", + seq, static_cast(key), p, w, c, static_cast(heap.base), index, heap.count, + heap.increment, text); + heap_lines.push_back(line); + } + } + } + char text[1400]; + int n = std::snprintf(text, sizeof(text), "x2w-frame cx-uav #%ld key %016llx ", seq, static_cast(key)); + if (indirect) n += std::snprintf(text + n, sizeof(text) - n, "indirect"); + else n += std::snprintf(text + n, sizeof(text) - n, "(%u, %u, %u)", x, y, z); + n += std::snprintf(text + n, sizeof(text) - n, " pipeline %p: %s%s:", static_cast(pass.pipeline), state, have_manifest || (key >> 56) != 0x67 ? "" : ", no manifest"); + if (ranges.empty()) n += std::snprintf(text + n, sizeof(text) - n, " no buffer bound"); + for (const TracedRange& r : ranges) { + if (n > static_cast(sizeof(text)) - 64) { + log("%s ...", text); + n = std::snprintf(text, sizeof(text), "x2w-frame cx-uav #%ld (cont.):", seq); + } + n += std::snprintf(text + n, sizeof(text) - n, " %c p%d+0x%x 0x%llx %llu;", r.label, r.param, r.offset, + static_cast(r.lo), static_cast(r.hi - r.lo)); + } + log("%s", text); + for (const std::string& line : image_lines) log("%s", line.c_str()); + for (const std::string& line : heap_lines) log("%s", line.c_str()); + char writer[96]; + std::snprintf(writer, sizeof(writer), "key %016llx #%ld (%s)", static_cast(key), seq, state); + AcquireSRWLockExclusive(&record_trace_lock); + traced_ranges().insert(traced_ranges().end(), ranges.begin(), ranges.end()); + for (const void* image : uav_images) traced_image_writers()[image] = writer; + ReleaseSRWLockExclusive(&record_trace_lock); +} + +// (f) d3d12_draw.inl draw_translated, a traced mesh call: one buffer srv it binds (title address and full size). +void record_trace_mesh_read(u64 key, UINT srv, int source, int a, int b, u64 address, u64 bytes) +{ + if (!record_trace_on() || !address || !bytes) return; + TracedMeshRead r; + r.key = key, r.kind = 'S', r.slot = static_cast(srv), r.source = source, r.a = a, r.b = b, r.lo = address, r.hi = address + bytes; + r.order = InterlockedIncrement(&record_trace_order); + AcquireSRWLockExclusive(&record_trace_lock); + traced_mesh_reads().push_back(r); + ReleaseSRWLockExclusive(&record_trace_lock); +} +// (f) the heap buffers a traced mesh call names through root constants the translation reads with bit 28 set +// (index in bits 0-9: the X2W_MESH_DUMP_INPUTS rule, ASSUMED). +void record_trace_mesh_heap(Wrapper* self, const Translation& tr) +{ + if (!record_trace_on()) return; + const Pass& pass = pass_of(self); + const TraceHeap heap = record_trace_heap(pass); + if (!heap.base) return; + std::vector reads; + for (const Translation::Ud& ud : tr.uds) { + if (ud.kind != Translation::root_constant || ud.a < 0 || ud.a >= 16 || ud.b < 0 || ud.b >= 8) continue; + const std::uint32_t c = pass.constants[ud.a][ud.b]; + if (!(c & (1u << 28)) || (c & 0x3ff) >= heap.count) continue; + u64 at = 0, bytes = 0; + Wrapper* image = nullptr; + char text[800]; + if (!record_trace_heap_slot(heap, c & 0x3ff, &at, &bytes, text, sizeof(text), &image)) continue; + bool again = false; + for (const TracedMeshRead& r : reads) again |= r.lo == at && r.hi == at + bytes; + if (again) continue; + TracedMeshRead r; + r.key = tr.key, r.kind = 'H', r.slot = static_cast(c & 0x3ff), r.a = ud.a, r.b = ud.b, r.lo = at, r.hi = at + bytes; + r.order = InterlockedIncrement(&record_trace_order); + reads.push_back(r); + } + if (reads.empty()) return; + AcquireSRWLockExclusive(&record_trace_lock); + traced_mesh_reads().insert(traced_mesh_reads().end(), reads.begin(), reads.end()); + ReleaseSRWLockExclusive(&record_trace_lock); +} + +// (a) list_execute_indirect, after indirect_execute: the call's record at record time. +void record_trace_indirect(Wrapper* self, UINT type, UINT stride, UINT max_count, Wrapper* arguments, u64 offset) +{ + if (!trace_frame_active || !record_trace_on()) return; + const bool dispatch_noted = record_trace_dispatch_noted; + record_trace_dispatch_noted = false; + TracedRecord t; + t.seq = InterlockedIncrement(&record_trace_seq); + t.type = type, t.stride = stride, t.max_count = max_count, t.list = self, t.wrapper = arguments, t.offset = offset; + const Pass& pass = pass_of(self); + t.dsv = pass.dsv_resource; + t.key = type == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH ? mesh_trace_key + : type == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH ? compute_key_of(self) + : 0; + t.base = arguments && arguments->own().kind == resource_kind ? static_cast(arguments->own().title_memory) : nullptr; + const UINT words = stride / 4 < 4 ? stride / 4 : 4; + if (t.base && words && x2w_local::readable(t.base + offset, words * 4)) { + t.words = words; + std::memcpy(t.at_record, t.base + offset, words * 4); + } + // An indirect Dispatch that never reached execute_dispatch (refused before staging) still gets its cx-uav line. + if (type == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH && !dispatch_noted) { + IndirectPending* const saved = indirect_current; + IndirectPending marker{}; + indirect_current = ▮ // only read as "indirect" by record_trace_dispatch + record_trace_dispatch(self, t.key, 0, 0, 0, false, co_not_run); + record_trace_dispatch_noted = false; + indirect_current = saved; + } + AcquireSRWLockExclusive(&record_trace_lock); + traced_records().push_back(t); + ReleaseSRWLockExclusive(&record_trace_lock); +} + +// (b) + writers. queue: wait for its work first (the busy-frame end); null: read at once (no GPU wait). +void record_trace_report(ID3D12CommandQueue* queue) +{ + if (!record_trace_on()) return; + AcquireSRWLockExclusive(&record_trace_lock); + std::vector records; + std::vector ranges; + std::vector mesh_reads; + records.swap(traced_records()); + ranges.swap(traced_ranges()); + mesh_reads.swap(traced_mesh_reads()); + traced_image_writers().clear(); + traced_tsharp_bases().clear(); + ReleaseSRWLockExclusive(&record_trace_lock); + InterlockedExchange(&record_trace_seq, 0); + InterlockedExchange(&dispatch_trace_seq, 0); + InterlockedExchange(&record_trace_order, 0); + if (records.empty() && ranges.empty() && mesh_reads.empty()) return; + const char* when = "no GPU wait"; + if (queue && the_device) { + ID3D12Fence* fence = nullptr; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (event && SUCCEEDED(device_of(the_device)->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))) && + SUCCEEDED(queue->Signal(fence, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, event))) + when = WaitForSingleObject(event, 5000) == WAIT_OBJECT_0 ? "after GPU wait on the presenting queue" : "GPU wait timed out"; + if (fence) fence->Release(); + if (event) CloseHandle(event); + } + struct Total { LONG calls = 0, x_record = 0, x_end = 0, unreadable = 0; }; + std::map, Total> totals; + std::map> by_buffer; + std::vector end_x(records.size()); + for (std::size_t i = 0; i < records.size(); ++i) { + const TracedRecord& t = records[i]; + std::uint32_t at_end[4] = {}; + const bool readable = t.words && x2w_local::readable(t.base + t.offset, t.words * 4); + if (readable) std::memcpy(at_end, t.base + t.offset, t.words * 4); + end_x[i] = at_end[0]; + Total& total = totals[{t.type, t.dsv}]; + ++total.calls; + if (!readable) ++total.unreadable; + if (readable && t.at_record[0]) ++total.x_record; + if (readable && at_end[0]) ++total.x_end; + if (t.base) by_buffer[t.base].push_back(i); + log("x2w-frame record #%ld type %u key %016llx list %p dsv %p args %p+0x%llx (wrapper %p, stride %u, max %u): at record %08x %08x %08x %08x, " + "at end %08x %08x %08x %08x%s", + t.seq, t.type, static_cast(t.key), t.list, t.dsv, static_cast(t.base), + static_cast(t.offset), t.wrapper, t.stride, t.max_count, t.at_record[0], t.at_record[1], t.at_record[2], + t.at_record[3], at_end[0], at_end[1], at_end[2], at_end[3], readable ? "" : " (unreadable)"); + } + for (const auto& [k, total] : totals) + log("x2w-frame record totals type %u dsv %p: calls %ld, X > 0 at record %ld, at end %ld, unreadable %ld (end read %s)", k.first, k.second, + total.calls, total.x_record, total.x_end, total.unreadable, when); + // Writers: per argument buffer, the dispatch ranges that cover at least one of its records. + for (const auto& [base, indices] : by_buffer) { + struct Writer { u64 key; const void* pipeline; char label; int param, offset; u64 lo, hi; const char* state; LONG dispatches = 0, first = 0; std::size_t covered = 0; }; + std::vector writers; + for (const TracedRange& r : ranges) { + std::size_t covered = 0; + for (const std::size_t i : indices) { + const u64 at = reinterpret_cast(base) + records[i].offset; + if (at >= r.lo && at + 4 <= r.hi) ++covered; + } + if (!covered) continue; + Writer* w = nullptr; + for (Writer& existing : writers) + if (existing.key == r.key && existing.pipeline == r.pipeline && existing.label == r.label && existing.param == r.param && existing.offset == r.offset && + existing.lo == r.lo && existing.hi == r.hi && std::strcmp(existing.state, r.state) == 0) + w = &existing; + if (!w) { + writers.push_back({r.key, r.pipeline, r.label, r.param, r.offset, r.lo, r.hi, r.state, 0, r.seq, 0}); + w = &writers.back(); + } + ++w->dispatches; + if (covered > w->covered) w->covered = covered; + } + std::size_t x_end = 0; + for (const std::size_t i : indices) x_end += end_x[i] != 0; + log("x2w-frame record writers args %p: %zu records (X > 0 at end %zu), %zu covering dispatch ranges%s", static_cast(base), + indices.size(), x_end, writers.size(), writers.empty() ? " (none of this frame's dispatches binds it)" : ""); + for (std::size_t n = 0; n < writers.size() && n < 32; ++n) { + const Writer& w = writers[n]; + log("x2w-frame record writers args %p: key %016llx pipeline %p %c p%d+0x%x 0x%llx %llu bytes, %s, %ld dispatches (first #%ld), covers %zu records", + static_cast(base), static_cast(w.key), w.pipeline, w.label, w.param, w.offset, + static_cast(w.lo), static_cast(w.hi - w.lo), w.state, w.dispatches, w.first, w.covered); + } + if (writers.size() > 32) log("x2w-frame record writers args %p: %zu more not shown", static_cast(base), writers.size() - 32); + } + // (f) mesh reads: per distinct (key, kind, slot, range), the dispatch ranges of the frame that overlap it. + struct Read { TracedMeshRead r; LONG calls = 0, first_order = 0; }; + std::vector distinct; + for (const TracedMeshRead& m : mesh_reads) { + Read* d = nullptr; + for (Read& e : distinct) + if (e.r.key == m.key && e.r.kind == m.kind && e.r.slot == m.slot && e.r.lo == m.lo && e.r.hi == m.hi) d = &e; + if (!d) { + distinct.push_back({m, 0, m.order}); + d = &distinct.back(); + } + ++d->calls; + } + std::size_t in_skipped = 0, in_run_only = 0, in_none = 0, shown = 0, in_skipped_entry = 0; + std::vector later; // lines without a skipped overlap, shown after the ones with + // Reverse view: per skipped dispatch range, the mesh reads that overlap it (not capped by the per-read lines). + struct ByRange { const TracedRange* r; LONG dispatches = 0; std::size_t reads = 0; LONG calls = 0; u64 keys[4] = {}; unsigned nkeys = 0; u64 overlap = 0; }; + std::vector by_range; + // Skipped ranges that overlap any mesh read, merged per (key, label, param, offset, range); dispatches = how many + // skipped dispatches bound that same range. + for (const TracedRange& r : ranges) { + if (r.executed) continue; + bool overlaps = false; + for (const Read& d : distinct) overlaps |= !(r.hi <= d.r.lo || r.lo >= d.r.hi); + if (!overlaps) continue; + ByRange* b = nullptr; + for (ByRange& e : by_range) + if (e.r->key == r.key && e.r->label == r.label && e.r->param == r.param && e.r->offset == r.offset && e.r->lo == r.lo && e.r->hi == r.hi) b = &e; + if (!b) { + by_range.push_back({&r}); + b = &by_range.back(); + } + ++b->dispatches; + } + for (const Read& d : distinct) { + bool entry_hit = false; + for (const ByRange& b : by_range) entry_hit |= b.r->label != 'R' && !(b.r->hi <= d.r.lo || b.r->lo >= d.r.hi); + in_skipped_entry += entry_hit; + } + // Reads and calls per range. + for (ByRange& b : by_range) { + for (const Read& d : distinct) { + if (b.r->hi <= d.r.lo || b.r->lo >= d.r.hi) continue; + ++b.reads; + b.calls += d.calls; + const u64 lo = b.r->lo > d.r.lo ? b.r->lo : d.r.lo, hi = b.r->hi < d.r.hi ? b.r->hi : d.r.hi; + b.overlap += hi - lo; + bool known = false; + for (unsigned k = 0; k < b.nkeys; ++k) known |= b.keys[k] == d.r.key; + if (!known && b.nkeys < 4) b.keys[b.nkeys++] = d.r.key; + } + } + std::stable_sort(by_range.begin(), by_range.end(), [](const ByRange& x, const ByRange& y) { return x.r->label != 'R' && y.r->label == 'R'; }); + for (const Read& d : distinct) { + // Overlapping dispatch ranges, merged per (key, label, param, offset, range, state): skipped first. + struct Hit { const TracedRange* r; LONG dispatches; bool before; }; + std::vector hits; + bool skipped = false; + for (const TracedRange& r : ranges) { + if (r.hi <= d.r.lo || r.lo >= d.r.hi) continue; + Hit* h = nullptr; + for (Hit& e : hits) + if (e.r->key == r.key && e.r->label == r.label && e.r->param == r.param && e.r->offset == r.offset && e.r->lo == r.lo && e.r->hi == r.hi && + e.r->executed == r.executed) + h = &e; + if (!h) { + hits.push_back({&r, 0, false}); + h = &hits.back(); + } + ++h->dispatches; + h->before |= r.order < d.first_order; + skipped |= !r.executed; + } + std::stable_sort(hits.begin(), hits.end(), [](const Hit& x, const Hit& y) { return !x.r->executed && y.r->executed; }); + if (skipped) ++in_skipped; + else if (!hits.empty()) ++in_run_only; + else ++in_none; + char text[1400]; + int n = std::snprintf(text, sizeof(text), "x2w-frame mesh-read key %016llx %c%d", static_cast(d.r.key), d.r.kind, d.r.slot); + if (d.r.kind == 'S') n += std::snprintf(text + n, sizeof(text) - n, " (source %d %d+0x%x)", d.r.source, d.r.a, d.r.b); + else n += std::snprintf(text + n, sizeof(text) - n, " (heap index %d, root constant p%d w%d)", d.r.slot, d.r.a, d.r.b); + n += std::snprintf(text + n, sizeof(text) - n, " 0x%llx %llu bytes, %ld calls: %s", static_cast(d.r.lo), + static_cast(d.r.hi - d.r.lo), d.calls, + skipped ? "INSIDE a skipped dispatch's range" : hits.empty() ? "no dispatch of this frame binds it" : "run dispatches only"); + for (std::size_t k = 0; k < hits.size() && k < 6 && n < static_cast(sizeof(text)) - 200; ++k) { + const TracedRange& r = *hits[k].r; + const u64 lo = r.lo > d.r.lo ? r.lo : d.r.lo, hi = r.hi < d.r.hi ? r.hi : d.r.hi; + n += std::snprintf(text + n, sizeof(text) - n, "; key %016llx %c p%d+0x%x 0x%llx %llu bytes, %s, %ld dispatches (first #%ld)%s, overlap %llu bytes", + static_cast(r.key), r.label, r.param, r.offset, static_cast(r.lo), + static_cast(r.hi - r.lo), r.state, hits[k].dispatches, r.seq, + hits[k].before ? " recorded before the first read" : " recorded after the first read", + static_cast(hi - lo)); + } + if (hits.size() > 6) std::snprintf(text + n, sizeof(text) - n, "; %zu more", hits.size() - 6); + if (skipped && shown < 64) { + log("%s", text); + ++shown; + } else if (!skipped && later.size() < 64) { + later.push_back(text); + } + } + for (std::size_t k = 0; k < later.size() && shown < 64; ++k, ++shown) log("%s", later[k].c_str()); + // The reverse view, table / heap entries first, then root windows (R: a readable window, not a size). + for (std::size_t k = 0; k < by_range.size() && k < 256; ++k) { + const ByRange& b = by_range[k]; + char keys[96] = ""; + int n = 0; + for (unsigned j = 0; j < b.nkeys; ++j) n += std::snprintf(keys + n, sizeof(keys) - n, "%s%016llx", j ? " " : "", static_cast(b.keys[j])); + log("x2w-frame mesh-read by-range key %016llx %c p%d+0x%x 0x%llx %llu bytes, %s, %ld dispatches (first #%ld)%s: %zu distinct mesh reads, %ld calls, " + "overlap %llu bytes, mesh keys %s%s", + static_cast(b.r->key), b.r->label, b.r->param, b.r->offset, static_cast(b.r->lo), + static_cast(b.r->hi - b.r->lo), b.r->state, b.dispatches, b.r->seq, b.r->label == 'R' ? " (root window)" : "", b.reads, + b.calls, static_cast(b.overlap), keys, b.nkeys == 4 ? " ..." : ""); + } + if (by_range.size() > 256) log("x2w-frame mesh-read by-range: %zu more not shown", by_range.size() - 256); + if (!mesh_reads.empty()) + log("x2w-frame mesh-read totals: %zu reads, %zu distinct ranges: %zu inside a skipped dispatch's range (%zu inside a skipped table / heap entry, " + "%zu only inside a skipped root window), %zu run dispatches only, %zu bound by no dispatch of this frame (%zu lines shown, %zu skipped ranges hit)", + mesh_reads.size(), distinct.size(), in_skipped, in_skipped_entry, in_skipped - in_skipped_entry, in_run_only, in_none, shown, by_range.size()); +} +extern "C" __declspec(dllexport) void x2w_d3d12_record_trace_report() { record_trace_report(nullptr); } // fixtures, after their fence diff --git a/src/startup_stubs/d3d12_regblob.inl b/src/startup_stubs/d3d12_regblob.inl new file mode 100644 index 0000000000..9cda0da28c --- /dev/null +++ b/src/startup_stubs/d3d12_regblob.inl @@ -0,0 +1,520 @@ + +namespace regblob { +constexpr std::size_t record_bytes = 0x160, desc_bytes = 0x300; +constexpr int record_words = static_cast(record_bytes / 8); +constexpr std::size_t blob_cap = 1u << 20; +constexpr std::uint32_t states_magic = 0x53573258; // "X2WS" +constexpr std::size_t table_cap = 1u << 18; + +struct Pair { + int word; + const unsigned char* data; + std::size_t bytes; +}; +struct Blob { + int word; + std::vector bytes; +}; +enum class Kind { set, generic_set, states, derived }; +struct Job { + Kind kind; + u64 key; + std::uint32_t hash = 0; // states: state hash + std::vector blobs; // set: every pair except code; generic: every pair; states: 1, 3, 7, 11 + std::vector record, desc, a, b, root; // sets; derived: record = raw patches + std::vector patch_hashes; // derived + bool generic_base = false; // derived: the base key is a g57 key + std::size_t bytes() const + { + std::size_t n = record.size() + desc.size() + a.size() + b.size() + root.size(); + for (const Blob& blob : blobs) n += blob.bytes.size(); + return n; + } +}; + +SRWLOCK queue_lock = SRWLOCK_INIT; +CONDITION_VARIABLE queue_ready = CONDITION_VARIABLE_INIT; +std::vector& queue() { static std::vector q; return q; } +LONG64 bytes_queued, bytes_pending; +LONG sets_written, generic_written, requests_written, states_appended, derived_lines, patch_files, failures; +LONG dropped_backlog, dropped_total, sets_dropped, table_full, queued_jobs; + +// A pointer/length pair at odd word i: pointer 4-aligned in the user range, length 4..cap, readable. +bool pair_at(const u64* w, int i, Pair& out) +{ + const u64 p = w[i], bytes = w[i + 1]; + if (p < 0x10000 || p > 0x00007FFFFFFEFFFFull || (p & 3) || bytes < 4 || bytes > blob_cap) return false; + if (readable_window(p, static_cast(bytes)) < bytes) return false; + out = {i, reinterpret_cast(p), static_cast(bytes)}; + return true; +} + +std::vector bytes_of(const void* data, std::size_t bytes) +{ + const auto* p = static_cast(data); + return std::vector(p, p + bytes); +} + +// \regblob\ +bool sub_path(wchar_t* out, const wchar_t* name) +{ + wchar_t dir[MAX_PATH]; + const DWORD n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); + if (!n || n >= MAX_PATH - 64) return false; + return swprintf(out, MAX_PATH, L"%s\\regblob\\%s", dir, name) > 0; +} + +bool exists(const wchar_t* path) { return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; } + +bool write_whole(const wchar_t* path, const void* data, std::size_t bytes) +{ + wchar_t temporary[MAX_PATH]; + if (swprintf(temporary, MAX_PATH, L"%s.%lu.%lu.tmp", path, GetCurrentProcessId(), GetCurrentThreadId()) < 0) return false; + HANDLE file = CreateFileW(temporary, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + DWORD written = 0; + const bool complete = WriteFile(file, data, static_cast(bytes), &written, nullptr) && written == bytes; + CloseHandle(file); + if (complete && MoveFileExW(temporary, path, MOVEFILE_REPLACE_EXISTING)) return true; + DeleteFileW(temporary); + return false; +} + +// An appended file: read it whole (for its existing entries), cut it back to valid_end(bytes) once, then +// append. Only the worker thread calls these. +std::vector read_all(const wchar_t* path) +{ + std::vector out; + HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) return out; + LARGE_INTEGER size{}; + if (GetFileSizeEx(file, &size) && size.QuadPart > 0 && size.QuadPart < (LONGLONG{64} << 20)) { + out.resize(static_cast(size.QuadPart)); + DWORD got = 0; + if (!ReadFile(file, out.data(), static_cast(out.size()), &got, nullptr) || got != out.size()) out.clear(); + } + CloseHandle(file); + return out; +} +void cut_to(const wchar_t* path, std::size_t bytes) +{ + HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) return; + LARGE_INTEGER at{}; + at.QuadPart = static_cast(bytes); + if (SetFilePointerEx(file, at, nullptr, FILE_BEGIN)) SetEndOfFile(file); + CloseHandle(file); +} +bool append(const wchar_t* path, const void* data, std::size_t bytes) +{ + HANDLE file = CreateFileW(path, FILE_APPEND_DATA, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + DWORD written = 0; + const bool complete = WriteFile(file, data, static_cast(bytes), &written, nullptr) && written == bytes; + CloseHandle(file); + return complete; +} + +void put_u32(std::vector& out, std::uint32_t v) +{ + out.insert(out.end(), reinterpret_cast(&v), reinterpret_cast(&v) + 4); +} + +const wchar_t* blob_name(int word, wchar_t* out, std::size_t size) +{ + if (word == 1) return L"vsregs"; + if (word == 3) return L"psregs"; + if (word == 7) return L"r78"; + swprintf(out, size, L"p%d", word); + return out; +} + +void write_set(const Job& job) +{ + wchar_t path[MAX_PATH], name[64], part[16]; + bool ok = true; + const bool generic = job.kind == Kind::generic_set; + if (generic) { + swprintf(name, std::size(name), L"g57_%016llx.rec", job.key); + if (!sub_path(path, name)) return; + if (exists(path)) { + swprintf(name, std::size(name), L"g57_%016llx.root", job.key); + if (sub_path(path, name) && !exists(path) && !write_whole(path, job.root.data(), job.root.size())) + InterlockedIncrement(&failures); + return; + } + } else if (!cache_path(path, L"req_", job.key, L".rec")) { + return; + } + const bool blobs = generic || !exists(path); + if (blobs) { + swprintf(name, std::size(name), L"%ls%016llx.desc", generic ? L"g57_" : L"", job.key); + ok = sub_path(path, name) && write_whole(path, job.desc.data(), job.desc.size()) && ok; + for (const Blob& blob : job.blobs) { + const wchar_t* ext = blob_name(blob.word, part, std::size(part)); + const bool in_cache = !generic && (blob.word == 1 || blob.word == 3 || blob.word == 7); + if (in_cache) { + swprintf(name, std::size(name), L".%ls", ext); + ok = cache_path(path, L"req_", job.key, name) && write_whole(path, blob.bytes.data(), blob.bytes.size()) && ok; + } else { + swprintf(name, std::size(name), L"%ls%016llx.%ls", generic ? L"g57_" : L"", job.key, ext); + ok = sub_path(path, name) && write_whole(path, blob.bytes.data(), blob.bytes.size()) && ok; + } + } + if (generic) { + // The root blob hashed into ck: mesh pipelines (code at [13]) need it to be translated. + swprintf(name, std::size(name), L"g57_%016llx.root", job.key); + ok = sub_path(path, name) && write_whole(path, job.root.data(), job.root.size()) && ok; + swprintf(name, std::size(name), L"g57_%016llx.rec", job.key); + ok = ok && sub_path(path, name) && write_whole(path, job.record.data(), job.record.size()); + } else { + ok = ok && cache_path(path, L"req_", job.key, L".rec") && write_whole(path, job.record.data(), job.record.size()); + } + if (ok) InterlockedIncrement(generic ? &generic_written : &sets_written); + } + // The request, in cached_translation's order (.a last); never replaced. Not after a failed set. + if (!generic && ok && !job.a.empty()) { + const struct { const wchar_t* ext; const std::vector* bytes; } parts[] = { + {L".b", &job.b}, {L".root", &job.root}, {L".a", &job.a}}; + for (const auto& p : parts) { + if (!cache_path(path, L"req_", job.key, p.ext)) { ok = false; break; } + if (exists(path)) continue; + if (!write_whole(path, p.bytes->data(), p.bytes->size())) { ok = false; break; } + if (p.ext[1] == L'a') InterlockedIncrement(&requests_written); + } + } + if (!ok) InterlockedIncrement(&failures); + static LONG logged; + if (blobs && ok && first_calls(logged, 8)) + log("x2w-regblob wrote %ls%016llx (%zu blobs)", generic ? L"regblob\\g57_" : L"req_", job.key, job.blobs.size()); +} + +// Valid prefix of a .states file; collects the state hashes in it. +std::size_t states_valid(const std::vector& f, std::unordered_set& seen) +{ + std::size_t at = 0; + while (at + 16 <= f.size()) { + std::uint32_t magic, bytes, hash; + std::memcpy(&magic, &f[at], 4); + std::memcpy(&bytes, &f[at + 4], 4); + std::memcpy(&hash, &f[at + 8], 4); + if (magic != states_magic || bytes < 8 || bytes > f.size() - at - 8) break; + seen.insert(hash); + at += 8 + bytes; + } + return at; +} + +void append_states(const Job& job) +{ + static std::unordered_map> known; // worker thread only + wchar_t path[MAX_PATH], name[64]; + swprintf(name, std::size(name), L"%016llx.states", job.key); + if (!sub_path(path, name)) return; + auto found = known.find(job.key); + if (found == known.end()) { + found = known.emplace(job.key, std::unordered_set{}).first; + const std::vector f = read_all(path); + const std::size_t valid = states_valid(f, found->second); + if (valid < f.size()) cut_to(path, valid); + } + if (!found->second.insert(job.hash).second) return; + std::vector out; + put_u32(out, states_magic); + put_u32(out, 0); + put_u32(out, job.hash); + put_u32(out, static_cast(job.blobs.size())); + for (const Blob& blob : job.blobs) { + put_u32(out, static_cast(blob.word)); + put_u32(out, static_cast(blob.bytes.size())); + out.insert(out.end(), blob.bytes.begin(), blob.bytes.end()); + } + const std::uint32_t after = static_cast(out.size() - 8); + std::memcpy(&out[4], &after, 4); + if (append(path, out.data(), out.size())) InterlockedIncrement(&states_appended); + else InterlockedIncrement(&failures); +} + +void append_derived(const Job& job) +{ + static bool loaded = false; // worker thread only + static std::unordered_set lines; + static std::unordered_set records; + wchar_t path[MAX_PATH], name[64]; + if (!sub_path(path, L"d55.txt")) return; + if (!loaded) { + loaded = true; + const std::vector f = read_all(path); + std::size_t start = 0, valid = 0; + for (std::size_t i = 0; i < f.size(); ++i) + if (f[i] == '\n') { + lines.emplace(reinterpret_cast(f.data()) + start, i - start); + start = valid = i + 1; + } + if (valid < f.size()) cut_to(path, valid); + } + char line[64 + 9 * 64]; + int n = std::snprintf(line, sizeof(line), "%s%016llx %zu", job.generic_base ? "g57_" : "", job.key, job.patch_hashes.size()); + for (std::size_t i = 0; i < job.patch_hashes.size() && n < static_cast(sizeof(line)) - 12; ++i) + n += std::snprintf(line + n, sizeof(line) - n, " %08x", job.patch_hashes[i]); + if (!lines.emplace(line, static_cast(n)).second) return; + constexpr std::size_t record = x2w_derived_blend::record_size; + bool ok = true; + for (std::size_t i = 0; i < job.patch_hashes.size() && (i + 1) * record <= job.record.size(); ++i) { + if (records.count(job.patch_hashes[i])) continue; + swprintf(name, std::size(name), L"d55_%08x.bin", job.patch_hashes[i]); + wchar_t file[MAX_PATH]; + if (!sub_path(file, name)) { ok = false; break; } + if (!exists(file)) { + if (!write_whole(file, job.record.data() + i * record, record)) { ok = false; break; } + InterlockedIncrement(&patch_files); + } + records.insert(job.patch_hashes[i]); + } + line[n++] = '\n'; + // One handle for the run: thousands of lines, and every open is a traced file call under the debugger. + static HANDLE out = INVALID_HANDLE_VALUE; + if (out == INVALID_HANDLE_VALUE) + out = CreateFileW(path, FILE_APPEND_DATA, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + DWORD written = 0; + if (ok && out != INVALID_HANDLE_VALUE && WriteFile(out, line, static_cast(n), &written, nullptr) && + written == static_cast(n)) + InterlockedIncrement(&derived_lines); + else + InterlockedIncrement(&failures); +} + +DWORD __stdcall worker(void*) +{ + wchar_t dir[MAX_PATH]; + if (sub_path(dir, L"")) CreateDirectoryW(dir, nullptr); + std::vector batch; + for (;;) { + AcquireSRWLockExclusive(&queue_lock); + while (queue().empty()) SleepConditionVariableSRW(&queue_ready, &queue_lock, INFINITE, 0); + batch.swap(queue()); + ReleaseSRWLockExclusive(&queue_lock); + for (const Job& job : batch) { + switch (job.kind) { + case Kind::set: case Kind::generic_set: write_set(job); break; + case Kind::states: append_states(job); break; + case Kind::derived: append_derived(job); break; + } + InterlockedAdd64(&bytes_pending, -static_cast(job.bytes())); + } + batch.clear(); + } +} + +void push(Job&& job) +{ + static const LONG64 cap = [] { + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_REGBLOB_MAX_MB", value, sizeof(value)); + const long mb = n && n < sizeof(value) ? std::strtol(value, nullptr, 10) : 512; + return LONG64{mb > 0 ? mb : 512} << 20; + }(); + const bool set = job.kind == Kind::set || job.kind == Kind::generic_set; + const LONG64 bytes = static_cast(job.bytes()); + // Only state and patch records drop while the writer is behind; a key's first set waits its turn. + if (InterlockedAdd64(&bytes_pending, bytes) > (LONG64{16} << 20) && !set) { + InterlockedAdd64(&bytes_pending, -bytes); + InterlockedIncrement(&dropped_backlog); + return; + } + if (InterlockedAdd64(&bytes_queued, bytes) > cap) { + InterlockedAdd64(&bytes_queued, -bytes); + InterlockedAdd64(&bytes_pending, -bytes); + InterlockedIncrement(&dropped_total); + if (set) InterlockedIncrement(&sets_dropped); + return; + } + static const bool started = [] { + HANDLE thread = CreateThread(nullptr, 0, worker, nullptr, 0, nullptr); + if (thread) CloseHandle(thread); + return thread != nullptr; + }(); + if (!started) { + InterlockedAdd64(&bytes_pending, -bytes); + return; + } + InterlockedIncrement(&queued_jobs); + AcquireSRWLockExclusive(&queue_lock); + queue().push_back(std::move(job)); + ReleaseSRWLockExclusive(&queue_lock); + WakeConditionVariable(&queue_ready); +} + +SRWLOCK key_lock = SRWLOCK_INIT; +// Slot-57 pipeline wrapper -> its key and whether it is a g57 key, for the derived pipelines built on it. +std::unordered_map>& keys_of() { static std::unordered_map> m; return m; } + +// Device slot 57, after note_pipeline. Returns the key (request key, or the g57 content key). +u64 dump57(const void* desc, const Wrapper* self) +{ + static const bool on = !x2w_local::env_on("X2W_REGBLOB_OFF"); + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_set keys, states; // handled this run + wchar_t probe[MAX_PATH]; + if (!on || !desc || !cache_path(probe, L"req_", 0, L"") || + readable_window(reinterpret_cast(desc), record_bytes) < record_bytes) return 0; + u64 w[record_words]; + std::memcpy(w, desc, sizeof(w)); + std::vector root_blob; + if (Wrapper* root = as_wrapper(reinterpret_cast(w[0]))) { + AcquireSRWLockShared(¬e_lock); + const auto found = root_blobs().find(root); + if (found != root_blobs().end()) root_blob = found->second; + ReleaseSRWLockShared(¬e_lock); + } + // The same conditions as translation_for, so the key is the request key. + const auto* a = reinterpret_cast(w[5]); + const auto* b = reinterpret_cast(w[9]); + const std::size_t a_bytes = static_cast(w[6]), b_bytes = static_cast(w[10]); + const bool keyed = !root_blob.empty() && a_bytes && b_bytes && a_bytes <= (1u << 20) && b_bytes <= (1u << 20) && + x2w_local::readable(a, a_bytes) && x2w_local::readable(b, b_bytes); + u64 key = 0, state = 1469598103934665603ull; + if (keyed) { + key = pipeline_key(a, a_bytes, b, b_bytes, root_blob); + for (int i : {1, 3, 7, 11}) { + Pair p; + if (!pair_at(w, i, p)) continue; + state = fnv_bytes(&i, sizeof(i), state); + state = fnv_bytes(p.data, p.bytes, state); + } + } else { + constexpr char seed[] = "x2w-regblob-g57-1"; + key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(seed, sizeof(seed) - 1)); + int pairs = 0; + for (int i = 1; i + 1 < record_words; i += 2) { + Pair p; + if (!pair_at(w, i, p)) continue; + ++pairs; + key = fnv_bytes(&i, sizeof(i), key); + key = fnv_bytes(p.data, p.bytes, key); + } + if (!pairs) return 0; + } + const u64 state_id = fnv_bytes(&state, sizeof(state), key); + AcquireSRWLockExclusive(&lock); + const bool plain = keys.insert(keyed ? key : ~key).second; + bool variant = false; + if (keyed && states.size() < table_cap) variant = states.insert(state_id).second; + else if (keyed && !states.count(state_id)) InterlockedIncrement(&table_full); + ReleaseSRWLockExclusive(&lock); + AcquireSRWLockExclusive(&key_lock); + keys_of()[self] = {key, !keyed}; + ReleaseSRWLockExclusive(&key_lock); + if (plain) { + Job job{keyed ? Kind::set : Kind::generic_set, key}; + job.record = bytes_of(desc, record_bytes); + job.desc = bytes_of(desc, readable_window(reinterpret_cast(desc), desc_bytes)); + for (int i = 1; i + 1 < record_words; i += 2) { + Pair p; + if ((keyed && (i == 5 || i == 9)) || !pair_at(w, i, p)) continue; + job.blobs.push_back({i, bytes_of(p.data, p.bytes)}); + } + static const bool requests = !x2w_local::env_on("X2W_REGBLOB_REQUESTS_OFF"); + if (keyed && requests) { + job.a = bytes_of(a, a_bytes); + job.b = bytes_of(b, b_bytes); + job.root = root_blob; + } + if (!keyed) job.root = root_blob; // regblob\g57_.root + push(std::move(job)); + } + if (variant) { + Job job{Kind::states, key}; + job.hash = static_cast(state ^ (state >> 32)); + for (int i : {1, 3, 7, 11}) { + Pair p; + if (pair_at(w, i, p)) job.blobs.push_back({i, bytes_of(p.data, p.bytes)}); + } + push(std::move(job)); + } + return key; +} + +// Hash of one patch record without the bytes the title leaves as garbage: the padding after each blend +// target's write mask, and everything after the desc of a depth-stencil or rasterizer record. +std::uint32_t patch_hash(const unsigned char* record) +{ + constexpr std::size_t size = x2w_derived_blend::record_size; + unsigned char canonical[size]; + std::memcpy(canonical, record, size); + std::uint32_t kind; + std::memcpy(&kind, canonical, sizeof(kind)); + unsigned char* body = canonical + sizeof(kind); + if (kind == 2) { + for (int t = 0; t < 8; ++t) + std::memset(body + offsetof(D3D12_BLEND_DESC, RenderTarget) + t * sizeof(D3D12_RENDER_TARGET_BLEND_DESC) + + offsetof(D3D12_RENDER_TARGET_BLEND_DESC, RenderTargetWriteMask) + 1, 0, 3); + } else if (kind == 0 || kind == 1) { + const std::size_t used = kind == 0 ? sizeof(D3D12_DEPTH_STENCIL_DESC) : sizeof(D3D12_RASTERIZER_DESC); + std::memset(body + used, 0, size - sizeof(kind) - used); + if (kind == 0) std::memset(body + offsetof(D3D12_DEPTH_STENCIL_DESC, StencilWriteMask) + 1, 0, 2); + } + static_assert(sizeof(D3D12_RENDER_TARGET_BLEND_DESC) == offsetof(D3D12_RENDER_TARGET_BLEND_DESC, RenderTargetWriteMask) + 4); + static_assert(offsetof(D3D12_DEPTH_STENCIL_DESC, FrontFace) == offsetof(D3D12_DEPTH_STENCIL_DESC, StencilWriteMask) + 3); + static_assert(sizeof(D3D12_DEPTH_STENCIL_DESC) + sizeof(std::uint32_t) <= size); + static_assert(sizeof(D3D12_RASTERIZER_DESC) + sizeof(std::uint32_t) <= size); + const u64 h = fnv_bytes(canonical, size); + return static_cast(h ^ (h >> 32)); +} + +// Device slot 55 (CreateDerivedPipelineStateX), after note_pipeline: one d55.txt line per distinct +// (base key, patch set). The base is found through the slot-55 base chain (depth 8), as translation_for does. +void dump55(const void* base, const void* patches, std::size_t bytes) +{ + static const bool on = !x2w_local::env_on("X2W_REGBLOB_OFF"); + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_set seen; + constexpr std::size_t record = x2w_derived_blend::record_size; + wchar_t probe[MAX_PATH]; + if (!on || !patches || !bytes || bytes > 64 * record || bytes % record || !cache_path(probe, L"req_", 0, L"")) return; + const Wrapper* w = as_wrapper(base); + std::pair found{0, false}; + bool have = false; + for (int depth = 0; w && depth < 8 && !have; ++depth) { + AcquireSRWLockShared(&key_lock); + const auto it = keys_of().find(w); + if (it != keys_of().end()) found = it->second, have = true; + ReleaseSRWLockShared(&key_lock); + if (have) break; + const PipelineInfo* info = pipeline_info(w); + w = info && info->path == 55 ? info->base : nullptr; + } + if (!have) return; + Job job{Kind::derived, found.first}; + job.generic_base = found.second; + const auto* p = static_cast(patches); + u64 set = fnv_bytes(&found, sizeof(found.first)); + for (std::size_t at = 0; at < bytes; at += record) { + job.patch_hashes.push_back(patch_hash(p + at)); + set = fnv_bytes(&job.patch_hashes.back(), 4, set); + } + AcquireSRWLockExclusive(&lock); + bool fresh = false; + if (seen.size() < table_cap) fresh = seen.insert(set).second; + else if (!seen.count(set)) InterlockedIncrement(&table_full); + ReleaseSRWLockExclusive(&lock); + if (!fresh) return; + job.record = bytes_of(patches, bytes); + push(std::move(job)); +} + +// Every 300 frames in render mode (frame heartbeat). +void report() +{ + static const bool on = !x2w_local::env_on("X2W_REGBLOB_OFF"); + if (!on || !queued_jobs) return; + AcquireSRWLockShared(&queue_lock); + const std::size_t pending = queue().size(); + ReleaseSRWLockShared(&queue_lock); + log("x2w-regblob totals: queued %ld (%lld KiB), pending %zu (%lld KiB), sets %ld, unclassified %ld, requests %ld, " + "states %ld, derived lines %ld (patch files %ld), failed %ld; dropped: writer behind %ld, over %s cap %ld " + "(first sets %ld), table full %ld", queued_jobs, bytes_queued >> 10, pending, bytes_pending >> 10, sets_written, + generic_written, requests_written, states_appended, derived_lines, patch_files, failures, dropped_backlog, + "X2W_REGBLOB_MAX_MB", dropped_total, sets_dropped, table_full); +} +} // namespace regblob diff --git a/src/startup_stubs/d3d12_upload_ring.inl b/src/startup_stubs/d3d12_upload_ring.inl new file mode 100644 index 0000000000..60d8288218 --- /dev/null +++ b/src/startup_stubs/d3d12_upload_ring.inl @@ -0,0 +1,469 @@ +namespace { +struct RingTag { + UINT chunk = ~0u; + u64 generation = 0; +}; +struct RingChunk { + ID3D12Resource* buffer = nullptr; + unsigned char* mapped = nullptr; + u64 base = 0; // offset of this chunk inside buffer (legacy segments share one buffer) + u64 bytes = 0, used = 0; + u64 first_use = 0, last_use = 0; // sequence numbers + u64 generation = 1; + enum State { free_, in_use, fenced } state = free_; + bool unsafe = false; // legacy: reused before it was free + std::vector> waits; + LONG idle_since = 0; +}; +struct RingList { + u64 reset = 0, close = 0, executed = 0; +}; +struct UploadRing { + SRWLOCK lock = SRWLOCK_INIT; + // 0: the upload ring (mapped upload heap). 1: the indirect argument ring (d3d12_indirect.inl): default heap with + // unordered access, never mapped, written by GPU copies recorded on the list that reads it. + int which = 0; + u64 old_ring = 0; // size of the ring this replaces (would-have-wrapped) + bool ready = false, legacy = false; + u64 chunk_bytes = 0, cap_bytes = 0; + std::vector chunks; + UINT current = ~0u; + u64 seq = 0; + std::unordered_map lists; + // Counters (since the start; the report line also gives the change since the last line). + u64 reserved = 0, refused_cap = 0, refused_cap_bytes = 0, refused_size = 0, overwritten = 0, overwritten_uses = 0, + would_wrap = 0, reexecuted = 0, made = 0, released = 0, peak_in_use = 0, cache_stale = 0, draws_refused = 0, unfenced = 0, repinned = 0; + u64 last_reserved = 0; + LONG last_report_frame = 0; +}; +UploadRing& upload_ring_state() +{ + static UploadRing r; + return r; +} +UploadRing& indirect_ring_state() +{ + static UploadRing r = [] { + UploadRing made; + made.which = 1; + return made; + }(); + return r; +} +const char* ring_name(const UploadRing& r) { return r.which ? "indirect" : "upload"; } +// Cap refusals on this thread: draw_translated compares it before and after its copies and does not issue a draw +// whose copy was refused. +thread_local u64 ring_cap_refusals; +u64 ring_env(const char* name, u64 fallback) +{ + char value[24]{}; + const DWORD n = GetEnvironmentVariableA(name, value, sizeof(value)); + return n && n < sizeof(value) ? std::strtoull(value, nullptr, 0) : fallback; +} + +// r.lock held. Upload ring: a mapped upload buffer. Indirect ring (gpu): a default-heap buffer with unordered access +// (the argument guard rewrites records in place), resting in COMMON, not mapped. +bool ring_make_buffer(u64 bytes, bool gpu, ID3D12Resource** buffer, unsigned char** mapped) +{ + const D3D12_HEAP_PROPERTIES heap{gpu ? D3D12_HEAP_TYPE_DEFAULT : D3D12_HEAP_TYPE_UPLOAD}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (gpu) desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + ID3D12Resource* created = nullptr; + void* base = nullptr; + if (FAILED(device_of(the_device)->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, + gpu ? D3D12_RESOURCE_STATE_COMMON : D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&created)))) + return false; + if (!gpu && FAILED(created->Map(0, nullptr, &base))) { + created->Release(); + return false; + } + *buffer = created; + *mapped = static_cast(base); + return true; +} + +// r.lock held. Upload ring: X2W_UPLOAD_RING[=legacy], _CHUNK_MIB (64), _CAP_MIB (2048), old ring 256 MiB. +// Indirect ring: X2W_INDIRECT_RING[=legacy], _CHUNK_MIB (4), _CAP_MIB (256), old ring 16 MiB. +// Fixtures: X2W__RING_TEST_KIB (the old ring / a chunk in KiB), X2W__RING_TEST_CAP_CHUNKS. +void ring_setup(UploadRing& r) +{ + r.ready = true; + const bool gpu = r.which == 1; + const auto env = [&](const char* upload_name, const char* indirect_name, u64 fallback) { + return ring_env(gpu ? indirect_name : upload_name, fallback); + }; + char mode[16]{}; + GetEnvironmentVariableA(gpu ? "X2W_INDIRECT_RING" : "X2W_UPLOAD_RING", mode, sizeof(mode)); + r.legacy = !std::strcmp(mode, "legacy"); + const u64 test_kib = env("X2W_UPLOAD_RING_TEST_KIB", "X2W_INDIRECT_RING_TEST_KIB", 0); + r.old_ring = test_kib ? test_kib << 10 : (gpu ? u64{16} : u64{256}) << 20; + if (r.legacy) { + const u64 ring = r.old_ring; + ID3D12Resource* buffer = nullptr; + unsigned char* mapped = nullptr; + if (ring_make_buffer(ring, gpu, &buffer, &mapped)) { + for (UINT i = 0; i < 4; ++i) { + RingChunk c; + c.buffer = buffer; + c.mapped = mapped ? mapped + i * (ring / 4) : nullptr; + c.base = i * (ring / 4); + c.bytes = ring / 4; + r.chunks.push_back(c); + } + r.chunk_bytes = ring / 4; + } + r.cap_bytes = ring; + } else { + r.chunk_bytes = test_kib ? test_kib << 10 : env("X2W_UPLOAD_RING_CHUNK_MIB", "X2W_INDIRECT_RING_CHUNK_MIB", gpu ? 4 : 64) << 20; + r.cap_bytes = env("X2W_UPLOAD_RING_CAP_MIB", "X2W_INDIRECT_RING_CAP_MIB", gpu ? 256 : 2048) << 20; + if (const u64 cap_chunks = env("X2W_UPLOAD_RING_TEST_CAP_CHUNKS", "X2W_INDIRECT_RING_TEST_CAP_CHUNKS", 0)) + r.cap_bytes = cap_chunks * r.chunk_bytes; + if (r.cap_bytes < r.chunk_bytes) r.cap_bytes = r.chunk_bytes; + } + log("x2w-%s ring: %s, %llu KiB chunks, cap %llu MiB%s", ring_name(r), + r.legacy ? "legacy (one ring, wraps without a fence check; tracked as 4 segments)" + : "chain (a chunk is reused only after its lists executed and their fences passed)", + r.chunk_bytes >> 10, r.cap_bytes >> 20, r.legacy && r.chunks.empty() ? ": ring buffer FAILED" : ""); +} + +// r.lock held. Does a live list's current recording still hold chunk c (overlapped its use, not executed yet)? +bool ring_held_by_lists(const UploadRing& r, const RingChunk& c) +{ + for (const auto& [list, l] : r.lists) { + if (!l.reset || l.reset > c.last_use) continue; // never recorded, or re-recorded after the last use + if (l.close && l.close < c.first_use) continue; // closed before the chunk was first used + if (l.close && l.executed > l.close) continue; // that recording was executed + return true; + } + return false; +} + +// r.lock held. Moves chunks along in_use -> fenced -> free. +void ring_poll(UploadRing& r) +{ + std::vector> now; + bool now_taken = false, unfenced = false; + for (UINT i = 0; i < r.chunks.size(); ++i) { + RingChunk& c = r.chunks[i]; + if (c.state == RingChunk::in_use && i != r.current && !ring_held_by_lists(r, c)) { + if (!now_taken) { + AcquireSRWLockShared(&allocator_lock); + for (const auto& [queue, submit] : queue_submits) { + if (submit.first) now.push_back(submit); + else unfenced = true; // note_submits could not make this queue's fence: nothing to wait on + } + ReleaseSRWLockShared(&allocator_lock); + now_taken = true; + } + if (unfenced) { + ++r.unfenced; // kept in use: a queue without a submit fence cannot prove the GPU is done + continue; + } + c.waits = now; + c.state = RingChunk::fenced; + } + if (c.state == RingChunk::fenced) { + bool passed = true; + for (const auto& [fence, value] : c.waits) passed &= fence->GetCompletedValue() >= value; + if (passed) { + c.state = RingChunk::free_; + ++c.generation; // cached frame copies in it are gone + c.idle_since = frame_number; + } + } + } + // Chain: keep at most 4 free chunks (256 MiB at the default size); release the rest after 300 idle frames. + if (!r.legacy) { + UINT free_count = 0; + for (UINT i = 0; i < r.chunks.size(); ++i) { + RingChunk& c = r.chunks[i]; + if (c.state != RingChunk::free_ || !c.buffer) continue; + if (++free_count > 4 && frame_number - c.idle_since > 300) { + c.buffer->Release(); + c.buffer = nullptr; + c.mapped = nullptr; + ++r.released; + } + } + } +} + +// r.lock held. Bytes in chunks that are not free (in use or waiting for fences). +u64 ring_in_use(const UploadRing& r) +{ + u64 bytes = 0; + for (const RingChunk& c : r.chunks) + if (c.buffer && c.state != RingChunk::free_) bytes += c.bytes; + return bytes; +} + +// r.lock held. A chunk to write into next, or ~0u (chain at its cap). +UINT ring_next_chunk(UploadRing& r) +{ + if (r.legacy) { + if (r.chunks.empty()) return ~0u; + const UINT next = r.current == ~0u ? 0 : (r.current + 1) % 4; + RingChunk& c = r.chunks[next]; + if (c.state != RingChunk::free_) ring_poll(r); + c.unsafe = c.state != RingChunk::free_; // the old ring reuses it anyway: count what it overwrites + ++c.generation; + return next; + } + ring_poll(r); + for (UINT i = 0; i < r.chunks.size(); ++i) + if (r.chunks[i].state == RingChunk::free_ && r.chunks[i].buffer && i != r.current) return i; + u64 live = 0; + for (const RingChunk& c : r.chunks) live += c.buffer ? c.bytes : 0; + if (live + r.chunk_bytes > r.cap_bytes) return ~0u; + RingChunk c; + c.bytes = r.chunk_bytes; + if (!ring_make_buffer(c.bytes, r.which == 1, &c.buffer, &c.mapped)) return ~0u; + ++r.made; + for (UINT i = 0; i < r.chunks.size(); ++i) + if (!r.chunks[i].buffer) { // reuse a released slot (keeps its generation counting up) + c.generation = r.chunks[i].generation + 1; + r.chunks[i] = c; + return i; + } + r.chunks.push_back(c); + return static_cast(r.chunks.size() - 1); +} +} // namespace + +// A slice of `bytes` for copies the GPU reads from a list recorded now. Returns its CPU address and sets the +// buffer and offset to bind (and the tag frame_copy keeps), or nullptr when refused. +// Both rings: a slice of `bytes` rounded to `align`. Returns false when refused (size, or the cap: counted, logged). +bool ring_reserve(UploadRing& r, std::size_t bytes, u64 align, u64* offset, ID3D12Resource** buffer, unsigned char** cpu_out, RingTag* tag) +{ + const bool upload = r.which == 0; + AcquireSRWLockExclusive(&r.lock); + if (!r.ready) ring_setup(r); + const u64 rounded = (bytes + align - 1) & ~(align - 1); + if (!bytes || rounded > r.chunk_bytes || (r.legacy && r.chunks.empty())) { + ++r.refused_size; + ReleaseSRWLockExclusive(&r.lock); + if (upload) x2w_memcut::note_ring_refused(); + return false; + } + if (r.current == ~0u || r.chunks[r.current].used + rounded > r.chunks[r.current].bytes) { + const UINT next = ring_next_chunk(r); + if (next == ~0u) { + if (upload) ++ring_cap_refusals; // draw_translated: the draw is not issued + ++r.refused_cap; + r.refused_cap_bytes += rounded; + const u64 refused = r.refused_cap; + ReleaseSRWLockExclusive(&r.lock); + if (upload) x2w_memcut::note_ring_refused(); + if (refused <= 8 || refused % 4096 == 0) + log("x2w-%s ring: refused %zu bytes at frame %ld: the chain is at its cap (X2W_%s_RING_CAP_MIB) and no chunk is free " + "yet; %s (refusal %llu)", ring_name(r), bytes, frame_number, upload ? "UPLOAD" : "INDIRECT", + upload ? "the copy fails" : "the indirect call is skipped (no-ring)", refused); + return false; + } + r.current = next; + RingChunk& c = r.chunks[next]; + c.state = RingChunk::in_use; + c.used = 0; + c.first_use = ++r.seq; + c.waits.clear(); + } + RingChunk& c = r.chunks[r.current]; + const u64 at = c.used; + c.used += rounded; + c.last_use = ++r.seq; + r.reserved += rounded; + const bool first_overwrite = c.unsafe && !r.overwritten_uses; + if (c.unsafe) r.overwritten += rounded, ++r.overwritten_uses; + const u64 in_use = ring_in_use(r); + if (in_use > r.peak_in_use) r.peak_in_use = in_use; + // The old ring (its size, or the test size) would have handed out unread / unexecuted space here. + const bool first_wrap = !r.legacy && in_use > r.old_ring && !r.would_wrap; + if (!r.legacy && in_use > r.old_ring) r.would_wrap += rounded; + *offset = c.base + at; + *buffer = c.buffer; + if (tag) *tag = RingTag{r.current, c.generation}; + if (cpu_out) *cpu_out = c.mapped ? c.mapped + at : nullptr; + ReleaseSRWLockExclusive(&r.lock); + if (upload) x2w_memcut::note_ring(frame_number, rounded); + if (first_overwrite) + log(upload ? "x2w-upload ring (legacy): first copy written over ring data the GPU had not read yet (frame %ld, %zu bytes)" + : "x2w-indirect ring (legacy): first slot reused while a list holding it had not executed or its fence had not passed " + "(frame %ld, %zu bytes)", + frame_number, bytes); + if (first_wrap) + log("x2w-%s ring (chain): first %s past the old ring's size while all of it is still unread (frame %ld): the old ring " + "would have reused unread space here", ring_name(r), upload ? "copy" : "record", frame_number); + return true; +} + +unsigned char* reserve_upload_ring(std::size_t bytes, u64* offset, ID3D12Resource** buffer, RingTag* tag) +{ + unsigned char* cpu = nullptr; + // 512: texture footprints are placed in the ring too + return ring_reserve(upload_ring_state(), bytes, 512, offset, buffer, &cpu, tag) ? cpu : nullptr; +} + +// d3d12_indirect.inl: ring space for one call's record (+ count), in 256-byte slots. The chunk to copy into and to +// read the arguments from, or nullptr when refused (the call is skipped as no-ring). +ID3D12Resource* reserve_indirect_ring(u64 bytes, u64* offset) +{ + ID3D12Resource* buffer = nullptr; + return ring_reserve(indirect_ring_state(), static_cast(bytes), 256, offset, &buffer, nullptr, nullptr) ? buffer : nullptr; +} + +// frame_copy cache hit: the slice may be bound again only while its chunk was not recycled. Marks the use. +bool ring_touch(const RingTag& tag) +{ + UploadRing& r = upload_ring_state(); + AcquireSRWLockExclusive(&r.lock); + RingChunk* c = tag.chunk < r.chunks.size() ? &r.chunks[tag.chunk] : nullptr; + // Same generation = not recycled since the copy was made; a recycled chunk is free or in use again. + const bool same = c && c->buffer && c->generation == tag.generation && c->state != RingChunk::free_; + if (!same) ++r.cache_stale; + // Fixtures only: X2W_UPLOAD_RING_TEST_NO_REPIN=1 skips the re-pin (the negative control of the reuse case). + static const bool no_repin = ring_env("X2W_UPLOAD_RING_TEST_NO_REPIN", 0) != 0; + bool first_repin = false; + if (same) { + c->last_use = ++r.seq; + // A chunk waiting for its fences is pinned again: the list binding it now may not have executed yet, and the + // fence snapshot was taken before this use. The next poll checks it against the lists again. + if (c->state == RingChunk::fenced && !no_repin) { + c->state = RingChunk::in_use; + c->waits.clear(); + first_repin = !r.repinned++; + } + } + ReleaseSRWLockExclusive(&r.lock); + if (first_repin) + log("x2w-upload ring: first cached copy bound again from a chunk waiting for its fences (frame %ld): the chunk is in use " + "again until the list binding it has executed", frame_number); + return same || r.legacy; // legacy: as before, the cache trusts its offset (stale hits are only counted) +} + +// draw_translated: a draw not issued because one of its copies was refused at the cap. +void ring_draw_refused(u64 key) +{ + UploadRing& r = upload_ring_state(); + AcquireSRWLockExclusive(&r.lock); + const u64 n = ++r.draws_refused; + ReleaseSRWLockExclusive(&r.lock); + if (n <= 8 || n % 4096 == 0) + log("x2w-upload ring: draw %016llx not issued at frame %ld: a copy it needs was refused (chain at its cap); refused draws %llu", + key, frame_number, n); +} + +// Hooks: list Reset / Close succeeded, lists executed (draw_lock held, after note_submits), list destroyed. +// Each hook updates both rings (the upload ring and the indirect argument ring). +void ring_list_reset(Wrapper* list) +{ + for (UploadRing* r : {&upload_ring_state(), &indirect_ring_state()}) { + AcquireSRWLockExclusive(&r->lock); + RingList& l = r->lists[list]; + l.reset = ++r->seq; + l.close = 0; + ReleaseSRWLockExclusive(&r->lock); + } +} +void ring_list_close(Wrapper* list) +{ + for (UploadRing* r : {&upload_ring_state(), &indirect_ring_state()}) { + AcquireSRWLockExclusive(&r->lock); + if (const auto l = r->lists.find(list); l != r->lists.end()) l->second.close = ++r->seq; + ReleaseSRWLockExclusive(&r->lock); + } +} +void ring_list_gone(Wrapper* list) +{ + for (UploadRing* r : {&upload_ring_state(), &indirect_ring_state()}) { + AcquireSRWLockExclusive(&r->lock); + r->lists.erase(list); + ReleaseSRWLockExclusive(&r->lock); + } +} +void ring_submitted_one(UploadRing& r, const std::vector& lists); +void ring_submitted(const std::vector& lists) +{ + ring_submitted_one(upload_ring_state(), lists); + ring_submitted_one(indirect_ring_state(), lists); +} +void ring_submitted_one(UploadRing& r, const std::vector& lists) +{ + AcquireSRWLockExclusive(&r.lock); + for (Wrapper* w : lists) + if (const auto l = r.lists.find(w); l != r.lists.end()) { + if (l->second.executed > l->second.close && l->second.close) ++r.reexecuted; // the same recording again + l->second.executed = ++r.seq; + } + if (r.ready) ring_poll(r); + const LONG frame = frame_number; + const bool report = r.ready && frame - r.last_report_frame >= 300; + char line[1024]; + if (report) { + r.last_report_frame = frame; + UINT total = 0, in_use = 0, fenced = 0, free_count = 0; + u64 held = 0; + for (const RingChunk& c : r.chunks) { + if (!c.buffer) continue; + ++total; + in_use += c.state == RingChunk::in_use; + fenced += c.state == RingChunk::fenced; + free_count += c.state == RingChunk::free_; + held += c.state == RingChunk::in_use && ring_held_by_lists(r, c); + } + // Upload ring in MiB; the indirect ring (256-byte records) in KiB. + const int shift = r.which ? 10 : 20; + const char* unit = r.which ? "KiB" : "MiB"; + const u64 total_bytes = r.legacy ? (r.chunks.empty() ? 0 : 4 * r.chunk_bytes) : total * r.chunk_bytes; + std::snprintf(line, sizeof(line), + "x2w-%s ring (frame %ld, %s): chunks %u (%llu %s: in use %u, %llu of them held by unexecuted lists, waiting for " + "fences %u, free %u), peak in use %llu %s, reserved %llu %s since the last line (%llu %s total), refused at " + "the cap %llu (%llu %s, draws not issued %llu), refused over the chunk size %llu, %s %llu %s in %llu " + "uses, would have wrapped in the old ring %llu %s, re-executed recordings %llu, stale cache hits %llu, chunks " + "made %llu released %llu, lists %zu, kept for a queue without a fence %llu", + ring_name(r), frame, r.legacy ? "legacy" : "chain", total, total_bytes >> shift, unit, in_use, held, fenced, free_count, + r.peak_in_use >> shift, unit, (r.reserved - r.last_reserved) >> shift, unit, r.reserved >> shift, unit, r.refused_cap, + r.refused_cap_bytes >> shift, unit, r.draws_refused, r.refused_size, + r.which ? "slots reused while a list holding them had not executed" : "written over data the GPU had not read", + r.overwritten >> shift, unit, r.overwritten_uses, r.would_wrap >> shift, unit, r.reexecuted, r.cache_stale, r.made, + r.released, r.lists.size(), r.unfenced); + r.last_reserved = r.reserved; + } + ReleaseSRWLockExclusive(&r.lock); + static LONG reports[2]; + if (report && first_calls(reports[r.which], 400)) log("%s", line); +} + +// Fixtures (export x2w_upload_ring_test, after the file's namespace): counters by index (0 reserved, 1 refused at +// the cap, 2 overwritten bytes, 3 would-wrap bytes, 4 chunks with a buffer, 5 stale cache hits, 6 legacy, 7 draws +// not issued, 8 chunks made, 9 fenced chunks re-pinned by a cache hit). 100 + index: the same for the indirect ring +// (2 = slot bytes reused while a list holding them had not executed, in legacy mode). +unsigned long long upload_ring_counter(int what) +{ + UploadRing& r = what >= 100 ? indirect_ring_state() : upload_ring_state(); + if (what >= 100) what -= 100; + AcquireSRWLockShared(&r.lock); + u64 v = 0; + switch (what) { + case 0: v = r.reserved; break; + case 1: v = r.refused_cap; break; + case 2: v = r.overwritten; break; + case 3: v = r.would_wrap; break; + case 4: for (const RingChunk& c : r.chunks) v += c.buffer != nullptr; break; + case 5: v = r.cache_stale; break; + case 6: v = r.legacy; break; + case 7: v = r.draws_refused; break; + case 8: v = r.made; break; + case 9: v = r.repinned; break; + default: break; + } + ReleaseSRWLockShared(&r.lock); + return v; +} diff --git a/src/startup_stubs/d3d12_vdesc.inl b/src/startup_stubs/d3d12_vdesc.inl new file mode 100644 index 0000000000..31e218febc --- /dev/null +++ b/src/startup_stubs/d3d12_vdesc.inl @@ -0,0 +1,56 @@ + +ID3D12Resource* vdesc_buffer; +std::uint32_t* vdesc_words; +LONG vdesc_image, vdesc_buffer_views, vdesc_none; // ids filled, by kind (totals) + +// fill_view_kinds (d3d12_compute.inl), for every view record it fills; draw_lock held. +void vdesc_fill(const ViewRecord& record) +{ + if (!vdesc_words || record.id >= view_ids_max) return; + std::uint32_t out[8]; + bool image = false, unmapped = false; + const bool made = view_record_words(record, out, &image, &unmapped); // out is zero when !made + if (made && image && out[1] == 0) out[1] = 1u << 8; + std::memcpy(vdesc_words + u64{record.id} * 8, out, 32); + InterlockedIncrement(!made ? &vdesc_none : image ? &vdesc_image : &vdesc_buffer_views); + static LONG shown; + if (made && first_calls(shown, 4)) + log("x2w-vdesc view %u (slot %u): %s words %08x %08x %08x %08x %08x %08x %08x %08x%s", record.id, record.slot, image ? "T#" : "V#", + out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7], unmapped ? " (format has no gfx10 code: FORMAT 0)" : ""); +} + +// draw_translated (d3d12_draw.inl), a `heapwords 1` translation, after fill_views; draw_lock held. Creates the +// buffer on first use and fills the views filled so far. False: no buffer (the draw / mesh call is skipped). +bool ensure_vdesc() +{ + static bool failed; + if (vdesc_words || failed) return vdesc_words != nullptr; + D3D12_HEAP_PROPERTIES up{D3D12_HEAP_TYPE_UPLOAD}; + D3D12_RESOURCE_DESC rd{}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rd.Width = u64{view_ids_max} * 32; + rd.Height = rd.DepthOrArraySize = rd.MipLevels = 1; + rd.SampleDesc.Count = 1; + rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + const HRESULT hr = device_of(the_device)->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&vdesc_buffer)); + std::uint32_t* words = nullptr; + if (SUCCEEDED(hr) && FAILED(vdesc_buffer->Map(0, nullptr, reinterpret_cast(&words)))) words = nullptr; + if (!words) { + failed = true; + log("x2w-vdesc buffer (%llu bytes) -> 0x%08lx: heapwords translations are skipped", static_cast(rd.Width), + static_cast(hr)); + return false; + } + std::memset(words, 0, static_cast(rd.Width)); + vdesc_words = words; + for (UINT i = 0; i < views_filled; ++i) { + AcquireSRWLockShared(¬e_lock); + const ViewRecord record = view_records()[i]; + ReleaseSRWLockShared(¬e_lock); + vdesc_fill(record); + } + log("x2w-vdesc buffer %u ids x 32 bytes at desktop 0x%llx; %u views filled so far (T# %ld, V# %ld, none %ld)", view_ids_max, + static_cast(vdesc_buffer->GetGPUVirtualAddress()), views_filled, vdesc_image, vdesc_buffer_views, vdesc_none); + return true; +} diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 292937af1c..96348a9d14 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -16,9 +16,18 @@ #include "x2w_build_rev.h" #include "xmem_page_batch.h" #include "startup_stubs/local_log.h" +#include "xmem_low.h" + +#include +#include +#include +#include +#include #include "startup_stubs/logical_view_table.h" #include "startup_stubs/list_compute_root.h" +#include "startup_stubs/placed_pool.h" #include "startup_stubs/overlay_window.h" +#include "startup_stubs/title_composition.h" #include "startup_stubs/draw_bmp.h" #include "startup_stubs/draw_dump_tracking.h" #include "startup_stubs/translated_sampler_bindings.h" @@ -31,6 +40,8 @@ #include "startup_stubs/indexed_rect_geometry.h" #include "startup_stubs/bc7_4k_s.h" #include "startup_stubs/bc64_chain.h" +#include "startup_stubs/gfx10_layout_local.h" +#include "startup_stubs/buffer_address_index.h" #include "startup_stubs/address_texture.h" #include "startup_stubs/list_upload_pages.h" #include "startup_stubs/resource_budget.h" @@ -67,6 +78,10 @@ #include "present_view_format.h" #include "state_block_blend.h" #include "title_heap_memory.h" +#include "gfx10_view_words.h" +#include "startup_stubs/rawaddr_table.h" +#include "startup_stubs/d3d12_mem_counters.h" +#include "xmem_section_lease.h" #include "startup_stubs/xmem_section_buffer.h" #include #include @@ -151,6 +166,7 @@ enum class RetireLeft : std::uint8_t { none, view, view_copy, residency, present struct alignas(16) WrapperOwn { IUnknown* real; LONG refs; + LONG cold_texture_state; // See d3d12_cold_texture.inl; zero unless the opt-in owns this committed texture. Kind kind; x2w_budget::Ticket* budget; x2w_budget::Ticket* backing_budget; @@ -164,6 +180,10 @@ struct alignas(16) WrapperOwn { ID3D12Resource* list_scratch; // Current recording's rectangle-list argument scratch, owned by its desktop allocator. bool list_close_failed; // Desktop Reset repeats a failed Close result indefinitely. bool tiled_address_srv; // Resource backed by 4 KiB tiled guest memory for translated draws. + bool linear_memory_srv : 1; + bool detiled_memory_srv : 1; + // (X2W_MEMORY_SRV_DETILE, gfx10_layout.h) and upload_texture detiles it. A bit + // field next to linear_memory_srv keeps WrapperOwn's size. bool retire_when_idle; // Resource: in the retire class (X2W_D3D12_RELEASE_RETIRED); cleared by any other use. Plain // accesses: a race needs the guest to use a resource across its own final Release. bool retire_hold_missed; // Resource: retire_hold could not record a use (no desktop object or no room), so the @@ -228,6 +248,199 @@ struct DescriptorRange { SRWLOCK descriptor_lock = SRWLOCK_INIT; std::vector descriptor_ranges; +LONG64 noop_census[16][512]; +LONG noop_census_hits[16][512]; +LONG64 noop_census_total; +bool noop_census_on() +{ + static const bool on = [] { + char value[4]{}; + return GetEnvironmentVariableA("X2W_NOOP_CENSUS", value, sizeof(value)) && value[0] == '1'; + }(); + return on; +} +void log(const char* format, ...); +bool first_calls(LONG& counter, LONG limit); +int range_watch_count(); // X2W_RANGE_WATCH, below +int range_watch_hit(std::uint64_t address, std::uint64_t bytes); +bool range_watch_line(int i); +std::uint64_t range_watch_address(int i); +extern LONG frame_number; +bool noop_census_enabled() +{ + static const bool on = [] { + if (noop_census_on()) log("x2w-noop-census on: counting no-op slot calls and descriptor handles in their arguments"); + return noop_census_on(); + }(); + return on; +} +struct CensusHeap { + std::uint64_t base, index, count; + bool desktop; +}; +bool noop_census_heap_index(std::uint64_t value, CensusHeap* out) +{ + if (value < 0x10000) return false; + bool found = false; + AcquireSRWLockShared(&descriptor_lock); + for (const auto& r : descriptor_ranges) { + if (r.title >= 0x10000 && r.title_stride && value >= r.title && value < r.title + r.bytes) { + *out = {r.title, (value - r.title) / r.title_stride, r.bytes / r.title_stride, false}; + found = true; + break; + } + if (r.desktop >= 0x10000 && r.desktop_stride && value >= r.desktop && value < r.desktop + r.desktop_descriptors * r.desktop_stride) { + *out = {r.desktop, (value - r.desktop) / r.desktop_stride, r.desktop_descriptors, true}; + found = true; + break; + } + } + ReleaseSRWLockShared(&descriptor_lock); + return found; +} +bool noop_census_hit(int kind, int slot) +{ + static LONG hits; + return hits < 240 && InterlockedIncrement(&noop_census_hits[kind & 15][slot & 511]) <= 6 && first_calls(hits, 240); +} +void noop_census_note(int kind, int slot, const std::uint64_t* args, std::uint64_t ret) +{ + const LONG64 calls = InterlockedIncrement64(&noop_census[kind & 15][slot & 511]); + const LONG64 total = InterlockedIncrement64(&noop_census_total); + static const char* const names[8] = {"rcx", "rdx", "r8", "r9", "s0", "s1", "s2", "s3"}; + for (int i = 1; i < 8 && range_watch_count(); ++i) { + const int r = range_watch_hit(args[i], 1); + if (r >= 0 && range_watch_line(r)) + log("x2w-watch 0x%llx: no-op %s::slot%d call %lld %s=0x%llx frame %ld; ret=+0x%llx", range_watch_address(r), kind_names[kind], + slot, calls, names[i], args[i], frame_number, ret); + std::uint64_t words[8]{}; + SIZE_T got = 0; + if (args[i] < 0x10000 || r >= 0 || + !ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(args[i]), words, sizeof(words), &got) || got != sizeof(words)) + continue; + for (int w = 0; w < 8; ++w) { + const int rw = range_watch_hit(words[w], 1); + if (rw >= 0 && range_watch_line(rw)) + log("x2w-watch 0x%llx: no-op %s::slot%d call %lld [%s+0x%x]=0x%llx frame %ld; ret=+0x%llx", range_watch_address(rw), + kind_names[kind], slot, calls, names[i], w * 8, words[w], frame_number, ret); + } + } + for (int i = 1; i < 8 && noop_census_hits[kind & 15][slot & 511] < 6; ++i) { + CensusHeap h{}; + const char* weak = i >= 4 ? " (stack word: weak)" : ""; + if (noop_census_heap_index(args[i], &h) && noop_census_hit(kind, slot)) + log("x2w-noop-census %s::slot%d call %lld: %s=0x%llx is %s index 0x%llx of the heap at 0x%llx (%llu descriptors)%s; ret=+0x%llx", + kind_names[kind], slot, calls, names[i], args[i], h.desktop ? "DESKTOP" : "title", h.index, h.base, h.count, weak, ret); + if (calls > 64 || args[i] < 0x10000) continue; + std::uint64_t words[8]{}; + SIZE_T got = 0; + if (!ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(args[i]), words, sizeof(words), &got) || got != sizeof(words)) continue; + for (int w = 0; w < 8; ++w) + if (noop_census_heap_index(words[w], &h) && noop_census_hit(kind, slot)) + log("x2w-noop-census %s::slot%d call %lld: [%s+0x%x]=0x%llx is %s index 0x%llx of the heap at 0x%llx (%llu descriptors)%s; ret=+0x%llx", + kind_names[kind], slot, calls, names[i], w * 8, words[w], h.desktop ? "DESKTOP" : "title", h.index, h.base, h.count, weak, ret); + } + if (total >= 1024 && (total & (total - 1)) == 0) { + for (int k = 0; k < kind_count; ++k) { + char text[1536]; + int at = std::snprintf(text, sizeof(text), "x2w-noop-census after %lld no-op calls, %s:", total, kind_names[k]); + bool any = false; + for (int s = 0; s < 512 && at < static_cast(sizeof(text)) - 32; ++s) + if (noop_census[k][s]) { + at += std::snprintf(text + at, sizeof(text) - at, " %d=%lld", s, noop_census[k][s]); + any = true; + } + if (any) log("%s", text); + } + } +} +// Views view_slot drops because the destination is in no known heap (desktop_cpu_handle gives 0). +void noop_census_dropped_view(int slot, std::uint64_t title_dest) +{ + static LONG64 dropped; + static LONG logged; + const LONG64 n = InterlockedIncrement64(&dropped); + if (first_calls(logged, 32) || (n & (n - 1)) == 0) + log("x2w-noop-census view slot %d dropped (destination 0x%llx is in no known heap); %lld dropped so far", slot, title_dest, n); +} + +extern LONG frame_number; +constexpr std::uint64_t range_watch_span = 0x100; +struct RangeWatch { + std::uint64_t address; + std::uint64_t hash; + bool sampled; + LONG lines; +}; +RangeWatch range_watches[4]; +int range_watch_count() +{ + static const int count = [] { + char text[128]{}; + int n = 0; + if (GetEnvironmentVariableA("X2W_RANGE_WATCH", text, sizeof(text))) { + for (char* at = text; *at && n < 4;) { + char* end = nullptr; + const std::uint64_t value = std::strtoull(at, &end, 16); + if (end == at) break; + if (value) range_watches[n++].address = value; + at = *end == ',' ? end + 1 : end; + } + log("x2w-watch X2W_RANGE_WATCH: %d range(s) of 0x%llx bytes watched (%s)", n, range_watch_span, text); + } + return n; + }(); + return count; +} +// Index of the first watched range that [address, address + bytes) overlaps, else -1. +int range_watch_hit(std::uint64_t address, std::uint64_t bytes) +{ + if (!range_watch_count() || !address) return -1; + if (!bytes) bytes = 1; + for (int i = 0; i < range_watch_count(); ++i) { + const std::uint64_t a = range_watches[i].address; + if (address < a + range_watch_span && address + bytes > a) return i; + } + return -1; +} +bool range_watch_line(int i) { return InterlockedIncrement(&range_watches[i].lines) <= 64; } +std::uint64_t range_watch_address(int i) { return range_watches[i].address; } +// Reads the watched range without faulting; false if it is not readable. +bool range_watch_read(int i, unsigned char (&bytes)[range_watch_span], std::uint64_t* hash) +{ + SIZE_T got = 0; + if (!ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(range_watches[i].address), bytes, sizeof(bytes), &got) || + got != sizeof(bytes)) + return false; + std::uint64_t h = 14695981039346656037ull; + for (unsigned char b : bytes) h = (h ^ b) * 1099511628211ull; + *hash = h; + return true; +} +void range_watch_text(const unsigned char* bytes, char (&text)[3 * 48 + 1]) +{ + for (int k = 0; k < 48; ++k) std::snprintf(text + 3 * k, 4, "%02x ", bytes[k]); +} +// Samples every watched range; logs the ones whose bytes changed since the last sample (or the first sample). +void range_watch_sample(const char* site, std::uint64_t key = 0) +{ + for (int i = 0; i < range_watch_count(); ++i) { + unsigned char bytes[range_watch_span]; + std::uint64_t hash = 0; + if (!range_watch_read(i, bytes, &hash)) continue; + RangeWatch& w = range_watches[i]; + if (w.sampled && w.hash == hash) continue; + const bool first = !w.sampled; + w.sampled = true; + w.hash = hash; + if (!range_watch_line(i)) continue; + char text[3 * 48 + 1]; + range_watch_text(bytes, text); + log("x2w-watch 0x%llx %s at %s %016llx frame %ld: hash %016llx [%s]", w.address, first ? "first sample" : "CHANGED", site, key, + frame_number, hash, text); + } +} + // Desktop rejects a shader-visible CBV/SRV/UAV heap above a driver-specific descriptor count: the // API documents 1,048,576, but a driver may accept fewer (1,000,000 on the GTX 1660 SUPER here), so // the accepted maximum is measured once and cached rather than assumed. @@ -342,27 +555,92 @@ Wrapper* the_device; // Time spent inside the stand-in per entry-point family, reported with the heartbeat. enum { time_list, time_device_noop, time_forward, time_create, time_view, time_queue, time_present, time_wait, - time_pipeline, time_heap, time_copy, time_count }; + time_pipeline, time_heap, time_copy, time_cx_fill_views, time_cx_desktop_range, time_cx_readable, time_cx_texture, + time_cx_execute, time_vquery, time_placed, time_placed_query, time_placed_create, time_placed_log, time_placed_gap, + time_draw_lock_wait, time_log, time_log_in_draw_lock, time_count }; const char* const time_names[time_count] = {"list", "device-noop", "forward", "create", "view", "queue", "present", "wait", - "pipeline", "heap", "copy"}; + "pipeline", "heap", "copy", "cx-fill-views", "cx-desktop-range", "cx-readable", + "cx-texture-view", "cx-execute", "vquery", "placed", "placed-query", + "placed-create", "placed-log", "placed-gap", "draw-lock-wait", "log", + "log-in-draw-lock"}; volatile LONG64 time_ticks[time_count], time_calls[time_count]; +struct Timed; +SIZE_T timed_query(const void* address, MEMORY_BASIC_INFORMATION* info); // VirtualQuery, timed as "vquery" volatile LONG64 list_slot_ticks[256], list_slot_calls[256]; // per command-list slot volatile LONG64 list_slot_census[256]; // per command-list slot, reported with the render totals +struct ThreadInside { + volatile LONG tid; + volatile LONG64 ticks; +}; +constexpr LONG thread_inside_max = 256; +ThreadInside thread_inside[thread_inside_max]; +volatile LONG thread_inside_count; +thread_local ThreadInside* thread_inside_mine; +thread_local int timed_depth; +ThreadInside* inside_slot() +{ + if (!thread_inside_mine) { + static ThreadInside overflow; + const LONG i = InterlockedIncrement(&thread_inside_count) - 1; + thread_inside_mine = i < thread_inside_max ? &thread_inside[i] : &overflow; + thread_inside_mine->tid = static_cast(GetCurrentThreadId()); + } + return thread_inside_mine; +} struct Timed { int category; LARGE_INTEGER start; - explicit Timed(int c) : category(c) { QueryPerformanceCounter(&start); } + explicit Timed(int c) : category(c) + { + ++timed_depth; + QueryPerformanceCounter(&start); + } ~Timed() { LARGE_INTEGER end; QueryPerformanceCounter(&end); InterlockedAdd64(&time_ticks[category], end.QuadPart - start.QuadPart); InterlockedIncrement64(&time_calls[category]); + if (--timed_depth == 0) InterlockedAdd64(&inside_slot()->ticks, end.QuadPart - start.QuadPart); } }; +struct TimedPart { + int category; + LARGE_INTEGER start; + explicit TimedPart(int c) : category(c) { QueryPerformanceCounter(&start); } + void stop() + { + if (category < 0) return; + LARGE_INTEGER end; + QueryPerformanceCounter(&end); + InterlockedAdd64(&time_ticks[category], end.QuadPart - start.QuadPart); + InterlockedIncrement64(&time_calls[category]); + category = -1; + } + ~TimedPart() { stop(); } +}; +// Slot 133 totals since the start, never reset (the per-report times above are). +volatile LONG64 placed_calls_total, placed_ticks_total; + +SIZE_T timed_query(const void* address, MEMORY_BASIC_INFORMATION* info) +{ + Timed timed(time_vquery); + return VirtualQuery(address, info, sizeof(*info)); +} + +extern SRWLOCK draw_lock; // d3d12_draw.inl +extern volatile LONG draw_lock_thread; // the thread that took draw_lock last void log(const char* format, ...) { + Timed timed(time_log); + TimedPart locked(time_log_in_draw_lock); + if (draw_lock_thread != static_cast(GetCurrentThreadId())) + locked.category = -1; + else if (TryAcquireSRWLockShared(&draw_lock)) { + ReleaseSRWLockShared(&draw_lock); + locked.category = -1; + } char line[1536]; va_list args; va_start(args, format); @@ -373,7 +651,7 @@ void log(const char* format, ...) line[n++] = '\r'; line[n++] = '\n'; x2w_trap::write_all(GetStdHandle(STD_ERROR_HANDLE), line, static_cast(n)); - x2w_trap::append_log(line, static_cast(n), false); + x2w_trap::append_trap_log(line, static_cast(n)); // one open handle per module (trap.h) } void guid_text(const GUID* g, char* out, std::size_t size) @@ -405,24 +683,63 @@ ID3D12Device* removal_device; LONG removal_reported, debug_lines; SRWLOCK debug_lock = SRWLOCK_INIT; +void report_dred_dispatches(const D3D12_AUTO_BREADCRUMB_NODE* node, UINT done); +void report_dred(ID3D12Device* device) +{ + ID3D12DeviceRemovedExtendedData* dred = nullptr; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&dred)))) { + log("x2w-dred not available"); + return; + } + D3D12_DRED_AUTO_BREADCRUMBS_OUTPUT crumbs{}; + if (SUCCEEDED(dred->GetAutoBreadcrumbsOutput(&crumbs))) { + int lists = 0; + for (const D3D12_AUTO_BREADCRUMB_NODE* node = crumbs.pHeadAutoBreadcrumbNode; node && lists < 24; node = node->pNext) { + const UINT done = node->pLastBreadcrumbValue ? *node->pLastBreadcrumbValue : 0; + if (done >= node->BreadcrumbCount) continue; // completed list + ++lists; + log("x2w-dred list %p: %u of %u operations completed", static_cast(node->pCommandList), done, node->BreadcrumbCount); + const UINT from = done > 6 ? done - 6 : 0, to = done + 4 < node->BreadcrumbCount ? done + 4 : node->BreadcrumbCount; + for (UINT i = from; i < to; ++i) + log("x2w-dred %s op %u: %d", i == done ? ">>" : " ", i, static_cast(node->pCommandHistory[i])); + report_dred_dispatches(node, done); + } + if (!lists) log("x2w-dred no incomplete list in the breadcrumbs"); + } + D3D12_DRED_PAGE_FAULT_OUTPUT fault{}; + if (SUCCEEDED(dred->GetPageFaultAllocationOutput(&fault))) { + log("x2w-dred page fault va 0x%llx", static_cast(fault.PageFaultVA)); + int n = 0; + for (const D3D12_DRED_ALLOCATION_NODE* a = fault.pHeadExistingAllocationNode; a && n < 8; a = a->pNext, ++n) + log("x2w-dred existing allocation type %d", static_cast(a->AllocationType)); + n = 0; + for (const D3D12_DRED_ALLOCATION_NODE* a = fault.pHeadRecentFreedAllocationNode; a && n < 8; a = a->pNext, ++n) + log("x2w-dred recently freed allocation type %d", static_cast(a->AllocationType)); + } + dred->Release(); +} + void check_device(const char* context, int slot) { if (removal_device && !removal_reported) { const HRESULT reason = removal_device->GetDeviceRemovedReason(); - if (reason != S_OK && InterlockedExchange(&removal_reported, 1) == 0) + if (reason != S_OK && InterlockedExchange(&removal_reported, 1) == 0) { log("x2w-d3d12 DEVICE REMOVED, reason 0x%08lx, first noticed after %s %d", static_cast(reason), context, slot); + report_dred(removal_device); + } } if (!info_queue) return; AcquireSRWLockExclusive(&debug_lock); const UINT64 count = info_queue->GetNumStoredMessages(); - for (UINT64 i = 0; i < count && debug_lines < 400; ++i) { + static std::unordered_map per_id; + for (UINT64 i = 0; i < count && debug_lines < 4000; ++i) { SIZE_T size = 0; info_queue->GetMessage(i, nullptr, &size); if (!size || size > 8192) continue; alignas(16) char storage[8192]; auto* message = reinterpret_cast(storage); - if (SUCCEEDED(info_queue->GetMessage(i, message, &size))) { + if (SUCCEEDED(info_queue->GetMessage(i, message, &size)) && ++per_id[message->ID] <= 4) { ++debug_lines; log("x2w-d3d12-debug [%s %d] sev=%d id=%d %.900s", context, slot, message->Severity, message->ID, message->pDescription); @@ -450,9 +767,12 @@ Wrapper* as_wrapper(const void* p) return known ? const_cast(static_cast(p)) : nullptr; } +#include "startup_stubs/d3d12_cold_texture.inl" + u64 unwrap(u64 value) { Wrapper* w = as_wrapper(reinterpret_cast(value)); + warm_texture(w); return w ? reinterpret_cast(w->own().real) : value; } @@ -556,8 +876,9 @@ bool list_noop() extern LONG draw_calls_seen; // X2W_D3D12_TRACE_FRAME=: every command-list call of presented frame n is logged ("x2w-frame") // with its slot, the kinds of any wrapped objects among its arguments, and stack arguments. -LONG trace_frame_active; +LONG trace_frame_active = x2w_local::env_on("X2W_D3D12_TRACE_ALL") ? 1 : 0; extern LONG capture_active; +extern LONG frame_number; // Command-list methods with a real implementation (render mode). Every list call enters through // noop_slot, which times, captures and traces it, then hands over to the entry here if there is one. using ListTyped = u64(__stdcall*)(u64, u64, u64, u64, u64, u64, u64, u64); @@ -604,11 +925,15 @@ __declspec(noinline) u64 noop_slot(u64 rcx, u64 rdx, u64 r8, u64 r9, u64 s0, u64 if (compute_binding_trace_enabled()) trace_compute_binding(reinterpret_cast(rcx), N, rdx, r8, r9, s0); } if (K == list_kind && list_typed[N]) return list_typed[N](rcx, rdx, r8, r9, s0, s1, s2, s3); + if (noop_census_enabled()) { + const u64 args[8] = {rcx, rdx, r8, r9, s0, s1, s2, s3}; + noop_census_note(K, N, args, reinterpret_cast(_ReturnAddress()) - reinterpret_cast(GetModuleHandleW(nullptr))); + } // Register arguments only: stale caller stack words often still point at an IID. The probe // costs over a millisecond per call in this process (memory queries), so only the first calls // of each slot are checked. static LONG shape_checks; - if (shape_checks < 32 && InterlockedIncrement(&shape_checks) <= 32 && create_shaped(rdx, r8, r9, 0, 0, 0, 0)) { + if (shape_checks < 32 && x2w_local::first_calls(shape_checks, 32) && create_shaped(rdx, r8, r9, 0, 0, 0, 0)) { char name[64]; std::snprintf(name, sizeof(name), "%s::slot%d(passes an IID)", kind_names[K], N); x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, name, N & 0xFF, rcx, rdx, r8, r9, _ReturnAddress()); @@ -637,8 +962,12 @@ template __declspec(noinline) u64 device_noop_slot(u64 rcx, u64 rdx, u64 r8, u64 r9, u64 s0, u64 s1, u64 s2, u64 s3) { Timed timed(time_device_noop); + if (noop_census_enabled()) { + const u64 args[8] = {rcx, rdx, r8, r9, s0, s1, s2, s3}; + noop_census_note(device_kind, N, args, reinterpret_cast(_ReturnAddress()) - reinterpret_cast(GetModuleHandleW(nullptr))); + } static LONG shape_checks; - if (shape_checks < 32 && InterlockedIncrement(&shape_checks) <= 32 && create_shaped(rdx, r8, r9, s0, s1, s2, s3)) { + if (shape_checks < 32 && x2w_local::first_calls(shape_checks, 32) && create_shaped(rdx, r8, r9, s0, s1, s2, s3)) { char name[64]; std::snprintf(name, sizeof(name), "Device::slot%d(passes an IID)", N); char first[3 * 64 + 1]; @@ -739,6 +1068,138 @@ DXGI_FORMAT desktop_format(DXGI_FORMAT format) return mapped; } +// Depth-stencil formats are planar on desktop: a stencil view format reads plane 1, a depth one +// plane 0. A view with the wrong plane removes the device (DXGI_ERROR_INVALID_CALL). +void fix_srv_plane(D3D12_SHADER_RESOURCE_VIEW_DESC& d) +{ + const bool stencil = d.Format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT || d.Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT; + const bool depth = d.Format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS || d.Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || + d.Format == DXGI_FORMAT_R32_FLOAT || d.Format == DXGI_FORMAT_R16_UNORM; + if (!stencil && !depth) return; + const UINT plane = stencil ? 1 : 0; + if (d.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D) d.Texture2D.PlaneSlice = plane; + else if (d.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY) d.Texture2DArray.PlaneSlice = plane; +} + +void fix_srv_samples(D3D12_SHADER_RESOURCE_VIEW_DESC& d, ID3D12Resource* resource) +{ + if (!resource) return; + const D3D12_RESOURCE_DESC rd = resource->GetDesc(); + if (rd.SampleDesc.Count <= 1) return; + if (d.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D) { + d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS; + d.Texture2DMS = {}; + } else if (d.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY) { + const UINT first = d.Texture2DArray.FirstArraySlice, size = d.Texture2DArray.ArraySize; + d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; + d.Texture2DMSArray = {}; + d.Texture2DMSArray.FirstArraySlice = first; + d.Texture2DMSArray.ArraySize = size ? size : rd.DepthOrArraySize; + } +} + +DXGI_FORMAT depth_view_format(DXGI_FORMAT resource, DXGI_FORMAT view) +{ + const bool stencil = view == DXGI_FORMAT_R8_UINT || view == DXGI_FORMAT_X24_TYPELESS_G8_UINT || + view == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT; + switch (resource) { + case DXGI_FORMAT_R24G8_TYPELESS: + return stencil ? DXGI_FORMAT_X24_TYPELESS_G8_UINT : DXGI_FORMAT_R24_UNORM_X8_TYPELESS; + case DXGI_FORMAT_R32G8X24_TYPELESS: + return stencil ? DXGI_FORMAT_X32_TYPELESS_G8X24_UINT : DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; + case DXGI_FORMAT_R32_TYPELESS: + return view == DXGI_FORMAT_D32_FLOAT || view == DXGI_FORMAT_UNKNOWN ? DXGI_FORMAT_R32_FLOAT : view; + case DXGI_FORMAT_R16_TYPELESS: + return view == DXGI_FORMAT_D16_UNORM || view == DXGI_FORMAT_UNKNOWN ? DXGI_FORMAT_R16_UNORM : view; + default: + return view; + } +} + +// The depth-stencil view format of a typeless depth family (DSVs need the D format). +DXGI_FORMAT depth_target_format(DXGI_FORMAT resource) +{ + switch (resource) { + case DXGI_FORMAT_R24G8_TYPELESS: return DXGI_FORMAT_D24_UNORM_S8_UINT; + case DXGI_FORMAT_R32G8X24_TYPELESS: return DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + case DXGI_FORMAT_R32_TYPELESS: return DXGI_FORMAT_D32_FLOAT; + case DXGI_FORMAT_R16_TYPELESS: return DXGI_FORMAT_D16_UNORM; + default: return DXGI_FORMAT_UNKNOWN; + } +} + +// A typed depth format of a texture that may be sampled -> its typeless family, so that shader +// resource views of it can exist on the desktop. Typed D formats allow no SRV at all. +DXGI_FORMAT typeless_depth_family(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_D24_UNORM_S8_UINT: return DXGI_FORMAT_R24G8_TYPELESS; + case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return DXGI_FORMAT_R32G8X24_TYPELESS; + case DXGI_FORMAT_D32_FLOAT: return DXGI_FORMAT_R32_TYPELESS; + case DXGI_FORMAT_D16_UNORM: return DXGI_FORMAT_R16_TYPELESS; + default: return format; + } +} + +// All shader-resource-view repairs for a view of `resource`: depth family format, plane, samples. +void fix_srv(D3D12_SHADER_RESOURCE_VIEW_DESC& d, ID3D12Resource* resource) +{ + if (!resource) return; + const D3D12_RESOURCE_DESC rd = resource->GetDesc(); + if (depth_target_format(rd.Format) != DXGI_FORMAT_UNKNOWN) { + const DXGI_FORMAT before = d.Format; + d.Format = depth_view_format(rd.Format, d.Format); + if (d.Format != before) { + static LONG calls; + if (first_calls(calls, 6)) log("x2w-d3d12 SRV of depth format %d: view format %d -> %d", rd.Format, before, d.Format); + } + fix_srv_plane(d); + } + fix_srv_samples(d, resource); +} + +// A default shader resource view description for a typeless depth resource (a null description is +// refused for typeless resources). +bool default_depth_srv(ID3D12Resource* resource, D3D12_SHADER_RESOURCE_VIEW_DESC& d) +{ + if (!resource) return false; + const D3D12_RESOURCE_DESC rd = resource->GetDesc(); + if (depth_target_format(rd.Format) == DXGI_FORMAT_UNKNOWN || rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return false; + d = {}; + d.Format = depth_view_format(rd.Format, DXGI_FORMAT_UNKNOWN); + d.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (rd.DepthOrArraySize > 1) { + d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + d.Texture2DArray.MipLevels = UINT(-1); + d.Texture2DArray.ArraySize = rd.DepthOrArraySize; + } else { + d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + d.Texture2D.MipLevels = UINT(-1); + } + fix_srv_samples(d, resource); + return true; +} + +// A default depth-stencil view description for a typeless depth resource. +bool default_depth_dsv(ID3D12Resource* resource, D3D12_DEPTH_STENCIL_VIEW_DESC& d) +{ + if (!resource) return false; + const D3D12_RESOURCE_DESC rd = resource->GetDesc(); + const DXGI_FORMAT format = depth_target_format(rd.Format); + if (format == DXGI_FORMAT_UNKNOWN || rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return false; + d = {}; + d.Format = format; + const bool ms = rd.SampleDesc.Count > 1; + if (rd.DepthOrArraySize > 1) { + d.ViewDimension = ms ? D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY : D3D12_DSV_DIMENSION_TEXTURE2DARRAY; + if (ms) d.Texture2DMSArray.ArraySize = rd.DepthOrArraySize; + else d.Texture2DArray.ArraySize = rd.DepthOrArraySize; + } else { + d.ViewDimension = ms ? D3D12_DSV_DIMENSION_TEXTURE2DMS : D3D12_DSV_DIMENSION_TEXTURE2D; + } + return true; +} + constexpr UINT desktop_resource_flags = 0x3f; D3D12_RESOURCE_DESC sanitized(const D3D12_RESOURCE_DESC& desc) { @@ -767,6 +1228,12 @@ D3D12_RESOURCE_DESC sanitized(const D3D12_RESOURCE_DESC& desc) } if (desc.Alignment != 0 && desc.Alignment != 0x10000 && desc.Alignment != 0x400000) copy.Alignment = 0; copy.Format = desktop_format(desc.Format); + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && (copy.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && + !(copy.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && typeless_depth_family(copy.Format) != copy.Format) { + static LONG depths; + if (first_calls(depths, 4)) log("x2w-d3d12 depth texture format %d created typeless (%d) so it can be sampled", copy.Format, typeless_depth_family(copy.Format)); + copy.Format = typeless_depth_family(copy.Format); + } // A packed target the adapter cannot render to or write as a UAV: packed_target_format.h. if (the_device && x2w_startup::packed_target_format(copy.Format)) { ID3D12Device* const device = static_cast(the_device->own().real); @@ -956,18 +1423,34 @@ HRESULT __stdcall query_interface(Wrapper* self, const GUID* iid, void** out) *out = nullptr; HRESULT hr = E_NOINTERFACE; if (is_base_iid(*iid) || kind_for(*iid) == self->own().kind) { - InterlockedIncrement(&self->own().refs); + const LONG refs = InterlockedIncrement(&self->own().refs); + warm_texture(self, refs == 1); *out = self; hr = S_OK; } log("x2w-d3d12 %s::QueryInterface riid=%s -> 0x%08lx", kind_names[self->own().kind], text, static_cast(hr)); return hr; } -ULONG __stdcall add_ref(Wrapper* self) { return static_cast(InterlockedIncrement(&self->own().refs)); } +ULONG __stdcall add_ref(Wrapper* self) +{ + const LONG refs = InterlockedIncrement(&self->own().refs); + warm_texture(self, refs == 1); + return static_cast(refs); +} // The wrappers and their desktop objects stay alive for the process (experiment scope). The one exception is // X2W_D3D12_RELEASE_RETIRED=1: the desktop object of a resource of the retire class is freed once nothing refers to it. // The wrapper stays. void retire_placement(Wrapper* w); +void memcut_released(Wrapper* self); +void memcut_list_reset(Wrapper* list); +void memcut_reap(); +void ring_list_reset(Wrapper* list); +void ring_list_close(Wrapper* list); +void ring_list_gone(Wrapper* list); +void ring_submitted(const std::vector& lists); +void memcut_revive(Wrapper* w); +ID3D12Heap* memcut_slab_heap(void* address, UINT64 bytes, UINT64* offset); // X2W_MEMCUT_ALIAS_SLABS +void memcut_slab_failed(void* address, UINT64 bytes, HRESULT hr); void register_retire_queue(Wrapper* queue); void retire_resource(Wrapper* w); void retire_leave_class(const void* object, RetireLeft why); @@ -989,6 +1472,7 @@ ULONG __stdcall release(Wrapper* self) { const auto refs = InterlockedDecrement(&self->own().refs); if (!refs) { + cool_texture(self); if (self->own().budget) self->own().budget->end_use(); if (self->own().backing_budget) self->own().backing_budget->end_use(); if (self->own().kind == descriptor_heap_kind) retire_drop_heap_views(self); @@ -1006,6 +1490,8 @@ ULONG __stdcall release(Wrapper* self) if (self->own().kind == device_kind) clear_unplaced_buffers(self); } + if (!refs && self->own().kind == resource_kind) memcut_released(self); + if (!refs && self->own().kind == list_kind) ring_list_gone(self); return static_cast(refs); } @@ -1131,31 +1617,32 @@ void __stdcall device_copyable_footprints(Wrapper* self, const D3D12_RESOURCE_DE device_of(self)->GetCopyableFootprints(©, first, count, base, layouts, rows, row_bytes, total); } +struct SignatureInfo { + UINT stride = 0; + std::vector args; +}; +SRWLOCK signature_lock = SRWLOCK_INIT; +std::unordered_map& signature_infos() +{ + static std::unordered_map infos; + return infos; +} // Device slot 41, desktop CreateCommandSignature(desc, root, riid, ppv); on failure the descriptor and // its argument descriptors are logged. The observed console-only type 0x69 gets a placeholder before // desktop validation. Other types still reach the desktop even when they postdate DISPATCH_MESH. u64 __stdcall device_create_command_signature(Wrapper* self, const D3D12_COMMAND_SIGNATURE_DESC* desc, u64 root, u64 iid, u64 out) { + // Argument types outside the desktop enumeration (0x69 seen, stride 12) cannot be created on + // desktop and are not passed to it (the debug layer reports CREATECOMMANDSIGNATURE_INVALID). + bool console_type = false; + for (UINT i = 0; desc && i < desc->NumArgumentDescs; ++i) + console_type |= static_cast(desc->pArgumentDescs[i].Type) > D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + const u64 result = console_type ? static_cast(static_cast(E_INVALIDARG)) + : create_slot(self, reinterpret_cast(desc), root, iid, out, 0, 0, 0, 0); void** output = reinterpret_cast(out); const bool readable_args = x2w_local::readable(desc, sizeof(*desc)) && x2w_local::readable(desc->pArgumentDescs, std::size_t{desc->NumArgumentDescs} * sizeof(*desc->pArgumentDescs)); - if (output && readable_args && x2w_startup::has_console_indirect_arg_type(desc->pArgumentDescs, desc->NumArgumentDescs) && - x2w_local::writable(output, sizeof(*output))) { - static LONG placeholders; - if (first_calls(placeholders, 8)) { - log("x2w-d3d12 CreateCommandSignature: console argument type -> placeholder (stride=%u args=%u)", - desc->ByteStride, desc->NumArgumentDescs); - for (UINT i = 0; i < desc->NumArgumentDescs && i < 8; ++i) { - char bytes[3 * 16 + 1]; - hex_text(&desc->pArgumentDescs[i], sizeof(D3D12_INDIRECT_ARGUMENT_DESC), bytes, sizeof(bytes)); - log("x2w-d3d12 arg[%u]=[%s]", i, bytes); - } - } - *output = wrap(nullptr, command_signature_kind); - return S_OK; - } - const u64 result = create_slot(self, reinterpret_cast(desc), root, iid, out, 0, 0, 0, 0); if (SUCCEEDED(static_cast(result)) && out && desc && root && desc->NumArgumentDescs > 1) { // A Dispatch preceded by root constants for the signature's root (#1759 part 2). Other root argument // types (root views, vertex and index buffer views) and graphics commands remain unsupported here. @@ -1201,15 +1688,31 @@ u64 __stdcall device_create_command_signature(Wrapper* self, const D3D12_COMMAND log("x2w-d3d12 arg[%u]=[%s]", i, bytes); } } - // Preserve the existing fallback for unknown types only after desktop has refused the real request. - if (FAILED(static_cast(result)) && readable_args && output && x2w_local::writable(output, sizeof(*output))) { - for (UINT i = 0; i < desc->NumArgumentDescs; ++i) { - if (static_cast(desc->pArgumentDescs[i].Type) > D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH) { - *output = wrap(nullptr, command_signature_kind); - return S_OK; - } + // The title gets a placeholder CommandSignature for those (command lists are not executed). + if (FAILED(static_cast(result)) && console_type && out) { + log("x2w-d3d12 CreateCommandSignature: console argument type -> placeholder"); + *reinterpret_cast(out) = wrap(nullptr, command_signature_kind); + } + if (out && desc && x2w_local::readable(desc, sizeof(*desc)) && *reinterpret_cast(out) && + (SUCCEEDED(static_cast(result)) || console_type)) { + SignatureInfo info; + info.stride = desc->ByteStride; + if (desc->NumArgumentDescs <= 16 && x2w_local::readable(desc->pArgumentDescs, desc->NumArgumentDescs * sizeof(D3D12_INDIRECT_ARGUMENT_DESC))) + info.args.assign(desc->pArgumentDescs, desc->pArgumentDescs + desc->NumArgumentDescs); + static LONG logged; + if (first_calls(logged, 40)) { + char text[256] = ""; + int at = 0; + for (const auto& a : info.args) + at += std::snprintf(text + at, sizeof(text) - at > 0 ? sizeof(text) - at : 0, " %u(%u,%u)", static_cast(a.Type), + a.Constant.RootParameterIndex, a.Constant.Num32BitValuesToSet); + log("x2w-d3d12 command signature %p: stride %u, args%s", *reinterpret_cast(out), info.stride, text); } + AcquireSRWLockExclusive(&signature_lock); + signature_infos()[*reinterpret_cast(out)] = std::move(info); + ReleaseSRWLockExclusive(&signature_lock); } + if (FAILED(static_cast(result)) && console_type && out) return S_OK; return result; } @@ -1354,6 +1857,31 @@ void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, D3D12 list->ResourceBarrier(1, &barrier); } +LONG upload_allocations; +u64 __stdcall list_allocate_upload(Wrapper*, u64 size, u64 alignment) +{ + static std::mutex arena_lock; + static unsigned char *cursor = nullptr, *limit = nullptr; + constexpr std::size_t block = std::size_t{64} << 20; + if (!size) size = 16; + if (alignment < 16) alignment = 16; + if ((alignment & (alignment - 1)) || size > block / 2) return 0; + const std::lock_guard guard(arena_lock); + auto aligned = [&] { return reinterpret_cast((reinterpret_cast(cursor) + alignment - 1) & ~(alignment - 1)); }; + if (!cursor || aligned() + size > limit) { + auto* fresh = static_cast(x2w_low::alloc(block, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!fresh) return 0; + cursor = fresh; + limit = fresh + block; + log("x2w-d3d12 upload arena block %p (64 MiB)", static_cast(fresh)); + } + unsigned char* result = aligned(); + cursor = result + size; + if (x2w_local::first_calls(upload_allocations, 4)) + log("x2w-d3d12 CommandList::slot148(AllocateUploadMemory) size=0x%llx align=0x%llx -> %p", size, alignment, + static_cast(result)); + return reinterpret_cast(result); +} LONG draw_dump_frame(); void discard_red_producer(ID3D12GraphicsCommandList* list); x2w_startup::DrawReadbacks& draw_dumps() @@ -1422,7 +1950,7 @@ bool allocator_idle(const DesktopAllocator* allocator) } // List slot 148 (Xbox order), allocate CPU-writable upload memory for this recording. -void* __stdcall list_allocate_upload(Wrapper* self, UINT64 bytes, UINT64 alignment) +void* __stdcall list_allocate_upload_pages(Wrapper* self, UINT64 bytes, UINT64 alignment) { if (!bytes || !alignment || (alignment & (alignment - 1)) || bytes > UINT64_MAX - (std::max)(alignment, UINT64{16})) return nullptr; @@ -1607,6 +2135,17 @@ extern "C" __declspec(dllexport) unsigned x2w_d3d12_allocator_pool_size(void* al return size; } +void forget_list_dispatches(ID3D12GraphicsCommandList* list); +namespace gpu_time { +void dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, bool after); +void close(Wrapper* self, ID3D12GraphicsCommandList* list); +void submitted(ID3D12CommandQueue* queue, const std::vector& wrappers); +void reset(Wrapper* self); +void report(); +enum Class { c_cx = 0, c_draw, c_c62, c_copy, c_list, c_count }; +void mark(Wrapper* self, ID3D12GraphicsCommandList* list, int cls, u64 key, bool after, bool drop = false); +void list_begin(Wrapper* self, ID3D12GraphicsCommandList* list); +} // namespace gpu_time // List slot 139 (Xbox order): (allocator, 0, 0), the per-frame reset. HRESULT __stdcall list_reset(Wrapper* self, void* allocator) { @@ -1677,6 +2216,12 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) } ReleaseSRWLockExclusive(&allocator_lock); if (SUCCEEDED(hr)) { + memcut_list_reset(self); + ring_list_reset(self); + forget_list_dispatches(static_cast(self->own().real)); + gpu_time::reset(self); + gpu_time::list_begin(self, static_cast(self->own().real)); + self->own().list_ready = false; reset_list_dynamic_state(self); discard_list_gpu_writes(self); discard_draw_sampler_heaps(previous); @@ -1705,6 +2250,7 @@ HRESULT __stdcall list_close(Wrapper* self) auto* list = static_cast(state.real); end_open_queries(self, list); release_targets(self); + gpu_time::close(self, list); const HRESULT hr = list->Close(); state.list_open = false; state.list_ready = SUCCEEDED(hr); @@ -1714,6 +2260,7 @@ HRESULT __stdcall list_close(Wrapper* self) found->second->close_failed = true; } ReleaseSRWLockExclusive(&allocator_lock); + ring_list_close(self); InterlockedIncrement(&render_closes); if (FAILED(hr)) { discard_list_gpu_writes(self); @@ -1729,25 +2276,157 @@ HRESULT __stdcall list_close(Wrapper* self) return hr; } +namespace fence_times { +struct Entry { + ID3D12Fence* fence; + Wrapper* wrapper; + UINT64 value; + LONG64 t0, t1, t2; + volatile LONG stage; +}; +bool timing() +{ + static const bool value = x2w_local::env_on("X2W_FENCE_TIMES"); + return value; +} +// X2W_FENCE_STORE=probe: the probe thread also stores the completed value as soon as its wait returns +// (the threadpool callback still stores it too; fence_reached only ever raises the value). +bool store_early() +{ + static const bool value = [] { + char text[16]{}; + return GetEnvironmentVariableA("X2W_FENCE_STORE", text, sizeof(text)) && std::strcmp(text, "probe") == 0; + }(); + return value; +} +bool on() { return timing() || store_early(); } +SRWLOCK lock = SRWLOCK_INIT; +std::deque entries; +HANDLE wake; +volatile LONG64 count, gpu_sum, gpu_max, store_sum, store_max, total_max, behind, timeouts; +LONG64 now() +{ + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return t.QuadPart; +} +void raise(volatile LONG64& slot, LONG64 value) +{ + for (LONG64 seen = slot; value > seen;) { + const LONG64 previous = InterlockedCompareExchange64(&slot, value, seen); + if (previous == seen) break; + seen = previous; + } +} +void finish(Entry* e) +{ + if (InterlockedIncrement(&e->stage) != 2) return; + if (e->t1 <= e->t2) { + InterlockedIncrement64(&count); + InterlockedAdd64(&gpu_sum, e->t1 - e->t0); + InterlockedAdd64(&store_sum, e->t2 - e->t1); + raise(gpu_max, e->t1 - e->t0); + raise(store_max, e->t2 - e->t1); + } else { + InterlockedIncrement64(&behind); + } + raise(total_max, e->t2 - e->t0); + e->fence->Release(); + delete e; +} +DWORD WINAPI probe(void*) +{ + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); + SetThreadDescription(GetCurrentThread(), L"x2w fence probe"); + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + for (;;) { + Entry* e = nullptr; + AcquireSRWLockExclusive(&lock); + if (!entries.empty()) { + e = entries.front(); + entries.pop_front(); + } + ReleaseSRWLockExclusive(&lock); + if (!e) { + WaitForSingleObject(wake, 100); + continue; + } + if (e->fence->GetCompletedValue() < e->value && SUCCEEDED(e->fence->SetEventOnCompletion(e->value, event)) && + WaitForSingleObject(event, 5000) != WAIT_OBJECT_0) + InterlockedIncrement64(&timeouts); + else if (store_early()) + fence_reached(e->wrapper, e->value); + e->t1 = now(); + finish(e); + } +} +Entry* start(Wrapper* wrapper, UINT64 value) +{ + if (!on()) return nullptr; + auto* fence = static_cast(wrapper->own().real); + static const bool started = [] { + wake = CreateEventW(nullptr, FALSE, FALSE, nullptr); + CloseHandle(CreateThread(nullptr, 0, probe, nullptr, 0, nullptr)); + return true; + }(); + (void)started; + fence->AddRef(); + auto* e = new Entry{fence, wrapper, value, now(), 0, 0, 0}; + AcquireSRWLockExclusive(&lock); + entries.push_back(e); + ReleaseSRWLockExclusive(&lock); + SetEvent(wake); + return e; +} +void stored(Entry* e) +{ + if (!e) return; + e->t2 = now(); + finish(e); +} +// One line per present split window; the counters restart. +void report() +{ + if (!timing()) return; + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + const auto ms = [&](LONG64 t) { return static_cast(t) * 1000.0 / static_cast(f.QuadPart); }; + const LONG64 n = InterlockedExchange64(&count, 0), gs = InterlockedExchange64(&gpu_sum, 0), ss = InterlockedExchange64(&store_sum, 0); + const LONG64 gm = InterlockedExchange64(&gpu_max, 0), sm = InterlockedExchange64(&store_max, 0), tm = InterlockedExchange64(&total_max, 0); + const LONG64 late = InterlockedExchange64(&behind, 0), lost = InterlockedExchange64(&timeouts, 0); + AcquireSRWLockShared(&lock); + const std::size_t queued = entries.size(); + ReleaseSRWLockShared(&lock); + log("x2w-fence times: %lld signals; our Signal -> desktop fence reached mean %.2f ms max %.2f; reached -> completed " + "value stored (what the title mwaits on) mean %.3f ms max %.2f; Signal -> stored max %.2f ms; probe behind %lld, " + "probe timeouts %lld, queued %zu", static_cast(n), n ? ms(gs) / n : 0.0, ms(gm), n ? ms(ss) / n : 0.0, ms(sm), + ms(tm), static_cast(late), static_cast(lost), queued); +} +} // namespace fence_times + // A fence signalled on a queue completes when the desktop GPU reaches it. struct PendingSignal { Wrapper* fence; UINT64 value; HANDLE event; + fence_times::Entry* timing; }; void CALLBACK signal_reached(PTP_CALLBACK_INSTANCE, void* context, PTP_WAIT wait, TP_WAIT_RESULT) { auto* pending = static_cast(context); fence_reached(pending->fence, pending->value); + fence_times::stored(pending->timing); CloseHandle(pending->event); delete pending; CloseThreadpoolWait(wait); } void complete_when_reached(Wrapper* fence, UINT64 value) { - auto* pending = new PendingSignal{fence, value, CreateEventW(nullptr, FALSE, FALSE, nullptr)}; + auto* pending = new PendingSignal{fence, value, CreateEventW(nullptr, FALSE, FALSE, nullptr), + fence_times::start(fence, value)}; if (FAILED(static_cast(fence->own().real)->SetEventOnCompletion(value, pending->event))) { fence_reached(fence, value); + fence_times::stored(pending->timing); CloseHandle(pending->event); delete pending; return; @@ -1764,7 +2443,10 @@ SRWLOCK shown_lock = SRWLOCK_INIT; char shown_note[160] = "no frame read back yet"; void write_file(const wchar_t* path, const void* data, std::size_t bytes); -void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) +void reduce_presented(const D3D12_RESOURCE_DESC& desc, const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& footprint, bool rgba, UINT64 total, + ID3D12Resource* readback); + +void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface, bool issue = true) { static ID3D12CommandAllocator* allocator; static ID3D12GraphicsCommandList* list; @@ -1772,6 +2454,25 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) static ID3D12Resource* readback; static UINT64 readback_bytes, fence_value; static HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + static const bool wait_for_copy = x2w_local::env_on("X2W_READBACK_WAIT"); + struct InFlight { + ID3D12Resource* surface = nullptr; // held until the copy is done + D3D12_RESOURCE_DESC desc{}; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + bool rgba = false; + UINT64 total = 0; + }; + static InFlight in_flight; + if (in_flight.surface) { + if (fence->GetCompletedValue() < fence_value) { + if (issue) std::snprintf(shown_note, sizeof(shown_note), "readback still in flight"); + return; + } + reduce_presented(in_flight.desc, in_flight.footprint, in_flight.rgba, in_flight.total, readback); + in_flight.surface->Release(); + in_flight.surface = nullptr; + } + if (!issue || !queue || !surface) return; ID3D12Device* device = device_of(the_device); const D3D12_RESOURCE_DESC desc = surface->GetDesc(); D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; @@ -1827,11 +2528,22 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) ID3D12CommandList* lists[] = {list}; queue->ExecuteCommandLists(1, lists); queue->Signal(fence, ++fence_value); + surface->AddRef(); + in_flight = {surface, desc, footprint, rgba, total}; + if (!wait_for_copy) return; fence->SetEventOnCompletion(fence_value, event); if (WaitForSingleObject(event, 3000) != WAIT_OBJECT_0) { std::snprintf(shown_note, sizeof(shown_note), "readback timed out"); - return; + return; // picked up by a later call once the fence passes } + reduce_presented(desc, footprint, rgba, total, readback); + in_flight.surface->Release(); + in_flight.surface = nullptr; +} + +void reduce_presented(const D3D12_RESOURCE_DESC& desc, const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& footprint, bool rgba, UINT64 total, + ID3D12Resource* readback) +{ void* mapped = nullptr; const D3D12_RANGE range{0, static_cast(total)}; if (FAILED(readback->Map(0, &range, &mapped))) return; @@ -1854,8 +2566,12 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) { static wchar_t dump_path[MAX_PATH]; static const bool dump = GetEnvironmentVariableW(L"X2W_D3D12_DUMP_SURFACE", dump_path, MAX_PATH) != 0; - if (dump && (shown_frames % 4) == 3 && desc.Width <= 8192 && desc.Height <= 8192) { - const UINT width = static_cast(desc.Width), height = desc.Height; + // A path containing %ld gets the read-back number and a picture reduced to at most 960 pixels + // wide, written at every read-back (about every 2 s), so a run keeps a series of shots. + static const bool numbered = dump && std::wcsstr(dump_path, L"%ld") != nullptr; + if (dump && (numbered || (shown_frames % 4) == 3) && desc.Width <= 8192 && desc.Height <= 8192) { + const UINT step = numbered && desc.Width > 960 ? static_cast((desc.Width + 959) / 960) : 1; + const UINT width = static_cast(desc.Width) / step, height = desc.Height / step; std::vector file(54 + std::size_t{width} * height * 4); const std::uint32_t header[] = {static_cast(file.size()), 0, 54, 40, width, static_cast(-static_cast(height)), 1 | (32u << 16), 0, width * height * 4, 2835, 2835, 0, 0}; @@ -1863,16 +2579,23 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) file[1] = 'M'; std::memcpy(file.data() + 2, header, sizeof(header)); for (UINT y = 0; y < height; ++y) { - const auto* row = static_cast(mapped) + footprint.Offset + UINT64{y} * footprint.Footprint.RowPitch; + const auto* row = static_cast(mapped) + footprint.Offset + UINT64{y} * step * footprint.Footprint.RowPitch; unsigned char* out = file.data() + 54 + std::size_t{y} * width * 4; for (UINT x = 0; x < width; ++x) { - out[x * 4 + 0] = rgba ? row[x * 4 + 2] : row[x * 4 + 0]; - out[x * 4 + 1] = row[x * 4 + 1]; - out[x * 4 + 2] = rgba ? row[x * 4 + 0] : row[x * 4 + 2]; + const unsigned char* texel = row + std::size_t{x} * step * 4; + out[x * 4 + 0] = rgba ? texel[2] : texel[0]; + out[x * 4 + 1] = texel[1]; + out[x * 4 + 2] = rgba ? texel[0] : texel[2]; out[x * 4 + 3] = 255; } } - write_file(dump_path, file.data(), file.size()); + if (numbered) { + wchar_t path[MAX_PATH]; + swprintf(path, MAX_PATH, dump_path, static_cast(shown_frames)); + write_file(path, file.data(), file.size()); + } else { + write_file(dump_path, file.data(), file.size()); + } } } const D3D12_RANGE none{0, 0}; @@ -1880,7 +2603,188 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) const LONG count = InterlockedIncrement(&shown_frames); std::snprintf(shown_note, sizeof(shown_note), "surface %llux%u format %d, readback %ld, mean level %.2f/255", desc.Width, desc.Height, desc.Format, count, sum / (3.0 * shown_width * shown_height)); - if ((count > 0 && count <= 3) || count % 40 == 0) log("x2w-render presented %s", shown_note); + if (x2w_local::first_of(count, 3) || count % 5 == 0) log("x2w-render presented %s (frame %ld)", shown_note, frame_number); +} + +SRWLOCK traced_lock = SRWLOCK_INIT; +struct TracedTarget { + ID3D12Resource* first; // the target + int second; // drawn draws + ID3D12Resource* snap; // copy taken right after its last drawn draw (COPY_DEST), or null +}; +std::vector& traced_targets() +{ + static std::vector targets; + return targets; +} +void require_state(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_STATES state); +void note_traced_target(Wrapper* self, ID3D12Resource* target, bool drawn, + D3D12_RESOURCE_STATES after = D3D12_RESOURCE_STATE_RENDER_TARGET) +{ + if (!target) return; + AcquireSRWLockExclusive(&traced_lock); + auto& all = traced_targets(); + auto found = std::find_if(all.begin(), all.end(), [&](const auto& e) { return e.first == target; }); + if (found == all.end()) { + target->AddRef(); + all.push_back({target, 0, nullptr}); + found = all.end() - 1; + } + static const bool snapshots = x2w_local::env_on("X2W_D3D12_TRACE_TARGETS"); + if (drawn) ++found->second; + if (drawn && snapshots) { + D3D12_RESOURCE_DESC desc = target->GetDesc(); + if (!found->snap && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1) { + desc.Flags &= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + if (FAILED(device_of(the_device)->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&found->snap)))) + found->snap = nullptr; + } + if (found->snap && self->own().list_open) { + auto* list = static_cast(self->own().real); + require_state(self, target, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyResource(found->snap, target); + require_state(self, target, after); + } + } + ReleaseSRWLockExclusive(&traced_lock); +} +extern "C" __declspec(dllexport) unsigned x2w_d3d12_traced_targets(unsigned* out, unsigned capacity) +{ + AcquireSRWLockShared(&traced_lock); + const auto& all = traced_targets(); + for (unsigned i = 0; out && i < capacity && i < all.size(); ++i) { + const D3D12_RESOURCE_DESC desc = all[i].first->GetDesc(); + out[4 * i] = static_cast(desc.Width); + out[4 * i + 1] = desc.Height; + out[4 * i + 2] = static_cast(desc.Format); + out[4 * i + 3] = static_cast(all[i].second); + } + const unsigned count = static_cast(all.size()); + ReleaseSRWLockShared(&traced_lock); + return count; +} +void summarise_traced_targets(ID3D12CommandQueue* queue); +extern "C" __declspec(dllexport) int x2w_d3d12_summarise_traced_targets() +{ + if (!the_device) return 0; + ID3D12CommandQueue* queue = nullptr; + const D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(device_of(the_device)->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue)))) return 0; + summarise_traced_targets(queue); + queue->Release(); + return 1; +} +void summarise_traced_targets(ID3D12CommandQueue* queue) +{ + AcquireSRWLockExclusive(&traced_lock); + std::vector all; + all.swap(traced_targets()); + ReleaseSRWLockExclusive(&traced_lock); + ID3D12Device* device = device_of(the_device); + ID3D12CommandAllocator* allocator = nullptr; + ID3D12GraphicsCommandList* list = nullptr; + ID3D12Fence* fence = nullptr; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + HRESULT hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)); + if (SUCCEEDED(hr)) hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, nullptr, IID_PPV_ARGS(&list)); + if (SUCCEEDED(hr)) hr = list->Close(); + if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); + UINT64 fence_value = 0; + for (std::size_t n = 0; n < all.size() && SUCCEEDED(hr); ++n) { + ID3D12Resource* target = all[n].snap ? all[n].snap : all[n].first; + const D3D12_RESOURCE_STATES rest = all[n].snap ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COMMON; + const D3D12_RESOURCE_DESC desc = target->GetDesc(); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT rows = 0; + UINT64 row_bytes = 0, total = 0; + device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, &rows, &row_bytes, &total); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || total == 0 || total == ~0ull || total > (512ull << 20)) { + log("x2w-frame target %zu %p fmt %d: not summarised", n, static_cast(target), desc.Format); + continue; + } + ID3D12Resource* readback = nullptr; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = total; + buffer.Height = 1; + buffer.DepthOrArraySize = 1; + buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback)))) continue; + allocator->Reset(); + list->Reset(allocator, nullptr); + transition(list, target, rest, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION from{}, to{}; + from.pResource = target; + from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + to.pResource = readback; + to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + to.PlacedFootprint = footprint; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + transition(list, target, D3D12_RESOURCE_STATE_COPY_SOURCE, rest); + list->Close(); + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + queue->Signal(fence, ++fence_value); + fence->SetEventOnCompletion(fence_value, event); + if (WaitForSingleObject(event, 5000) != WAIT_OBJECT_0) { + log("x2w-frame target %zu: read-back timed out", n); + readback->Release(); + break; + } + void* mapped = nullptr; + const D3D12_RANGE range{0, static_cast(total)}; + if (SUCCEEDED(readback->Map(0, &range, &mapped))) { + const UINT texel = desc.Width ? static_cast(row_bytes / desc.Width) : 0; + std::uint64_t nonzero = 0, sum = 0, texels = 0; + for (UINT y = 0; y < rows; y += 2) { + const auto* row = static_cast(mapped) + footprint.Offset + UINT64{y} * footprint.Footprint.RowPitch; + for (UINT64 x = 0; x < desc.Width && texel; x += 2) { + bool any = false; + for (UINT b = 0; b < texel; ++b) { + any |= row[x * texel + b] != 0; + sum += row[x * texel + b]; + } + nonzero += any; + ++texels; + } + } + log("x2w-frame target %zu %s %p %llux%u fmt %d draws %d: non-zero texels %.4f, mean byte %.2f", n, all[n].snap ? "snapshot" : "end", static_cast(all[n].first), + static_cast(desc.Width), desc.Height, desc.Format, all[n].second, + texels ? double(nonzero) / texels : 0.0, texels && texel ? double(sum) / (texels * texel) : 0.0); + if (texel && texel <= 16 && rows) { + char text[9 * 36 + 1]{}; + std::size_t used = 0; + for (UINT gy = 1; gy < 6; gy += 2) + for (UINT gx = 1; gx < 6; gx += 2) { + const UINT y = static_cast(UINT64{rows} * gy / 6); + const UINT64 x = desc.Width * gx / 6; + const auto* at = static_cast(mapped) + footprint.Offset + UINT64{y} * footprint.Footprint.RowPitch + x * texel; + if (used + 2 * texel + 2 < sizeof(text)) { + for (UINT b = 0; b < texel; ++b) used += std::snprintf(text + used, sizeof(text) - used, "%02x", at[b]); + used += std::snprintf(text + used, sizeof(text) - used, " "); + } + } + log("x2w-frame target %zu texels 3x3 (rows top to bottom, raw bytes): %s", n, text); + } + const D3D12_RANGE none{0, 0}; + readback->Unmap(0, &none); + } + readback->Release(); + } + for (auto& e : all) { + e.first->Release(); + if (e.snap) e.snap->Release(); + } + if (list) list->Release(); + if (allocator) allocator->Release(); + if (fence) fence->Release(); + CloseHandle(event); } // --------------------------------------------------------------------------------------------- @@ -1932,8 +2836,31 @@ HRESULT __stdcall device_create_root_signature(Wrapper* self, UINT node, const v if (!out || !iid) return E_POINTER; *out = nullptr; ID3D12RootSignature* root = nullptr; + ID3DBlob* stripped = nullptr; + { + ID3D12VersionedRootSignatureDeserializer* reader = nullptr; + if (blob && SUCCEEDED(D3D12CreateVersionedRootSignatureDeserializer(blob, size, IID_PPV_ARGS(&reader)))) { + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc = nullptr; + constexpr UINT indexed = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | + D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + if (SUCCEEDED(reader->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &desc)) && desc && + (static_cast(desc->Desc_1_1.Flags) & indexed)) { + D3D12_VERSIONED_ROOT_SIGNATURE_DESC copy = *desc; + copy.Desc_1_1.Flags = static_cast(static_cast(copy.Desc_1_1.Flags) & ~indexed); + if (FAILED(D3D12SerializeVersionedRootSignature(©, &stripped, nullptr))) stripped = nullptr; + static LONG strips; + if (first_calls(strips, 4)) + log("x2w-d3d12 Device::CreateRootSignature flags 0x%x: heap-directly-indexed bits cleared for the desktop (%s)", + static_cast(desc->Desc_1_1.Flags), stripped ? "ok" : "serialize failed, kept"); + } + reader->Release(); + } + } const HRESULT hr = kind_for(*iid) == root_signature_kind - ? device_of(self)->CreateRootSignature(node, blob, size, IID_PPV_ARGS(&root)) : E_NOINTERFACE; + ? device_of(self)->CreateRootSignature(node, stripped ? stripped->GetBufferPointer() : blob, + stripped ? stripped->GetBufferSize() : size, IID_PPV_ARGS(&root)) + : E_NOINTERFACE; + if (stripped) stripped->Release(); static LONG calls; const bool log_it = first_calls(calls, 6); if (FAILED(hr)) { @@ -2255,67 +3182,25 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES // Transient data the title addresses by GPU address (fetch tables, vertices, constants) is copied // from its memory into a desktop upload buffer; the copy's GPU address is bound instead. -ID3D12Resource* upload_ring; -bool ring_copy(u64 title_address, std::size_t bytes, u64* offset); -D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(u64 title_address, std::size_t bytes) -{ - u64 offset = 0; - return ring_copy(title_address, bytes, &offset) ? upload_ring->GetGPUVirtualAddress() + offset : 0; -} -unsigned char* reserve_upload_ring(std::size_t bytes, u64* offset) -{ - constexpr u64 ring_bytes = u64{256} << 20; - ID3D12Resource*& ring = upload_ring; - static unsigned char* mapped; - static volatile LONG64 cursor; - static SRWLOCK lock = SRWLOCK_INIT; - if (!ring) { - AcquireSRWLockExclusive(&lock); - if (!ring) { - const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_UPLOAD}; - D3D12_RESOURCE_DESC buffer{}; - buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - buffer.Width = ring_bytes; - buffer.Height = 1; - buffer.DepthOrArraySize = 1; - buffer.MipLevels = 1; - buffer.SampleDesc.Count = 1; - buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - ID3D12Resource* created = nullptr; - void* base = nullptr; - auto* device = device_of(the_device); - if (SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&created)))) { - auto* budget = x2w_budget::committed(device, created, D3D12_HEAP_TYPE_UPLOAD); - if (SUCCEEDED(created->Map(0, nullptr, &base))) { - mapped = static_cast(base); - ring = created; - } else if (budget) { - budget->end_use(); // The failed Map leaves the existing desktop reference held. - } - } - } - ReleaseSRWLockExclusive(&lock); - } - if (!ring || bytes == 0 || bytes > ring_bytes / 4) return nullptr; - const u64 rounded = (bytes + 511) & ~u64{511}; // 512: texture footprints are placed in the ring too - u64 start = static_cast(InterlockedExchangeAdd64(&cursor, static_cast(rounded))) % ring_bytes; - if (start + rounded > ring_bytes) start = static_cast(InterlockedExchangeAdd64(&cursor, static_cast(rounded) + (ring_bytes - start))) % ring_bytes, start = 0; - *offset = start; - return mapped + start; -} - -bool ring_copy(u64 title_address, std::size_t bytes, u64* offset) +#include "startup_stubs/d3d12_upload_ring.inl" +bool ring_copy(u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** buffer) { - auto* dest = reserve_upload_ring(bytes, offset); + auto* dest = reserve_upload_ring(bytes, offset, buffer, nullptr); if (!dest) return false; std::memcpy(dest, reinterpret_cast(title_address), bytes); return true; } +D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(u64 title_address, std::size_t bytes) +{ + u64 offset = 0; + ID3D12Resource* buffer = nullptr; + return ring_copy(title_address, bytes, &offset, &buffer) ? buffer->GetGPUVirtualAddress() + offset : 0; +} // Number of contiguous readable bytes at address, up to wanted. std::size_t readable_window(u64 address, std::size_t wanted) { + Timed timed(time_cx_readable); return x2w_local::probe_readable(static_cast(address), wanted); } @@ -2336,9 +3221,9 @@ struct Pass { std::vector copied_gpu_ranges; // exact CopyBufferRegion destinations on this recording bool pipeline_real = false; // the bound pipeline has a desktop pipeline bool compute_pipeline = false; - ID3D12RootSignature* compute_root = nullptr; // latest guest root if it was forwarded - x2w_startup::ComPtr desktop_compute_root; // last root actually set on this recording - std::array desktop_compute_upload_srvs{}; + ID3D12RootSignature* compute_root_desktop = nullptr; + x2w_startup::ComPtr desktop_compute_root; // upstream: last root its slot 33 set on this recording + std::array desktop_compute_upload_srvs{}; // upstream slot 43 (X2W_UPSTREAM_COMPUTE_ROOT) const std::vector* compute_params = nullptr; std::unique_ptr compute_trace; IndirectGraphicsPipeline indirect_graphics; @@ -2346,6 +3231,7 @@ struct Pass { bool targets_bound = false; bool topology_ok = false; unsigned srv_bound = 0; // bit per root parameter with a desktop address bound + unsigned srv_pending = 0; const std::vector* root = nullptr; // Heap-indexing flags of the title root signature last set by slot 34. While nonzero, that root signature is // deferred: it is not set on the desktop list, root SRVs are not forwarded, and real draws go through decide_real_root. @@ -2369,11 +3255,16 @@ struct Pass { D3D12_INDEX_BUFFER_VIEW ib = {}; DXGI_FORMAT target_formats[8] = {}; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; + bool dsv_read_only = false; + ID3D12Resource* dsv_resource = nullptr; bool targets_single_sample = false; bool depth_view_writable = false; UINT stencil_reference = 0; // last guest OMSetStencilRef on this recording UINT target_count = 0; ID3D12Resource* target0 = nullptr; // desktop resource of render target 0 (for per-draw dumps) + ID3D12Resource* targets[8] = {}; + D3D12_VIEWPORT viewport0 = {}; + D3D12_RECT scissor0 = {}; ID3D12Resource* trace_targets[8]{}; ID3D12Resource* trace_depth = nullptr; bool heap_set = false; @@ -2381,6 +3272,12 @@ struct Pass { std::unique_ptr sampler_snapshot; x2w_startup::ComPtr sampler_heap; ID3D12DescriptorHeap* bound_sampler_heap = nullptr; + Wrapper* compute_root = nullptr; + int compute_kind[16] = {}; + u64 compute_address[16] = {}; + std::uint32_t compute_constants[16][16] = {}; + UINT compute_count[16] = {}; + std::uint16_t compute_set[16] = {}; // Whether the title set a viewport / scissor on this list; without them a desktop list draws no pixel. bool viewport_set = false; bool scissor_set = false; @@ -2555,25 +3452,25 @@ UINT __stdcall list_resource_barriers(Wrapper* self, UINT count, const D3D12_RES return 0; // no console barrier actions to perform on the caller's side } -void __stdcall list_compute_root(Wrapper* self, void* root) +void __stdcall list_compute_root_desktop(Wrapper* self, void* root) { auto* list = recording(self); if (!list) return; Wrapper* w = as_wrapper(root); Pass& pass = pass_of(self); const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); - pass.compute_root = real ? static_cast(w->own().real) : nullptr; + pass.compute_root_desktop = real ? static_cast(w->own().real) : nullptr; pass.compute_tables.set_signature(w ? root_info(w) : nullptr); // a different signature leaves no table bound pass.compute_params = real ? root_info(w) : nullptr; if (compute_binding_trace_enabled() && (!pass.compute_trace || pass.compute_trace->root != w)) { pass.compute_trace = std::make_unique(); pass.compute_trace->root = w; } - if (pass.compute_root) { - if (pass.desktop_compute_root.Get() != pass.compute_root) + if (pass.compute_root_desktop) { + if (pass.desktop_compute_root.Get() != pass.compute_root_desktop) pass.desktop_compute_upload_srvs.fill(0); - pass.desktop_compute_root = pass.compute_root; - list->SetComputeRootSignature(pass.compute_root); + pass.desktop_compute_root = pass.compute_root_desktop; + list->SetComputeRootSignature(pass.compute_root_desktop); } } @@ -2760,7 +3657,7 @@ constexpr const char* unknown = "unknown"; } // namespace indirect_other_refusal_code // The guest method has independent resource and byte-offset arguments. -void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, +void __stdcall list_execute_indirect_upstream(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, void* count_buffer, u64 count_offset) { // Every refusal is counted under the signature's kind, including those before the signature is checked. @@ -2879,9 +3776,9 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (samples.Count != 1 || samples.Quality) return refuse("draw requires a single-sample render target", indirect_other, indirect_other_refusal_code::multisample_target); } - } else if (!pass.compute_pipeline || !pass.compute_root) { + } else if (!pass.compute_pipeline || !pass.compute_root_desktop) { return refuse("requires a desktop compute pipeline and root", indirect_compute_pipeline); - } else if (sig->own().signature_root && sig->own().signature_root != pass.compute_root) { + } else if (sig->own().signature_root && sig->own().signature_root != pass.compute_root_desktop) { return refuse("signature root constants require the bound compute root", indirect_other, indirect_other_refusal_code::compute_root_mismatch); } else if (sig->own().signature_root && (count != 1 || count_buffer)) { // Batched and count-buffer Dispatch is supported for rootless signatures only in this slice. @@ -3065,8 +3962,10 @@ void __stdcall list_graphics_root(Wrapper* self, void* root) } pass.root = params; pass.srv_bound = 0; + pass.srv_pending = 0; + static const bool defer_heap_roots = x2w_local::env_on("X2W_DEFER_HEAP_ROOTS"); const bool real = w && w->own().kind == root_signature_kind && w->own().real; - pass.root_heap_flags = real ? root_heap_flags(w) : 0; + pass.root_heap_flags = real && defer_heap_roots ? root_heap_flags(w) : 0; pass.deferred_root = pass.root_heap_flags ? static_cast(w->own().real) : nullptr; pass.graphics_root = nullptr; auto* list = recording(self); @@ -3210,28 +4109,18 @@ void __stdcall list_clear_depth_stencil(Wrapper* self, u64 handle, D3D12_CLEAR_F InterlockedIncrement(&render_clears); } // List slot 52 (desktop 48 + 4), ClearRenderTargetView(view, colour, rect count, rects). Desktop -// resources rest in COMMON here, so the target is moved to RENDER_TARGET around the clear. The view is -// read from its shadow record, as OMSetRenderTargets does, so a descriptor the title copied clears the -// resource it now holds; a handle with no record falls back to the creation-time map. +// resources rest in COMMON here, so the target is moved to RENDER_TARGET around the clear. +LONG clears_dropped[2]; // slot 52 dropped: [0] list not open or no colour, [1] view resolves to no target void __stdcall list_clear_target(Wrapper* self, u64 handle, const float* colour, UINT rect_count, const D3D12_RECT* rects) { - if (!self->own().list_open || !colour) return; + if (!self->own().list_open || !colour) return (void)InterlockedIncrement(&clears_dropped[0]); const u64 desktop = desktop_cpu_handle(handle); - const ResolvedView view = resolve_view(desktop, 20); - ID3D12Resource* target = view.resource; + ID3D12Resource* target = view_target(desktop); static LONG logged; if (first_calls(logged, 4)) log("x2w-render ClearRenderTargetView view=0x%llx target=%p colour=%.3f %.3f %.3f %.3f rects=%u", handle, static_cast(target), colour[0], colour[1], colour[2], colour[3], rect_count); - if (!target) { - InterlockedIncrement(&render_target_unresolved); - static LONG refused; - if (first_calls(refused, 6)) - log("x2w-d3d12 ClearRenderTargetView skipped: view 0x%llx is %s", handle, - view.wrong_kind ? "not a render target view" - : view.skipped ? "a skipped render target view" : "not a known render target view"); - return; - } + if (!target) return (void)InterlockedIncrement(&clears_dropped[1]); auto* list = static_cast(self->own().real); use_as_target(self, target); const auto red_sample = red_producers().before(self, list, target, "clear-rtv", 0, 0); @@ -3240,6 +4129,17 @@ void __stdcall list_clear_target(Wrapper* self, u64 handle, const float* colour, red_producers().after(self, red_sample); InterlockedIncrement(&render_clears); } + +// Outcome of every slot 50 call (exactly one each), reported and reset every 300 presented frames. +enum TargetBind { + bind_bound, bind_single_range_bound, bind_not_recording, bind_count_over_8, bind_handles_unreadable, + bind_range_past_heap, bind_wrong_kind, bind_unresolved, bind_empty, bind_depth_wrong_kind, bind_depth_unknown, + bind_depth_one_plane, bind_outcomes +}; +LONG target_binds[bind_outcomes], target_unresolved_at[8]; +LONG target_depth_unreadable, target_depth_unmapped; // bound without the depth the title passed +LONG draws_without_targets; // translated draws refused because no bind succeeded on the list (d3d12_draw.inl) +LONG state_dropped[3]; // while recording: viewports, scissors (count 0, over 16 or unreadable), blend factor unreadable // The desktop shader-visible CBV/SRV/UAV heap that owns the GPU handle's descriptor, or null. ID3D12DescriptorHeap* owning_view_heap(u64 gpu) { @@ -3334,10 +4234,13 @@ void __stdcall list_discard(Wrapper* self, u64 title_resource, const D3D12_DISCA if (first_calls(logged, 4)) log("x2w-render DiscardResource resource=%p rects=%u", static_cast(resource), region ? safe.NumRects : 0); } // List slot 50 (desktop 46 + 4), OMSetRenderTargets(count, handles, single range, depth). -// With single_range the title passes the first handle only and the rest follow it at the title's own -// descriptor stride (also for one target). A descriptor of the wrong kind, a handle that holds no view, a -// DSV with only one plane read-only (needs per-plane states), or a depth view that resolves to nothing -// refuses the whole bind: nothing is set and draws are skipped. Each refusal is logged and counted. +// With single_range the title passes only the first handle; target i is at handle + i * the title's RTV +// stride (title_descriptor_stride: for RTV heaps the same desktop increment the title reads from the +// forwarded GetDescriptorHandleIncrementSize), and each is mapped to its desktop descriptor on its own. +// A descriptor of the wrong kind, a colour handle that holds no view, a DSV with only one plane +// read-only (needs per-plane states), or a depth view that resolves to nothing refuses the whole bind: +// nothing is set and draws are skipped. Binding fewer or null targets is not done: the title's own +// pipelines expect its count and formats, and an unresolved view has no known format. void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* handles, BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* depth) { @@ -3349,47 +4252,46 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO pass.target_count = 0; pass.target0 = nullptr; pass.dsv_format = DXGI_FORMAT_UNKNOWN; - if (!list) return; + pass.dsv_read_only = false; + pass.dsv_resource = nullptr; static LONG refused, unresolved_logged; + const auto refuse = [](TargetBind why) { InterlockedIncrement(&target_binds[why]); }; + if (!list) return refuse(bind_not_recording); if (count > 8) { - InterlockedIncrement(&render_target_unresolved); if (first_calls(refused, 6)) log("x2w-d3d12 OMSetRenderTargets refused: %u render targets (at most 8)", count); - return; + return refuse(bind_count_over_8); } const UINT listed = single_range ? (count ? 1 : 0) : count; - if (listed && !x2w_local::readable(handles, listed * sizeof(*handles))) return; - UINT stride = 0; + if (listed && !x2w_local::readable(handles, listed * sizeof(*handles))) return refuse(bind_handles_unreadable); + u64 stride = 0; if (single_range && count) { const UINT increment = the_device ? device_of(the_device)->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) : 0; - stride = increment ? title_descriptor_stride(handles[0].ptr, increment) : 0; - if (!stride) { - InterlockedIncrement(&render_target_unresolved); - return; + stride = title_descriptor_stride(handles[0].ptr, increment); + UINT available = 0; + desktop_cpu_handle(handles[0].ptr, nullptr, &available); + if (!stride || available < count) { + if (first_calls(refused, 6)) + log("x2w-d3d12 OMSetRenderTargets refused: single range of %u at 0x%llx has %u descriptors left in its heap", + count, static_cast(handles[0].ptr), available); + return refuse(bind_range_past_heap); } } D3D12_CPU_DESCRIPTOR_HANDLE desktop[8]; ID3D12Resource* targets[8]{}; DXGI_FORMAT formats[8]{}; for (UINT i = 0; i < count; ++i) { - const u64 step = u64{i} * stride; - if (single_range && handles[0].ptr > (~u64{0}) - step) { - InterlockedIncrement(&render_target_unresolved); - if (first_calls(unresolved_logged, 6)) - log("x2w-d3d12 OMSetRenderTargets refused: render target %u handle overflow (0x%llx + %llu)", i, - static_cast(handles[0].ptr), static_cast(step)); - return; - } - const u64 title = single_range ? handles[0].ptr + step : handles[i].ptr; + const u64 title = single_range ? handles[0].ptr + i * stride : handles[i].ptr; desktop[i].ptr = static_cast(desktop_cpu_handle(title)); const ResolvedView view = resolve_view(desktop[i].ptr, 20); if (view.wrong_kind && first_calls(refused, 6)) log("x2w-d3d12 OMSetRenderTargets refused: render target %u is not a render target view", i); targets[i] = view.resource; if (!targets[i]) { - InterlockedIncrement(&render_target_unresolved); - if (!view.wrong_kind && first_calls(unresolved_logged, 6)) - log("x2w-d3d12 OMSetRenderTargets refused: render target %u (0x%llx) %s", i, static_cast(title), - view.skipped ? "holds a skipped view" : "holds no view"); - return; + if (view.wrong_kind) return refuse(bind_wrong_kind); + if (first_calls(refused, 6)) + log("x2w-d3d12 OMSetRenderTargets refused: render target %u of %u (title 0x%llx, %s) holds no known view", i, count, + static_cast(title), single_range ? "single range" : "array"); + InterlockedIncrement(&target_unresolved_at[i]); + return refuse(bind_unresolved); } formats[i] = view_format_of(desktop[i].ptr, targets[i]); } @@ -3398,23 +4300,24 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO ID3D12Resource* dsv_target = nullptr; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; D3D12_RESOURCE_STATES dsv_state = D3D12_RESOURCE_STATE_DEPTH_WRITE; + if (depth && !x2w_local::readable(depth, sizeof(*depth))) InterlockedIncrement(&target_depth_unreadable); if (depth && x2w_local::readable(depth, sizeof(*depth))) { const u64 resolved = desktop_cpu_handle(depth->ptr); + if (!resolved && depth->ptr) InterlockedIncrement(&target_depth_unmapped); if (!resolved) { // The handle maps to no desktop descriptor: no depth is bound although the pipeline may expect one. InterlockedIncrement(&render_target_unresolved); if (first_calls(unresolved_logged, 6)) log("x2w-d3d12 OMSetRenderTargets: depth handle 0x%llx maps to no descriptor; binding no depth", static_cast(depth->ptr)); - } else { + } + if (resolved) { const ResolvedView view = resolve_view(resolved, 21); dsv_target = view.resource; if (!dsv_target) { InterlockedIncrement(&render_target_unresolved); if (first_calls(refused, 6)) - log("x2w-d3d12 OMSetRenderTargets refused: depth handle is %s", - view.wrong_kind ? "not a depth stencil view" - : view.skipped ? "a skipped depth stencil view" : "not a known depth stencil view"); - return; + log("x2w-d3d12 OMSetRenderTargets refused: depth handle is %s", view.wrong_kind ? "not a depth stencil view" : "not a known depth stencil view"); + return refuse(view.wrong_kind ? bind_depth_wrong_kind : bind_depth_unknown); } dsv_format = view_format_of(resolved, dsv_target); const bool read_depth = (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_DEPTH) != 0; @@ -3422,14 +4325,14 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO const bool read_stencil = !format_has_stencil(dsv_format) ? read_depth : (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_STENCIL) != 0; if (read_depth != read_stencil) { if (first_calls(refused, 6)) log("x2w-d3d12 OMSetRenderTargets refused: depth stencil view with one read-only plane (flags 0x%x)", view.dsv_flags); - return; + return refuse(bind_depth_one_plane); } if (read_depth) dsv_state = D3D12_RESOURCE_STATE_DEPTH_READ; desktop_dsv.ptr = static_cast(resolved); dsv_ptr = &desktop_dsv; } } - if (!count && !dsv_ptr) return; + if (!count && !dsv_ptr) return refuse(bind_empty); if (red_producers().enabled()) { std::copy_n(targets, 8, pass.trace_targets); pass.trace_depth = dsv_target; @@ -3437,11 +4340,14 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO for (UINT i = 0; i < count; ++i) { use_as_target(self, targets[i]); pass.target_formats[i] = formats[i]; + pass.targets[i] = targets[i]; if (i == 0) pass.target0 = targets[i]; } if (dsv_target) require_state(self, dsv_target, dsv_state); pass.target_count = count; pass.dsv_format = dsv_format; + pass.dsv_read_only = dsv_state == D3D12_RESOURCE_STATE_DEPTH_READ; + pass.dsv_resource = dsv_target; const auto single_sample = [](ID3D12Resource* resource) { const auto samples = resource->GetDesc().SampleDesc; return samples.Count == 1 && !samples.Quality; @@ -3452,6 +4358,34 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO list->OMSetRenderTargets(count, count ? desktop : nullptr, FALSE, dsv_ptr); pass.targets_bound = true; InterlockedIncrement(&render_target_binds); + InterlockedIncrement(&target_binds[single_range ? bind_single_range_bound : bind_bound]); +} +void report_target_binds() +{ + LONG n[bind_outcomes], at[8]; + LONG calls = 0; + for (int i = 0; i < bind_outcomes; ++i) calls += n[i] = InterlockedExchange(&target_binds[i], 0); + for (int i = 0; i < 8; ++i) at[i] = InterlockedExchange(&target_unresolved_at[i], 0); + log("x2w-targets 300 frames: binds %ld bound %ld single-range %ld refused by reason (not recording %ld, count over 8 %ld, " + "handles unreadable %ld, range past heap %ld, wrong kind %ld, unresolved target %ld [at %ld %ld %ld %ld %ld %ld %ld %ld], " + "empty %ld, depth wrong kind %ld, depth unknown %ld, depth one read-only plane %ld), bound without depth (unreadable %ld, " + "unmapped %ld), draws without targets %ld; also dropped: clears (list closed or no colour %ld, no target %ld), " + "viewports %ld, scissors %ld, blend factor %ld", + calls, n[bind_bound] + n[bind_single_range_bound], n[bind_single_range_bound], n[bind_not_recording], + n[bind_count_over_8], n[bind_handles_unreadable], n[bind_range_past_heap], n[bind_wrong_kind], n[bind_unresolved], + at[0], at[1], at[2], at[3], at[4], at[5], at[6], at[7], n[bind_empty], n[bind_depth_wrong_kind], + n[bind_depth_unknown], n[bind_depth_one_plane], InterlockedExchange(&target_depth_unreadable, 0), + InterlockedExchange(&target_depth_unmapped, 0), InterlockedExchange(&draws_without_targets, 0), + InterlockedExchange(&clears_dropped[0], 0), InterlockedExchange(&clears_dropped[1], 0), InterlockedExchange(&state_dropped[0], 0), + InterlockedExchange(&state_dropped[1], 0), InterlockedExchange(&state_dropped[2], 0)); +} +// Fixtures: slot 50 outcome counts since the last report, in TargetBind order (bound, single-range bound, +// then the refusal reasons). Returns how many outcomes exist. +extern "C" __declspec(dllexport) unsigned x2w_d3d12_target_bind_stats(unsigned* counts, unsigned capacity) +{ + for (unsigned i = 0; counts && i < capacity && i < bind_outcomes; ++i) + counts[i] = static_cast(InterlockedCompareExchange(&target_binds[i], 0, 0)); + return bind_outcomes; } // List slots 21 / 22 / 23, RSSetViewports / RSSetScissorRects / OMSetBlendFactor. void __stdcall list_viewports(Wrapper* self, UINT count, const D3D12_VIEWPORT* viewports) @@ -3460,27 +4394,117 @@ void __stdcall list_viewports(Wrapper* self, UINT count, const D3D12_VIEWPORT* v if (auto* list = recording(self); list && count && count <= 16 && x2w_local::readable(viewports, count * sizeof(*viewports))) { list->RSSetViewports(count, viewports); pass_of(self).viewport_set = true; - } + pass_of(self).viewport0 = viewports[0]; + if (trace_frame_active) + log("x2w-frame viewport list=%p count %u: x %.1f y %.1f w %.1f h %.1f", static_cast(self), count, viewports[0].TopLeftX, + viewports[0].TopLeftY, viewports[0].Width, viewports[0].Height); + } else if (list) InterlockedIncrement(&state_dropped[0]); } void __stdcall list_scissors(Wrapper* self, UINT count, const D3D12_RECT* rects) { if (auto* list = recording(self); list && count && count <= 16 && x2w_local::readable(rects, count * sizeof(*rects))) { list->RSSetScissorRects(count, rects); pass_of(self).scissor_set = true; - } + pass_of(self).scissor0 = rects[0]; + if (trace_frame_active) + log("x2w-frame scissor list=%p count %u: %ld %ld %ld %ld", static_cast(self), count, rects[0].left, rects[0].top, rects[0].right, + rects[0].bottom); + } else if (list) InterlockedIncrement(&state_dropped[1]); } void __stdcall list_blend_factor(Wrapper* self, const float* factor) { if (auto* list = recording(self); list && x2w_local::readable(factor, 16)) list->OMSetBlendFactor(factor); + else if (list) InterlockedIncrement(&state_dropped[2]); } -// List slot 24, OMSetStencilRef(reference): list state that the stencil test of the next draws compares against. void __stdcall list_stencil_ref(Wrapper* self, UINT reference) { if (auto* list = recording(self)) { - pass_of(self).stencil_reference = reference; - list->OMSetStencilRef(reference); + pass_of(self).stencil_reference = reference; // upstream X2W_DEPTH_STATE (#2169): list state the scoped reference restores + list->OMSetStencilRef(reference & 0xFF); } } +SRWLOCK cleared_depth_lock = SRWLOCK_INIT; +std::unordered_set& cleared_depth_targets() +{ + static std::unordered_set s; + return s; +} +bool depth_target_cleared(const ID3D12Resource* resource) +{ + if (!resource) return false; + AcquireSRWLockShared(&cleared_depth_lock); + const bool found = cleared_depth_targets().count(resource) != 0; + ReleaseSRWLockShared(&cleared_depth_lock); + return found; +} +struct DepthClearValue { + float depth = 0; + UINT stencil = 0, flags = 0; + LONG frame = 0; +}; +std::unordered_map& depth_clear_values() +{ + static std::unordered_map m; + return m; +} +bool last_depth_clear(const ID3D12Resource* resource, DepthClearValue* out) +{ + if (!resource) return false; + AcquireSRWLockShared(&cleared_depth_lock); + const auto found = depth_clear_values().find(resource); + const bool known = found != depth_clear_values().end(); + if (known) *out = found->second; + ReleaseSRWLockShared(&cleared_depth_lock); + return known; +} +LONG depth_clears[5]; // [0] forwarded, [1] list not open, [2] view not a known depth view, [3] depth value outside [0, 1], [4] nothing left to clear +void __stdcall list_clear_depth(Wrapper* self, u64 handle, UINT flags, float depth, UINT stencil, UINT rect_count, const D3D12_RECT* rects) +{ + InterlockedIncrement64(&list_slot_calls[51]); + InterlockedIncrement64(&list_slot_census[51]); + InterlockedIncrement(&draw_calls_seen); + static LONG logged; + const bool log_this = first_calls(logged, 8); + auto* list = recording(self); + if (!list) return (void)InterlockedIncrement(&depth_clears[1]); + const u64 resolved = desktop_cpu_handle(handle); + const ResolvedView view = resolved ? resolve_view(resolved, 21) : ResolvedView{}; + ID3D12Resource* target = view.resource; + const DXGI_FORMAT format = target ? view_format_of(resolved, target) : DXGI_FORMAT_UNKNOWN; + UINT clear = flags & (D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL); + if (!format_has_stencil(format)) clear &= ~D3D12_CLEAR_FLAG_STENCIL; + if (log_this) + log("x2w-render ClearDepthStencilView view=0x%llx target=%p format %d flags 0x%x depth %g stencil %u rects %u", handle, + static_cast(target), static_cast(format), flags, depth, stencil & 0xFF, rect_count); + if (!target) return (void)InterlockedIncrement(&depth_clears[2]); + if ((clear & D3D12_CLEAR_FLAG_DEPTH) && !(depth >= 0.0f && depth <= 1.0f)) return (void)InterlockedIncrement(&depth_clears[3]); + if (!clear) return (void)InterlockedIncrement(&depth_clears[4]); + if (rect_count && !x2w_local::readable(rects, rect_count * sizeof(*rects))) return (void)InterlockedIncrement(&depth_clears[2]); + D3D12_RESOURCE_STATES before = D3D12_RESOURCE_STATE_COMMON; + bool known = false; + for (const auto& s : pass_of(self).states) + if (s.first == target) before = s.second, known = true; + require_state(self, target, D3D12_RESOURCE_STATE_DEPTH_WRITE); + list->ClearDepthStencilView(D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(resolved)}, static_cast(clear), depth, + static_cast(stencil & 0xFF), rect_count, rect_count ? rects : nullptr); + if (known && before != D3D12_RESOURCE_STATE_DEPTH_WRITE) require_state(self, target, before); // a read-only bind stays valid + // Only a depth clear initialises the depth plane; marked at record time, never unmarked (a freed and reused address stays marked). + if (clear & D3D12_CLEAR_FLAG_DEPTH) { + AcquireSRWLockExclusive(&cleared_depth_lock); + cleared_depth_targets().insert(target); + ReleaseSRWLockExclusive(&cleared_depth_lock); + } + { + AcquireSRWLockExclusive(&cleared_depth_lock); + DepthClearValue& v = depth_clear_values()[target]; + if (clear & D3D12_CLEAR_FLAG_DEPTH) v.depth = depth; + if (clear & D3D12_CLEAR_FLAG_STENCIL) v.stencil = stencil & 0xFF; + v.flags = clear; + v.frame = frame_number; + ReleaseSRWLockExclusive(&cleared_depth_lock); + } + InterlockedIncrement(&depth_clears[0]); +} // List slot 43 (desktop 39 + 4), set a compute root SRV backed by this recording's upload pages. void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 address) { @@ -3497,11 +4521,18 @@ void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 add } // List slot 44 (desktop 40 + 4), SetGraphicsRootShaderResourceView(parameter, title GPU address). +bool root_srv_lazy() +{ + static const bool on = x2w_local::env_on("X2W_ROOT_SRV_LAZY"); + return on; +} +LONG root_srv_deferred, root_srv_lazy_bound; +void bind_root_srv(Wrapper* self, ID3D12GraphicsCommandList* list, UINT parameter, u64 address); void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) { auto* list = recording(self); Pass& pass = pass_of(self); - if (parameter < 32) pass.srv_bound &= ~(1u << parameter); + if (parameter < 32) pass.srv_bound &= ~(1u << parameter), pass.srv_pending &= ~(1u << parameter); if (parameter < 16) pass.root_address[parameter] = address; // Under a deferred heap-indexed root the desktop list holds another root signature; only the title address is kept. if (!list || !pass.root || pass.root_heap_flags || parameter >= pass.root->size() || parameter >= 32 || @@ -3515,6 +4546,34 @@ void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) pass.srv_bound |= 1u << parameter; return; } + if (root_srv_lazy() && parameter < 16) { + pass.srv_pending |= 1u << parameter; + const LONG n = InterlockedIncrement(&root_srv_deferred); + if (n == 1) log("x2w-render X2W_ROOT_SRV_LAZY=1: root SRVs are copied at a real-pipeline draw only"); + return; + } + bind_root_srv(self, list, parameter, address); +} +// X2W_ROOT_SRV_LAZY: before a draw on a real desktop pipeline, the root SRVs set since the root signature +// was bound and not copied yet. +void bind_lazy_root_srvs(Wrapper* self, ID3D12GraphicsCommandList* list) +{ + if (!root_srv_lazy()) return; + Pass& pass = pass_of(self); + if (!pass.root) return; + for (UINT p = 0; p < 16 && p < pass.root->size(); ++p) + if ((pass.srv_pending & (1u << p)) && (*pass.root)[p].type == D3D12_ROOT_PARAMETER_TYPE_SRV && pass.root_address[p]) { + pass.srv_pending &= ~(1u << p); + bind_root_srv(self, list, p, pass.root_address[p]); + const LONG n = InterlockedIncrement(&root_srv_lazy_bound); + if (x2w_local::first_of(n, 3)) + log("x2w-render X2W_ROOT_SRV_LAZY: root SRV %u copied at a real-pipeline draw (%ld so far; %ld calls deferred)", p, n, + root_srv_deferred); + } +} +void bind_root_srv(Wrapper* self, ID3D12GraphicsCommandList* list, UINT parameter, u64 address) +{ + Pass& pass = pass_of(self); const std::size_t bytes = readable_window(address, 0x10000); const D3D12_GPU_VIRTUAL_ADDRESS desktop = bytes ? upload_from_title(address, bytes) : 0; static LONG logged; @@ -3527,6 +4586,98 @@ void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) list->SetGraphicsRootShaderResourceView(parameter, desktop); pass.srv_bound |= 1u << parameter; } +LONG indirect_calls_local; +struct IndirectCall { + const void* signature; + int path; + const void* base; + const unsigned char* record; + UINT stride; + UINT type; + bool nonzero_at_record; +}; +SRWLOCK indirect_lock = SRWLOCK_INIT; +std::vector& indirect_trace() +{ + static std::vector calls; + return calls; +} +void indirect_execute(Wrapper* self, void* signature, UINT max_count, Wrapper* arguments, u64 offset, Wrapper* count_resource, u64 count_offset); +void record_trace_indirect(Wrapper* self, UINT type, UINT stride, UINT max_count, Wrapper* arguments, u64 offset); +void record_trace_dispatch(Wrapper* self, u64 key, UINT x, UINT y, UINT z, bool executed, int outcome); +void record_trace_report(ID3D12CommandQueue* queue); +void record_trace_mesh_read(u64 key, UINT srv, int source, int a, int b, u64 address, u64 bytes); // d3d12_draw.inl, mesh calls +void record_trace_mesh_heap(Wrapper* self, const Translation& tr); +void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT max_count, Wrapper* arguments, u64 offset, + Wrapper* count_resource, u64 count_offset) +{ + InterlockedIncrement(&indirect_calls_local); + indirect_execute(self, signature, max_count, arguments, offset, count_resource, count_offset); + if (!trace_frame_active) return; + SignatureInfo info; + AcquireSRWLockShared(&signature_lock); + const auto found = signature_infos().find(signature); + if (found != signature_infos().end()) info = found->second; + ReleaseSRWLockShared(&signature_lock); + IndirectCall call{}; + call.signature = signature; + call.stride = info.stride; + call.type = info.args.empty() ? ~0u : static_cast(info.args.back().Type); + const PipelineInfo* pipeline = pass_of(self).pipeline ? pipeline_info(pass_of(self).pipeline) : nullptr; + call.path = pipeline ? pipeline->path : -1; + call.base = arguments && arguments->own().kind == resource_kind ? arguments->own().title_memory : nullptr; + call.record = call.base ? static_cast(call.base) + offset : nullptr; + const UINT bytes = info.stride && info.stride <= 64 ? info.stride : 12; + if (call.record && x2w_local::readable(call.record, bytes)) + for (UINT i = 0; i < bytes; ++i) call.nonzero_at_record |= call.record[i] != 0; + else + call.record = nullptr; + (void)max_count; + (void)count_resource; + (void)count_offset; + AcquireSRWLockExclusive(&indirect_lock); + indirect_trace().push_back(call); + ReleaseSRWLockExclusive(&indirect_lock); + record_trace_indirect(self, call.type, info.stride, max_count, arguments, offset); +} +void summarise_indirect_calls() +{ + record_trace_report(nullptr); + AcquireSRWLockExclusive(&indirect_lock); + std::vector calls; + calls.swap(indirect_trace()); + ReleaseSRWLockExclusive(&indirect_lock); + struct Group { + int calls = 0, unreadable = 0, nonzero_at_record = 0, nonzero_at_end = 0; + UINT stride = 0, type = 0; + std::uint32_t sample[4] = {}; + }; + std::map, Group> groups; + for (const auto& c : calls) { + Group& g = groups[{c.signature, c.path, c.base}]; + ++g.calls; + g.stride = c.stride; + g.type = c.type; + if (!c.record) { + ++g.unreadable; + continue; + } + const UINT bytes = c.stride && c.stride <= 64 ? c.stride : 12; + bool nonzero = false; + if (x2w_local::readable(c.record, bytes)) + for (UINT i = 0; i < bytes; ++i) nonzero |= c.record[i] != 0; + g.nonzero_at_record += c.nonzero_at_record; + if (nonzero) { + if (!g.nonzero_at_end) std::memcpy(g.sample, c.record, bytes < 16 ? bytes : 16); + ++g.nonzero_at_end; + } + } + log("x2w-frame indirect summary: %zu calls, %zu groups (signature, pipeline creation path, argument resource)", calls.size(), groups.size()); + for (const auto& [key, g] : groups) + log("x2w-frame indirect group sig %p type %u stride %u path %d args %p: calls %d, unreadable %d, non-zero at record %d, at end %d, sample %08x %08x %08x %08x", + std::get<0>(key), g.type, g.stride, std::get<1>(key), std::get<2>(key), g.calls, g.unreadable, g.nonzero_at_record, + g.nonzero_at_end, g.sample[0], g.sample[1], g.sample[2], g.sample[3]); +} // List slot 42 (desktop 38 + 4), SetGraphicsRootConstantBufferView(parameter, title GPU address). // A translated shader reads a root CBV through the same pointer source as a root SRV (root_address). Nothing // is forwarded to the desktop list and srv_bound is left alone: bit 0 means a vertex-fetch SRV is bound. @@ -3546,15 +4697,30 @@ void __stdcall list_root_cbv(Wrapper* self, UINT parameter, u64 address) pass.root_address[parameter] = (address && readable_window(address, 1)) ? address : 0; } extern LONG translated_draws, untranslated_draws, frame_number; +bool indirect_pending(Wrapper* self); +bool indirect_draw_issue(Wrapper* self, ID3D12GraphicsCommandList* list, bool indexed); +void indirect_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z); +void mesh_note57(const void* desc, const Wrapper* self); bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance); +extern thread_local u64 last_draw_key; +extern thread_local const char* last_draw_why; +extern thread_local u64 last_draw_key; +extern thread_local const char* last_draw_why; // List slot 12, DrawInstanced. void __stdcall list_draw(Wrapper* self, UINT vertices, UINT instances, UINT first_vertex, UINT first_instance) { auto* list = recording(self); Pass& pass = pass_of(self); if (list && !pass.pipeline_real) { - InterlockedIncrement(draw_translated(self, false, vertices, instances, first_vertex, 0, first_instance) ? &translated_draws - : &untranslated_draws); + const bool done = draw_translated(self, false, vertices, instances, first_vertex, 0, first_instance); + InterlockedIncrement(done ? &translated_draws : &untranslated_draws); + if (trace_frame_active) { + note_traced_target(self, pass.target0, done); + const D3D12_RESOURCE_DESC rd = pass.target0 ? pass.target0->GetDesc() : D3D12_RESOURCE_DESC{}; + log("x2w-frame draw %u %s target %p %llux%u fmt %d topology 0x%x key %016llx %s", vertices, done ? "drawn" : "NOT drawn", + static_cast(pass.target0), static_cast(rd.Width), rd.Height, rd.Format, pass.topology, + last_draw_key, done ? "" : (last_draw_why ? last_draw_why : "draw failed")); + } return; } if (list && pass.root_heap_flags) { @@ -3577,15 +4743,24 @@ void __stdcall list_draw(Wrapper* self, UINT vertices, UINT instances, UINT firs list->SetGraphicsRootSignature(pass.deferred_root); } // The translated vertex shaders read their fetch table through root parameter 0. - if (list && pass.pipeline_real && pass.targets_bound && pass.topology_ok && pass.topology != 0x11 && (pass.srv_bound & 1)) { + if (list && pass.pipeline_real) bind_lazy_root_srvs(self, list); + const bool real_drawn = list && pass.pipeline_real && pass.targets_bound && pass.topology_ok && pass.topology != 0x11 && (pass.srv_bound & 1); + if (real_drawn) { const auto red_samples = red_producer_draw_before(self, list, "native-draw", 0); list->DrawInstanced(vertices, instances, first_vertex, first_instance); red_producer_draw_after(self, red_samples); const LONG n = InterlockedIncrement(&render_draws); - if (n > 0 && n <= 3) log("x2w-render DrawInstanced(%u, %u, %u, %u) recorded", vertices, instances, first_vertex, first_instance); + if (x2w_local::first_of(n, 3)) log("x2w-render DrawInstanced(%u, %u, %u, %u) recorded", vertices, instances, first_vertex, first_instance); } else { InterlockedIncrement(&render_draws_skipped); } + if (trace_frame_active) { + note_traced_target(self, pass.target0, real_drawn); + const D3D12_RESOURCE_DESC rd = pass.target0 ? pass.target0->GetDesc() : D3D12_RESOURCE_DESC{}; + log("x2w-frame draw %u %s target %p %llux%u fmt %d topology 0x%x desktop pipeline%s", vertices, real_drawn ? "drawn" : "NOT drawn", + static_cast(pass.target0), static_cast(rd.Width), rd.Height, rd.Format, pass.topology, + real_drawn ? "" : !list ? ": not recording" : !pass.pipeline_real ? ": no pipeline" : ": state (targets/topology/srv 0)"); + } } extern SRWLOCK written_lock; @@ -3598,6 +4773,427 @@ std::unordered_map& written_textures(); ID3D12Resource* sampled_address_texture(Wrapper* resource); bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); #include "startup_stubs/d3d12_draw.inl" +#include "startup_stubs/d3d12_regblob.inl" + + +LONG frame_dispatches; +std::unordered_map>& compute_regs() { static std::unordered_map> m; return m; } +SRWLOCK compute_lock = SRWLOCK_INIT; +std::unordered_map& compute_keys() { static std::unordered_map m; return m; } +D3D12_GPU_VIRTUAL_ADDRESS desktop_va(u64 address); +void note_window(ID3D12Resource* buffer); +bool execute_translated(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, UINT x, UINT y, UINT z); +bool rawaddr_pipeline(u64 key, Wrapper* root, Wrapper* pipeline); // d3d12_rawaddr.inl +bool rawaddr_dispatch(Wrapper* self, ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z); // d3d12_rawaddr.inl +SRWLOCK compute_pso_lock = SRWLOCK_INIT; +std::unordered_map& compute_psos() +{ + static std::unordered_map m; + return m; +} +LONG compute_executed, compute_skipped_args; +enum ComputeOutcome { co_c62_run, co_c62_table_arg, co_c62_unmapped, co_c67_run, co_c67_off, co_c67_other_key, co_c67_untranslated, + co_c67_heap, co_not_run, co_cx_skip, co_rawaddr_run, co_c67_unresolved, co_c67_compiling /* X2W_CX_ASYNC */, co_count }; +LONG compute_outcomes[co_count]; // compute_lock; counted with the per-key count by execute_dispatch +thread_local int dispatch_outcome; // set on this thread by the path that handled the dispatch + +struct IssuedDispatch { u64 key; UINT x, y, z; char path; bool indirect; }; +struct IssuedList { std::vector current, previous; }; +thread_local u64 cx_issue_key; // set by execute_dispatch for indirect_dispatch +thread_local char cx_issue_path; // 'c' slot-62 desktop pipeline, 't' translated, 'r' raw-address +SRWLOCK issued_lock = SRWLOCK_INIT; +constexpr std::size_t issued_cap = 16384; // per recording +std::unordered_map& issued_lists() { static std::unordered_map m; return m; } +const void* issued_id(ID3D12GraphicsCommandList* list) { return static_cast(static_cast(list)); } +void note_issued_dispatch(ID3D12GraphicsCommandList* list, UINT x, UINT y, UINT z, bool indirect) +{ + AcquireSRWLockExclusive(&issued_lock); + std::vector& v = issued_lists()[issued_id(list)].current; + if (v.size() < issued_cap) v.push_back({cx_issue_key, x, y, z, cx_issue_path, indirect}); + ReleaseSRWLockExclusive(&issued_lock); +} +void forget_list_dispatches(ID3D12GraphicsCommandList* list) +{ + AcquireSRWLockExclusive(&issued_lock); + const auto found = issued_lists().find(issued_id(list)); + if (found != issued_lists().end()) { + found->second.previous.swap(found->second.current); + found->second.current.clear(); + } + ReleaseSRWLockExclusive(&issued_lock); +} +const char* issued_path_name(char path) +{ + return path == 'c' ? "slot-62" : path == 't' ? "translated" : path == 'r' ? "raw-address" : path == 'g' ? "indirect guard pass" : path == 'b' ? "GPU buffer copy (draw-rt)" : "?"; +} +// For one incomplete DRED list: the dispatch at op `done` (the Dispatch ops before it are counted from the op +// types, so the barriers between dispatches need no fixed stride) and the five before and after it. +void report_dred_dispatches(const D3D12_AUTO_BREADCRUMB_NODE* node, UINT done) +{ + if (!node->pCommandList || !node->pCommandHistory) return; + UINT before = 0, total = 0; // Dispatch ops before op `done`, and in the whole list + for (UINT i = 0; i < node->BreadcrumbCount; ++i) + if (node->pCommandHistory[i] == D3D12_AUTO_BREADCRUMB_OP_DISPATCH) { + if (i < done) ++before; + ++total; + } + const bool at_dispatch = done < node->BreadcrumbCount && node->pCommandHistory[done] == D3D12_AUTO_BREADCRUMB_OP_DISPATCH; + std::vector current, previous; + AcquireSRWLockShared(&issued_lock); + const auto found = issued_lists().find(issued_id(node->pCommandList)); + if (found != issued_lists().end()) current = found->second.current, previous = found->second.previous; + ReleaseSRWLockShared(&issued_lock); + const auto direct_of = [](const std::vector& v) { + std::vector out; + for (const IssuedDispatch& d : v) + if (!d.indirect) out.push_back(d); + return out; + }; + std::vector direct = direct_of(current); + const char* which = "current recording"; + if (direct.size() != total) { + std::vector older = direct_of(previous); + if (older.size() == total) direct.swap(older), which = "previous recording"; + } + const bool match = direct.size() == total; + log("x2w-dred dispatches list %p: op %u is %s; %u Dispatch ops before it, %u in the list; %zu direct dispatches in the %s " + "(%zu recorded now, %zu before the last Reset)%s", + static_cast(node->pCommandList), done, at_dispatch ? "a Dispatch" : "not a Dispatch", before, total, direct.size(), + which, current.size(), previous.size(), match ? "" : "; COUNT MISMATCH, the mapping below is not reliable"); + if (direct.empty()) return; + const std::size_t at = before < direct.size() ? before : direct.size() - 1; + const std::size_t from = at > 5 ? at - 5 : 0, to = at + 6 < direct.size() ? at + 6 : direct.size(); + for (std::size_t i = from; i < to; ++i) + log("x2w-dred %s dispatch %zu: key %016llx (%u, %u, %u) %s", i == at && at_dispatch ? ">>" : " ", i, direct[i].key, + direct[i].x, direct[i].y, direct[i].z, issued_path_name(direct[i].path)); +} + +bool cx_skip_key(u64 key) +{ + static const std::vector keys = [] { + std::vector out; + char value[2048]{}; + const DWORD n = GetEnvironmentVariableA("X2W_CX_SKIP", value, sizeof(value)); + if (!n || n >= sizeof(value)) return out; + for (const char* p = value; *p;) { + char* end = nullptr; + const u64 k = std::strtoull(p, &end, 16); + if (end == p) { + ++p; + continue; + } + out.push_back(k); + p = end; + } + log("x2w-cx X2W_CX_SKIP: %zu keys", out.size()); + for (const u64 k : out) log("x2w-cx X2W_CX_SKIP key %016llx", k); + return out; + }(); + if (keys.empty()) return false; + return std::find(keys.begin(), keys.end(), key) != keys.end(); +} +LONG compute_root_same, compute_root_changed; +void __stdcall list_compute_root(Wrapper* self, Wrapper* root) +{ + static const bool always_reset = x2w_local::env_on("X2W_CX_ROOT_RESET"); // the old behaviour + Pass& pass = pass_of(self); + if (root && root == pass.compute_root && !always_reset) { + InterlockedIncrement(&compute_root_same); + return; + } + InterlockedIncrement(&compute_root_changed); + pass.compute_root = root; + for (auto& k : pass.compute_kind) k = 0; + for (auto& s : pass.compute_set) s = 0; +} +// slot 35, SetComputeRootDescriptorTable(parameter, handle): not replayed (the executed shaders use none). +void __stdcall list_compute_table(Wrapper* self, UINT parameter, u64 gpu_handle) +{ + if (parameter >= 16) return; + u64 address = 0; // the table's address in the title's descriptor memory (as list_table) + AcquireSRWLockShared(¬e_lock); + for (const HeapInfo& heap : heap_infos()) + if (heap.desktop_gpu && heap.title_cpu && gpu_handle >= heap.desktop_gpu && gpu_handle < heap.desktop_gpu + u64{heap.count} * heap.increment) + address = heap.title_cpu + (gpu_handle - heap.desktop_gpu); + ReleaseSRWLockShared(¬e_lock); + pass_of(self).compute_kind[parameter] = 5; + pass_of(self).compute_address[parameter] = address; + pass_of(self).compute_set[parameter] = 0; +} +// slot 37, SetComputeRoot32BitConstant(parameter, value, offset) +void __stdcall list_compute_constant(Wrapper* self, UINT parameter, UINT value, UINT offset) +{ + Pass& pass = pass_of(self); + if (parameter >= 16 || offset >= 16) return; + if (pass.compute_kind[parameter] != 1) pass.compute_set[parameter] = 0; + pass.compute_kind[parameter] = 1; + pass.compute_constants[parameter][offset] = value; + pass.compute_set[parameter] |= static_cast(1u << offset); + if (offset + 1 > pass.compute_count[parameter]) pass.compute_count[parameter] = offset + 1; +} +// slot 39, SetComputeRoot32BitConstants(parameter, count, data, offset) +void __stdcall list_compute_constants(Wrapper* self, UINT parameter, UINT count, const void* data, UINT offset) +{ + Pass& pass = pass_of(self); + if (parameter >= 16 || offset >= 16 || !data || !x2w_local::readable(data, std::size_t{count} * 4)) return; + if (offset + count > 16) count = 16 - offset; + if (pass.compute_kind[parameter] != 1) pass.compute_set[parameter] = 0; + pass.compute_kind[parameter] = 1; + std::memcpy(&pass.compute_constants[parameter][offset], data, std::size_t{count} * 4); + for (UINT i = 0; i < count; ++i) pass.compute_set[parameter] |= static_cast(1u << (offset + i)); + if (offset + count > pass.compute_count[parameter]) pass.compute_count[parameter] = offset + count; +} +void compute_root_descriptor(Wrapper* self, UINT parameter, u64 address, int kind) +{ + Pass& pass = pass_of(self); + if (parameter >= 16) return; + pass.compute_kind[parameter] = kind; + pass.compute_address[parameter] = address; + pass.compute_set[parameter] = 0; +} +void __stdcall list_compute_cbv(Wrapper* self, UINT parameter, u64 address) { compute_root_descriptor(self, parameter, address, 2); } +void __stdcall list_compute_srv(Wrapper* self, UINT parameter, u64 address) { compute_root_descriptor(self, parameter, address, 3); } +void __stdcall list_compute_uav(Wrapper* self, UINT parameter, u64 address) { compute_root_descriptor(self, parameter, address, 4); } + +// Runs a dispatch through a desktop compute pipeline when one exists for the bound pipeline. +bool execute_dispatch_inner(Wrapper* self, UINT x, UINT y, UINT z, u64 key) +{ + static const bool enabled = !x2w_local::env_on("X2W_COMPUTE_OFF"); + if (cx_skip_key(key)) { + dispatch_outcome = co_cx_skip; + static LONG logged; + if (first_calls(logged, 8)) log("x2w-cx dispatch of key %016llx skipped (X2W_CX_SKIP)", key); + return false; + } + auto* list = recording(self); + Pass& pass = pass_of(self); + if (!enabled || !list || !pass.pipeline) { + dispatch_outcome = co_not_run; + return false; + } + cx_issue_key = key; + cx_issue_path = 'r'; + if (rawaddr_dispatch(self, list, x, y, z)) { + dispatch_outcome = co_rawaddr_run; + return true; + } + cx_issue_path = 't'; + if (!pass.compute_root || !pass.compute_root->own().real) return execute_translated(self, list, key, x, y, z); + AcquireSRWLockShared(&compute_pso_lock); + const auto found = compute_psos().find(pass.pipeline); + ID3D12PipelineState* pso = found != compute_psos().end() ? found->second : nullptr; + ReleaseSRWLockShared(&compute_pso_lock); + if (!pso) return execute_translated(self, list, key, x, y, z); + cx_issue_path = 'c'; + D3D12_GPU_VIRTUAL_ADDRESS addresses[16] = {}; + for (UINT i = 0; i < 16; ++i) { + const int kind = pass.compute_kind[i]; + if (kind == 5) { + InterlockedIncrement(&compute_skipped_args); + dispatch_outcome = co_c62_table_arg; + return false; + } + if (kind >= 2 && kind <= 4) { + addresses[i] = desktop_va(pass.compute_address[i]); + if (!addresses[i] && pass.compute_address[i]) { + InterlockedIncrement(&compute_skipped_args); + dispatch_outcome = co_c62_unmapped; + return false; + } + } + } + list->SetPipelineState(pso); + list->SetComputeRootSignature(static_cast(pass.compute_root->own().real)); + for (UINT i = 0; i < 16; ++i) { + switch (pass.compute_kind[i]) { + case 1: list->SetComputeRoot32BitConstants(i, pass.compute_count[i], pass.compute_constants[i], 0); break; + case 2: list->SetComputeRootConstantBufferView(i, addresses[i]); break; + case 3: list->SetComputeRootShaderResourceView(i, addresses[i]); break; + case 4: list->SetComputeRootUnorderedAccessView(i, addresses[i]); break; + default: break; + } + } + gpu_time::mark(self, list, gpu_time::c_c62, key, false); + indirect_dispatch(self, list, x, y, z); + gpu_time::mark(self, list, gpu_time::c_c62, key, true); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + const LONG n = InterlockedIncrement(&compute_executed); + dispatch_outcome = co_c62_run; + if (x2w_local::first_of(n, 4) || n % 5000 == 0) log("x2w-compute dispatch %ld executed (%u, %u, %u)", n, x, y, z); + return true; +} +struct DispatchCount { LONG64 calls = 0; LONG64 groups = 0; UINT x = 0, y = 0, z = 0; }; +std::unordered_map& dispatch_counts() { static std::unordered_map m; return m; } +bool execute_dispatch(Wrapper* self, UINT x, UINT y, UINT z, u64 key) +{ + dispatch_outcome = co_not_run; + const bool executed = execute_dispatch_inner(self, x, y, z, key); + const int outcome = dispatch_outcome >= 0 && dispatch_outcome < co_count ? dispatch_outcome : co_not_run; + if (trace_frame_active) record_trace_dispatch(self, key, x, y, z, executed, outcome); + AcquireSRWLockExclusive(&compute_lock); + DispatchCount& count = dispatch_counts()[key]; + ++count.calls; + count.groups += LONG64{x} * y * z; + if (x | y | z) count.x = x, count.y = y, count.z = z; + ++compute_outcomes[outcome]; + ReleaseSRWLockExclusive(&compute_lock); + return executed; +} +LONG c67_checked, c67_sets_done, c67_parts_written, c67_incomplete, c67_failed; // this run +void complete_c67_request(u64 key, Wrapper* pipeline, const PipelineInfo* info, const void* code, u64 code_bytes, const void* meta, + u64 meta_bytes, const std::vector& root_blob) +{ + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_set keys; // handled this run + wchar_t path[MAX_PATH]; + if (!cache_path(path, L"req_c67_", key, L".done")) return; + AcquireSRWLockExclusive(&lock); + const bool fresh = keys.insert(key).second; + ReleaseSRWLockExclusive(&lock); + if (!fresh || GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) return; + InterlockedIncrement(&c67_checked); + std::vector regs; + AcquireSRWLockShared(&compute_lock); + if (const auto found = compute_regs().find(pipeline); found != compute_regs().end()) regs = found->second; + ReleaseSRWLockShared(&compute_lock); + const bool have_meta = meta_bytes && meta_bytes <= 0x10000 && x2w_local::readable(meta, meta_bytes); + struct Part { const wchar_t* ext; const void* data; std::size_t bytes; bool available; }; + const Part parts[] = { + {L".cs", code, static_cast(code_bytes), true}, + {L".meta", meta, have_meta ? static_cast(meta_bytes) : 0, have_meta}, + {L".root", root_blob.data(), root_blob.size(), true}, + {L".desc", info->desc.data(), info->desc.size(), true}, + {L".regs", regs.data(), regs.size(), !regs.empty()}, + }; + int present = 0, written = 0; + bool failed = false; + for (const Part& part : parts) { + WIN32_FILE_ATTRIBUTE_DATA a{}; + if (!cache_path(path, L"req_c67_", key, part.ext)) return; + const bool on_disk = GetFileAttributesExW(path, GetFileExInfoStandard, &a); + const u64 size = (u64{a.nFileSizeHigh} << 32) | a.nFileSizeLow; + if (on_disk && (!part.available || size == part.bytes)) { + ++present; + continue; + } + if (!part.available) continue; + if (regblob::write_whole(path, part.data, part.bytes)) ++present, ++written; + else failed = true; + } + InterlockedAdd(&c67_parts_written, written); + const bool whole = present == static_cast(std::size(parts)); + static const char marker[] = "ok\n"; + if (whole && cache_path(path, L"req_c67_", key, L".done") && regblob::write_whole(path, marker, 3)) InterlockedIncrement(&c67_sets_done); + else InterlockedIncrement(failed ? &c67_failed : &c67_incomplete); // retried by the next run + static LONG logged; + if ((written || !whole) && first_calls(logged, 6)) + log("x2w-cx request %016llx: %d of 5 parts on disk, %d written now%s", key, present, written, + whole ? ", .done written" : failed ? ", a write failed (no .done)" : ", no .regs or .meta yet (no .done)"); +} +// The compute key of the pipeline bound on list self (also used by indirect dispatches). +u64 compute_key_for(Wrapper* pipeline); +bool prewarm_enabled(); // d3d12_compute.inl +bool prewarm_compute(u64 key, bool front = false); +u64 compute_key_of(Wrapper* self) +{ + Pass& pass = pass_of(self); + u64 key = ~0ull; // no compute pipeline bound + AcquireSRWLockExclusive(&compute_lock); + if (pass.pipeline) { + const auto found = compute_keys().find(pass.pipeline); + key = found != compute_keys().end() ? found->second : ~1ull; // ~1: no compute key known for it + } + ReleaseSRWLockExclusive(&compute_lock); + return key == ~1ull ? compute_key_for(pass.pipeline) : key; +} +// The compute key of a pipeline, derived from its creation description and remembered in compute_keys() +// (also at creation, for the background prewarm in d3d12_compute.inl). +u64 compute_key_for(Wrapper* pipeline) +{ + u64 key = ~1ull; + { + // Device slot 67: a console compute pipeline. Its description has the layout of slot 57: + // [0] root signature, [5]/[6] machine code address and length, [7]/[8] the stage's metadata. + // The key is fnv(root blob, fnv(code)), tagged with 0x67 in the top byte; the code, metadata + // and root blob are written to the shader cache as req_c67_.{cs,meta,root,desc,regs}, then .done + // (complete_c67_request). + const PipelineInfo* info = pipeline_info(pipeline); + if (info && info->path == 67 && info->desc.size() >= 0x48) { + u64 words[9]; + std::memcpy(words, info->desc.data(), sizeof(words)); + std::vector root_blob; + if (Wrapper* root = as_wrapper(reinterpret_cast(words[0]))) { + AcquireSRWLockShared(¬e_lock); + const auto found = root_blobs().find(root); + if (found != root_blobs().end()) root_blob = found->second; + ReleaseSRWLockShared(¬e_lock); + } + const auto* code = reinterpret_cast(words[5]); + const auto* meta = reinterpret_cast(words[7]); + if (words[6] && words[6] <= (1u << 20) && x2w_local::readable(code, words[6])) { + key = (fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(code, words[6])) & 0x00ffffffffffffffull) | (0x67ull << 56); + complete_c67_request(key, pipeline, info, code, words[6], meta, words[8], root_blob); + } else { + key = 0x67ull << 56; // code unreadable + } + } else if (info) { + key = (0xeeull << 56) | static_cast(info->path); // another creation path + } + AcquireSRWLockExclusive(&compute_lock); + compute_keys()[pipeline] = key; + ReleaseSRWLockExclusive(&compute_lock); + } + return key; +} +void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) +{ + const u64 key = compute_key_of(self); + InterlockedIncrement(&frame_dispatches); + const bool executed = execute_dispatch(self, x, y, z, key); + if (trace_frame_active) log("x2w-frame dispatch %016llx (%u, %u, %u)%s", key, x, y, z, executed ? " executed" : ""); +} +void report_dispatches() +{ + std::vector> all; + AcquireSRWLockExclusive(&compute_lock); + LONG o[co_count]; + for (const auto& entry : dispatch_counts()) all.push_back(entry); + dispatch_counts().clear(); + for (int i = 0; i < co_count; ++i) o[i] = compute_outcomes[i], compute_outcomes[i] = 0; // the keys' window + ReleaseSRWLockExclusive(&compute_lock); + std::sort(all.begin(), all.end(), [](const auto& a, const auto& b) { return a.second.calls > b.second.calls; }); + static const char prefix[] = "x2w-render dispatches per compute key (300 frames):"; + // log() cuts a line at 1533 characters (its 1536-byte buffer): stay below it, or the tail keys are lost. + char line[1400]; + int n = std::snprintf(line, sizeof(line), "%s", prefix), lines = 0; + for (const auto& entry : all) { + if (n > static_cast(sizeof(line)) - 80) { + log("%s", line); + ++lines; + n = std::snprintf(line, sizeof(line), "%s", prefix); + } + wchar_t path[MAX_PATH]; + const bool signed_ready = cache_path(path, L"", entry.first, L".cs.dxbc") && GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; + n += std::snprintf(line + n, sizeof(line) - n, " %016llx%s:%lld(%u,%u,%u)", entry.first, signed_ready ? "*" : "", + entry.second.calls, entry.second.x, entry.second.y, entry.second.z); + } + log("%s", line); + ++lines; + log("x2w-render dispatch keys (300 frames): %zu keys in %d lines", all.size(), lines); + log("x2w-compute dispatches (300 frames): executed %ld skipped %ld; slot-62 desktop pipeline executed %ld skipped %ld " + "(table argument %ld, unmapped root address %ld); translated executed %ld skipped %ld (X2W_CX_OFF %ld, not a slot-67 key %ld, " + "no translation %ld, heap or vinfo %ld); not run %ld (no list or pipeline, or X2W_COMPUTE_OFF); X2W_CX_SKIP skipped %ld; raw-address executed %ld; translated skipped, entry value unresolved %ld; translated skipped while compiling (X2W_CX_ASYNC) %ld", + o[co_c62_run] + o[co_c67_run] + o[co_rawaddr_run], o[co_c62_table_arg] + o[co_c62_unmapped] + o[co_c67_off] + o[co_c67_other_key] + o[co_c67_untranslated] + o[co_c67_heap] + o[co_cx_skip] + o[co_c67_unresolved] + o[co_c67_compiling], + o[co_c62_run], o[co_c62_table_arg] + o[co_c62_unmapped], o[co_c62_table_arg], o[co_c62_unmapped], o[co_c67_run], + o[co_c67_off] + o[co_c67_other_key] + o[co_c67_untranslated] + o[co_c67_heap], o[co_c67_off], o[co_c67_other_key], o[co_c67_untranslated], + o[co_c67_heap], o[co_not_run], o[co_cx_skip], o[co_rawaddr_run], o[co_c67_unresolved], o[co_c67_compiling]); + if (c67_checked) + log("x2w-cx requests (this run): %ld keys without .done checked, %ld sets completed (.done written), %ld parts written, " + "%ld incomplete (no .meta or .regs at creation), %ld with a failed write; incomplete ones are retried next run", + c67_checked, c67_sets_done, c67_parts_written, c67_incomplete, c67_failed); +} #include "startup_stubs/mesh86_cache.inl" #include "startup_stubs/d3d12_compute_binding_trace.inl" #include "startup_stubs/list_copy_texture.inl" @@ -3613,7 +5209,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) std::vector ready; std::vector submitted; // Pin the closed recording and its allocator through submission bookkeeping. - AcquireSRWLockExclusive(&draw_lock); + lock_draw(0 + __LINE__); AcquireSRWLockExclusive(&allocator_lock); for (UINT i = 0; i < count; ++i) { Wrapper* w = as_wrapper(lists[i]); @@ -3626,6 +5222,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) bool split = false; const auto submit = [&](const auto& native_lists, const auto& wrappers) { const UINT ready_count = static_cast(native_lists.size()); + if (range_watch_count()) range_watch_sample("submit"); red_producers().execute(queue, native_lists, [&] { if (draw_dump_frame()) { const HRESULT hr = draw_dumps().execute(queue, ready_count, native_lists.data()); @@ -3661,6 +5258,13 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) submit(ready, submitted); } ReleaseSRWLockExclusive(&allocator_lock); + if (!ready.empty()) { + memcut_reap(); + ring_submitted(submitted); + gpu_time::submitted(static_cast(self->own().real), submitted); + static const bool srv_report_submits = x2w_local::env_on("X2W_DRAW_SRV_STATS_SUBMITS"); + if (srv_report_submits) report_srv_copies(); + } ReleaseSRWLockExclusive(&draw_lock); check_device("CommandQueue execute", 35); return; @@ -3770,6 +5374,10 @@ __declspec(noinline) u64 queue_dynamic(Wrapper* self, u64 rdx, u64 r8, u64 r9) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, name, N & 0xFF, reinterpret_cast(self), rdx, r8, r9, _ReturnAddress()); } + if (noop_census_enabled()) { + const u64 args[8] = {reinterpret_cast(self), rdx, r8, r9, 0, 0, 0, 0}; + noop_census_note(queue_kind, N, args, reinterpret_cast(_ReturnAddress()) - reinterpret_cast(GetModuleHandleW(nullptr))); + } if (log_it) { char name[64]; std::snprintf(name, sizeof(name), "CommandQueue::slot%d", N); @@ -4018,6 +5626,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) const u64 title_dest = args[D]; args[D] = desktop_cpu_handle(args[D]); if (!args[D]) { + if (noop_census_enabled()) noop_census_dropped_view(N, title_dest); if constexpr (N == 18) retire_leave_class(reinterpret_cast(a), RetireLeft::view); return 0; } @@ -4073,7 +5682,26 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) std::memcpy(desc_copy, &mapped, sizeof(mapped)); args[desc_index] = reinterpret_cast(desc_copy); } + if (N == 18) { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + std::memcpy(&view, desc_copy, sizeof(view)); + const D3D12_SHADER_RESOURCE_VIEW_DESC before = view; + fix_srv(view, reinterpret_cast(args[0])); + if (std::memcmp(&view, &before, sizeof(view)) != 0) { + std::memcpy(desc_copy, &view, sizeof(view)); + args[desc_index] = reinterpret_cast(desc_copy); + static LONG planes; + if (first_calls(planes, 4)) log("x2w-d3d12 Device::slot18 view format %d: plane slice set for the depth-stencil plane", view.Format); + } + } } + // A typeless depth texture (typeless_depth_family) needs a description; the title passed none. + D3D12_SHADER_RESOURCE_VIEW_DESC default_srv{}; + D3D12_DEPTH_STENCIL_VIEW_DESC default_dsv{}; + if (N == 18 && args[0] && !args[1] && default_depth_srv(reinterpret_cast(args[0]), default_srv)) + args[1] = reinterpret_cast(&default_srv); + if (N == 21 && args[0] && !args[1] && default_depth_dsv(reinterpret_cast(args[0]), default_dsv)) + args[1] = reinterpret_cast(&default_dsv); D3D12_UNORDERED_ACCESS_VIEW_DESC null_uav{}; D3D12_RENDER_TARGET_VIEW_DESC null_rtv{}; if constexpr (N == 19) { @@ -4310,10 +5938,230 @@ IndirectAddressAlias indirect_address_alias(Wrapper* device, u64 address, u64 by return {it->resource.Get(), offset}; } volatile LONG64 placed_buffer_calls, placed_buffer_region_info, placed_buffer_queries; // five-second totals +struct PrivateRange { u64 base, end; }; +SRWLOCK private_range_lock = SRWLOCK_INIT; +std::vector private_ranges; +void note_private_range(void* base, ID3D12Heap* heap) +{ + if (!base || !heap) return; + const u64 size = heap->GetDesc().SizeInBytes; + AcquireSRWLockExclusive(&private_range_lock); + private_ranges.push_back({reinterpret_cast(base), reinterpret_cast(base) + size}); + ReleaseSRWLockExclusive(&private_range_lock); +} +// The allocation base and end of a private allocation opened as a heap that contains address. +bool known_private(u64 address, u64* base, u64* end) +{ + bool found = false; + AcquireSRWLockShared(&private_range_lock); + for (const PrivateRange& r : private_ranges) + if (address >= r.base && address < r.end) { + *base = r.base; + *end = r.end; + found = true; + break; + } + ReleaseSRWLockShared(&private_range_lock); + return found; +} +ID3D12Heap* existing_heap(void* base) +{ + std::lock_guard lock(placed_mutex); + for (auto& [known, h] : existing_heaps) + if (known == base) return h.real; + ID3D12Device3* device3 = nullptr; + ID3D12Heap* heap = nullptr; + HRESULT hr = device_of(the_device)->QueryInterface(IID_PPV_ARGS(&device3)); + if (SUCCEEDED(hr)) { + hr = device3->OpenExistingHeapFromAddress(base, IID_PPV_ARGS(&heap)); + device3->Release(); + } + if (FAILED(hr)) { + log("x2w-va OpenExistingHeapFromAddress(%p) -> 0x%08lx", base, static_cast(hr)); + return nullptr; + } + existing_heaps.emplace_back(base, ExistingHeap{heap, nullptr}); + note_private_range(base, heap); + return heap; +} +struct VaWindow { + void* base; + UINT64 start; + ID3D12Resource* buffer; +}; +SRWLOCK va_lock = SRWLOCK_INIT; +std::vector& va_windows() +{ + static std::vector windows; + return windows; +} +LONG va_mapped, va_failed; +ID3D12Heap* existing_heap(void* base); // opens (once) the desktop heap over a private allocation +// A chunk section opened once as a desktop heap (nullptr when it cannot be); shared by section_va and, with +// X2W_MEMCUT_ALIAS_SLABS, by placed buffers over pool slabs (device slot 133). +ID3D12Heap* section_heap(HANDLE section) +{ + static SRWLOCK lock = SRWLOCK_INIT; + static std::vector> heaps; + AcquireSRWLockExclusive(&lock); + for (const auto& [h, hp] : heaps) + if (h == section) { + ReleaseSRWLockExclusive(&lock); + return hp; + } + ID3D12Heap* heap = nullptr; + ID3D12Device3* device3 = nullptr; + HRESULT hr = device_of(the_device)->QueryInterface(IID_PPV_ARGS(&device3)); + if (SUCCEEDED(hr)) { + hr = device3->OpenExistingHeapFromFileMapping(section, IID_PPV_ARGS(&heap)); + device3->Release(); + } + log("x2w-va heap over chunk section %p -> 0x%08lx size 0x%llx", section, static_cast(hr), + SUCCEEDED(hr) ? heap->GetDesc().SizeInBytes : 0ull); + if (FAILED(hr)) heap = nullptr; + heaps.emplace_back(section, heap); + ReleaseSRWLockExclusive(&lock); + return heap; +} +// A chunk section opened once as a desktop heap; buffers placed on it in 256 MiB steps (512 MiB long). +D3D12_GPU_VIRTUAL_ADDRESS section_va(HANDLE section, ULONG64 offset) +{ + static SRWLOCK lock = SRWLOCK_INIT; + static std::vector> windows; + const ULONG64 start = offset & ~((1ull << 28) - 1); + AcquireSRWLockExclusive(&lock); + for (const auto& [h, s, b] : windows) + if (h == section && s == start) { + const D3D12_GPU_VIRTUAL_ADDRESS va = b ? b->GetGPUVirtualAddress() + (offset - start) : 0; + ReleaseSRWLockExclusive(&lock); + return va; + } + ID3D12Heap* heap = section_heap(section); + HRESULT hr = S_OK; + ID3D12Resource* buffer = nullptr; + if (heap) { + const UINT64 size = heap->GetDesc().SizeInBytes; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size - start < (2ull << 28) ? size - start : (2ull << 28); + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + hr = device_of(the_device)->CreatePlacedResource(heap, start, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&buffer)); + if (FAILED(hr)) buffer = nullptr; + log("x2w-va chunk window %p+0x%llx -> 0x%08lx va 0x%llx", section, start, static_cast(hr), + buffer ? buffer->GetGPUVirtualAddress() : 0ull); + } + windows.emplace_back(section, start, buffer); + ReleaseSRWLockExclusive(&lock); + note_window(buffer); + return buffer ? buffer->GetGPUVirtualAddress() + (offset - start) : 0; +} +D3D12_GPU_VIRTUAL_ADDRESS desktop_va(u64 address) +{ + if (!address) return 0; + MEMORY_BASIC_INFORMATION info{}; + u64 known_base = 0, known_end = 0; + const bool known = known_private(address, &known_base, &known_end); + if (known) { + info.AllocationBase = reinterpret_cast(known_base); + info.Type = MEM_PRIVATE; + info.State = MEM_COMMIT; + } else if (timed_query(reinterpret_cast(address), &info) != sizeof(info)) { + info = {}; + } + if (info.Type == MEM_MAPPED) { + // Physical pages in 1 GiB chunk sections (xmem X2W_XMEM_CHUNKS=1): a heap over the chunk. + using Location = BOOL(WINAPI*)(const void*, HANDLE*, ULONG64*); + static const Location location = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_gpu_location")) : nullptr; + }(); + HANDLE section = nullptr; + ULONG64 at = 0; + if (location && location(reinterpret_cast(address), §ion, &at)) + return section_va(section, at); + if (x2w_local::first_of(InterlockedIncrement(&va_failed), 8)) log("x2w-va 0x%llx: mapped page without a chunk location", address); + return 0; + } + if (info.Type != MEM_PRIVATE || info.State != MEM_COMMIT) { + if (x2w_local::first_of(InterlockedIncrement(&va_failed), 8)) + log("x2w-va 0x%llx: not a committed private allocation (type 0x%lx state 0x%lx)", address, info.Type, info.State); + return 0; + } + void* base = info.AllocationBase; + const UINT64 offset = address - reinterpret_cast(base); + const UINT64 start = offset & ~((1ull << 28) - 1); + AcquireSRWLockShared(&va_lock); + for (const auto& w : va_windows()) + if (w.base == base && w.start == start) { + const D3D12_GPU_VIRTUAL_ADDRESS va = w.buffer ? w.buffer->GetGPUVirtualAddress() + (offset - start) : 0; + ReleaseSRWLockShared(&va_lock); + return va; + } + ReleaseSRWLockShared(&va_lock); + ID3D12Heap* heap = existing_heap(base); + ID3D12Resource* buffer = nullptr; + HRESULT hr = E_FAIL; + if (heap) { + const UINT64 size = heap->GetDesc().SizeInBytes; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size - start < (2ull << 28) ? size - start : (2ull << 28); + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + hr = device_of(the_device)->CreatePlacedResource(heap, start, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&buffer)); + } + AcquireSRWLockExclusive(&va_lock); + va_windows().push_back({base, start, SUCCEEDED(hr) ? buffer : nullptr}); + ReleaseSRWLockExclusive(&va_lock); + if (SUCCEEDED(hr)) note_window(buffer); + const LONG n = SUCCEEDED(hr) ? InterlockedIncrement(&va_mapped) : InterlockedIncrement(&va_failed); + if (x2w_local::first_of(n, 16)) + log("x2w-va window base=%p start=0x%llx heap=%p -> 0x%08lx desktop va 0x%llx", base, start, static_cast(heap), + static_cast(hr), SUCCEEDED(hr) ? buffer->GetGPUVirtualAddress() : 0ull); + return SUCCEEDED(hr) ? buffer->GetGPUVirtualAddress() + (offset - start) : 0; +} + HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3D12_RESOURCE_DESC* desc, UINT state, const void* clear, const GUID* iid, void** out) { + static thread_local LONG64 placed_last_end = 0; + struct PlacedEnd { + LARGE_INTEGER start; + LONG64* last_end; + ~PlacedEnd() + { + LARGE_INTEGER end; + QueryPerformanceCounter(&end); + InterlockedAdd64(&time_ticks[time_placed], end.QuadPart - start.QuadPart); + InterlockedIncrement64(&time_calls[time_placed]); + InterlockedAdd64(&placed_ticks_total, end.QuadPart - start.QuadPart); + InterlockedIncrement64(&placed_calls_total); + *last_end = end.QuadPart; + } + } placed_end{{}, &placed_last_end}; + QueryPerformanceCounter(&placed_end.start); + { + static const LONG64 frequency = [] { + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + return f.QuadPart; + }(); + const LONG64 gap = placed_end.start.QuadPart - placed_last_end; + if (placed_last_end && gap >= 0 && gap < frequency) { + InterlockedAdd64(&time_ticks[time_placed_gap], gap); + InterlockedIncrement64(&time_calls[time_placed_gap]); + } + } char text[48]; guid_text(iid, text, sizeof(text)); if (!out || !desc || !iid) return E_POINTER; @@ -4331,8 +6179,10 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 texture.Height = surface.rows * x2w_startup::Bc16Surface::block_texels; } const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_CLEAR_VALUE mapped_clear{}; + if (clear) { mapped_clear = *static_cast(clear); mapped_clear.Format = desktop_format(mapped_clear.Format); } D3D12_CLEAR_VALUE clear_copy{}; - const auto* clear_value = packed_clear_value(static_cast(clear), + const auto* clear_value = packed_clear_value(clear ? &mapped_clear : nullptr, desktop_format(desc->Format), texture.Format, clear_copy); ID3D12Resource* created = nullptr; HRESULT texture_hr = device_of(self)->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &texture, @@ -4356,6 +6206,9 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 Wrapper* w = wrap(created, resource_kind); w->own().budget = x2w_budget::committed(device_of(self), created, props.Type); w->own().title_memory = address; + if (cold_textures_enabled() && address && texture.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + texture.SampleDesc.Count == 1 && texture.Flags == D3D12_RESOURCE_FLAG_NONE) + InterlockedExchange(&w->own().cold_texture_state, priority_normal); note_resource(w, desc, 0); retire_set_class(w, props, D3D12_HEAP_FLAG_NONE, texture, address, /*allow_title_memory=*/true); *out = w; @@ -4368,16 +6221,15 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 // block (X2W_XMEM_LAZY_STARTUP) is committed whole, as the heap opened on it is reused for the block. x2w_local::commit_lazy(address, static_cast(desc->Width)); x2w_local::commit_lazy_block(address); - x2w_startup::PlacedBufferRange range; - const bool committed = x2w_startup::measure_placed_buffer(address, desc->Width, range); InterlockedIncrement64(&placed_buffer_calls); - if (range.region_info) InterlockedIncrement64(&placed_buffer_region_info); - InterlockedAdd64(&placed_buffer_queries, range.queries); - if (!committed) { + TimedPart query_time(time_placed_query); + MEMORY_BASIC_INFORMATION info{}; + if (!address || VirtualQuery(address, &info, sizeof(info)) != sizeof(info) || info.State != MEM_COMMIT) { + query_time.stop(); log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) address=%p not committed -> E_INVALIDARG", address); return E_INVALIDARG; } - void* base = range.base; + void* base = info.AllocationBase; const auto initial_state = state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE || state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS ? static_cast(state) : D3D12_RESOURCE_STATE_COMMON; if (initial_state != D3D12_RESOURCE_STATE_COMMON && !(desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) @@ -4389,9 +6241,45 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 // Desktop only accepts 64 KiB-aligned offsets, a private (VirtualAlloc) allocation, and a buffer // that lies inside that one allocation. Attempts that cannot succeed are skipped: each failure // throws inside D3D12Core. - if ((offset & 0xFFFF) || !range.covered || range.type != MEM_PRIVATE || - initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE) hr = E_INVALIDARG; - if (SUCCEEDED(hr)) { + static const bool always_walk = x2w_local::env_on("X2W_D3D12_PLACED_WALK"); + const bool rejected = (offset & 0xFFFF) || info.Type != MEM_PRIVATE || + initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE; + MEMORY_BASIC_INFORMATION region{}; + SIZE_T allocation_bytes = 0; + static const bool placed_fast = x2w_local::env_on("X2W_PLACED_FAST"); + bool fast = false; + if (placed_fast && !rejected && !always_walk) { + const auto* region_end = static_cast(info.BaseAddress) + info.RegionSize; + if (static_cast(address) + desc->Width <= region_end) { + UINT64 heap_bytes = 0; + { + std::lock_guard lock(placed_mutex); + for (auto& [known, h] : existing_heaps) + if (known == base) heap_bytes = h.real->GetDesc().SizeInBytes; + } + if (heap_bytes && offset <= heap_bytes && desc->Width <= heap_bytes - offset) { + fast = true; + allocation_bytes = static_cast(heap_bytes); + static LONG fast_calls; + const LONG n = InterlockedIncrement(&fast_calls); + if (x2w_local::first_of(n, 3) || n % 10000 == 0) + log("x2w-d3d12 slot133 X2W_PLACED_FAST: %ld calls placed without the allocation walk (heap %llu bytes)", n, heap_bytes); + } + } + } + if ((!rejected || always_walk) && !fast) + for (auto* cursor = static_cast(base); + VirtualQuery(cursor, ®ion, sizeof(region)) && region.AllocationBase == base && region.State == MEM_COMMIT; + cursor += region.RegionSize) + allocation_bytes += region.RegionSize; + UINT64 slab_offset = 0; + ID3D12Heap* const slab_heap = info.Type == MEM_MAPPED && initial_state != D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE + ? memcut_slab_heap(address, desc->Width, &slab_offset) : nullptr; + if (!slab_heap && (rejected || offset > allocation_bytes || desc->Width > allocation_bytes - offset)) hr = E_INVALIDARG; + query_time.stop(); + TimedPart create_time(time_placed_create); + if (slab_heap) heap = slab_heap; + else if (SUCCEEDED(hr)) { std::lock_guard lock(placed_mutex); for (const auto& [known, h] : existing_heaps) { if (known == base) { @@ -4409,6 +6297,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 if (SUCCEEDED(hr)) { backing_budget = x2w_budget::backing_heap(heap, 0); existing_heaps.emplace_back(base, ExistingHeap{heap, backing_budget}); + note_private_range(base, heap); } } } @@ -4417,22 +6306,35 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER); ID3D12Resource* resource = nullptr; if (SUCCEEDED(hr)) - hr = device_of(self)->CreatePlacedResource(heap, offset, ©, initial_state, nullptr, + hr = device_of(self)->CreatePlacedResource(heap, slab_heap ? slab_offset : offset, ©, initial_state, nullptr, IID_PPV_ARGS(&resource)); // A buffer that spans several allocations (adjacent placeholder pieces) cannot be placed on one // existing heap. Fallback: a committed default-heap buffer, not aliased with the title memory. const bool aliased = SUCCEEDED(hr); - const char* placement = "aliased"; + const char* placement = slab_heap && aliased ? "aliased slab" : "aliased"; + if (slab_heap && !aliased) memcut_slab_failed(address, desc->Width, hr); if (FAILED(hr)) { const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; copy.Flags = static_cast(desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); - hr = device_of(self)->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, ©, initial_state, - nullptr, IID_PPV_ARGS(&resource)); - placement = "not aliased"; + static x2w_startup::PlacedPool pool; + hr = pool.create(device_of(self), copy, initial_state, &resource); + placement = "not aliased pooled"; + if (FAILED(hr)) { + hr = device_of(self)->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, ©, initial_state, + nullptr, IID_PPV_ARGS(&resource)); + placement = "not aliased"; + } } + create_time.stop(); + TimedPart log_time(time_placed_log); log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) address=%p base=%p offset=0x%llx width=0x%llx flags=0x%x " "state=0x%x clear=%p riid=%s -> 0x%08lx %s gpuva=0x%llx", address, base, offset, desc->Width, desc->Flags, state, clear, text, static_cast(hr), placement, resource ? resource->GetGPUVirtualAddress() : 0ull); + if (const int r = range_watch_hit(reinterpret_cast(address), desc->Width); r >= 0 && range_watch_line(r)) + log("x2w-watch 0x%llx: slot133 placed buffer at %p width 0x%llx flags 0x%x -> 0x%08lx %s frame %ld", range_watch_address(r), address, + desc->Width, desc->Flags, static_cast(hr), placement, frame_number); + if (range_watch_count()) range_watch_sample("slot133-create"); + log_time.stop(); if (FAILED(hr)) return hr; Wrapper* w = wrap(resource, resource_kind); if (release_retired_enabled()) w->own().retire_never = static_cast(RetireNever::buffer); @@ -4596,6 +6498,7 @@ void retire_note_title_release(Wrapper* w) // held. Assumption, not proven: the guest has no raw pointer to the desktop object of a class member. void retire_hold(Wrapper* list, Wrapper* resource) { + warm_texture(resource); // Copies and resolves can bind wrappers directly. if (!resource || !resource->own().retire_when_idle) return; bool held = false; AcquireSRWLockExclusive(&retire_lock); @@ -5312,7 +7215,7 @@ void dump_pipeline(const char* what, int slot, const void* desc, std::size_t byt return GetEnvironmentVariableA("X2W_D3D12_DUMP_PSO", value, sizeof(value)) && value[0] == '1'; }(); static LONG dumped[512]; - if (!enabled || !desc || !first_calls(dumped[slot & 511], 4)) return; + if (!enabled || !desc || !x2w_local::first_calls(dumped[slot & 511], 4)) return; if (!x2w_local::readable(desc, bytes)) return; const auto* words = static_cast(desc); log("x2w-pso %s slot %d desc %p, %llu bytes", what, slot, desc, static_cast(bytes)); @@ -5415,11 +7318,52 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper*, const D3D12_COMPUTE log("x2w-d3d12 Device::slot62(CreateComputePipelineState?) root=%p cs=%p len=0x%llx node=0x%x flags=0x%x extra=0x%llx,0x%llx " "riid=%s -> placeholder [%s]", static_cast(desc->pRootSignature), desc->CS.pShaderBytecode, static_cast(desc->CS.BytecodeLength), desc->NodeMask, desc->Flags, extra0, extra1, text, bytes); + u64 compute_key = 0; + if (Wrapper* root = as_wrapper(desc->pRootSignature); root && desc->CS.BytecodeLength && + desc->CS.BytecodeLength <= (1u << 20) && x2w_local::readable(desc->CS.pShaderBytecode, desc->CS.BytecodeLength)) { + std::vector root_blob; + AcquireSRWLockShared(¬e_lock); + const auto found = root_blobs().find(root); + if (found != root_blobs().end()) root_blob = found->second; + ReleaseSRWLockShared(¬e_lock); + const u64 key = fnv_bytes(root_blob.data(), root_blob.size(), + fnv_bytes(desc->CS.pShaderBytecode, desc->CS.BytecodeLength)); + if (!root_blob.empty()) compute_key = key; + wchar_t path[MAX_PATH]; + if (!root_blob.empty() && cache_path(path, L"req_cs_", key, L".cs") && GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES) { + write_file(path, desc->CS.pShaderBytecode, desc->CS.BytecodeLength); + cache_path(path, L"req_cs_", key, L".root"); + write_file(path, root_blob.data(), root_blob.size()); + } + } if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE; *out = wrap(nullptr, pipeline_kind); auto* pipeline = static_cast(*out); note_pipeline(pipeline, 62, nullptr, desc, sizeof(*desc)); note_compute_binding_pipeline(pipeline, *desc); + if (compute_key) { + wchar_t path[MAX_PATH]; + ID3DBlob* code = nullptr; + Wrapper* root = as_wrapper(desc->pRootSignature); + if (!rawaddr_pipeline(compute_key, root, static_cast(*out)) && + root && root->own().real && cache_path(path, L"", compute_key, L".cs.dxbc") && SUCCEEDED(D3DReadFileToBlob(path, &code))) { + D3D12_COMPUTE_PIPELINE_STATE_DESC real{}; + real.pRootSignature = static_cast(root->own().real); + real.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + ID3D12PipelineState* pso = nullptr; + const HRESULT hr = device_of(the_device)->CreateComputePipelineState(&real, IID_PPV_ARGS(&pso)); + log("x2w-compute pipeline %016llx from signed container -> 0x%08lx", compute_key, static_cast(hr)); + if (SUCCEEDED(hr)) { + AcquireSRWLockExclusive(&compute_pso_lock); + compute_psos()[static_cast(*out)] = pso; + ReleaseSRWLockExclusive(&compute_pso_lock); + } + code->Release(); + } + } + AcquireSRWLockExclusive(&compute_lock); + compute_keys()[static_cast(*out)] = compute_key; + ReleaseSRWLockExclusive(&compute_lock); return S_OK; } @@ -5458,7 +7402,8 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE // guest cache creates a pending translation for any DXBC container. real_pipeline = build_stream_pipeline(desc, why, sizeof(why), compute, graphics); bool mesh_cache_request = false; - if (!real_pipeline) + static const bool upstream_mesh86_cache = x2w_local::env_on("X2W_UPSTREAM_MESH86_CACHE"); + if (!real_pipeline && upstream_mesh86_cache) real_pipeline = try_cached_mesh86(*desc, why, sizeof(why), graphics, mesh_cache_request, mesh86_key); if (!mesh_cache_request && (!real_pipeline || graphics.root)) translation = stream_translation(*desc, blend, has_blend, depth_stencil, has_depth_stencil, dsv_format, @@ -5526,6 +7471,23 @@ HRESULT __stdcall device_create_pipeline_placeholder(Wrapper*, const void* desc, if constexpr (N == 67) publish_compute_request(desc); *out = wrap(nullptr, pipeline_kind); note_pipeline(static_cast(*out), N, nullptr, desc, 0x300); + if (N == 57) regblob::dump57(desc, static_cast(*out)); + if (N == 57) mesh_note57(desc, static_cast(*out)); + if (N == 67 &&x2w_local::readable(desc, 0x28)) { + u64 words[5]; + std::memcpy(words, desc, sizeof(words)); + std::vector regs; + for (int i : {1, 3}) { + const std::uint32_t bytes = words[i + 1] <= 0x1000 && x2w_local::readable(reinterpret_cast(words[i]), words[i + 1]) + ? static_cast(words[i + 1]) : 0u; + regs.insert(regs.end(), reinterpret_cast(&bytes), reinterpret_cast(&bytes) + 4); + if (bytes) regs.insert(regs.end(), reinterpret_cast(words[i]), reinterpret_cast(words[i]) + bytes); + } + AcquireSRWLockExclusive(&compute_lock); + compute_regs()[static_cast(*out)] = std::move(regs); + ReleaseSRWLockExclusive(&compute_lock); + if (prewarm_enabled()) prewarm_compute(compute_key_for(static_cast(*out))); + } return S_OK; } @@ -5553,6 +7515,7 @@ HRESULT __stdcall device_create_derived_pipeline(Wrapper*, void* base, UINT coun } *out = wrap(nullptr, pipeline_kind); note_pipeline(static_cast(*out), 55, base, desc, bytes_in_patches); + regblob::dump55(base, desc, bytes_in_patches); return S_OK; } @@ -5577,6 +7540,8 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP const D3D12_RESOURCE_ALLOCATION_INFO info = device_of(self)->GetResourceAllocationInfo(0, 1, ©); check_device("Device before slot", 127); void* const title_memory = info.SizeInBytes != ~0ull ? title_resource_memory(info.SizeInBytes, info.Alignment) : nullptr; + D3D12_CLEAR_VALUE mapped_clear{}; + if (clear) { mapped_clear = *clear; mapped_clear.Format = desktop_format(mapped_clear.Format); clear = &mapped_clear; } ID3D12Resource* resource = nullptr; const D3D12_RESOURCE_STATES initial = props->Type == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ : props->Type == D3D12_HEAP_TYPE_READBACK ? D3D12_RESOURCE_STATE_COPY_DEST @@ -5627,7 +7592,12 @@ HRESULT __stdcall device_wait_frame_event(Wrapper*, UINT type, UINT timeout, voi QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&origin); } - const LONGLONG interval = frequency.QuadPart * (frame_interval_us ? frame_interval_us : 33333) / 1000000; + static const UINT override_us = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_FRAME_US", value, sizeof(value)) ? static_cast(std::atol(value)) : 0u; + }(); + const UINT interval_us = override_us ? override_us : frame_interval_us ? frame_interval_us : 33333; + const LONGLONG interval = frequency.QuadPart * interval_us / 1000000; LARGE_INTEGER now; QueryPerformanceCounter(&now); LONGLONG target; @@ -5636,7 +7606,8 @@ HRESULT __stdcall device_wait_frame_event(Wrapper*, UINT type, UINT timeout, voi if (target < now.QuadPart) target = now.QuadPart; // running late: start a new timeline here origin.QuadPart = target; } else { - target = origin.QuadPart + frequency.QuadPart * frame_event_offset_us[type < 4 ? type : 3] / 1000000; + const UINT offset_us = frame_event_offset_us[type < 4 ? type : 3]; + target = origin.QuadPart + frequency.QuadPart * (override_us && offset_us > override_us ? override_us : offset_us) / 1000000; } const LONGLONG wait_ticks = target > now.QuadPart ? target - now.QuadPart : 0; ReleaseSRWLockExclusive(&lock); @@ -5711,7 +7682,77 @@ void draw_overlay(LONG frame, double seconds) ReleaseDC(window, dc); } +#include "startup_stubs/d3d12_compute.inl" +#include "startup_stubs/d3d12_range_alias.inl" +#include "startup_stubs/d3d12_vdesc.inl" +#include "startup_stubs/d3d12_gpu_time.inl" +#include "startup_stubs/d3d12_indirect.inl" +#include "startup_stubs/d3d12_mesh.inl" +#include "startup_stubs/d3d12_record_trace.inl" +#include "startup_stubs/d3d12_rawaddr.inl" #include "startup_stubs/d3d12_present.inl" +#include "startup_stubs/d3d12_copy_buffer.inl" + +LONG present_split_period() +{ + static const LONG period = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_PRESENT_SPLIT", value, sizeof(value)) ? std::atol(value) : 300L; + }(); + return period; +} + +void present_split(LONG frame) +{ + static LARGE_INTEGER frequency, last; + static LONG last_frame; + static LONG64 last_inside, last_ticks[thread_inside_max]; + static ULONG64 last_cpu; + static DWORD last_tid; + if (!frequency.QuadPart) QueryPerformanceFrequency(&frequency); + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + FILETIME created, exited, kernel, user; + GetThreadTimes(GetCurrentThread(), &created, &exited, &kernel, &user); + const auto u64_of = [](const FILETIME& t) { return (static_cast(t.dwHighDateTime) << 32) | t.dwLowDateTime; }; + const ULONG64 cpu = u64_of(kernel) + u64_of(user); // 100 ns units + const DWORD tid = GetCurrentThreadId(); + const LONG64 inside = inside_slot()->ticks; + const LONG count = thread_inside_count < thread_inside_max ? thread_inside_count : thread_inside_max; + const auto ms = [](LONG64 ticks) { return static_cast(ticks) * 1000.0 / static_cast(frequency.QuadPart); }; + if (last.QuadPart && tid == last_tid && frame > last_frame) { + const double wall = ms(now.QuadPart - last.QuadPart), in = ms(inside - last_inside); + const double cpu_ms = static_cast(cpu - last_cpu) / 1e4; + struct Top { LONG tid; LONG64 ticks; } top[4]{}; + for (LONG i = 0; i < count; ++i) { + const LONG64 delta = thread_inside[i].ticks - last_ticks[i]; + for (int j = 0; j < 4; ++j) { + if (delta <= top[j].ticks) continue; + for (int m = 3; m > j; --m) top[m] = top[m - 1]; + top[j] = {thread_inside[i].tid, delta}; + break; + } + } + char text[160]; + int used = 0; + text[0] = 0; + for (const Top& t : top) + if (t.ticks) used += std::snprintf(text + used, sizeof(text) - used, " %ld:%.0f", t.tid, ms(t.ticks)); + const LONG frames = frame - last_frame; + log("x2w-present split over %ld frames (%.1f ms/frame): presenting thread %lu inside timed d3d12_xs calls %.1f " + "ms/frame, outside %.1f ms/frame (xmem/XCRDAPI time counts as outside); its CPU %.1f ms/frame, so %.1f ms/frame " + "blocked or not running; timed d3d12_xs ms by thread (tid:ms over the window):%s; %ld threads seen", + frames, wall / frames, tid, in / frames, (wall - in) / frames, + cpu_ms / frames, (wall - cpu_ms) / frames, text, count); + fence_times::report(); // X2W_FENCE_TIMES=1, same window + } + last = now; + last_frame = frame; + last_inside = inside; + last_cpu = cpu; + last_tid = tid; + for (LONG i = 0; i < count; ++i) last_ticks[i] = thread_inside[i].ticks; +} // Render mode: a coarse signature of the presented picture for input-script waits (present_signature.h, // present_signature_sampler.h). The block always counts presents; samples are taken every 4 presents @@ -5815,7 +7856,19 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa static LONG frames; static ULONGLONG started, last_report; const LONG frame = InterlockedIncrement(&frames); + if (const LONG period = present_split_period(); period > 0) { + static ULONGLONG split_due; + const ULONGLONG tick = GetTickCount64(); + if (frame == 1 || frame % period == 0 || tick >= split_due) { + split_due = tick + 10000; + present_split(frame); + } + } frame_number = frame; + if (range_watch_count()) range_watch_sample("present"); + note_present_planes(frame, planes, plane_parameters, present_parameters); + note_quiet_frame(frame); + note_descriptor_watch(frame); draw_dump_flush(); red_producers().flush(); { @@ -5831,6 +7884,38 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa InterlockedExchange(&trace_frame_active, 0); log("x2w-frame ---- end frame %ld", wanted); } + static const LONG busy = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_D3D12_TRACE_BUSY", value, sizeof(value)) ? std::atol(value) : 0L; + }(); + static LONG busy_end, busy_next; + const LONG dispatched = InterlockedExchange(&frame_dispatches, 0); + mesh_stats_present(frame); + mesh_fs_present(); + if (busy && busy_end && frame == busy_end) { + InterlockedExchange(&trace_frame_active, 0); + log("x2w-frame ---- end busy frame %ld", frame); + // The target read-back stalls Present for about a second: only with X2W_D3D12_TRACE_TARGETS=1. + static const bool targets = x2w_local::env_on("X2W_D3D12_TRACE_TARGETS"); + record_trace_report(static_cast(self->own().real)); + if (targets) summarise_traced_targets(static_cast(self->own().real)); + summarise_indirect_calls(); + busy_end = 0; + } else if (busy && !busy_end && frame >= busy_next) { + static const LONG after = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_D3D12_TRACE_BUSY_AFTER", value, sizeof(value)) ? std::atol(value) : 0L; + }(); + static LONG busy_seen; + if (!busy_seen && dispatched >= busy) busy_seen = frame; + if (busy_seen && frame >= busy_seen + after) { + log("x2w-frame ---- begin busy frame %ld (previous frame: %ld dispatches; first busy frame %ld)", frame + 1, dispatched, busy_seen); + InterlockedExchange(&trace_frame_active, 1); + busy_end = frame + 1; + busy_next = frame + 3000; + busy_seen = 0; + } + } } bool shown_in_window = false; { @@ -5855,7 +7940,14 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa hex_text(present_parameters, 0x40, b, sizeof(b)); log("x2w-d3d12 CommandQueue::slot32(present) planes=%u plane=[%s] present=[%s]", planes, a, b); } - if (render_mode() && frame % (shown_in_window ? 60 : 6) == 0 && planes && plane_parameters) { + static const ULONGLONG shot_frames = [] { + char value[8]{}; + const DWORD n = GetEnvironmentVariableA("X2W_D3D12_SHOT_FRAMES", value, sizeof(value)); + const unsigned long frames = n && n < sizeof(value) ? std::strtoul(value, nullptr, 10) : 0ul; + return frames ? static_cast(frames) : 60ull; + }(); + if (render_mode()) read_back_presented(nullptr, nullptr, false); + if (render_mode() && frame % (shown_in_window ? shot_frames : 6) == 0 && planes && plane_parameters) { // Plane parameters: +0x00 frame token, +0x08 resource count, +0x10 pointer to the resources. const auto* words = static_cast(plane_parameters); if (x2w_local::readable(words, 0x18) && words[1] >= 1 && x2w_local::readable(reinterpret_cast(words[2]), 8)) { @@ -5868,7 +7960,7 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa } } if (shown_in_window) { - if (frame % 30 == 0) { + if (!present_in_title_window() && frame % 30 == 0) { // About 100 fixed characters, the revision (at most 46) and three numbers fit in 256. wchar_t text[256]; swprintf(text, 256, L"Xbox2Windows %ls - frame %ld, %.1f fps, %ld translated draws (title bar is diagnostics, picture is game output)", @@ -5881,7 +7973,7 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa // The null-binding total and its causes change together under draw_lock (draw_translated holds it), so they are copied there. LONG null_total = 0, null_causes[x2w_local::null_cause_count] = {}; if (render_mode() && frame % 300 == 0) { - AcquireSRWLockExclusive(&draw_lock); + lock_draw(0 + __LINE__); null_total = null_bindings; for (int c = 0; c < x2w_local::null_cause_count; ++c) null_causes[c] = null_by_cause[c]; ReleaseSRWLockExclusive(&draw_lock); @@ -5889,17 +7981,31 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa if (render_mode() && frame % 300 == 0) log("x2w-render totals: resets %ld (failed %ld), closes %ld, clears %ld, target binds %ld (unresolved %ld), executes %ld, draws %ld (skipped %ld), " "translated draws %ld (not drawn %ld), pipelines translated %ld / missing %ld, null bindings %ld (entry %ld, buffer %ld, token %ld, wrapper %ld, dimension %ld), " - "formatted-load draws refused %ld, textures uploaded %ld (%ld KiB, unreadable %ld), heap-indexed roots deferred %ld (real draws refused: view heap %ld, " + "buffer links %ld, refused-view entries %ld (nulled %ld, rewritten markers %ld), textures uploaded %ld (%ld KiB, unreadable %ld), heap-indexed roots deferred %ld (real draws refused: view heap %ld, " "sampler heap %ld, both heaps %ld, state %ld), pipelines first looked up by ExecuteIndirect %ld, compute requests published %ld (already present %ld, failed %ld, pointer-like blob qwords %ld)", render_resets, render_reset_failures, render_closes, render_clears, render_target_binds, render_target_unresolved, render_executes, render_draws, render_draws_skipped, translated_draws, untranslated_draws, translation_ready, translation_missing, null_total, - null_causes[0], null_causes[1], null_causes[2], null_causes[3], null_causes[4], formatted_draws_refused, textures_uploaded, + null_causes[0], null_causes[1], null_causes[2], null_causes[3], null_causes[4], buffer_links, buffer_refused_views, buffer_links_nulled, marker_rewrites, textures_uploaded, texture_bytes_uploaded, textures_unreadable, heap_roots_deferred, heap_root_refusals[static_cast(x2w_startup::RealRootDecision::view_heap_missing)], heap_root_refusals[static_cast(x2w_startup::RealRootDecision::sampler_heap_missing)], heap_root_refusals[static_cast(x2w_startup::RealRootDecision::both_heaps_missing)], heap_root_refusals[static_cast(x2w_startup::RealRootDecision::state_not_restorable)], indirect_first_lookups, compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words); + if (render_mode() && frame % 300 == 0) report_target_binds(); + if (render_mode() && frame % 300 == 0) report_draw_state(); + if (frame % 300 == 0) draw_lock_times::report("300 frames"); + if (x2w_local::probe_cache_on()) { + x2w_local::invalidate_probe_cache(); + if (frame % 300 == 0) { + x2w_local::ProbeCache& c = x2w_local::probe_cache(); + LARGE_INTEGER f; + QueryPerformanceFrequency(&f); + log("x2w-probe cache (X2W_PROBE_CACHE, %llu ms, cleared at each present): since start %lld probes answered from the cache without a " + "fault, %lld faults (%lld VirtualQuery, %.1f ms), %lld unreadable ranges kept", x2w_local::probe_cache_ms(), c.hits, c.faults, + c.queries, static_cast(c.query_ticks) * 1000.0 / static_cast(f.QuadPart), c.cached); + } + } if (render_mode() && frame % 300 == 0) { // Slot-61 calls since the start, by outcome, then by signature kind (zero kinds left out). static const char* const outcomes[] = {"forwarded", "refused graphics-pipeline", "compute-pipeline", @@ -5926,6 +8032,12 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa if (calls) n += std::snprintf(line + n, sizeof(line) - n, " %d:%.1f", i, calls / 300.0); } log("%s", line); + report_dispatches(); + report_indirect(300); + report_mesh(300); + regblob::report(); + report_cx_views(); + gpu_time::report(); } if (now - last_report >= 5000) { last_report = now; @@ -5936,7 +8048,7 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); - char text[512]; + char text[768]; int used = 0; for (int i = 0; i < time_count; ++i) { const LONG64 ticks = InterlockedExchange64(&time_ticks[i], 0), calls = InterlockedExchange64(&time_calls[i], 0); @@ -5945,6 +8057,13 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa static_cast(ticks * 1000 / frequency.QuadPart), static_cast(calls)); } log("x2w-d3d12 time inside the stand-in since the last report (ms/calls):%s", text); + static LONG64 placed_reported = 0; + const LONG64 placed_calls = placed_calls_total; + if (placed_calls != placed_reported) { + placed_reported = placed_calls; + log("x2w-d3d12 placed resources (slot 133) since the start: %lld calls, %lld ms inside", static_cast(placed_calls), + static_cast(placed_ticks_total * 1000 / frequency.QuadPart)); + } used = 0; text[0] = 0; for (int i = 0; i < 256; ++i) { @@ -5955,6 +8074,11 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa } if (used) log("x2w-d3d12 command-list slots over 20 ms:%s", text); } + rawaddr_report(); + report_srv_copies(); + report_cx_async(); + report_prewarm_known("at the heartbeat"); + report_draw_async(); memory_srv_census.report([](const char* line) { log("%s", line); }, true); token_null_census.report([](const char* line) { log("%s", line); }, true); memory_srv_writes.report([](const char* line) { log("%s", line); }, true); @@ -6057,6 +8181,8 @@ void build_tables() // Xbox order from here. tables[device_kind][48] = reinterpret_cast(&device_create_command_queue_x); tables[device_kind][70] = reinterpret_cast(&device_memory_srv); + if (memory_srv_buffer_on()) tables[device_kind][71] = reinterpret_cast(&device_memory_uav); + if (texture_census_on()) tables[device_kind][61] = reinterpret_cast(&device_slot61_census); tables[device_kind][73] = reinterpret_cast(&device_create_command_list_x); tables[device_kind][78] = reinterpret_cast(&device_frame_interval); tables[device_kind][79] = reinterpret_cast(&device_frame_event); @@ -6076,6 +8202,7 @@ void build_tables() fill_noops(tables[list_kind], std::make_index_sequence{}); tables[list_kind][7] = reinterpret_cast(&child_get_device); } + list_typed[148] = reinterpret_cast(&list_allocate_upload); if (render_mode()) { list_typed[9] = reinterpret_cast(&list_close); list_typed[51] = reinterpret_cast(&list_clear_depth_stencil); @@ -6091,30 +8218,46 @@ void build_tables() list_typed[54] = reinterpret_cast(&list_clear_uav); list_typed[55] = reinterpret_cast(&list_discard); list_typed[139] = reinterpret_cast(&list_reset); - list_typed[148] = reinterpret_cast(&list_allocate_upload); + if (x2w_local::env_on("X2W_LIST_UPLOAD_PAGES")) list_typed[148] = reinterpret_cast(&list_allocate_upload_pages); list_typed[12] = reinterpret_cast(&list_draw); + list_typed[14] = reinterpret_cast(&list_dispatch); + list_typed[61] = reinterpret_cast(&list_execute_indirect); + list_typed[33] = reinterpret_cast(&list_compute_root); + list_typed[35] = reinterpret_cast(&list_compute_table); + list_typed[37] = reinterpret_cast(&list_compute_constant); + list_typed[39] = reinterpret_cast(&list_compute_constants); + list_typed[41] = reinterpret_cast(&list_compute_cbv); + list_typed[43] = reinterpret_cast(&list_compute_srv); + list_typed[45] = reinterpret_cast(&list_compute_uav); list_typed[16] = reinterpret_cast(&list_copy_texture); list_typed[20] = reinterpret_cast(&list_topology); list_typed[21] = reinterpret_cast(&list_viewports); list_typed[22] = reinterpret_cast(&list_scissors); list_typed[23] = reinterpret_cast(&list_blend_factor); - list_typed[24] = reinterpret_cast(&list_stencil_ref); + if (x2w_pipeline_state::switches_from_env().depth || x2w_local::env_on("X2W_DEPTH_STATE") || + x2w_local::env_on("X2W_UPSTREAM_STENCIL_REF")) list_typed[24] = reinterpret_cast(&list_stencil_ref); + if (x2w_pipeline_state::switches_from_env().depth_clear) + tables[list_kind][51] = reinterpret_cast(&list_clear_depth); list_typed[25] = reinterpret_cast(&list_pipeline); list_typed[x2w_list_slots::resource_barrier_slot] = reinterpret_cast(&list_resource_barriers); list_typed[32] = reinterpret_cast(&list_set_descriptor_heaps); - list_typed[33] = reinterpret_cast(&list_compute_root); + static const bool upstream_compute_root = x2w_local::env_on("X2W_UPSTREAM_COMPUTE_ROOT"); + if (upstream_compute_root) list_typed[33] = reinterpret_cast(&list_compute_root_desktop); list_typed[34] = reinterpret_cast(&list_graphics_root); - list_typed[43] = reinterpret_cast(&list_compute_upload_srv); + if (upstream_compute_root) list_typed[43] = reinterpret_cast(&list_compute_upload_srv); list_typed[44] = reinterpret_cast(&list_root_srv); + list_typed[46] = reinterpret_cast(&list_root_uav); list_typed[42] = reinterpret_cast(&list_root_cbv); list_typed[50] = reinterpret_cast(&list_targets); list_typed[13] = reinterpret_cast(&list_draw_indexed); - list_typed[35] = reinterpret_cast(&list_compute_table); + if (upstream_compute_root) list_typed[35] = reinterpret_cast(&list_compute_table_desktop); list_typed[36] = reinterpret_cast(&list_table); list_typed[40] = reinterpret_cast(&list_root_constants); list_typed[47] = reinterpret_cast(&list_index_buffer); list_typed[48] = reinterpret_cast(&list_vertex_buffers); - list_typed[x2w_list_slots::execute_indirect_slot] = reinterpret_cast(&list_execute_indirect); + install_copy_buffer(list_typed); + if (x2w_local::env_on("X2W_UPSTREAM_EXECUTE_INDIRECT")) + list_typed[x2w_list_slots::execute_indirect_slot] = reinterpret_cast(&list_execute_indirect_upstream); // X2W_D3D12_QUERY_SLOTS=1 (diagnostic): which console methods sit at 28 to 30 is a hypothesis, so the query // bindings are opt-in. Unset, the slots stay no-ops. if (wchar_t on[4]{}; GetEnvironmentVariableW(L"X2W_D3D12_QUERY_SLOTS", on, 4) && on[0] == L'1') { @@ -6130,7 +8273,8 @@ void build_tables() fill_queue_dynamic(tables[queue_kind], std::make_index_sequence<64>{}); tables[queue_kind][17] = reinterpret_cast(&queue_wait); tables[queue_kind][18] = reinterpret_cast(&queue_timestamp_frequency); - tables[queue_kind][31] = reinterpret_cast(&queue_page_mappings); + if (x2w_local::env_on("X2W_UPSTREAM_QUEUE_PAGE_BATCH")) + tables[queue_kind][31] = reinterpret_cast(&queue_page_mappings); tables[queue_kind][32] = reinterpret_cast(&queue_present); // Fence: GetCompletedValue, SetEventOnCompletion, Signal, GetCreationFlags. @@ -6153,6 +8297,12 @@ void build_tables() tables[descriptor_heap_kind][9] = reinterpret_cast(&descriptor_heap_cpu_start); tables[descriptor_heap_kind][10] = reinterpret_cast(&descriptor_heap_gpu_start); if (device_noop()) fill_all_remaining_noops(std::make_index_sequence{}); + // Say what the tables hold after the fill, so a census run shows which build it ran. + if (noop_census_enabled()) + log("x2w-noop-census tables: device slot 70 = %s, list slot 12 typed = %s, list slot 44 typed = %s, render mode %d, device noop %d, list noop %d", + tables[device_kind][70] == reinterpret_cast(&device_memory_srv) ? "memory SRV handler" + : tables[device_kind][70] == reinterpret_cast(&device_noop_slot<70>) ? "NO-OP" : "other", + list_typed[12] ? "yes" : "NO", list_typed[44] ? "yes" : "NO", render_mode() ? 1 : 0, device_noop() ? 1 : 0, list_noop() ? 1 : 0); } SRWLOCK written_lock = SRWLOCK_INIT; @@ -6169,6 +8319,10 @@ void note_texture_write(void* base, UINT bc7_width, UINT bc7_height) ReleaseSRWLockExclusive(&written_lock); } } // namespace +#include "startup_stubs/d3d12_mem_counters.inl" +#include "startup_stubs/d3d12_memcut_release.inl" +#include "startup_stubs/d3d12_memcut_alias.inl" +extern "C" __declspec(dllexport) unsigned long long x2w_upload_ring_test(int what) { return upload_ring_counter(what); } void x2w_startup::attach_device(ID3D12Device* device, void** wrapped) { @@ -6177,6 +8331,7 @@ void x2w_startup::attach_device(ID3D12Device* device, void** wrapped) removal_device = device; the_device = wrap(device, device_kind); *wrapped = the_device; + prewarm_known_start(); } HRESULT x2w_startup::resolve_placed_build(void* guest_device, UINT64 dest, UINT64 scratch, @@ -6251,6 +8406,31 @@ HRESULT x2w_d3d12_permissive_create_device(IUnknown* adapter, const void* parame log("x2w-d3d12 debug layer: 0x%08lx%s", static_cast(debug_hr), SUCCEEDED(debug_hr) ? " enabled" : " (not installed?)"); } + static const bool background = [] { + if (!x2w_local::env_on("X2W_BACKGROUND_PRIORITY")) return false; + // gdi32!D3DKMTSetProcessSchedulingPriorityClass(process, D3DKMT_SCHEDULINGPRIORITYCLASS): + // 0 idle, 1 below normal, 2 normal (d3dkmthk.h); NTSTATUS result. + using SetGpuClass = LONG(APIENTRY*)(HANDLE, int); + const HMODULE gdi = LoadLibraryW(L"gdi32.dll"); + const auto set_gpu = gdi ? reinterpret_cast(GetProcAddress(gdi, "D3DKMTSetProcessSchedulingPriorityClass")) : nullptr; + const LONG gpu = set_gpu ? set_gpu(GetCurrentProcess(), 1) : -1; + const BOOL cpu = SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); + const DWORD cpu_error = cpu ? 0 : GetLastError(); + log("x2w-d3d12 background priority: GPU scheduling class below normal -> 0x%08lx%s; CPU priority class below normal -> %s " + "(error %lu, class now 0x%lx)", static_cast(gpu), set_gpu ? "" : " (entry point not found)", + cpu ? "ok" : "refused", cpu_error, GetPriorityClass(GetCurrentProcess())); + return true; + }(); + (void)background; + if (x2w_local::env_on("X2W_D3D12_DRED")) { + ID3D12DeviceRemovedExtendedDataSettings* dred = nullptr; + if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&dred)))) { + dred->SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + dred->SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + dred->Release(); + log("x2w-d3d12 DRED enabled"); + } + } ID3D12Device* device = nullptr; const HRESULT hr = kind_for(iid) == device_kind || iid == __uuidof(IUnknown) ? D3D12CreateDevice(adapter ? reinterpret_cast(unwrap(reinterpret_cast(adapter))) : nullptr, diff --git a/src/startup_stubs/d3d12_xs_traps.cpp b/src/startup_stubs/d3d12_xs_traps.cpp new file mode 100644 index 0000000000..05312660f4 --- /dev/null +++ b/src/startup_stubs/d3d12_xs_traps.cpp @@ -0,0 +1,5 @@ +#define X2W_TRAP_MODULE "d3d12_xs.dll" +#define X2W_TRAP_MODULE_ID 7 +#include "startup_stubs/trap.h" + +X2W_TRAP_EXPORT(0, D3D12ConfigureVirtualMemoryX) diff --git a/src/startup_stubs/derived_blend.h b/src/startup_stubs/derived_blend.h index faced7f24d..97afe075e6 100644 --- a/src/startup_stubs/derived_blend.h +++ b/src/startup_stubs/derived_blend.h @@ -1,5 +1,7 @@ #pragma once +#include "pipeline_state_decode.h" + #include #include #include @@ -13,16 +15,11 @@ static_assert(record_size == 0x14c); inline bool last_blend(const unsigned char* records, std::size_t bytes, D3D12_BLEND_DESC& blend, std::size_t& offset) { - if (!records || bytes % record_size) return false; - for (std::size_t end = bytes; end; end -= record_size) { - const std::size_t at = end - record_size; - std::uint32_t tag; - std::memcpy(&tag, records + at, sizeof(tag)); - if (tag != 2) continue; - offset = at + sizeof(tag); - std::memcpy(&blend, records + offset, sizeof(blend)); - return true; - } - return false; + // The record walk is shared with the other parts (pipeline_state_decode.h). + const std::size_t at = x2w_pipeline_state::last_part(records, bytes, x2w_pipeline_state::part_blend); + if (at == SIZE_MAX) return false; + offset = at; + std::memcpy(&blend, records + offset, sizeof(blend)); + return true; } } // namespace x2w_derived_blend diff --git a/src/startup_stubs/dstorage_status_stats.h b/src/startup_stubs/dstorage_status_stats.h new file mode 100644 index 0000000000..71a9f444da --- /dev/null +++ b/src/startup_stubs/dstorage_status_stats.h @@ -0,0 +1,210 @@ +#pragma once + +#include + +#include +#include + +namespace x2w_dstorage_stats { + +struct StatusStats { + unsigned capacity = 0; + unsigned serial = 0; + const volatile LONG* results = nullptr; // the array's results (owned by the stand-in) + LONG64* enqueued_at = nullptr; // QPC ticks of the latest EnqueueStatus per index + LONG* enqueued_gen = nullptr; // EnqueueStatus calls per index + LONG* completed_gen = nullptr; // generation of the latest result written per index + void* volatile queue = nullptr; // the queue of the latest EnqueueStatus (opaque here) + void* volatile poller = nullptr; + volatile LONG64 polls_pending = 0, polls_complete = 0; + volatile LONG64 completions = 0, wait_ticks = 0, wait_max = 0; // reset by each report + volatile LONG64 completions_total = 0; + volatile LONG reused = 0, stale = 0; +}; + +inline bool enabled() noexcept +{ + static const bool on = [] { + const DWORD saved = GetLastError(); + char value[4]{}; + const bool off = GetEnvironmentVariableA("X2W_DSTORAGE_STATUS_STATS", value, sizeof(value)) && value[0] == '0'; + SetLastError(saved); + return !off; + }(); + return on; +} + +inline LONG64 now() noexcept +{ + LARGE_INTEGER t{}; + QueryPerformanceCounter(&t); + return t.QuadPart; +} + +inline double ms(LONG64 ticks) noexcept +{ + static const double frequency = [] { + LARGE_INTEGER f{}; + QueryPerformanceFrequency(&f); + return f.QuadPart ? static_cast(f.QuadPart) : 1.0; + }(); + return static_cast(ticks) * 1000.0 / frequency; +} + +constexpr LONG max_arrays = 64; +inline StatusStats* arrays[max_arrays]; +inline volatile LONG array_count = 0; + +// Null when off or out of memory; every other call accepts null. +inline StatusStats* make(unsigned capacity, const volatile LONG* results) noexcept +{ + if (!enabled() || !capacity || !results) return nullptr; + auto* s = new (std::nothrow) StatusStats; + if (!s) return nullptr; + s->capacity = capacity; + s->results = results; + s->enqueued_at = new (std::nothrow) LONG64[capacity](); + s->enqueued_gen = new (std::nothrow) LONG[capacity](); + s->completed_gen = new (std::nothrow) LONG[capacity](); + if (!s->enqueued_at || !s->enqueued_gen || !s->completed_gen) { + delete[] s->enqueued_at; + delete[] s->enqueued_gen; + delete[] s->completed_gen; + delete s; + return nullptr; + } + const LONG slot = InterlockedIncrement(&array_count) - 1; + s->serial = static_cast(slot); + if (slot < max_arrays) arrays[slot] = s; // later arrays are tracked but not reported + return s; +} + +// At EnqueueStatus, before the index is set pending. Returns the entry's generation (0 when off). +inline LONG on_enqueue(StatusStats* s, unsigned index, void* queue) noexcept +{ + if (!s || index >= s->capacity) return 0; + const LONG gen = InterlockedIncrement(&s->enqueued_gen[index]); + if (s->completed_gen[index] != gen - 1) InterlockedIncrement(&s->reused); + s->queue = queue; + InterlockedExchange64(&s->enqueued_at[index], now()); + return gen; +} + +// Right before the result is written (afterwards the title may enqueue the index again). +inline void on_complete(StatusStats* s, unsigned index, LONG gen) noexcept +{ + if (!s || index >= s->capacity || !gen) return; + if (gen != s->enqueued_gen[index]) { + InterlockedIncrement(&s->stale); + return; + } + const LONG64 wait = now() - s->enqueued_at[index]; + InterlockedIncrement64(&s->completions); + InterlockedIncrement64(&s->completions_total); + InterlockedAdd64(&s->wait_ticks, wait); + for (LONG64 seen = s->wait_max; wait > seen;) { + const LONG64 prior = InterlockedCompareExchange64(&s->wait_max, wait, seen); + if (prior == seen) break; + seen = prior; + } + InterlockedExchange(&s->completed_gen[index], gen); +} + +// IsComplete runs at tens of millions of calls per second while the title waits, so the poll counts are +// plain (unlocked) increments on the array's own counters: approximate when several threads poll one +// array or a report resets them mid-increment, but no locked instruction on the title's poll path. +inline void on_poll(StatusStats* s, bool complete, void* caller) noexcept +{ + if (!s) return; + volatile LONG64& polls = complete ? s->polls_complete : s->polls_pending; + polls = polls + 1; + if (!s->poller) InterlockedCompareExchangePointer(&s->poller, caller, nullptr); +} + +inline void module_offset(const void* address, char* out, std::size_t size) noexcept +{ + HMODULE module = nullptr; + char path[MAX_PATH] = "?"; + if (address && GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast(address), &module) && module) { + GetModuleFileNameA(module, path, MAX_PATH); + const char* name = path; + for (const char* p = path; *p; ++p) + if (*p == '\\' || *p == '/') name = p + 1; + std::snprintf(out, size, "%s+0x%llx", name, + static_cast(static_cast(address) - reinterpret_cast(module))); + } else { + std::snprintf(out, size, "%p", address); + } +} + +// Heartbeat. `queue_text` describes a queue's entry counts into a buffer (the stand-in's own state). +// `pending_result` is the value an index holds while pending. +template +void report(int second, LONG pending_result, Log log, QueueText queue_text) +{ + if (!enabled()) return; + const LONG count = array_count < max_arrays ? array_count : max_arrays; + LONG64 completions = 0, wait_ticks = 0, wait_max = 0, polls_pending = 0, polls_complete = 0; + LONG reused = 0, stale = 0, max_at = -1, active = 0; + char pollers[256] = ""; + int used = 0; + void* seen_pollers[4] = {}; + for (LONG i = 0; i < count; ++i) { + StatusStats* s = arrays[i]; + if (!s) continue; + const LONG64 c = InterlockedExchange64(&s->completions, 0); + const LONG64 t = InterlockedExchange64(&s->wait_ticks, 0); + const LONG64 m = InterlockedExchange64(&s->wait_max, 0); + const LONG64 pp = InterlockedExchange64(&s->polls_pending, 0); + const LONG64 pc = InterlockedExchange64(&s->polls_complete, 0); + if (c || pp || pc) ++active; + completions += c; + wait_ticks += t; + if (m > wait_max) { + wait_max = m; + max_at = i; + } + polls_pending += pp; + polls_complete += pc; + reused += s->reused; + stale += s->stale; + void* poller = s->poller; + bool known = !poller; + for (void*& p : seen_pollers) { + if (p == poller) known = true; + if (!known && !p) { + p = poller; + char where[160]; + module_offset(poller, where, sizeof(where)); + if (used < static_cast(sizeof(pollers)) - 1) + used += std::snprintf(pollers + used, sizeof(pollers) - used, " %s", where); + known = true; + } + } + } + if (completions || polls_pending || polls_complete || reused || stale) + log("x2w-dstorage status %d s: arrays %ld (active %ld), completions %lld, wait mean %.3f ms max %.3f ms (array #%ld); " + "IsComplete polls (approximate) pending %lld complete %lld; reused before complete %ld, stale writes %ld (since start); first pollers:%s", + second, static_cast(array_count), static_cast(active), completions, + completions ? ms(wait_ticks) / static_cast(completions) : 0.0, ms(wait_max), static_cast(max_at), + polls_pending, polls_complete, static_cast(reused), static_cast(stale), used ? pollers : " none"); + int shown = 0; + const LONG64 t = now(); + for (LONG i = 0; i < count && shown < 8; ++i) { + StatusStats* s = arrays[i]; + if (!s) continue; + for (unsigned index = 0; index < s->capacity && shown < 8; ++index) { + if (s->results[index] != pending_result || !s->enqueued_gen[index]) continue; + const double age = ms(t - s->enqueued_at[index]); + if (age < 1000.0) continue; + char queue[160] = ""; + queue_text(s->queue, queue, sizeof(queue)); + log("x2w-dstorage status PENDING array #%ld index %u for %.1f s (enqueued %ld, completed %ld; %s)", static_cast(i), index, + age / 1000.0, static_cast(s->enqueued_gen[index]), static_cast(s->completed_gen[index]), queue); + ++shown; + } + } +} + +} // namespace x2w_dstorage_stats diff --git a/src/startup_stubs/gfx10_layout_equations.inc b/src/startup_stubs/gfx10_layout_equations.inc new file mode 100644 index 0000000000..0000cfca81 --- /dev/null +++ b/src/startup_stubs/gfx10_layout_equations.inc @@ -0,0 +1,62 @@ +// GENERATED by tests/gfx10_layout_check.cpp --print-equations from AMD addrlib (Mesa 5c142e46f3f6e752ed745fd48912ebb8fad67145, +// mesa-25.1.0, src/amd/addrlib, MIT; see gfx10_layout.h): [thick][4KB_S 4KB_D 64KB_S 64KB_D][log2 bytes]. +{ + { + {12, {0x00, 0x01, 0x02, 0x03, 0x40, 0x41, 0x42, 0x43, 0x44, 0x04, 0x45, 0x05, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0x00, 0x01, 0x02, 0x40, 0x41, 0x42, 0x03, 0x43, 0x04, 0x44, 0x05, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0x00, 0x01, 0x40, 0x41, 0x42, 0x02, 0x43, 0x03, 0x44, 0x04, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0xc2, 0x00, 0x40, 0x41, 0x01, 0x02, 0x42, 0x03, 0x43, 0x04, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0xc2, 0xc3, 0x40, 0x41, 0x00, 0x01, 0x42, 0x02, 0x43, 0x03, 0xff, 0xff, 0xff, 0xff}}, + }, + { + {12, {0x00, 0x01, 0x02, 0x41, 0x40, 0x42, 0x03, 0x43, 0x44, 0x04, 0x45, 0x05, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0x00, 0x01, 0x02, 0x40, 0x41, 0x42, 0x03, 0x43, 0x04, 0x44, 0x05, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0x00, 0x01, 0x40, 0x41, 0x42, 0x02, 0x43, 0x03, 0x44, 0x04, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0xc2, 0x00, 0x40, 0x01, 0x02, 0x41, 0x42, 0x03, 0x43, 0x04, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0xc2, 0xc3, 0x00, 0x40, 0x01, 0x41, 0x42, 0x02, 0x43, 0x03, 0xff, 0xff, 0xff, 0xff}}, + }, + { + {16, {0x00, 0x01, 0x02, 0x03, 0x40, 0x41, 0x42, 0x43, 0x44, 0x04, 0x45, 0x05, 0x46, 0x06, 0x47, 0x07}}, + {16, {0xc0, 0x00, 0x01, 0x02, 0x40, 0x41, 0x42, 0x03, 0x43, 0x04, 0x44, 0x05, 0x45, 0x06, 0x46, 0x07}}, + {16, {0xc0, 0xc1, 0x00, 0x01, 0x40, 0x41, 0x42, 0x02, 0x43, 0x03, 0x44, 0x04, 0x45, 0x05, 0x46, 0x06}}, + {16, {0xc0, 0xc1, 0xc2, 0x00, 0x40, 0x41, 0x01, 0x02, 0x42, 0x03, 0x43, 0x04, 0x44, 0x05, 0x45, 0x06}}, + {16, {0xc0, 0xc1, 0xc2, 0xc3, 0x40, 0x41, 0x00, 0x01, 0x42, 0x02, 0x43, 0x03, 0x44, 0x04, 0x45, 0x05}}, + }, + { + {16, {0x00, 0x01, 0x02, 0x41, 0x40, 0x42, 0x03, 0x43, 0x44, 0x04, 0x45, 0x05, 0x46, 0x06, 0x47, 0x07}}, + {16, {0xc0, 0x00, 0x01, 0x02, 0x40, 0x41, 0x42, 0x03, 0x43, 0x04, 0x44, 0x05, 0x45, 0x06, 0x46, 0x07}}, + {16, {0xc0, 0xc1, 0x00, 0x01, 0x40, 0x41, 0x42, 0x02, 0x43, 0x03, 0x44, 0x04, 0x45, 0x05, 0x46, 0x06}}, + {16, {0xc0, 0xc1, 0xc2, 0x00, 0x40, 0x01, 0x02, 0x41, 0x42, 0x03, 0x43, 0x04, 0x44, 0x05, 0x45, 0x06}}, + {16, {0xc0, 0xc1, 0xc2, 0xc3, 0x00, 0x40, 0x01, 0x41, 0x42, 0x02, 0x43, 0x03, 0x44, 0x04, 0x45, 0x05}}, + }, +}, +{ + { + {12, {0x00, 0x01, 0x80, 0x40, 0x81, 0x41, 0x02, 0x82, 0x42, 0x03, 0x83, 0x43, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0x00, 0x80, 0x40, 0x81, 0x41, 0x01, 0x82, 0x42, 0x02, 0x83, 0x43, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0x00, 0x40, 0x80, 0x41, 0x01, 0x81, 0x42, 0x02, 0x82, 0x43, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0xc2, 0x00, 0x80, 0x40, 0x01, 0x81, 0x41, 0x02, 0x82, 0x42, 0xff, 0xff, 0xff, 0xff}}, + {12, {0xc0, 0xc1, 0xc2, 0xc3, 0x80, 0x40, 0x00, 0x81, 0x41, 0x01, 0x82, 0x42, 0xff, 0xff, 0xff, 0xff}}, + }, + { + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + }, + { + {16, {0x00, 0x01, 0x80, 0x40, 0x81, 0x41, 0x02, 0x82, 0x42, 0x03, 0x83, 0x43, 0x04, 0x84, 0x44, 0x05}}, + {16, {0xc0, 0x00, 0x80, 0x40, 0x81, 0x41, 0x01, 0x82, 0x42, 0x02, 0x83, 0x43, 0x03, 0x84, 0x44, 0x04}}, + {16, {0xc0, 0xc1, 0x00, 0x40, 0x80, 0x41, 0x01, 0x81, 0x42, 0x02, 0x82, 0x43, 0x03, 0x83, 0x44, 0x04}}, + {16, {0xc0, 0xc1, 0xc2, 0x00, 0x80, 0x40, 0x01, 0x81, 0x41, 0x02, 0x82, 0x42, 0x03, 0x83, 0x43, 0x04}}, + {16, {0xc0, 0xc1, 0xc2, 0xc3, 0x80, 0x40, 0x00, 0x81, 0x41, 0x01, 0x82, 0x42, 0x02, 0x83, 0x43, 0x03}}, + }, + { + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {0, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + }, +}, diff --git a/src/startup_stubs/gfx10_layout_local.h b/src/startup_stubs/gfx10_layout_local.h new file mode 100644 index 0000000000..5e8a009539 --- /dev/null +++ b/src/startup_stubs/gfx10_layout_local.h @@ -0,0 +1,237 @@ +#pragma once + +// 0x106 SW_4KB_D, 0x109 SW_64KB_S, 0x10a SW_64KB_D; Layout field = gfx10 swizzle mode + 0x100), for detiling +// memory views into desktop textures. +// +// Derived from AMD addrlib as shipped in Mesa (src/amd/addrlib at commit 5c142e46f3f6e752ed745fd48912ebb8fad67145, +// tag mesa-25.1.0): the mip, tail and slice placement follows Gfx10Lib::ComputeSurfaceInfoMacroTiled, +// Gfx10Lib::HwlComputeSurfaceInfoLinear and Gfx10Lib::ComputeSurfaceAddrFromCoordMacroTiled (gfx10addrlib.cpp), +// the block dimensions Lib::ComputeThinBlockDimension / ComputeThickBlockDimension / GetMipTailDim +// (addrlib2.cpp), and the in-block equations below were generated from addrlib's own address computation +// (tests/gfx10_layout_check.cpp --print-equations, which also checks this table against addrlib). Only the +// non-XOR modes are covered: they do not depend on the pipe/bank configuration (GB_ADDR_CONFIG). +// +// addrlib notice: +// Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved. +// SPDX-License-Identifier: MIT +// 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 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. +// +// ASSUMED, not measured: the console lays a texture out as addrlib's gfx10 code does for the same swizzle mode, +// with no extra pitch or slice padding, and a memory view's address is the surface base. + +#include + +namespace x2w_startup::gfx10_local { + +constexpr unsigned sw_linear = 0, sw_4kb_s = 5, sw_4kb_d = 6, sw_64kb_s = 9, sw_64kb_d = 10; + +// Address bit i of a block comes from src[i]: 0x00|k element x bit k, 0x40|k y bit k, 0x80|k z bit k, +// 0xc0|k byte k inside the element. +struct Equation { + std::uint8_t bits; + std::uint8_t src[16]; +}; + +inline int mode_index(unsigned mode) +{ + switch (mode) { + case sw_4kb_s: return 0; + case sw_4kb_d: return 1; + case sw_64kb_s: return 2; + case sw_64kb_d: return 3; + default: return -1; + } +} + +// [thick][mode_index][log2 element bytes]; bits 0 = addrlib has no equation for the combination. +// GENERATED by tests/gfx10_layout_check.cpp --print-equations (addrlib, see above). +inline const Equation equations[2][4][5] = { +#include "gfx10_layout_equations.inc" +}; + +struct Level { + unsigned pitch = 0, height = 0; // in elements, as addrlib aligns them (for tail levels the tail's dimensions) + std::uint64_t offset = 0; // macroBlockOffset (tiled) or the level offset (linear), inside one slice + unsigned tail_x = 0, tail_y = 0, tail_z = 0; + bool in_tail = false; // addrlib's test: mipTailOffset != 0 +}; + +struct Layout { + bool valid = false, linear = false, thick = false; + unsigned mode = 0, elem_log2 = 0, block_log2 = 0, bw = 1, bh = 1, bd = 1; + unsigned mips = 0, slices = 0; + std::uint64_t slice_size = 0, size = 0; + const Equation* eq = nullptr; + Level level[16]; + + // Test-only mutations (tests/gfx10_layout_check.cpp negative controls). + enum Mutation { none, floor_mips, no_tail_coords }; + + // width/height in elements (4x4 blocks for BC); depth_or_array: volume depth for 3D, else array size. + Layout(unsigned swizzle_mode, bool is3d, unsigned elem_bytes, unsigned width, unsigned height, unsigned depth_or_array, + unsigned mip_count, Mutation mutation = none) + { + unsigned e = 0; + while ((1u << e) < elem_bytes) ++e; + if ((1u << e) != elem_bytes || e > 4 || !width || !height || !depth_or_array || !mip_count || mip_count > 15) return; + mode = swizzle_mode; + elem_log2 = e; + mips = mip_count; + const auto ceil_shift = [&](unsigned v, unsigned s) { + if (mutation == floor_mips) return (v >> s) ? (v >> s) : 1u; + return (v + (1u << s) - 1) >> s; + }; + const auto align = [](std::uint64_t v, std::uint64_t a) { return (v + a - 1) / a * a; }; + if (mode == sw_linear) { + linear = true; + const unsigned pitch_align = 256u >> e; + slices = depth_or_array; + std::uint64_t slice = 0; + for (int i = static_cast(mips) - 1; i >= 0; --i) { + Level& l = level[i]; + l.pitch = static_cast(align(ceil_shift(width, i), pitch_align)); + l.height = ceil_shift(height, i); + l.offset = slice; + slice += std::uint64_t{l.pitch} * l.height * elem_bytes; + } + slice_size = slice; + size = slice_size * slices; + valid = true; + return; + } + const int mi = mode_index(mode); + if (mi < 0) return; + thick = is3d; // the S and D modes are thick for 3D resources (Gfx10Lib::HwlIsThick) + eq = &equations[thick][mi][e]; + if (!eq->bits) return; + block_log2 = (mode == sw_4kb_s || mode == sw_4kb_d) ? 12 : 16; + if (!thick) { + const unsigned n = block_log2 - e, w = (n + 1) / 2; + bw = 1u << w; + bh = 1u << (n - w); + bd = 1; + } else { + static const unsigned b1k[5][3] = {{16, 8, 8}, {8, 8, 8}, {8, 8, 4}, {8, 4, 4}, {4, 4, 4}}; + const unsigned in1k = block_log2 - 10, avg = in1k / 3, rest = in1k % 3; + bw = b1k[e][0] << avg; + bh = b1k[e][1] << (avg + rest / 2); + bd = b1k[e][2] << (avg + (rest ? 1 : 0)); + } + const std::uint64_t block = std::uint64_t{1} << block_log2; + const unsigned pitch0 = static_cast(align(width, bw)), height0 = static_cast(align(height, bh)); + slices = static_cast(align(depth_or_array, bd)); + if (mips == 1) { + slice_size = std::uint64_t{pitch0} * height0 * elem_bytes; + size = slice_size * slices; + level[0].pitch = pitch0; + level[0].height = height0; + valid = true; + return; + } + unsigned tail_w = bw, tail_h = bh, tail_d = bd; + if (thick) { + const unsigned dim = block_log2 % 3; + if (dim == 0) tail_h >>= 1; + else if (dim == 1) tail_w >>= 1; + else tail_d >>= 1; + } else { + tail_w >>= 1; + } + (void)tail_d; + const unsigned depth0 = thick ? depth_or_array : 1; + unsigned effective = block_log2; + if (thick) effective -= (block_log2 - 8) / 3; + const unsigned max_in_tail = effective <= 11 ? 1 + (1u << (effective - 9)) : effective - 4; + unsigned first_tail = mips; + std::uint64_t chain = 0, mip_slice[16]{}; + for (unsigned i = 0; i < mips; ++i) { + const unsigned w = ceil_shift(width, i), h = ceil_shift(height, i), d = ceil_shift(depth0, i); + if (w <= tail_w && h <= tail_h && mips - i <= max_in_tail) { + first_tail = i; + chain += block / bd; + break; + } + const unsigned p = static_cast(align(w, bw)), hh = static_cast(align(h, bh)); + (void)d; + const std::uint64_t slice = std::uint64_t{p} * hh * elem_bytes; + mip_slice[i] = slice * bd; + chain += slice; + level[i].pitch = p; + level[i].height = hh; + } + slice_size = chain; + size = chain * slices; + std::uint64_t macro = first_tail != mips ? block : 0; + for (int i = static_cast(first_tail) - 1; i >= 0; --i) { + level[i].offset = macro; + macro += mip_slice[i]; + } + static const unsigned b256_2d[5][2] = {{16, 16}, {16, 8}, {8, 8}, {8, 4}, {4, 4}}; + static const unsigned b256_3d[5][3] = {{8, 4, 8}, {4, 4, 8}, {4, 4, 4}, {4, 2, 4}, {2, 2, 4}}; + unsigned pitch = tail_w, height_t = tail_h; + for (unsigned i = first_tail; i < mips; ++i) { + const unsigned m = max_in_tail - 1 - (i - first_tail); + const unsigned offset = m > 6 ? (16u << m) : (m << 8); + Level& l = level[i]; + l.offset = 0; + l.in_tail = offset != 0; + l.pitch = pitch; + l.height = height_t; + unsigned x = ((offset >> 9) & 1) | ((offset >> 10) & 2) | ((offset >> 11) & 4) | ((offset >> 12) & 8) | + ((offset >> 13) & 16) | ((offset >> 14) & 32); + unsigned y = ((offset >> 8) & 1) | ((offset >> 9) & 2) | ((offset >> 10) & 4) | ((offset >> 11) & 8) | + ((offset >> 12) & 16) | ((offset >> 13) & 32); + if (block_log2 & 1) { + const unsigned t = x; + x = y; + y = t; + if (e & 1) { + y = (y << 1) | (x & 1); + x >>= 1; + } + } + const unsigned ew = thick ? b256_3d[e][0] : b256_2d[e][0], eh = thick ? b256_3d[e][1] : b256_2d[e][1]; + if (mutation != no_tail_coords) { + l.tail_x = x * ew; + l.tail_y = y * eh; + } + pitch = pitch >> 1 > ew ? pitch >> 1 : ew; + height_t = height_t >> 1 > eh ? height_t >> 1 : eh; + } + valid = true; + } + + std::uint64_t block_offset(unsigned x, unsigned y, unsigned z) const + { + std::uint64_t off = 0; + for (unsigned i = 0; i < eq->bits; ++i) { + const unsigned s = eq->src[i], k = s & 0x3f; + const unsigned v = (s & 0xc0) == 0x00 ? x : (s & 0xc0) == 0x40 ? y : (s & 0xc0) == 0x80 ? z : 0; + off |= std::uint64_t{(v >> k) & 1} << i; + } + return off; + } + + // Byte offset of element (x, y) of slice or depth z in level mip, from the surface base. + std::uint64_t address(unsigned mip, unsigned x, unsigned y, unsigned z) const + { + const Level& l = level[mip]; + if (linear) return slice_size * z + l.offset + (std::uint64_t{y} * l.pitch + x) * (1u << elem_log2); + const std::uint64_t slice = thick ? slice_size * bd : slice_size; + const unsigned slice_id = thick ? z / bd : z; + const unsigned xx = l.in_tail ? x + l.tail_x : x, yy = l.in_tail ? y + l.tail_y : y, zz = l.in_tail ? z + l.tail_z : z; + const std::uint64_t blk = std::uint64_t{y / bh} * (l.pitch / bw) + x / bw; + return slice * slice_id + l.offset + (blk << block_log2) + block_offset(xx, yy, zz); + } +}; + +} // namespace x2w_startup::gfx10_local diff --git a/src/startup_stubs/gfx10_view_words.h b/src/startup_stubs/gfx10_view_words.h new file mode 100644 index 0000000000..61be905bef --- /dev/null +++ b/src/startup_stubs/gfx10_view_words.h @@ -0,0 +1,324 @@ +#pragma once + +// that the title created, in the console's own terms. +// +// - buffer_view_layout: where a buffer view starts and how an index steps through it. A typed buffer view +// (StructureByteStride 0, not RAW) steps by the format's element size, as the hardware buffer descriptor of a +// typed buffer holds stride = element size (buffer_load_format ... idxen addresses base + index * stride). +// - gfx10_format: the GFX10_FORMAT code (the 7-bit BUF_FMT / 9-bit IMG format of RDNA 1) of a DXGI format. +// - gfx10_buffer_words / gfx10_image_words: the dwords of the buffer (V#) or image (T#) descriptor that the +// console would hold for the view, for programs that read descriptor fields as numbers. +// +// Sources (public, Mesa revision bb59ce45, 2026-11-24): +// - src/amd/registers/gfx10-rsrc.json: field bits of SQ_BUF_RSRC_WORD1..3 and SQ_IMG_RSRC_WORD1..5, and the +// GFX10_FORMAT enum. +// - src/amd/registers/gfx6.json: SQ_RSRC_IMG_TYPE (1D 8, 2D 9, 3D 10, CUBE 11, 1D_ARRAY 12, 2D_ARRAY 13) and +// SQ_SEL_XYZW01 (0 0, 1 1, X 4, Y 5, Z 6, W 7). +// - src/amd/common/ac_descriptors.c: ac_build_buffer_descriptor (word1 = BASE_ADDRESS_HI | STRIDE, word2 = size), +// ac_build_raw_buffer_descriptor (format 32_FLOAT, swizzle XYZW, OOB_SELECT_RAW), and +// ac_build_gfx10_texture_descriptor (word1 FORMAT | WIDTH_LO(width - 1), word2 WIDTH_HI((width - 1) >> 2) | +// HEIGHT(height - 1), word3 DST_SEL | BASE_LEVEL | LAST_LEVEL | TYPE, word4 DEPTH | BASE_ARRAY with "Depth is +// the last accessible layer", word5 ARRAY_PITCH (3D: 0 SRV, 1 UAV) | MAX_MIP = levels - 1). +// - src/amd/common/gfx10_format_table.py: format names list channels from the most significant bits ("Keep the +// bit sizes in little-endian order"), so DXGI R10G10B10A2 is 2_10_10_10 and R11G11B10 is 10_11_11. +// +// Fields that are NOT synthesized and stay 0 (the runtime logs this once per kind): buffer base address (word0, +// word1 BASE_ADDRESS_HI), SWIZZLE_ENABLE, CACHE_SWIZZLE, INDEX_STRIDE, ADD_TID_ENABLE, RESOURCE_LEVEL; image base +// address (word0, word1 BASE_ADDRESS_HI), MIN_LOD, RESOURCE_LEVEL, SW_MODE, BC_SWIZZLE, PERF_MOD, words 6-7 +// (metadata / compression). +#include + +#include +#include + +namespace x2w_startup { + +namespace gfx10 { +constexpr std::uint32_t sel_0 = 0, sel_1 = 1, sel_x = 4, sel_y = 5, sel_z = 6, sel_w = 7; // SQ_SEL_XYZW01 +constexpr std::uint32_t dst_sel(std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint32_t w) +{ + return x | (y << 3) | (z << 6) | (w << 9); // DST_SEL_X [0,2], _Y [3,5], _Z [6,8], _W [9,11] +} +constexpr std::uint32_t xyzw = dst_sel(sel_x, sel_y, sel_z, sel_w), xyz1 = dst_sel(sel_x, sel_y, sel_z, sel_1), + xy01 = dst_sel(sel_x, sel_y, sel_0, sel_1), x001 = dst_sel(sel_x, sel_0, sel_0, sel_1), + zyxw = dst_sel(sel_z, sel_y, sel_x, sel_w), zyx1 = dst_sel(sel_z, sel_y, sel_x, sel_1), + a8 = dst_sel(sel_0, sel_0, sel_0, sel_x); +constexpr std::uint32_t img_1d = 8, img_2d = 9, img_3d = 10, img_cube = 11, img_1d_array = 12, img_2d_array = 13; // SQ_RSRC_IMG_TYPE +constexpr std::uint32_t format_32_float = 22; +constexpr std::uint32_t oob_structured_with_offset = 0, oob_raw = 3; // SQ_BUF_RSRC_WORD3__OOB_SELECT +} // namespace gfx10 + +struct Gfx10Format { + std::uint32_t code = 0; // GFX10_FORMAT; 0 = not mapped + std::uint32_t bytes = 0; // element bytes when usable as a buffer format, else 0 + std::uint32_t dst_sel = 0; // DST_SEL_X..W of the channels the format has +}; + +// The GFX10_FORMAT of a desktop DXGI format (typed, not typeless). Unmapped formats return code 0. +inline Gfx10Format gfx10_format(DXGI_FORMAT f) +{ + using namespace gfx10; + switch (f) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: return {77, 16, xyzw}; + case DXGI_FORMAT_R32G32B32A32_UINT: return {75, 16, xyzw}; + case DXGI_FORMAT_R32G32B32A32_SINT: return {76, 16, xyzw}; + case DXGI_FORMAT_R32G32B32_FLOAT: return {74, 12, xyz1}; + case DXGI_FORMAT_R32G32B32_UINT: return {72, 12, xyz1}; + case DXGI_FORMAT_R32G32B32_SINT: return {73, 12, xyz1}; + case DXGI_FORMAT_R16G16B16A16_FLOAT: return {71, 8, xyzw}; + case DXGI_FORMAT_R16G16B16A16_UNORM: return {65, 8, xyzw}; + case DXGI_FORMAT_R16G16B16A16_UINT: return {69, 8, xyzw}; + case DXGI_FORMAT_R16G16B16A16_SNORM: return {66, 8, xyzw}; + case DXGI_FORMAT_R16G16B16A16_SINT: return {70, 8, xyzw}; + case DXGI_FORMAT_R32G32_FLOAT: return {64, 8, xy01}; + case DXGI_FORMAT_R32G32_UINT: return {62, 8, xy01}; + case DXGI_FORMAT_R32G32_SINT: return {63, 8, xy01}; + case DXGI_FORMAT_R10G10B10A2_UNORM: return {50, 4, xyzw}; // 2_10_10_10_UNORM + case DXGI_FORMAT_R10G10B10A2_UINT: return {54, 4, xyzw}; // 2_10_10_10_UINT + case DXGI_FORMAT_R11G11B10_FLOAT: return {36, 4, xyz1}; // 10_11_11_FLOAT + case DXGI_FORMAT_R8G8B8A8_UNORM: return {56, 4, xyzw}; + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return {130, 0, xyzw}; // 8_8_8_8_SRGB (image only) + case DXGI_FORMAT_R8G8B8A8_UINT: return {60, 4, xyzw}; + case DXGI_FORMAT_R8G8B8A8_SNORM: return {57, 4, xyzw}; + case DXGI_FORMAT_R8G8B8A8_SINT: return {61, 4, xyzw}; + case DXGI_FORMAT_B8G8R8A8_UNORM: return {56, 4, zyxw}; + case DXGI_FORMAT_B8G8R8X8_UNORM: return {56, 4, zyx1}; + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return {130, 0, zyxw}; + case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return {130, 0, zyx1}; + case DXGI_FORMAT_R16G16_FLOAT: return {29, 4, xy01}; + case DXGI_FORMAT_R16G16_UNORM: return {23, 4, xy01}; + case DXGI_FORMAT_R16G16_UINT: return {27, 4, xy01}; + case DXGI_FORMAT_R16G16_SNORM: return {24, 4, xy01}; + case DXGI_FORMAT_R16G16_SINT: return {28, 4, xy01}; + case DXGI_FORMAT_D32_FLOAT: return {22, 0, x001}; + case DXGI_FORMAT_R32_FLOAT: return {22, 4, x001}; + case DXGI_FORMAT_R32_UINT: return {20, 4, x001}; + case DXGI_FORMAT_R32_SINT: return {21, 4, x001}; + case DXGI_FORMAT_R8G8_UNORM: return {14, 2, xy01}; + case DXGI_FORMAT_R8G8_UINT: return {18, 2, xy01}; + case DXGI_FORMAT_R8G8_SNORM: return {15, 2, xy01}; + case DXGI_FORMAT_R8G8_SINT: return {19, 2, xy01}; + case DXGI_FORMAT_R16_FLOAT: return {13, 2, x001}; + case DXGI_FORMAT_D16_UNORM: return {7, 0, x001}; + case DXGI_FORMAT_R16_UNORM: return {7, 2, x001}; + case DXGI_FORMAT_R16_UINT: return {11, 2, x001}; + case DXGI_FORMAT_R16_SNORM: return {8, 2, x001}; + case DXGI_FORMAT_R16_SINT: return {12, 2, x001}; + case DXGI_FORMAT_R8_UNORM: return {1, 1, x001}; + case DXGI_FORMAT_R8_UINT: return {5, 1, x001}; + case DXGI_FORMAT_R8_SNORM: return {2, 1, x001}; + case DXGI_FORMAT_R8_SINT: return {6, 1, x001}; + case DXGI_FORMAT_A8_UNORM: return {1, 1, a8}; + case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: return {132, 0, xyz1}; // 5_9_9_9_FLOAT + // Depth/stencil as Mesa's hardcoded table (Z24_UNORM_S8_UINT 8_24_UNORM, Z32_FLOAT_S8X24 X24_8_32_FLOAT). + case DXGI_FORMAT_D24_UNORM_S8_UINT: case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: return {141, 0, x001}; + case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: return {146, 0, x001}; + case DXGI_FORMAT_BC1_UNORM: return {169, 0, xyzw}; + case DXGI_FORMAT_BC1_UNORM_SRGB: return {170, 0, xyzw}; + case DXGI_FORMAT_BC2_UNORM: return {171, 0, xyzw}; + case DXGI_FORMAT_BC2_UNORM_SRGB: return {172, 0, xyzw}; + case DXGI_FORMAT_BC3_UNORM: return {173, 0, xyzw}; + case DXGI_FORMAT_BC3_UNORM_SRGB: return {174, 0, xyzw}; + case DXGI_FORMAT_BC4_UNORM: return {175, 0, x001}; + case DXGI_FORMAT_BC4_SNORM: return {176, 0, x001}; + case DXGI_FORMAT_BC5_UNORM: return {177, 0, xy01}; + case DXGI_FORMAT_BC5_SNORM: return {178, 0, xy01}; + case DXGI_FORMAT_BC6H_UF16: return {179, 0, xyz1}; + case DXGI_FORMAT_BC6H_SF16: return {180, 0, xyz1}; + case DXGI_FORMAT_BC7_UNORM: return {181, 0, xyzw}; + case DXGI_FORMAT_BC7_UNORM_SRGB: return {182, 0, xyzw}; + default: return {}; + } +} + +// ---- Buffer views ---------------------------------------------------------------------------------------------- +enum class BufferViewKind { raw, structured, typed, unknown }; +struct BufferViewLayout { + BufferViewKind kind = BufferViewKind::unknown; + std::uint64_t offset = 0; // bytes from the resource start to element 0 + std::uint64_t bytes = 0; // bytes the view covers + std::uint32_t index_stride = 0; // bytes per index step (descriptor STRIDE); 0 for raw views + std::uint32_t num_records = 0; // descriptor NUM_RECORDS: elements when strided, bytes when raw + Gfx10Format format{}; // typed views only +}; + +// first_element/count/structure_stride/flags as in D3D12_BUFFER_SRV / D3D12_BUFFER_UAV (flags bit 0 = RAW in both). +// legacy = the behaviour before the typed-view fix (element 4 bytes when the stride is 0, index stride 0). +inline BufferViewLayout buffer_view_layout(DXGI_FORMAT format, std::uint64_t first_element, std::uint32_t count, + std::uint32_t structure_stride, std::uint32_t flags, bool legacy = false) +{ + BufferViewLayout l; + std::uint32_t element = 4; + if (legacy) { + element = structure_stride ? structure_stride : 4; + l.kind = structure_stride ? BufferViewKind::structured : BufferViewKind::unknown; + l.index_stride = structure_stride; + } else if (structure_stride) { + element = structure_stride; + l.kind = BufferViewKind::structured; + l.index_stride = structure_stride; + } else if ((flags & 1) || format == DXGI_FORMAT_R32_TYPELESS) { + l.kind = BufferViewKind::raw; + } else if (const Gfx10Format f = gfx10_format(format); f.code && f.bytes) { + element = f.bytes; + l.kind = BufferViewKind::typed; + l.index_stride = f.bytes; + l.format = f; + } + l.offset = first_element * element; + l.bytes = std::uint64_t{count} * element; + l.num_records = l.index_stride ? count : static_cast(l.bytes); + return l; +} + +// The buffer part of a recorded D3D12 view description: slot 18 SRV {Format, ViewDimension, Mapping, Buffer at 16}, +// slot 19 UAV {Format, ViewDimension, Buffer at 8}; Buffer = {FirstElement u64, NumElements, StructureByteStride, +// (UAV: CounterOffsetInBytes u64), Flags}, so Flags is at byte 32 in both. False when it is not a buffer view. +inline bool buffer_view_layout_from_desc(bool uav, const unsigned char* desc, std::size_t bytes, BufferViewLayout& out, bool legacy = false) +{ + if (bytes < 36) return false; + std::uint32_t format = 0, dim = 0, count = 0, stride = 0, flags = 0; + std::uint64_t first = 0; + const std::size_t at = uav ? 8 : 16; + std::memcpy(&format, desc, 4); + std::memcpy(&dim, desc + 4, 4); + if (dim != 1) return false; // D3D12_SRV_DIMENSION_BUFFER == D3D12_UAV_DIMENSION_BUFFER == 1 + std::memcpy(&first, desc + at, 8); + std::memcpy(&count, desc + at + 8, 4); + std::memcpy(&stride, desc + at + 12, 4); + std::memcpy(&flags, desc + 32, 4); + out = buffer_view_layout(static_cast(format), first, count, stride, flags, legacy); + return true; +} + +// V# dwords 0..3 (4..7 = 0) for a buffer view. Word 0 / BASE_ADDRESS_HI stay 0 (no address is synthesized). +inline void gfx10_buffer_words(const BufferViewLayout& l, std::uint32_t out[8]) +{ + using namespace gfx10; + std::memset(out, 0, 8 * sizeof(std::uint32_t)); + out[1] = (l.index_stride & 0x3fff) << 16; // STRIDE [16,29] + out[2] = l.num_records; // NUM_RECORDS + const bool typed = l.kind == BufferViewKind::typed; + const std::uint32_t format = typed ? l.format.code : format_32_float; + const std::uint32_t sel = typed ? l.format.dst_sel : xyzw; + const std::uint32_t oob = l.index_stride ? oob_structured_with_offset : oob_raw; + out[3] = sel | ((format & 127) << 12) | (oob << 28); // FORMAT [12,18], OOB_SELECT [28,29], TYPE [30,31] = 0 +} + +// ---- Image views ----------------------------------------------------------------------------------------------- +struct ImageViewFacts { + // the resource (desktop description; same extent as the title's) + D3D12_RESOURCE_DIMENSION dimension = D3D12_RESOURCE_DIMENSION_UNKNOWN; + std::uint64_t width = 0; + std::uint32_t height = 0, depth_or_array = 0, mip_levels = 0; + // the view + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; // typed view format (typeless already mapped) + std::uint32_t view_dimension = 0; // D3D12_SRV_DIMENSION / D3D12_UAV_DIMENSION value (same numbers here) + bool uav = false; + std::uint32_t base_level = 0, level_count = 0; // level_count 0xffffffff: to the last level + std::uint32_t first_slice = 0, slice_count = 0; +}; + +// Reads the view part of a recorded D3D12 view description (slot 18 SRV: union at byte 16; slot 19 UAV: at byte 8). +// False for buffer, multisampled or unknown view dimensions. +inline bool image_view_from_desc(bool uav, const unsigned char* desc, std::size_t bytes, ImageViewFacts& v) +{ + if (bytes < 8) return false; + std::uint32_t f = 0, dim = 0, u[6] = {}; + std::memcpy(&f, desc, 4); + std::memcpy(&dim, desc + 4, 4); + const std::size_t at = uav ? 8 : 16; + if (bytes < at + sizeof(u)) return false; + std::memcpy(u, desc + at, sizeof(u)); + v.format = static_cast(f); + v.view_dimension = dim; + v.uav = uav; + v.first_slice = 0; + v.slice_count = 1; + if (uav) { + // UAV: Texture1D {MipSlice}, 1DArray {MipSlice, First, Size}, 2D {MipSlice, Plane}, 2DArray {MipSlice, First, + // Size, Plane}, 3D {MipSlice, FirstWSlice, WSize} + v.base_level = u[0]; + v.level_count = 1; + if (dim == D3D12_UAV_DIMENSION_TEXTURE1DARRAY || dim == D3D12_UAV_DIMENSION_TEXTURE2DARRAY || dim == D3D12_UAV_DIMENSION_TEXTURE3D) { + v.first_slice = u[1]; + v.slice_count = u[2]; + } else if (dim != D3D12_UAV_DIMENSION_TEXTURE1D && dim != D3D12_UAV_DIMENSION_TEXTURE2D) { + return false; + } + return true; + } + // SRV: {MostDetailedMip, MipLevels, ...}; arrays add FirstArraySlice, ArraySize; cube array First2DArrayFace, NumCubes + v.base_level = u[0]; + v.level_count = u[1]; + switch (dim) { + case D3D12_SRV_DIMENSION_TEXTURE1D: case D3D12_SRV_DIMENSION_TEXTURE2D: case D3D12_SRV_DIMENSION_TEXTURE3D: break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: v.first_slice = u[2]; v.slice_count = u[3]; break; + case D3D12_SRV_DIMENSION_TEXTURECUBE: v.slice_count = 6; break; + case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: v.first_slice = u[2]; v.slice_count = 6 * u[3]; break; + default: return false; + } + return true; +} + +// T# dwords 0..7. False (all words 0) when the view cannot be described; unmapped_format is set when the format +// has no GFX10_FORMAT (the words are still written, with FORMAT 0). +inline bool gfx10_image_words(const ImageViewFacts& v, std::uint32_t out[8], bool* unmapped_format = nullptr) +{ + using namespace gfx10; + std::memset(out, 0, 8 * sizeof(std::uint32_t)); + if (unmapped_format) *unmapped_format = false; + if (!v.width || !v.height || !v.mip_levels) return false; + std::uint32_t type = 0; + const bool three_d = v.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + switch (v.view_dimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: type = img_1d; break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: type = img_1d_array; break; + case D3D12_SRV_DIMENSION_TEXTURE2D: type = img_2d; break; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: type = img_2d_array; break; + case D3D12_SRV_DIMENSION_TEXTURE3D: type = img_3d; break; // D3D12_UAV_DIMENSION_TEXTURE3D is also 8 + case D3D12_SRV_DIMENSION_TEXTURECUBE: case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: type = v.uav ? 0 : img_cube; break; + default: break; + } + if (!type || (type == img_3d) != three_d) return false; + const Gfx10Format f = gfx10_format(v.format); + if (!f.code && unmapped_format) *unmapped_format = true; + const std::uint32_t w = static_cast(v.width - 1), h = v.height - 1; + std::uint32_t base = v.base_level < v.mip_levels ? v.base_level : 0; + std::uint32_t count = v.level_count == 0xffffffffu || v.level_count == 0 || base + v.level_count > v.mip_levels ? v.mip_levels - base : v.level_count; + const std::uint32_t last = base + count - 1; + out[1] = ((f.code & 511) << 20) | ((w & 3) << 30); // FORMAT [20,28], WIDTH_LO [30,31] + out[2] = ((w >> 2) & 0xfff) | ((h & 0x3fff) << 14); // WIDTH_HI [0,11], HEIGHT [14,27] + out[3] = (f.code ? f.dst_sel : xyzw) | ((base & 15) << 12) | ((last & 15) << 16) | (type << 28); // BASE/LAST_LEVEL, TYPE + std::uint32_t depth = 0, base_array = 0, array_pitch = 0; + if (type == img_3d) { + if (v.uav) { // UAV mode: BASE_ARRAY first slice, DEPTH last slice of the bound level + const std::uint32_t level_depth = (v.depth_or_array >> base) ? (v.depth_or_array >> base) : 1; + const std::uint32_t first = v.first_slice < level_depth ? v.first_slice : 0; + const std::uint32_t n = v.slice_count == 0xffffffffu || first + v.slice_count > level_depth ? level_depth - first : v.slice_count; + depth = first + n - 1; + base_array = first; + array_pitch = 1; + } else { + depth = v.depth_or_array - 1; // SRV mode: last slice of level 0 + } + } else if (type == img_1d_array || type == img_2d_array || type == img_cube) { + const std::uint32_t layers = v.depth_or_array ? v.depth_or_array : 1; + const std::uint32_t first = v.first_slice < layers ? v.first_slice : 0; + const std::uint32_t n = v.slice_count == 0 || v.slice_count == 0xffffffffu || first + v.slice_count > layers ? layers - first : v.slice_count; + depth = first + n - 1; // the last accessible layer + base_array = first; + } + out[4] = (depth & 0x1fff) | ((base_array & 0x1fff) << 16); // DEPTH [0,12], BASE_ARRAY [16,28] + out[5] = (array_pitch & 15) | (((v.mip_levels - 1) & 15) << 4); // ARRAY_PITCH [0,3], MAX_MIP [4,7] + return true; +} + +// The UAV format of an integer texture UAV (manifest kind tex2du, RWTexture2D) over a resource of this format: +// R32_UINT, or UNKNOWN when D3D12 does not allow an R32_UINT view of it. +inline DXGI_FORMAT integer_uav_format(DXGI_FORMAT resource_format) +{ + return resource_format == DXGI_FORMAT_R32_TYPELESS || resource_format == DXGI_FORMAT_R32_UINT ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_UNKNOWN; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/local_log.h b/src/startup_stubs/local_log.h index bea306fde9..9ba8d129a7 100644 --- a/src/startup_stubs/local_log.h +++ b/src/startup_stubs/local_log.h @@ -2,10 +2,14 @@ // permissive startup paths. Lines go to stderr and are appended to %X2W_TRAP_LOG% when set. #pragma once +#include "startup_stubs/log_cap.h" #include "startup_stubs/trap.h" #include +#include +#include #include +#include namespace x2w_local { @@ -33,35 +37,103 @@ inline void logf(const char* format, ...) noexcept line[n++] = '\n'; const DWORD error = GetLastError(); x2w_trap::write_all(GetStdHandle(STD_ERROR_HANDLE), line, static_cast(n)); - x2w_trap::append_log(line, static_cast(n), false); + x2w_trap::append_trap_log(line, static_cast(n)); // one open handle per module (trap.h) SetLastError(error); } -// True for the first `limit` calls on `counter`. The counter stops at the limit instead of counting -// every call: a gate on a hot path would otherwise pass 2^31 calls, turn negative and pass again. -inline bool first_calls(volatile LONG& counter, LONG limit) noexcept -{ - LONG seen = counter; - while (seen < limit) { - const LONG previous = InterlockedCompareExchange(&counter, seen + 1, seen); - if (previous == seen) return true; - seen = previous; - } - return false; -} +// first_calls (a saturating log cap) is in startup_stubs/log_cap.h. // Number of contiguous readable bytes at start, up to bytes, found by touching one byte per page. // VirtualQuery is not used for this: on the title's multi-gigabyte regions one query takes about a // millisecond (it walks the region to size it). A bad pointer costs a first-chance exception, so // callers on hot paths should pass values that normally are pointers. A guard page that the probe // trips is re-armed. +struct ProbeCache { + struct Range { std::uintptr_t start, end; ULONGLONG until; }; + static constexpr unsigned size = 64; + SRWLOCK lock = SRWLOCK_INIT; + Range ranges[size] = {}; + unsigned next = 0; + volatile LONG64 hits = 0, faults = 0, cached = 0, queries = 0, query_ticks = 0; + volatile LONG generation = 0; // invalidate_probe_cache: entries of an older generation are ignored + LONG range_generation[size] = {}; +}; +inline ProbeCache& probe_cache() noexcept +{ + static ProbeCache cache; + return cache; +} +inline bool probe_cache_on() noexcept +{ + static const bool on = env_on("X2W_PROBE_CACHE"); + return on; +} +inline ULONGLONG probe_cache_ms() noexcept +{ + static const ULONGLONG ms = [] { + const DWORD saved = GetLastError(); + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_PROBE_CACHE_MS", value, sizeof(value)); + SetLastError(saved); + const unsigned long parsed = n && n < sizeof(value) ? std::strtoul(value, nullptr, 10) : 100; + return static_cast(parsed); + }(); + return ms; +} +inline void invalidate_probe_cache() noexcept { InterlockedIncrement(&probe_cache().generation); } +// The end of the part of [start, end) before the first cached unreadable range; start itself when start is in one. +inline std::uintptr_t probe_cache_clamp(std::uintptr_t start, std::uintptr_t end) noexcept +{ + ProbeCache& c = probe_cache(); + const ULONGLONG now = GetTickCount64(); + const LONG generation = c.generation; + AcquireSRWLockShared(&c.lock); + for (unsigned i = 0; i < ProbeCache::size; ++i) { + const ProbeCache::Range& r = c.ranges[i]; + if (r.end <= r.start || now >= r.until || c.range_generation[i] != generation || r.end <= start || r.start >= end) continue; + end = r.start <= start ? start : r.start; + if (end == start) break; + } + ReleaseSRWLockShared(&c.lock); + return end; +} +inline void probe_cache_fault(std::uintptr_t at) noexcept +{ + ProbeCache& c = probe_cache(); + InterlockedIncrement64(&c.faults); + MEMORY_BASIC_INFORMATION info{}; + LARGE_INTEGER t0, t1; + QueryPerformanceCounter(&t0); + const SIZE_T got = VirtualQuery(reinterpret_cast(at), &info, sizeof(info)); + QueryPerformanceCounter(&t1); + InterlockedIncrement64(&c.queries); + InterlockedAdd64(&c.query_ticks, t1.QuadPart - t0.QuadPart); + if (got != sizeof(info) || !info.RegionSize) return; + const DWORD protect = info.Protect & 0xFF; + const bool unreadable = info.State != MEM_COMMIT || protect == PAGE_NOACCESS || protect == 0; + if (!unreadable || (info.Protect & PAGE_GUARD)) return; + const auto begin = reinterpret_cast(info.BaseAddress); + AcquireSRWLockExclusive(&c.lock); + const unsigned slot = c.next++ % ProbeCache::size; + c.ranges[slot] = {begin, begin + info.RegionSize, GetTickCount64() + probe_cache_ms()}; + c.range_generation[slot] = c.generation; + ReleaseSRWLockExclusive(&c.lock); + InterlockedIncrement64(&c.cached); +} inline std::size_t probe_readable(std::uintptr_t start, std::size_t bytes) noexcept { if (start < 0x10000 || start > 0x00007FFFFFFEFFFFull || bytes == 0) return 0; std::size_t done = 0; DWORD code = 0; std::uintptr_t at = start; - const std::uintptr_t end = start + bytes; + std::uintptr_t end = start + bytes; + const bool cache = probe_cache_on(); + if (cache) { + const std::uintptr_t clamped = probe_cache_clamp(start, end); + if (clamped != end) InterlockedIncrement64(&probe_cache().hits); + end = clamped; + if (end == start) return 0; + } __try { volatile unsigned char sink = 0; while (at < end) { @@ -77,6 +149,8 @@ inline std::size_t probe_readable(std::uintptr_t start, std::size_t bytes) noexc DWORD old = 0; if (VirtualQuery(reinterpret_cast(at), &info, sizeof(info)) && info.State == MEM_COMMIT) VirtualProtect(reinterpret_cast(at & ~std::uintptr_t{0xFFF}), 0x1000, info.Protect | PAGE_GUARD, &old); + } else if (cache) { + probe_cache_fault(at); } } return done; diff --git a/src/startup_stubs/log_cap.h b/src/startup_stubs/log_cap.h new file mode 100644 index 0000000000..78798298bf --- /dev/null +++ b/src/startup_stubs/log_cap.h @@ -0,0 +1,33 @@ +// Experimental (docs/startup-runtime.md): caps for diagnostic log lines in the startup stand-ins. +// +// The old pattern `static LONG calls; if (InterlockedIncrement(&calls) <= N) log(...)` wraps after +// 2^31 calls: the counter turns negative, `<= N` holds again, and the line is logged on every call for +// the next two billion calls. A title that polls a stand-in at tens of millions of calls per second +// reaches that in under a minute (a status poll did, and wrote 7.8 million identical lines). +#pragma once + +#include + +namespace x2w_local { + +// True for the first `limit` calls that reach it, false for every later one, from any number of +// threads. The counter never goes past limit + 1, and once it is there a call only reads it: no +// interlocked write, so a hot caller does not keep moving the counter's cache line between cores. +// For a pure log budget only: a counter that is also reported as a total must keep counting (see +// first_of below). +inline bool first_calls(volatile LONG& counter, LONG limit) noexcept +{ + LONG seen = counter; + for (;;) { + if (seen > limit) return false; + const LONG prior = InterlockedCompareExchange(&counter, seen + 1, seen); + if (prior == seen) return seen + 1 <= limit; + seen = prior; + } +} + +// For a count that is also a statistic (it must keep counting): true when the value an increment +// returned is one of the first `limit`, false once the count has wrapped negative. +inline bool first_of(LONG count, LONG limit) noexcept { return count > 0 && count <= limit; } + +} // namespace x2w_local diff --git a/src/startup_stubs/overlay_window.h b/src/startup_stubs/overlay_window.h index bf8c13e73f..daae37ebb4 100644 --- a/src/startup_stubs/overlay_window.h +++ b/src/startup_stubs/overlay_window.h @@ -19,6 +19,19 @@ inline bool is_title_window(HWND candidate, wchar_t (&name)[256]) return GetClassNameW(candidate, name, 256) && lstrcmpW(name, presenter_class) != 0; } +inline HWND title_picture_window() +{ + HWND window = nullptr; + EnumWindows([](HWND candidate, LPARAM out) -> BOOL { + wchar_t name[256]{}; + if (!is_title_window(candidate, name) || lstrcmpW(name, dialog_class) == 0 || + (GetWindowLongPtrW(candidate, GWL_EXSTYLE) & WS_EX_TOOLWINDOW)) return TRUE; + *reinterpret_cast(out) = candidate; + return FALSE; + }, reinterpret_cast(&window)); + return window; +} + inline HWND overlay_window() { HWND window = nullptr; diff --git a/src/startup_stubs/pipeline_state_decode.h b/src/startup_stubs/pipeline_state_decode.h index 77f5842191..2ad421a756 100644 --- a/src/startup_stubs/pipeline_state_decode.h +++ b/src/startup_stubs/pipeline_state_decode.h @@ -1,6 +1,17 @@ -// Experimental (docs/startup-runtime.md): the depth-stencil state of a pipeline created through -// device slot 57, decoded from the register words in its state block A (#1999, item A). +// Experimental (docs/startup-runtime.md): fixed-function state of a pipeline created through device +// slot 57, decoded from its state block A, plus the desktop-layout parts a slot 55 derivation patches. // + +// layout notes; mesh pipelines, A+0x004 == 6, carry the same fields 0x54 bytes later from +0x058 on): +// +0x078 CB_SHADER_MASK, +0x09c PA_CL_CLIP_CNTL, +0x0a0 PA_SU_SC_MODE_CNTL, +// +0x0ac / +0x0b0 / +0x0b4 three floats taken as PA_SU_POLY_OFFSET_CLAMP / _FRONT_SCALE / _FRONT_OFFSET +// (the hardware register order; value ranges fit, not measured), +0x0b8 DB_DEPTH_CONTROL, +// +0x0bc DB_STENCIL_CONTROL, +0x0c0 / +0x0c4 DB_STENCILREFMASK / _BF, +0x0cc CB_TARGET_MASK, +// +0x0d0 .. +0x0ec CB_BLEND0..7_CONTROL (decoded by cb_blend.h). +// Field layouts and enumerations: Mesa's src/amd/registers/gfx10.json (MIT). Facing and polygon offset +// conventions as Mesa's RADV programs them (src/amd/vulkan/radv_cmd_buffer.c: FACE = VkFrontFace, so + +// as vkd3d-proton maps D3D12 (FrontCounterClockwise -> VK_FRONT_FACE_COUNTER_CLOCKWISE). // State block A holds DB_DEPTH_CONTROL at +0xB8, DB_STENCIL_CONTROL at +0xBC and DB_STENCILREFMASK / // DB_STENCILREFMASK_BF at +0xC0 / +0xC4, before the CB_BLENDn_CONTROL words at +0xD0 (#1216). The // positions were measured locally on the vertex-pipeline layout, whose word at +0x004 is 4. @@ -9,34 +20,65 @@ // on sits 0x54 bytes later (so DB_DEPTH_CONTROL is at +0x10C), and the words before +0x058 keep their // offsets. Also measured locally; a block with any other value at +0x004 is read at the vertex offsets. // -// Field layouts and enumerations follow Mesa's src/amd/registers/gfx10.json (MIT): DB_DEPTH_CONTROL -// STENCIL_ENABLE [0], Z_ENABLE [1], Z_WRITE_ENABLE [2], DEPTH_BOUNDS_ENABLE [3], ZFUNC [6:4], -// BACKFACE_ENABLE [7], STENCILFUNC [10:8], STENCILFUNC_BF [22:20], ENABLE_COLOR_WRITES_ON_DEPTH_FAIL [30], -// DISABLE_COLOR_WRITES_ON_DEPTH_PASS [31]; DB_STENCIL_CONTROL STENCILFAIL [3:0], STENCILZPASS [7:4], -// STENCILZFAIL [11:8] and the _BF fields at [15:12], [19:16], [23:20]; DB_STENCILREFMASK STENCILTESTVAL -// [7:0], STENCILMASK [15:8], STENCILWRITEMASK [23:16], STENCILOPVAL [31:24]; CompareFrag FRAG_NEVER (0) -// .. FRAG_ALWAYS (7); StencilOp STENCIL_KEEP (0) .. STENCIL_XNOR (15). -// -// Pure functions, not used by the draw path yet. A form D3D12 cannot express is refused with a -// reason so the caller can keep the state it had before. +// Pure functions; a form D3D12 cannot express is refused with a reason (or, where noted, approximated +// and flagged) so the caller can keep its previous state and count the cause. #pragma once +#include "cb_blend.h" + #include +#include #include #include #include namespace x2w_pipeline_state { -// ---- state block A offsets (vertex-pipeline layout) ---- -constexpr std::size_t a_depth = 0x0b8, a_stencil = 0x0bc, a_refmask = 0x0c0, a_refmask_bf = 0x0c4; -// The mesh-pipeline layout: the word at +0x004 and the shift applied from +0x058 on. -constexpr std::size_t a_layout = 0x004, a_mesh_shift_from = 0x058, a_mesh_shift = 0x54; -constexpr std::uint32_t a_layout_mesh = 6; +// ---- state block A offsets (vertex / keyed pipelines; mesh_shift added from +0x058 on) ---- +constexpr std::size_t a_shader_mask = 0x078, a_clip = 0x09c, a_mode = 0x0a0, a_bias = 0x0ac, a_depth = 0x0b8, + a_stencil = 0x0bc, a_refmask = 0x0c0, a_refmask_bf = 0x0c4, a_target_mask = 0x0cc, a_blend = 0x0d0; +constexpr std::size_t mesh_shift = 0x54; constexpr std::uint32_t bits(std::uint32_t v, unsigned lo, unsigned hi) { return (v >> lo) & ((1u << (hi - lo + 1)) - 1); } +// The register words of one state block A. +struct Words { + std::uint32_t shader_mask = 0, clip = 0, mode = 0, depth = 0, stencil = 0, refmask = 0, refmask_bf = 0, target_mask = 0; + std::uint32_t blend[8] = {}; + float bias_clamp = 0, bias_scale = 0, bias_offset = 0; + bool mesh = false; +}; + +inline bool read_words(const unsigned char* a, std::size_t bytes, Words& w) +{ + if (!a || bytes < 8) return false; + std::uint32_t kind; + std::memcpy(&kind, a + 4, 4); + w.mesh = kind == 6; + const std::size_t s = w.mesh ? mesh_shift : 0; + if (bytes < a_blend + s + 32) return false; + auto u = [&](std::size_t off) { std::uint32_t v; std::memcpy(&v, a + off + s, 4); return v; }; + auto f = [&](std::size_t off) { float v; std::memcpy(&v, a + off + s, 4); return v; }; + w.shader_mask = u(a_shader_mask); + w.clip = u(a_clip); + w.mode = u(a_mode); + w.bias_clamp = f(a_bias); + w.bias_scale = f(a_bias + 4); + w.bias_offset = f(a_bias + 8); + w.depth = u(a_depth); + w.stencil = u(a_stencil); + w.refmask = u(a_refmask); + w.refmask_bf = u(a_refmask_bf); + w.target_mask = u(a_target_mask); + for (unsigned i = 0; i < 8; ++i) w.blend[i] = u(a_blend + 4 * i); + return true; +} + +// The mesh-pipeline layout: the word at +0x004 and the shift applied from +0x058 on. +constexpr std::size_t a_layout = 0x004, a_mesh_shift_from = 0x058, a_mesh_shift = mesh_shift; +constexpr std::uint32_t a_layout_mesh = 6; + // Bytes to add to a vertex-layout offset at or after +0x058 for this block (0 or a_mesh_shift). inline std::size_t state_block_a_shift(const unsigned char* a, std::size_t bytes) { @@ -66,12 +108,13 @@ inline bool read_depth_stencil_words(const unsigned char* a, std::size_t bytes, return true; } +// ---- depth / stencil: DB_DEPTH_CONTROL, DB_STENCIL_CONTROL, DB_STENCILREFMASK(_BF) ---- struct DepthStencil { bool ok = false; const char* reason = nullptr; D3D12_DEPTH_STENCIL_DESC desc{}; std::uint8_t stencil_ref = 0; // STENCILTESTVAL: D3D12 sets it on the command list (OMSetStencilRef) - bool depth_bounds = false; // DEPTH_BOUNDS_ENABLE: not applied (the bounds are separate state); flagged only + bool depth_bounds = false; // DEPTH_BOUNDS_ENABLE: not applied (values are dynamic); flagged only bool masks_differ = false; // back-face read/write masks or reference differ from the front: front used, flagged }; @@ -79,7 +122,7 @@ struct DepthStencil { constexpr D3D12_COMPARISON_FUNC compare(std::uint32_t frag) { return static_cast((frag & 7) + 1); } // StencilOp -> D3D12_STENCIL_OP; 0 when D3D12 has no equivalent. opval: STENCILOPVAL, the amount the -// ADD / SUB ops apply (D3D12's INCR / DECR forms add or subtract one). +// ADD / SUB ops apply (D3D12's INCR / DECR forms add one). inline D3D12_STENCIL_OP stencil_op(std::uint32_t op, std::uint32_t opval) { switch (op) { @@ -132,12 +175,241 @@ inline DepthStencil decode_depth_stencil(std::uint32_t depth_control, std::uint3 d.FrontFace = d.BackFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}; } else { out.stencil_ref = static_cast(bits(refmask, 0, 7)); - // D3D12 has one reference and one pair of masks for both faces. - if (back_own && bits(refmask_bf, 0, 23) != bits(refmask, 0, 23)) out.masks_differ = true; + if (back_own && bits(refmask_bf, 0, 23) != bits(refmask, 0, 23)) out.masks_differ = true; // masks or reference (upstream) } if (!z) d.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; // canonical: the function of a disabled test is ignored out.ok = true; return out; } +// ---- rasterizer: PA_SU_SC_MODE_CNTL, PA_CL_CLIP_CNTL, polygon offset ---- +struct Raster { + bool ok = false; + const char* reason = nullptr; + D3D12_RASTERIZER_DESC desc{}; + bool clip_split = false; // only one of ZCLIP_NEAR/FAR_DISABLE: D3D12 has one switch; clipping kept + bool bias_rounded = false; // FRONT_OFFSET not an integer: rounded to DepthBias +}; + +inline Raster decode_rasterizer(std::uint32_t mode, std::uint32_t clip, float bias_clamp, float bias_scale, float bias_offset, + bool flip_winding) +{ + Raster out; + D3D12_RASTERIZER_DESC& r = out.desc; + if (bits(mode, 3, 4)) { // POLY_MODE dual: per-face point / line / triangle drawing + const std::uint32_t front = bits(mode, 5, 7), back = bits(mode, 8, 10); + if (front != back || front == 0) { + out.reason = "polygon mode with points or with different front and back modes"; + return out; + } + r.FillMode = front == 1 ? D3D12_FILL_MODE_WIREFRAME : D3D12_FILL_MODE_SOLID; + } else { + r.FillMode = D3D12_FILL_MODE_SOLID; + } + const bool cull_front = bits(mode, 0, 0) != 0, cull_back = bits(mode, 1, 1) != 0; + if (cull_front && cull_back) { + out.reason = "both faces culled"; + return out; + } + r.CullMode = cull_front ? D3D12_CULL_MODE_FRONT : cull_back ? D3D12_CULL_MODE_BACK : D3D12_CULL_MODE_NONE; + r.FrontCounterClockwise = (bits(mode, 2, 2) == 0) != flip_winding; + const bool offset_front = bits(mode, 11, 11) != 0, offset_back = bits(mode, 12, 12) != 0; + if (offset_front != offset_back) { + out.reason = "polygon offset on one face only"; + return out; + } + if (offset_front) { + if (!std::isfinite(bias_clamp) || !std::isfinite(bias_scale) || !std::isfinite(bias_offset) || std::fabs(bias_offset) > 1e6f) { + out.reason = "polygon offset values not finite"; + return out; + } + const float rounded = std::nearbyint(bias_offset); + out.bias_rounded = rounded != bias_offset; + r.DepthBias = static_cast(rounded); + r.DepthBiasClamp = bias_clamp; + r.SlopeScaledDepthBias = bias_scale / 16.0f; + } + const bool near_off = bits(clip, 26, 26) != 0, far_off = bits(clip, 27, 27) != 0; + out.clip_split = near_off != far_off; + r.DepthClipEnable = !(near_off && far_off); + r.MultisampleEnable = FALSE; + r.AntialiasedLineEnable = FALSE; + r.ForcedSampleCount = 0; + r.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; + out.ok = true; + return out; +} + +// ---- blend: CB_BLENDn_CONTROL (cb_blend.h) with CB_TARGET_MASK & CB_SHADER_MASK per target ---- +struct Blend { + bool ok = false; + const char* reason = nullptr; + unsigned refused_targets = 0; + D3D12_BLEND_DESC desc{}; + bool dual_source = false; // an enabled target uses a SRC1 factor: the pixel shader must export a second colour + unsigned masked_targets = 0; // bit per target whose write mask is narrower than RGBA +}; + +inline bool uses_src1(D3D12_BLEND f) +{ + return f == D3D12_BLEND_SRC1_COLOR || f == D3D12_BLEND_INV_SRC1_COLOR || f == D3D12_BLEND_SRC1_ALPHA || f == D3D12_BLEND_INV_SRC1_ALPHA; +} + +// apply_masks false reproduces state_block_blend.h (every target writes RGBA). +inline Blend decode_blend(const std::uint32_t control[8], std::uint32_t target_mask, std::uint32_t shader_mask, bool apply_masks, + bool alpha_factor_supported) +{ + Blend out; + out.desc.IndependentBlendEnable = TRUE; + for (unsigned t = 0; t < 8; ++t) { + const std::uint32_t mask = apply_masks ? ((target_mask & shader_mask) >> (4 * t)) & 0xF : 0xF; + const x2w_cb_blend::Decoded d = x2w_cb_blend::decode(control[t], mask, alpha_factor_supported); + if (!d.ok) { + if (!out.refused_targets) out.reason = d.reason; + out.refused_targets |= 1u << t; + continue; + } + out.desc.RenderTarget[t] = d.desc; + if (mask != 0xF) out.masked_targets |= 1u << t; + const auto& r = d.desc; + if (r.BlendEnable && (uses_src1(r.SrcBlend) || uses_src1(r.DestBlend) || uses_src1(r.SrcBlendAlpha) || uses_src1(r.DestBlendAlpha))) + out.dual_source = true; + } + out.ok = !out.refused_targets; + return out; +} + +// ---- slot 55 derived records: {u32 part; desktop desc} of record_size bytes; the last of a part wins ---- +constexpr std::size_t record_size = sizeof(std::uint32_t) + sizeof(D3D12_BLEND_DESC); +static_assert(record_size == 0x14c, "derived record size"); +enum Part : std::uint32_t { part_depth_stencil = 0, part_rasterizer = 1, part_blend = 2 }; + +// Returns the byte offset of the last record's desc with the given part, or SIZE_MAX. +inline std::size_t last_part(const unsigned char* records, std::size_t bytes, std::uint32_t part) +{ + if (!records || !bytes || bytes % record_size) return SIZE_MAX; + for (std::size_t end = bytes; end; end -= record_size) { + std::uint32_t tag; + std::memcpy(&tag, records + end - record_size, sizeof(tag)); + if (tag == part) return end - record_size + sizeof(tag); + } + return SIZE_MAX; +} + +inline bool valid_stencil_face(const D3D12_DEPTH_STENCILOP_DESC& f) +{ + auto op = [](D3D12_STENCIL_OP o) { return o >= D3D12_STENCIL_OP_KEEP && o <= D3D12_STENCIL_OP_DECR; }; + return op(f.StencilFailOp) && op(f.StencilDepthFailOp) && op(f.StencilPassOp) && f.StencilFunc >= D3D12_COMPARISON_FUNC_NEVER && + f.StencilFunc <= D3D12_COMPARISON_FUNC_ALWAYS; +} + +// A derived depth-stencil part, read field by field (the title leaves garbage in padding); false when a +// field is outside its enumeration. +inline bool derived_depth_stencil(const unsigned char* records, std::size_t bytes, D3D12_DEPTH_STENCIL_DESC& out) +{ + const std::size_t at = last_part(records, bytes, part_depth_stencil); + if (at == SIZE_MAX) return false; + D3D12_DEPTH_STENCIL_DESC d; + std::memcpy(&d, records + at, sizeof(d)); + if (static_cast(d.DepthWriteMask) > 1 || d.DepthFunc < D3D12_COMPARISON_FUNC_NEVER || d.DepthFunc > D3D12_COMPARISON_FUNC_ALWAYS || + !valid_stencil_face(d.FrontFace) || !valid_stencil_face(d.BackFace)) + return false; + D3D12_DEPTH_STENCIL_DESC clean{}; // field by field: the padding after StencilWriteMask holds garbage + clean.DepthEnable = d.DepthEnable != 0; + clean.DepthWriteMask = d.DepthWriteMask; + clean.DepthFunc = d.DepthFunc; + clean.StencilEnable = d.StencilEnable != 0; + clean.StencilReadMask = d.StencilReadMask; + clean.StencilWriteMask = d.StencilWriteMask; + clean.FrontFace = d.FrontFace; + clean.BackFace = d.BackFace; + out = clean; + return true; +} + +inline bool derived_rasterizer(const unsigned char* records, std::size_t bytes, D3D12_RASTERIZER_DESC& out) +{ + const std::size_t at = last_part(records, bytes, part_rasterizer); + if (at == SIZE_MAX) return false; + D3D12_RASTERIZER_DESC r; + std::memcpy(&r, records + at, sizeof(r)); + if (r.FillMode < D3D12_FILL_MODE_WIREFRAME || r.FillMode > D3D12_FILL_MODE_SOLID || r.CullMode < D3D12_CULL_MODE_NONE || + r.CullMode > D3D12_CULL_MODE_BACK || !std::isfinite(r.DepthBiasClamp) || !std::isfinite(r.SlopeScaledDepthBias) || + r.ForcedSampleCount > 16 || static_cast(r.ConservativeRaster) > 1) + return false; + r.FrontCounterClockwise = r.FrontCounterClockwise != 0; + r.DepthClipEnable = r.DepthClipEnable != 0; + r.MultisampleEnable = r.MultisampleEnable != 0; + r.AntialiasedLineEnable = r.AntialiasedLineEnable != 0; + out = r; + return true; +} + +// ---- a decoded depth-stencil state against the depth target the draw has bound ---- +enum TargetAdjust : unsigned { + adjust_no_target = 1, // depth or stencil test with no depth target bound: both turned off + adjust_no_stencil = 2, // stencil test on a format without a stencil plane: stencil turned off + adjust_read_only = 4, // read-only depth target: depth and stencil writes turned off +}; + +inline unsigned adjust_for_target(D3D12_DEPTH_STENCIL_DESC& d, bool has_target, bool stencil_plane, bool read_only) +{ + unsigned done = 0; + if (!has_target) { + if (d.DepthEnable || d.StencilEnable) done |= adjust_no_target; + d.DepthEnable = FALSE; + d.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + d.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + d.StencilEnable = FALSE; + return done; + } + if (d.StencilEnable && !stencil_plane) { + d.StencilEnable = FALSE; + done |= adjust_no_stencil; + } + if (read_only && ((d.DepthEnable && d.DepthWriteMask != D3D12_DEPTH_WRITE_MASK_ZERO) || (d.StencilEnable && d.StencilWriteMask))) { + d.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + d.StencilWriteMask = 0; + done |= adjust_read_only; + } + return done; +} + +struct Switches { + bool depth = false, cull = false, flip = false, blend = false, depth_clear = false, uncleared = false, depthclip = false; +}; + +inline bool is_one(const char* v) { return v && v[0] == '1' && v[1] == 0; } +inline bool is_zero(const char* v) { return v && v[0] == '0' && v[1] == 0; } + +inline Switches parse_switches(const char* all, const char* depth, const char* cull, const char* blend, const char* flip, + const char* depth_clear = nullptr, const char* uncleared = nullptr, const char* depthclip = nullptr) +{ + Switches s; + if (is_zero(all)) return s; + s.depthclip = is_one(depthclip); + s.depth = is_one(depth); + s.cull = is_one(cull); + s.flip = s.cull && is_one(flip); + s.blend = is_one(blend); + s.depth_clear = is_one(depth_clear); + s.uncleared = s.depth && is_one(uncleared); + return s; +} + +#ifdef _WIN32 +inline Switches switches_from_env() +{ + constexpr int n = 8; + char v[n][8] = {}; + const char* names[n] = {"X2W_DRAW_STATE", "X2W_DRAW_STATE_DEPTH", "X2W_DRAW_STATE_CULL", + "X2W_DRAW_STATE_BLEND", "X2W_DRAW_STATE_CULL_FLIP", "X2W_DRAW_STATE_DEPTH_CLEAR", + "X2W_DRAW_STATE_DEPTH_UNCLEARED", "X2W_DRAW_STATE_DEPTHCLIP"}; + const char* p[n] = {}; + for (int i = 0; i < n; ++i) + if (GetEnvironmentVariableA(names[i], v[i], sizeof(v[i])) && v[i][0]) p[i] = v[i]; + return parse_switches(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]); +} +#endif + } // namespace x2w_pipeline_state diff --git a/src/startup_stubs/placed_pool.h b/src/startup_stubs/placed_pool.h new file mode 100644 index 0000000000..e487642759 --- /dev/null +++ b/src/startup_stubs/placed_pool.h @@ -0,0 +1,88 @@ +#pragma once + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include + +#include +#include + +namespace x2w_startup { + +class PlacedPool { +public: + static constexpr std::uint64_t slot_bytes = std::uint64_t{64} << 10; + static constexpr std::uint64_t heap_bytes = std::uint64_t{64} << 20; + + // S_OK with *out set, or a failure (pool off, full, buffer too large, or a desktop error): the + // caller then creates a committed resource as before. + HRESULT create(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, ID3D12Resource** out) + { + *out = nullptr; + if (!enabled() || desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || desc.Width == 0 || desc.Width > slot_bytes) + return E_NOTIMPL; + AcquireSRWLockExclusive(&lock_); + HRESULT hr = S_OK; + if (!heap_ || used_ + slot_bytes > heap_bytes) { + if (total_ + heap_bytes > budget()) { + hr = E_OUTOFMEMORY; + } else { + D3D12_HEAP_DESC heap_desc{}; + heap_desc.SizeInBytes = heap_bytes; + heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT; + heap_desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS; + ID3D12Heap* heap = nullptr; + hr = device->CreateHeap(&heap_desc, IID_PPV_ARGS(&heap)); + if (SUCCEEDED(hr)) { + heap_ = heap; // kept for the life of the process (placed buffers also hold it) + used_ = 0; + total_ += heap_bytes; + ++heaps_; + } + } + } + if (SUCCEEDED(hr)) { + D3D12_RESOURCE_DESC placed = desc; + placed.Alignment = 0; + hr = device->CreatePlacedResource(heap_, used_, &placed, state, nullptr, IID_PPV_ARGS(out)); + if (SUCCEEDED(hr)) { + used_ += slot_bytes; + ++placed_; + } + } + ReleaseSRWLockExclusive(&lock_); + return hr; + } + + std::uint64_t placed() const { return placed_; } + std::uint64_t heaps() const { return heaps_; } + +private: + static bool enabled() + { + static const bool on = [] { + char value[4]{}; + return GetEnvironmentVariableA("X2W_D3D12_PLACED_POOL", value, sizeof(value)) && value[0] == '1'; + }(); + return on; + } + static std::uint64_t budget() + { + static const std::uint64_t bytes = [] { + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_D3D12_PLACED_POOL_MIB", value, sizeof(value)); + const unsigned long mib = n && n < sizeof(value) ? std::strtoul(value, nullptr, 10) : 512ul; + return std::uint64_t{mib} << 20; + }(); + return bytes; + } + + SRWLOCK lock_ = SRWLOCK_INIT; + ID3D12Heap* heap_ = nullptr; + std::uint64_t used_ = 0, total_ = 0, heaps_ = 0, placed_ = 0; +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/rawaddr_table.h b/src/startup_stubs/rawaddr_table.h new file mode 100644 index 0000000000..16c9f91a11 --- /dev/null +++ b/src/startup_stubs/rawaddr_table.h @@ -0,0 +1,167 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace x2w_startup::rawaddr { + +constexpr unsigned kRegions = 8; +constexpr unsigned kSpace = 100; +constexpr unsigned kNullSlot = kRegions; +constexpr unsigned kStatsSlot = kRegions + 1; +constexpr unsigned kSlots = kRegions + 2; +constexpr unsigned kTableDwords = 3 * kRegions; +// Statistics slot written by the shader: [0] miss count, [16 + 8 * (n & 7)] the missed address (lo, hi). +constexpr unsigned kStatsBytes = 128; +constexpr unsigned kStatsRing = 8; + +enum class SeedKind { rootconst64, rootconst32, rootdesc }; +struct Seed { + SeedKind kind; + unsigned param = 0, word = 0, shift = 0; +}; + +// Parses a sidecar; false when it is not a version-1 file with the expected table shape. +inline bool parse_sidecar(const std::string& text, std::vector& seeds) +{ + seeds.clear(); + bool version = false, shape = false; + for (std::size_t at = 0; at < text.size();) { + std::size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + const std::string line = text.substr(at, end - at); + at = end + 1; + unsigned a = 0, b = 0, c = 0; + char kind[24] = ""; + if (line.rfind("rawaddr 1", 0) == 0) { + version = true; + } else if (std::sscanf(line.c_str(), "slots %u space %u", &a, &b) == 2) { + shape = a == kRegions && b == kSpace; + } else if (std::sscanf(line.c_str(), "seed %23s %u %u %u", kind, &a, &b, &c) >= 2) { + Seed s{}; + if (!std::strcmp(kind, "rootconst64")) s = {SeedKind::rootconst64, a, b, 0}; + else if (!std::strcmp(kind, "rootconst32")) s = {SeedKind::rootconst32, a, b, c}; + else if (!std::strcmp(kind, "rootdesc")) s = {SeedKind::rootdesc, a, 0, 0}; + else return false; + if (s.param >= 16 || s.word >= 16 || (s.kind == SeedKind::rootconst64 && s.word >= 15) || s.shift >= 40) return false; + seeds.push_back(s); + } + } + return version && shape; +} + +// The title address a seed names, from the title's root state (16 parameters x 16 constant words, and the +// title address of each root descriptor). 0 when the parameter is not of the expected kind. +inline std::uint64_t seed_address(const Seed& s, const int kind[16], const std::uint32_t constants[16][16], const std::uint64_t address[16]) +{ + if (s.param >= 16) return 0; + switch (s.kind) { + case SeedKind::rootconst64: + return kind[s.param] == 1 && s.word < 15 ? (constants[s.param][s.word] | (std::uint64_t{constants[s.param][s.word + 1]} << 32)) : 0; + case SeedKind::rootconst32: + return kind[s.param] == 1 && s.word < 16 ? (std::uint64_t{constants[s.param][s.word]} << s.shift) : 0; + case SeedKind::rootdesc: + return kind[s.param] == 3 || kind[s.param] == 4 ? address[s.param] : 0; + } + return 0; +} + +// One region of the table: the title address the view's first byte stands for, and the bytes it covers. +// A raw view must start 16-byte aligned, so the window offset is rounded down and the difference is folded +// into the base (the shader then also accepts the 0..15 bytes before the title address: still the same +// window memory). +struct Region { + std::uint64_t base = 0; + std::uint32_t size = 0; + std::uint64_t view_offset = 0; // byte offset of the view in the window buffer (16-byte aligned) +}; +inline Region make_region(std::uint64_t title_address, std::uint64_t bytes, std::uint64_t window_offset) +{ + Region r; + const std::uint64_t slack = window_offset & 15; + r.view_offset = window_offset - slack; + const std::uint64_t size = bytes + slack; + r.size = static_cast(size > 0xfffffff0ull ? 0xfffffff0ull : size) & ~3u; + r.base = title_address - slack; + return r; +} +inline bool region_contains(const Region& r, std::uint64_t address) { return r.size && address - r.base < r.size; } + +inline void fill_table(const Region* regions, unsigned count, std::uint32_t words[kTableDwords]) +{ + std::memset(words, 0, sizeof(std::uint32_t) * kTableDwords); + for (unsigned k = 0; k < count && k < kRegions; ++k) { + words[3 * k] = static_cast(regions[k].base); + words[3 * k + 1] = static_cast(regions[k].base >> 32); + words[3 * k + 2] = regions[k].size; + } +} + +// The title root signature plus [n] kTableDwords constants b0 space100 and [n + 1] a table of kSlots UAVs +// u0 space100. The heap-directly-indexed flags are cleared as device_create_root_signature does. +// *first_extra = n. Returns the serialized blob (caller releases) or null; *error gets the failing step. +inline ID3DBlob* augmented_root(const void* blob, std::size_t bytes, UINT* first_extra, const char** error) +{ + *error = nullptr; + ID3D12VersionedRootSignatureDeserializer* reader = nullptr; + if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(blob, bytes, IID_PPV_ARGS(&reader)))) { + *error = "deserialize"; + return nullptr; + } + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* source = nullptr; + if (FAILED(reader->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &source)) || !source) { + reader->Release(); + *error = "version 1.1"; + return nullptr; + } + const D3D12_ROOT_SIGNATURE_DESC1& in = source->Desc_1_1; + std::vector params(in.pParameters, in.pParameters + in.NumParameters); + for (const auto& p : params) + if ((p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE && [&] { + for (UINT i = 0; i < p.DescriptorTable.NumDescriptorRanges; ++i) + if (p.DescriptorTable.pDescriptorRanges[i].RegisterSpace == kSpace) return true; + return false; + }()) || + ((p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) && p.Constants.RegisterSpace == kSpace) || + ((p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV || p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV || + p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_UAV) && p.Descriptor.RegisterSpace == kSpace)) { + reader->Release(); + *error = "title root uses register space 100"; + return nullptr; + } + *first_extra = static_cast(params.size()); + D3D12_ROOT_PARAMETER1 table{}; + table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + table.Constants = {0, kSpace, kTableDwords}; + table.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + params.push_back(table); + static const D3D12_DESCRIPTOR_RANGE1 range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, kSlots, 0, kSpace, + D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, 0}; + D3D12_ROOT_PARAMETER1 uavs{}; + uavs.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + uavs.DescriptorTable = {1, &range}; + uavs.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + params.push_back(uavs); + constexpr UINT indexed = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC out{}; + out.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + out.Desc_1_1 = {static_cast(params.size()), params.data(), in.NumStaticSamplers, in.pStaticSamplers, + static_cast(in.Flags & ~indexed)}; + ID3DBlob* result = nullptr; + ID3DBlob* errors = nullptr; + const HRESULT hr = D3D12SerializeVersionedRootSignature(&out, &result, &errors); + if (errors) errors->Release(); + reader->Release(); // owns source: released only after serialization + if (FAILED(hr)) { + *error = "serialize (over 64 root dwords?)"; + return nullptr; + } + return result; +} + +} // namespace x2w_startup::rawaddr diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 7c9a170462..543d8836b0 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -194,10 +194,7 @@ using x2w_api_trace::no_argument; template __declspec(noinline) u64 forward(Proxy* self, u64 a, u64 b, u64 c, u64 s0, u64 s1, u64 s2, u64 s3, u64 s4, u64 s5, u64 s6, u64 s7) { - // call_counts also feeds the periodic call-rate summary, so it keeps counting; a count that has - // passed 2^31 is negative and must not log again. - const LONG call = N >= 3 ? InterlockedIncrement(&call_counts[self->provider][N]) : 0; - const bool log_it = call > 0 && call <= 6; + const bool log_it = N >= 3 && x2w_local::first_of(InterlockedIncrement(&call_counts[self->provider][N]), 6); u64 args[11] = {a, b, c, s0, s1, s2, s3, s4, s5, s6, s7}; // Declared outputs are snapshotted so the write is seen rather than assumed; nothing else is read. The // snapshot is bounded by the declared width, so a one-byte flag, a DWORD and a caller-sized buffer @@ -322,11 +319,91 @@ void fill_slots(std::index_sequence) ((slot_table[I] = reinterpret_cast(&forward(I)>)), ...); } +struct CachedQuery { + GUID provider, iid; + void* real; // what the runtime returned + void* answer; // what the title received (the proxy, or the object itself) + int same; + bool cached; +}; +constexpr int max_cached_queries = 32, cache_after = 8; +CachedQuery cached_queries[max_cached_queries]; +int cached_query_count; +SRWLOCK cached_query_lock = SRWLOCK_INIT; +volatile LONG cached_answers; // queries answered from the cache (heartbeat) +bool query_cache_on() noexcept +{ + static const bool on = [] { + char value[8]; + const DWORD n = GetEnvironmentVariableA("X2W_RUNTIME_QUERY_CACHE", value, sizeof(value)); + return !(n == 1 && value[0] == '0'); + }(); + return on; +} +using AddRefMethod = ULONG(__stdcall*)(void*); +void add_ref(void* object) { reinterpret_cast((*reinterpret_cast(object))[1])(object); } + +bool cached_answer(const GUID* provider, const GUID* iid, void** out) +{ + void* real = nullptr; + void* answer = nullptr; + AcquireSRWLockShared(&cached_query_lock); + for (int i = 0; i < cached_query_count; ++i) { + const CachedQuery& entry = cached_queries[i]; + if (entry.cached && IsEqualGUID(entry.provider, *provider) && IsEqualGUID(entry.iid, *iid)) { + real = entry.real; + answer = entry.answer; + break; + } + } + ReleaseSRWLockShared(&cached_query_lock); + if (!answer) return false; + add_ref(real); // the title releases the answer once per query; the proxy forwards Release to real + *out = answer; + InterlockedIncrement(&cached_answers); + return true; +} + +void note_answer(const GUID& provider, const GUID& iid, void* real, void* answer) +{ + AcquireSRWLockExclusive(&cached_query_lock); + CachedQuery* entry = nullptr; + for (int i = 0; i < cached_query_count && !entry; ++i) + if (IsEqualGUID(cached_queries[i].provider, provider) && IsEqualGUID(cached_queries[i].iid, iid)) entry = &cached_queries[i]; + if (!entry && cached_query_count < max_cached_queries) { + entry = &cached_queries[cached_query_count++]; + *entry = CachedQuery{provider, iid, real, answer, 0, false}; + } + bool now_cached = false; + if (entry && !entry->cached) { + if (entry->real == real && entry->answer == answer) { + ++entry->same; + } else { + entry->real = real; + entry->answer = answer; + entry->same = 1; + } + if (entry->same >= cache_after) { + add_ref(real); // the cache's own reference, never released + entry->cached = now_cached = true; + } + } + ReleaseSRWLockExclusive(&cached_query_lock); + if (now_cached) + x2w_local::logf("x2w-runtime QueryApiImpl %08lx/%08lx: same object %d times, later queries answered from the cache " + "(X2W_RUNTIME_QUERY_CACHE=0 turns this off)", provider.Data1, iid.Data1, cache_after); +} + HRESULT __stdcall proxy_query(const GUID* provider, const GUID* iid, void** out) { + if (provider && iid && out && query_cache_on() && cached_answer(provider, iid, out)) return S_OK; const QueryApi query = load_real_query(); if (!query) return E_FAIL; const HRESULT hr = query(provider, iid, out); + const bool cacheable = hr == S_OK && provider && iid && out && *out && query_cache_on(); + void* const real_object = cacheable ? *out : nullptr; + // Read only after a successful real query: a failed one may have been given an unreadable provider (E_POINTER). + const GUID asked_provider = cacheable ? *provider : GUID{}; const bool output_writable = FAILED(hr) && fake_user() && x2w_local::writable(out, sizeof(*out)); const bool pair_readable = output_writable && x2w_local::readable(provider, sizeof(*provider)) && x2w_local::readable(iid, sizeof(*iid)); @@ -397,6 +474,7 @@ HRESULT __stdcall proxy_query(const GUID* provider, const GUID* iid, void** out) } ReleaseSRWLockExclusive(&proxy_lock); if (proxy) *out = proxy; + if (cacheable) note_answer(asked_provider, *iid, real_object, *out); if (local) return proxy ? S_OK : hr; return hr; } @@ -1345,6 +1423,16 @@ bool area_call(const GUID& provider_id, int slot, u64* args, u64* result) *result = 0; return true; } + if (slot > 3 && IsEqualGUID(provider_id, store_provider_id)) { + for (int i = 0; i < 6; ++i) { + if (args[i] != store_context_handle) continue; + static LONG refused; + if (x2w_local::first_calls(refused, 16)) + x2w_local::logf("x2w-runtime store slot %d with the offline context -> E_FAIL", slot); + *result = 0x80004005; + return true; + } + } return false; } @@ -1487,6 +1575,7 @@ BOOL WINAPI DllMain(HINSTANCE self, DWORD reason, void*) // logs have gone quiet. if (HANDLE heartbeat = CreateThread(nullptr, 0, [](void*) -> DWORD { static LONG seen[max_providers][max_slots]; + LONG cached_seen = 0; for (int second = 10;; second += 10) { Sleep(10000); char line[1024]; @@ -1501,6 +1590,12 @@ BOOL WINAPI DllMain(HINSTANCE self, DWORD reason, void*) any = true; } } + const LONG cached_now = cached_answers, cached_delta = cached_now - cached_seen; + cached_seen = cached_now; + if (cached_delta > 0 && n < static_cast(sizeof(line)) - 40) { + n += std::snprintf(line + n, sizeof(line) - n, " (queries from cache x%ld)", cached_delta); + any = true; + } if (any) x2w_local::logf("%s", line); } }, nullptr, 0, nullptr)) CloseHandle(heartbeat); diff --git a/src/startup_stubs/state_block_blend.h b/src/startup_stubs/state_block_blend.h index 31cb19c83e..f6f2745831 100644 --- a/src/startup_stubs/state_block_blend.h +++ b/src/startup_stubs/state_block_blend.h @@ -2,11 +2,11 @@ // slot 57, read from its state block A (#1216). // // State block A holds the eight CB_BLENDn_CONTROL words at +0xD0, one per render target (measured -// on #1216). They are decoded with cb_blend.h. CB_TARGET_MASK has not been located, so every -// target keeps all four channels. +// on #1216). They are decoded with cb_blend.h. Every target keeps all four channels here; the +// write masks (CB_TARGET_MASK & CB_SHADER_MASK) are pipeline_state_decode.h's, behind a switch. #pragma once -#include "cb_blend.h" +#include "pipeline_state_decode.h" #include #include @@ -42,35 +42,32 @@ inline bool state_block_blend(const unsigned char* block, std::size_t bytes, boo why = "state block A shorter than the blend words"; return false; } - D3D12_BLEND_DESC blend{}; - blend.IndependentBlendEnable = TRUE; - unsigned refused = 0; - bool target0_dual_source = false; - for (unsigned target = 0; target < 8; ++target) { - std::uint32_t word; - std::memcpy(&word, block + state_block_blend_offset + 4 * target, sizeof(word)); - const x2w_cb_blend::Decoded decoded = x2w_cb_blend::decode(word, 0xF, alpha_factor_supported); - if (decoded.ok && decoded.desc.BlendEnable) { - const bool dual = uses_dual_source(decoded.desc); - if (target == 0) { - target0_dual_source = dual; - } else if (dual || target0_dual_source) { - if (!refused) - why = dual ? "dual-source factor on a target other than 0" - : "dual-source blend on target 0 with another blending target"; - refused |= 1u << target; - continue; - } - } - if (decoded.ok) { - blend.RenderTarget[target] = decoded.desc; - continue; - } - if (!refused) why = decoded.reason; - refused |= 1u << target; + // One decoder for the eight words (pipeline_state_decode.h), with every target writing RGBA. + std::uint32_t words[8]; + std::memcpy(words, block + state_block_blend_offset, sizeof(words)); + const x2w_pipeline_state::Blend decoded = x2w_pipeline_state::decode_blend(words, 0, 0, false, alpha_factor_supported); + // Upstream rule kept at the merge: D3D12 dual-source blending is target 0 only, and no other target may blend + // beside it. A dual-source factor on another target, or a blending target beside a dual-source target 0, is refused. + unsigned dual_refused = 0; + const char* dual_why = nullptr; + const auto& t0 = decoded.desc.RenderTarget[0]; + const bool target0_dual_source = t0.BlendEnable && uses_dual_source(t0); + for (unsigned target = 1; target < 8; ++target) { + const auto& t = decoded.desc.RenderTarget[target]; + if (!t.BlendEnable) continue; + const bool dual = uses_dual_source(t); + if (!dual && !target0_dual_source) continue; + if (!dual_refused && !(decoded.refused_targets & ((1u << target) - 1))) + dual_why = dual ? "dual-source factor on a target other than 0" : "dual-source blend on target 0 with another blending target"; + dual_refused |= 1u << target; } - if (refused_targets) *refused_targets = refused; - if (refused) return false; + if (refused_targets) *refused_targets = decoded.refused_targets | dual_refused; + if (!decoded.ok || dual_refused) { + why = dual_why && (!decoded.refused_targets || (dual_refused & -dual_refused) < (decoded.refused_targets & -decoded.refused_targets)) + ? dual_why : decoded.reason ? decoded.reason : dual_why; + return false; + } + const D3D12_BLEND_DESC& blend = decoded.desc; *out = blend; return true; } diff --git a/src/startup_stubs/title_composition.h b/src/startup_stubs/title_composition.h new file mode 100644 index 0000000000..755113b7e2 --- /dev/null +++ b/src/startup_stubs/title_composition.h @@ -0,0 +1,48 @@ +#pragma once + +#include +#include +#include + +namespace x2w_startup { + +// Attach the GPU output to the existing client area without taking ownership of the window or its message loop. +struct TitleComposition { + Microsoft::WRL::ComPtr device; + Microsoft::WRL::ComPtr target; + Microsoft::WRL::ComPtr visual; + HWND window = nullptr; + SIZE size{}; + + HRESULT show(HWND hwnd, IDXGISwapChain1* chain, UINT width, UINT height) + { + RECT client{}; + if (!GetClientRect(hwnd, &client)) return HRESULT_FROM_WIN32(ERROR_INVALID_WINDOW_HANDLE); + if (client.right <= 0 || client.bottom <= 0) return S_FALSE; + if (!device) { + HRESULT hr = DCompositionCreateDevice(nullptr, IID_PPV_ARGS(device.GetAddressOf())); + if (FAILED(hr)) return hr; + } + if (window != hwnd || !target) { + Microsoft::WRL::ComPtr next_target; + Microsoft::WRL::ComPtr next_visual; + HRESULT hr = device->CreateTargetForHwnd(hwnd, TRUE, next_target.GetAddressOf()); + if (SUCCEEDED(hr)) hr = device->CreateVisual(next_visual.GetAddressOf()); + if (SUCCEEDED(hr)) hr = next_visual->SetContent(chain); + if (SUCCEEDED(hr)) hr = next_target->SetRoot(next_visual.Get()); + if (FAILED(hr)) return hr; + target = next_target; + visual = next_visual; + window = hwnd; + size = {}; + } + if (size.cx == client.right && size.cy == client.bottom) return S_OK; + D2D_MATRIX_3X2_F transform{static_cast(client.right) / width, 0, 0, + static_cast(client.bottom) / height, 0, 0}; + HRESULT hr = visual->SetTransform(transform); + if (SUCCEEDED(hr)) hr = device->Commit(); + if (SUCCEEDED(hr)) size = {client.right, client.bottom}; + return hr; + } +}; +} diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index a4aca72ddf..27971ba45e 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -19,6 +19,47 @@ constexpr UINT translated_sampler_space = 1; constexpr UINT translated_sampler_fallback = translated_sampler_count - 1; constexpr UINT title_sampler_stride = sizeof(SamplerWords); +inline bool sampler_lod_fields_on() +{ + static const bool on = [] { + char value[4]{}; + const DWORD saved = GetLastError(); + const bool v = GetEnvironmentVariableA("X2W_SAMPLER_LOD", value, sizeof(value)) && value[0] == '1'; + SetLastError(saved); + return v; + }(); + return on; +} + +struct SamplerLodFields { + float bias, min_lod, max_lod; + D3D12_STATIC_BORDER_COLOR border; + bool border_register; // BORDER_COLOR_TYPE 3 (a border colour table entry): not translated, transparent black +}; + +// Field positions of SQ_IMG_SAMP_WORD1..3 (Mesa src/amd/registers/gfx10-rsrc.json, as cited in tools/pixel_aot.py): +// word 1 bits 11:0 MIN_LOD and 23:12 MAX_LOD, unsigned 4.8 fixed point; word 2 bits 13:0 LOD_BIAS, signed 5.8 +// (bits 19:14 LOD_BIAS_SEC, the secondary bias, are not carried); word 3 bits 31:30 BORDER_COLOR_TYPE +// (0 transparent black, 1 opaque black, 2 opaque white, 3 register), numbered as D3D12_STATIC_BORDER_COLOR 0..2. +// MAX_LOD 0xfff (15.996) stays unlimited. D3D12 limits the bias to [-16, 15.99]. +inline SamplerLodFields sampler_lod_fields(const SamplerWords& words) +{ + SamplerLodFields f{}; + int bias = static_cast(words[2] & 0x3fff); + if (bias & 0x2000) bias -= 0x4000; + f.bias = static_cast(bias) / 256.0f; + if (f.bias < D3D12_MIP_LOD_BIAS_MIN) f.bias = D3D12_MIP_LOD_BIAS_MIN; + if (f.bias > D3D12_MIP_LOD_BIAS_MAX) f.bias = D3D12_MIP_LOD_BIAS_MAX; + f.min_lod = static_cast(words[1] & 0xfff) / 256.0f; + const UINT max_raw = (words[1] >> 12) & 0xfff; + f.max_lod = max_raw == 0xfff ? D3D12_FLOAT32_MAX : static_cast(max_raw) / 256.0f; + if (f.max_lod < f.min_lod) f.max_lod = f.min_lod; + const UINT type = words[3] >> 30; + f.border_register = type == 3; + f.border = type == 3 ? D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK : static_cast(type); + return f; +} + // comparison: the sampler is read through a SamplerComparisonState (manifest line smpc). SQ_IMG_SAMP_WORD0 bits // 14:12 hold SQ_TEX_DEPTH_COMPARE, which lists NEVER..ALWAYS in the order of D3D12_COMPARISON_FUNC minus one. // lod_limits (manifest line smpl, image_sample_b and a constant sampler of image_sample, _l, _lz): the descriptor's LOD clamp is carried over. MIN_LOD (word 1 bits @@ -27,7 +68,7 @@ constexpr UINT title_sampler_stride = sizeof(SamplerWords); // divided by 256. dynamic_sampler() sets it for every heap entry. Without it MinLOD stays 0 and MaxLOD unbounded, as // for the other sample forms. inline D3D12_STATIC_SAMPLER_DESC decode_sampler(const SamplerWords& words, UINT shader_register, bool comparison = false, - bool lod_limits = false) + bool lod_limits = false, bool lod_fields = sampler_lod_fields_on()) { static const D3D12_TEXTURE_ADDRESS_MODE modes[8] = { D3D12_TEXTURE_ADDRESS_MODE_WRAP, D3D12_TEXTURE_ADDRESS_MODE_MIRROR, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, @@ -54,6 +95,13 @@ inline D3D12_STATIC_SAMPLER_DESC decode_sampler(const SamplerWords& words, UINT : border_type == 1u ? D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK : D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; s.MaxLOD = D3D12_FLOAT32_MAX; + if (lod_fields) { + const auto f = sampler_lod_fields(words); + s.MipLODBias = f.bias; + s.MinLOD = f.min_lod; + s.MaxLOD = f.max_lod; + s.BorderColor = f.border; + } if (lod_limits) { s.MinLOD = static_cast(words[1] & 0xfffu) / 256.0f; s.MaxLOD = static_cast((words[1] >> 12) & 0xfffu) / 256.0f; @@ -106,7 +154,7 @@ inline std::vector decode_statics(const TranslatedSam std::vector statics; for (UINT i = 0; i < samplers.statics.size(); ++i) statics.push_back(decode_sampler(samplers.statics[i], i, i < samplers.comparison.size() && samplers.comparison[i], - i < samplers.lod_limits.size() && samplers.lod_limits[i])); + i < samplers.lod_limits.size() && samplers.lod_limits[i], sampler_lod_fields_on())); return statics; } @@ -187,21 +235,24 @@ inline SamplerSnapshot snapshot_samplers(SamplerSource source, bool reserved_fal return snapshot; } -inline D3D12_SAMPLER_DESC dynamic_sampler(const SamplerWords& words) +inline D3D12_SAMPLER_DESC dynamic_sampler(const SamplerWords& words, bool lod_fields = sampler_lod_fields_on()) { - // A heap entry is the title's own descriptor, so its MIN_LOD, MAX_LOD (#2221) and fixed border color apply. - const auto s = decode_sampler(words, 0, false, true); - const float rgb = s.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE ? 1.0f : 0.0f; - const float alpha = (s.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE || - s.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK) ? 1.0f : 0.0f; - return {s.Filter, s.AddressU, s.AddressV, s.AddressW, s.MipLODBias, s.MaxAnisotropy, s.ComparisonFunc, - {rgb, rgb, rgb, alpha}, s.MinLOD, s.MaxLOD}; + const auto s = decode_sampler(words, 0, false, true, lod_fields); + D3D12_SAMPLER_DESC d{s.Filter, s.AddressU, s.AddressV, s.AddressW, s.MipLODBias, s.MaxAnisotropy, s.ComparisonFunc, + {}, s.MinLOD, s.MaxLOD}; + if (lod_fields) { + const float rgb = s.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE ? 1.0f : 0.0f; + const float alpha = s.BorderColor == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK ? 0.0f : 1.0f; + d.BorderColor[0] = d.BorderColor[1] = d.BorderColor[2] = rgb; + d.BorderColor[3] = alpha; + } + return d; } inline D3D12_SAMPLER_DESC border_sampler() { // Not a title descriptor: its zero word 1 is not a LOD clamp, so the full mip range stays available. - auto s = dynamic_sampler({6u | (6u << 3) | (6u << 6), 0, 0, 0}); + auto s = dynamic_sampler({6u | (6u << 3) | (6u << 6), 0, 0, 0}, false); s.MaxLOD = D3D12_FLOAT32_MAX; return s; } diff --git a/src/startup_stubs/trap.h b/src/startup_stubs/trap.h index 150686eed5..31d997152e 100644 --- a/src/startup_stubs/trap.h +++ b/src/startup_stubs/trap.h @@ -36,6 +36,46 @@ inline void write_all(HANDLE handle, const char* text, DWORD length) noexcept WriteFile(handle, text, length, &written, nullptr); } +inline void append_trap_log(const char* text, DWORD length) noexcept +{ + const DWORD error = GetLastError(); + wchar_t path[MAX_PATH]; + const DWORD path_length = GetEnvironmentVariableW(L"X2W_TRAP_LOG", path, MAX_PATH); + const bool usable = path_length && path_length < MAX_PATH; + static const bool reopen = [] { + char value[4]{}; + return GetEnvironmentVariableA("X2W_TRAP_LOG_REOPEN", value, sizeof(value)) && value[0] == '1'; + }(); + if (reopen) { + if (usable) { + HANDLE out = CreateFileW(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (out != INVALID_HANDLE_VALUE) { + write_all(out, text, length); + CloseHandle(out); + } + } + SetLastError(error); + return; + } + static SRWLOCK lock = SRWLOCK_INIT; + static HANDLE handle = INVALID_HANDLE_VALUE; + static wchar_t open_path[MAX_PATH]; + AcquireSRWLockExclusive(&lock); + if (handle != INVALID_HANDLE_VALUE && (!usable || std::wcscmp(path, open_path) != 0)) { + CloseHandle(handle); + handle = INVALID_HANDLE_VALUE; + } + if (handle == INVALID_HANDLE_VALUE && usable) { + handle = CreateFileW(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle != INVALID_HANDLE_VALUE) std::wmemcpy(open_path, path, path_length + 1); + } + write_all(handle, text, length); + ReleaseSRWLockExclusive(&lock); + SetLastError(error); +} + // Switch: %X2W_TRAP_CONTINUE% lists export names (comma-separated, or *) whose // trap logs the call with "x2w-continue" and returns 0 instead of terminating. Off when unset. inline bool listed(const char* variable, const char* name) noexcept diff --git a/src/xmem_census.cpp b/src/xmem_census.cpp new file mode 100644 index 0000000000..2f8d9fc83e --- /dev/null +++ b/src/xmem_census.cpp @@ -0,0 +1,484 @@ +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#include +#include +#include + +#include "xmem_census.h" +#include "startup_stubs/local_log.h" + +#include +#include +#include +#include +#include + +namespace { +constexpr ULONGLONG mib = 1ull << 20; + +ULONGLONG system_commit(ULONGLONG* limit) noexcept +{ + PERFORMANCE_INFORMATION info{}; + info.cb = sizeof(info); + if (!GetPerformanceInfo(&info, sizeof(info))) return 0; + if (limit) *limit = static_cast(info.CommitLimit) * info.PageSize; + return static_cast(info.CommitTotal) * info.PageSize; +} + +// The system commit when xmem.dll was loaded: the reference for "this run". +const ULONGLONG commit_at_load = system_commit(nullptr); +const ULONGLONG tick_at_load = GetTickCount64(); + +SRWLOCK block_lock = SRWLOCK_INIT; +std::vector>* blocks; // sorted by base when the census reads it + +int append(char* out, int at, int capacity, const char* format, ...) noexcept +{ + if (at >= capacity - 1) return at; + va_list args; + va_start(args, format); + const int n = std::vsnprintf(out + at, static_cast(capacity - at), format, args); + va_end(args); + if (n < 0) return at; + return std::min(capacity - 1, at + n); +} + +// GPU memory of this process per adapter that has some (DXGI segment groups). +int gpu_text(char* out, int at, int capacity) noexcept +{ + Microsoft::WRL::ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return append(out, at, capacity, " gpu unknown"); + Microsoft::WRL::ComPtr adapter; + bool any = false; + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) { + Microsoft::WRL::ComPtr three; + if (FAILED(adapter.As(&three))) continue; + DXGI_QUERY_VIDEO_MEMORY_INFO local{}, nonlocal{}; + if (FAILED(three->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &local))) continue; + three->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &nonlocal); + if (!local.CurrentUsage && !nonlocal.CurrentUsage) continue; + DXGI_ADAPTER_DESC1 desc{}; + adapter->GetDesc1(&desc); + at = append(out, at, capacity, " gpu%u(%04x) local=%llu/%llu non-local=%llu/%llu MiB", i, desc.DeviceId, + local.CurrentUsage / mib, local.Budget / mib, nonlocal.CurrentUsage / mib, nonlocal.Budget / mib); + any = true; + } + return any ? at : append(out, at, capacity, " gpu none"); +} + +int heap_text(char* out, int at, int capacity) noexcept +{ + HANDLE heaps[256]; + const DWORD n = GetProcessHeaps(256, heaps); + ULONGLONG committed = 0, largest = 0; + DWORD counted = 0; + for (DWORD i = 0; i < n && i < 256; ++i) { + HEAP_SUMMARY summary{}; + summary.cb = sizeof(summary); + if (!HeapSummary(heaps[i], 0, &summary)) continue; + committed += summary.cbCommitted; + largest = std::max(largest, summary.cbCommitted); + ++counted; + } + return append(out, at, capacity, " heaps %lu committed=%llu MiB (largest %llu)", counted, committed / mib, largest / mib); +} + +int block_resident_walk(char* out, int at, int capacity); +int block_resident_text(char* out, int at, int capacity) noexcept +{ + try { + return block_resident_walk(out, at, capacity); + } catch (...) { + return at; // out of memory: no residency text this time + } +} +int block_resident_walk(char* out, int at, int capacity) +{ + std::vector> known; + AcquireSRWLockShared(&block_lock); + if (blocks) known = *blocks; + ReleaseSRWLockShared(&block_lock); + if (known.empty()) return at; + std::sort(known.begin(), known.end()); + constexpr SIZE_T page = 4096, chunk = 65536; + std::vector info(chunk); + at = append(out, at, capacity, "; block resident MiB"); + for (const auto& [base, bytes] : known) { + if (bytes < (16ull << 20)) continue; + ULONGLONG resident = 0; + for (SIZE_T done = 0; done < bytes / page;) { + const SIZE_T n = std::min(chunk, bytes / page - done); + for (SIZE_T i = 0; i < n; ++i) info[i].VirtualAddress = reinterpret_cast(base + (done + i) * page); + if (!QueryWorkingSetEx(GetCurrentProcess(), info.data(), static_cast(n * sizeof(info[0])))) break; + for (SIZE_T i = 0; i < n; ++i) resident += info[i].VirtualAttributes.Valid; + done += n; + } + at = append(out, at, capacity, " %llx:%llu/%llu", static_cast(base), resident * page / mib, + static_cast(bytes / mib)); + } + return at; +} + +// Counters of other stand-ins (x2w_memory_counters exports). +int stand_in_text(char* out, int at, int capacity) noexcept +{ + HMODULE modules[512]; + DWORD needed = 0; + if (!EnumProcessModules(GetCurrentProcess(), modules, sizeof(modules), &needed)) return at; + const DWORD count = std::min(needed / sizeof(HMODULE), 512); + for (DWORD i = 0; i < count; ++i) { + const auto counters = reinterpret_cast(GetProcAddress(modules[i], "x2w_memory_counters")); + if (!counters) continue; + char name[64]{}; + GetModuleBaseNameA(GetCurrentProcess(), modules[i], name, sizeof(name)); + char text[512]{}; + const int n = counters(text, sizeof(text)); + if (n > 0) at = append(out, at, capacity, "; %s: %s", name, text); + } + return at; +} + +void report(ULONGLONG second) noexcept +{ + char line[1536]; + ULONGLONG limit = 0; + const ULONGLONG committed = system_commit(&limit); + PROCESS_MEMORY_COUNTERS_EX counters{}; + counters.cb = sizeof(counters); + GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&counters), sizeof(counters)); + X2wXmemStats x{}; + x2w_xmem_memory_stats(&x); + const long long delta = static_cast(committed) - static_cast(commit_at_load); + int at = std::snprintf(line, sizeof(line), + "x2w-mem %llu s: system %+lld MiB since load (committed %llu / limit %llu MiB, headroom %llu); " + "private %llu MiB (peak %llu); slabs %llu = %llu MiB, %llu file-backed, %llu moved for the GPU%s (pages %llu live, %llu free slots%s%llu%s); " + "xmem commits: startup blocks %llu MiB (%llu), permissive %llu MiB (%llu);", + second, delta / static_cast(mib), committed / mib, limit / mib, + limit > committed ? (limit - committed) / mib : 0, counters.PrivateUsage / mib, + counters.PeakPagefileUsage / mib, x.slabs, x.slab_bytes / mib, x.file_slabs, x.migrations, + x.migration_failures ? " (SOME MOVES FAILED)" : "", x.live_pages, x.free_slots, + x.slab_budget_bytes ? ", budget " : "", x.slab_budget_bytes / mib, + x.slab_refusals ? " MiB, REFUSED pages" : (x.slab_budget_bytes ? " MiB" : ""), + x.startup_block_bytes / mib, x.startup_block_calls, x.permissive_commit_bytes / mib, + x.permissive_commit_calls); + if (at < 0) return; + at = heap_text(line, at, sizeof(line)); + at = gpu_text(line, at, sizeof(line)); + at = stand_in_text(line, at, sizeof(line)); + x2w_local::logf("%s", line); +} + +struct CensusRegion { ULONG_PTR start, base; ULONGLONG bytes; DWORD protect; bool mapped; }; +bool census_classes_on() noexcept +{ + static const bool on = [] { + char v[4]{}; + return GetEnvironmentVariableA("X2W_MEM_CENSUS_CLASSES", v, sizeof(v)) && v[0] == '1'; + }(); + return on; +} +// Resident bytes of [start, start + bytes), one sample per 64 KiB (the whole range when smaller). +ULONGLONG sampled_resident(ULONG_PTR start, ULONGLONG bytes, std::vector& info) +{ + constexpr ULONGLONG stride = 65536; + const ULONGLONG samples = bytes <= stride ? 1 : (bytes + stride - 1) / stride; + const ULONGLONG weight = bytes <= stride ? bytes : stride; + ULONGLONG valid = 0; + for (ULONGLONG done = 0; done < samples;) { + const ULONGLONG n = std::min(info.size(), samples - done); + for (ULONGLONG i = 0; i < n; ++i) info[i].VirtualAddress = reinterpret_cast(start + (done + i) * stride); + if (!QueryWorkingSetEx(GetCurrentProcess(), info.data(), static_cast(n * sizeof(info[0])))) break; + for (ULONGLONG i = 0; i < n; ++i) valid += info[i].VirtualAttributes.Valid; + done += n; + } + return std::min(bytes, valid * weight); +} +void census_classes(ULONGLONG second, const std::vector& regions) noexcept +{ + try { + const ULONGLONG began = GetTickCount64(); + static std::vector previous; // allocation bases at the last census (reporter thread only) + // Committed bytes per allocation base at the last census (sorted by base): which existing allocations grew. + static std::vector> previous_bytes; + const bool first = previous.empty(); + struct Total { ULONG_PTR base; ULONGLONG committed, resident; int c; }; + std::vector totals; // per allocation base, this census + std::vector info(16384); + // reservations: the stand-in's reserved ranges (size, not commit), where the title's pages are mapped + enum { p4, p404, other, mapped, reservations, classes }; + const char* const names[classes] = {"p4", "p404", "other", "mapped", "stand-in reservations"}; + ULONGLONG committed[classes]{}, resident[classes]{}, count[classes]{}; + ULONGLONG fresh_committed[classes]{}, fresh_resident[classes]{}, fresh_count[classes]{}; + struct Fresh { ULONG_PTR base; ULONGLONG committed, resident; DWORD protect; bool mapped; }; + std::vector fresh; + std::vector bases; + for (const CensusRegion& r : regions) { + const int c = r.mapped ? (r.protect ? mapped : reservations) : (r.protect & ~0x100u) == PAGE_READWRITE ? p4 + : (r.protect & ~0x100u) == (PAGE_READWRITE | PAGE_WRITECOMBINE) ? p404 : other; + const ULONGLONG res = sampled_resident(r.start, r.bytes, info); + const bool new_base = !std::binary_search(previous.begin(), previous.end(), r.base); + committed[c] += r.bytes; + resident[c] += res; + if (!totals.empty() && totals.back().base == r.base) { + totals.back().committed += r.bytes; + totals.back().resident += res; + } else { + totals.push_back({r.base, r.bytes, res, c}); + } + if (bases.empty() || bases.back() != r.base) { + bases.push_back(r.base); + ++count[c]; + if (new_base) ++fresh_count[c]; + } + if (!new_base || first) continue; + fresh_committed[c] += r.bytes; + fresh_resident[c] += res; + if (!fresh.empty() && fresh.back().base == r.base) { + fresh.back().committed += r.bytes; + fresh.back().resident += res; + } else { + fresh.push_back({r.base, r.bytes, res, r.protect, r.mapped}); + } + } + std::sort(bases.begin(), bases.end()); + bases.erase(std::unique(bases.begin(), bases.end()), bases.end()); + previous.swap(bases); + std::stable_sort(totals.begin(), totals.end(), [](const Total& a, const Total& b) { return a.base < b.base; }); + std::vector merged; // one entry per base (regions of one allocation are adjacent; merged to be sure) + for (const Total& t : totals) { + if (!merged.empty() && merged.back().base == t.base) { + merged.back().committed += t.committed; + merged.back().resident += t.resident; + } else { + merged.push_back(t); + } + } + struct Grown { ULONG_PTR base; ULONGLONG grown, committed, resident; int c; }; + std::vector grown; + ULONGLONG grown_bytes[classes]{}; + std::vector> now_bytes; + now_bytes.reserve(merged.size()); + for (const Total& t : merged) { + now_bytes.emplace_back(t.base, t.committed); + const auto before = std::lower_bound(previous_bytes.begin(), previous_bytes.end(), std::make_pair(t.base, ULONGLONG{0})); + if (first || before == previous_bytes.end() || before->first != t.base || t.committed <= before->second) continue; + grown.push_back({t.base, t.committed - before->second, t.committed, t.resident, t.c}); + grown_bytes[t.c] += t.committed - before->second; + } + previous_bytes.swap(now_bytes); + char line[1500]; + int n = std::snprintf(line, sizeof(line), "x2w-mem census-classes %llu s: outside startup blocks, committed/resident MiB (allocations):", + second); + if (n < 0) return; + for (int c = 0; c < classes; ++c) + n = append(line, n, sizeof(line), " %s %llu/%llu (%llu)", names[c], committed[c] / mib, resident[c] / mib, count[c]); + if (first) { + n = append(line, n, sizeof(line), "; first census: nothing to compare"); + } else { + n = append(line, n, sizeof(line), "; new since the last census:"); + for (int c = 0; c < classes; ++c) + n = append(line, n, sizeof(line), " %s %llu/%llu (%llu)", names[c], fresh_committed[c] / mib, fresh_resident[c] / mib, + fresh_count[c]); + std::sort(fresh.begin(), fresh.end(), [](const Fresh& a, const Fresh& b) { return a.committed > b.committed; }); + n = append(line, n, sizeof(line), "; largest new:"); + // A mapped view (counted under "mapped") is marked: its protection alone reads like a p4 allocation. + for (std::size_t i = 0; i < fresh.size() && i < 12; ++i) + n = append(line, n, sizeof(line), " %p:%llu/%llu %sp%lx", reinterpret_cast(fresh[i].base), fresh[i].committed / mib, + fresh[i].resident / mib, fresh[i].mapped ? "mapped-" : "", fresh[i].protect); + } + n = append(line, n, sizeof(line), " (%llu ms)", GetTickCount64() - began); + x2w_local::logf("%s", line); + if (first) return; + // Second line (logf keeps 1.5 KB a line): growth inside allocations that already existed at the last census. + char more[1024]; + int m = std::snprintf(more, sizeof(more), "x2w-mem census-grown %llu s: existing allocations grown MiB:", second); + if (m < 0) return; + for (int c = 0; c < classes; ++c) m = append(more, m, sizeof(more), " %s +%llu", names[c], grown_bytes[c] / mib); + std::sort(grown.begin(), grown.end(), [](const Grown& a, const Grown& b) { return a.grown > b.grown; }); + m = append(more, m, sizeof(more), "; grown most (base:+MiB, now committed/resident, class):"); + for (std::size_t i = 0; i < grown.size() && i < 10; ++i) + m = append(more, m, sizeof(more), " %p:+%llu %llu/%llu %s", reinterpret_cast(grown[i].base), grown[i].grown / mib, + grown[i].committed / mib, grown[i].resident / mib, names[grown[i].c]); + x2w_local::logf("%s", more); + } catch (...) { + // out of memory while counting: no line this time + } +} + +// A VirtualQuery walk outside the stand-in's page reservations: private committed bytes by kind +// and the largest private allocations. Bounded to a few seconds. +void census(ULONGLONG second) noexcept +{ + const ULONGLONG began = GetTickCount64(); + std::vector ranges(2 * 4096); + const SIZE_T total = x2w_xmem_reserved_ranges(ranges.data(), 4096); + std::vector> skip; + for (SIZE_T i = 0; i < std::min(total, 4096); ++i) skip.emplace_back(ranges[2 * i], ranges[2 * i] + ranges[2 * i + 1]); + std::sort(skip.begin(), skip.end()); + std::vector> known; + AcquireSRWLockShared(&block_lock); + if (blocks) known = *blocks; + ReleaseSRWLockShared(&block_lock); + std::sort(known.begin(), known.end()); + auto in_block = [&](ULONG_PTR address) { + auto it = std::upper_bound(known.begin(), known.end(), std::make_pair(address, ~SIZE_T{0})); + return it != known.begin() && address - std::prev(it)->first < std::prev(it)->second; + }; + struct Allocation { ULONG_PTR base; ULONGLONG committed, reserved; DWORD protect; }; + std::vector top; + ULONGLONG blocks_bytes = 0, private_bytes = 0, image_charged = 0, mapped_bytes = 0, skipped_bytes = 0; + ULONGLONG buckets[5]{}, bucket_counts[5]{}; // <1 MiB, <16, <256, <1024, >=1024 MiB + ULONGLONG queries = 0; + const bool classes_on = census_classes_on(); + std::vector regions; + Allocation current{0, 0, 0, 0}; + auto close = [&] { + if (!current.base || !current.committed) return; + if (in_block(current.base)) { + blocks_bytes += current.committed; + } else { + const ULONGLONG m = current.committed / mib; + const int b = m < 1 ? 0 : m < 16 ? 1 : m < 256 ? 2 : m < 1024 ? 3 : 4; + buckets[b] += current.committed; + ++bucket_counts[b]; + top.push_back(current); + std::sort(top.begin(), top.end(), [](const Allocation& a, const Allocation& c) { return a.committed > c.committed; }); + if (top.size() > 16) top.pop_back(); + } + }; + ULONG_PTR at = 0x10000; + std::size_t next_skip = 0; + bool partial = false; + while (at < 0x7FFFFFFF0000ull) { + while (next_skip < skip.size() && skip[next_skip].second <= at) ++next_skip; + if (next_skip < skip.size() && skip[next_skip].first <= at) { + skipped_bytes += skip[next_skip].second - at; + at = skip[next_skip].second; + continue; + } + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(at), &info, sizeof(info))) break; + ++queries; + ULONG_PTR end = reinterpret_cast(info.BaseAddress) + info.RegionSize; + if (next_skip < skip.size() && end > skip[next_skip].first) end = skip[next_skip].first; // the part before a reservation + const ULONGLONG bytes = end - at; + if (info.State == MEM_COMMIT && classes_on && (info.Type == MEM_PRIVATE || info.Type == MEM_MAPPED) && !in_block(at)) + regions.push_back({at, reinterpret_cast(info.AllocationBase), bytes, info.Protect, info.Type == MEM_MAPPED}); + if (info.State == MEM_COMMIT) { + if (info.Type == MEM_PRIVATE) { + private_bytes += bytes; + const auto base = reinterpret_cast(info.AllocationBase); + if (base != current.base) { + close(); + current = {base, 0, 0, info.Protect}; + } + current.committed += bytes; + } else if (info.Type == MEM_IMAGE) { + const DWORD p = info.Protect & 0xFF; + if (p == PAGE_READWRITE || p == PAGE_WRITECOPY || p == PAGE_EXECUTE_READWRITE || p == PAGE_EXECUTE_WRITECOPY) + image_charged += bytes; + } else if (info.Type == MEM_MAPPED) { + mapped_bytes += bytes; + } + } + if (info.Type == MEM_PRIVATE && info.State != MEM_FREE) { + const auto base = reinterpret_cast(info.AllocationBase); + if (base == current.base) current.reserved += bytes; + } + at = end; + if (GetTickCount64() - began > 5000) { + partial = true; + break; + } + } + close(); + char line[1500]; + int n = std::snprintf(line, sizeof(line), + "x2w-mem census %llu s (%llu ms, %llu queries%s, %llu MiB of %llu stand-in reservations skipped): " + "private committed %llu MiB = startup blocks %llu + other %llu [<1M %llu MiB/%llu, <16M %llu/%llu, " + "<256M %llu/%llu, <1G %llu/%llu, >=1G %llu/%llu]; image writable %llu MiB; mapped outside reservations %llu MiB; top:", + second, GetTickCount64() - began, queries, partial ? ", PARTIAL" : "", skipped_bytes / mib, + static_cast(total), private_bytes / mib, blocks_bytes / mib, + (private_bytes - blocks_bytes) / mib, buckets[0] / mib, bucket_counts[0], buckets[1] / mib, + bucket_counts[1], buckets[2] / mib, bucket_counts[2], buckets[3] / mib, bucket_counts[3], + buckets[4] / mib, bucket_counts[4], image_charged / mib, mapped_bytes / mib); + if (n < 0) return; + for (const Allocation& a : top) + n = append(line, n, sizeof(line), " %p:%llu/%lluMiB p%lx", reinterpret_cast(a.base), a.committed / mib, + a.reserved / mib, a.protect); + const ULONGLONG walk = GetTickCount64(); + n = block_resident_text(line, n, sizeof(line)); + n = append(line, n, sizeof(line), " (%llu ms)", GetTickCount64() - walk); + x2w_local::logf("%s", line); + if (classes_on) { + // The stand-in reservations (title pages are mapped there) as one class: base = the reservation. + for (const auto& [start, end] : skip) regions.push_back({start, start, end - start, 0, true}); + census_classes(second, regions); + } +} + +DWORD WINAPI reporter(void*) +{ + std::vector census_at; + char text[256]{}; + const DWORD n = GetEnvironmentVariableA("X2W_MEM_CENSUS_AT", text, sizeof(text)); + if (n && n < sizeof(text)) + for (char* p = text; *p;) { + char* end = nullptr; + const ULONGLONG v = std::strtoull(p, &end, 10); + if (end == p) break; + census_at.push_back(v); + p = *end ? end + 1 : end; + } + std::sort(census_at.begin(), census_at.end()); + ULONGLONG next_report = 0; // a first line at once: a run may end within seconds + for (;;) { + const ULONGLONG second = (GetTickCount64() - tick_at_load) / 1000; + if (second >= next_report) { + report(second); + next_report = second < 30 ? second + 2 : second + 10; + } + if (!census_at.empty() && second >= census_at.front()) { + census_at.erase(census_at.begin()); + census(second); + } + Sleep(250); + } +} +} // namespace + +namespace x2w_census { +void note_block(void* base, SIZE_T bytes) noexcept +{ + AcquireSRWLockExclusive(&block_lock); + try { + if (!blocks) blocks = new std::vector>; + blocks->emplace_back(reinterpret_cast(base), bytes); + } catch (...) { + } + ReleaseSRWLockExclusive(&block_lock); +} + +void start() noexcept +{ + static INIT_ONCE once = INIT_ONCE_STATIC_INIT; + InitOnceExecuteOnce(&once, [](INIT_ONCE*, void*, void**) -> BOOL { + char value[4]{}; + const DWORD saved = GetLastError(); + // Startup runs only (the debugger sets X2W_TRAP_LOG): tests that load xmem.dll get no thread. + const bool off = (GetEnvironmentVariableA("X2W_MEM_REPORT", value, sizeof(value)) && value[0] == '0') || + !GetEnvironmentVariableA("X2W_TRAP_LOG", nullptr, 0); + if (!off) { + // Pin the module: the thread runs until the process ends. + HMODULE self = nullptr; + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast(&reporter), &self); + if (HANDLE thread = CreateThread(nullptr, 64 << 10, reporter, nullptr, STACK_SIZE_PARAM_IS_A_RESERVATION, nullptr)) + CloseHandle(thread); + } + SetLastError(saved); + return TRUE; + }, nullptr, nullptr); +} +} // namespace x2w_census diff --git a/src/xmem_census.h b/src/xmem_census.h new file mode 100644 index 0000000000..51b022dc5c --- /dev/null +++ b/src/xmem_census.h @@ -0,0 +1,26 @@ +#pragma once +#include + +namespace x2w_census { +// The title's startup blocks (commit_startup_block): the census reports them as their own kind. +void note_block(void* base, SIZE_T bytes) noexcept; +// Starts the reporter once (cheap after the first call). +void start() noexcept; +} // namespace x2w_census + +// Other stand-in DLLs may export this; the reporter adds their counters to its line: +// extern "C" int WINAPI x2w_memory_counters(char* text, int capacity); +// writes "name= ..." pairs (bytes held now), returns the length. +using X2wMemoryCounters = int(WINAPI*)(char* text, int capacity); + +// Exported by xmem.dll (xmem_mapped_pages.cpp). +struct X2wXmemStats { + ULONGLONG slabs, slab_bytes, live_pages, free_slots, slab_budget_bytes, slab_refusals; + ULONGLONG startup_block_bytes, startup_block_calls, permissive_commit_bytes, permissive_commit_calls; + ULONGLONG reservations; + ULONGLONG file_slabs, migrations, migration_failures; // X2W_XMEM_SLAB_DIR +}; +extern "C" BOOL WINAPI x2w_xmem_memory_stats(X2wXmemStats* stats); +// Copies up to capacity (base, bytes) pairs of the stand-in's page reservations; returns the count +// of all of them (may exceed capacity). +extern "C" SIZE_T WINAPI x2w_xmem_reserved_ranges(ULONG_PTR* pairs, SIZE_T capacity); diff --git a/src/xmem_gpu_pool.cpp b/src/xmem_gpu_pool.cpp new file mode 100644 index 0000000000..73603c9196 --- /dev/null +++ b/src/xmem_gpu_pool.cpp @@ -0,0 +1,74 @@ +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include "xmem_gpu_pool.h" + +#include "startup_stubs/local_log.h" + +#include + +namespace x2w_gpu_pool { +namespace { +LONG next_index = 0; +LONG misses = 0; + +bool owner() noexcept +{ + static const bool owned = [] { + const HANDLE claim = CreateEventW(nullptr, TRUE, FALSE, L"Local\\x2w-gpu-slab-pool-owner"); + const DWORD error = GetLastError(); + const bool ok = claim && error != ERROR_ALREADY_EXISTS; + if (!ok) { + if (claim) CloseHandle(claim); + x2w_local::logf("x2w-xmem GPU slab pool: in use by another process (error %lu): fresh sections instead", error); + } + return ok; // the handle is kept open on purpose + }(); + return owned; +} +} // namespace + +Mode mode() noexcept +{ + static const Mode value = [] { + char text[8]{}; + const DWORD n = GetEnvironmentVariableA("X2W_XMEM_GPU_POOL", text, sizeof(text)); + if (n == 1 && text[0] == '0') return Mode::off; + if (n == 3 && (text[0] | 0x20) == 'a' && (text[1] | 0x20) == 'l' && (text[2] | 0x20) == 'l') return Mode::all; + return Mode::moves; + }(); + return value; +} + +HANDLE take(ULONG64 bytes) noexcept +{ + if (mode() == Mode::off || !owner()) return nullptr; + const LONG index = InterlockedIncrement(&next_index) - 1; + wchar_t name[64]; + swprintf(name, 64, L"Local\\x2w-gpu-slab-%ld", index); + const HANDLE section = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, name); + if (!section) { + const DWORD error = GetLastError(); + if (InterlockedIncrement(&misses) <= 2) + x2w_local::logf("x2w-xmem GPU slab pool: %ls not available (error %lu): a fresh section instead " + "(a pagefile one opened as a GPU heap stays charged after this process; " + "tools/startup/gpu_slab_pool.py ensure)", + name, error); + return nullptr; + } + // Size check through a view: the holder may run with another --mib. + void* view = MapViewOfFile(section, FILE_MAP_READ, 0, 0, 0); + MEMORY_BASIC_INFORMATION info{}; + const bool big_enough = view && VirtualQuery(view, &info, sizeof(info)) == sizeof(info) && info.RegionSize >= bytes; + if (view) UnmapViewOfFile(view); + if (!big_enough) { + CloseHandle(section); + x2w_local::logf("x2w-xmem GPU slab pool: %ls is smaller than 0x%llx bytes: a fresh section instead", name, + static_cast(bytes)); + return nullptr; + } + static LONG taken; + if (InterlockedIncrement(&taken) <= 64) + x2w_local::logf("x2w-xmem GPU slab pool: %ls taken for %s", name, mode() == Mode::all ? "a slab" : "a GPU slab"); + return section; +} +} // namespace x2w_gpu_pool diff --git a/src/xmem_gpu_pool.h b/src/xmem_gpu_pool.h new file mode 100644 index 0000000000..1cf39666e9 --- /dev/null +++ b/src/xmem_gpu_pool.h @@ -0,0 +1,11 @@ +#pragma once +#include + +namespace x2w_gpu_pool { +enum class Mode { off, moves, all }; +Mode mode() noexcept; +// The next unused pool section of at least bytes, opened read-write, or nullptr (pool off, not running, +// exhausted, owned by another process, or too small). The contents are whatever the previous user left: the caller +// overwrites or zeroes them. +HANDLE take(ULONG64 bytes) noexcept; +} // namespace x2w_gpu_pool diff --git a/src/xmem_low.h b/src/xmem_low.h new file mode 100644 index 0000000000..d0f6b2d7a2 --- /dev/null +++ b/src/xmem_low.h @@ -0,0 +1,42 @@ +#pragma once +#include + +namespace x2w_low { +inline bool on() noexcept +{ + static const bool value = [] { + char text[8]; + const DWORD n = GetEnvironmentVariableA("X2W_XMEM_LOW40", text, sizeof text); + return n && n < sizeof text && text[0] == '1'; + }(); + return value; +} + +using VirtualAlloc2Fn = PVOID(WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG); +inline VirtualAlloc2Fn virtual_alloc2() noexcept +{ + static const VirtualAlloc2Fn fn = [] { + const HMODULE base = GetModuleHandleW(L"kernelbase.dll"); + return base ? reinterpret_cast(GetProcAddress(base, "VirtualAlloc2")) : nullptr; + }(); + return fn; +} + +// address == nullptr only; type/protect as for VirtualAlloc2 (placeholders allowed). +inline void* alloc(SIZE_T bytes, ULONG type, ULONG protect) noexcept +{ + const auto fn = virtual_alloc2(); + if (!fn) return VirtualAlloc(nullptr, bytes, type, protect); + if (on()) { + MEM_ADDRESS_REQUIREMENTS requirements{}; + // Floor at 4 GiB: low 32-bit addresses can collide with values the title treats as non-pointers. + requirements.LowestStartingAddress = reinterpret_cast(ULONG_PTR{1} << 32); + requirements.HighestEndingAddress = reinterpret_cast((ULONG_PTR{1} << 40) - 1); + MEM_EXTENDED_PARAMETER parameter{}; + parameter.Type = MemExtendedParameterAddressRequirements; + parameter.Pointer = &requirements; + if (void* low = fn(GetCurrentProcess(), nullptr, bytes, type, protect, ¶meter, 1)) return low; + } + return fn(GetCurrentProcess(), nullptr, bytes, type, protect, nullptr, 0); +} +} // namespace x2w_low diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 7567418981..f42ab6c407 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -1,8 +1,17 @@ #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include +#include #include "era_physical.h" +#include "xmem_low.h" +#include "xmem_census.h" +#include "xmem_gpu_pool.h" + +#include +#include "startup_stubs/local_log.h" + +#include #include "xmem_slab_slots.h" #include "xmem_section_lease.h" #include "xmem_page_batch.h" @@ -15,12 +24,14 @@ #include +#include #include #include #include #include #include #include +#include #include namespace { @@ -32,7 +43,7 @@ struct Backing { bool committed = true; // false while a lazily mapped slot is untouched (X2W_XMEM_LAZY_COMMIT) }; -using Slot = std::pair; +using Slot = std::pair; struct SlotPin { unsigned references{}; bool retired{}; }; struct SectionLease { UINT version; @@ -57,11 +68,16 @@ struct PhysicalMemory { SIZE_T mirror_bytes = 0; std::set explicit_mirror_pages; std::map runs; // OS views: base -> bytes - // The slabs and their 64 KiB slots; released slots are reused lowest first, so that pages reused together - // are adjacent slots again. - x2w_xmem::SlabSlots slots{era_physical::page_bytes}; + std::vector slabs; + ULONG64 slab_used = 0; + std::set> free_slots; // ordered, so that pages reused together are adjacent slots again + std::set file_slabs; + ULONG64 migrations = 0, migration_failures = 0; + std::map pool_views; + unsigned char* newest_pool_view = nullptr; // pool_views of slabs.back(), or nullptr when it is not a pool slab + ULONG64 pool_slabs = 0; // not counted against the slab budget: already charged by the holder // A grant may be freed after unmapping while a submitted GPU operation - // still uses the section. Keep those slots out of the reusable pool. + // still uses the section. Keep those slots out of the reusable pool (free_slots). std::map pins; std::map leases; ULONG64 next_lease = 1; @@ -70,7 +86,7 @@ struct PhysicalMemory { { for (const auto& run : runs) UnmapViewOfFile(reinterpret_cast(run.first)); - for (const HANDLE slab : slots.slabs()) + for (const HANDLE slab : slabs) CloseHandle(slab); } }; @@ -78,7 +94,23 @@ struct PhysicalMemory { PhysicalMemory memory; constexpr SIZE_T page_bytes = era_physical::page_bytes; -// Caller holds memory.mutex. A lease may only refer to committed pages whose +volatile LONG64 startup_block_bytes = 0, startup_block_calls = 0; // commit_startup_block +volatile LONG64 permissive_commit_bytes = 0, permissive_commit_calls = 0; // local_virtual_alloc commits +volatile LONG slab_refusals = 0; + +// X2W_XMEM_SLAB_BUDGET_MIB=: no new slab once the slabs would pass n MiB; the page mapping or +// page write that needed it fails (ERROR_COMMITMENT_LIMIT), as on a host without memory, but +// inside the title instead of exhausting the host. 0 or unset: no budget. +ULONG64 slab_budget_bytes() noexcept +{ + static const ULONG64 value = [] { + char text[24]{}; + const DWORD n = GetEnvironmentVariableA("X2W_XMEM_SLAB_BUDGET_MIB", text, sizeof(text)); + return n && n < sizeof(text) ? std::strtoull(text, nullptr, 10) << 20 : 0ull; + }(); + return value; +} + // CPU and GPU views still name the same grant. bool mirrored_range(ULONG_PTR address, SIZE_T length) { @@ -104,7 +136,7 @@ void unpin_slot(const Slot& slot) { const auto found = memory.pins.find(slot); if (--found->second.references) return; - if (found->second.retired) memory.slots.release(slot.first, slot.second); + if (found->second.retired) memory.free_slots.insert(slot); memory.pins.erase(found); } @@ -123,6 +155,112 @@ BOOL physical_result(era_physical::Status status) noexcept } } +constexpr ULONG64 slab_bytes = 4096 * ULONG64{page_bytes}; + +const wchar_t* slab_dir() noexcept +{ + static wchar_t dir[MAX_PATH]{}; + static const bool usable = [] { + const DWORD n = GetEnvironmentVariableW(L"X2W_XMEM_SLAB_DIR", dir, MAX_PATH); + if (!n || n >= MAX_PATH - 40) return false; + const bool absolute = n >= 3 && dir[1] == L':' && (dir[2] == L'\\' || dir[2] == L'/'); + wchar_t cwd[MAX_PATH]{}; + GetCurrentDirectoryW(MAX_PATH, cwd); + const bool same_drive = absolute && (cwd[0] | 0x20) == (dir[0] | 0x20) && cwd[1] == L':'; + const DWORD attributes = absolute ? GetFileAttributesW(dir) : INVALID_FILE_ATTRIBUTES; + const bool ok = absolute && !same_drive && attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY); + x2w_local::logf("x2w-xmem slab directory %ls: %s", dir, + ok ? "file-backed slabs (no commit charge; GPU slabs move to the pagefile)" + : "refused (must be an existing absolute directory off the current drive); pagefile slabs"); + return ok; + }(); + return usable ? dir : nullptr; +} + +ULONG64 pagefile_slabs() noexcept { return memory.slabs.size() - memory.file_slabs.size() - memory.pool_slabs; } + +HANDLE pagefile_slab() noexcept +{ + const ULONG64 budget = slab_budget_bytes(); + if (budget && (pagefile_slabs() + 1) * slab_bytes > budget) { + if (x2w_local::first_of(InterlockedIncrement(&slab_refusals), 4)) + x2w_local::logf("x2w-xmem slab budget reached (X2W_XMEM_SLAB_BUDGET_MIB=%llu, %llu pagefile slabs of 256 MiB): refused", + static_cast(budget >> 20), static_cast(pagefile_slabs())); + SetLastError(ERROR_COMMITMENT_LIMIT); + return nullptr; + } + return CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, static_cast(slab_bytes >> 32), + static_cast(slab_bytes), nullptr); +} + +HANDLE gpu_slab(bool* pooled) noexcept +{ + *pooled = false; + const ULONG64 budget = slab_budget_bytes(); + if (!budget || (pagefile_slabs() + 1) * slab_bytes <= budget) + if (const HANDLE section = x2w_gpu_pool::take(slab_bytes)) { + *pooled = true; + return section; + } + return pagefile_slab(); +} + +HANDLE pool_slab(unsigned char** view) noexcept +{ + static bool exhausted = false; + if (exhausted) return nullptr; + const HANDLE section = x2w_gpu_pool::take(slab_bytes); + void* mapped = section ? MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 0) : nullptr; + if (!mapped) { + if (section) CloseHandle(section); + exhausted = true; + x2w_local::logf("x2w-xmem GPU slab pool (all): no further pool section after %llu (error %lu): fresh %s slabs from " + "now on%s", static_cast(memory.pool_slabs), GetLastError(), + slab_dir() ? "file-backed" : "pagefile", + slab_dir() ? " (moved for the GPU as without the pool)" : " (under the slab budget)"); + return nullptr; + } + *view = static_cast(mapped); + return section; +} + +// A new slab: from the pool with X2W_XMEM_GPU_POOL=all, else file-backed when X2W_XMEM_SLAB_DIR allows it, else from +// the pagefile. *file says whether it is file-backed, *pool_view is the pool section's view (or nullptr). +HANDLE new_slab(bool* file, unsigned char** pool_view) noexcept +{ + *file = false; + *pool_view = nullptr; + if (x2w_gpu_pool::mode() == x2w_gpu_pool::Mode::all) + if (const HANDLE slab = pool_slab(pool_view)) return slab; + if (const wchar_t* dir = slab_dir()) { + static LONG serial; + wchar_t path[MAX_PATH]; + swprintf_s(path, L"%ls\\x2w-slab-%lu-%ld.tmp", dir, GetCurrentProcessId(), InterlockedIncrement(&serial)); + const HANDLE backing = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + if (backing != INVALID_HANDLE_VALUE) { + DWORD returned = 0; + DeviceIoControl(backing, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &returned, nullptr); + const HANDLE slab = CreateFileMappingW(backing, nullptr, PAGE_READWRITE, static_cast(slab_bytes >> 32), + static_cast(slab_bytes), nullptr); + const DWORD error = GetLastError(); + CloseHandle(backing); // the section keeps the file; it is deleted when the section goes + if (slab) { + *file = true; + return slab; + } + static LONG failed; + if (x2w_local::first_calls(failed, 4)) + x2w_local::logf("x2w-xmem file-backed slab %ls failed (error %lu): pagefile slab instead", path, error); + } else { + static LONG failed; + if (x2w_local::first_calls(failed, 4)) + x2w_local::logf("x2w-xmem slab file %ls could not be created (error %lu): pagefile slab instead", path, GetLastError()); + } + } + return pagefile_slab(); +} + // Pages are slots of 256 MiB pagefile-backed sections rather than one section each: one handle and // one view per page is what makes large batches slow. A slab is created with SEC_RESERVE, so it costs // no commit until a slot is used; a slot is committed here, when its page is first mapped or written, @@ -294,52 +432,47 @@ LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) return EXCEPTION_CONTINUE_EXECUTION; } -HANDLE section_for(ULONG_PTR page, bool need_commit = true) +HANDLE section_for(ULONG_PTR page, bool /*need_commit*/ = true) { const auto existing = memory.backings.find(page); - if (existing != memory.backings.end()) { - if (need_commit && !commit_backing(existing->second)) return nullptr; + if (existing != memory.backings.end()) return existing->second.section; - } - // A fresh slot (never used) of a SEC_RESERVE slab reads as zero once committed, so it can wait for its first - // touch. A reused slot is committed and zeroed now, as before. - const bool defer = !need_commit && lazy_commit(); - x2w_xmem::SlabSlots::Slot slot; - if (memory.slots.lowest_free(slot)) { - if (!commit_slot(slot.slab, slot.offset, true)) return nullptr; - memory.backings.emplace(page, Backing{slot.slab, 0, slot.offset, slot.slab_index}); - memory.slots.take_lowest_free(); - return slot.slab; - } - const ULONG64 slab_bytes = memory.slots.slab_bytes(); - bool first_slot_committed = false; - const auto make_slab = [slab_bytes, &first_slot_committed, defer](HANDLE& slab) { - slab = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, - static_cast(slab_bytes >> 32), static_cast(slab_bytes), nullptr); - if (!slab) return false; - if (defer) return true; - first_slot_committed = commit_slot(slab, 0, false); - if (!first_slot_committed) { - const DWORD error = GetLastError(); + if (!memory.free_slots.empty()) { + const auto [section, offset] = *memory.free_slots.begin(); + if (const auto pool = memory.pool_views.find(section); pool != memory.pool_views.end()) { + std::memset(pool->second + offset, 0, page_bytes); // through the pool slab's own view + } else { + void* view = MapViewOfFile(section, FILE_MAP_WRITE, static_cast(offset >> 32), static_cast(offset), page_bytes); + if (!view) return nullptr; + std::memset(view, 0, page_bytes); // a reused slot starts zero-filled, as a fresh section did + UnmapViewOfFile(view); + } + memory.backings.emplace(page, Backing{section, 0, offset}); + memory.free_slots.erase(memory.free_slots.begin()); + return section; + } + if (memory.slabs.empty() || memory.slab_used == slab_bytes) { + bool file = false; + unsigned char* pool_view = nullptr; + const HANDLE slab = new_slab(&file, &pool_view); + if (!slab) return nullptr; + try { + memory.slabs.push_back(slab); + if (file) memory.file_slabs.insert(slab); + if (pool_view) memory.pool_views.emplace(slab, pool_view), ++memory.pool_slabs; + } catch (const std::bad_alloc&) { + if (pool_view) UnmapViewOfFile(pool_view); CloseHandle(slab); - SetLastError(error); + throw; } - return first_slot_committed; - }; - if (!memory.slots.take_fresh(make_slab, [](HANDLE slab) { CloseHandle(slab); }, slot)) return nullptr; - if (!defer && !first_slot_committed && !commit_slot(slot.slab, slot.offset, false)) { - const DWORD error = GetLastError(); - memory.slots.unwind_fresh(slot); - SetLastError(error); - return nullptr; + memory.newest_pool_view = pool_view; + memory.slab_used = 0; } - try { - memory.backings.emplace(page, Backing{slot.slab, 0, slot.offset, slot.slab_index, !defer}); - } catch (...) { - memory.slots.unwind_fresh(slot); - throw; - } - return slot.slab; + const HANDLE section = memory.slabs.back(); + if (memory.newest_pool_view) std::memset(memory.newest_pool_view + memory.slab_used, 0, page_bytes); + memory.backings.emplace(page, Backing{section, 0, memory.slab_used}); + memory.slab_used += page_bytes; + return section; } auto owned_reservation(ULONG_PTR address) @@ -350,32 +483,40 @@ auto owned_reservation(ULONG_PTR address) return address - it->first < it->second ? it : memory.reservations.end(); } -// Only split a reservation owned by the shim. Caller-owned placeholders must already match the view. -// Once a split succeeds, report the retry's result even if it fails for a different reason. -template -bool map_split(void* target, SIZE_T bytes, Map map) +struct MapErrors { + DWORD map = 0, split = 0, retry = 0; + bool split_tried = false; +}; +thread_local MapErrors map_errors; + +// One view of bytes at address: replace the placeholder, or split it out of a bigger recorded placeholder first. +bool map_placeholder(ULONG_PTR address, HANDLE section, ULONG64 section_offset, SIZE_T bytes) { + auto* target = reinterpret_cast(address); + auto map = [&] { + return MapViewOfFile3(section, GetCurrentProcess(), target, section_offset, bytes, MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, nullptr, 0) != nullptr; + }; + map_errors = MapErrors{}; if (map()) return true; - const DWORD error = GetLastError(); - const auto address = reinterpret_cast(target); - const auto reservation = owned_reservation(address); - if (reservation != memory.reservations.end() && bytes <= reservation->second - (address - reservation->first) && - VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) - return map(); - SetLastError(error); + map_errors.map = GetLastError(); + if (owned_reservation(address) == memory.reservations.end()) { + SetLastError(map_errors.map); + return false; + } + map_errors.split_tried = true; + if (!VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) { + map_errors.split = GetLastError(); + return false; + } + if (map()) return true; + map_errors.retry = GetLastError(); return false; } bool map_view(ULONG_PTR address, const Backing& backing) { - const HANDLE section = backing.section; - const ULONG64 section_offset = backing.offset; - auto* target = reinterpret_cast(address); - auto map = [&] { - return MapViewOfFile3(section, GetCurrentProcess(), target, section_offset, - page_bytes, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0) != nullptr; - }; - return map_split(target, page_bytes, map); + return map_placeholder(address, backing.section, backing.offset, page_bytes); } // Maps bytes of one section at address as a single view; falls back to one view per page when the @@ -383,12 +524,7 @@ bool map_view(ULONG_PTR address, const Backing& backing) bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, std::vector>& made, ULONG_PTR& failed_address) { - auto* target = reinterpret_cast(address); - auto map = [&] { - return MapViewOfFile3(backing.section, GetCurrentProcess(), target, backing.offset, bytes, - MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0) != nullptr; - }; - if (map_split(target, bytes, map)) { + if (map_placeholder(address, backing.section, backing.offset, bytes)) { memory.runs[address] = bytes; made.emplace_back(address, bytes); return true; @@ -496,6 +632,113 @@ struct MappingThread { ~MappingThread() { mapping_thread = false; } }; +struct MapFailure; +ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failure = nullptr); // defined below (upstream MapFailure) + +bool retry_handler_ready() noexcept +{ + static const bool ready = [] { + HMODULE pinned = nullptr; + return GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast(&retry_remapped_page), &pinned) && + AddVectoredExceptionHandler(1, retry_remapped_page) != nullptr; + }(); + return ready; +} + +HANDLE migrate_slab(HANDLE old_slab) +{ + const ULONG64 began = GetTickCount64(); + if (!retry_handler_ready()) { + ++memory.migrations, ++memory.migration_failures; + x2w_local::logf("x2w-xmem slab move refused: the fault handler could not be set up"); + return nullptr; + } + for (const auto& [slot, pin] : memory.pins) + if (slot.first == old_slab) { + ++memory.migrations, ++memory.migration_failures; + x2w_local::logf("x2w-xmem slab move refused: a section lease pins one of its slots"); + return nullptr; + } + std::map broken; + for (const auto& [address, page] : memory.views) { + if (memory.backings.at(page).section != old_slab) continue; + auto run = memory.runs.upper_bound(address); + if (run == memory.runs.begin()) continue; + --run; + if (address - run->first < run->second) broken.insert(*run); + } + bool pooled = false; + const HANDLE moved = gpu_slab(&pooled); + if (!moved) { + ++memory.migration_failures; + x2w_local::logf("x2w-xmem slab move refused: no pagefile slab (error %lu)", GetLastError()); + return nullptr; + } + const MappingThread marker; + begin_break(broken); + DWORD error = ERROR_SUCCESS; + std::vector> unmapped; + for (const auto& [base, size] : broken) { + if (!UnmapViewOfFile2(GetCurrentProcess(), reinterpret_cast(base), MEM_PRESERVE_PLACEHOLDER)) { + error = GetLastError(); + break; + } + memory.runs.erase(base); + unmapped.emplace_back(base, size); + } + bool copied = false; + if (error == ERROR_SUCCESS) { + void* from = MapViewOfFile(old_slab, FILE_MAP_READ, 0, 0, 0); + void* to = MapViewOfFile(moved, FILE_MAP_WRITE, 0, 0, 0); + if (from && to) { + // Only the used part of the newest slab holds pages. + const bool newest = !memory.slabs.empty() && memory.slabs.back() == old_slab; + std::memcpy(to, from, newest ? memory.slab_used : slab_bytes); + // A pool section holds an earlier run's bytes: the unused tail must read as zero, as a fresh one. + if (pooled && newest) std::memset(static_cast(to) + memory.slab_used, 0, slab_bytes - memory.slab_used); + copied = true; + } else { + error = GetLastError(); + } + if (from) UnmapViewOfFile(from); + if (to) UnmapViewOfFile(to); + } + if (copied) { + for (auto& [page, backing] : memory.backings) + if (backing.section == old_slab) backing.section = moved; + std::vector> slots; + for (auto it = memory.free_slots.begin(); it != memory.free_slots.end();) { + if (it->first == old_slab) { + slots.emplace_back(moved, it->second); + it = memory.free_slots.erase(it); + } else { + ++it; + } + } + memory.free_slots.insert(slots.begin(), slots.end()); + std::replace(memory.slabs.begin(), memory.slabs.end(), old_slab, moved); + memory.file_slabs.erase(old_slab); + } + ULONG_PTR lost = 0; + for (const auto& [base, size] : unmapped) lost += map_recorded(base, size, false); + end_break(); + ++memory.migrations; + if (!copied) { + ++memory.migration_failures; + CloseHandle(moved); + x2w_local::logf("x2w-xmem slab move failed (error %lu); %llu page(s) could not be mapped again", error, + static_cast(lost)); + return nullptr; + } + CloseHandle(old_slab); + x2w_local::logf("x2w-xmem slab moved to the pagefile for the GPU (#%llu): %llu view(s) in %llu ms, %llu page(s) lost, " + "%llu file-backed slab(s) left", static_cast(memory.migrations), + static_cast(unmapped.size()), static_cast(GetTickCount64() - began), + static_cast(lost), static_cast(memory.file_slabs.size())); + return moved; +} + // Shared views are opt-in: X2W_XMEM_SHARED_VIEWS=1, read once by the first mapping call. Without // it every page has a view of its own, as before: unmapping a page never takes a neighbour away, // no handler is registered, and the module unloads like any DLL. @@ -677,11 +920,66 @@ ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failu return lost; } +struct PageEvent { + ULONG64 tick = 0, serial = 0; + ULONG_PTR page = 0; + DWORD thread = 0; + unsigned char kind = 0; // 1 map, 2 unmap +}; +std::unordered_map page_events; +ULONG64 page_event_serial = 0; // one per successful map or unmap step +ULONG64 remap_gaps = 0; // addresses unmapped and mapped again in one call (P -> Q): a VirtualQuery from another + // thread inside that call sees them uncommitted + +void note_events(const std::map& batch, unsigned char kind) noexcept +{ + const ULONG64 tick = GetTickCount64(), serial = ++page_event_serial; + const DWORD thread = GetCurrentThreadId(); + try { + for (const auto& [address, page] : batch) page_events[address] = PageEvent{tick, serial, page, thread, kind}; + } catch (const std::bad_alloc&) { + } +} + +void log_refusal(const char* what, bool mapping, ULONG_PTR count, ULONG_PTR index, ULONG_PTR address, ULONG_PTR page, + const char* check, DWORD error, ULONG_PTR mapped_before, bool windows) noexcept +{ + MEMORY_BASIC_INFORMATION info{}; + const bool queried = address && VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) == sizeof(info); + const auto live = memory.views.find(address); + const auto reservation = owned_reservation(address); + char windows_text[160] = ""; + if (windows) + std::snprintf(windows_text, sizeof(windows_text), " MapViewOfFile3 err %lu, split %s%lu, map again err %lu;", + map_errors.map, map_errors.split_tried ? "err " : "not tried ", map_errors.split, map_errors.retry); + x2w_local::logf("x2w-xmem REFUSED %s (%s) thread %lu: entry %llu of %llu, address %p page 0x%llx (token 0x%llx, %s): %s, " + "error %lu;%s %llu page(s) of the call mapped before it were taken back | Windows at the address: base %p " + "allocation %p size 0x%llx state 0x%lx type 0x%lx protect 0x%lx%s | registry: %s 0x%llx, reservation %p+0x%llx | " + "slabs %llu (%llu pool), %llu pages live, %llu free slots, budget %llu MiB", + what, mapping ? "map" : "unmap", GetCurrentThreadId(), static_cast(index), + static_cast(count), reinterpret_cast(address), static_cast(page), + static_cast(page << 4), page && era_physical::owns(page) ? "granted" : "NOT granted", + check, static_cast(error), windows_text, static_cast(mapped_before), + queried ? info.BaseAddress : nullptr, queried ? info.AllocationBase : nullptr, + static_cast(queried ? info.RegionSize : 0), queried ? info.State : 0ul, + queried ? info.Type : 0ul, queried ? info.Protect : 0ul, queried ? "" : " (VirtualQuery failed)", + live != memory.views.end() ? "view of page" : "no view", static_cast( + live != memory.views.end() ? live->second : 0), + reservation != memory.reservations.end() ? reinterpret_cast(reservation->first) : nullptr, + static_cast(reservation != memory.reservations.end() ? reservation->second : 0), + static_cast(memory.slabs.size()), static_cast(memory.pool_slabs), + static_cast(memory.backings.size()), + static_cast(memory.free_slots.size()), + static_cast(slab_budget_bytes() >> 20)); + SetLastError(error); +} + // Destinations must be caller-owned, page-sized Windows placeholders. Live views // are owned by this shim until it unmaps them. The caller must not replace them. +// Called with memory.mutex held and a MappingThread marker on this thread (map_pages, local_apply). template -BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& address_at, - bool share_views, MapFailure* failure = nullptr) noexcept +BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& address_at, bool share_views, + const char* what, MapFailure* failure = nullptr) noexcept { if (!count || count > era_physical::capacity_pages) return physical_result(era_physical::Status::invalid); @@ -690,26 +988,42 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& for (ULONG_PTR i = 0; i < count; ++i) { const auto address = address_at(i); const auto live = memory.views.find(address); - const ULONG_PTR page = tokens ? tokens[i] : (live != memory.views.end() ? live->second : 0); - const char* invalid = nullptr; - if (!address || address % page_bytes) invalid = "invalid-address"; - else if (tokens && live != memory.views.end()) invalid = "already-mapped"; - else if (tokens && !era_physical::owns(page)) invalid = "unowned-page"; - else if (!tokens && live == memory.views.end()) invalid = "unmapped-address"; - else if (!batch.emplace(address, page).second) invalid = "duplicate-address"; - if (invalid) { - if (failure) failure->record(invalid, address, page, ERROR_INVALID_PARAMETER); + const char* check = !address || address % page_bytes ? "address is zero or not 64 KiB aligned" + : tokens && live != memory.views.end() ? "a view is already recorded at the address" + : tokens && !era_physical::owns(tokens[i]) ? "the page is not granted (era_physical::owns)" + : !tokens && live == memory.views.end() ? "no view is recorded at the address" + : nullptr; + if (!check && !batch.emplace(address, tokens ? tokens[i] : live->second).second) + check = "the address is named twice in the call"; + if (check) { + log_refusal(what, tokens != nullptr, count, i, address, + tokens ? tokens[i] : live != memory.views.end() ? live->second : 0, check, + ERROR_INVALID_PARAMETER, 0, false); + if (failure) { + const ULONG_PTR page = tokens ? tokens[i] : live != memory.views.end() ? live->second : 0; + const char* stage = !address || address % page_bytes ? "invalid-address" + : tokens && live != memory.views.end() ? "already-mapped" + : tokens && !era_physical::owns(page) ? "unowned-page" + : !tokens && live == memory.views.end() ? "unmapped-address" + : "duplicate-address"; + failure->record(stage, address, page, ERROR_INVALID_PARAMETER); + } return physical_result(era_physical::Status::invalid); } } // Adjacent pages that are adjacent slots of one section share a single view (a "run"): a // multi-gigabyte batch then takes a few views instead of one per 64 KiB page. if (tokens) { + ULONG_PTR index = 0; for (const auto& [address, page] : batch) { - if (!section_for(page, false)) { // committed on first touch with X2W_XMEM_LAZY_COMMIT - if (failure) failure->record("section-backing", address, page, GetLastError()); + if (!section_for(page, false)) { + const DWORD section_error = GetLastError(); + log_refusal(what, true, count, index, address, page, "no backing section for the page (section_for)", + section_error, 0, false); + if (failure) failure->record("section-backing", address, page, section_error); return FALSE; } + ++index; } std::vector> made; auto first = batch.begin(); @@ -724,9 +1038,20 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& ULONG_PTR failed_address; if (!map_run(first->first, head, bytes, made, failed_address)) { const DWORD error = GetLastError(); + // The page map_run stopped at: the first page of the run that has no view. + ULONG_PTR at = first->first; + while (memory.runs.count(at) && at < first->first + bytes) at += page_bytes; + const auto failed = batch.find(at); + log_refusal(what, true, count, static_cast(std::distance(batch.begin(), failed)), at, + failed != batch.end() ? failed->second : 0, + "Windows refused the view (sorted entry; MapViewOfFile3 / placeholder split)", error, + made.size(), true); if (failure) failure->record("map-view", failed_address, batch.at(failed_address), error); for (const auto& [base, size] : made) { - UnmapViewOfFile2(GetCurrentProcess(), reinterpret_cast(base), MEM_PRESERVE_PLACEHOLDER); + if (!UnmapViewOfFile2(GetCurrentProcess(), reinterpret_cast(base), MEM_PRESERVE_PLACEHOLDER)) + x2w_local::logf("x2w-xmem REFUSED %s: taking back the view %p+0x%llx failed (error %lu): a view the " + "registry does not know stays there", what, reinterpret_cast(base), + static_cast(size), GetLastError()); memory.runs.erase(base); } coalesce_unused(batch); @@ -737,6 +1062,7 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& } for (const auto& [address, page] : batch) ++memory.backings.at(page).views; + note_events(batch, 1); memory.views.merge(batch); } else { // Unmap every run that holds a page of the batch, then map the surviving pages of those @@ -769,6 +1095,7 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& } const bool refused = error != ERROR_SUCCESS; if (!refused) { + note_events(batch, 2); for (const auto& [address, page] : batch) { --memory.backings.at(page).views; memory.views.erase(address); @@ -795,14 +1122,16 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& } template -BOOL map_pages(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& address_at, +BOOL map_pages(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& address_at, const char* what, MapFailure* failure = nullptr) noexcept { X2W_ZONE("xmem map_pages"); + if (!count || count > era_physical::capacity_pages) + return physical_result(era_physical::Status::invalid); const bool share_views = fault_retry.ready(); const MappingThread marker; const std::lock_guard guard(memory.mutex); - return map_pages_locked(count, tokens, address_at, share_views, failure); + return map_pages_locked(count, tokens, address_at, share_views, what, failure); } } @@ -844,8 +1173,9 @@ void* local_virtual_alloc(void* address, SIZE_T bytes, DWORD type, ULONGLONG att how = "placeholder kept for page mapping"; } else if (type & MEM_COMMIT) { if (!address) { - result = VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, protect); + result = x2w_low::alloc(bytes, MEM_COMMIT | MEM_RESERVE, protect); how = "commit"; + if (result) InterlockedAdd64(&permissive_commit_bytes, static_cast(bytes)), InterlockedIncrement64(&permissive_commit_calls); } else { result = VirtualAlloc(address, bytes, MEM_COMMIT, protect); if (!result) { @@ -854,10 +1184,12 @@ void* local_virtual_alloc(void* address, SIZE_T bytes, DWORD type, ULONGLONG att MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, protect, nullptr, 0); } how = "commit at address"; + if (result) InterlockedAdd64(&permissive_commit_bytes, static_cast(bytes)), InterlockedIncrement64(&permissive_commit_calls); } } else { - result = VirtualAlloc2(GetCurrentProcess(), address, bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, - nullptr, 0); + result = address ? VirtualAlloc2(GetCurrentProcess(), address, bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, + nullptr, 0) + : x2w_low::alloc(bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS); // A caller that asks for a placeholder splits it itself; other reservations are split here on mapping. if (result && !(type & MEM_RESERVE_PLACEHOLDER)) record_reservation(result, bytes); how = "placeholder reserve"; @@ -924,9 +1256,29 @@ void log_failed_ranges(const char* what, const char* operation, const std::vecto BOOL local_apply_locked(ULONG_PTR count, const ULONG_PTR* addresses, const ULONG_PTR* pages, const char* what, bool share_views) { - std::map want; - for (ULONG_PTR i = 0; i < count; ++i) want[addresses[i]] = pages[i]; + // The pairs in ascending address order, the last pair for a repeated address winning, as an + // ordered map assigned in call order would give; but one allocation instead of a tree node per + // page (a single call can carry ~100,000 pages). + std::vector> want; + want.reserve(count); + bool ascending = true; + for (ULONG_PTR i = 0; i < count; ++i) { + ascending = ascending && (!i || addresses[i] > addresses[i - 1]); + want.emplace_back(addresses[i], pages[i]); + } + if (!ascending) { + std::stable_sort(want.begin(), want.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); + std::size_t kept = 0; + for (std::size_t i = 0; i < want.size(); ++i) { + if (i + 1 < want.size() && want[i + 1].first == want[i].first) continue; // a later pair names it again + want[kept++] = want[i]; + } + want.resize(kept); + } std::vector unmap, map_at, map_page; + // The plan (which addresses to unmap, which to map) and both steps run under ONE hold of the mutex (the + // caller's, local_apply): a call from another thread naming the same addresses in between would make the plan + // wrong and the call fail, where the console applies both calls one after the other. for (const auto& [address, page] : want) { const auto live = memory.views.find(address); if (!page) { @@ -936,6 +1288,7 @@ BOOL local_apply_locked(ULONG_PTR count, const ULONG_PTR* addresses, const ULONG if (live != memory.views.end()) { if (live->second == page) continue; unmap.push_back(address); + ++remap_gaps; } map_at.push_back(address); map_page.push_back(page); @@ -944,13 +1297,13 @@ BOOL local_apply_locked(ULONG_PTR count, const ULONG_PTR* addresses, const ULONG DWORD error = 0; MapFailure failure; if (!unmap.empty() && !map_pages_locked(unmap.size(), nullptr, [&](ULONG_PTR i) { return unmap[i]; }, - share_views, &failure)) { + share_views, what, &failure)) { ok = FALSE; error = GetLastError(); } if (ok && !map_at.empty() && !map_pages_locked(map_at.size(), map_page.data(), [&](ULONG_PTR i) { return map_at[i]; }, - share_views, &failure)) { + share_views, what, &failure)) { ok = FALSE; error = GetLastError(); } @@ -961,10 +1314,14 @@ BOOL local_apply_locked(ULONG_PTR count, const ULONG_PTR* addresses, const ULONG } static LONG calls; if (!ok || x2w_local::first_calls(calls, 16)) - x2w_local::logf("x2w-xmem %s count=0x%llx first=%p map=%llu unmap=%llu -> %d (err %lu)", what, - static_cast(count), count ? reinterpret_cast(addresses[0]) : nullptr, - static_cast(map_at.size()), static_cast(unmap.size()), ok, - static_cast(error)); + x2w_local::logf("x2w-xmem %s count=0x%llx first=%p map=%llu unmap=%llu -> %d (err %lu) thread %lu, %s, lowest %p " + "highest %p%s", what, static_cast(count), + count ? reinterpret_cast(addresses[0]) : nullptr, static_cast(map_at.size()), + static_cast(unmap.size()), ok, static_cast(error), + GetCurrentThreadId(), ascending ? "ascending" : "unsorted", + want.empty() ? nullptr : reinterpret_cast(want.front().first), + want.empty() ? nullptr : reinterpret_cast(want.back().first), + ok ? "" : " (the x2w-xmem REFUSED line above names the entry and the cause; no page of the refused step is mapped)"); SetLastError(error); return ok; } @@ -1015,6 +1372,7 @@ BOOL free_pages(ULONG_PTR count, PULONG_PTR pages); extern "C" BOOL WINAPI XMemAllocatePhysicalPages(ULONG_PTR flags, PULONG_PTR count, PULONG_PTR pages) { + x2w_census::start(); static_assert(sizeof(ULONG_PTR) == sizeof(std::uint64_t)); if (local_permissive()) { const ULONG_PTR requested = count ? *count : 0; @@ -1062,11 +1420,11 @@ BOOL free_pages(ULONG_PTR count, PULONG_PTR pages) for (ULONG_PTR i = 0; i < count; ++i) { const auto backing = memory.backings.find(pages[i]); if (backing != memory.backings.end()) { - const Slot slot{backing->second.slab, backing->second.offset}; + const Slot slot{backing->second.section, backing->second.offset}; if (const auto pin = memory.pins.find(slot); pin != memory.pins.end()) pin->second.retired = true; else - memory.slots.release(slot.first, slot.second); + memory.free_slots.insert(slot); memory.backings.erase(backing); } } @@ -1405,10 +1763,10 @@ extern "C" BOOL WINAPI x2w_xmem_lease_section(UINT version, ULONG_PTR address, S if (!slot) return FALSE; if (selected.empty()) section = slot->section; - else if (slot->section != section || slot->slab != selected.front().first || + else if (slot->section != section || slot->offset != selected.front().second + i * page_bytes) return FALSE; - selected.emplace_back(slot->slab, slot->offset); + selected.emplace_back(slot->section, slot->offset); } if (!DuplicateHandle(GetCurrentProcess(), section, GetCurrentProcess(), &duplicate, 0, FALSE, DUPLICATE_SAME_ACCESS)) @@ -1445,7 +1803,7 @@ extern "C" BOOL WINAPI x2w_xmem_match_section(UINT version, ULONG64 lease, SIZE_ const auto first_page = address & ~(page_bytes - 1); for (SIZE_T slot = first_slot; slot <= last_slot; ++slot) { const auto* backing = lease_backing(version, first_page + (slot - first_slot) * page_bytes); - if (!backing || pin.slots[slot] != Slot{backing->slab, backing->offset}) return FALSE; + if (!backing || pin.slots[slot] != Slot{backing->section, backing->offset}) return FALSE; } return TRUE; } @@ -1471,6 +1829,40 @@ extern "C" BOOL WINAPI x2w_xmem_page_stats(ULONGLONG* live_sections) return TRUE; } +extern "C" BOOL WINAPI x2w_xmem_memory_stats(X2wXmemStats* stats) +{ + if (!stats) return FALSE; + const std::lock_guard guard(memory.mutex); + stats->slabs = memory.slabs.size(); + stats->slab_bytes = memory.slabs.size() * slab_bytes; + stats->live_pages = memory.backings.size(); + stats->free_slots = memory.free_slots.size(); + stats->slab_budget_bytes = slab_budget_bytes(); + stats->slab_refusals = static_cast(slab_refusals); + stats->startup_block_bytes = static_cast(startup_block_bytes); + stats->startup_block_calls = static_cast(startup_block_calls); + stats->permissive_commit_bytes = static_cast(permissive_commit_bytes); + stats->permissive_commit_calls = static_cast(permissive_commit_calls); + stats->reservations = memory.reservations.size(); + stats->file_slabs = memory.file_slabs.size(); + stats->migrations = memory.migrations; + stats->migration_failures = memory.migration_failures; + return TRUE; +} + +extern "C" SIZE_T WINAPI x2w_xmem_reserved_ranges(ULONG_PTR* pairs, SIZE_T capacity) +{ + const std::lock_guard guard(memory.mutex); + SIZE_T i = 0; + for (const auto& [base, bytes] : memory.reservations) { + if (pairs && i < capacity) { + pairs[2 * i] = base; + pairs[2 * i + 1] = bytes; + } + ++i; + } + return i; +} // Experimental export: the slab accounting behind those pages (#1199): slabs open, slots in use and slots free // in the open slabs. A slab is reserved when it is created, its slots are committed on first use, and it is closed only at process end, so // a slot freed by a grant stays committed and these numbers do not show the commit held. @@ -1478,9 +1870,9 @@ extern "C" BOOL WINAPI x2w_xmem_slab_stats(ULONGLONG* slabs, ULONGLONG* slots_in { if (!slabs || !slots_in_use || !slots_free) return FALSE; const std::lock_guard guard(memory.mutex); - *slabs = memory.slots.slab_count(); - *slots_in_use = memory.slots.slots_in_use(); - *slots_free = memory.slots.slots_free(); + *slabs = memory.slabs.size(); + *slots_in_use = memory.backings.size(); + *slots_free = memory.free_slots.size() + (memory.slabs.empty() ? 0 : (slab_bytes - memory.slab_used) / page_bytes); return TRUE; } @@ -1637,14 +2029,12 @@ extern "C" BOOL WINAPI x2w_xmem_write_physical(const ULONG_PTR* tokens, ULONG_PT ULONG_PTR index = 0; while (bytes) { if (index >= count || (tokens[index] & 0xF)) return FALSE; - HANDLE section = nullptr; - ULONG64 section_offset = 0; - { - const std::lock_guard guard(memory.mutex); - section = section_for(tokens[index] >> 4); - if (section) section_offset = memory.backings.at(tokens[index] >> 4).offset; - } + // The lock is held across the write: a slab move (migrate_slab) must not happen between + // finding the section and writing into it. + const std::lock_guard guard(memory.mutex); + const HANDLE section = section_for(tokens[index] >> 4); if (!section) return FALSE; + const ULONG64 section_offset = memory.backings.at(tokens[index] >> 4).offset; void* view = MapViewOfFile(section, FILE_MAP_WRITE, static_cast(section_offset >> 32), static_cast(section_offset), page_bytes); if (!view) return FALSE; @@ -1682,7 +2072,7 @@ extern "C" void* WINAPI XMemMapPhysicalPages(void* base, ULONG_PTR count, const if (!local_apply(count, addresses.data(), pages.data(), "XMemMapPhysicalPages")) return nullptr; return base; } - return map_pages(count, tokens, [=](ULONG_PTR i) { return address + i * page_bytes; }) ? base : nullptr; + return map_pages(count, tokens, [=](ULONG_PTR i) { return address + i * page_bytes; }, "XMemMapPhysicalPages") ? base : nullptr; } extern "C" BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, ULONG_PTR count, @@ -1696,7 +2086,7 @@ extern "C" BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, ULONG return FALSE; return TRUE; } - return map_pages(count, tokens, [=](ULONG_PTR i) { return reinterpret_cast(addresses[i]); }); + return map_pages(count, tokens, [=](ULONG_PTR i) { return reinterpret_cast(addresses[i]); }, "XMemMapPhysicalPagesScatter"); } // Startup compatibility configuration (#1758, under #874): X2W_XMEM_STARTUP_BELOW_40=1 places the @@ -1762,8 +2152,8 @@ static void* keep_startup_block_below_40(void* block, SIZE_T bytes, ULONGLONG at // granularity. Large pages themselves and the console protection bits above PAGE_READWRITE // are not reproduced. A host failure returns NULL with the host error. X2W_XMEM_STARTUP_BELOW_40 // adds an address limit for the 0x283 blocks (keep_startup_block_below_40). -static void* commit_startup_block(SIZE_T bytes, DWORD allocation_type, ULONGLONG attributes, - DWORD protection) noexcept +static void* commit_startup_block_raw(SIZE_T bytes, DWORD allocation_type, ULONGLONG attributes, + DWORD protection) noexcept { constexpr SIZE_T granularity = SIZE_T{64} << 10; const bool large_pages = allocation_type == 0x20003000; @@ -1781,10 +2171,14 @@ static void* commit_startup_block(SIZE_T bytes, DWORD allocation_type, ULONGLONG const DWORD type = lazy ? MEM_RESERVE : MEM_RESERVE | MEM_COMMIT; void* block = nullptr; if (!large_pages) { - block = VirtualAlloc(nullptr, bytes, type, PAGE_READWRITE); + block = x2w_low::alloc(bytes, type, PAGE_READWRITE); } else { MEM_ADDRESS_REQUIREMENTS requirements{}; requirements.Alignment = SIZE_T{2} << 20; + if (x2w_low::on()) { + requirements.LowestStartingAddress = reinterpret_cast(ULONG_PTR{1} << 32); + requirements.HighestEndingAddress = reinterpret_cast((ULONG_PTR{1} << 40) - 1); + } // supported already limits attribute 0x283 to protection 0x2004 or 0x2404. if (below_40 && !startup_below_40_mutant("no_limit")) requirements.HighestEndingAddress = reinterpret_cast(startup_low_limit - 1); @@ -1813,11 +2207,31 @@ static void* commit_startup_block(SIZE_T bytes, DWORD allocation_type, ULONGLONG return block; } +static void* commit_startup_block(SIZE_T bytes, DWORD allocation_type, ULONGLONG attributes, + DWORD protection) noexcept +{ + void* block = commit_startup_block_raw(bytes, allocation_type, attributes, protection); + const DWORD error = GetLastError(); + if (block) { + InterlockedAdd64(&startup_block_bytes, static_cast(bytes)); + x2w_census::note_block(block, bytes); + } + const LONG64 n = InterlockedIncrement64(&startup_block_calls); + if (n <= 64 || !block) + x2w_local::logf("x2w-xmem startup block #%lld size=0x%llx type=0x%lx attr=0x%llx prot=0x%lx -> %p (err %lu), %lld MiB so far", + static_cast(n), static_cast(bytes), static_cast(allocation_type), + attributes, static_cast(protection), block, block ? 0ul : static_cast(error), + static_cast(startup_block_bytes >> 20)); + SetLastError(error); + return block; +} + // The startup commit profile above, and the reserve-only desktop profile from the source-built // #888 comparison. extern "C" void* WINAPI XMemVirtualAlloc(void* address, SIZE_T bytes, DWORD allocation_type, ULONGLONG attributes, DWORD protection) { + x2w_census::start(); constexpr DWORD startup_reserve = 0x20402000; constexpr SIZE_T gib = SIZE_T{1} << 30; if (!address && (allocation_type == 0x20003000 || allocation_type == (startup_reserve | MEM_COMMIT))) @@ -1839,8 +2253,7 @@ extern "C" void* WINAPI XMemVirtualAlloc(void* address, SIZE_T bytes, DWORD allo else ++it; } - auto* reservation = VirtualAlloc2(GetCurrentProcess(), nullptr, bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, - PAGE_NOACCESS, nullptr, 0); + auto* reservation = x2w_low::alloc(bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS); if (!reservation) return nullptr; try { memory.reservations.insert_or_assign(reinterpret_cast(reservation), bytes); @@ -1864,3 +2277,117 @@ extern "C" void* WINAPI XMemVirtualAlloc(void* address, SIZE_T bytes, DWORD allo } return reservation; } + +extern "C" BOOL WINAPI x2w_xmem_page_event(const void* address, ULONG* event_kind, ULONG64* page, ULONG* thread, + ULONG64* age_ms, ULONG64* serial, ULONG64* remaps) +{ + const auto at = reinterpret_cast(address) & ~(ULONG_PTR{page_bytes} - 1); + const std::lock_guard guard(memory.mutex); + const auto event = page_events.find(at); + const PageEvent e = event != page_events.end() ? event->second : PageEvent{}; + if (event_kind) *event_kind = e.kind; + if (page) *page = e.page; + if (thread) *thread = e.thread; + if (age_ms) *age_ms = e.tick ? GetTickCount64() - e.tick : 0; + if (serial) *serial = e.serial; + if (remaps) *remaps = remap_gaps; + return memory.views.count(at) != 0; +} + +bool range_writable(ULONG_PTR start, SIZE_T bytes) noexcept +{ + for (ULONG_PTR cursor = start; cursor < start + bytes;) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(cursor), &info, sizeof(info)) || info.State != MEM_COMMIT || + (info.Protect & (PAGE_GUARD | PAGE_NOACCESS))) + return false; + const DWORD protect = info.Protect & 0xFF; + if (protect != PAGE_READWRITE && protect != PAGE_WRITECOPY && protect != PAGE_EXECUTE_READWRITE && + protect != PAGE_EXECUTE_WRITECOPY) + return false; + const ULONG_PTR end = reinterpret_cast(info.BaseAddress) + info.RegionSize; + if (end <= cursor) return false; + cursor = end; + } + return true; +} + +extern "C" BOOL WINAPI x2w_xmem_write_settled(void* destination, const void* data, SIZE_T bytes, SIZE_T capacity) +{ + if (!destination || (bytes && !data) || bytes > capacity) return FALSE; + const auto start = reinterpret_cast(destination); + if (capacity > std::numeric_limits::max() - start) return FALSE; + const MappingThread marker; // a fault in the copy is never retried by retry_remapped_page (it takes the mutex) + std::unique_lock guard(memory.mutex); + // Inside a recorded reservation, or one starts inside the destination. + const auto next = memory.reservations.upper_bound(start); + const bool ours = owned_reservation(start) != memory.reservations.end() || + (next != memory.reservations.end() && next->first < start + capacity); + if (!ours) guard.unlock(); + if (!range_writable(start, capacity)) return FALSE; + std::memcpy(destination, data, bytes); + return TRUE; +} + +extern "C" BOOL WINAPI x2w_xmem_write_settled_wait(void* destination, const void* data, SIZE_T bytes, SIZE_T capacity, + ULONG wait_ms, ULONG* waited_ms) +{ + const ULONG64 began = GetTickCount64(); + for (;;) { + const BOOL ok = x2w_xmem_write_settled(destination, data, bytes, capacity); + const ULONG64 spent = GetTickCount64() - began; + if (ok || spent >= wait_ms) { + if (waited_ms) *waited_ms = static_cast(spent); + return ok; + } + Sleep(5); + } +} + +extern "C" BOOL WINAPI x2w_xmem_gpu_location(const void* address, HANDLE* section, ULONG64* offset) +{ + if (!section || !offset) return FALSE; + const auto at = reinterpret_cast(address); + const std::lock_guard guard(memory.mutex); + const auto view = memory.views.find(at - at % page_bytes); + if (view == memory.views.end()) return FALSE; + const auto backing = memory.backings.find(view->second); + if (backing == memory.backings.end()) return FALSE; + if (memory.file_slabs.count(backing->second.section) && !migrate_slab(backing->second.section)) return FALSE; + *section = backing->second.section; // the pagefile slab after a move + *offset = backing->second.offset + at % page_bytes; + return TRUE; +} + +extern "C" BOOL WINAPI x2w_xmem_pool_run(const void* address, SIZE_T bytes, HANDLE* section, ULONG64* offset) +{ + if (!section || !offset || !bytes) return FALSE; + const auto at = reinterpret_cast(address); + if (at % page_bytes) return FALSE; +#ifdef X2W_XMEM_TEST_CONTROLS + // Test build only: any slab counts as a pool section (a fixture must not claim the real pool). + static const bool any_slab = x2w_local::env_on("X2W_XMEM_TEST_POOL_ANY"); +#else + constexpr bool any_slab = false; +#endif + const std::lock_guard guard(memory.mutex); + HANDLE first_section = nullptr; + ULONG64 first_offset = 0; + for (SIZE_T done = 0; done < bytes; done += page_bytes) { + const auto view = memory.views.find(at + done); + if (view == memory.views.end()) return FALSE; + const auto backing = memory.backings.find(view->second); + if (backing == memory.backings.end()) return FALSE; + const HANDLE s = backing->second.section; + if (!done) { + if (!memory.pool_views.count(s) && !any_slab) return FALSE; // not a pool section + first_section = s; + first_offset = backing->second.offset; + } else if (s != first_section || backing->second.offset != first_offset + done) { + return FALSE; // the pages are not consecutive in one section + } + } + *section = first_section; + *offset = first_offset; + return TRUE; +} diff --git a/src/xmem_shim.cpp b/src/xmem_shim.cpp index a5b43f0f1d..e9341ae9a6 100644 --- a/src/xmem_shim.cpp +++ b/src/xmem_shim.cpp @@ -28,6 +28,7 @@ #define NOMINMAX #endif #include +#include "xmem_low.h" namespace { // The BVH callers' query buffer. era_query writes at most its first 0x31 bytes. @@ -57,7 +58,7 @@ std::unordered_set& local_blocks() void* local_alloc(SIZE_T bytes, ULONGLONG attributes) { - void* block = bytes ? VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) : nullptr; + void* block = bytes ? x2w_low::alloc(bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) : nullptr; if (block) { AcquireSRWLockExclusive(&local_lock); local_blocks().insert(block); diff --git a/src/xmem_shim.def b/src/xmem_shim.def index 3776c7529f..c1626092b0 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -15,10 +15,17 @@ EXPORTS XMemTransferMemory @13 x2w_xmem_write_physical @14 x2w_xmem_page_stats @15 - x2w_xmem_slab_stats @16 - x2w_xmem_commit_range @17 - x2w_xmem_commit_block @18 - x2w_xmem_lease_section @19 - x2w_xmem_release_section @20 - x2w_xmem_match_section @21 - X2WMapPageBatch @22 + x2w_xmem_gpu_location @16 + x2w_xmem_memory_stats @17 + x2w_xmem_reserved_ranges @18 + x2w_xmem_pool_run @19 + x2w_xmem_page_event @20 + x2w_xmem_write_settled @21 + x2w_xmem_write_settled_wait @22 + x2w_xmem_slab_stats @23 + x2w_xmem_commit_range @24 + x2w_xmem_commit_block @25 + x2w_xmem_lease_section @26 + x2w_xmem_release_section @27 + x2w_xmem_match_section @28 + X2WMapPageBatch @29 diff --git a/tests/bcpack_bc6h_test.cpp b/tests/bcpack_bc6h_test.cpp new file mode 100644 index 0000000000..341cb1d134 --- /dev/null +++ b/tests/bcpack_bc6h_test.cpp @@ -0,0 +1,127 @@ +// BC6H BCPack rebuild (src/startup_stubs/bcpack_bc6h.h) on synthetic lane symbols (no title data). +// 1. Exact path: 48 blocks over all 14 modes whose references stay inside the stream; expected bytes +// from an independent Python model (bcpack_bc6h_vectors.inl). +// 2. Fallback path: the same stream with block 0 pointed at the dictionary; every block whose +// endpoint chain starts there must be counted and must still be a legal block (mode, anchors). +// 3. Negative control: a mode code of 14 fails the stream. +// Exit code 0 = pass. +#include +#include +#include + +#include "../src/startup_stubs/bcpack_bc6h.h" + +namespace { +#include "bcpack_bc6h_vectors.inl" + +using namespace x2w_bcpack; + +int failures = 0; + +void check(bool ok, const char* what) { + std::printf("%s %s\n", ok ? "pass" : "FAIL", what); + failures += ok ? 0 : 1; +} + +// Mode index of a packed block, or -1. +int mode_of(const uint8_t* b) { + const uint32_t m2 = b[0] & 3u; + if (m2 < 2) return static_cast(m2); + for (int k = 2; k < 14; ++k) + if ((b[0] & 31u) == bc6h::MODES[k].code) return k; + return -1; +} + +} // namespace + +int main() { + const size_t nb = BC6H_VEC_BLOCKS; + std::vector sym(BC6H_VEC_SYMBOLS, BC6H_VEC_SYMBOLS + 16 * 2 * nb); + std::vector out(16 * nb); + bc6h::Stats st; + bool ok = bc6h::decode_blocks(sym, nb, out.data(), out.size(), &st); + check(ok, "exact stream decodes"); + check(st.exact == nb && st.endpoints_only == 0 && st.copied == 0 && st.constant == 0, "all blocks exact"); + size_t first = nb; + for (size_t i = 0; i < nb && first == nb; ++i) + if (std::memcmp(out.data() + 16 * i, BC6H_VEC_BLOCKS_OUT + 16 * i, 16) != 0) first = i; + if (first != nb) std::printf(" first mismatch at block %zu\n", first); + check(first == nb, "blocks match the independent model byte for byte"); + + // Block 0: endpoint reference 1 and index reference 1 (> 0 = before the stream start: slot 0). + std::vector fb = sym; + const size_t t = 2 * nb; + fb[0 * t + 0] = 0; fb[0 * t + 1] = 0; // d = 0 -> er = x + fb[1 * t + 0] = 1; fb[1 * t + 1] = 0; // x = 1 + ok = bc6h::decode_blocks(fb, nb, out.data(), out.size(), &st); + check(ok, "dictionary-rooted stream decodes with fallback"); + std::printf(" exact %zu endpoints_only %zu copied %zu constant %zu\n", st.exact, st.endpoints_only, st.copied, + st.constant); + check(st.exact + st.endpoints_only + st.copied + st.constant == nb && st.exact < nb && st.copied + st.endpoints_only > 0, + "fallback classes counted"); + bool legal = true; + for (size_t i = 0; i < nb; ++i) legal &= mode_of(out.data() + 16 * i) >= 0; + check(legal, "fallback blocks carry valid modes"); + + // With a dictionary entry for slot 0 that equals the half-range start, block 0 behaves as ref 0. + static uint16_t dep[255][4][3]; + static uint8_t dix[255][16]; + static bool known[255]; + for (auto& e : dep) for (auto& r : e) for (auto& v : r) v = 0x8000; + for (auto& e : dix) for (auto& v : e) v = 8; + known[0] = true; + bc6h::Dictionary dict; + dict.ep = dep; dict.ep_known = known; dict.ix = dix; dict.ix_known = known; + std::vector zero_ref = sym; + // in the original vector block 0 already references 0; compare dictionary path to it + std::vector out2(16 * nb); + ok = bc6h::decode_blocks(fb, nb, out2.data(), out2.size(), &st, &dict); + std::vector out3(16 * nb); + std::vector fb0 = fb; + fb0[1 * t + 0] = 0; // x = 0, er = 0 + bc6h::Stats st3; + bool ok3 = bc6h::decode_blocks(fb0, nb, out3.data(), out3.size(), &st3); + check(ok && ok3 && st.exact == nb && std::memcmp(out2.data(), out3.data(), out2.size()) == 0, + "a known dictionary slot is used like a stream reference"); + + // Fallback classes against the independent model: a mixed stream (all four paths but constant) + // and a stream whose every endpoint chain is rooted (constant blocks only). + struct FbVec { const char* name; const uint16_t* symbols; const uint8_t* expected; const size_t* counts; }; + const FbVec fbv[] = { { "mixed", BC6H_MIX_SYMBOLS, BC6H_MIX_OUT, BC6H_MIX_COUNTS }, + { "all rooted", BC6H_ROOTED_SYMBOLS, BC6H_ROOTED_OUT, BC6H_ROOTED_COUNTS } }; + for (const FbVec& v : fbv) { + const size_t n = 40; + std::vector s(v.symbols, v.symbols + 16 * 2 * n); + std::vector o(16 * n); + bc6h::Stats fs; + const bool d = bc6h::decode_blocks(s, n, o.data(), o.size(), &fs); + const bool counts = fs.exact == v.counts[0] && fs.endpoints_only == v.counts[1] && fs.copied == v.counts[2] && + fs.constant == v.counts[3]; + std::printf(" %s: exact %zu endpoints_only %zu copied %zu constant %zu\n", v.name, fs.exact, fs.endpoints_only, + fs.copied, fs.constant); + check(d && counts && std::memcmp(o.data(), v.expected, o.size()) == 0, + v.name[0] == 'm' ? "mixed fallback stream matches the model (bytes and counts)" + : "all-rooted stream gives the model's constant blocks"); + } + // copy_known = false: the copied blocks of the mixed stream become constant blocks. + { + std::vector s(BC6H_MIX_SYMBOLS, BC6H_MIX_SYMBOLS + 16 * 2 * 40); + std::vector o(16 * 40); + bc6h::Stats ns; + const bool d = bc6h::decode_blocks(s, 40, o.data(), o.size(), &ns, nullptr, bc6h::DEFAULT_FILL_BASE, false); + check(d && ns.copied == 0 && ns.constant == BC6H_MIX_COUNTS[2] && ns.exact == BC6H_MIX_COUNTS[0], + "copy_known = false turns copied blocks into constant blocks"); + } + // The constant block: mode 13 (5-bit code 0x0f), base 16913 in all channels, x = 0, indices 0. + { + const uint8_t* c = BC6H_ROOTED_OUT; + check((c[0] & 31) == 0x0f, "constant block uses mode 13"); + } + + std::vector bad = sym; + bad[15 * t + 2 * 5] = 14; + check(!bc6h::decode_blocks(bad, nb, out.data(), out.size(), &st), "mode code 14 is rejected"); + + std::printf("%s\n", failures ? "FAILED" : "ALL PASS"); + return failures ? 1 : 0; +} diff --git a/tests/bcpack_bc6h_vectors.inl b/tests/bcpack_bc6h_vectors.inl new file mode 100644 index 0000000000..4902b31c22 --- /dev/null +++ b/tests/bcpack_bc6h_vectors.inl @@ -0,0 +1,193 @@ +static constexpr size_t BC6H_VEC_BLOCKS = 48; +static constexpr uint16_t BC6H_VEC_SYMBOLS[16 * 96] = { + 0, 0, 0, 0, 2, 0, 1, 0, 0, 2, 3, 1, 3, 0, 0, 0, 1, 1, 0, 3, 0, 2, 0, 0, 0, 0, 3, 3, 0, 1, 1, 1, 3, 3, 6, 2, 1, 1, 1, 3, 1, 2, 0, 4, 5, 3, 1, 3, 1, 3, 2, 0, 1, 2, 1, 1, 1, 2, 0, 2, 3, 0, 1, 6, 6, 3, 0, 3, 3, 3, 0, 0, 2, 0, 4, 3, 5, 2, 0, 2, 6, 1, 7, 2, 0, 2, 3, 0, 1, 1, 2, 3, 1, 3, 1, 6, + 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 2, 0, 2, 0, 2, 0, 3, 0, 0, 0, 3, 0, 3, 1, 1, 2, 0, 2, 1, 0, 3, 0, 4, 0, 1, 1, 1, 3, 0, 3, 3, 2, 1, 0, 4, 1, 3, 1, 2, 3, 3, 0, 6, 1, 2, 0, 6, 0, 4, 0, 2, 0, 6, 1, 1, 3, 1, 0, 7, 3, 4, 0, 6, 3, 7, 0, 2, 3, 2, 0, 2, 0, 6, 0, 5, 1, 0, 4, 2, 6, 2, 4, 1, 7, 2, 7, + 58, 246, 125, 17, 34, 12, 111, 115, 202, 49, 35, 116, 57, 57, 53, 89, 164, 96, 46, 43, 142, 26, 205, 167, 233, 204, 165, 243, 166, 16, 244, 138, 107, 180, 186, 50, 82, 9, 216, 113, 131, 65, 219, 160, 55, 38, 111, 64, 120, 175, 0, 192, 157, 148, 27, 30, 155, 6, 157, 230, 30, 134, 109, 84, 0, 139, 88, 83, 97, 23, 253, 246, 163, 158, 182, 101, 198, 10, 34, 181, 138, 245, 112, 72, 68, 68, 117, 154, 73, 107, 9, 248, 150, 128, 156, 9, + 76, 119, 253, 52, 120, 72, 227, 111, 50, 175, 204, 206, 29, 96, 162, 103, 87, 233, 29, 93, 14, 77, 202, 201, 16, 210, 94, 245, 18, 72, 56, 210, 212, 155, 63, 166, 140, 2, 113, 31, 187, 173, 25, 41, 221, 216, 78, 7, 72, 24, 108, 115, 17, 159, 194, 38, 3, 172, 232, 207, 255, 160, 101, 153, 146, 101, 214, 39, 66, 221, 14, 81, 19, 216, 30, 230, 23, 35, 28, 235, 211, 114, 193, 177, 146, 224, 211, 106, 19, 129, 181, 145, 42, 145, 194, 112, + 47, 110, 50, 242, 73, 89, 146, 14, 164, 218, 197, 143, 75, 191, 232, 199, 74, 99, 163, 159, 52, 67, 192, 184, 221, 161, 182, 50, 3, 131, 56, 16, 31, 120, 137, 124, 151, 66, 192, 23, 132, 176, 224, 1, 7, 53, 22, 206, 190, 4, 90, 34, 99, 57, 139, 240, 22, 193, 189, 18, 1, 198, 217, 111, 173, 211, 165, 152, 129, 12, 231, 77, 205, 139, 144, 0, 231, 237, 39, 109, 193, 9, 148, 53, 159, 1, 203, 92, 125, 103, 200, 46, 186, 113, 6, 187, + 28, 7, 0, 18, 20, 19, 21, 12, 16, 1, 31, 5, 18, 22, 9, 20, 18, 3, 11, 20, 18, 21, 25, 4, 30, 3, 30, 11, 16, 0, 19, 1, 7, 5, 30, 6, 20, 13, 9, 6, 17, 24, 22, 28, 15, 28, 17, 10, 17, 2, 13, 20, 31, 8, 12, 29, 22, 28, 20, 14, 31, 14, 28, 5, 19, 18, 5, 24, 25, 20, 2, 6, 7, 12, 0, 5, 9, 7, 10, 17, 4, 30, 17, 29, 29, 30, 3, 6, 7, 22, 23, 22, 29, 16, 15, 4, + 14, 8, 3, 18, 26, 0, 28, 31, 29, 19, 27, 1, 13, 8, 25, 12, 0, 0, 10, 15, 11, 6, 31, 0, 16, 20, 4, 23, 7, 15, 0, 12, 30, 12, 18, 28, 22, 3, 25, 17, 0, 8, 20, 10, 4, 22, 1, 12, 6, 27, 1, 4, 8, 9, 5, 17, 2, 11, 7, 24, 16, 11, 14, 17, 20, 10, 26, 25, 31, 17, 15, 30, 25, 24, 11, 31, 11, 8, 3, 29, 31, 6, 15, 8, 27, 14, 21, 2, 28, 30, 9, 15, 29, 15, 19, 10, + 27, 17, 9, 24, 17, 22, 13, 13, 28, 1, 11, 25, 5, 4, 25, 4, 7, 25, 27, 30, 3, 30, 30, 16, 19, 6, 24, 0, 29, 1, 3, 7, 26, 24, 22, 9, 4, 7, 25, 20, 6, 24, 1, 25, 16, 29, 31, 17, 7, 29, 13, 6, 0, 30, 29, 7, 6, 15, 7, 12, 8, 21, 6, 31, 20, 26, 9, 16, 12, 17, 16, 10, 31, 2, 11, 18, 12, 2, 0, 25, 12, 25, 26, 15, 13, 5, 29, 19, 22, 14, 18, 20, 3, 29, 29, 22, + 3, 42, 5, 3, 13, 34, 8, 41, 20, 24, 36, 30, 38, 6, 35, 4, 47, 41, 5, 14, 8, 41, 51, 21, 30, 17, 13, 48, 56, 45, 2, 18, 44, 41, 13, 44, 43, 57, 12, 48, 34, 17, 61, 23, 47, 2, 49, 40, 43, 52, 13, 39, 2, 33, 45, 18, 53, 39, 30, 29, 49, 60, 39, 35, 48, 29, 57, 29, 9, 21, 25, 0, 6, 12, 17, 46, 6, 39, 44, 6, 11, 37, 41, 60, 40, 36, 37, 42, 42, 55, 27, 55, 26, 5, 4, 50, + 63, 38, 13, 42, 63, 31, 53, 36, 46, 21, 62, 46, 10, 7, 48, 25, 52, 17, 48, 53, 44, 28, 6, 55, 38, 28, 25, 8, 41, 45, 18, 3, 35, 46, 54, 4, 37, 45, 16, 54, 8, 20, 62, 38, 13, 1, 46, 28, 51, 57, 25, 44, 44, 61, 5, 59, 11, 27, 39, 10, 30, 24, 55, 38, 45, 11, 43, 49, 32, 60, 25, 50, 49, 21, 50, 3, 13, 10, 51, 28, 58, 44, 25, 40, 27, 61, 16, 22, 56, 43, 40, 6, 13, 46, 8, 55, + 37, 51, 18, 41, 47, 12, 26, 36, 6, 12, 28, 63, 0, 25, 42, 43, 13, 50, 29, 52, 21, 7, 36, 48, 26, 34, 43, 12, 27, 48, 40, 2, 20, 15, 43, 21, 2, 29, 32, 27, 47, 43, 57, 11, 63, 46, 40, 62, 53, 48, 49, 23, 38, 5, 9, 62, 48, 7, 24, 30, 5, 47, 39, 54, 13, 62, 49, 37, 41, 7, 63, 9, 57, 45, 3, 23, 50, 13, 24, 17, 22, 0, 39, 59, 60, 16, 6, 50, 38, 24, 16, 21, 9, 35, 3, 57, + 191, 121, 238, 109, 51, 106, 115, 116, 91, 204, 134, 7, 180, 15, 7, 40, 193, 152, 247, 215, 160, 239, 31, 213, 226, 242, 212, 60, 235, 153, 157, 35, 174, 51, 28, 11, 207, 234, 124, 108, 232, 136, 242, 119, 145, 104, 139, 89, 141, 144, 45, 8, 15, 52, 49, 122, 94, 31, 7, 136, 44, 27, 249, 105, 148, 71, 210, 245, 157, 130, 140, 212, 97, 52, 16, 94, 97, 235, 160, 119, 196, 58, 95, 65, 128, 71, 208, 37, 177, 42, 54, 40, 151, 81, 48, 175, + 106, 163, 99, 67, 48, 83, 93, 141, 144, 240, 55, 178, 132, 110, 29, 102, 17, 41, 40, 54, 160, 172, 207, 101, 150, 140, 247, 226, 111, 102, 87, 181, 222, 115, 64, 207, 110, 239, 20, 143, 219, 29, 232, 66, 219, 14, 2, 213, 69, 66, 202, 220, 133, 30, 146, 173, 30, 49, 26, 193, 195, 195, 197, 254, 132, 13, 14, 240, 201, 194, 73, 105, 147, 238, 218, 15, 101, 26, 50, 76, 8, 38, 95, 88, 100, 250, 126, 63, 170, 3, 244, 37, 160, 185, 24, 254, + 223, 55, 130, 116, 129, 228, 157, 43, 254, 108, 195, 25, 158, 140, 4, 134, 122, 3, 45, 227, 69, 85, 146, 65, 119, 11, 194, 89, 23, 14, 52, 64, 150, 246, 169, 244, 220, 238, 204, 102, 209, 92, 215, 105, 151, 12, 167, 137, 5, 92, 209, 26, 186, 10, 158, 84, 160, 17, 245, 26, 31, 219, 36, 185, 216, 247, 104, 228, 96, 64, 108, 31, 88, 36, 158, 141, 105, 142, 30, 151, 109, 190, 16, 224, 70, 123, 223, 181, 227, 252, 148, 218, 73, 81, 116, 197, + 90, 0, 94, 22, 245, 155, 12, 33, 246, 3, 199, 208, 210, 204, 44, 82, 149, 10, 90, 231, 27, 210, 187, 185, 176, 45, 246, 115, 60, 65, 98, 48, 0, 24, 91, 192, 46, 65, 132, 147, 144, 254, 190, 235, 127, 187, 76, 242, 159, 117, 56, 48, 165, 88, 151, 157, 4, 200, 130, 244, 32, 148, 223, 59, 35, 248, 78, 126, 37, 16, 79, 71, 160, 0, 31, 239, 81, 110, 149, 251, 157, 189, 219, 96, 21, 31, 178, 141, 112, 64, 196, 38, 24, 45, 81, 90, + 7, 23, 8, 16, 6, 23, 12, 20, 2, 18, 12, 8, 8, 6, 8, 22, 8, 10, 1, 16, 2, 12, 0, 14, 2, 0, 1, 9, 10, 9, 1, 18, 0, 9, 11, 23, 7, 10, 0, 22, 9, 12, 7, 30, 10, 22, 11, 27, 0, 20, 2, 16, 8, 22, 7, 12, 4, 16, 1, 3, 9, 13, 6, 31, 8, 23, 11, 1, 0, 7, 10, 15, 9, 17, 4, 8, 0, 2, 10, 27, 4, 14, 0, 31, 1, 29, 4, 17, 2, 19, 9, 26, 2, 3, 10, 8, +}; +static constexpr uint8_t BC6H_VEC_BLOCKS_OUT[768] = { + 0xd6, 0xc6, 0x5e, 0x02, 0x6e, 0x41, 0x19, 0xb6, 0xdd, 0xe2, 0x82, 0x07, 0xcc, 0x84, 0xc0, 0x22, + 0xda, 0xba, 0xe3, 0x0c, 0xa0, 0x32, 0xad, 0x3f, 0x1b, 0x17, 0xd2, 0x2b, 0xdb, 0x46, 0xff, 0xfa, + 0x12, 0x91, 0xce, 0x3e, 0x3f, 0xe1, 0xc8, 0xab, 0xaa, 0xed, 0x16, 0xd0, 0x5e, 0x38, 0x17, 0x8e, + 0x0b, 0x46, 0x0c, 0x6d, 0x3a, 0xbe, 0x68, 0x41, 0x9a, 0x90, 0x01, 0x47, 0xc9, 0xfe, 0x5d, 0xa7, + 0x62, 0xda, 0x5f, 0xa8, 0x76, 0x8f, 0x8e, 0x27, 0xb0, 0x48, 0x9a, 0x96, 0xb6, 0xf9, 0xfb, 0x6c, + 0xab, 0x1d, 0x3e, 0x44, 0x27, 0x86, 0x1b, 0x8e, 0xb7, 0x2d, 0x2f, 0x8f, 0x31, 0xbd, 0xf8, 0xa4, + 0x9a, 0x25, 0x2f, 0x04, 0x77, 0x49, 0x3a, 0x17, 0x81, 0xdd, 0x4c, 0xcb, 0xbf, 0xe4, 0x5b, 0xd5, + 0x3a, 0x23, 0x7c, 0x90, 0x38, 0xf7, 0xda, 0x57, 0x08, 0xdd, 0xa6, 0x31, 0xc4, 0xb8, 0xf1, 0x96, + 0xda, 0x82, 0x1d, 0x43, 0xfa, 0x73, 0x93, 0x3d, 0xaa, 0x41, 0xb9, 0x18, 0x75, 0x00, 0x5b, 0xda, + 0x95, 0xeb, 0xe8, 0xbb, 0x4d, 0xe9, 0xc8, 0xa2, 0xda, 0x14, 0x86, 0xe1, 0xcc, 0xaf, 0xcc, 0x52, + 0xc2, 0x83, 0x59, 0x7b, 0x3d, 0xb4, 0x03, 0xf4, 0xe3, 0x9c, 0x5d, 0x3d, 0x51, 0x71, 0x27, 0x25, + 0x7c, 0x65, 0x61, 0xd5, 0xed, 0xa2, 0x33, 0x94, 0x3c, 0xd3, 0xd1, 0x46, 0x04, 0x9f, 0x93, 0x85, + 0xe2, 0x14, 0x48, 0xe2, 0x3f, 0x99, 0x94, 0x00, 0x8b, 0x17, 0xcc, 0xfa, 0xe3, 0xa2, 0x1a, 0x0c, + 0x51, 0xa6, 0xbd, 0x9d, 0x7a, 0xa6, 0x27, 0x40, 0x33, 0x3c, 0x85, 0x90, 0x25, 0x9f, 0xeb, 0xbc, + 0xa3, 0x2b, 0x85, 0xe0, 0x03, 0x0b, 0x14, 0xcb, 0xb5, 0x57, 0x44, 0xd5, 0xed, 0x5c, 0xb1, 0x49, + 0xc5, 0xd2, 0xd6, 0xbf, 0x52, 0x12, 0x34, 0x96, 0x96, 0x53, 0x92, 0x1b, 0x65, 0x94, 0x13, 0xd9, + 0xa0, 0xa4, 0x5c, 0x33, 0x1d, 0xae, 0xca, 0x4f, 0x17, 0x37, 0x11, 0xda, 0x37, 0x32, 0xcf, 0x72, + 0xc7, 0xaa, 0x94, 0x2f, 0x75, 0x4c, 0xc4, 0xc5, 0xe6, 0x45, 0x84, 0x7f, 0xd4, 0xc2, 0x9a, 0x8d, + 0x76, 0x4f, 0xe7, 0x56, 0x68, 0xc3, 0x92, 0x6f, 0x81, 0x4b, 0x8d, 0xb3, 0x65, 0x2a, 0x05, 0x21, + 0x20, 0x4a, 0xc9, 0x1a, 0x80, 0xc9, 0xf1, 0x42, 0xd7, 0xc5, 0x32, 0xe7, 0x7f, 0x99, 0x79, 0x1d, + 0x3e, 0x2c, 0xa8, 0x4f, 0x69, 0x08, 0x12, 0x07, 0xb7, 0x8a, 0x21, 0xf2, 0xc9, 0xc9, 0x2f, 0x05, + 0xf6, 0x86, 0xda, 0xd7, 0x44, 0x97, 0x3b, 0xae, 0xf2, 0xd2, 0xc7, 0xa0, 0xe0, 0x83, 0xc4, 0x9c, + 0xa3, 0xe9, 0xa7, 0x20, 0x2f, 0x81, 0xcf, 0xd8, 0xf0, 0xed, 0x52, 0xda, 0xab, 0xbf, 0xe6, 0xe3, + 0xe7, 0x8d, 0x6e, 0xfd, 0x6f, 0xba, 0x1d, 0x96, 0x15, 0x59, 0xeb, 0x80, 0x4b, 0x51, 0x51, 0x32, + 0x40, 0x83, 0x0c, 0xa6, 0xf2, 0x9a, 0xe0, 0xe1, 0x2b, 0x84, 0x32, 0x93, 0xa7, 0xe8, 0xd9, 0xc1, + 0x02, 0xfb, 0xce, 0xfc, 0xa3, 0x96, 0x52, 0x89, 0xf2, 0x01, 0x8e, 0xb2, 0x91, 0x98, 0x76, 0x90, + 0xfa, 0x3f, 0x66, 0xed, 0x4c, 0x81, 0xac, 0x0c, 0xaf, 0xd1, 0xf2, 0x83, 0x64, 0x48, 0xdb, 0x95, + 0x96, 0xb0, 0xe4, 0x38, 0x69, 0xd2, 0x50, 0x73, 0x44, 0x86, 0x5d, 0x90, 0x99, 0x56, 0x94, 0xa9, + 0x2a, 0xcd, 0xae, 0xd7, 0x6a, 0xdd, 0xdc, 0xbf, 0x77, 0x15, 0xe2, 0xcb, 0x80, 0x05, 0x6f, 0x1a, + 0xf5, 0x13, 0xa3, 0x60, 0x2b, 0x80, 0x77, 0x35, 0x78, 0x6d, 0x60, 0x51, 0xe7, 0xd2, 0xf2, 0x13, + 0xbe, 0x59, 0xfc, 0x86, 0x34, 0x3e, 0xd0, 0xcd, 0x47, 0xbc, 0x8d, 0x76, 0x1b, 0xd4, 0xa9, 0x05, + 0x72, 0x3f, 0xcb, 0x2d, 0xf8, 0x77, 0x05, 0x66, 0x1f, 0xf3, 0x53, 0x7f, 0x55, 0x19, 0x21, 0xbc, + 0x3a, 0x8e, 0x78, 0xa8, 0x3c, 0xdb, 0x0f, 0x3d, 0x30, 0xf6, 0x76, 0x58, 0x4a, 0xa9, 0x7b, 0xce, + 0xa7, 0xb8, 0x73, 0x2f, 0x3b, 0x7c, 0x82, 0x9f, 0x4a, 0x46, 0x52, 0x08, 0x8b, 0x14, 0xab, 0xa9, + 0xb8, 0x82, 0x0a, 0x32, 0x65, 0x22, 0xa2, 0xf8, 0xf3, 0xed, 0x8c, 0x33, 0x97, 0xec, 0x9f, 0x6c, + 0x83, 0xd2, 0x5e, 0x63, 0xb3, 0x30, 0x08, 0xb2, 0x7a, 0x90, 0x9f, 0x51, 0xb3, 0x4a, 0x28, 0xf8, + 0xfe, 0x1b, 0xd1, 0xd8, 0x0b, 0xe6, 0xcd, 0xe6, 0x66, 0x34, 0x36, 0x5a, 0x6e, 0x43, 0xae, 0x6b, + 0x6a, 0x36, 0xe5, 0x37, 0xea, 0x85, 0x91, 0x84, 0xc4, 0x01, 0x31, 0x85, 0xa1, 0xef, 0x47, 0x60, + 0xf4, 0xe4, 0xaa, 0x62, 0x24, 0xba, 0xce, 0xaa, 0x4f, 0x59, 0x28, 0x63, 0xfd, 0xc7, 0x56, 0x8b, + 0xe3, 0xdf, 0xa2, 0xf9, 0x9b, 0x88, 0x81, 0x60, 0x77, 0x1d, 0xbc, 0xa2, 0xe1, 0x05, 0x64, 0x71, + 0x6a, 0x21, 0x0b, 0x78, 0x33, 0xb1, 0x80, 0x76, 0x0c, 0xd7, 0x45, 0xde, 0x04, 0xed, 0xca, 0xb0, + 0x1c, 0x16, 0x8f, 0xb2, 0x70, 0x89, 0x81, 0xee, 0x09, 0xf9, 0x8f, 0x8e, 0x26, 0x13, 0x95, 0xdf, + 0x4d, 0x4c, 0x5a, 0xab, 0x1c, 0xb5, 0x6c, 0x48, 0x54, 0xb4, 0x87, 0xe1, 0xa0, 0x19, 0x4f, 0xf5, + 0xaa, 0xdd, 0xa6, 0xda, 0xf4, 0xb9, 0x6e, 0x47, 0x44, 0x2d, 0xf2, 0xef, 0x13, 0x6d, 0x60, 0xf9, + 0x42, 0x7b, 0x32, 0x74, 0xa4, 0xf9, 0xf3, 0xbc, 0xbe, 0x78, 0xda, 0x43, 0x42, 0x3f, 0x07, 0x92, + 0x3e, 0xd8, 0x8e, 0x37, 0x43, 0x08, 0x2b, 0x40, 0x8e, 0x5f, 0x3b, 0x91, 0xaf, 0xef, 0x7b, 0xcd, + 0x42, 0xc9, 0x19, 0xe6, 0x5a, 0x6d, 0x8c, 0x0e, 0xc7, 0x68, 0x04, 0x44, 0xf0, 0xdb, 0x13, 0x0b, + 0xc3, 0x86, 0x28, 0xbf, 0x51, 0xbf, 0x36, 0xfa, 0xc5, 0x26, 0x83, 0xde, 0xf8, 0x80, 0x47, 0x44, +}; +// BC6H_MIX: exact 13, endpoints-only 8, copied 19, constant 0 (Python model) +static constexpr size_t BC6H_MIX_COUNTS[4] = { 13, 8, 19, 0 }; +static constexpr uint16_t BC6H_MIX_SYMBOLS[16 * 80] = { + 0, 0, 0, 2, 0, 1, 0, 3, 1, 0, 2, 1, 5, 0, 0, 0, 2, 0, 0, 1, 3, 1, 0, 0, 0, 2, 1, 3, 4, 0, 1, 1, 6, 2, 1, 1, 3, 1, 4, 0, 0, 4, 4, 1, 1, 0, 3, 1, 5, 2, 5, 1, 7, 1, 1, 6, 1, 0, 3, 4, 2, 1, 7, 4, 0, 3, 1, 4, 7, 2, 5, 0, 7, 7, 5, 1, 2, 2, 4, 2, + 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 3, 1, 1, 2, 1, 1, 1, 1, 2, 0, 1, 3, 0, 0, 3, 1, 1, 2, 0, 0, 0, 0, 3, 2, 3, 0, 1, 2, 0, 2, 0, 5, 1, 3, 2, 3, 2, 7, 0, 7, 1, 7, 1, 6, 2, 7, 3, 2, 0, 5, 3, 3, 2, 5, 1, 3, 4, 4, 3, 2, 4, 3, 3, 3, 0, 1, 1, + 71, 28, 188, 246, 77, 27, 129, 159, 166, 79, 98, 128, 87, 29, 96, 239, 56, 51, 63, 55, 243, 248, 69, 39, 40, 211, 113, 119, 40, 254, 18, 108, 123, 222, 164, 235, 108, 62, 81, 121, 202, 127, 64, 2, 159, 106, 5, 244, 202, 89, 11, 127, 138, 233, 40, 55, 169, 65, 43, 5, 150, 235, 55, 71, 164, 17, 46, 199, 115, 151, 37, 2, 18, 70, 169, 204, 111, 86, 47, 63, + 47, 185, 146, 236, 230, 137, 56, 204, 92, 244, 9, 220, 71, 11, 134, 21, 120, 235, 97, 0, 83, 177, 225, 225, 91, 170, 142, 141, 35, 202, 121, 82, 72, 81, 105, 10, 114, 7, 198, 219, 145, 250, 226, 254, 22, 190, 149, 218, 227, 229, 177, 158, 33, 220, 133, 112, 111, 135, 250, 102, 63, 97, 65, 132, 191, 163, 254, 95, 25, 87, 29, 238, 26, 124, 103, 195, 141, 225, 224, 156, + 220, 79, 126, 200, 169, 131, 197, 120, 77, 130, 86, 178, 213, 167, 85, 131, 118, 116, 119, 131, 229, 158, 75, 41, 171, 38, 113, 124, 228, 77, 20, 100, 153, 253, 89, 53, 115, 127, 113, 124, 188, 46, 144, 54, 82, 75, 177, 71, 227, 212, 167, 10, 235, 71, 133, 73, 101, 58, 180, 78, 32, 46, 46, 29, 158, 230, 204, 31, 71, 53, 191, 116, 92, 240, 200, 202, 51, 225, 71, 54, + 14, 30, 13, 15, 20, 21, 6, 7, 23, 28, 0, 13, 31, 11, 11, 7, 29, 17, 24, 14, 27, 28, 1, 29, 21, 0, 12, 24, 4, 8, 26, 17, 8, 3, 6, 26, 28, 3, 4, 20, 1, 2, 15, 28, 4, 11, 22, 3, 23, 31, 1, 21, 29, 16, 7, 17, 16, 5, 10, 12, 26, 7, 23, 23, 1, 13, 30, 19, 18, 15, 10, 19, 22, 13, 3, 23, 13, 11, 17, 9, + 28, 0, 18, 24, 10, 31, 13, 27, 22, 20, 18, 19, 8, 14, 3, 1, 26, 29, 25, 20, 25, 0, 27, 21, 11, 0, 27, 14, 23, 2, 8, 0, 0, 2, 22, 22, 13, 11, 10, 25, 2, 14, 18, 13, 26, 22, 13, 23, 26, 30, 14, 24, 27, 15, 30, 30, 10, 3, 15, 16, 20, 18, 24, 4, 5, 29, 25, 7, 29, 9, 0, 0, 15, 16, 7, 14, 21, 29, 0, 5, + 26, 12, 28, 31, 2, 8, 17, 20, 21, 26, 11, 15, 23, 10, 22, 8, 28, 12, 1, 9, 6, 12, 28, 11, 22, 15, 25, 28, 1, 5, 10, 22, 13, 20, 4, 29, 14, 9, 27, 24, 9, 27, 2, 17, 29, 22, 12, 3, 10, 13, 8, 16, 30, 11, 9, 23, 16, 19, 22, 25, 0, 12, 24, 25, 22, 17, 11, 20, 1, 10, 19, 13, 21, 4, 17, 16, 4, 7, 13, 19, + 49, 22, 61, 16, 32, 0, 22, 52, 6, 0, 13, 36, 17, 60, 32, 25, 41, 53, 17, 7, 24, 22, 36, 37, 39, 44, 49, 20, 22, 29, 29, 9, 10, 17, 58, 10, 21, 31, 16, 42, 53, 31, 19, 2, 36, 53, 58, 31, 50, 27, 11, 58, 26, 60, 43, 26, 45, 54, 0, 28, 10, 48, 18, 44, 5, 62, 54, 8, 41, 41, 27, 57, 11, 56, 61, 21, 58, 48, 47, 19, + 51, 37, 34, 14, 40, 22, 0, 19, 2, 3, 0, 1, 59, 41, 54, 36, 8, 20, 30, 12, 63, 19, 24, 58, 29, 63, 48, 8, 59, 40, 12, 1, 23, 28, 43, 55, 51, 30, 49, 38, 3, 63, 42, 3, 1, 13, 53, 39, 57, 21, 59, 43, 7, 37, 24, 25, 47, 12, 43, 58, 55, 31, 1, 46, 3, 49, 21, 32, 39, 62, 7, 50, 22, 13, 7, 20, 40, 19, 14, 55, + 4, 45, 3, 41, 48, 25, 6, 12, 3, 51, 43, 22, 60, 63, 32, 35, 45, 16, 44, 13, 37, 33, 18, 39, 37, 24, 46, 44, 16, 11, 9, 21, 35, 41, 54, 14, 36, 28, 24, 13, 36, 33, 42, 30, 23, 50, 52, 25, 13, 23, 11, 5, 61, 13, 26, 39, 3, 30, 18, 17, 25, 17, 34, 4, 3, 17, 52, 33, 31, 55, 27, 16, 34, 7, 39, 47, 21, 29, 32, 7, + 210, 220, 128, 249, 223, 251, 113, 138, 157, 37, 223, 174, 32, 26, 205, 233, 36, 1, 82, 176, 79, 1, 82, 82, 100, 211, 198, 160, 62, 1, 72, 55, 49, 214, 134, 42, 51, 54, 26, 183, 95, 54, 173, 2, 118, 167, 175, 253, 225, 185, 120, 82, 115, 245, 8, 41, 108, 82, 168, 31, 19, 64, 220, 156, 166, 189, 35, 105, 232, 189, 3, 25, 125, 236, 3, 69, 185, 65, 11, 218, + 46, 149, 66, 103, 57, 218, 90, 157, 100, 106, 235, 220, 127, 211, 173, 119, 222, 49, 173, 199, 229, 242, 50, 24, 52, 154, 52, 70, 96, 182, 111, 103, 241, 46, 146, 105, 20, 112, 171, 150, 46, 70, 99, 87, 99, 49, 231, 246, 114, 109, 168, 177, 195, 148, 119, 138, 163, 192, 118, 248, 131, 104, 50, 5, 167, 222, 110, 212, 93, 107, 115, 124, 78, 235, 69, 42, 73, 122, 99, 140, + 113, 156, 236, 253, 203, 246, 121, 75, 47, 122, 25, 111, 13, 230, 0, 208, 54, 24, 16, 75, 99, 60, 241, 105, 128, 203, 92, 52, 103, 139, 175, 62, 23, 9, 4, 49, 166, 104, 159, 3, 37, 171, 96, 212, 28, 142, 225, 37, 191, 187, 66, 163, 120, 77, 61, 63, 114, 18, 234, 123, 156, 55, 222, 161, 115, 161, 161, 223, 45, 243, 120, 116, 41, 248, 68, 52, 142, 121, 49, 253, + 75, 139, 112, 239, 102, 164, 49, 90, 168, 229, 208, 207, 98, 201, 56, 167, 88, 145, 104, 236, 213, 253, 218, 35, 163, 82, 138, 224, 161, 167, 209, 71, 117, 191, 54, 111, 119, 160, 194, 82, 38, 51, 190, 167, 18, 74, 27, 125, 241, 179, 50, 185, 155, 195, 208, 102, 56, 161, 136, 98, 30, 247, 43, 155, 5, 52, 212, 159, 224, 54, 210, 175, 101, 57, 148, 53, 142, 15, 98, 5, + 10, 22, 9, 20, 11, 30, 10, 16, 6, 5, 0, 24, 8, 21, 0, 31, 7, 25, 0, 16, 5, 30, 2, 1, 11, 14, 4, 26, 8, 19, 9, 25, 5, 22, 1, 29, 1, 29, 4, 8, 1, 14, 2, 7, 8, 26, 4, 29, 13, 7, 13, 9, 1, 9, 13, 10, 8, 10, 7, 31, 6, 1, 9, 2, 12, 28, 6, 20, 1, 2, 12, 30, 3, 14, 0, 22, 0, 23, 0, 24, +}; +static constexpr uint8_t BC6H_MIX_OUT[640] = { + 0xa3, 0x14, 0x4a, 0xfb, 0xf5, 0x1b, 0x55, 0x79, 0xe7, 0xfd, 0x94, 0x4c, 0x1a, 0xbd, 0x63, 0x27, + 0xa3, 0x14, 0x4a, 0xfb, 0xf5, 0x1b, 0x55, 0x79, 0x7f, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0xa3, 0x14, 0x4a, 0xfb, 0xf5, 0x1b, 0x55, 0x79, 0x7f, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0xe4, 0xd4, 0x91, 0x16, 0x61, 0x89, 0xa3, 0x3f, 0xbc, 0x06, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0xe4, 0xd4, 0x91, 0x16, 0x61, 0x89, 0xa3, 0x3f, 0xbc, 0x06, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0xe4, 0xd4, 0x91, 0x16, 0x61, 0x89, 0xa3, 0x3f, 0xbc, 0x06, 0x73, 0x4b, 0x3b, 0x12, 0x39, 0x4b, + 0xba, 0x19, 0xfc, 0x09, 0xe3, 0x0d, 0xfa, 0x17, 0xea, 0xa5, 0xbe, 0x6d, 0xdb, 0xde, 0xb6, 0x6d, + 0xba, 0x19, 0xfc, 0x09, 0xe3, 0x0d, 0xfa, 0x17, 0xea, 0xa5, 0xbe, 0x6d, 0xdb, 0xde, 0xb6, 0x6d, + 0xd6, 0x39, 0xc5, 0xb2, 0x8e, 0xbb, 0xa3, 0x17, 0x60, 0x30, 0x1f, 0x7c, 0x1d, 0x65, 0x82, 0xe5, + 0xf8, 0x5c, 0x91, 0xf7, 0x03, 0x67, 0xd5, 0xfe, 0xaa, 0x14, 0xbe, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, + 0x0e, 0xb2, 0x86, 0xd1, 0xcd, 0x68, 0xd7, 0xcc, 0x15, 0xcc, 0xdf, 0x36, 0x41, 0x05, 0xf9, 0x16, + 0x02, 0x36, 0x21, 0x24, 0x77, 0x3a, 0xd4, 0x8d, 0x0e, 0x3b, 0xbc, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, + 0x02, 0x36, 0x21, 0x24, 0x77, 0x3a, 0xd4, 0x8d, 0x0e, 0x3b, 0xbc, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, + 0x0a, 0xc7, 0x5f, 0x4b, 0xc0, 0xd2, 0x0f, 0xd6, 0x03, 0x4f, 0x47, 0x28, 0xf1, 0x82, 0x12, 0xd2, + 0x0a, 0xc7, 0x5f, 0x4b, 0xc0, 0xd2, 0x0f, 0xd6, 0x03, 0x4f, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0x7e, 0x70, 0xa8, 0x72, 0x1c, 0x14, 0x1b, 0xe7, 0xea, 0x39, 0xbf, 0x6d, 0xdb, 0xde, 0xb6, 0x6d, + 0x7e, 0x70, 0xa8, 0x72, 0x1c, 0x14, 0x1b, 0xe7, 0xea, 0x39, 0xbf, 0x6d, 0xdb, 0xde, 0xb6, 0x6d, + 0x2d, 0x95, 0xbf, 0x1b, 0x77, 0x80, 0xc6, 0x29, 0x8f, 0xab, 0x2b, 0xa5, 0xfd, 0xc0, 0x05, 0x0c, + 0x61, 0x4c, 0xae, 0xa9, 0x79, 0xe6, 0x9d, 0x44, 0x2a, 0xb8, 0x0f, 0x74, 0x88, 0x02, 0xf6, 0x3e, + 0x8a, 0x81, 0xc9, 0x4b, 0x40, 0x10, 0x03, 0x7d, 0xc4, 0x0c, 0xc1, 0x37, 0xb4, 0x45, 0x07, 0xef, + 0x65, 0xa1, 0x86, 0xb6, 0x95, 0x0f, 0xd0, 0x24, 0xde, 0xd3, 0x51, 0x48, 0xba, 0xeb, 0x28, 0x6b, + 0x82, 0x4e, 0xd3, 0xb9, 0xb0, 0x41, 0x59, 0xb5, 0xcc, 0xf0, 0x84, 0x44, 0xf4, 0x8d, 0x77, 0x4c, + 0x82, 0x4e, 0xd3, 0xb9, 0xb0, 0x41, 0x59, 0xb5, 0xcc, 0xf0, 0xbc, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, + 0x6f, 0x2c, 0xf6, 0xda, 0x41, 0xd7, 0x81, 0x0d, 0x7e, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0x6f, 0x2c, 0xf6, 0xda, 0x41, 0xd7, 0x81, 0x0d, 0x7e, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0x6f, 0x2c, 0xf6, 0xda, 0x41, 0xd7, 0x81, 0x0d, 0x7e, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0x3d, 0xcd, 0x67, 0x74, 0xd4, 0x0c, 0x84, 0x1e, 0x85, 0x28, 0x0d, 0xe0, 0x6e, 0xf8, 0xd0, 0xdc, + 0x3d, 0xcd, 0x67, 0x74, 0xd4, 0x0c, 0x84, 0x1e, 0x85, 0x28, 0xbd, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, + 0xd6, 0x23, 0x5a, 0xed, 0xcf, 0x35, 0x29, 0xaa, 0xc7, 0xec, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0xd6, 0x23, 0x5a, 0xed, 0xcf, 0x35, 0x29, 0xaa, 0xc7, 0xec, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0xd6, 0x23, 0x5a, 0xed, 0xcf, 0x35, 0x29, 0xaa, 0xc7, 0xec, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0x1e, 0xe8, 0x47, 0xb7, 0x02, 0x1e, 0xba, 0x20, 0x52, 0x5b, 0x6c, 0x16, 0xbf, 0xa5, 0x4b, 0x64, + 0x1e, 0xe8, 0x47, 0xb7, 0x02, 0x1e, 0xba, 0x20, 0x52, 0x5b, 0xbc, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, + 0xf2, 0xc7, 0x1d, 0xd2, 0x79, 0x49, 0xda, 0x46, 0x08, 0x9d, 0xbe, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0xf2, 0xc7, 0x1d, 0xd2, 0x79, 0x49, 0xda, 0x46, 0x08, 0x9d, 0xbe, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0x6b, 0xca, 0x41, 0x8b, 0x1d, 0x93, 0x37, 0x28, 0x7e, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0x6b, 0xca, 0x41, 0x8b, 0x1d, 0x93, 0x37, 0x28, 0x7e, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0x6b, 0xca, 0x41, 0x8b, 0x1d, 0x93, 0x37, 0x28, 0x7e, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x77, + 0xb8, 0xec, 0xab, 0xe9, 0x75, 0xbe, 0x01, 0x54, 0x3d, 0x03, 0xbf, 0xb7, 0x6d, 0xdb, 0xb6, 0x6d, + 0xb8, 0xec, 0xab, 0xe9, 0x75, 0xbe, 0x01, 0x54, 0x3d, 0x03, 0xab, 0x55, 0x4e, 0x22, 0x77, 0x99, +}; +// BC6H_ROOTED: exact 0, endpoints-only 0, copied 0, constant 40 (Python model) +static constexpr size_t BC6H_ROOTED_COUNTS[4] = { 0, 0, 0, 40 }; +static constexpr uint16_t BC6H_ROOTED_SYMBOLS[16 * 80] = { + 2, 0, 0, 1, 0, 0, 1, 0, 2, 1, 0, 3, 2, 2, 0, 1, 0, 1, 3, 1, 4, 0, 2, 0, 6, 1, 4, 2, 1, 0, 0, 4, 3, 2, 1, 1, 4, 1, 3, 3, 0, 7, 0, 4, 0, 5, 3, 5, 6, 5, 1, 6, 7, 0, 1, 5, 4, 2, 1, 5, 3, 3, 4, 6, 7, 2, 3, 6, 2, 0, 10, 2, 0, 1, 4, 6, 4, 1, 12, 1, + 1, 0, 0, 0, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 2, 2, 0, 0, 0, 0, 3, 3, 0, 0, 5, 0, 4, 1, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 4, 2, 0, 0, 4, 3, 5, 3, 6, 2, 0, 0, 6, 3, 7, 3, 0, 0, 1, 4, 0, 5, 1, 5, 0, 0, 3, 4, 0, 0, 0, 0, 0, 0, + 39, 15, 40, 12, 12, 23, 22, 59, 156, 225, 207, 66, 50, 80, 135, 172, 125, 26, 117, 195, 36, 36, 235, 146, 236, 99, 174, 46, 116, 23, 61, 27, 109, 111, 103, 130, 247, 102, 138, 141, 16, 100, 99, 67, 229, 23, 186, 206, 134, 201, 76, 198, 190, 106, 65, 247, 7, 160, 106, 29, 79, 31, 201, 175, 136, 212, 177, 176, 68, 31, 184, 4, 237, 140, 88, 142, 175, 179, 19, 82, + 173, 16, 238, 178, 241, 228, 227, 96, 177, 148, 25, 193, 97, 36, 82, 23, 2, 220, 98, 210, 169, 82, 159, 42, 206, 10, 124, 155, 13, 86, 89, 29, 35, 65, 17, 179, 191, 71, 242, 105, 82, 14, 141, 119, 210, 207, 77, 115, 146, 53, 250, 149, 173, 66, 26, 107, 233, 79, 25, 37, 76, 183, 143, 246, 189, 46, 136, 145, 44, 104, 254, 199, 47, 130, 109, 195, 165, 249, 99, 175, + 229, 206, 160, 126, 248, 13, 249, 38, 18, 162, 110, 249, 38, 147, 191, 224, 252, 88, 74, 40, 228, 112, 64, 245, 134, 76, 169, 249, 4, 21, 5, 151, 126, 37, 183, 236, 30, 55, 236, 49, 196, 234, 224, 114, 186, 73, 27, 156, 75, 186, 123, 29, 25, 219, 103, 241, 236, 113, 172, 140, 212, 177, 105, 108, 32, 84, 91, 28, 58, 80, 143, 155, 170, 67, 161, 231, 217, 153, 33, 69, + 20, 5, 21, 26, 10, 18, 18, 21, 16, 23, 8, 25, 21, 7, 16, 20, 23, 12, 31, 28, 28, 19, 7, 14, 1, 22, 30, 1, 18, 23, 25, 22, 12, 7, 22, 31, 29, 5, 12, 23, 17, 10, 23, 15, 1, 8, 20, 10, 23, 28, 24, 29, 8, 14, 10, 18, 6, 18, 7, 17, 28, 1, 12, 28, 7, 28, 1, 23, 31, 14, 22, 16, 3, 31, 8, 23, 29, 30, 6, 0, + 13, 23, 1, 30, 22, 10, 31, 16, 10, 13, 12, 31, 2, 3, 6, 9, 28, 13, 5, 27, 28, 23, 11, 20, 3, 15, 23, 13, 8, 27, 26, 7, 10, 11, 26, 30, 8, 28, 0, 7, 22, 18, 22, 27, 14, 16, 5, 26, 10, 21, 16, 18, 13, 17, 3, 30, 14, 7, 8, 19, 30, 18, 8, 18, 1, 3, 2, 24, 8, 13, 2, 13, 25, 28, 31, 14, 13, 12, 7, 24, + 24, 14, 25, 25, 20, 17, 10, 21, 16, 8, 23, 12, 24, 17, 26, 28, 22, 31, 24, 25, 25, 8, 17, 6, 22, 13, 29, 12, 12, 23, 14, 31, 6, 29, 27, 29, 4, 4, 0, 8, 10, 3, 28, 26, 27, 4, 10, 6, 24, 29, 27, 31, 26, 5, 11, 19, 7, 22, 12, 19, 9, 18, 24, 21, 3, 29, 9, 26, 31, 26, 7, 7, 30, 2, 28, 8, 0, 30, 9, 17, + 4, 7, 47, 58, 60, 44, 0, 50, 61, 6, 22, 60, 19, 28, 33, 40, 62, 22, 52, 30, 19, 63, 32, 12, 1, 47, 53, 35, 57, 58, 25, 29, 39, 49, 48, 13, 18, 59, 36, 8, 54, 25, 31, 49, 52, 54, 37, 36, 55, 19, 5, 6, 31, 23, 36, 54, 58, 53, 51, 23, 24, 34, 14, 22, 61, 40, 21, 35, 36, 1, 3, 11, 62, 57, 61, 2, 31, 54, 19, 56, + 31, 33, 43, 32, 17, 33, 58, 33, 55, 55, 63, 44, 59, 40, 16, 39, 61, 24, 29, 54, 48, 15, 44, 10, 9, 29, 9, 40, 33, 30, 11, 63, 27, 52, 24, 48, 42, 34, 48, 35, 19, 44, 54, 17, 52, 58, 28, 22, 34, 50, 29, 57, 41, 53, 60, 39, 41, 42, 47, 12, 21, 40, 51, 59, 48, 36, 12, 3, 6, 42, 21, 20, 18, 62, 54, 12, 57, 4, 44, 22, + 36, 18, 33, 50, 38, 0, 31, 7, 37, 17, 43, 33, 60, 29, 47, 15, 53, 61, 39, 10, 42, 39, 48, 55, 49, 1, 59, 36, 28, 32, 23, 26, 63, 40, 62, 17, 7, 25, 9, 51, 61, 24, 58, 60, 1, 7, 39, 7, 24, 28, 42, 60, 5, 6, 62, 25, 48, 39, 61, 27, 55, 16, 52, 1, 49, 53, 9, 34, 58, 37, 29, 26, 50, 19, 5, 34, 45, 29, 44, 32, + 49, 103, 139, 71, 133, 163, 212, 83, 213, 1, 242, 39, 179, 192, 110, 190, 123, 116, 216, 184, 79, 200, 175, 48, 249, 160, 14, 42, 7, 18, 97, 62, 223, 182, 61, 84, 106, 145, 209, 92, 87, 207, 200, 45, 204, 73, 129, 235, 40, 113, 83, 64, 230, 24, 201, 231, 157, 246, 182, 175, 26, 74, 13, 198, 153, 87, 202, 144, 157, 248, 169, 237, 115, 20, 81, 222, 25, 100, 151, 139, + 118, 168, 89, 207, 85, 7, 241, 157, 61, 191, 111, 89, 194, 124, 177, 1, 32, 211, 197, 246, 148, 54, 254, 69, 39, 235, 147, 162, 55, 111, 123, 27, 40, 82, 77, 107, 147, 214, 81, 183, 209, 177, 148, 161, 171, 106, 55, 30, 30, 2, 17, 204, 185, 247, 246, 245, 15, 5, 32, 7, 144, 156, 39, 99, 50, 215, 197, 206, 23, 28, 253, 186, 45, 53, 54, 50, 95, 149, 79, 100, + 67, 86, 157, 246, 250, 196, 239, 218, 123, 150, 170, 143, 124, 254, 202, 221, 210, 187, 242, 160, 16, 177, 17, 190, 145, 137, 42, 240, 227, 85, 167, 230, 81, 253, 76, 221, 136, 126, 148, 22, 170, 1, 111, 11, 237, 33, 110, 58, 102, 143, 222, 52, 28, 38, 60, 179, 120, 171, 54, 103, 248, 39, 73, 211, 82, 219, 201, 128, 228, 23, 62, 112, 202, 56, 244, 119, 137, 236, 10, 192, + 192, 172, 91, 251, 187, 220, 10, 129, 199, 187, 255, 214, 181, 212, 111, 141, 170, 197, 73, 176, 92, 221, 30, 8, 119, 200, 82, 77, 117, 125, 200, 225, 76, 215, 220, 250, 214, 139, 126, 240, 84, 178, 169, 212, 62, 118, 70, 126, 0, 107, 246, 206, 42, 162, 42, 127, 205, 194, 132, 113, 204, 139, 148, 150, 241, 248, 181, 37, 144, 34, 178, 5, 22, 182, 72, 205, 202, 120, 56, 77, + 6, 1, 10, 2, 0, 21, 7, 2, 8, 11, 6, 15, 3, 16, 5, 11, 9, 25, 8, 16, 12, 19, 2, 14, 2, 28, 11, 13, 13, 26, 1, 23, 13, 9, 7, 6, 11, 24, 8, 7, 1, 9, 10, 5, 1, 0, 9, 3, 5, 22, 7, 6, 4, 24, 1, 25, 3, 16, 3, 3, 11, 24, 9, 13, 6, 19, 13, 5, 9, 14, 4, 28, 6, 29, 12, 2, 6, 22, 9, 15, +}; +static constexpr uint8_t BC6H_ROOTED_OUT[640] = { + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2f, 0xc2, 0x08, 0x23, 0x04, 0x01, 0x04, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; diff --git a/tests/bcpack_bcn_check.py b/tests/bcpack_bcn_check.py new file mode 100644 index 0000000000..de45bd1ab2 --- /dev/null +++ b/tests/bcpack_bcn_check.py @@ -0,0 +1,267 @@ +"""Synthetic BCPack BC3/BC4/BC5 streams: encode chosen blocks, decode, compare (no title data). + +The test owns its encoder side: it picks block contents (endpoints, ramp positions and the +references each block predicts from), derives the lane symbols from the reference rules, rANS +encodes every lane with the single-lane test encoder from bcpack_symbols_check.py, and interleaves +the lanes in the order the cycle-level decoder requests bytes. Expected blocks are packed here +directly from the chosen contents, not by the decoder under test. + +PINNED holds one stream per format produced by this encoder (seed 7); the C++ decoder in +src/startup_stubs/bcpack_decoder.h is checked against the same bytes by +tests/bcpack_bcn_decode_test.cpp, which keeps both implementations in step. +""" +import random +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tests")) +import bcpack_bcn # noqa: E402 +from bcpack_bcn import BCPackError, LAYOUTS, tables, zigzag # noqa: E402 +from _bcpack_rans import decode_lanes # noqa: E402 +from bcpack_symbols_check import encode_fragment # noqa: E402 + +ALPHA_CODE = (0, 2, 3, 4, 5, 6, 7, 1) +COLOUR_CODE = (0, 2, 3, 1) + + +def signed(v, bits): + v &= (1 << bits) - 1 + return v - (1 << bits) if v >> (bits - 1) else v + + +def nibbles(byte): + even = odd = 0 + for k in range(4): + even |= ((byte >> (2 * k)) & 1) << k + odd |= ((byte >> (2 * k + 1)) & 1) << k + return even, odd + + +def interleave_lanes(lane_values, alphabet_bits, rng): + """rANS-encode each lane (one flushed fragment) and interleave in decoder request order.""" + streams = [] + for values, ab in zip(lane_values, alphabet_bits): + q = rng.randrange(16) + streams.append(encode_fragment(ab + 1, q, values)) + cursor = [0] * len(streams) + + def source(lane): + byte = streams[lane][cursor[lane]] + cursor[lane] += 1 + return byte + + n = len(lane_values[0]) + order = decode_lanes(b"", list(alphabet_bits), [n] * len(alphabet_bits), source=source)["order"] + if cursor != [len(s) for s in streams]: + raise AssertionError("encoder schedule did not use every lane byte") + cursor = [0] * len(streams) + out = bytearray() + for lane in order: + out.append(streams[lane][cursor[lane]]) + cursor[lane] += 1 + return bytes(out) + + +class Encoder: + """Build lane symbols for chosen blocks of one format.""" + + def __init__(self, fmt, rng): + self.fmt = fmt + self.rng = rng + t = tables() + name = {3: "BC3", 4: "BC4", 5: "BC5"}[fmt] + self.dictionary = t[name + "_DICTIONARY"] + pairs = t["RANK_PAIR_BC3_ALPHA" if fmt == 3 else "RANK_PAIR_" + name] + self.pair_symbol = {tuple(ab): s for s, ab in enumerate(pairs)} + self.quad_symbol = {tuple(v): s for s, v in enumerate(t["RANK_QUAD_BC3_COLOUR"])} + self.ab, self.block, self.per = LAYOUTS[fmt] + self.lanes = [[] for _ in self.ab] + self.hist = [] + self.expected = bytearray() + self.n_ep = {3: 8, 4: 2, 5: 4}[fmt] + self.n_ix = 16 if fmt == 4 else 32 + + def source(self, i, r): + if r == 0: + return [0] * self.n_ep, [0] * self.n_ix + if r <= i: + return self.hist[i - r] + ep, ix = self.dictionary[r - i - 1] + return list(ep), list(ix) + + def put_ref(self, er, xr): + d = zigzag(signed(er - xr, 8)) + if self.per == 1: + self.lanes[0].append(d) + self.lanes[1].append(xr) + else: + self.lanes[0].extend(nibbles(d)) + self.lanes[1].extend(nibbles(xr)) + + def add(self, er, xr, ep, ix): + """Append one block with endpoint states `ep`, ramp positions `ix`, references er/xr.""" + i = len(self.hist) + ep_ref, _ = self.source(i, er) + _, ix_ref = self.source(i, xr) + self.put_ref(er, xr) + widths = {3: (8, 8, 5, 6, 5, 5, 6, 5), 4: (8, 8), 5: (8, 8, 8, 8)}[self.fmt] + res = [zigzag(signed(ep[k] - ep_ref[k], widths[k])) for k in range(self.n_ep)] + if self.fmt == 4: + self.lanes[2].append(res[0]) + self.lanes[3].append(res[1]) + elif self.fmt == 5: + self.lanes[2].extend(res[0:2]) + self.lanes[3].extend(res[2:4]) + else: + self.lanes[2].extend(res[0:2]) + for c in range(3): + self.lanes[7 + c].extend((res[2 + c], res[5 + c])) + alpha_channels = {3: 1, 4: 1, 5: 2}[self.fmt] + for c in range(alpha_channels): + for k in range(8): + p = 16 * c + 2 * k + sym = self.pair_symbol[((ix[p] - ix_ref[p]) & 7, (ix[p + 1] - ix_ref[p + 1]) & 7)] + if self.fmt == 4: + self.lanes[4 + k].append(sym) + else: + base = 3 if self.fmt == 3 else 4 + 4 * c + self.lanes[base + k // 2].append(sym) + if self.fmt == 3: + quad_pixels = [] + for ox, oy in ((0, 0), (2, 0), (0, 2), (2, 2)): + quad_pixels.append([16 + 4 * (oy + dy) + ox + dx for dx, dy in ((0, 0), (1, 0), (0, 1), (1, 1))]) + for q, pix in enumerate(quad_pixels): + key = tuple((ix[p] - ix_ref[p]) & 3 for p in pix) + self.lanes[10 + (q >> 1)].append(self.quad_symbol[key]) + self.hist.append((list(ep), list(ix))) + self.expected += self.pack(ep, ix) + + def pack(self, ep, ix): + def alpha(e0, e1, pos): + v = (e0 ^ 0x80) | (e1 ^ 0x80) << 8 + for p in range(16): + v |= ALPHA_CODE[pos[p]] << (16 + 3 * p) + return v.to_bytes(8, "little") + + if self.fmt == 4: + return alpha(ep[0], ep[1], ix) + if self.fmt == 5: + return alpha(ep[0], ep[1], ix[:16]) + alpha(ep[2], ep[3], ix[16:]) + c0 = ep[2] << 11 | ep[3] << 5 | ep[4] + c1 = ep[5] << 11 | ep[6] << 5 | ep[7] + w = sum(COLOUR_CODE[ix[16 + p]] << (2 * p) for p in range(16)) + return (alpha(ep[0], ep[1], ix[:16]) + c0.to_bytes(2, "little") + c1.to_bytes(2, "little") + + w.to_bytes(4, "little")) + + def random_block(self, er, xr): + rng = self.rng + i = len(self.hist) + ep_ref, ix_ref = self.source(i, er) + widths = {3: (8, 8, 5, 6, 5, 5, 6, 5), 4: (8, 8), 5: (8, 8, 8, 8)}[self.fmt] + # Small residuals mostly (like real data), sometimes a full-range value. + ep = [(ep_ref[k] + (rng.randrange(-3, 4) if rng.random() < 0.7 else rng.randrange(1 << widths[k]))) + & ((1 << widths[k]) - 1) for k in range(self.n_ep)] + ix = [] + for p in range(self.n_ix): + mask = 3 if self.fmt == 3 and p >= 16 else 7 + ix.append(rng.randrange(mask + 1)) + self.add(er, xr, ep, ix) + + def stream(self): + return interleave_lanes(self.lanes, self.ab, self.rng), bytes(self.expected) + + +def build(fmt, seed, blocks=24): + """Blocks cover: zero references, history references at several distances, dictionary + references before the first block, and non-zero index references.""" + rng = random.Random(seed) + enc = Encoder(fmt, rng) + for i in range(blocks): + choice = i % 6 + if i == 0: + er, xr = 3, 0 # dictionary entry 2 (before the chunk) + elif i == 1: + er, xr = 0, 2 # zero endpoint state, index state from dictionary entry 0 + elif choice == 2: + er, xr = 1, 1 + elif choice == 3: + er, xr = min(i, 5), 0 + elif choice == 4: + er, xr = 0, min(i, 3) + else: + er, xr = rng.randrange(1, i + 1), rng.randrange(0, i + 1) + enc.random_block(er, xr) + return enc.stream() + + +# Seed-7 streams of 4 blocks, as decoded by tests/bcpack_bcn_decode_test.cpp. +PINNED_SEED = 7 +PINNED_BLOCKS = 4 + + +class BcnChecks(unittest.TestCase): + def test_roundtrip_all_formats(self): + for fmt in (3, 4, 5): + for seed in (1, 2, 3): + with self.subTest(fmt=fmt, seed=seed): + stream, expected = build(fmt, seed) + self.assertEqual(bcpack_bcn.decode(stream, fmt, len(expected)), expected) + + def test_lane_shape_and_trailing_zeros(self): + stream, expected = build(5, 4) + syms, n = bcpack_bcn.lane_symbols(stream + bytes(16), 5, len(expected)) + self.assertEqual(n, len(expected) // 16) + self.assertTrue(all(len(lane) == 2 * n for lane in syms)) + with self.assertRaises(BCPackError): + bcpack_bcn.decode(stream + b"\x01", 5, len(expected)) + + def test_negative_controls(self): + for fmt in (3, 4, 5): + stream, expected = build(fmt, 5) + block = LAYOUTS[fmt][1] + with self.subTest(fmt=fmt, case="truncated"), self.assertRaises(BCPackError): + bcpack_bcn.decode(stream[:-1], fmt, len(expected)) + with self.subTest(fmt=fmt, case="one block too many"), self.assertRaises(BCPackError): + bcpack_bcn.decode(stream, fmt, len(expected) + block) + with self.subTest(fmt=fmt, case="not a block multiple"), self.assertRaises(ValueError): + bcpack_bcn.decode(stream, fmt, len(expected) - 1) + # A flipped payload byte must not reproduce the expected blocks. + bad = bytearray(stream) + bad[len(bad) // 2] ^= 0x40 + with self.subTest(fmt=fmt, case="flipped byte"): + try: + self.assertNotEqual(bcpack_bcn.decode(bytes(bad), fmt, len(expected)), expected) + except BCPackError: + pass + + def test_wrong_format_layout_rejected(self): + # A BC5 stream read with the BC4 layout must not decode cleanly to the same bytes. + stream, expected = build(5, 6) + try: + self.assertNotEqual(bcpack_bcn.decode(stream, 4, len(expected)), expected) + except BCPackError: + pass + + def test_cpp_vectors_match(self): + source = (ROOT / "tests" / "bcpack_bcn_decode_test.cpp").read_text(encoding="utf-8") + for fmt in (3, 4, 5): + stream, expected = build(fmt, PINNED_SEED, PINNED_BLOCKS) + with self.subTest(fmt=fmt): + self.assertIn('"%s"' % stream.hex(), source) + self.assertIn('"%s"' % expected.hex(), source) + + +def print_pinned(): + for fmt in (3, 4, 5): + stream, expected = build(fmt, PINNED_SEED, PINNED_BLOCKS) + print(fmt, stream.hex(), expected.hex()) + + +if __name__ == "__main__": + if sys.argv[1:] == ["--print-pinned"]: + print_pinned() + else: + unittest.main() diff --git a/tests/bcpack_bcn_decode_test.cpp b/tests/bcpack_bcn_decode_test.cpp new file mode 100644 index 0000000000..19c2ffac6e --- /dev/null +++ b/tests/bcpack_bcn_decode_test.cpp @@ -0,0 +1,94 @@ +// Synthetic BCPack BC3/BC4/BC5 vectors for x2w_bcpack::decode_bcpack (no title data). +// The streams and expected blocks come from the encoder in tests/bcpack_bcn_check.py +// (seed 7, 4 blocks per format); that test checks the Python reference decoder against the +// same bytes, so both implementations stay in step. Exit code 0 = pass. +#include +#include +#include +#include + +#include "../src/startup_stubs/bcpack_decoder.h" + +namespace { + +struct Vector { + unsigned format; + const char* stream; + const char* expected; +}; + +const Vector kVectors[] = { + { 3, + "161f1b1010181f18050706090909130705011b0101a301018801200000010065943056f5f3dcff88a924b9a56124db5bc1ffbc744452ff37dc161b1e1b0709130f782501035b0700f231ddfffb74154f9b596bffe137e40cfffed924eddefffd33f8600bff59b629d8ff074404ffcec7ffa2fff1c2ffb43052bdffe4ff03e9f2ffbd04c492ff7ef48cb1f218d1ffb0000054ffbc00d8ff00bd00000000", + "7e7d878883583f75118cf16338605daf7e7f876c275223349dfce007372de15a7c7fda48642d767b6ef3e9b7544521267b7e529254939b816f74d153cbbcbb9a" }, + { 4, + "1e191c1b101e1b1506050407060b090608020e92010108042446724900008a02fe0478742cfffffed0316b2950d4e0a6e540ad16e8ffff05c8d9131f1116060b0606050102976f003dc3ffffc4df08d625a4faff14fb1351e0ffff1b1ced11d1d5fff3a0000000ffcd49bbe8f6edff960000ee00000000", + "1f159241e8177588814b20d64f9d6809814b4e5c8e6a9c4a1d6239643b911aa1" }, + { 5, + "1f1e1f1f191214130f0711110a0909090101010101021c0301010202eef0cc13ff30ffffcf24ff39f2240302f94781a0ffffffff67411a97f105021a181f150d0d1309031b01032eec00acd3ffff785f81dccbe9a5ff87ffff016af4aeddfff10204f4fedd2afeffffffffd51ce5eefbf101be01d7ff20ffa72105b57dee14f19d02dda9ffff3001fff991fae9030205cbff98ffff8b17a51e09cf3673ff55ff0054c4208dfff6f10106ff2c0000000000f40000000000", + "7e7d20f48b3a441c8080c4faa9132d81817fa31aa7d2e7e5807e90ed446a84a6327fecf847cbbbf7817b3ea78d44d6627d7cffaf1c1433199b83c264885fed48" }, +}; + +std::vector hex(const char* s) { + std::vector out; + auto nibble = [](char c) -> unsigned { + return c <= '9' ? static_cast(c - '0') : static_cast(c - 'a' + 10); + }; + for (size_t i = 0; s[i] && s[i + 1]; i += 2) { + out.push_back(static_cast(nibble(s[i]) << 4 | nibble(s[i + 1]))); + } + return out; +} + +int failures = 0; + +void check(bool ok, const std::string& what) { + std::printf("%s %s\n", ok ? "PASS" : "FAIL", what.c_str()); + if (!ok) ++failures; +} + +} // namespace + +int main() { + for (const Vector& v : kVectors) { + const std::vector in = hex(v.stream); + const std::vector want = hex(v.expected); + const std::string tag = "BC" + std::to_string(v.format); + const size_t block = v.format == 4 ? 8 : 16; + + std::vector out(want.size(), 0xCD); + size_t produced = 0; + bool ok = x2w_bcpack::decode_bcpack(in.data(), in.size(), v.format, out.data(), out.size(), &produced); + check(ok && produced == want.size() && out == want, tag + " decodes the expected blocks"); + + // Zero padding after the stream is accepted (archive intervals are padded). + std::vector padded = in; + padded.resize(in.size() + 16, 0); + ok = x2w_bcpack::decode_bcpack(padded.data(), padded.size(), v.format, out.data(), out.size(), &produced); + check(ok && out == want, tag + " accepts trailing zero padding"); + + // Negative controls: truncated stream, non-zero trailing byte, wrong block count, size + // that is not a whole number of blocks. + ok = x2w_bcpack::decode_bcpack(in.data(), in.size() - 1, v.format, out.data(), out.size(), &produced); + check(!ok, tag + " rejects a truncated stream"); + std::vector junk = in; + junk.push_back(1); + ok = x2w_bcpack::decode_bcpack(junk.data(), junk.size(), v.format, out.data(), out.size(), &produced); + check(!ok, tag + " rejects non-zero trailing data"); + std::vector big(want.size() + block); + ok = x2w_bcpack::decode_bcpack(in.data(), in.size(), v.format, big.data(), big.size(), &produced); + check(!ok, tag + " rejects one block more than encoded"); + ok = x2w_bcpack::decode_bcpack(in.data(), in.size(), v.format, out.data(), out.size() - 1, &produced); + check(!ok, tag + " rejects a size that is not a block multiple"); + } + + // BC6H has a verified lane layout but no block reconstruction: the decoder must refuse it. + const std::vector any = hex(kVectors[2].stream); + std::vector out(64); + size_t produced = 0; + check(!x2w_bcpack::decode_bcpack(any.data(), any.size(), 6, out.data(), out.size(), &produced), + "BC6H (format 6) is refused"); + + std::printf("%s (%d failures)\n", failures ? "FAILED" : "OK", failures); + return failures ? 1 : 0; +} diff --git a/tests/buffer_address_index_check.cpp b/tests/buffer_address_index_check.cpp new file mode 100644 index 0000000000..19ae432e77 --- /dev/null +++ b/tests/buffer_address_index_check.cpp @@ -0,0 +1,112 @@ +#include "startup_stubs/buffer_address_index.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Index = x2w_startup::BufferAddressIndex; + +namespace { +int failures; +void fail(const char* what, std::uint64_t a, std::uint64_t b) +{ + if (failures++ < 10) std::printf("FAIL %s (0x%llx, %llu)\n", what, static_cast(a), static_cast(b)); +} + +std::set query(const Index& index, std::uint64_t address, std::uint64_t bytes) +{ + std::set out; + index.containing(address, bytes, [&](int key, std::uint64_t, std::uint64_t) { + out.insert(key); + return true; + }); + return out; +} +std::set walk(const std::map>& ranges, std::uint64_t address, std::uint64_t bytes) +{ + std::set out; + for (const auto& [key, r] : ranges) { + const auto [base, width] = r; + if (address < base || address - base >= width || bytes > width - (address - base)) continue; + out.insert(key); + } + return out; +} + +void explicit_cases(Index::Mutation m) +{ + Index index(m); + index.insert(1, 0x10000, 0x1000); // small + index.insert(2, 0x10800, 0x100); // nested in 1 + index.insert(3, 0x0, 0x40000000); // 1 GiB, covers everything below + if (query(index, 0x10850, 4) != std::set{1, 2, 3}) fail("overlap: nested ranges", 0x10850, 4); + if (query(index, 0x10fff, 1) != std::set{1, 3}) fail("overlap: last byte of 1", 0x10fff, 1); + if (query(index, 0x10ffe, 4) != std::set{3}) fail("crossing the end of 1", 0x10ffe, 4); + if (query(index, 0x11000, 1) != std::set{3}) fail("one past 1", 0x11000, 1); + index.erase(2); + if (query(index, 0x10850, 4) != std::set{1, 3}) fail("removal of 2", 0x10850, 4); + index.insert(1, 0x20000, 0x1000); // move + if (query(index, 0x10850, 4) != std::set{3} || query(index, 0x20010, 4) != std::set{1, 3}) fail("move of 1", 0x20010, 4); + index.erase(3); + if (!query(index, 0x10, 1).empty() || index.size() != 1) fail("removal of 3", 0x10, 1); + if (index.erase(3)) fail("second erase", 3, 0); +} + +void random_cases(Index::Mutation m, unsigned operations) +{ + Index index(m); + std::map> ranges; + std::mt19937_64 rng(20261125); + const std::uint64_t widths[] = {16, 256, 4096, 65536, 65537, 1ull << 20, (1ull << 20) + 16, 1ull << 24, 3ull << 24, 1ull << 28, 1ull << 30}; + const std::uint64_t space = 1ull << 32; // dense: ranges overlap often + unsigned queries = 0, hits = 0; + for (unsigned op = 0; op < operations; ++op) { + const unsigned kind = rng() % 10; + const int key = static_cast(rng() % 4000); + if (kind < 3) { // insert or move + const std::uint64_t width = widths[rng() % std::size(widths)] - (rng() % 2 ? rng() % 8 : 0); + const std::uint64_t base = (rng() % space) & ~(rng() % 2 ? std::uint64_t{0xfff} : std::uint64_t{0}); + index.insert(key, base, width); + ranges[key] = {base, width}; + } else if (kind < 4) { + const bool was = ranges.erase(key) != 0; + if (index.erase(key) != was) fail("erase result", static_cast(key), was); + } else { // query: inside a known range (start, interior, last byte), or anywhere + std::uint64_t address = rng() % space; + if (!ranges.empty() && rng() % 2) { + auto it = ranges.begin(); + std::advance(it, static_cast(rng() % ranges.size())); + const auto [base, width] = it->second; + const unsigned where = rng() % 3; + address = where == 0 ? base : where == 1 ? base + rng() % width : base + width - 1; + } + const std::uint64_t bytes = rng() % 3 == 0 ? 1 : 1 + rng() % 8192; + const auto got = query(index, address, bytes), want = walk(ranges, address, bytes); + ++queries; + hits += !want.empty(); + if (got != want) fail("random query differs from the walk", address, bytes); + } + } + if (index.size() != ranges.size()) fail("size", index.size(), ranges.size()); + std::printf("buffer_address_index%s: %u operations, %u queries (%u with a containing range), %zu ranges at the end, %d failures\n", + m == Index::Mutation::exact_start ? " --mutate" : "", operations, queries, hits, ranges.size(), failures); +} +} // namespace + +int main(int argc, char** argv) +{ + const auto m = argc == 2 && std::strcmp(argv[1], "--mutate") == 0 ? Index::Mutation::exact_start : Index::Mutation::none; + if (argc > 2 || (argc == 2 && m == Index::Mutation::none)) { + std::puts("usage: buffer_address_index_check [--mutate]"); + return 2; + } + explicit_cases(m); + random_cases(m, 200000); + return failures ? 1 : 0; +} diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 84ff8c3f52..30ec7e50cc 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -13,7 +13,7 @@ Microsoft::WRL::ComPtr resource(ID3D12Device* device, const D3D1 D3D12_HEAP_TYPE heap, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear = nullptr); void check_compute(ID3D12Device* device, bool tables); void check_sampler_views(ID3D12Device* device, const char* shader_path); -bool check_startup_sampler_x(ID3D12Device* device, bool swapped); +bool check_startup_sampler_x(ID3D12Device* device, bool swapped, int words = 0); int check_startup_cb_blend(ID3D12Device* device, bool swapped); int check_startup_export_write_mask(ID3D12Device* device, bool unmasked); int check_startup_composite_provenance(ID3D12Device* device); diff --git a/tests/gfx10_layout_check.cpp b/tests/gfx10_layout_check.cpp new file mode 100644 index 0000000000..3f5ffcf6bd --- /dev/null +++ b/tests/gfx10_layout_check.cpp @@ -0,0 +1,654 @@ + +// memory views) on synthetic shapes. +// +// Without addrlib (every build): +// gfx10_layout_check every element address of every golden shape hashes to the addrlib value +// recorded in , and the layout agrees with the repo's two +// independent tiled forms (Bc16Surface, bc64::Chain) where they overlap +// gfx10_layout_check --mutate floor|tail negative controls: a floor mip size or dropped tail +// coordinates must be detected (the test then fails) +// With addrlib (XBOX2WINDOWS_ADDRLIB_DIR, Mesa 25.1.0 src/amd/addrlib, MIT; see tools/fetch_addrlib.py): +// --addrlib every element address and surface size against Addr2ComputeSurfaceAddrFromCoord +// / Addr2ComputeSurfaceInfo on four configurations (Navi1x and Navi21, 1 and +// 16 pipes), the in-tree equation table against addrlib, and BC formats given +// as pixels (ADDR_FMT_BC*) against the same shape given as 4x4 blocks +// --print-equations the equation table (src/startup_stubs/gfx10_layout_equations.inc) +// --write-golden the golden file, hashed from addrlib's addresses (not from gfx10_layout.h) +// --write-tiled --addrlib the synthetic surface of the WARP detile draw, every element at addrlib's +// address (the same without --addrlib uses gfx10_layout.h: plumbing only) +#include "startup_stubs/gfx10_layout_local.h" +#include "startup_stubs/bc64_chain.h" +#include "startup_stubs/bc7_4k_s.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using x2w_startup::gfx10_local::Layout; + +namespace { +struct Shape { + const char* name; + unsigned mode; + bool is3d; + unsigned elem; // bytes per element + unsigned w, h, d, mips; // elements (4x4 blocks for BC), depth or array size + unsigned bc; // 0, or the BC number for the pixel-form addrlib check (pixel size = 4 * elements) + unsigned pw = 0, ph = 0; // BC: the pixel size when it is not 4 * elements (mip-0 blocks ceil(pixels / 4)) +}; + +const Shape shapes[] = { + {"r16_64x64x32_array", 5, false, 2, 64, 64, 32, 1, 0}, + {"r16_64x64x32_array_7mips", 5, false, 2, 64, 64, 32, 7, 0}, + {"bc1_12x44", 5, false, 8, 3, 11, 1, 1, 1}, + {"bc3_512x468", 5, false, 16, 128, 117, 1, 1, 3}, + {"bc1_2048_12mips", 5, false, 8, 512, 512, 1, 12, 1}, + {"bc3_256_9mips", 5, false, 16, 64, 64, 1, 9, 3}, + {"rgba16f_17cubed_3d", 5, true, 8, 17, 17, 17, 1, 0}, + {"rgba16f_17cubed_3d_5mips", 5, true, 8, 17, 17, 17, 5, 0}, + {"r32f_128x72_7mips_linear", 0, false, 4, 128, 72, 1, 7, 0}, + {"rgba8_300x200_9mips_4k_s", 5, false, 4, 300, 200, 1, 9, 0}, + {"rgba8_300x200_9mips_4k_d", 6, false, 4, 300, 200, 1, 9, 0}, + {"rgba8_300x200_9mips_64k_s", 9, false, 4, 300, 200, 1, 9, 0}, + {"rgba8_300x200_9mips_64k_d", 10, false, 4, 300, 200, 1, 9, 0}, + {"r8_1000x7_10mips_64k_s", 9, false, 1, 1000, 7, 1, 10, 0}, + {"r16_77x300_9mips_4k_s", 5, false, 2, 77, 300, 1, 9, 0}, + {"rg32_129x65_8mips_64k_d", 10, false, 8, 129, 65, 1, 8, 0}, + {"rgba8_64x64x6_7mips_64k_s", 9, false, 4, 64, 64, 6, 7, 0}, + {"r8_32cubed_3d_6mips_64k_s", 9, true, 1, 32, 32, 32, 6, 0}, + {"rgba32f_40x24x9_3d_6mips_4k_s", 5, true, 16, 40, 24, 9, 6, 0}, + {"bc7_1024_9mips_64k_s", 9, false, 16, 256, 256, 1, 9, 7}, + {"bc7_1024x512x2_9mips_64k_s", 9, false, 16, 256, 128, 2, 9, 7}, + {"bc5_4096_13mips_64k_s", 9, false, 16, 1024, 1024, 1, 13, 5}, + {"bc1_13x5_4mips_4k_s", 5, false, 8, 4, 2, 1, 3, 1}, + {"r32f_77x33_7mips_linear", 0, false, 4, 77, 33, 1, 7, 0}, + {"rgba8_5x3x4_linear_3d", 0, true, 4, 5, 3, 4, 1, 0}, + {"bc1_1024_11mips_64k_d", 10, false, 8, 256, 256, 1, 11, 1}, + {"bc7_2048x1024_12mips_64k_d", 10, false, 16, 512, 256, 1, 12, 7}, + {"bc7_300x200x3_7mips_4k_d", 6, false, 16, 75, 50, 3, 7, 7}, + {"bc1_44x12_4mips_4k_d", 6, false, 8, 11, 3, 1, 4, 1}, + // The WARP detile draw (tests/startup_memory_srv_detile_check.py; --write-tiled), with rgba16f_17cubed_3d_5mips. + {"bc1_256_9mips_4k_s", 5, false, 8, 64, 64, 1, 9, 1}, + {"bc1_256x128x2_8mips_64k_d", 10, false, 8, 64, 32, 2, 8, 1}, + {"bc3_256_9mips_4k_s", 5, false, 16, 64, 64, 1, 9, 3}, // a tiled_bc_srv description the tiled paths refuse (mips) + {"rgba16f_100x60_3mips_linear", 0, false, 8, 100, 60, 1, 3, 0}, + {"bc7_512x1056_8mips_4k_s", 5, false, 16, 128, 264, 1, 8, 7, 512, 1056}, + {"bc7_1000x600_10mips_64k_d", 10, false, 16, 250, 150, 1, 10, 7, 1000, 600}, + {"bc1_132_8mips_4k_s", 5, false, 8, 33, 33, 1, 8, 1, 132, 132}, + {"bc3_132x68x2_8mips_64k_d", 10, false, 16, 33, 17, 2, 8, 3, 132, 68}, +}; + +unsigned ceil_shift(unsigned v, unsigned s) { return (v + (1u << s) - 1) >> s; } + +struct Fnv { + std::uint64_t h = 1469598103934665603ull; + void add(std::uint64_t v) + { + for (int i = 0; i < 8; ++i) { + h ^= (v >> (8 * i)) & 0xff; + h *= 1099511628211ull; + } + } +}; + +// Every element of every level and slice, in a fixed order, with addrlib's (ceiling) level extents. +template void for_each_element(const Shape& s, Visit visit) +{ + for (unsigned mip = 0; mip < s.mips; ++mip) { + const unsigned w = ceil_shift(s.w, mip), h = ceil_shift(s.h, mip); + // A 3D mip holds max(1, depth >> mip) slices (D3D's floor; addrlib's Valid3DMipSliceIdConstraint refuses the + // rest), while width and height round up as the placement does. + const unsigned depth = s.is3d ? (std::max)(1u, s.d >> mip) : s.d; + for (unsigned z = 0; z < depth; ++z) + for (unsigned y = 0; y < h; ++y) + for (unsigned x = 0; x < w; ++x) visit(mip, x, y, z); + } +} + +Layout layout_of(const Shape& s, Layout::Mutation m = Layout::none) +{ + return Layout(s.mode, s.is3d, s.elem, s.w, s.h, s.d, s.mips, m); +} + +int failures; +void fail(const char* format, const char* a, std::uint64_t b = 0, std::uint64_t c = 0) +{ + if (failures++ < 12) { + std::printf("FAIL "); + std::printf(format, a, b, c); + std::printf("\n"); + } +} + +// The two existing, independently written tiled forms, where gfx10_layout.h covers the same surface. +void cross_check() +{ + // Bc16Surface: 16-byte 4 KiB standard, one level. + for (const auto [w, h] : {std::pair{512u, 468u}, std::pair{64u, 64u}, std::pair{100u, 36u}}) { + const x2w_startup::Bc16Surface bc(w, h); + const Layout l(5, false, 16, bc.columns, bc.rows, 1, 1); + for (unsigned y = 0; y < bc.rows; ++y) + for (unsigned x = 0; x < bc.columns; ++x) + if (l.address(0, x, y, 0) != bc.block_offset(x, y)) { + fail("Bc16Surface %s differs at %llu,%llu", "4KB_S", x, y); + return; + } + } + // bc64::Chain: 16-byte 64 KiB standard 1024-wide chains. + for (const auto [h, mips, slices] : {std::tuple{1024u, 6u, 1u}, std::tuple{1024u, 9u, 2u}, std::tuple{512u, 9u, 1u}}) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = 1024; + d.Height = h; + d.DepthOrArraySize = static_cast(slices); + d.MipLevels = static_cast(mips); + d.Format = DXGI_FORMAT_BC7_UNORM; + d.SampleDesc.Count = 1; + d.Layout = static_cast(0x109); + const x2w_startup::bc64::Chain chain(d); + const Layout l(9, false, 16, 256, h / 4, slices, mips); + if (l.size != chain.bytes()) fail("bc64::Chain size %s: %llu vs %llu", "64KB_S", l.size, chain.bytes()); + for (unsigned s = 0; s < slices; ++s) + for (unsigned mip = 0; mip < mips; ++mip) + for (unsigned y = 0; y < chain.rows(mip); ++y) + for (unsigned x = 0; x < chain.columns(mip); ++x) + if (l.address(mip, x, y, s) != chain.address(mip, x, y, s)) { + fail("bc64::Chain differs at mip/x %s %llu %llu", "64KB_S", mip, x); + return; + } + } +} + +int golden_check(const char* path, Layout::Mutation mutation) +{ + FILE* f = std::fopen(path, "r"); + if (!f) { + std::printf("FAIL cannot open %s\n", path); + return 1; + } + char line[512]; + unsigned checked = 0; + while (std::fgets(line, sizeof line, f)) { + if (line[0] == '#' || line[0] == '\n') continue; + char name[128]; + unsigned long long size = 0, hash = 0; + if (std::sscanf(line, "%127s %llu %llx", name, &size, &hash) != 3) continue; + const Shape* s = nullptr; + for (const auto& c : shapes) + if (std::strcmp(c.name, name) == 0) s = &c; + if (!s) { + fail("golden shape %s is not in the shape list", name); + continue; + } + const Layout l = layout_of(*s, mutation); + if (!l.valid) { + fail("%s: layout refused", name); + continue; + } + if (l.size != size) fail("%s: size %llu, golden %llu", name, l.size, size); + Fnv fnv; + for_each_element(*s, [&](unsigned mip, unsigned x, unsigned y, unsigned z) { fnv.add(l.address(mip, x, y, z)); }); + if (fnv.h != hash) fail("%s: address hash %llx, golden %llx", name, fnv.h, hash); + ++checked; + } + std::fclose(f); + if (checked != sizeof shapes / sizeof shapes[0]) fail("golden has %s%llu of %llu shapes", "", checked, sizeof shapes / sizeof shapes[0]); + if (mutation == Layout::none) cross_check(); + std::printf("gfx10_layout%s: %u golden shapes, %d failures\n", + mutation == Layout::floor_mips ? " --mutate floor" : mutation == Layout::no_tail_coords ? " --mutate tail" : "", + checked, failures); + return failures ? 1 : 0; +} + +const Shape* shape_named(const char* name) +{ + for (const auto& s : shapes) + if (std::strcmp(s.name, name) == 0) return &s; + return nullptr; +} + +std::uint16_t half_of(unsigned n) // an integer below 2048 as binary16 (exact) +{ + if (!n) return 0; + unsigned e = 0; + while ((2u << e) <= n) ++e; + return static_cast(((e + 15) << 10) | ((n << (10 - e)) & 0x3ff)); +} + +// The synthetic element pattern of the WARP detile draw; tests/startup_memory_srv_detile_check.py checks the same +// values in its pixel shader. BC1 shapes: a solid block (color0 = color1 = id, indices 0) with id = x | y << 6 | +// (mip + 8 * slice) << 12. BC3 shapes: the same color block after a solid alpha block (alpha0 = alpha1 = +// 16 * level + 5, indices 0). Other 8-byte shapes: R16G16B16A16_FLOAT (x, y, z, mip + 1). +bool pattern(const Shape& s, unsigned mip, unsigned x, unsigned y, unsigned z, unsigned char* out) +{ + if (s.bc == 3 && s.elem == 16) { + const unsigned level = mip + 8 * z; + if (x >= 64 || y >= 64 || level >= 16) return false; + const unsigned id = x | y << 6 | level << 12; + const auto alpha = static_cast(16 * level + 5); + const unsigned char block[16] = {alpha, alpha, 0, 0, 0, 0, 0, 0, static_cast(id), static_cast(id >> 8), + static_cast(id), static_cast(id >> 8), 0, 0, 0, 0}; + std::memcpy(out, block, 16); + return true; + } + if (s.elem != 8) return false; + if (s.bc == 1) { + const unsigned level = mip + 8 * z; + if (x >= 64 || y >= 64 || level >= 16) return false; + const unsigned id = x | y << 6 | level << 12; + const unsigned char block[8] = {static_cast(id), static_cast(id >> 8), + static_cast(id), static_cast(id >> 8), 0, 0, 0, 0}; + std::memcpy(out, block, 8); + return true; + } + if (s.bc || x >= 2048 || y >= 2048 || z >= 2048) return false; + const std::uint16_t h[4] = {half_of(x), half_of(y), half_of(z), half_of(mip + 1)}; + std::memcpy(out, h, 8); + return true; +} + +// The surface bytes of a shape with every element's pattern at the address `address` gives (addrlib's for the +// WARP oracle, gfx10_layout.h's for the plumbing variant); gaps stay zero. +template int write_tiled(const Shape& s, const char* path, std::uint64_t size, Address address) +{ + if (!size || size > (64ull << 20)) { + std::printf("FAIL %s: surface size %llu\n", s.name, static_cast(size)); + return 1; + } + std::vector bytes(static_cast(size)); + bool ok = true; + unsigned elements = 0; + for_each_element(s, [&](unsigned mip, unsigned x, unsigned y, unsigned z) { + std::uint64_t a = 0; + if (!ok || !address(mip, x, y, z, a) || a + s.elem > size || !pattern(s, mip, x, y, z, &bytes[static_cast(a)])) + ok = false; + ++elements; + }); + FILE* f = ok ? std::fopen(path, "wb") : nullptr; + if (!f || std::fwrite(bytes.data(), 1, bytes.size(), f) != bytes.size()) { + std::printf("FAIL %s: cannot write the tiled surface to %s\n", s.name, path); + if (f) std::fclose(f); + return 1; + } + std::fclose(f); + std::printf("wrote %s: %s, %u elements, %llu bytes\n", path, s.name, elements, static_cast(size)); + return 0; +} + +int write_tiled_layout(const char* name, const char* path) +{ + const Shape* s = shape_named(name); + if (!s) return 2; + const Layout l = layout_of(*s); + if (!l.valid) return 1; + return write_tiled(*s, path, l.size, [&](unsigned mip, unsigned x, unsigned y, unsigned z, std::uint64_t& a) { + a = l.address(mip, x, y, z); + return true; + }); +} +} // namespace + +#ifdef XBOX2WINDOWS_HAVE_ADDRLIB +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#include "addrinterface.h" + +namespace { +VOID* ADDR_API alloc_sys_mem(const ADDR_ALLOCSYSMEM_INPUT* in) { return std::malloc(in->sizeInBytes); } +ADDR_E_RETURNCODE ADDR_API free_sys_mem(const ADDR_FREESYSMEM_INPUT* in) +{ + std::free(in->pVirtAddr); + return ADDR_OK; +} + +struct Config { + const char* name; + UINT_32 revision, gb_addr_config; + bool rb_plus; // Navi21: addrlib's RB+ pattern tables +}; +// Family NV (0x8F). Navi10 (revision 0x03, no RB+ tables) and Navi21 (0x28, RB+ tables); GB_ADDR_CONFIG NUM_PIPES +// (bits 0-2, log2) 0 or 4 with NUM_PKRS (bits 8-10) 0 or 4 and the 0x40 of Mesa's navi21 test configuration. +const Config configs[] = { + {"navi10 1 pipe", 0x03, 0x40, false}, + {"navi10 16 pipes", 0x03, 0x40 | 4u | (4u << 8), false}, + {"navi21 1 pipe", 0x28, 0x40, true}, + {"navi21 16 pipes", 0x28, 0x40 | 4u | (4u << 8), true}, +}; + +ADDR_HANDLE create(const Config& c) +{ + ADDR_CREATE_INPUT in{}; + ADDR_CREATE_OUTPUT out{}; + in.size = sizeof in; + out.size = sizeof out; + in.chipEngine = 0x0000000D; // CIASICIDGFXENGINE_ARCTICISLAND + in.chipFamily = 0x8F; + in.chipRevision = c.revision; + in.callbacks.allocSysMem = alloc_sys_mem; + in.callbacks.freeSysMem = free_sys_mem; + in.regValue.gbAddrConfig = c.gb_addr_config; + return AddrCreate(&in, &out) == ADDR_OK ? out.hLib : nullptr; +} + +AddrFormat element_format(unsigned elem) +{ + switch (elem) { + case 1: return ADDR_FMT_8; + case 2: return ADDR_FMT_16; + case 4: return ADDR_FMT_32; + case 8: return ADDR_FMT_32_32; + default: return ADDR_FMT_32_32_32_32; + } +} +AddrFormat bc_format(unsigned bc) +{ + switch (bc) { + case 1: return ADDR_FMT_BC1; + case 3: return ADDR_FMT_BC3; + case 5: return ADDR_FMT_BC5; + default: return ADDR_FMT_BC7; + } +} + +ADDR_E_RETURNCODE info(ADDR_HANDLE lib, const Shape& s, ADDR2_COMPUTE_SURFACE_INFO_OUTPUT& out, ADDR2_MIP_INFO* mips, + bool pixels = false) +{ + ADDR2_COMPUTE_SURFACE_INFO_INPUT in{}; + in.size = sizeof in; + in.flags.texture = 1; + in.swizzleMode = static_cast(s.mode); + in.resourceType = s.is3d ? ADDR_RSRC_TEX_3D : ADDR_RSRC_TEX_2D; + in.format = pixels ? bc_format(s.bc) : element_format(s.elem); + in.bpp = pixels ? 0 : s.elem * 8; + in.width = pixels ? (s.pw ? s.pw : s.w * 4) : s.w; + in.height = pixels ? (s.ph ? s.ph : s.h * 4) : s.h; + in.numSlices = s.d; + in.numMipLevels = s.mips; + in.numSamples = 1; + in.numFrags = 1; + out = {}; + out.size = sizeof out; + out.pMipInfo = mips; + return Addr2ComputeSurfaceInfo(lib, &in, &out); +} + +bool addr(ADDR_HANDLE lib, const Shape& s, unsigned mip, unsigned x, unsigned y, unsigned z, std::uint64_t& address) +{ + ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT in{}; + ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT out{}; + in.size = sizeof in; + out.size = sizeof out; + in.x = x; + in.y = y; + in.slice = z; + in.mipId = mip; + in.unalignedWidth = s.w; + in.unalignedHeight = s.h; + in.numSlices = s.d; + in.numMipLevels = s.mips; + in.numSamples = 1; + in.numFrags = 1; + in.swizzleMode = static_cast(s.mode); + in.resourceType = s.is3d ? ADDR_RSRC_TEX_3D : ADDR_RSRC_TEX_2D; + in.bpp = s.elem * 8; + in.flags.texture = 1; + if (Addr2ComputeSurfaceAddrFromCoord(lib, &in, &out) != ADDR_OK || out.bitPosition != 0) return false; + address = out.addr; + return true; +} + +// The in-block equation of (thick, mode, element bytes), probed bit by bit on a one-block surface: in a non-XOR +// mode each coordinate bit moves exactly one address bit. +x2w_startup::gfx10_local::Equation probe(ADDR_HANDLE lib, bool thick, unsigned mode, unsigned e) +{ + x2w_startup::gfx10_local::Equation eq{}; + Shape s{"probe", mode, thick, 1u << e, 1, 1, 1, 1, 0}; + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT o{}; + if (info(lib, s, o, nullptr) != ADDR_OK) return eq; + s.w = o.blockWidth; + s.h = o.blockHeight; + s.d = thick ? o.blockSlices : 1; + const unsigned block_log2 = (mode == 5 || mode == 6) ? 12 : 16; + std::uint8_t src[16]; + std::memset(src, 0xff, sizeof src); + for (unsigned k = 0; k < e; ++k) src[k] = static_cast(0xc0 | k); + const auto place = [&](unsigned channel, unsigned extent, unsigned x, unsigned y, unsigned z, unsigned k) { + std::uint64_t a = 0; + if (!addr(lib, s, 0, x, y, z, a) || !a || (a & (a - 1)) || a >= (1ull << block_log2)) return false; + unsigned bit = 0; + while ((1ull << bit) != a) ++bit; + if (src[bit] != 0xff) return false; + src[bit] = static_cast(channel | k); + (void)extent; + return true; + }; + for (unsigned k = 0; (1u << k) < s.w; ++k) + if (!place(0x00, s.w, 1u << k, 0, 0, k)) return eq; + for (unsigned k = 0; (1u << k) < s.h; ++k) + if (!place(0x40, s.h, 0, 1u << k, 0, k)) return eq; + if (thick) + for (unsigned k = 0; (1u << k) < s.d; ++k) + if (!place(0x80, s.d, 0, 0, 1u << k, k)) return eq; + for (unsigned i = 0; i < block_log2; ++i) + if (src[i] == 0xff) return eq; + eq.bits = static_cast(block_log2); + std::memcpy(eq.src, src, sizeof src); + return eq; +} + +const unsigned table_modes[4] = {5, 6, 9, 10}; + +int print_equations() +{ + ADDR_HANDLE lib = create(configs[0]); + if (!lib) return 1; + std::printf("// GENERATED by tests/gfx10_layout_check.cpp --print-equations from AMD addrlib (Mesa 5c142e46f3f6e752ed745fd48912ebb8fad67145,\n" + "// mesa-25.1.0, src/amd/addrlib, MIT; see gfx10_layout.h): [thick][4KB_S 4KB_D 64KB_S 64KB_D][log2 bytes].\n"); + for (int thick = 0; thick < 2; ++thick) { + std::printf("{\n"); + for (unsigned mode : table_modes) { + std::printf(" {\n"); + for (unsigned e = 0; e < 5; ++e) { + const auto eq = probe(lib, thick != 0, mode, e); + std::printf(" {%u, {", eq.bits); + for (unsigned i = 0; i < 16; ++i) std::printf("%s0x%02x", i ? ", " : "", eq.bits ? eq.src[i] : 0); + std::printf("}},\n"); + } + std::printf(" },\n"); + } + std::printf("},\n"); + } + AddrDestroy(lib); + return 0; +} + +int write_golden(const char* path) +{ + ADDR_HANDLE lib = create(configs[0]); + FILE* f = lib ? std::fopen(path, "w") : nullptr; + if (!f) return 1; + std::fprintf(f, "# GENERATED by tests/gfx10_layout_check.cpp --write-golden from AMD addrlib (Mesa 5c142e46f3f6e752ed745fd48912ebb8fad67145,\n" + "# mesa-25.1.0, src/amd/addrlib, MIT), configuration %s: shape, surface bytes, FNV-1a 64 of every element\n" + "# address (level, slice or depth, row, column order, addrlib's level extents). Synthetic shapes only.\n", + configs[0].name); + for (const auto& s : shapes) { + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT o{}; + ADDR2_MIP_INFO mips[16]{}; + if (info(lib, s, o, mips) != ADDR_OK) { + std::printf("FAIL addrlib refuses %s\n", s.name); + return 1; + } + Fnv fnv; + bool ok = true; + for_each_element(s, [&](unsigned mip, unsigned x, unsigned y, unsigned z) { + std::uint64_t a = 0; + ok = ok && addr(lib, s, mip, x, y, z, a); + fnv.add(a); + }); + if (!ok) { + std::printf("FAIL addrlib address failed for %s\n", s.name); + return 1; + } + std::fprintf(f, "%s %llu %016llx\n", s.name, static_cast(o.surfSize), static_cast(fnv.h)); + } + std::fclose(f); + AddrDestroy(lib); + std::printf("wrote %s (%zu shapes)\n", path, sizeof shapes / sizeof shapes[0]); + return 0; +} + +int write_tiled_addrlib(const char* name, const char* path) +{ + const Shape* s = shape_named(name); + ADDR_HANDLE lib = s ? create(configs[0]) : nullptr; + if (!lib) return 2; + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT o{}; + ADDR2_MIP_INFO mips[16]{}; + int rc = 1; + if (info(lib, *s, o, mips) == ADDR_OK) + rc = write_tiled(*s, path, o.surfSize, [&](unsigned mip, unsigned x, unsigned y, unsigned z, std::uint64_t& a) { + return addr(lib, *s, mip, x, y, z, a); + }); + AddrDestroy(lib); + return rc; +} + +int debug_shape(const char* name) +{ + ADDR_HANDLE lib = create(configs[0]); + for (const auto& s : shapes) { + if (std::strcmp(s.name, name) != 0) continue; + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT o{}; + ADDR2_MIP_INFO mips[16]{}; + const auto rc = info(lib, s, o, mips); + const Layout l = layout_of(s); + std::printf("%s: addrlib rc %d size %llu slice %llu block %ux%ux%u first tail %u; layout size %llu slice %llu block %ux%ux%u\n", + s.name, rc, o.surfSize, o.sliceSize, o.blockWidth, o.blockHeight, o.blockSlices, o.firstMipIdInTail, l.size, + l.slice_size, l.bw, l.bh, l.bd); + for (unsigned m = 0; m < s.mips; ++m) { + std::uint64_t a = 0; + const bool ok = addr(lib, s, m, 0, 0, 0, a); + std::printf(" mip %u: addrlib pitch %u height %u depth %u offset %llu macro %llu tail %llu (%u,%u,%u) addr(0,0,0) %s%llu; " + "layout pitch %u height %u macro %llu tail %d (%u,%u) addr %llu\n", + m, mips[m].pitch, mips[m].height, mips[m].depth, mips[m].offset, mips[m].macroBlockOffset, static_cast(mips[m].mipTailOffset), + mips[m].mipTailCoordX, mips[m].mipTailCoordY, mips[m].mipTailCoordZ, ok ? "" : "FAILED ", a, l.level[m].pitch, + l.level[m].height, l.level[m].offset, l.level[m].in_tail, l.level[m].tail_x, l.level[m].tail_y, l.address(m, 0, 0, 0)); + } + } + AddrDestroy(lib); + return 0; +} + +// The D modes (4KB_D, 64KB_D) with 4-byte elements: addrlib's RB+ equation differs from the Navi1x one, so the +// in-tree table (Navi1x) is compared with Navi1x only, and on Navi21 the difference itself is asserted. The runtime +// does not detile D modes with 4-byte elements (d3d12_memory_srv.inl detile_layout). +bool chip_dependent(unsigned mode, unsigned elem) { return (mode == 6 || mode == 10) && elem == 4; } + +int addrlib_check() +{ + unsigned compared = 0, chip_dependent_seen = 0; + for (const auto& c : configs) { + ADDR_HANDLE lib = create(c); + if (!lib) { + fail("AddrCreate %s", c.name); + continue; + } + for (int thick = 0; thick < 2; ++thick) + for (unsigned mi = 0; mi < 4; ++mi) + for (unsigned e = 0; e < 5; ++e) { + const auto eq = probe(lib, thick != 0, table_modes[mi], e); + const auto& in_tree = x2w_startup::gfx10_local::equations[thick][mi][e]; + const bool differs = eq.bits != in_tree.bits || (eq.bits && std::memcmp(eq.src, in_tree.src, sizeof eq.src) != 0); + if (c.rb_plus && !thick && chip_dependent(table_modes[mi], 1u << e)) { + if (!differs) fail("%s: the D-mode equation e %llu was expected to differ on RB+", c.name, e); + ++chip_dependent_seen; + continue; + } + if (differs) + fail("%s: equation thick %llu mode index/e %llu differs from the in-tree table", c.name, thick, mi * 10 + e); + } + for (const auto& s : shapes) { + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT o{}; + ADDR2_MIP_INFO mips[16]{}; + if (info(lib, s, o, mips) != ADDR_OK) { + fail("addrlib (%s) refuses shape %llu", c.name, static_cast(&s - shapes)); + continue; + } + const Layout l = layout_of(s); + if (!l.valid) { + fail("%s: layout refuses it", s.name); + continue; + } + if (c.rb_plus && !s.is3d && chip_dependent(s.mode, s.elem)) continue; // Navi1x-only (see chip_dependent) + if (l.size != o.surfSize || l.slice_size != o.sliceSize) + fail("%s: size %llu vs addrlib %llu", s.name, l.size, o.surfSize); + bool reported = false; + for_each_element(s, [&](unsigned mip, unsigned x, unsigned y, unsigned z) { + std::uint64_t a = 0; + const bool ok = addr(lib, s, mip, x, y, z, a); + if (!ok || a != l.address(mip, x, y, z)) { + if (!reported) { + fail("%s: first address mismatch", s.name); + std::printf(" (%s) at mip %u x %u y %u z %u: addrlib %s%llu, layout %llu\n", c.name, mip, x, y, z, ok ? "" : "FAILED ", + static_cast(a), static_cast(l.address(mip, x, y, z))); + } + reported = true; + } + ++compared; + }); + if (s.bc) { + // The same shape given as BC pixels: identical sizes and level placement. + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT p{}; + ADDR2_MIP_INFO pm[16]{}; + if (info(lib, s, p, pm, true) != ADDR_OK) { + fail("addrlib (%s) refuses the BC pixel form of shape %llu", c.name, static_cast(&s - shapes)); + continue; + } + if (p.surfSize != o.surfSize || p.sliceSize != o.sliceSize) fail("%s: BC pixel form size %llu vs %llu", s.name, p.surfSize, o.surfSize); + for (unsigned m = 0; m < s.mips; ++m) + if (pm[m].offset != mips[m].offset || pm[m].macroBlockOffset != mips[m].macroBlockOffset || + pm[m].mipTailOffset != mips[m].mipTailOffset) + fail("%s: BC pixel form level %llu offset %llu differs", s.name, m, pm[m].offset); + } + } + AddrDestroy(lib); + } + std::printf("gfx10_layout --addrlib: %zu configurations, %zu shapes, %u element addresses compared, %u chip-dependent D-mode " + "equations confirmed different on RB+, %d failures\n", + sizeof configs / sizeof configs[0], sizeof shapes / sizeof shapes[0], compared, chip_dependent_seen, failures); + return failures ? 1 : 0; +} +} // namespace +#endif + +int main(int argc, char** argv) +{ + if (argc == 4 && std::strcmp(argv[1], "--write-tiled") == 0) return write_tiled_layout(argv[2], argv[3]); + if (argc >= 2 && std::strncmp(argv[1], "--", 2) == 0) { +#ifdef XBOX2WINDOWS_HAVE_ADDRLIB + if (argc == 5 && std::strcmp(argv[1], "--write-tiled") == 0 && std::strcmp(argv[4], "--addrlib") == 0) + return write_tiled_addrlib(argv[2], argv[3]); + if (std::strcmp(argv[1], "--addrlib") == 0) return addrlib_check(); + if (std::strcmp(argv[1], "--print-equations") == 0) return print_equations(); + if (std::strcmp(argv[1], "--write-golden") == 0 && argc == 3) return write_golden(argv[2]); + if (std::strcmp(argv[1], "--debug") == 0 && argc == 3) return debug_shape(argv[2]); + std::puts("usage: gfx10_layout_check [--mutate floor|tail] | --addrlib | --print-equations | --write-golden "); + return 2; +#else + std::puts("gfx10_layout: SKIP (built without addrlib; configure with -DXBOX2WINDOWS_ADDRLIB_DIR=/src/amd/addrlib)"); + return 77; +#endif + } + if (argc == 2) return golden_check(argv[1], Layout::none); + if (argc == 4 && std::strcmp(argv[2], "--mutate") == 0) + return golden_check(argv[1], std::strcmp(argv[3], "floor") == 0 ? Layout::floor_mips : Layout::no_tail_coords); + std::puts("usage: gfx10_layout_check [--mutate floor|tail] | --addrlib | --print-equations | --write-golden "); + return 2; +} diff --git a/tests/gfx10_layout_golden.txt b/tests/gfx10_layout_golden.txt new file mode 100644 index 0000000000..5a57b7faf6 --- /dev/null +++ b/tests/gfx10_layout_golden.txt @@ -0,0 +1,40 @@ +# GENERATED by tests/gfx10_layout_check.cpp --write-golden from AMD addrlib (Mesa 5c142e46f3f6e752ed745fd48912ebb8fad67145, +# mesa-25.1.0, src/amd/addrlib, MIT), configuration navi10 1 pipe: shape, surface bytes, FNV-1a 64 of every element +# address (level, slice or depth, row, column order, addrlib's level extents). Synthetic shapes only. +r16_64x64x32_array 262144 322424fe75dbef83 +r16_64x64x32_array_7mips 393216 6ce0a245c1c284d9 +bc1_12x44 4096 dbc347a0667eaaa7 +bc3_512x468 262144 16ef1352c0d7b283 +bc1_2048_12mips 2797568 867b7cc2d199d683 +bc3_256_9mips 90112 260e8160b1de2c74 +rgba16f_17cubed_3d 110592 43e0285162792dba +rgba16f_17cubed_3d_5mips 184320 7e95600211374e81 +r32f_128x72_7mips_linear 55552 958524d240edd663 +rgba8_300x200_9mips_4k_s 409600 39b182ea028ab720 +rgba8_300x200_9mips_4k_d 409600 39b182ea028ab720 +rgba8_300x200_9mips_64k_s 655360 45aeccbdf91a7f2c +rgba8_300x200_9mips_64k_d 655360 45aeccbdf91a7f2c +r8_1000x7_10mips_64k_s 524288 2f94bd6d219cea6d +r16_77x300_9mips_4k_s 126976 0bf355dd68c005a1 +rg32_129x65_8mips_64k_d 393216 e72b8efa0c1f8b56 +rgba8_64x64x6_7mips_64k_s 393216 a2ec140eb40e73ee +r8_32cubed_3d_6mips_64k_s 65536 e79b5cc07a360843 +rgba32f_40x24x9_3d_6mips_4k_s 376832 866e2f7e496c5388 +bc7_1024_9mips_64k_s 1441792 8a83925d27f45685 +bc7_1024x512x2_9mips_64k_s 1572864 15f301a6837bc1ef +bc5_4096_13mips_64k_s 22413312 d543ae5e9812860a +bc1_13x5_4mips_4k_s 4096 6b654a182752697c +r32f_77x33_7mips_linear 26368 1a35b3f65f020482 +rgba8_5x3x4_linear_3d 3072 71898ab306df7d03 +bc1_1024_11mips_64k_d 720896 403864daa4e00219 +bc7_2048x1024_12mips_64k_d 2883584 ecadf344d968835a +bc7_300x200x3_7mips_4k_d 368640 6287ed1ffb381865 +bc1_44x12_4mips_4k_d 4096 9def92b21b91b09a +bc1_256_9mips_4k_s 45056 1a9e971b8f78bd83 +bc1_256x128x2_8mips_64k_d 131072 af09b31a6ca7535f +bc3_256_9mips_4k_s 90112 260e8160b1de2c74 +rgba16f_100x60_3mips_linear 80640 ab16f83d4b2dc28a +bc7_512x1056_8mips_4k_s 770048 a1cacc58ccc68e04 +bc7_1000x600_10mips_64k_d 1179648 a44e6cc400a3e325 +bc1_132_8mips_4k_s 36864 737b019b60566d3c +bc3_132x68x2_8mips_64k_d 262144 eb2a1b819988722b diff --git a/tests/mesh_clip_distance_check.py b/tests/mesh_clip_distance_check.py new file mode 100644 index 0000000000..4fa20ee7ee --- /dev/null +++ b/tests/mesh_clip_distance_check.py @@ -0,0 +1,94 @@ +"""A mesh-stage pos1 export as SV_ClipDistance0, from the pipeline's PA_CL_VS_OUT_CNTL (req_.vsout).""" +import os +import struct +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import root_blob # noqa: E402 + + +def mesh(pos1_word0, pos1_word1): + return struct.pack('<14I', + 0x7e0202f2, # v_mov_b32 v1, 1.0 + 0x7e040280, # v_mov_b32 v2, 0 + 0xb07c1003, # s_movk_i32 m0, 0x1003 + 0xbf900009, # s_sendmsg 0x9 + 0xf80000cf, 0x01020201, # exp pos0 v1, v2, v2, v1 + pos1_word0, pos1_word1, # exp pos1 ... done + 0xf800020f, 0x01020201, # exp param0 v1, v2, v2, v1 + 0xf8000941, 0x00000002, # exp prim v2 done + 0xbf810000, 0xbf810000) # s_endpgm (twice: padding) + + +MS_XY = mesh(0xf80008d3, 0x00000201) # exp pos1 v1, v2, off, off done +MS_X = mesh(0xf80008d1, 0x00000001) # exp pos1 v1, off, off, off done +PS = struct.pack('<4I', 0x7e0002f2, # v_mov_b32 v0, 1.0 + 0xf800180f, 0x00000000, # exp mrt0 v0, v0, v0, v0 done vm + 0xbf810000) + + +def refused(code, cntl, why): + try: + M.MeshPipeline(code, PS, root_blob(), vs_out_cntl=cntl).hlsl_ms() + except G.Unsupported as error: + assert why in str(error), (why, str(error)) + else: + raise AssertionError('accepted PA_CL_VS_OUT_CNTL %r' % cntl) + + +def accepted(code, cntl, decl, write): + pipe = M.MeshPipeline(code, PS, root_blob(), vs_out_cntl=cntl) + ms, ps = pipe.hlsl_ms(), pipe.hlsl_ps() + assert ' %s clip0 : SV_ClipDistance0;' % decl in ms, ms + assert ' %s clip0 : SV_ClipDistance0;' % decl in ps, ps + assert 'if (exec & 1) { %s }' % write in ms, ms + # the pixel input struct and the mesh output struct list the same fields in the same order (linkage) + def fields(text, name): + body = text.split('struct %s {' % name, 1)[1].split('};', 1)[0] + return [l.strip() for l in body.strip().splitlines()] + out_fields = fields(ms, 'MSOut') + ps_struct = next(n for n in ('PSIn', 'VSOut', 'PSInput') if 'struct %s {' % n in ps) + assert out_fields == fields(ps, ps_struct), (out_fields, fields(ps, ps_struct)) + return pipe + + +def main(): + text = [x[3] for x in G.decode(MS_XY)] + assert text[3] == 's_sendmsg 0x9' and text[5] == 'exp pos1 v1, v2, off, off done', text + assert [x[3] for x in G.decode(MS_X)][5] == 'exp pos1 v1, off, off, off done' + refused(MS_XY, None, 'pos1 without PA_CL_VS_OUT_CNTL') # negative control: no register state + refused(MS_XY, 0x01400f0f, 'PA_CL_VS_OUT_CNTL') # four distances enabled, two written + refused(MS_XY, 0x01400300, 'PA_CL_VS_OUT_CNTL') # cull distances only + refused(MS_XY, 0x01400303 | 1 << 21, 'PA_CL_VS_OUT_CNTL') # misc vector first: pos1 is not distances + refused(MS_XY, 0x01400303 | 1 << 23, 'PA_CL_VS_OUT_CNTL') # a second distance vector + accepted(MS_X, 0x01400101, 'float', 'o.clip0 = F(v1);') + accepted(MS_XY, 0x01400303, 'float2', 'o.clip0 = float2(F(v1), F(v2));') + compiled = 'dxc not found' + if os.path.isfile(M.DXC): + with tempfile.TemporaryDirectory() as d: + for key, (code, cntl) in enumerate(((MS_X, 0x01400101), (MS_XY, 0x01400303))): + r = M.translate_to(d, key, code, PS, root_blob(), vs_out_cntl=cntl) + assert r == 'ok', r + r = M.translate_to(d, 9, MS_XY, PS, root_blob()) + assert r.startswith('unsupported:') and 'pos1' in r, r + # a request: req_.{a,b,root} and the optional .vsout beside it + base = os.path.join(d, 'req_%016x' % 5) + for ext, data in (('.a', PS), ('.b', MS_XY), ('.root', root_blob())): + open(base + ext, 'wb').write(data) + r = M.translate_request(d, 5) + assert r.startswith('unsupported:') and 'pos1' in r, r + open(base + '.vsout', 'w', newline='\n').write('pa_cl_vs_out_cntl 1 01400303\n') + r = M.translate_request(d, 5) + assert r == 'ok', r + assert 'SV_ClipDistance0' in open(os.path.join(d, '%016x.ms.hlsl' % 5)).read() + compiled = 'dxc ms_6_5 + ps_6_0 ok' + print('mesh clip distance: pos1 refused without PA_CL_VS_OUT_CNTL; 0x01400101 -> float, 0x01400303 -> float2 ' + 'SV_ClipDistance0 in both stage structs; 4 bad states refused; %s' % compiled) + + +if __name__ == '__main__': + main() diff --git a/tests/mesh_loop_state_check.py b/tests/mesh_loop_state_check.py new file mode 100644 index 0000000000..41345b4945 --- /dev/null +++ b/tests/mesh_loop_state_check.py @@ -0,0 +1,168 @@ +"""Loop-carried scalar state in the mesh-stage translator (mesh2hlsl MeshStage.loop_one / MeshPipeline.mesh_stage). + +Hand-assembled NGG mesh programs (no cache bytes), each a uniform scalar loop (s_cbranch_scc1 back edge, RDNA 2 ISA: +SCC from s_cmp_lt_u32, the branch taken when SCC = 1): + + counter: s0 = 0; L: s0 += 1; s_cmp_lt_u32 s0, 3; s_cbranch_scc1 L; v1 = float(s0); exp pos0 v1, ... + midentry: s2 = 0; s1 = 5; s_branch E; H: s1 = s4; E: s4 = s1 + 1; s2 += 1; s_cmp_lt_u32 s2, 3; s_cbranch_scc1 H; + v1 = float(s4) (H is reached only by the back edge: the loop is entered in its body) + +The console computes s0 = 3 and s4 = 8. A translation that keeps, at the loop head, the state of the instruction +above it folds the constant before the loop into the body (`s0 = 0x00000000u + 0x00000001u`: the HLSL loop never +ends and stops at its guard). Checks: the loop counters are read as variables in the loop body, and the program +exports the right value when the emitted body is evaluated by a small interpreter for the statement forms it +uses. + + taint: v1 = 0; s0 = 0; H: v_cmp_lt_u32 vcc, 0, v1; s_cbranch_vccz +1; s_nop; v1 = v5; s0 += 1; s_cmp_lt_u32 s0, 3; + s_cbranch_scc1 H (v1 is uniform on the entry edge and the vertex id on the back edge) + +The vccz branch reads a vcc that differs between lanes from the second pass on: the translation must refuse it +("lane-dependent vcc"), which it does only when the head's lane taint joins the back edge. (Since e1a2ad2a, the +base's loop-head rule alone keeps counter / midentry right; taint is what still needs the join.) +Negative control: with X2W_MESH_LOOP_JOIN=0 (the old linear state) the same checks FAIL (run in a child). +""" +import os +import re +import struct +import subprocess +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import root_blob # noqa: E402 + +TAIL = (0x7e020c00, # v_cvt_f32_u32 v1, s + 0x7e040280, # v_mov_b32 v2, 0 + 0xb07c1003, # s_movk_i32 m0, 0x1003 + 0xbf900009, # s_sendmsg 0x9 + 0xf80008cf, 0x02020201, # exp pos0 v1, v2, v2, v2 done + 0xf8000941, 0x00000002, # exp prim v2 done + 0xbf810000) # s_endpgm + + +def program(words, src): + tail = list(TAIL) + tail[0] = 0x7e020c00 | src + return struct.pack('<%dI' % (len(words) + len(tail)), *(list(words) + tail)) + + +COUNTER = program([0xbe800380, # 0x00 s_mov_b32 s0, 0 + 0x80008100, # 0x04 s_add_u32 s0, s0, 1 + 0xbf0a8300, # 0x08 s_cmp_lt_u32 s0, 3 + 0xbf85fffd], # 0x0c s_cbranch_scc1 0x04 + 0) +MIDENTRY = program([0xbe820380, # 0x00 s_mov_b32 s2, 0 + 0xbe810385, # 0x04 s_mov_b32 s1, 5 + 0xbf820001, # 0x08 s_branch 0x10 + 0xbe810304, # 0x0c s_mov_b32 s1, s4 + 0x80048101, # 0x10 s_add_u32 s4, s1, 1 + 0x80028102, # 0x14 s_add_u32 s2, s2, 1 + 0xbf0a8302, # 0x18 s_cmp_lt_u32 s2, 3 + 0xbf85fffb], # 0x1c s_cbranch_scc1 0x0c + 4) +TAINT = program([0x7e020280, # 0x00 v_mov_b32 v1, 0 + 0xbe800380, # 0x04 s_mov_b32 s0, 0 + 0x7d820280, # 0x08 v_cmp_lt_u32 vcc, 0, v1 + 0xbf860001, # 0x0c s_cbranch_vccz 0x14 + 0xbf800000, # 0x10 s_nop 0 + 0x7e020305, # 0x14 v_mov_b32 v1, v5 + 0x80008100, # 0x18 s_add_u32 s0, s0, 1 + 0xbf0a8300, # 0x1c s_cmp_lt_u32 s0, 3 + 0xbf85fff9], # 0x20 s_cbranch_scc1 0x08 + 0) +TEXT = { + 'counter': ['s_mov_b32 s0, 0', 's_add_u32 s0, s0, 1', 's_cmp_lt_u32 s0, 3', 's_cbranch_scc1 label_0x4'], + 'midentry': ['s_mov_b32 s2, 0', 's_mov_b32 s1, 5', 's_branch label_0x10', 's_mov_b32 s1, s4', + 's_add_u32 s4, s1, 1', 's_add_u32 s2, s2, 1', 's_cmp_lt_u32 s2, 3', 's_cbranch_scc1 label_0xc'], + 'taint': ['v_mov_b32_e32 v1, 0', 's_mov_b32 s0, 0', 'v_cmp_lt_u32_e32 vcc_lo, 0, v1', 's_cbranch_vccz label_0x14', + 's_nop 0', 'v_mov_b32_e32 v1, v5', 's_add_u32 s0, s0, 1', 's_cmp_lt_u32 s0, 3', 's_cbranch_scc1 label_0x8'], +} + + +def run_body(hlsl): + """Evaluates the scalar statements of the emitted pc loop (uint assignments, scc compares, pc dispatch) for + one thread and returns the exported position x. Only the forms these programs produce are understood.""" + lines = [l.strip() for l in hlsl.split('uint pc = 0;', 1)[1].splitlines()] + blocks, cur = {}, None + for l in lines: + if l.startswith('GroupMemoryBarrierWithGroupSync'): + break + m = re.match(r'(?:else )?if \(pc == (\d+)\) \{$', l) + if m: + cur = int(m.group(1)) + blocks[cur] = [] + elif l.startswith('[loop] for ('): # a bounded pc loop around a loop's blocks (the dispatch below repeats) + continue + elif cur is not None and l != '}': + blocks[cur].append(l) + env = {'pc': 0, 'scc': 0, 'exec': 1} + + def ev(expr): + e = re.sub(r'0x([0-9a-f]+)u', lambda mm: str(int(mm.group(1), 16)), expr) + e = re.sub(r'\b(\d+)u\b', r'\1', e) + e = e.replace('U(float(', '(float(').replace('F(', '(') + e = re.sub(r'\((scc)\) \? (\d+) : (\d+)', r'(\2 if \1 else \3)', e) + e = e.replace('&&', ' and ').replace('||', ' or ') + return eval(e, {'float': float}, env) + for _ in range(1000): + pc = env['pc'] + if pc >= 0xffff or pc not in blocks: + break + for stmt in blocks[pc]: + for part in [p.strip() for p in stmt.split(';') if p.strip()]: + m = re.match(r'if \(exec & 1\) \{ o\.pos = float4\((.*?), .*$', part) + if m: + env['posx'] = ev(m.group(1)) + continue + if part.startswith(('if (exec & 1) { x2w_prim', 'if (exec & 1) x2w_alloc', '}')): + continue + m = re.match(r'(\w+) = (.*)$', part) + assert m, 'statement form %r' % part + value = ev(m.group(2)) + env[m.group(1)] = (int(value) & 0xffffffff) if isinstance(value, (int, bool)) else value + else: + raise AssertionError('the translated loop does not end') + return env.get('posx') + + +def check(): + # A loop entered from its middle. The forward jump skips an alignment + # NOP before the head; its only real predecessor is the back edge. + padded = MIDENTRY[:8] + struct.pack(' 3.0, mid-body entry -> 8.0, back-edge taint refused' + + +def main(): + if os.environ.get('X2W_MESH_LOOP_JOIN') == '0': # child of the negative control + check() + return + summary = check() + env = dict(os.environ, X2W_MESH_LOOP_JOIN='0') + r = subprocess.run([sys.executable, '-B', os.path.abspath(__file__)], env=env, capture_output=True, text=True) + assert r.returncode != 0 and 'AssertionError' in r.stderr, ('negative control passed', r.stdout, r.stderr) + print('mesh loop state: %s; X2W_MESH_LOOP_JOIN=0 fails (%s)' % (summary, r.stderr.strip().splitlines()[-1][:80])) + + +if __name__ == '__main__': + main() diff --git a/tests/mesh_pc_table_check.py b/tests/mesh_pc_table_check.py new file mode 100644 index 0000000000..6bbebd87e0 --- /dev/null +++ b/tests/mesh_pc_table_check.py @@ -0,0 +1,41 @@ +"""A source-built mesh reads an embedded four-word position table through GETPC.""" +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import mesh2hlsl as M +from mesh_loop_state_check import TAIL, root_blob + + +def stage(declared_bytes, contents): + # Assemble the low/high address in s[8:9], the byte size in s10, and the + # raw byte-addressed buffer control word in s11. v5 selects the byte offset. + words = [0xbe881f00, # s_getpc_b64 s[8:9] + 0x8008ff08, 0, # s_add_u32 s8, s8, pool - 4 + 0xb00a0000 | declared_bytes, # s_movk_i32 s10, declared_bytes + 0xbe8b03ff, 0x31016fac, # s_mov_b32 s11, raw buffer control + 0xe0301000, 0x80020105, # buffer_load_dword v1, v5, s[8:11], 0 offen + *TAIL[1:]] + words[2] = 4 * len(words) - 4 + words.extend(contents) + return M.MeshPipeline(struct.pack('<%dI' % len(words), *words), None, root_blob()) + + +if __name__ == '__main__': + contents = (0x3f800000, 0x40000000, 0x40400000, 0x40800000) + pipe = stage(16, contents) + hlsl = pipe.hlsl_ms() + (offset, size), = pipe.vs.literal_tables + name = pipe.vs.literal_tables[(offset, size)] + assert size == 16 + assert '%s[4] = {0x3f800000u, 0x40000000u, 0x40400000u, 0x40800000u}' % name in hlsl + assert 'a = v5 >> 2u;' in hlsl + assert '(a < 4u ? %s[min(a, 3u) + 0u] : 0u)' % name in hlsl + try: + stage(20, contents) + except M.Unsupported as e: + assert 'incomplete PC-relative raw buffer' in str(e), e + else: + raise AssertionError('accepted a literal table beyond the supplied program') + print('Embedded four-word position table translated; truncated table refused') diff --git a/tests/mesh_perlane_loop_check.py b/tests/mesh_perlane_loop_check.py new file mode 100644 index 0000000000..e49e9b51a9 --- /dev/null +++ b/tests/mesh_perlane_loop_check.py @@ -0,0 +1,109 @@ +"""Per-lane loops in the mesh-stage translator (mesh2hlsl MeshStage.perlane_loop). + +The compiler keeps the lanes that still loop in a mask M and loops while some lane does (SCC = M != 0): + + v_and_b32 v6, 3, v5 (each lane's own trip count - 1) + v_mov_b32 v1, 0 + s_mov_b64 s[6:7], exec; s_mov_b64 s[8:9], exec; s_mov_b32 s4, 0 + H: s_mov_b64 exec, s[8:9] (the lanes still looping) + v_add_f32 v1, 1.0, v1 + v_cmp_eq_u32 vcc, s4, v6 (this lane is done after this iteration) + s_add_u32 s4, s4, 1 + s_and_b64 exec, vcc, exec (exec = the lanes that are done) + s_andn2_b64 s[8:9], s[8:9], exec (they leave M; SCC = some lane remains) + s_cbranch_scc1 H + s_mov_b64 exec, s[6:7] + exp pos0 v1, ... + +On the console each lane runs (v5 & 3) + 1 iterations of its vector instructions (the wave runs the most), so it +exports float((v5 & 3) + 1). Hand-assembled programs (no cache bytes); RDNA 2 ISA encodings. Checks: + full every lane on: lanes 0..7 and 127 export float((v5 & 3) + 1) + partial exec narrowed first (v_cmpx_ne_u32 0, v5 & 3): those lanes the same, the others nothing + refused s4 read after the loop (the hardware leaves the wave's last count, a thread its own), an s_barrier + in the loop, no exec restore after it, an SCC not from `s_andn2_b64 M, M, exec` (s_xor) +and dxc ms_6_5 + ps_6_0 compile the full program. The emitted code is evaluated per lane (mesh_waterfall_check's +interpreter). Negative control: with X2W_MESH_PERLANE_LOOPS=0 the same checks FAIL (run in a child): the loop +is refused as before. +""" +import os +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import root_blob # noqa: E402 +from mesh_waterfall_check import run_lane, TAIL, PS, NARROW, words, refused # noqa: E402 + +PRE = [0x360c0a83, # v_and_b32 v6, 3, v5 + 0x7e020280, # v_mov_b32 v1, 0 + 0xbe86047e, # s_mov_b64 s[6:7], exec + 0xbe88047e, # s_mov_b64 s[8:9], exec + 0xbe840380] # s_mov_b32 s4, 0 +BODY = [0xbefe0408, # H: s_mov_b64 exec, s[8:9] + 0x060202f2, # v_add_f32 v1, 1.0, v1 + 0x7d840c04, # v_cmp_eq_u32 vcc, s4, v6 + 0x80048104, # s_add_u32 s4, s4, 1 + 0x87fe7e6a] # s_and_b64 exec, vcc, exec +EXIT = 0x8a887e08 # s_andn2_b64 s[8:9], s[8:9], exec +BACK = 0xbf85fff9 # s_cbranch_scc1 H +RESTORE = 0xbefe0406 # s_mov_b64 exec, s[6:7] + +FULL = words(PRE, BODY, [EXIT, BACK, RESTORE], TAIL) +PARTIAL = words(NARROW, PRE, BODY, [EXIT, BACK, RESTORE], TAIL) +LIVE_AFTER = words(PRE, BODY, [EXIT, BACK, RESTORE, 0x7e020c04], TAIL) # v_cvt_f32_u32 v1, s4 after it +BARRIER = words(PRE, BODY[:1], [0xbf8a0000], BODY[1:], [EXIT, 0xbf85fff8, RESTORE], TAIL) +NO_RESTORE = words(PRE, BODY, [EXIT, BACK, 0xbf800000], TAIL) # s_nop 0 in place of the restore +XOR = words(PRE, BODY, [0x89887e08, BACK, RESTORE], TAIL) # s_xor_b64 s[8:9], s[8:9], exec +TEXT = ['v_and_b32_e32 v6, 3, v5', 'v_mov_b32_e32 v1, 0', 's_mov_b64 s[6:7], exec', 's_mov_b64 s[8:9], exec', + 's_mov_b32 s4, 0', 's_mov_b64 exec, s[8:9]', 'v_add_f32_e32 v1, 1.0, v1', 'v_cmp_eq_u32_e32 vcc_lo, s4, v6', + 's_add_u32 s4, s4, 1', 's_and_b64 exec, vcc, exec', 's_andn2_b64 s[8:9], s[8:9], exec', + 's_cbranch_scc1 label_0x14', 's_mov_b64 exec, s[6:7]'] + + +def hlsl_of(code): + return M.MeshPipeline(code, None, root_blob()).hlsl_ms() + + +def check(): + assert [x[3] for x in G.decode(FULL)][:len(TEXT)] == TEXT, [x[3] for x in G.decode(FULL)] + full = hlsl_of(FULL) + for v5 in list(range(8)) + [127]: + got = run_lane(full, v5) + assert got == float((v5 & 3) + 1), ('full', v5, got) + partial = hlsl_of(PARTIAL) + for v5 in list(range(8)) + [64, 127]: + got = run_lane(partial, v5) + want = None if v5 % 4 == 0 else float((v5 & 3) + 1) + assert got == want, ('partial', v5, got, want) + refused(LIVE_AFTER, 's4 written in it is live after it') + refused(BARRIER, 's_barrier') + refused(NO_RESTORE, 'no s_mov_b64 exec restore') + refused(XOR, 'SCC not from the remaining-lanes mask') + compiled = 'dxc not found' + if os.path.isfile(M.DXC): + with tempfile.TemporaryDirectory() as d: + r = M.translate_to(d, 1, FULL, PS, root_blob()) + assert r == 'ok', r + compiled = 'dxc ms_6_5 + ps_6_0 ok' + return compiled + + +def main(): + if os.environ.get('X2W_MESH_PERLANE_LOOPS') == '0': # child of the negative control + check() + return + compiled = check() + env = dict(os.environ, X2W_MESH_PERLANE_LOOPS='0') + r = subprocess.run([sys.executable, '-B', os.path.abspath(__file__)], env=env, capture_output=True, text=True) + assert r.returncode != 0 and 'Unsupported' in r.stderr, ('negative control passed', r.stdout, r.stderr) + print('mesh per-lane loop: lanes 0..7/127 (full) and v5 %% 4 != 0 (partial) export float((v5 & 3) + 1); ' + 'live-after, barrier, no-restore and xor refused; %s; X2W_MESH_PERLANE_LOOPS=0 fails (%s)' + % (compiled, r.stderr.strip().splitlines()[-1][:90])) + + +if __name__ == '__main__': + main() diff --git a/tests/mesh_waterfall_check.py b/tests/mesh_waterfall_check.py new file mode 100644 index 0000000000..0d825dd59c --- /dev/null +++ b/tests/mesh_waterfall_check.py @@ -0,0 +1,177 @@ +"""Waterfall loops in the mesh-stage translator (mesh2hlsl MeshStage.waterfalls / waterfall_step). + +The compiler's loop for a value that must be uniform but differs between lanes (LLVM AMDGPU +SIInstrInfo emitLoadScalarOpsFromVGPRLoop): + + s_mov_b64 s[6:7], exec; s_mov_b64 s[8:9], exec + H: v_readfirstlane_b32 s4, v5 (the first remaining lane's value) + v_cmpx_eq_u32 s4, v5 (exec = the remaining lanes holding it) + v_cvt_f32_u32 v1, s4 (the body: uses s4 as a uniform value) + s_andn2_wrexec_b64 s[8:9], s[8:9] (the lanes done leave; SCC = some lane remains) + s_cbranch_scc1 H + s_mov_b64 exec, s[6:7] + exp pos0 v1, ... + +On the console each lane active at H makes exactly one pass, with s4 = its own v5 (v5 = the vertex id, different in +every lane), so it exports float(v5). Hand-assembled programs (no cache bytes); RDNA 2 ISA encodings. Checks: + full every lane on: lanes 0, 1, 37, 127 export float(v5) + partial exec narrowed first (v_cmpx_ne_u32 0, v5 & 3): lanes with v5 % 4 != 0 export float(v5), the + others nothing (every wave keeps active lanes: s_sendmsg is guarded by exec here) + refused s4 read after the loop (the hardware leaves the last pass's value), no exec restore after the loop, + an s_barrier in the body +and dxc ms_6_5 + ps_6_0 compile the full program. The emitted body is evaluated per lane by a small interpreter +for the statement forms it uses. Negative control: with X2W_MESH_WATERFALL=0 the same checks FAIL (run in a +child): the loops are refused as before (here at the lane-mask SCC publish inside the loop). +""" +import os +import re +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import root_blob # noqa: E402 + +NARROW = [0x360c0a83, # v_and_b32 v6, 3, v5 + 0x7daa0c80] # v_cmpx_ne_u32_e32 0, v6 (every fourth lane off, in every wave) +LOOP = [0xbe86047e, # s_mov_b64 s[6:7], exec + 0xbe88047e, # s_mov_b64 s[8:9], exec + 0x7e080505, # H: v_readfirstlane_b32 s4, v5 + 0x7da40a04, # v_cmpx_eq_u32_e32 s4, v5 + 0x7e020c04, # v_cvt_f32_u32_e32 v1, s4 + 0xbe883a08, # s_andn2_wrexec_b64 s[8:9], s[8:9] + 0xbf85fffb, # s_cbranch_scc1 H + 0xbefe0406] # s_mov_b64 exec, s[6:7] +TAIL = [0x7e040280, # v_mov_b32 v2, 0 + 0xb07c1003, # s_movk_i32 m0, 0x1003 + 0xbf900009, # s_sendmsg 0x9 + 0xf80008cf, 0x02020201, # exp pos0 v1, v2, v2, v2 done + 0xf8000941, 0x00000002, # exp prim v2 done + 0xbf810000] # s_endpgm +PS = struct.pack('<4I', 0x7e0002f2, 0xf800180f, 0x00000000, 0xbf810000) # v_mov v0, 1.0; exp mrt0; s_endpgm + + +def words(*parts): + w = [x for p in parts for x in p] + return struct.pack('<%dI' % len(w), *w) + + +FULL = words(LOOP, TAIL) +PARTIAL = words(NARROW, LOOP, TAIL) +LIVE_AFTER = words(LOOP, [0x7e020c04], TAIL) # v_cvt_f32_u32 v1, s4 after the restore +NO_RESTORE = words(LOOP[:-1], [0xbf800000], TAIL) # s_nop 0 in place of the restore +BARRIER = words(LOOP[:4], [0xbf8a0000], LOOP[4:6], [0xbf85fffa], LOOP[7:], TAIL) # s_barrier in the body +TEXT = ['s_mov_b64 s[6:7], exec', 's_mov_b64 s[8:9], exec', 'v_readfirstlane_b32 s4, v5', + 'v_cmpx_eq_u32_e32 s4, v5', 'v_cvt_f32_u32_e32 v1, s4', 's_andn2_wrexec_b64 s[8:9], s[8:9]', + 's_cbranch_scc1 label_0x8', 's_mov_b64 exec, s[6:7]'] + + +def run_lane(hlsl, v5): + """Evaluates the emitted pc loop for one thread whose v5 (vertex id) is v5; returns the exported position x, + or None when the thread exports nothing. Only the statement forms these programs produce are understood.""" + lines = [l.strip() for l in hlsl.split('uint pc = 0;', 1)[1].splitlines()] + blocks, cur = {}, None + for l in lines: + if l.startswith('GroupMemoryBarrierWithGroupSync'): + break + m = re.match(r'(?:else )?if \(pc == (\d+)\) \{$', l) + if m: + cur = int(m.group(1)) + blocks[cur] = [] + elif l.startswith('[loop] for ('): # a bounded pc loop around a loop's blocks (the dispatch below repeats) + continue + elif cur is not None and l != '}': + blocks[cur].append(l) + env = {'pc': 0, 'scc': 0, 'exec': 1, 'v5': v5} + + def ev(expr): + e = re.sub(r'0x([0-9a-f]+)u', lambda mm: str(int(mm.group(1), 16)), expr) + e = re.sub(r'\b(\d+)u\b', r'\1', e) + e = re.sub(r'\b[UF]\(', '(', e) + e = re.sub(r'\(\((.*?)\) \? (\d+) : (\d+)\)', r'(\2 if (\1) else \3)', e) + e = re.sub(r'^\((\w+)\) \? (\d+) : (\d+)$', r'(\2 if \1 else \3)', e) + e = re.sub(r'~(\w+)', r'(~\1 & 0xffffffff)', e) + e = e.replace('&&', ' and ').replace('||', ' or ').replace('false', '0').replace('true', '1') + return eval(e, {'float': float}, env) + posx = None + for _ in range(100): + pc = env['pc'] + if pc >= 0xffff or pc not in blocks: + break + for stmt in blocks[pc]: + guarded = stmt.startswith('if (exec & 1) ') + body = stmt[len('if (exec & 1) '):] if guarded else stmt + if guarded and not (env['exec'] & 1): + continue + body = body.strip('{} ') + for part in [p.strip() for p in body.split(';') if p.strip()]: + m = re.match(r'o\.pos = float4\((.*?), .*$', part) + if m: + posx = ev(m.group(1)) + continue + if part.startswith(('x2w_prim', 'x2w_alloc')): + continue + m = re.match(r'(\w+) = (.*)$', part) + assert m, 'statement form %r' % part + value = ev(m.group(2)) + env[m.group(1)] = (int(value) & 0xffffffff) if isinstance(value, (int, bool)) else value + else: + raise AssertionError('the translated program does not end') + return posx + + +def hlsl_of(code): + return M.MeshPipeline(code, None, root_blob()).hlsl_ms() + + +def refused(code, why): + try: + hlsl_of(code) + except G.Unsupported as e: + assert why in str(e), (why, str(e)) + return + raise AssertionError('not refused: %s' % why) + + +def check(): + assert [x[3] for x in G.decode(FULL)][:len(TEXT)] == TEXT, [x[3] for x in G.decode(FULL)] + full = hlsl_of(FULL) + for v5 in (0, 1, 37, 127): + got = run_lane(full, v5) + assert got == float(v5), ('full', v5, got) + partial = hlsl_of(PARTIAL) + for v5 in (0, 1, 2, 3, 4, 64, 65, 127): + got = run_lane(partial, v5) + want = None if v5 % 4 == 0 else float(v5) + assert got == want, ('partial', v5, got, want) + refused(LIVE_AFTER, 's4 written in it is live after it') + refused(NO_RESTORE, 'no s_mov_b64 exec restore') + refused(BARRIER, 's_barrier') + compiled = 'dxc not found' + if os.path.isfile(M.DXC): + with tempfile.TemporaryDirectory() as d: + r = M.translate_to(d, 1, FULL, PS, root_blob()) + assert r == 'ok', r + compiled = 'dxc ms_6_5 + ps_6_0 ok' + return compiled + + +def main(): + if os.environ.get('X2W_MESH_WATERFALL') == '0': # child of the negative control + check() + return + compiled = check() + env = dict(os.environ, X2W_MESH_WATERFALL='0') + r = subprocess.run([sys.executable, '-B', os.path.abspath(__file__)], env=env, capture_output=True, text=True) + assert r.returncode != 0 and 'Unsupported' in r.stderr, ('negative control passed', r.stdout, r.stderr) + print('mesh waterfall: one pass per lane, full exec lanes 0/1/37/127 and partial exec lanes v5 %% 4 != 0 export ' + 'float(v5); live-after, no-restore and barrier refused; %s; X2W_MESH_WATERFALL=0 fails (%s)' + % (compiled, r.stderr.strip().splitlines()[-1][:90])) + + +if __name__ == '__main__': + main() diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index d3973cdd18..b525bc7e73 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1242,10 +1242,10 @@ OperationResult run_startup_range_provenance(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } -template +template OperationResult run_startup_sampler_x(const OperationContext& ctx) { - return skip_if_false(check_startup_sampler_x(ctx.device, Swapped), + return skip_if_false(check_startup_sampler_x(ctx.device, Swapped, Words), "skip: R32_FLOAT does not report filtered sampling with mips"); } @@ -1752,6 +1752,8 @@ const OperationSpec kOperations[] = { {"--descriptor-heap-paging-swapped", 3, 3, nullptr, kGateSm60BufferOps, run_descriptor_heap_paging}, {"--startup-sampler-x", 3, 3, nullptr, kGateSm60BufferOps, run_startup_sampler_x}, {"--startup-sampler-x-swapped", 3, 3, nullptr, kGateSm60BufferOps, run_startup_sampler_x}, + {"--startup-sampler-x-words", 3, 3, nullptr, kGateSm60BufferOps, run_startup_sampler_x}, + {"--startup-sampler-x-words-dropped", 3, 3, nullptr, kGateSm60BufferOps, run_startup_sampler_x}, {"--startup-sampler-lod", 3, 3, nullptr, kNoGate, run_startup_sampler_lod}, {"--startup-sampler-lod-dropped", 3, 3, nullptr, kNoGate, run_startup_sampler_lod}, {"--startup-cb-blend", 3, 3, nullptr, kNoGate, run_startup_cb_blend}, diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index d2a72fc2d3..d2b7fff68e 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -6,9 +6,11 @@ #include #include #include +#include #include using Word = std::uint64_t; +extern "C" __declspec(dllimport) HRESULT XGCreateTextureComputer(const D3D12_RESOURCE_DESC*, void***, UINT64, UINT64); Word invoke(void*, unsigned, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0); extern "C" __declspec(dllimport) void x2w_d3d12_texture_written(void* base, unsigned long long bytes); extern "C" __declspec(dllimport) void x2w_d3d12_bc7_4k_s_written(void* base, UINT width, UINT height); @@ -342,6 +344,108 @@ int draw_bc_chain(void* guest, void* list) return 0; } +int draw_announced_srvs(ID3D12Device* desktop, void* guest, void* list) +{ + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 2, 2, 1, 2, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + static_cast(0x105), static_cast(0x300000)}; + static std::array storage{}; + std::array memory{}; + for (unsigned i = 0; i < 3; ++i) + memory[i] = reinterpret_cast(((ptr(storage.data()) + 0xffff) & ~Word{0xffff}) + i * Word{65536}); + const auto texel = [](unsigned which, unsigned mip, unsigned x, unsigned y) -> std::array { + if (mip) return which == 1 ? std::array{9, 99, 199, 255} : std::array{5, 6, 7, 255}; + return which == 1 ? std::array{static_cast(100 + 20 * x + 50 * y), 50, 150, 255} + : std::array{static_cast(10 + 40 * x + 80 * y), 200, 30, 255}; + }; + for (unsigned which = 0; which < 3; ++which) { + void** computer = nullptr; + if (FAILED(XGCreateTextureComputer(&desc, &computer, 0, 0)) || !computer) return 50; + const auto table = static_cast(computer[0]); + using Write = HRESULT(*)(void*, unsigned char*, UINT, UINT, const unsigned char*, UINT, UINT); + for (unsigned mip = 0; mip < 2; ++mip) { + const unsigned side = 2 >> mip; + std::array linear{}; + for (unsigned y = 0; y < side; ++y) + for (unsigned x = 0; x < side; ++x) std::memcpy(&linear[(y * side + x) * 4], texel(which % 2, mip, x, y).data(), 4); + if (which < 2) { + if (FAILED(reinterpret_cast(table[8])(computer, memory[which], 0, mip, linear.data(), side * 4, side * side * 4))) + return 51; + } else { + // C: the bytes CopyIntoSubresource would write (desktop footprints), without the announcement. + D3D12_RESOURCE_DESC plain = desc; + plain.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + plain.Flags = D3D12_RESOURCE_FLAG_NONE; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; + desktop->GetCopyableFootprints(&plain, mip, 1, 0, &fp, nullptr, nullptr, nullptr); + for (unsigned y = 0; y < side; ++y) + std::memcpy(memory[2] + fp.Offset + y * fp.Footprint.RowPitch, &linear[y * side * 4], side * 4); + } + } + reinterpret_cast(table[1])(computer); + } + Word cpu = 0; + if (!bind_view_table(guest, list, cpu)) return 42; + ViewAt v{}; + v.view.Format = desc.Format; + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.view.Texture2D.MipLevels = 2; + const unsigned order[8] = {0, 1, 2, 0, 1, 2, 0, 0}; + for (LONG x = 0; x < 8; ++x) { + v.address = ptr(memory[order[x]]); + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + const D3D12_RECT strip{x, 0, x + 1, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + } + // Device slot 61 (the title's sampler call, a no-op): with X2W_TEXTURE_CENSUS=1 its arguments are logged. + std::array sampler_words{}; + for (unsigned i = 0; i < sampler_words.size(); ++i) sampler_words[i] = 0x61000000u + i; + invoke(guest, 61, ptr(sampler_words.data()), 0x5150, 1); + return 0; +} + +int draw_detile_srvs(void* guest, void* list) +{ + wchar_t path[MAX_PATH]{}; + char desc_text[128]{}; + const DWORD length = GetEnvironmentVariableW(L"X2W_TEST_DETILE_SRV", path, MAX_PATH); + if (!length || length >= MAX_PATH || !GetEnvironmentVariableA("X2W_TEST_DETILE_DESC", desc_text, sizeof desc_text)) return 43; + unsigned layout = 0, dimension = 0, format = 0, width = 0, height = 0, depth = 0, mips = 0; + if (std::sscanf(desc_text, "%x %u %u %u %u %u %u", &layout, &dimension, &format, &width, &height, &depth, &mips) != 7) return 43; + std::ifstream input(path, std::ios::binary); + const std::vector bytes{std::istreambuf_iterator(input), std::istreambuf_iterator{}}; + if (bytes.empty()) return 43; + // 64 KiB-aligned, with 1 MiB of zero slack so a wrong (larger) layout in a control stays readable. + void* memory = VirtualAlloc(nullptr, bytes.size() + (1u << 20), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!memory) return 44; + std::memcpy(memory, bytes.data(), bytes.size()); + const D3D12_RESOURCE_DESC desc{static_cast(dimension), 0, width, height, static_cast(depth), + static_cast(mips), static_cast(format), {1, 0}, static_cast(layout), + static_cast(0x300000)}; + ViewAt v{}; + v.address = ptr(memory); + v.view.Format = desc.Format; + v.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + v.view.Texture3D.MipLevels = mips; + } else if (depth > 1) { + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + v.view.Texture2DArray.MipLevels = mips; + v.view.Texture2DArray.ArraySize = depth; + } else { + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.view.Texture2D.MipLevels = mips; + } + Word cpu = 0; + if (!bind_view_table(guest, list, cpu)) return 42; + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); // the same view again: the first desktop texture is reused + invoke(list, 12, 3, 1); + return 0; +} + namespace { struct PlacedPair { std::array memory{}; diff --git a/tests/startup_bfm_absdiff_check.py b/tests/startup_bfm_absdiff_check.py new file mode 100644 index 0000000000..432eea6d68 --- /dev/null +++ b/tests/startup_bfm_absdiff_check.py @@ -0,0 +1,60 @@ +"""v_bfm_b32 (VOP3) and s_absdiff_i32 (SOP2). + +Synthetic gfx1013 words. References (AMD RDNA 2 ISA): V_BFM_B32 D = ((1 << S0[4:0]) - 1) << S1[4:0]; +S_ABSDIFF_I32 D = S0 - S1 (32-bit wrap), negated if negative, SCC = (D != 0) (LLVM SOPInstructions.td Defs = [SCC]). +The emitted HLSL is evaluated with the integer evaluator of startup_gfx2hlsl_bit_alu_check (abs added here with +HLSL int semantics: abs(INT_MIN) = INT_MIN) over an edge grid. Negative controls: a wrong expression of each form +(the shift count masked to 4 bits; abs dropped) is caught. +""" +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 +from startup_scalar_bits_check import GRID, MASK, asm, lines_of, rhs # noqa: E402 + + +class AbsExpr(Expr): + @staticmethod + def call(name, args): + if name == 'abs': + v, s = args[0] + assert s + x = v - (1 << 32) if v >> 31 else v + return (-x if x < 0 else x) & MASK, True + return Expr.call(name, args) + + +def s32(x): + return x - (1 << 32) if x >> 31 else x + + +def main(): + grid = GRID + [33 << 16 | 5, 0x1f001f, 0x3f] + words = [0xd4000000 | 0x363 << 16 | 2, 256 | 257 << 9] + assert asm(words) == ['v_bfm_b32 v2, v0, v1'], asm(words) + _, lines = lines_of(words) + expr = rhs(lines[0], 'v2') + ref = lambda a, b: (((1 << (a & 31)) - 1) << (b & 31)) & MASK # noqa: E731 + bad = [(a, b) for a in grid for b in grid if Expr(expr).run({'v0': a, 'v1': b})[0] & MASK != ref(a, b)] + assert not bad, (expr, bad[:4]) + wrong = Expr(expr.replace('{0} & 31'.format('v0'), 'v0 & 15')) + assert any(wrong.run({'v0': a, 'v1': b})[0] & MASK != ref(a, b) for a in grid for b in grid) + words = [0x80000000 | 0x2c << 23 | 5 << 16 | 7 << 8 | 6] + assert asm(words) == ['s_absdiff_i32 s5, s6, s7'], asm(words) + _, lines = lines_of(words) + assert len(lines) == 2 and lines[1] == 'scc = s5 != 0;', lines + expr = rhs(lines[0], 's5') + ref = lambda a, b: abs(s32((a - b) & MASK)) & MASK # noqa: E731 + bad = [(a, b) for a in grid for b in grid if AbsExpr(expr).run({'s6': a, 's7': b})[0] & MASK != ref(a, b)] + assert not bad, (expr, bad[:4]) + assert ref(0x80000000, 0) == 0x80000000 + wrong = AbsExpr(expr.replace('abs(', '(')) + assert any(wrong.run({'s6': a, 's7': b})[0] & MASK != ref(a, b) for a in grid for b in grid) + print('bfm_absdiff: v_bfm_b32 and s_absdiff_i32 (SCC = D != 0) match the ISA references on %d inputs; ' + 'negative controls caught' % len(grid) ** 2) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_buffer_address_check.py b/tests/startup_buffer_address_check.py index 6e2ba647ec..4dfec4e83a 100644 --- a/tests/startup_buffer_address_check.py +++ b/tests/startup_buffer_address_check.py @@ -230,9 +230,7 @@ def request(load): assert classify_shader_reason('buffer_load_format_xyzw requires descriptor FORMAT and DST_SEL') == 'buffer_* instruction' -def controls(): - formatted_mubuf_request_controls() - +def address_mode_controls(): # 1. Existing single-mode forms keep their exact HLSL output. asm, st = translate_bytes(encode_mubuf(imm=12, soffset=128 + 16)) assert asm == ['buffer_load_dword v4, off, s[16:19], 16 offset:12'], asm @@ -261,6 +259,11 @@ def controls(): assert st.lines[0] == 'a = v6 * ud2 + v7 + 5;', st.lines assert {6, 7}.issubset(st.used_v), st.used_v + +def controls(): + address_mode_controls() + formatted_mubuf_request_controls() + # 3. Scalar soffset from an SGPR (root constant, folded scalar constant, or runtime SGPR, up to s105). asm, st = translate_bytes(encode_mubuf(imm=12, idxen=1, offen=1, vaddr=2, soffset=8)) assert asm == ['buffer_load_dword v4, v[2:3], s[16:19], s8 idxen offen offset:12'], asm @@ -283,6 +286,8 @@ def controls(): assert st.lines[0] == 'a = v254 * ud2 + v255 + 4;', st.lines must_refuse_bytes(encode_mubuf(imm=4, idxen=1, offen=1, vaddr=255), 'v[255:256]') + must_refuse_asm('buffer_load_dword v4, off, s[16:19], 0 lwe', 'buffer modifier lwe') + # 6. Unmodeled modifiers (lds, tfe, unknown) are refused with Unsupported, never dropped or crashed. must_refuse_bytes(encode_mubuf(imm=8, offen=1, vaddr=2, lds=1), 'buffer modifier lds') must_refuse_bytes(encode_mubuf(imm=8, lds=1), 'buffer modifier lds') diff --git a/tests/startup_buffer_heap_index_check.py b/tests/startup_buffer_heap_index_check.py new file mode 100644 index 0000000000..7798e6d20f --- /dev/null +++ b/tests/startup_buffer_heap_index_check.py @@ -0,0 +1,100 @@ +"""Startup buffer heap index check.""" +from pathlib import Path +import re +import sys +import tempfile + +from startup_draw_uav_check import run_mode + +IDENTITY = bytes((0, 0, 0x80, 0x3F)) +VALUE = bytes((99, 0, 0, 0)) +DECOY = bytes((55, 0, 0, 0)) +ON = {"X2W_BUFFER_HEAP_INDEX": "1", "X2W_BUFFER_ADDRESS_INDEX": "check"} +REWRITE_LOG = dict(ON, X2W_MARKER_REWRITE_LOG="1") +MODES = {"membuf": ON, "membuf-off": {}, "membuf-link": ON, "membuf-structured": ON, "membuf-typed": ON, "membuf-refused": REWRITE_LOG, + "membuf-unaligned": ON, "membuf-unaligned-off": {}, "membuf-rewrite": REWRITE_LOG} + + +def columns(image): + """Pixels (x, y) for x < 2 of the 8x4 RGBA8 read-back: what the two strips drew.""" + return {image[(y * 8 + x) * 4:(y * 8 + x) * 4 + 4] for y in range(4) for x in range(2)} + + +def check(directory, consumer, backend): + results = {} + for mode, env in MODES.items(): + got = run_mode(directory, consumer, backend, mode, dict(env, X2W_DRAW_NULL_IDENTITY="1")) + if got is None: + print("no existing-heap support or no adapter: skip") + return 77 + results[mode] = got + for mode, (_, image, log) in results.items(): + if DECOY in columns(image): + raise AssertionError(f"{mode}: the draw read the decoy at slot N (55)\n{log[-3000:]}") + _, image, log = results["membuf"] + if columns(image) != {VALUE}: + raise AssertionError(f"membuf: pixels {image[:32].hex()} (expected 99 = {VALUE.hex()})\n{log[-4000:]}") + # The switch-on modes run X2W_BUFFER_ADDRESS_INDEX=check: the index answers as the walk (here: no buffer). + for mode in ("membuf", "membuf-structured", "membuf-typed"): + lines = re.findall(r"^x2w-memsrv buffer address index checked (\d+) lookups against the walk: (\d+) differ$", results[mode][2], re.M) + if not lines or any(d != "0" for _, d in lines) or "DIFFERS" in results[mode][2]: + raise AssertionError(f"{mode}: address index check lines {lines}\n{results[mode][2][-3000:]}") + for mode, layout in (("membuf", "stride 0, records 256, word 3 0x"), ("membuf-structured", "stride 16, records 4, word 3 0x"), + ("membuf-typed", "stride 4, records 64, word 3 0x"), + ("membuf-unaligned", "stride 12, records 4, word 3 0x")): + _, image, log = results[mode] + words = re.search(r"^membuf entry words: (\w+) (\w+) (\w+) (\w+)$", log, re.M) + if columns(image) != {VALUE} or not words or words.group(1) in ("00000001", "56573258", "52463258") or words.group(4) == "00000000": + raise AssertionError(f"{mode}: pixels {image[:32].hex()} (expected 99), entry {words.group(0) if words else None}\n{log[-4000:]}") + written = re.search(r"^x2w-memsrv buffer descriptor written at .*$", log, re.M) + if "X2W_BUFFER_HEAP_INDEX=1" not in log or not written or layout not in written.group(0) or "stand-in buffer at" in log: + raise AssertionError(f"{mode}: descriptor line {written.group(0) if written else None} (expected {layout!r}), or a stand-in\n{log[-4000:]}") + _, image, log = results["membuf-unaligned"] + if "(a buffer is there, at an offset the view cannot name)" not in log \ + or "buffer descriptors: written 1 (no buffer 0, buffer at an offset the view cannot name 1)" not in log \ + or not re.search(r"per written call: buffer lookup \d+\.\d\d us, destination checks \d+\.\d\d us, shadow clear \d+\.\d\d us " + r"\(lock taken [01]\)", log): + raise AssertionError(f"membuf-unaligned: the found-buffer case is not named\n{log[-4000:]}") + _, image, log = results["membuf-unaligned-off"] + if columns(image) != {IDENTITY} or "reason=buffer_unavailable" not in log or "buffer descriptor written" in log: + raise AssertionError(f"membuf-unaligned-off: pixels {image[:32].hex()} (expected the identity fill)\n{log[-4000:]}") + _, image, log = results["membuf-refused"] + line = re.search(r"^x2w-frame srv-heapbuf .*$", log, re.M) + if columns(image) != {IDENTITY} or "membuf entry words: 52463258" not in log or not line \ + or "(refused: null_address)" not in line.group(0) \ + or not re.search(r"refused view: fmt \d+ layout 0x[0-9a-f]+ dim 1 mips \d+ [1-9]\d*x1x1 address 0x0 unreadable, detile: -$", + line.group(0)): + raise AssertionError(f"membuf-refused: pixels {image[:32].hex()}, line {line.group(0) if line else None}\n{log[-4000:]}") + # membuf-refused is also the negative control of X2W_MARKER_REWRITE_LOG: an intact marker is not flagged. + if "rewritten refused-view marker" in log or "X2W_MARKER_REWRITE_LOG=1" not in log: + raise AssertionError(f"membuf-refused: an intact marker was flagged as rewritten, or the switch line is missing\n{log[-4000:]}") + # membuf-rewrite: the title patches word 0 / word 1 bits 0-15 of the refused destination with a V# base after the + # call; the copied entry is flagged, with the description and the base read back from the rewritten words. + _, image, log = results["membuf-rewrite"] + entry = re.search(r"^membuf entry words: ([0-9a-f]{8}) ([0-9a-f]{8}) ([0-9a-f]{8}) ([0-9a-f]{8})$", log, re.M) + line = re.search(r"^x2w-draw rewritten refused-view marker .*$", log, re.M) + if not entry or not line: + raise AssertionError(f"membuf-rewrite: entry {entry.group(0) if entry else None}, line {line.group(0) if line else None}\n{log[-4000:]}") + base = int(entry.group(1), 16) | (int(entry.group(2), 16) & 0xFFFF) << 32 + if entry.group(1) == "52463258" or f"as a V# 0x{base:x}" not in line.group(0) \ + or not re.search(r"described as fmt \d+ layout 0x[0-9a-f]+ dim 1 mips \d+ [1-9]\d*x1x1 address 0x0 unreadable, detile: -;", + line.group(0)) \ + or "x2w-draw rewritten refused-view markers 1" not in log: + raise AssertionError(f"membuf-rewrite: base 0x{base:x}, line {line.group(0)}\n{log[-4000:]}") + _, image, log = results["membuf-off"] + if columns(image) != {IDENTITY} or "membuf entry words: 00000001 00000000 00000000 00000000" not in log \ + or "reason=buffer_unavailable" not in log or "X2W_BUFFER_HEAP_INDEX" in log: + raise AssertionError(f"membuf-off: pixels {image[:32].hex()} (expected the identity fill {IDENTITY.hex()})\n{log[-4000:]}") + _, image, log = results["membuf-link"] + line = re.search(r"^x2w-frame srv-heapbuf .*$", log, re.M) + if columns(image) != {IDENTITY} or not line or "(free link)" not in line.group(0) \ + or "slot N-1 0x0 words 00000001" not in line.group(0) or "slot N 0x1 token 56573258" not in line.group(0): + raise AssertionError(f"membuf-link: pixels {image[:32].hex()}, line {line.group(0) if line else None}\n{log[-4000:]}") + print(f"{backend}: slot-70 buffer without a resource read through a copied entry (99) with X2W_BUFFER_HEAP_INDEX; " + f"switch off: link 1 copied, identity fill; free link: bound null and logged with slots N-1 / N; decoy at slot N never read; structured and typed views 99; a refused call's marker is carried, bound null and named") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_buffer_store_check.py b/tests/startup_buffer_store_check.py new file mode 100644 index 0000000000..fde312ba85 --- /dev/null +++ b/tests/startup_buffer_store_check.py @@ -0,0 +1,136 @@ +"""buffer_store_dword* to a raw buffer UAV, behind X2W_DRAW_FEATURES=uav (tools/startup/gfx2hlsl.py). + +Synthetic register states (descriptor s[16:19] from table 0 at byte 0x20). Checked: +1. feature off: refused with the old message (the op name); +2. feature on: `a = ud + vaddr + soffset + offset`, Store3 of the three data VGPRs, the exec guard after a + branch made exec unknown, a literal soffset folded into the constant; +3. refusals: idxen (no UAV stride source), a vertex-buffer source, an unknown modifier, a ninth UAV; a buffer both read and + stored is read through the UAV (StoredSrv retry signal, rw_keys); descriptor edits that keep the base are accepted; +4. manifest `uav 0 buf table 0 32` after the srv lines, `udsrc uavbase 0`, and the HLSL declaration + RWByteAddressBuffer u0 : register(u0). +Not checked: stores on a GPU (draw-rt's startup_draw_uav_check covers the runtime side with its own shaders). +""" +import os +import sys +from types import SimpleNamespace + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + sampler_heap = False + root = {'params': [], 'flags': 0} + uav = G.Pipeline.uav + resource = G.Pipeline.resource + + def __init__(self, features): + self.features = frozenset(features) + self.resources, self.uds, self.modified, self.heapvars = {}, [], set(), [] + + def ud(self, source): + if source not in self.uds: + self.uds.append(source) + return self.uds.index(source) + + +def stage(features=('uav',), source=('table', 0), pipe=None): + s = G.Stage(pipe or Pipe(features), 'ps', b'') + s.lines = [] + for i in range(4): + s.sym[16 + i] = ('desc', source, 0x20, i) + s.pc = 0 + return s + + +def refused(s, op, ops, mods, want): + try: + getattr(s, op)(ops, mods) + except G.Unsupported as error: + assert want in str(error), (want, str(error)) + else: + raise AssertionError('accepted: %s %s %s' % (op, ops, mods)) + + +STORE = ['v[4:6]', 'v1', 's[16:19]', '0'] + + +def main(): + refused(stage(()), 'op_buffer_store_dwordx3', STORE, ['offen'], 'buffer_store_dwordx3') + assert str(G.Unsupported('buffer_store_dwordx3')) == 'buffer_store_dwordx3' + + s = stage() + s.op_buffer_store_dwordx3(STORE, ['offen', 'offset:16']) + assert s.lines == ['a = ud0 + v1 + 16;', 'u0.Store3(a, uint3(v4, v5, v6));'], s.lines + assert s.pipe.uds == [('uavbase', 0)] and s.pipe.uavs == {(('table', 0), 0x20): 0}, (s.pipe.uds, s.pipe.uavs) + s = stage() + s.exec_known = False + s.op_buffer_store_dword(['v4', 'v1', 's[16:19]', 's3'], ['offen']) + assert s.lines == ['a = ud0 + v1 + s3 + 0;', 'if (exec & 1) u0.Store(a, v4);'], s.lines + s = stage() + s.op_buffer_store_dwordx2(['v[4:5]', 'off', 's[16:19]', '0x40'], []) + assert s.lines == ['a = ud0 + 64;', 'u0.Store2(a, uint2(v4, v5));'], s.lines + print('store: feature off refused as before; address with uavbase, exec guard, literal soffset folded') + + refused(stage(), 'op_buffer_store_dwordx3', STORE, ['idxen'], 'modifier idxen') + refused(stage(), 'op_buffer_store_dwordx3', STORE, ['offen', 'tfe'], 'modifier tfe') + refused(stage(source=('vbtab',)), 'op_buffer_store_dwordx3', STORE, ['offen'], 'through vbtab') + # A buffer read and stored: a load before the store raises StoredSrv (translate_to rebuilds with the key in + # rw_keys); with it there, or after a store, loads go through the UAV at the uavbase-shifted address. + s = stage() + s.op_buffer_load_dword(['v8', 'v1', 's[16:19]', '0'], ['offen']) + try: + s.op_buffer_store_dwordx3(STORE, ['offen']) + except G.StoredSrv as conflict: + assert conflict.key == (('table', 0), 0x20), conflict.key + else: + raise AssertionError('store after an SRV read accepted without rw_keys') + s = stage() + s.pipe.rw_keys = {(('table', 0), 0x20)} + s.op_buffer_load_dword(['v8', 'v1', 's[16:19]', '0'], ['offen']) + s.op_buffer_store_dwordx3(STORE, ['offen']) + assert s.lines == ['a = ud0 + v1 + 0;', 'v8 = u0.Load(a + 0);', 'a = ud0 + v1 + 0;', 'u0.Store3(a, uint3(v4, v5, v6));'], s.lines + refused(s, 'op_buffer_load_dword', ['v8', 'v1', 's[16:19]', '0'], ['idxen'], 'indexed load through a buffer') + refused(s, 'op_tbuffer_load_format_x', ['v8', 'v1', 's[16:19]', '0'], ['offen', 'format:[BUF_FMT_8_UNORM]'], + 'typed load through a buffer the program stores to') + refused(s, 'op_s_buffer_load_dword', ['s0', 's[16:19]', '0x0'], [], 'read as an SRV and stored to as a UAV') + s = stage() + s.op_buffer_store_dwordx3(STORE, ['offen']) + s.op_buffer_load_dword(['v8', 'v1', 's[16:19]', '0'], ['offen']) + assert s.lines[-1] == 'v8 = u0.Load(a + 0);', s.lines + + # Descriptor edits: stride cleared (AND keeping [15:0] of word 1), records and word 3 changed -> accepted; + # word 0 or a word-1 edit touching the base -> refused. + for edits, ok in (([(1, 's_and_b32', ('0xc000ffff',)), (2, 's_mul_i32', ('s10',)), (3, 's_or_b32', ('0x30000000',))], True), + ([(0, 's_add_u32', ('0x10',))], False), ([(1, 's_and_b32', ('0xc0000fff',))], False), + ([(1, 's_or_b32', ('0x10000',))], False)): + s = stage() + s.pipe.modified.add((('table', 0), 0x20)) + s.pipe.modified_words = {(('table', 0), 0x20): edits} + if ok: + s.op_buffer_store_dwordx3(['v[1:3]', 'off', 's[16:19]', 's13'], []) + assert s.lines[-1] == 'u0.Store3(a, uint3(v1, v2, v3));', s.lines + else: + refused(s, 'op_buffer_store_dwordx3', ['v[1:3]', 'off', 's[16:19]', 's13'], [], 'modified descriptor') + pipe = Pipe(('uav',)) + for n in range(8): + pipe.uav((('table', 0), 0x100 * (n + 1))) + refused(stage(pipe=pipe), 'op_buffer_store_dwordx3', ['v[4:6]', 'v1', 's[16:19]', '0'], ['offen'], 'more than 8 UAVs') + print('store: idxen, tfe, vertex buffer, ninth UAV refused; read+store through the UAV (retry signal, rw loads); base-keeping descriptor edits accepted, others refused') + + s = stage() + s.op_buffer_store_dwordx3(STORE, ['offen']) + p = s.pipe + p.resource((('table', 1), 0), 'buf') + fake = SimpleNamespace(uds=p.uds, resources=p.resources, uavs=p.uavs, heapvars=[], samplers={}, + uses_sampler_heap=False, params=[], ps=SimpleNamespace(exports={'mrt0': 1})) + manifest = G.Pipeline.manifest(fake).split('\n') + assert manifest[:5] == ['x2w-manifest 1', 'ud 1', 'udsrc 0 uavbase 0', 'srv 0 buf table 1 0', 'uav 0 buf table 0 32'], manifest + common = SimpleNamespace(helper_text='', uds=p.uds, resources=p.resources, uavs=p.uavs, samplers={}, heapvars=[], + uses_sampler_heap=False) + assert 'RWByteAddressBuffer u0 : register(u0);' in G.Pipeline.common(common) + print('manifest: uav line after the srv lines, uavbase entry; RWByteAddressBuffer declared') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_carry_dst_check.py b/tests/startup_carry_dst_check.py new file mode 100644 index 0000000000..d8f9e48d7d --- /dev/null +++ b/tests/startup_carry_dst_check.py @@ -0,0 +1,38 @@ +"""A carry-out or compare destination that is not an SGPR, vcc or exec is refused (it used to crash the translation). + +Synthetic VOP3B word: v_add_co_ci_u32_e64 v100, , 0, v100, vcc_lo (op 0x128). With sdst vcc_hi (107) the +translator raised TypeError in write_compare (reg_range('vcc_hi') is None), which ends a whole translation as a +crash; it is now the refusal "compare or carry destination vcc_hi". Controls: sdst s20 is lowered and s20 becomes a +lane mask; sdst vcc_lo writes vcc. +""" +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_scalar_bits_check import asm, stage # noqa: E402 + + +def word(sdst): + return [0xd4000000 | 0x128 << 16 | sdst << 8 | 100, 128 | (256 + 100) << 9 | 106 << 18] + + +def main(): + assert asm(word(107)) == ['v_add_co_ci_u32_e64 v100, vcc_hi, 0, v100, vcc_lo'], asm(word(107)) + try: + stage(word(107)) + except G.Unsupported as error: + assert str(error) == 'compare or carry destination vcc_hi', str(error) + else: + raise AssertionError('vcc_hi carry-out accepted') + s = stage(word(20)) + assert 20 in s.masks, s.masks + s = stage(word(106)) + assert not s.masks + print('carry_dst: vcc_hi carry-out refused (was a TypeError crash); s20 and vcc_lo controls lowered') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_class_f16_sdwa_check.py b/tests/startup_class_f16_sdwa_check.py new file mode 100644 index 0000000000..d5a17e7c81 --- /dev/null +++ b/tests/startup_class_f16_sdwa_check.py @@ -0,0 +1,95 @@ +"""v_cmp_class_f16_sdwa: a binary16 value selected from a register, classified against a class-mask register. + +Synthetic VOPC SDWA words (word 0: src0 = 0xf9, vsrc1, op 0x8f = v_cmp_class_f16, 0x3e; word 1: src0, sdst | SD, +src0_sel, src0_neg, src0_abs, S0, src1_sel). SDWA source selection (AMD RDNA ISA, SDWA): the selected field is +zero-extended and the f16 op reads bits [15:0], so WORD_1 classifies the high half; neg/abs act on bit 15 of the +selected value. The emitted HLSL is checked as text, and its value is evaluated with a Python model of the ten class +bits (LLVM SIDefines.h ClassFlags order) for every field selection over sample halves. +Controls: a constant value is refused (its f16 inline form is not modelled); v_cmp_class_f32_sdwa is unchanged. +""" +import re +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def vopc_sdwa(op, src0, vsrc1, sdst, src0_sel=6, src1_sel=6, neg0=False, abs0=False, s0=False): + w0 = 0xf9 | vsrc1 << 9 | op << 17 | 0x3e << 25 + w1 = src0 | (sdst | 0x80) << 8 | src0_sel << 16 | int(neg0) << 20 | int(abs0) << 21 | int(s0) << 23 \ + | src1_sel << 24 + return [w0, w1] + + +def one(words): + s = G.Stage(Pipe(), 'vs', b'') + s.lines = [] + _, n, name, text = G.decode(struct.pack('<2I', *words))[0] + s.pc = 0 + s.one(name, text) + return text, '\n'.join(s.lines) + + +def cls16(h): + e, m, neg = h >> 10 & 31, h & 0x3ff, h >> 15 & 1 + if e == 31: + return (1 if m & 0x200 else 0) if m else (2 if neg else 9) + if e == 0: + return (4 if neg else 7) if m else (5 if neg else 6) + return 3 if neg else 8 + + +def evaluate(expr, v1, v2): + """Evaluate the emitted uint expression in Python (x2w_class_f16 by the model, HLSL uint ops as Python ints).""" + py = expr.replace('u)', ')').replace('u ', ' ') + py = re.sub(r'(0x[0-9a-f]+|\d+)u\b', r'\1', py) + return eval(py, {'v1': v1, 'v2': v2, 'x2w_class_f16': lambda x, mask: mask >> cls16(x & 0xffff) & 1}) + + +def main(): + halves = [0x0000, 0x8000, 0x0001, 0x8001, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7e00, 0x7d00, 0x03ff, 0xfbff] + sels = {0: 'BYTE_0', 1: 'BYTE_1', 4: 'WORD_0', 5: 'WORD_1', 6: 'DWORD'} + checked = 0 + for sel, name in sels.items(): + for neg, ab in ((False, False), (True, False), (False, True), (True, True)): + text, body = one(vopc_sdwa(0x8f, 1, 2, 38, src0_sel=sel, neg0=neg, abs0=ab)) + shown = '-|v1|' if neg and ab else '-v1' if neg else '|v1|' if ab else 'v1' + assert text == 'v_cmp_class_f16_sdwa s38, %s, v2 src0_sel:%s src1_sel:DWORD' % (shown, name), text + m = re.fullmatch(r's38 = (.*);', body) + assert m and 'x2w_class_f16(' in body, body + for lo in halves: + for hi in halves: + v1 = hi << 16 | lo + off, width = G.SDWA_SEL[name] + field = (v1 >> off) & ((1 << width) - 1) + h = field & 0xffff + h = h & 0x7fff if ab else h # abs first, then neg (-|x| is negative) + h = h ^ 0x8000 if neg else h + for bit in range(10): + assert evaluate(m.group(1), v1, 1 << bit) == int(cls16(h) == bit), (name, neg, ab, hex(v1)) + checked += 1 + _, body = one(vopc_sdwa(0x8f, 1, 2, 38, src0_sel=5)) + assert body == 's38 = x2w_class_f16(((v1 >> 16u) & 0xffffu), v2);', body + try: + one(vopc_sdwa(0x8f, 240, 2, 38, s0=True)) # constant 0.5 + except G.Unsupported as error: + assert 'f16 value operand' in str(error), str(error) + else: + raise AssertionError('constant f16 class value accepted') + text, body = one(vopc_sdwa(0x88, 128, 6, 38, src1_sel=1, neg0=True, s0=True)) + assert body == 's38 = x2w_class_f32((0x00000000u ^ 0x80000000u), ((v6 >> 8u) & 0xffu));', body + print('class_f16 sdwa: %d (selection, modifier, value, class) cases match the class model; WORD_1 reads the ' + 'high half; constant value refused; f32 control unchanged' % checked) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_class_sdwa_check.py b/tests/startup_class_sdwa_check.py new file mode 100644 index 0000000000..52f2e5d459 --- /dev/null +++ b/tests/startup_class_sdwa_check.py @@ -0,0 +1,81 @@ +"""v_cmp_class_f32_sdwa: a constant f32 value classified against a byte of a register (src1_sel:BYTE_1). + +Synthetic VOPC SDWA words (word 0: src0 = 0xf9, vsrc1, op 0x88, 0x3e; word 1: src0, sdst | SD, src0_sel, src0_neg, +S0, src1_sel). A compiler tests single bits of a byte with it: class(-0.0) is mask bit 5, class(-denormal 0x80000001) +bit 4, class(0xffffffff, a quiet NaN) bit 1 (class bits: LLVM SIDefines.h ClassFlags, the order x2w_class_f32 +uses). The emitted HLSL is checked as text and its value computed with a Python model of the class bits. +Controls: src0_sel other than DWORD is refused, and an integer SDWA compare keeps its old lowering. +""" +import math +import re +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def vopc_sdwa(op, src0, vsrc1, sdst, src0_sel=6, src1_sel=1, neg0=False, s0=True): + w0 = 0xf9 | vsrc1 << 9 | op << 17 | 0x3e << 25 + w1 = src0 | (sdst | 0x80) << 8 | src0_sel << 16 | int(neg0) << 20 | int(s0) << 23 | src1_sel << 24 + return [w0, w1] + + +def one(words): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + _, n, name, text = G.decode(struct.pack('<2I', *words))[0] + s.pc = 0 + s.one(name, text) + return text, '\n'.join(s.lines) + + +def cls(bits): + """Class bit index of an f32 bit pattern: 0 sNaN, 1 qNaN, 2 -inf, 3 -normal, 4 -denormal, 5 -0, 6 +0, 7 +denormal, + 8 +normal, 9 +inf.""" + e, m, neg = bits >> 23 & 255, bits & 0x7fffff, bits >> 31 + if e == 255: + return (1 if m & 0x400000 else 0) if m else (2 if neg else 9) + if e == 0: + return (4 if neg else 7) if m else (5 if neg else 6) + return 3 if neg else 8 + + +def main(): + cases = [(128, True, 'neg(0)', '(0x00000000u ^ 0x80000000u)', 5), + (129, True, 'neg(1)', '(0x00000001u ^ 0x80000000u)', 4), + (193, False, '-1', '0xffffffffu', 1)] + for src0, neg, shown, value, bit in cases: + text, body = one(vopc_sdwa(0x88, src0, 6, 38, neg0=neg)) + assert text == 'v_cmp_class_f32_sdwa s38, %s, v6 src0_sel:DWORD src1_sel:BYTE_1' % shown, text + want = 's38 = x2w_class_f32(%s, ((v6 >> 8u) & 0xffu));' % value + assert body == want, (body, want) + bits = int(re.sub(r'u', '', value.strip('()').split(' ^ ')[0]), 16) ^ (0x80000000 if neg else 0) + assert cls(bits) == bit, (shown, cls(bits)) + # the result is mask bit `bit` of byte 1 of v6 + for v6 in (0, 1 << (8 + bit), 0xff00 ^ 1 << (8 + bit), 0xffffffff): + assert (((v6 >> 8) & 0xff) >> cls(bits) & 1) == (v6 >> (8 + bit) & 1) + assert math.isnan(struct.unpack('> 0u) & 0xffu)) > int(((v7 >> 0u) & 0xffu))) ? 1u : 0u);', body + print('class sdwa: -0.0 / -denormal / NaN against byte 1 of v6 (bits 5, 4, 1); sub-dword value refused; ' + 'integer SDWA control unchanged') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_clip_distance_check.py b/tests/startup_clip_distance_check.py new file mode 100644 index 0000000000..d4720f9d98 --- /dev/null +++ b/tests/startup_clip_distance_check.py @@ -0,0 +1,58 @@ +"""A vertex-stage pos1 export as SV_ClipDistance0, from the request's PA_CL_VS_OUT_CNTL (req_.vsout).""" +import os +import struct +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import PS_WORDS, root_blob # noqa: E402 + +VS = struct.pack('<7I', 0x7e0802f2, 0x7e0a0280, # v_mov_b32 v4, 1.0 ; v_mov_b32 v5, 0 + 0xf80000cf, 0x04050504, # exp pos0 v4, v5, v5, v4 + 0xf80008d3, 0x00000504, # exp pos1 v4, v5, off, off done + 0xbf810000) +GOOD = 0x01400303 + + +def refused(cntl, why): + try: + G.Pipeline(VS, PS_WORDS, root_blob(), vs_out_cntl=cntl).hlsl_vs() + except G.Unsupported as error: + assert why in str(error), (why, str(error)) + else: + raise AssertionError('accepted PA_CL_VS_OUT_CNTL %r' % cntl) + + +def main(): + text = [x[3] for x in G.decode(VS)] + assert text[2] == 'exp pos0 v4, v5, v5, v4' and text[3] == 'exp pos1 v4, v5, off, off done', text + refused(None, 'export target pos1') + pipe = G.Pipeline(VS, PS_WORDS, root_blob(), vs_out_cntl=GOOD) + vs, ps = pipe.hlsl_vs(), pipe.hlsl_ps() + for line in (' float2 clip0 : SV_ClipDistance0;', 'o.clip0 = float2(F(v4), F(v5));', + ' o.clip0 = p.clip0 + r.clip0 - q.clip0;'): + assert line in vs, (line, vs) + assert ' float2 clip0 : SV_ClipDistance0;' in ps, ps + with tempfile.TemporaryDirectory() as d: + result = G.translate_to(d, 1, VS, PS_WORDS, root_blob(), vs_out_cntl=GOOD) + assert result == 'ok', result + assert os.path.getsize(os.path.join(d, '%016x.vs.cso' % 1)) > 0 + for content, ok in (('pa_cl_vs_out_cntl 1 01400303\n', True), ('pa_cl_vs_out_cntl 1 1400303\n', False)): + p = os.path.join(d, 'x.vsout') + open(p, 'w', newline='\n').write(content) + try: + assert G.read_vs_out(p) == GOOD and ok + except G.Unsupported as error: + assert not ok and 'invalid vertex output control file' in str(error), str(error) + refused(GOOD | 1 << 21, 'PA_CL_VS_OUT_CNTL') # misc vector first: pos1 is not the distances + refused(0x00400300, 'PA_CL_VS_OUT_CNTL') # cull distances only + refused(0x00400307, 'PA_CL_VS_OUT_CNTL') # three clip distances, two channels written + refused(GOOD | 1 << 23, 'PA_CL_VS_OUT_CNTL') # a second distance vector + refused(GOOD & ~(1 << 22), 'PA_CL_VS_OUT_CNTL') # no distance vector enabled + print('clip distance: pos1 refused without .vsout; 0x01400303 -> SV_ClipDistance0 float2, FXC ok; 5 refusals') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_cselect_vcc_lo_check.py b/tests/startup_cselect_vcc_lo_check.py new file mode 100644 index 0000000000..2ea7dc516f --- /dev/null +++ b/tests/startup_cselect_vcc_lo_check.py @@ -0,0 +1,52 @@ +"""s_cselect_b32 into vcc_lo (wave32 lane mask) and into a non-SGPR destination. + +Synthetic words. In wave32, vcc_lo is the whole VCC lane mask, so `s_cselect_b32 vcc_lo, -1, 0` sets the lane's +VCC bit from SCC, as the generic scalar path already treats vcc_lo. Before this the select path assumed an SGPR +destination and raised a TypeError. Control: s_cselect_b32 into an SGPR is unchanged; into m0 it is refused. +""" +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def one(word): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + _, n, name, text = G.decode(struct.pack(' +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "startup_cx_async_cs.h" +#include "startup_cx_heap_cs.h" + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e, f); +} +bool ok(Word hr) { return SUCCEEDED(static_cast(hr)); } +std::uint64_t fnv(const void* data, std::size_t bytes, std::uint64_t hash = 1469598103934665603ull) +{ + for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ static_cast(data)[i]) * 1099511628211ull; + return hash; +} +bool write_file(const std::wstring& path, const void* data, std::size_t bytes) +{ + FILE* f = _wfopen(path.c_str(), L"wb"); + if (!f) return false; + const bool written = std::fwrite(data, 1, bytes, f) == bytes; + return std::fclose(f) == 0 && written; +} +std::string read_log(const std::wstring& path) +{ + std::ifstream file(path, std::ios::binary); + return std::string{std::istreambuf_iterator(file), {}}; +} +HANDLE hold_event; +DWORD WINAPI release_later(void*) +{ + Sleep(300); + SetEvent(hold_event); + return 0; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) return 2; + const std::string mode = argv[2]; + if (mode != "async" && mode != "sync" && mode != "known" && mode != "seen" && mode != "heap") return 2; + const bool async = mode == "async"; + const bool heap = mode == "heap"; + const bool prewarm = mode == "known" || mode == "seen"; // X2W_CX_PREWARM_ALL (no hold) + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + LARGE_INTEGER driver{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls driver=%u.%u.%u.%u mode=%s\n", adapter_desc.Description, HIWORD(driver.HighPart), LOWORD(driver.HighPart), + HIWORD(driver.LowPart), LOWORD(driver.LowPart), mode.c_str()); + { // existing heaps over process memory (the windows); a probe device only + ComPtr desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 4; + void* block = VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + ComPtr heap; + const HRESULT hr = block ? desktop->OpenExistingHeapFromAddress(block, IID_PPV_ARGS(&heap)) : E_OUTOFMEMORY; + heap.Reset(); + if (block) VirtualFree(block, 0, MEM_RELEASE); + if (FAILED(hr)) { + std::printf("OpenExistingHeapFromAddress -> 0x%08lx: capability skip\n", static_cast(hr)); + return 77; + } + } + + // Shader cache, log and hold event of this process (process id + tick count: never an earlier run's files). + wchar_t temp[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, temp)) return 5; + const std::wstring tag = std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(GetTickCount64()); + const std::wstring cache = std::wstring(temp) + L"x2w_cx_async_" + tag; + CreateDirectoryW(cache.c_str(), nullptr); + SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()); + const std::wstring log_path = cache + L"\\trap.log"; + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + const std::wstring event_name = L"Local\\x2w_cx_hold_" + tag; + hold_event = CreateEventW(nullptr, TRUE, FALSE, event_name.c_str()); + if (!hold_event) return 5; + if (!prewarm && !heap) SetEnvironmentVariableW(L"X2W_CX_TEST_HOLD_EVENT", event_name.c_str()); + + // The title's compute root signature (its bytes go into the key; the translated one comes from the manifest). + D3D12_ROOT_PARAMETER title_params[1]{}; + title_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + const D3D12_ROOT_SIGNATURE_DESC title_root_desc{1, title_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr title_blob; + if (FAILED(D3D12SerializeRootSignature(&title_root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &title_blob, nullptr))) return 5; + static unsigned char code[192]; // fake console code (the stand-in only hashes it) + for (int i = 0; i < 192; ++i) code[i] = static_cast(0x3B ^ (i * 5)); + const std::uint64_t key = (fnv(title_blob->GetBufferPointer(), title_blob->GetBufferSize(), fnv(code, sizeof(code))) & 0x00ffffffffffffffull) | + (0x67ull << 56); + char key_text[24]; + std::snprintf(key_text, sizeof(key_text), "%016llx", static_cast(key)); + std::printf("compute key %s\n", key_text); + // known / seen: a second cached translation (key B, never created or dispatched); seen: a keys-seen file of + // B and C (C has no translation), so only B is queued at start and the file afterwards holds A, B and C. + const std::uint64_t key_b = key ^ 0x10, key_c = 0x67000000000000c0ull; + for (const std::uint64_t k : {key, key_b}) { + if (k == key_b && !prewarm) continue; + wchar_t name[24]; + swprintf(name, 24, L"%016llx", static_cast(k)); + const std::wstring base = cache + L"\\" + name; + const std::string manifest = heap ? "cs 1 1 1\nuav 0 buf root 0 0\nheap 1\n" : "cs 1 1 1\nuav 0 buf root 0 0\n"; + if (!(heap ? write_file(base + L".cs.cso", startup_cx_heap_cs, sizeof(startup_cx_heap_cs)) + : write_file(base + L".cs.cso", startup_cx_async_cs, sizeof(startup_cx_async_cs))) || + !write_file(base + L".cs.txt", manifest.data(), manifest.size())) + return 5; + } + const auto key_line = [](std::uint64_t k) { + char text[24]; + std::snprintf(text, sizeof(text), "%016llx\n", static_cast(k)); + return std::string(text); + }; + const std::wstring seen_path = cache + L"\\cx_keys_seen.lst"; + if (mode == "seen") { + const std::string seen = key_line(key_b) + key_line(key_c); + if (!write_file(seen_path, seen.data(), seen.size())) return 5; + } + + std::array device_parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), device_parameters.data(), __uuidof(ID3D12Device), &device))) return 6; + ComPtr desktop; // the same device object as the stand-in's (one device per adapter) + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 6; + // known / seen: the start prewarm loads the known keys before the title creates anything (at most 15 s). + const std::string all_loaded = std::string("x2w-cx prewarm: all ") + (mode == "known" ? "2" : "1") + " known pipelines loaded"; + if (prewarm) { + bool loaded = false; + for (int i = 0; i < 300 && !loaded; ++i) { + loaded = read_log(log_path).find(all_loaded) != std::string::npos; + if (!loaded) Sleep(50); + } + std::printf("start prewarm: \"%s\" %s\n", all_loaded.c_str(), loaded ? "seen" : "NOT seen within 15 s"); + if (!loaded) return 9; + } + void *title_root = nullptr, *pipeline = nullptr; + if (!ok(invoke(device, 16, 0, arg(title_blob->GetBufferPointer()), title_blob->GetBufferSize(), arg(&__uuidof(ID3D12RootSignature)), arg(&title_root)))) + return 7; + // The slot-67 record: [0] root signature, [5]/[6] code. Creation queues the key for the prewarm workers, whose + // load now waits for the event. + alignas(8) static unsigned char record[0x300]; + Word record_words[9] = {}; + record_words[0] = arg(title_root); + record_words[5] = arg(code), record_words[6] = sizeof(code); + std::memcpy(record, record_words, sizeof(record_words)); + if (!ok(invoke(device, 67, arg(record), arg(&__uuidof(ID3D12PipelineState)), arg(&pipeline))) || !pipeline) return 8; + + // Title memory: 2 MiB, word 0 the counter; a placed buffer over all of it (the window the UAV is made on; a root + // UAV is bound over the readable bytes from its address, at most 1 MiB, which must lie inside one window). + auto* memory = static_cast(VirtualAlloc(nullptr, 2u << 20, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!memory) return 10; + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 2u << 20, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + void* placed = nullptr; + if (!ok(invoke(device, 133, arg(memory), arg(&buffer), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&placed)))) return 11; + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *queue = nullptr, *fence = nullptr, *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 13; + Word fence_value = 0; + // One list of `dispatches` Dispatch(1, 1, 1), executed and waited for. + const auto run_list = [&](int dispatches) { + invoke(list, 139, arg(allocator)); // Reset + invoke(list, 33, arg(title_root)); // SetComputeRootSignature + invoke(list, 25, arg(pipeline)); // SetPipelineState (the slot-67 pipeline) + invoke(list, 45, 0, arg(memory)); // SetComputeRootUnorderedAccessView(0, title address) + for (int i = 0; i < dispatches; ++i) invoke(list, 14, 1, 1, 1); + invoke(list, 9); // Close + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), ++fence_value))) return false; + const auto deadline = GetTickCount64() + 30000; + while (invoke(fence, 8) < fence_value) { + if (GetTickCount64() >= deadline) return false; + Sleep(1); + } + return true; + }; + + int failures = 0; + if (heap) { + // A shader-visible 4-slot title view heap at title + 1 MiB (128 bytes); word 0 of slot 1 = A, and word 0 of + // "slot 4", the first word past the heap, = B. heapmem is a bounded view of the heap, so the shader must + // read A and 0. (An unbounded root SRV, the earlier binding, reads B there.) + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, arg(memory + 0x40000), 4 * 32}; + void* view_heap = nullptr; + if (!ok(invoke(device, 14, arg(&heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&view_heap))) || !view_heap) return 12; + constexpr std::uint32_t A = 0xa1a1a1a1u, B = 0xb2b2b2b2u; + memory[0x40000 + 8] = A; // slot 1 (byte 32) + memory[0x40000 + 32] = B; // byte 128: past the heap + memory[1] = memory[2] = 0x11111111u; + if (!run_list(1)) return 14; + const std::string log = read_log(log_path); + const auto has = [&](const std::string& text) { return log.find(text) != std::string::npos; }; + const bool skipped32 = has(std::string("x2w-cx ") + key_text + ": heap dispatch skipped: increment not 32"); + std::printf("heap: in range %08x (want %08x), past the end %08x (want 00000000; unbounded would read %08x); increment skip %d\n", + memory[1], A, memory[2], B, skipped32); + if (skipped32) { // WARP: views are not 32 bytes apart, so `heap 1` dispatches are skipped by design + std::printf("heap dispatches need a 32-byte view increment: capability skip\n"); + return memory[1] == 0x11111111u && memory[2] == 0x11111111u ? 77 : 16; + } + const bool bounded = has(std::string("x2w-cx ") + key_text + ": bounded heap views: heapmem 128 bytes (title heap 128), vinfo "); + std::printf("log: bounded heap views line %d\n", bounded); + if (memory[1] != A || memory[2] != 0 || !bounded) { + std::printf("FAIL: heapmem is not a bounded view of the 128-byte heap\n"); + ++failures; + } + for (std::size_t p = log.find("x2w-d3d12-debug"); p != std::string::npos; p = log.find("x2w-d3d12-debug", p + 1)) { + const std::size_t end = log.find('\n', p); + const std::string line = log.substr(p, end == std::string::npos ? std::string::npos : end - p); + std::printf("%s\n", line.c_str()); + if (line.find("sev=0 ") != std::string::npos || line.find("sev=1 ") != std::string::npos) ++failures; + } + std::printf("device removed reason: 0x%08lx\n", static_cast(desktop->GetDeviceRemovedReason())); + if (desktop->GetDeviceRemovedReason() != S_OK) ++failures; + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; + } + if (mode == "sync") { + if (const HANDLE t = CreateThread(nullptr, 0, release_later, nullptr, 0, nullptr)) CloseHandle(t); + else return 13; + } + const ULONGLONG list1_start = GetTickCount64(); + if (!run_list(3)) return 14; + const std::uint32_t after_first = memory[0]; + std::printf(prewarm ? "list 1 (3 dispatches, pipeline prewarmed at start): counter %u, recorded and executed in %llu ms\n" + : "list 1 (3 dispatches, pipeline held back): counter %u, recorded and executed in %llu ms\n", after_first, + static_cast(GetTickCount64() - list1_start)); + if (after_first != (async ? 0u : 3u)) { + std::printf("FAIL: list 1 should leave the counter at %u\n", async ? 0u : 3u); + ++failures; + } + int tries = 0; + if (async) { + SetEvent(hold_event); + while (memory[0] == 0 && tries < 200) { + Sleep(50); + ++tries; + if (!run_list(1)) return 14; + } + std::printf("after the release: counter %u after %d one-dispatch lists\n", memory[0], tries); + if (memory[0] != 1) { + std::printf("FAIL: once ready, exactly one dispatch should have run (counter 1)\n"); + ++failures; + } + } + + // The log (the worker writes the ready line just after the load completes: wait for it at most 5 s). + const std::string skip_line = std::string("x2w-cx ") + key_text + ": pipeline not loaded yet, dispatch skipped"; + const std::string ready_line = std::string("x2w-cx ") + key_text + " ready (X2W_CX_ASYNC)"; + std::string log = read_log(log_path); + for (int i = 0; async && i < 100 && log.find(ready_line) == std::string::npos; ++i) { + Sleep(50); + log = read_log(log_path); + } + const auto has = [&](const std::string& text) { return log.find(text) != std::string::npos; }; + long skipped = -1; + if (const std::size_t p = log.find(ready_line); p != std::string::npos) { + const std::string line = log.substr(p, log.find('\n', p) - p); + std::printf("log: %s\n", line.c_str()); + if (const std::size_t q = line.find("; "); q != std::string::npos) skipped = std::strtol(line.c_str() + q + 2, nullptr, 10); + } + const bool translated = has(std::string("x2w-cx ") + key_text + " translated: "); + const bool released = has(std::string("x2w-cx ") + key_text + ": load held by X2W_CX_TEST_HOLD_EVENT (released)"); + std::printf("log: translated %d, hold released %d, skip line %d, ready line %d (%ld dispatches skipped while compiling)\n", translated, released, + has(skip_line), has(ready_line), skipped); + if (!translated || released == prewarm) { + std::printf("FAIL: the translation was not loaded %s\n", prewarm ? "(or the hold was set)" : "through the hold"); + ++failures; + } + if (prewarm) { + // The queued line, and the keys-seen file the writer thread writes every 10 s (wait at most 25 s). + const std::string queued = mode == "known" + ? "x2w-cx prewarm: 2 known pipelines queued (X2W_CX_PREWARM_ALL; no keys seen file: every cached translation)" + : "x2w-cx prewarm: 1 known pipelines queued (X2W_CX_PREWARM_ALL; keys seen file "; + const std::string counts = ": 2 keys, 1 with a translation)"; + const bool queued_ok = has(queued) && (mode == "known" || has(counts)); + std::printf("log: queued line %d\n", queued_ok); + if (!queued_ok) { + std::printf("FAIL: the start prewarm did not queue what mode %s expects\n", mode.c_str()); + ++failures; + } + std::uint64_t sorted[3] = {key_c, key < key_b ? key : key_b, key < key_b ? key_b : key}; // key_c is the smallest + const std::string want = mode == "known" ? key_line(key) : key_line(sorted[0]) + key_line(sorted[1]) + key_line(sorted[2]); + std::string seen; + for (int i = 0; i < 250; ++i) { + seen = read_log(seen_path); + if (seen == want) break; + Sleep(100); + } + std::printf("keys seen file: \"%s\" (want \"%s\")\n", seen.c_str(), want.c_str()); + if (seen != want) { + std::printf("FAIL: the keys seen file is not the union of the earlier file and the dispatched key\n"); + ++failures; + } + } + if (async ? (!has(skip_line) || skipped < 3) : (has(skip_line) || has(ready_line))) { + std::printf("FAIL: the X2W_CX_ASYNC lines do not match mode %s\n", mode.c_str()); + ++failures; + } + for (std::size_t p = log.find("x2w-d3d12-debug"); p != std::string::npos; p = log.find("x2w-d3d12-debug", p + 1)) { + const std::size_t end = log.find('\n', p); + const std::string line = log.substr(p, end == std::string::npos ? std::string::npos : end - p); + std::printf("%s\n", line.c_str()); + if (line.find("sev=0 ") != std::string::npos || line.find("sev=1 ") != std::string::npos) ++failures; + } + std::printf("device removed reason: 0x%08lx\n", static_cast(desktop->GetDeviceRemovedReason())); + if (desktop->GetDeviceRemovedReason() != S_OK) ++failures; + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; +} diff --git a/tests/startup_cx_async.hlsl b/tests/startup_cx_async.hlsl new file mode 100644 index 0000000000..ab8a2faa93 --- /dev/null +++ b/tests/startup_cx_async.hlsl @@ -0,0 +1,15 @@ +RWByteAddressBuffer counter : register(u0); + +ByteAddressBuffer heapmem : register(t0, space1); +[numthreads(1, 1, 1)] +void HeapMain() +{ + counter.Store2(4, uint2(heapmem.Load(32), heapmem.Load(128))); +} + +[numthreads(1, 1, 1)] +void CountMain() +{ + uint before; + counter.InterlockedAdd(0, 1, before); +} diff --git a/tests/startup_draw_async_check.py b/tests/startup_draw_async_check.py new file mode 100644 index 0000000000..f0049a8646 --- /dev/null +++ b/tests/startup_draw_async_check.py @@ -0,0 +1,79 @@ +"""Startup draw async check.""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +from startup_stream_check import gfx2hlsl +from startup_stream_draw_check import pixel, vertex + + +def check(directory, consumer, backend, mode): + if mode not in ("async", "sync"): + return 2 + cache = directory / "cache" + cache.mkdir() + vs, ps, root, output = (directory / name for name in ("vs", "ps", "root", "pixels")) + vs.write_bytes(vertex()) + ps.write_bytes(pixel(False)) + args = [consumer, vs, ps, root] + env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_SHADER_CACHE=str(cache)) + env.setdefault("X2W_D3D12_DEBUG", "0") + for name in ("X2W_DRAW_ASYNC", "X2W_CX_ASYNC", "X2W_DRAW_PSO_LOCKED"): + env.pop(name, None) + subprocess.run(args, env=env, check=True) + subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True) + key = gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()) + + run_env = dict(env, X2W_CX_TEST_HOLD_EVENT=f"Local\\x2w_draw_hold_{os.getpid()}", + X2W_TEST_HOLD_RELEASE="first" if mode == "async" else "300") + if mode == "async": + run_env["X2W_DRAW_ASYNC"] = "1" + result = subprocess.run(args + [backend, output], env=run_env, capture_output=True, text=True, timeout=60) + print(result.stdout, end="") + log = result.stderr + for line in log.splitlines(): + if "X2W_DRAW_ASYNC" in line or "X2W_CX_TEST_HOLD_EVENT" in line or "x2w-d3d12-debug " in line or "-> drawn;" in line: + print(line) + if backend == "hardware" and result.returncode == 77: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + if result.returncode: + raise RuntimeError(f"consumer failed on {backend}: {result.returncode}\n{log}") + red, clear = bytes((255, 0, 0, 255)), bytes((0, 0, 255, 255)) + drawn = (red * 4 + clear * 4) * 4 + first, second = Path(str(output) + ".first").read_bytes(), output.read_bytes() + skip_line = f"x2w-draw {key:016x}: desktop pipeline not built yet, draw skipped and the build queued (X2W_DRAW_ASYNC)" + ready_line = f"x2w-draw {key:016x} ready (X2W_DRAW_ASYNC); 1 draws skipped while compiling" + held = f"x2w-draw {key:016x}: load held by X2W_CX_TEST_HOLD_EVENT (released)" + draws = log.count("-> drawn;") + want_first = clear * 32 if mode == "async" else drawn + failures = [] + if first != want_first: + failures.append(f"first draw: {first.hex()} want {want_first.hex()}") + if second != drawn: + failures.append(f"second draw: {second.hex()} want {drawn.hex()}") + if draws != (1 if mode == "async" else 2): + failures.append(f"{draws} '-> drawn;' lines") + if held not in log: + failures.append("the compile was not held and released") + if mode == "async" and (log.count(skip_line) != 1 or ready_line not in log): + failures.append("skip / ready lines missing") + if mode == "sync" and ("X2W_DRAW_ASYNC" in log): + failures.append("X2W_DRAW_ASYNC lines without the switch") + if any("x2w-d3d12-debug " in line and (" sev=0 " in line or " sev=1 " in line) for line in log.splitlines()): + failures.append("debug-layer error or corruption") + print(f"{backend} {mode}: first draw {'clear' if first == clear * 32 else 'red' if first == drawn else 'other'}, " + f"second {'red' if second == drawn else 'other'}, {draws} drawn lines") + if failures: + print("FAIL: " + "; ".join(failures)) + return 1 + print("PASS") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:])) diff --git a/tests/startup_draw_fma_check.py b/tests/startup_draw_fma_check.py new file mode 100644 index 0000000000..0393e2ad55 --- /dev/null +++ b/tests/startup_draw_fma_check.py @@ -0,0 +1,106 @@ +"""The multiply-add rule in draw stages (tools/startup/gfx2hlsl.py, X2W_DRAW_FMA; lead 000800 answer). + +RDNA 2 ISA: V_FMA_F32 / V_FMAC_F32 / V_FMAMK_F32 / V_FMAAK_F32 compute a * b + c with one rounding; V_MAD_F32 / +V_MAC_F32 / V_MADMK_F32 / V_MADAK_F32 round the product first. Rule (the same as mesh2hlsl's): +- exact (default): fused ops -> x2w_fma_exact = (float)fma((double)a, (double)b, (double)c); unfused ops -> + x2w_mad_precise = precise multiply then precise add; the manifest says `fma exact`; +- precise: both through x2w_mad_precise; `fma precise`; +- legacy: `a * b + c` as before, no manifest line. +Checked on synthetic vertex stages (VOP3 v_fma_f32 and v_mad_f32 into v4, exp pos0 v[4:7]): the emitted call, +the helper definitions, the manifest line; a stage with no multiply-add has no `fma` line and no helper. The +helpers' arithmetic in Python with exact rationals: on a case where a * b + c rounded twice differs from the fused +value, the binary64 fma rounded to binary32 equals the fused value and the precise form equals the two-rounding +value. With fxc available, a vs_5_1 shader with both helpers compiles. Not checked: a GPU readback. +""" +import os +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_sampler_heap_check import root_blob # noqa: E402 +from startup_stream_check import gfx2hlsl as G # noqa: E402 + +EXPORT = (0xf80008cf, 0x07060504, 0xbf810000) # exp pos0 v4, v5, v6, v7 done; s_endpgm +PS = struct.pack('<3I', 0xf800180f, 0, 0xbf810000) + + +def vop3(op, dst, a, b, c): + return (0xd4000000 | op << 16 | dst, (256 + a) | (256 + b) << 9 | (256 + c) << 18) + + +def pipeline(*ops): + words = [w for op in ops for w in vop3(*op)] + list(EXPORT) + vs = struct.pack('<%dI' % len(words), *words) + p = G.Pipeline(vs, PS, root_blob(flags=0)) + return [x[3] for x in G.decode(vs)], p.hlsl_vs(), p.manifest().split('\n') + + +def f32(x): + return struct.unpack(' nearest binary32 (ties to even), through the exact neighbours.""" + lo = f32(q) + return lo if Fraction(lo) == q else min((lo, *(struct.unpack(' x2w_fma_exact, unfused -> x2w_mad_precise, manifest fma exact/precise, legacy unchanged; ' + 'no multiply-add -> no line; fused value matched through binary64 where two roundings give 0; helpers %s' + % compiled) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_draw_heap_check.py b/tests/startup_draw_heap_check.py new file mode 100644 index 0000000000..edebf4cb78 --- /dev/null +++ b/tests/startup_draw_heap_check.py @@ -0,0 +1,75 @@ +"""Resource-heap (bindless) descriptors in a draw stage: manifest `heap 1`, behind X2W_DRAW_FEATURES=heap.""" +import os +import struct +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import VS_WORDS # noqa: E402 + + +def heap_root(): + rts0 = struct.pack('<6I', 2, 0, 24, 0, 0, 0x400) + part = b'RTS0' + struct.pack('> 1, 10 << 25] # s_load_dwordx8 s[16:23], s[8:9], s10 +V_MOV_V0_1 = 0x7e000000 | 0 << 17 | 1 << 9 | 129 # v_mov_b32 v0, 1 +V_MOV_V1_2 = 0x7e000000 | 1 << 17 | 1 << 9 | 130 # v_mov_b32 v1, 2 +IMAGE_LOAD = [0xf0000000 | 0xf << 8 | 1 << 3, 0 | 4 << 8 | (16 // 4) << 16] +EXPORT = [0xf800180f, 0x07060504] # exp mrt0 v4, v5, v6, v7 done vm + + +def words(*parts): + flat = [] + for p in parts: + flat += p if isinstance(p, list) else [p] + return struct.pack('<%dI' % (len(flat) + 1), *flat, 0xbf810000) + + +def main(): + ps = words(S_MOV_S10_64, S_LOAD_X8, V_MOV_V0_1, V_MOV_V1_2, IMAGE_LOAD, EXPORT) + text = [x[3] for x in G.decode(ps)] + assert text[1] == 's_load_dwordx8 s[16:23], s[8:9], s10', text + assert text[4] == 'image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D', text + try: + G.Pipeline(VS_WORDS, ps, heap_root(), features=()) + except G.Unsupported as error: + assert "s_load with a register offset through ('resheap',)" in str(error), str(error) + else: + raise AssertionError('heap load accepted with the feature off') + + pipe = G.Pipeline(VS_WORDS, ps, heap_root(), features=('heap',)) + hlsl, manifest = pipe.hlsl_ps(), pipe.manifest() + for line in ('ByteAddressBuffer heapmem : register(t0, space1);', + 'ByteAddressBuffer vinfo : register(t1, space1);', + 'uint x2w_vid(uint h) { return heapmem.Load(h) == 0x56573258u ? heapmem.Load(h + 4) : 0xffffffffu; }', + 'uint x2w_hix(uint h, uint k) { uint i = x2w_vid(h); return i < 90000u ? 8u + 8u * i + k : k; }', + 'Texture2D heaptex2d[720008] : register(t0, space2);', + 'h0 = 0x00000040u;', + 't = heaptex2d[NonUniformResourceIndex(x2w_hix(h0, 0u))].Load(int3(v0, v1, 0));'): + assert line in hlsl, (line, hlsl) + assert 'heaptex2da' not in hlsl and 'heapbuf' not in hlsl, 'only the kinds used are declared' + assert 'heap 1' in manifest.split('\n') and 'srv ' not in manifest, manifest + # The index helper, evaluated: ids below 90000 land at 8 + 8 * id + kind, others on the empty view kind. + hix = lambda i, k: 8 + 8 * i + k if i < 90000 else k # noqa: E731 + assert (hix(0, 0), hix(1, 0), hix(89999, 4), hix(0xffffffff, 2)) == (8, 16, 720004, 2) + assert hix(89999, 4) < 720008, 'the bounded arrays cover the whole view-id region' + # A heap descriptor's words are not numbers here: reading one is refused. + numeric = words(S_MOV_S10_64, S_LOAD_X8, 0x7e000000 | 4 << 17 | 1 << 9 | 17, # v_mov_b32 v4, s17 + V_MOV_V1_2, 0x7e000000 | 5 << 17 | 1 << 9 | 130, 0x7e000000 | 6 << 17 | 1 << 9 | 130, + 0x7e000000 | 7 << 17 | 1 << 9 | 130, EXPORT) + try: + G.Pipeline(VS_WORDS, numeric, heap_root(), features=('heap',)).hlsl_ps() + except G.Unsupported as error: + assert 'holding desc' in str(error), str(error) + else: + raise AssertionError('a heap descriptor word was read as a number') + print('heap: texel through a run-time heap offset; manifest heap 1; feature-off and numeric-word controls refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_draw_heapwords_check.py b/tests/startup_draw_heapwords_check.py new file mode 100644 index 0000000000..55d8e3eef3 --- /dev/null +++ b/tests/startup_draw_heapwords_check.py @@ -0,0 +1,70 @@ +"""buffer_load_format_* through a resource-heap descriptor in a draw stage: manifest `heapwords 1`.""" +import os +import struct +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import VS_WORDS # noqa: E402 +from startup_draw_heap_check import heap_root, words, S_MOV_S10_64, S_LOAD_X8, V_MOV_V0_1, V_MOV_V1_2, \ + IMAGE_LOAD, EXPORT # noqa: E402 + +S_LOAD_X4 = [0xf4000000 | 2 << 18 | 16 << 6 | 8 >> 1, 10 << 25] # s_load_dwordx4 s[16:19], s[8:9], s10 +FORMAT_X = [0xe0000000 | 0 << 18 | 1 << 13, 0 | 4 << 8 | 4 << 16 | 128 << 24] # buffer_load_format_x v4, v0, s[16:19], 0 idxen +MOVS = [0x7e000000 | n << 17 | 1 << 9 | 130 for n in (5, 6, 7)] # v_mov_b32 v5..v7, 2 + + +def hword(heapmem, vdesc, h, i): + """x2w_hword as emitted: token check at heapmem[h], id below 90000, else 0.""" + token, vid = heapmem.get(h, (0, 0)) + vid = vid if token == G.HEAP_TOKEN else 0xffffffff + return vdesc.get((vid, i), 0) if vid < 90000 else 0 + + +def main(): + ps = words(S_MOV_S10_64, S_LOAD_X4, V_MOV_V0_1, FORMAT_X, MOVS, EXPORT) + text = [x[3] for x in G.decode(ps)] + assert text[1] == 's_load_dwordx4 s[16:19], s[8:9], s10', text + assert text[3] == 'buffer_load_format_x v4, v0, s[16:19], 0 idxen', text + + for features in (('heap', 'bufword3'), ('heap', 'bufword3', 'uav')): + try: + G.Pipeline(VS_WORDS, ps, heap_root(), features=features).hlsl_ps() + except G.Unsupported as error: + assert 'buffer_load_format_x through heapdyn' in str(error), str(error) + else: + raise AssertionError('heap format load accepted without heapwords (%s)' % (features,)) + + pipe = G.Pipeline(VS_WORDS, ps, heap_root(), features=('heap', 'bufword3', 'heapwords')) + hlsl, manifest = pipe.hlsl_ps(), pipe.manifest() + for line in ('ByteAddressBuffer x2w_vdesc : register(t2, space1);', + 'uint x2w_hword(uint h, uint i) { uint id = x2w_vid(h); return id < 90000u ? ' + 'x2w_vdesc.Load(id * 32u + 4u * i) : 0u; }', + 'ByteAddressBuffer heapbuf[720008] : register(t0, space6);', + 'a = v0 * x2w_vstride(h0) + 0;', + 'v4 = x2w_fmt_load(heapbuf[NonUniformResourceIndex(x2w_hix(h0, 4u))], a, x2w_hword(h0, 3u), 0u);'): + assert line in hlsl, (line, hlsl) + assert 'uint x2w_fmt_load(' in hlsl, 'the format decoder is emitted' + lines = manifest.split('\n') + assert 'heap 1' in lines and 'heapwords 1' in lines and lines.index('heapwords 1') == lines.index('heap 1') + 1, manifest + assert not any(l.startswith('udsrc') and 'bufword3' in l for l in lines), manifest + + # the helper, evaluated: slot 64 holds view 7, whose word 3 is 0x00026fac (an arbitrary value) + heapmem = {64: (G.HEAP_TOKEN, 7), 96: (0x12345678, 7), 128: (G.HEAP_TOKEN, 90000)} + vdesc = {(7, 3): 0x00026fac, (7, 1): 0x00100000} + assert hword(heapmem, vdesc, 64, 3) == 0x00026fac and hword(heapmem, vdesc, 64, 1) == 0x00100000 + assert hword(heapmem, vdesc, 96, 3) == 0, 'a slot without the view token reads 0' + assert hword(heapmem, vdesc, 128, 3) == 0, 'an id at the limit reads 0' + assert hword(heapmem, vdesc, 32, 3) == 0, 'an empty slot reads 0' + + # Negative control: a heap program without a format load has neither vdesc nor `heapwords 1`. + plain = G.Pipeline(VS_WORDS, words(S_MOV_S10_64, S_LOAD_X8, V_MOV_V0_1, V_MOV_V1_2, IMAGE_LOAD, EXPORT), + heap_root(), features=('heap', 'bufword3', 'heapwords')) + assert 'x2w_vdesc' not in plain.hlsl_ps() and 'heapwords 1' not in plain.manifest().split('\n'), plain.manifest() + print('heapwords: heap typed load reads word 3 from vdesc (t2 space1); manifest heap 1 + heapwords 1; ' + 'refused without heapwords; helper evaluated on 4 slots; image-only heap program unchanged') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_draw_lock_split_check.py b/tests/startup_draw_lock_split_check.py new file mode 100644 index 0000000000..647469b975 --- /dev/null +++ b/tests/startup_draw_lock_split_check.py @@ -0,0 +1,135 @@ +"""Startup draw lock split check.""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_address_srv_check import prepare_draw_cache + +HLSL = ( + "ByteAddressBuffer constants : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " return asfloat(constants.Load4(0));\n" + "}\n" +) +RED = bytes((255, 0, 0, 255)) +BLUE = bytes((0, 0, 255, 255)) +THREADS, REPEAT = 2, 25 +SOURCE = Path(__file__).resolve().parent.parent / "src" / "startup_stubs" / "d3d12_draw.inl" + + +def sites(): + """Site ids of draw_translated read from the source lines: entry, tail, frame_copy_unlocked lookup and commit + (lookup + 1), and every site that exists only under the switch.""" + lines = SOURCE.read_text(encoding="utf-8", errors="replace").splitlines() + start = next(i for i, line in enumerate(lines) if line.startswith("bool draw_translated(")) + entry = tail = lookup = None + compare = next(i for i, line in enumerate(lines) if line.startswith("bool compare_draw_copy(")) + copy_tail = next(100000 + i + 1 for i in range(compare, len(lines)) if "lock_draw(100000 + __LINE__)" in lines[i]) + split_only = {copy_tail} + for i in range(start, len(lines)): + line, number = lines[i], 100000 + i + 1 + if line.startswith("}"): + break + if entry is None and "lock_draw(100000 + __LINE__)" in line: + entry = number + if "SplitRelock relock(split, 100000 + __LINE__)" in line: + split_only.add(number) + if "have = frame_copy_unlocked(" in line: + lookup = number + split_only.update((number, number + 1)) + if "if (split) lock_draw(100000 + __LINE__)" in line: + tail = number + split_only.add(number) + if None in (entry, tail, lookup, copy_tail): + raise RuntimeError(f"draw_translated site ids not found in {SOURCE}: entry {entry} tail {tail} lookup {lookup}") + return entry, tail, lookup, lookup + 1, copy_tail, split_only + + +def report_holds(log): + lines = [line for line in log.splitlines() if "x2w-draw lock times (fixture" in line] + if len(lines) != 1: + raise AssertionError(f"{len(lines)} fixture lock-times lines") + return {int(m.group(1)): int(m.group(2)) for m in re.finditer(r" (\d+) \S+ (\d+)/[\d.]+/[\d.]+, \d+/", lines[0])}, lines[0] + + +def run(directory, consumer, backend, mode, frame): + """frame "changed": every draw misses the frame-copy cache (red, then blue, then red again on the next frame); + "same": red twice, so after each thread's first draw the copies are cache hits.""" + entry, tail, lookup, commit, copy_tail, split_only = sites() + folder = directory / frame + folder.mkdir() + env, args, output = prepare_draw_cache(folder, consumer, HLSL, {"X2W_TEST_FRAME_COPY": frame}, "srv 0 buf table 0 0") + for name in ("X2W_DRAW_LOCK_SPLIT", "X2W_DRAW_COPY_SPLIT_MIN", "X2W_DRAW_ASYNC", "X2W_DRAW_SRV_IN_PLACE"): + env.pop(name, None) + env.update(X2W_TEST_THREADS=str(THREADS), X2W_TEST_REPEAT=str(REPEAT), X2W_DRAW_LOCK_TIMES="1") + if mode == "split": + env["X2W_DRAW_LOCK_SPLIT"] = "1" + if mode == "copy": + env["X2W_DRAW_COPY_SPLIT_MIN"] = "1" + if mode == "below": + env["X2W_DRAW_COPY_SPLIT_MIN"] = "1048576" + result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True, timeout=120) + print(result.stdout, end="") + if backend == "hardware" and result.returncode == 77: + print("No D3D12 feature-level 12 hardware adapter") + return None + if result.returncode: + raise RuntimeError(f"consumer failed on {backend}: {result.returncode}\n{result.stderr[-5000:]}") + holds, line = report_holds(result.stderr) + print(line) + draws = THREADS * REPEAT * 2 + wanted = (RED * 4 + BLUE * 4) * 4 if frame == "changed" else RED * 32 + failures = [] + for t in range(THREADS): + pixels = Path(f"{output}.t{t}").read_bytes() + if pixels != wanted: + failures.append(f"{frame} thread {t}: {pixels.hex()} want {wanted.hex()}") + if holds.get(entry) != draws: + failures.append(f"{frame} entry site {entry}: {holds.get(entry)} holds, want {draws}") + seen = sorted(site for site in split_only if site in holds) + if mode == "copy": + if seen != [copy_tail] or not 0 < holds.get(copy_tail, 0) < draws: + failures.append(f"{frame}: need only compare relock {copy_tail}, between first snapshot and final draw; got {seen}, {holds}") + elif mode == "split": + if copy_tail in holds: + failures.append(f"{frame}: copy-only relock active in broad split") + if holds.get(tail) != draws: + failures.append(f"{frame} tail site {tail}: {holds.get(tail)} holds, want {draws}") + if holds.get(lookup) != draws: + failures.append(f"{frame} frame_copy lookup site {lookup}: {holds.get(lookup)} holds, want {draws}") + misses = holds.get(commit, 0) + if frame == "changed" and misses != draws: + failures.append(f"changed: {misses} frame_copy commits (misses), want {draws}") + if frame == "same" and not THREADS <= misses < draws // 2: + failures.append(f"same: {misses} frame_copy commits (misses), want {THREADS} to {draws // 2 - 1} (mostly hits)") + elif seen: + failures.append(f"{frame}: split-only sites {seen} without the switch") + if any("x2w-d3d12-debug " in l and (" sev=0 " in l or " sev=1 " in l) for l in result.stderr.splitlines()): + failures.append(f"{frame}: debug-layer error or corruption") + print(f"{backend} {mode} {frame}: {THREADS} threads x {REPEAT} frames, entry {entry}={holds.get(entry)}, tail {tail}={holds.get(tail)}, " + f"frame_copy lookup {lookup}={holds.get(lookup)} commit {commit}={holds.get(commit)}, split-only sites in the report {seen}") + return failures + + +def check(directory, consumer, backend, mode): + if mode not in ("split", "copy", "below", "locked"): + return 2 + failures = [] + for frame in ("changed", "same"): + result = run(directory, consumer, backend, mode, frame) + if result is None: + return 77 + failures += result + if failures: + print("FAIL: " + "; ".join(failures)) + return 1 + print("PASS") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:])) diff --git a/tests/startup_draw_lock_times.cpp b/tests/startup_draw_lock_times.cpp new file mode 100644 index 0000000000..9fc19a39ab --- /dev/null +++ b/tests/startup_draw_lock_times.cpp @@ -0,0 +1,76 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Test = std::uint64_t(WINAPI*)(int, std::uint64_t, std::uint64_t); + +namespace { +struct SiteRow { long holds = -1; double hold_total = 0, hold_max = 0; long waits = 0; double wait_total = 0, wait_max = 0; }; +SiteRow find_site(const std::string& line, long id) +{ + SiteRow row; + const std::string key = " " + std::to_string(id) + " fixture "; + const std::size_t p = line.find(key); + if (p == std::string::npos) return row; + std::sscanf(line.c_str() + p + key.size(), "%ld/%lf/%lf, %ld/%lf/%lf", &row.holds, &row.hold_total, &row.hold_max, &row.waits, + &row.wait_total, &row.wait_max); + return row; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + const std::string mode = argv[1]; + if (mode != "on" && mode != "off") return 2; + wchar_t temp[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, temp)) return 3; + const std::wstring log_path = std::wstring(temp) + L"x2w_draw_lock_times_" + std::to_wstring(GetCurrentProcessId()) + L"_" + + std::to_wstring(GetTickCount64()) + L".log"; + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + HMODULE module = LoadLibraryW(L"d3d12_xs.dll"); + if (!module) return 4; + const auto test = reinterpret_cast(GetProcAddress(module, "x2w_draw_lock_times_test")); + if (!test) return 5; + std::vector threads; + for (int t = 1; t <= 3; ++t) + threads.emplace_back([test, t] { + for (int i = 0; i < 50; ++i) test(0, t == 3 ? 0 : 2000, static_cast(t)); + }); + for (auto& thread : threads) thread.join(); + const std::uint64_t reported = test(1, 0, 0); + + std::ifstream file(log_path, std::ios::binary); + const std::string log{std::istreambuf_iterator(file), {}}; + const std::size_t at = log.find("x2w-draw lock times (fixture"); + const std::string line = at == std::string::npos ? std::string() : log.substr(at, log.find('\n', at) - at); + int failures = 0; + if (mode == "off") { + std::printf("op 1 -> %llu (want 0); report line %s (want none)\n", static_cast(reported), line.empty() ? "none" : "present"); + if (reported != 0 || !line.empty()) ++failures; + } else { + std::printf("%s\n", line.empty() ? "no report line" : line.c_str()); + if (reported != 1 || line.empty()) ++failures; + double waited = 0; + for (long id : {999001L, 999002L, 999003L}) { + const SiteRow r = find_site(line, id); + std::printf("site %ld: holds %ld total %.1f ms max %.2f ms; waits %ld total %.1f ms max %.2f ms\n", id, r.holds, r.hold_total, r.hold_max, + r.waits, r.wait_total, r.wait_max); + waited += r.wait_total; + if (r.holds != 50) ++failures; + if (id != 999003 && (r.hold_total < 100.0 || r.hold_total > 1000.0 || r.hold_max < 2.0)) ++failures; + } + std::printf("waited over the three sites %.1f ms (want > 50)\n", waited); + if (waited <= 50.0) ++failures; + } + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; +} diff --git a/tests/startup_draw_srv_limit_check.py b/tests/startup_draw_srv_limit_check.py new file mode 100644 index 0000000000..1486dbf735 --- /dev/null +++ b/tests/startup_draw_srv_limit_check.py @@ -0,0 +1,63 @@ +"""Read the final SRV of a translated draw table on WARP and check its upper bound.""" +import os +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from startup_formatted_view_draw_check import CASES, CLEAR, PIXEL, TARGET, spec +from startup_stream_check import gfx2hlsl +from startup_stream_draw_check import vertex + + +def check(work, consumer, fxc): + cache = work / 'cache' + cache.mkdir() + vs, ps, root, output = (work / name for name in ('vs', 'ps', 'root', 'pixels')) + vs.write_bytes(vertex()) + ps.write_bytes(PIXEL) + 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), X2W_FXC=fxc, + X2W_DRAW_FEATURES='bufword3', X2W_TEST_FORMATTED_VIEW=spec(CASES[0])) + + def draw(): + result = subprocess.run([consumer, vs, ps, root, 'warp', output, str(TARGET)], env=env, + capture_output=True, text=True, timeout=60) + if result.returncode == 77: + raise SystemExit(77) + assert result.returncode == 0, result.stderr[-2000:] + assert not re.search(r'x2w-d3d12-debug.*sev=[012]\b', result.stderr), result.stderr[-2000:] + return struct.unpack('<4I', output.read_bytes()[:16]), result.stderr + + for _ in range(2): + draw() + subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', cache], env=env, check=True) + variant = next(p for p in cache.glob('*.txt') if 'rtv1' in p.read_text()) + hlsl = variant.with_suffix('.ps.hlsl') + source = hlsl.read_text() + original_manifest = variant.read_text() + assert 'srv 0 buf table 0 0' in original_manifest and 'register(t0)' in source + # Only the final slot names the typed view. Reading any filler slot returns a different value. + for slot in (31, 32, 63, 64): + entries = ['srv %d buf vb 7' % i for i in range(slot)] + ['srv %d buf table 0 0' % slot] + manifest = original_manifest.replace('srv 0 buf table 0 0', '\n'.join(entries)) + for kind in ('stride', 'bufword3'): + manifest = re.sub(r'(udsrc \d+ %s )0$' % kind, lambda m: m[1] + str(slot), manifest, flags=re.M) + variant.write_text(manifest.replace(' bufword3 ', ' descword3 ')) + hlsl.write_text(source.replace('register(t0)', 'register(t%d)' % slot)) + subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', variant.with_suffix('.ps.cso'), hlsl], + check=True, capture_output=True) + words, log = draw() + accepted = slot < 64 + assert ('-> drawn;' in log) == accepted, (slot, log[-2000:]) + assert words == (CASES[0][5] if accepted else CLEAR), (slot, words, log[-2000:]) + print('t%d: %s' % (slot, 'bit-exact' if accepted else 'over-limit translation refused')) + + +if __name__ == '__main__': + if not Path(sys.argv[2]).is_file(): + raise SystemExit(77) + with tempfile.TemporaryDirectory() as temp: + check(Path(temp), *sys.argv[1:]) diff --git a/tests/startup_draw_state.cpp b/tests/startup_draw_state.cpp new file mode 100644 index 0000000000..adaf4029f5 --- /dev/null +++ b/tests/startup_draw_state.cpp @@ -0,0 +1,295 @@ +// Draws through device slot 57 pipelines whose state block A carries hand-written DB_DEPTH_CONTROL, +// PA_SU_SC_MODE_CNTL and CB_TARGET_MASK words (pipeline_state_decode.h), into an 8x4 RGBA target with +// a D32 depth target, and writes each case's pixels to /. Whether the decoded state is +// applied is decided by the X2W_DRAW_STATE_* switches the driver script sets; this program only draws. +// No title data. +// +// usage: startup_draw_state [] +// Without : creates the stream pipelines only (their shader requests feed the offline translator). +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "startup_stream_setup.h" + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { + +using Word = std::uint64_t; +template Word ptr_arg(T* p) { return reinterpret_cast(p); } + +bool read_bytes(const char* path, std::vector& out) +{ + std::ifstream file(path, std::ios::binary); + out.assign(std::istreambuf_iterator(file), {}); + return !out.empty(); +} + +int pick_adapter(bool hardware, ComPtr& adapter) +{ + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; + if (!hardware) return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) ? 0 : 4; + ComPtr factory6; + if (FAILED(factory.As(&factory6))) return 77; + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory6->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 4; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 4; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + return 0; + } + } +} + +struct alignas(8) StageSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + D3D12_SHADER_BYTECODE shader; +}; +struct alignas(8) RootSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + ID3D12RootSignature* signature; +}; +struct PlainStream { + StageSubobject ps; + RootSubobject root; + StageSubobject vs; +}; + +void* create_stream_pso(void* device, void* root, const std::vector& vs, const std::vector& ps) +{ + using CreateStream = HRESULT(WINAPI*)(void*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); + PlainStream stream{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {ps.data(), ps.size()}}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, static_cast(root)}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, {vs.data(), vs.size()}}}; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + void* pso = nullptr; + return SUCCEEDED(reinterpret_cast((*static_cast(device))[86])(device, &desc, __uuidof(ID3D12PipelineState), &pso)) + ? pso : nullptr; +} + +// Slot 57 description as the stand-in reads it (tests/startup_stream_consumer.cpp): 64-bit words 0 (root +// signature), 1-2 (state block A and its size), 5-6 and 9-10 (vertex and pixel shader). The shaders are +// read at the first draw, so their storage outlives the pipeline here. +struct Slot57 { + std::vector desc = std::vector(0x300); + std::vector state_a = std::vector(0x200); +}; + +void* create_slot57(void* device, void* root, const std::vector& vs, const std::vector& ps, + const std::vector>& words, Slot57& keep) +{ + for (const auto& [offset, word] : words) std::memcpy(keep.state_a.data() + offset, &word, sizeof(word)); + const Word d[12] = {ptr_arg(root), ptr_arg(keep.state_a.data()), keep.state_a.size(), 0, 0, ptr_arg(vs.data()), vs.size(), 0, 0, + ptr_arg(ps.data()), ps.size(), 0}; + std::memcpy(keep.desc.data(), d, sizeof(d)); + using Create = HRESULT(WINAPI*)(void*, const void*, REFIID, void**); + void* pso = nullptr; + return SUCCEEDED(reinterpret_cast((*static_cast(device))[57])(device, keep.desc.data(), __uuidof(ID3D12PipelineState), &pso)) + ? pso : nullptr; +} + +// The depth target is cleared on the desktop device (list slot 51 is the stand-in's own subject). +int clear_depth_desktop(ID3D12Device* desktop, ID3D12Resource* depth_tex, float value) +{ + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; + ComPtr heap; + if (FAILED(desktop->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))) return 40; + const D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; + const D3D12_CPU_DESCRIPTOR_HANDLE handle = heap->GetCPUDescriptorHandleForHeapStart(); + desktop->CreateDepthStencilView(depth_tex, &dsv_desc, handle); + D3D12_COMMAND_QUEUE_DESC qd{}; + ComPtr queue; + ComPtr alloc; + ComPtr list; + ComPtr fence; + if (FAILED(desktop->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue))) || + FAILED(desktop->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc))) || + FAILED(desktop->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.Get(), nullptr, IID_PPV_ARGS(&list))) || + FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) return 41; + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {depth_tex, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE}; + list->ResourceBarrier(1, &b); + list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH, value, 0, 0, nullptr); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; + list->ResourceBarrier(1, &b); + if (FAILED(list->Close())) return 42; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), 1))) return 43; + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!ev) return 44; + const bool ok = SUCCEEDED(fence->SetEventOnCompletion(1, ev)) && WaitForSingleObject(ev, 10000) == WAIT_OBJECT_0; + CloseHandle(ev); + return ok ? 0 : 45; +} + +int execute_guest_list(void* queue, void* list, void* fence, UINT64 fence_value) +{ + if (FAILED(static_cast(invoke(list, 9)))) return 50; + void* lists[] = {list}; + invoke(queue, 10, 1, ptr_arg(lists)); + if (FAILED(static_cast(invoke(queue, 14, ptr_arg(fence), fence_value)))) return 51; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < fence_value && GetTickCount64() < deadline) Sleep(1); + return invoke(fence, 8) >= fence_value ? 0 : 53; +} + +// State block A offsets (vertex layout) and register fields used here. +constexpr unsigned a_shader_mask = 0x78, a_mode = 0xa0, a_depth = 0xb8, a_target_mask = 0xcc; +constexpr std::uint32_t z_less_write = 1u << 1 | 1u << 2 | 1u << 4; // Z_ENABLE, Z_WRITE_ENABLE, ZFUNC FRAG_LESS +constexpr std::uint32_t cull_front = 1u << 0, cull_back = 1u << 1, face_cw = 1u << 2; + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 7 && argc != 8) return 2; + std::vector vs_near, vs_far, ps_green, ps_red; + if (!read_bytes(argv[1], vs_near) || !read_bytes(argv[2], vs_far) || !read_bytes(argv[3], ps_green) || !read_bytes(argv[4], ps_red)) return 3; + const bool hardware = std::strcmp(argv[6], "hardware") == 0; + ComPtr adapter; + if (const int rc = pick_adapter(hardware, adapter)) return rc; + std::array parameters{}; + void* guest = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &guest))) return 5; + D3D12_ROOT_SIGNATURE_DESC root_desc{}; + ComPtr blob; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr))) return 6; + std::ofstream(argv[5], std::ios::binary).write(static_cast(blob->GetBufferPointer()), blob->GetBufferSize()); + void* root = nullptr; + if (FAILED(static_cast(invoke(guest, 16, 0, ptr_arg(blob->GetBufferPointer()), blob->GetBufferSize(), + ptr_arg(&__uuidof(ID3D12RootSignature)), ptr_arg(&root))))) return 7; + if (argc == 7) { + return create_stream_pso(guest, root, vs_near, ps_green) && create_stream_pso(guest, root, vs_far, ps_red) ? 0 : 9; + } + const std::string outdir = argv[7]; + + // Every case keeps all channels writable unless it sets the target mask itself. + const std::vector> rgba = {{a_shader_mask, 0xF}, {a_target_mask, 0xF}}; + auto with = [&](std::vector> extra) { + auto words = rgba; + words.insert(words.end(), extra.begin(), extra.end()); + return words; + }; + struct Case { + const char* name; + std::vector> words; + bool far_second; // also draw the far red triangle after the near green one, same state + UINT guest_clear = 0; // list slot 51 with these flags and guest_depth, after the desktop pre-clear + float desktop_depth = 1.0f; + float guest_depth = 1.0f; + }; + // The depth target is one resource for all cases and the shim never forgets a cleared target, so the cases that + // must see it uncleared run first. + const Case cases[] = { + {"uncleared", with({{a_depth, z_less_write}}), false, 0, 0.0f}, + // A stencil-only clear on a D32 target does not initialise depth: same as uncleared. + {"guest_clear_stencil_only", with({{a_depth, z_less_write}}), false, D3D12_CLEAR_FLAG_STENCIL, 0.0f}, + {"depth", with({{a_depth, z_less_write}}), true, D3D12_CLEAR_FLAG_DEPTH}, + // Negative control: bits 30-31 make the decoder refuse the word, so the draw keeps the state of before. + {"depth_refused", with({{a_depth, z_less_write | 1u << 30}}), true, D3D12_CLEAR_FLAG_DEPTH}, + {"no_state", with({}), true}, + {"cull_back", with({{a_mode, cull_back}}), false}, + {"cull_front", with({{a_mode, cull_front}}), false}, + {"cull_back_face1", with({{a_mode, cull_back | face_cw}}), false}, + {"mask_rg", {{a_shader_mask, 0xF}, {a_target_mask, 0x3}}, false}, + // List slot 51: a forwarded depth clear to 1 lets the near triangle pass LESS over a depth of 0. + {"guest_clear", with({{a_depth, z_less_write}}), false, D3D12_CLEAR_FLAG_DEPTH, 0.0f, 1.0f}, + // Negative control: a forwarded clear to 0 over a desktop depth of 1 makes LESS fail, so the value is forwarded. + {"guest_clear0", with({{a_depth, z_less_write}}), false, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0.0f}, + }; + std::vector keep(2 * std::size(cases)); + std::vector> psos; + for (std::size_t i = 0; i < std::size(cases); ++i) { + void* near_pso = create_slot57(guest, root, vs_near, ps_green, cases[i].words, keep[2 * i]); + void* far_pso = create_slot57(guest, root, vs_far, ps_red, cases[i].words, keep[2 * i + 1]); + if (!near_pso || !far_pso) return 10; + psos.emplace_back(near_pso, far_pso); + } + + ComPtr desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 20; + constexpr UINT width = 8, height = 4; + StreamTarget state{}; + state.count = 1; + state.attachments[0].row_bytes = width * 4; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const float clear_color[] = {0.0f, 0.0f, 1.0f, 1.0f}; + const D3D12_RESOURCE_DESC rtv_tex_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE rtv_clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0.0f, 0.0f, 1.0f, 1.0f}}; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &rtv_tex_desc, D3D12_RESOURCE_STATE_COMMON, &rtv_clear, + IID_PPV_ARGS(&state.attachments[0].texture)))) return 21; + ComPtr depth_tex; + const D3D12_RESOURCE_DESC dsv_tex_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, DXGI_FORMAT_D32_FLOAT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}; + // No optimized clear value: the cases clear to 0 and to 1. + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &dsv_tex_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&depth_tex)))) return 21; + const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; Word backing, bytes; } rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}, + dsv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}, 0, 0}; + void* dsv_heap = nullptr; + if (FAILED(static_cast(invoke(guest, 14, ptr_arg(&rtv_heap_desc), ptr_arg(&__uuidof(ID3D12DescriptorHeap)), ptr_arg(&state.rtv_heap)))) || + FAILED(static_cast(invoke(guest, 14, ptr_arg(&dsv_heap_desc), ptr_arg(&__uuidof(ID3D12DescriptorHeap)), ptr_arg(&dsv_heap))))) return 22; + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast(invoke(state.rtv_heap, 9))}; + const D3D12_CPU_DESCRIPTOR_HANDLE dsv{static_cast(invoke(dsv_heap, 9))}; + const D3D12_RENDER_TARGET_VIEW_DESC rtv_view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + const D3D12_DEPTH_STENCIL_VIEW_DESC dsv_view{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; + invoke(guest, 20, ptr_arg(state.attachments[0].texture.Get()), ptr_arg(&rtv_view), rtv.ptr); + invoke(guest, 21, ptr_arg(depth_tex.Get()), ptr_arg(&dsv_view), dsv.ptr); + D3D12_COMMAND_QUEUE_DESC qd{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast(invoke(guest, 8, ptr_arg(&qd), ptr_arg(&__uuidof(ID3D12CommandQueue)), ptr_arg(&state.queue)))) || + FAILED(static_cast(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, ptr_arg(&__uuidof(ID3D12CommandAllocator)), ptr_arg(&state.allocator)))) || + FAILED(static_cast(invoke(guest, 73, ptr_arg(list_desc), ptr_arg(state.allocator), 0, ptr_arg(&__uuidof(ID3D12GraphicsCommandList)), + ptr_arg(&state.list)))) || + FAILED(static_cast(invoke(guest, 36, 0, 0, ptr_arg(&__uuidof(ID3D12Fence)), ptr_arg(&state.fence))))) return 23; + const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; + const D3D12_RECT rect{0, 0, 4, static_cast(height)}; + + UINT64 fence_value = 0; + for (std::size_t i = 0; i < std::size(cases); ++i) { + if (const int rc = clear_depth_desktop(desktop.Get(), depth_tex.Get(), cases[i].desktop_depth)) return rc; + if (FAILED(static_cast(invoke(state.allocator, 8)))) return 24; + if (FAILED(static_cast(invoke(state.list, 139, ptr_arg(state.allocator))))) return 25; + invoke(state.list, 52, rtv.ptr, ptr_arg(clear_color)); + invoke(state.list, 21, 1, ptr_arg(&viewport)); + invoke(state.list, 22, 1, ptr_arg(&rect)); + invoke(state.list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(state.list, 50, 1, ptr_arg(&rtv), FALSE, ptr_arg(&dsv)); + if (cases[i].guest_clear) { + // Typed call: the depth value is a float argument (xmm3), which invoke cannot pass. + using ClearDepth = void(WINAPI*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, FLOAT, UINT8, UINT, const D3D12_RECT*); + reinterpret_cast((*static_cast(state.list))[51])(state.list, dsv, static_cast(cases[i].guest_clear), + cases[i].guest_depth, 0, 0, nullptr); + } + invoke(state.list, 25, ptr_arg(psos[i].first)); + invoke(state.list, 12, 3, 1); + if (cases[i].far_second) { + invoke(state.list, 25, ptr_arg(psos[i].second)); + invoke(state.list, 12, 3, 1); + } + if (const int rc = execute_guest_list(state.queue, state.list, state.fence, ++fence_value)) return rc; + if (const int rc = read_stream_target(desktop.Get(), state, (outdir + "/" + cases[i].name).c_str())) return rc; + } + return 0; +} diff --git a/tests/startup_draw_state_check.py b/tests/startup_draw_state_check.py new file mode 100644 index 0000000000..61a0bc6e09 --- /dev/null +++ b/tests/startup_draw_state_check.py @@ -0,0 +1,112 @@ +"""Decoded fixed-function state on translated slot 57 draws (src/startup_stubs/pipeline_state_decode.h,""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_stream_check import gfx2hlsl +from startup_stream_depth_check import vertex +from startup_stream_draw_check import pixel + +GREEN, RED, BLUE, CYAN = (0, 255, 0, 255), (255, 0, 0, 255), (0, 0, 255, 255), (0, 255, 255, 255) +SWITCHES = ("X2W_DRAW_STATE", "X2W_DRAW_STATE_DEPTH", "X2W_DRAW_STATE_CULL", "X2W_DRAW_STATE_BLEND", "X2W_DRAW_STATE_CULL_FLIP", + "X2W_DRAW_STATE_DEPTH_CLEAR", "X2W_DRAW_STATE_DEPTH_UNCLEARED") +GROUPS = {"X2W_DRAW_STATE_DEPTH": "1", "X2W_DRAW_STATE_CULL": "1", "X2W_DRAW_STATE_BLEND": "1"} +MODES = { + "off": {}, + "on": dict(GROUPS, X2W_DRAW_STATE_DEPTH_CLEAR="1"), + "on-noclear": GROUPS, + "on-uncleared": dict(GROUPS, X2W_DRAW_STATE_DEPTH_CLEAR="1", X2W_DRAW_STATE_DEPTH_UNCLEARED="1"), + "master-off": dict(GROUPS, X2W_DRAW_STATE="0", X2W_DRAW_STATE_DEPTH_CLEAR="1"), +} +BEFORE = {"uncleared": GREEN, "guest_clear_stencil_only": GREEN, "depth": RED, "depth_refused": RED, "no_state": RED, + "cull_back": GREEN, "cull_front": GREEN, "cull_back_face1": GREEN, "mask_rg": GREEN, "guest_clear": GREEN, + "guest_clear0": GREEN} +DECODED = dict(BEFORE, depth=GREEN, cull_front=BLUE, cull_back_face1=BLUE, mask_rg=CYAN, guest_clear0=BLUE) +EXPECTED = { + "off": BEFORE, + "on": DECODED, + # Nothing forwards the guest clears, so no depth target counts as initialised and every depth test stays off. + "on-noclear": dict(DECODED, depth=RED, guest_clear0=GREEN), + "on-uncleared": dict(DECODED, uncleared=BLUE, guest_clear_stencil_only=BLUE), + "master-off": BEFORE, +} +CLEARS = ["flags 0x2 depth 1 ", "flags 0x1 depth 1 ", "flags 0x1 depth 1 ", "flags 0x1 depth 1 ", "flags 0x1 depth 0 "] + + +def left(pixels, name): + assert len(pixels) == 8 * 4 * 4, f"{name}: {len(pixels)} bytes" + drawn = None + for y in range(4): + for x in range(8): + texel = tuple(pixels[(y * 8 + x) * 4:(y * 8 + x) * 4 + 4]) + if x >= 4: + assert texel == BLUE, f"{name}: outside the scissor ({x}, {y}) is {texel}" + elif drawn is None: + drawn = texel + else: + assert texel == drawn, f"{name}: ({x}, {y}) is {texel}, (0, 0) is {drawn}" + return drawn + + +def check(directory, program, backend): + cache = directory / "cache" + cache.mkdir() + vs_near, vs_far, ps_green, ps_red, root = (directory / n for n in ("vs_near", "vs_far", "ps_green", "ps_red", "root")) + vs_near.write_bytes(vertex(0x3e800000)) # z = 0.25 + vs_far.write_bytes(vertex(0x3f400000)) # z = 0.75 + ps_green.write_bytes(pixel(True)) + ps_red.write_bytes(pixel(False)) + base = {k: v for k, v in os.environ.items() if k not in SWITCHES} + base.update(X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", X2W_SHADER_CACHE=str(cache)) + base.setdefault("X2W_D3D12_DEBUG", "1") + args = [str(program), str(vs_near), str(vs_far), str(ps_green), str(ps_red), str(root), backend] + request = subprocess.run(args, env=base, capture_output=True, text=True) + if backend == "hardware" and request.returncode == 77: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + if request.returncode: + raise RuntimeError(f"request run failed: {request.returncode}\n{request.stderr}") + subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=base, check=True) + + for mode, switches in MODES.items(): + out = directory / mode + out.mkdir() + run = subprocess.run(args + [str(out)], env=dict(base, **switches), capture_output=True, text=True) + if run.returncode or "-> drawn;" not in run.stderr: + raise RuntimeError(f"{mode}: draw failed on {backend}: {run.returncode}\n{run.stderr[-3000:]}") + # The cases clear depth to 0 and to 1, so the debug layer's clear-value performance warnings (820 mismatching + # clear value, 821 no clear value at creation) are expected; every other warning or error fails. + errors = [line for line in run.stderr.splitlines() + if re.search(r"x2w-d3d12-debug.*sev=[012]\b", line) and not re.search(r"sev=2 id=82[01] ", line)] + assert not errors, f"{mode}: debug layer: {errors[:4]}" + on = mode.startswith("on") + expected = EXPECTED[mode] + decoded_psos = run.stderr.count(", decoded state") + switch_line = [line for line in run.stderr.splitlines() if "x2w-draw-state switches:" in line] + assert switch_line, f"{mode}: no switch line" + assert ("depth 1 cull 1" in switch_line[0]) == on, f"{mode}: {switch_line[0]}" + clears = [line for line in run.stderr.splitlines() if "x2w-render ClearDepthStencilView" in line] + if mode in ("on", "on-uncleared"): + assert len(clears) == len(CLEARS) and all(c in line for c, line in zip(CLEARS, clears)), clears + else: + assert not clears, f"{mode}: slot 51 forwarded: {clears}" + assert (decoded_psos > 0) == on, f"{mode}: {decoded_psos} pipelines with decoded state" + assert "decoded state refused" not in run.stderr, f"{mode}: a decoded PSO failed creation" + got = {name: left((out / name).read_bytes(), f"{mode} {name}") for name in expected} + print(f"{backend} {mode}: " + ", ".join(f"{n} {c}" for n, c in got.items()) + f"; PSOs with decoded state {decoded_psos}") + wrong = {name: (got[name], colour) for name, colour in expected.items() if got[name] != colour} + assert not wrong, f"{mode}: drew / expected {wrong}" + print(f"startup_draw_state: PASS on {backend} (off and X2W_DRAW_STATE=0 draw as before; on: depth LESS keeps near green, " + f"CULL_FRONT and FACE 1 + CULL_BACK cull the counter-clockwise triangle, CULL_BACK keeps it, target mask 0x3 keeps " + f"blue; refused depth word draws as before; slot 51 depth clear forwarded only with X2W_DRAW_STATE_DEPTH_CLEAR=1, " + f"a clear to 0 makes LESS fail; no depth test against a target no forwarded depth clear initialised, " + f"X2W_DRAW_STATE_DEPTH_UNCLEARED=1 restores it and hides the near triangle)") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:])) diff --git a/tests/startup_draw_uav.cpp b/tests/startup_draw_uav.cpp new file mode 100644 index 0000000000..c2f16c2bc3 --- /dev/null +++ b/tests/startup_draw_uav.cpp @@ -0,0 +1,313 @@ +// Translated draws with UAV stores and resource-heap reads (tests/startup_draw_uav_check.py). Title buffers +// are private allocations: the stand-in opens them as desktop heaps, so the stores must reach these pages. +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using Word = std::uint64_t; +Word invoke(void*, unsigned, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0); +namespace { +template Word ptr(T* value) { return reinterpret_cast(value); } +std::uint32_t* uav_memory; +wchar_t uav_mode[32]; + +bool mode_is(const wchar_t* name) { return std::wcscmp(uav_mode, name) == 0; } + +std::uint32_t* private_pages() +{ + return static_cast(VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); +} + +// A one-entry shader-visible view heap whose descriptor memory is `backing` (0: the stand-in's own). +void* view_heap(void* guest, void* backing, UINT entries = 1) +{ + struct Extended { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word address, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, entries, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, ptr(backing), backing ? 65536u : 0u}; + void* heap = nullptr; + if (FAILED(static_cast(invoke(guest, 14, ptr(&heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&heap))))) return nullptr; + return heap; +} + +void* placed(void* guest, void* memory, const D3D12_RESOURCE_DESC& desc) +{ + void* resource = nullptr; + if (FAILED(static_cast(invoke(guest, 133, ptr(memory), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + ptr(&__uuidof(ID3D12Resource)), ptr(&resource))))) return nullptr; + return resource; +} + +// Modes tex, tex-noflag, tex-uint: entry 0 is a view of an 8x4 texture (UAV-capable RGBA8, a plain RGBA8 texture +// with a shader-resource view, or an RGBA8 typeless texture with an R8G8B8A8_UINT UAV). +int bind_texture_entry(void* guest, Word cpu) +{ + const bool uav_flag = !mode_is(L"tex-noflag"); + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 8, 4, 1, 1, + mode_is(L"tex-uint") ? DXGI_FORMAT_R8G8B8A8_TYPELESS : DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + uav_flag ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE}; + void* texture = placed(guest, private_pages(), desc); + if (!texture) return 46; + if (uav_flag) { + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{mode_is(L"tex-uint") ? DXGI_FORMAT_R8G8B8A8_UINT : DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(guest, 19, ptr(texture), 0, ptr(&uav), cpu); + } else { + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Texture2D.MipLevels = 1; + invoke(guest, 18, ptr(texture), ptr(&srv), cpu); + } + return 0; +} + +// Mode heap: the view heap's memory is a private allocation (read in place as heapmem); entry 0 is a raw +// buffer view of a placed buffer whose first dword is 77. +int bind_heap_entry(void* guest, Word cpu) +{ + std::uint32_t* memory = private_pages(); + if (!memory) return 45; + memory[0] = 77; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 256; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + void* buffer = placed(guest, memory, desc); + if (!buffer) return 47; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer.NumElements = 64; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + invoke(guest, 18, ptr(buffer), ptr(&srv), cpu); + return 0; +} + +int bind_heap_memory_entry(void* guest, Word cpu, const wchar_t* path) +{ + std::ifstream input(path, std::ios::binary); + const std::vector bytes{std::istreambuf_iterator(input), std::istreambuf_iterator{}}; + if (bytes.empty()) return 43; + void* memory = VirtualAlloc(nullptr, bytes.size() + (1u << 20), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!memory) return 45; + std::memcpy(memory, bytes.data(), bytes.size()); + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 256, 256, 1, 9, DXGI_FORMAT_BC1_UNORM, {1, 0}, + static_cast(0x105), static_cast(0x300000)}; + struct ViewAt { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + Word address; + Word tail[2]; + } v{}; + static_assert(offsetof(ViewAt, address) == 0x28 && sizeof(ViewAt) == 0x40); + v.view.Format = desc.Format; + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.view.Texture2D.MipLevels = 9; + v.address = ptr(memory); + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + return 0; +} + +int bind_heap_texture_entry(void* guest, Word cpu) +{ + wchar_t surface[MAX_PATH]{}; + const DWORD length = GetEnvironmentVariableW(L"X2W_TEST_HEAPTEX_SURFACE", surface, MAX_PATH); + if (length && length < MAX_PATH) return bind_heap_memory_entry(guest, cpu, surface); + auto* memory = reinterpret_cast(private_pages()); + if (!memory) return 45; + for (unsigned y = 0; y < 4; ++y) + for (unsigned x = 0; x < 8; ++x) { + unsigned char* t = memory + y * 256 + x * 4; + t[0] = static_cast(10 + 20 * x); + t[1] = static_cast(30 + 40 * y); + t[2] = 7; + t[3] = 255; + } + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 8, 4, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + void* texture = placed(guest, memory, desc); + if (!texture) return 46; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Texture2D.MipLevels = 1; + invoke(guest, 18, ptr(texture), ptr(&srv), cpu); + return 0; +} + +int bind_memory_buffer_entries(void* guest, Word cpu, UINT increment) +{ + if (increment < 32 || 128 % increment) return 48; + auto* heap_bytes = reinterpret_cast(cpu); + for (std::uint32_t m = 0; m < 5; ++m) { + const std::uint32_t link = m + 1; + std::memset(heap_bytes + m * increment, 0, increment); + std::memcpy(heap_bytes + m * increment, &link, 4); + } + std::uint32_t* decoy = private_pages(); + std::uint32_t* memory = private_pages(); + if (!decoy || !memory) return 45; + decoy[0] = 55; + memory[0] = 99; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 256; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + void* buffer = placed(guest, decoy, desc); + if (!buffer) return 47; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer.NumElements = 64; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + invoke(guest, 18, ptr(buffer), ptr(&srv), cpu + increment); + if (!mode_is(L"membuf-link")) { + struct ViewAt { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + Word address; + Word tail[2]; + } v{}; + static_assert(offsetof(ViewAt, address) == 0x28 && sizeof(ViewAt) == 0x40); + v.view = srv; + // membuf-refused / membuf-rewrite: null address, refused null_address + v.address = mode_is(L"membuf-refused") || mode_is(L"membuf-rewrite") ? 0 : ptr(memory); + if (mode_is(L"membuf-structured")) { + v.view.Format = DXGI_FORMAT_UNKNOWN; + v.view.Buffer.NumElements = 4; + v.view.Buffer.StructureByteStride = 16; + v.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; + } else if (mode_is(L"membuf-typed")) { + v.view.Format = DXGI_FORMAT_R32_UINT; + v.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; + } else if (std::wcsncmp(uav_mode, L"membuf-unaligned", 16) == 0) { + memory[0] = 0; + memory[5] = 99; + if (!placed(guest, memory, desc)) return 47; + v.address = ptr(memory) + 20; + v.view.Format = DXGI_FORMAT_UNKNOWN; + v.view.Buffer.NumElements = 4; + v.view.Buffer.StructureByteStride = 12; + v.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; + } + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + if (mode_is(L"membuf-rewrite")) { + // The title patches the descriptor it created in place: the V# base (word 0, word 1 bits 0-15) of the + // memory, the rest as it was (with X2W_BUFFER_HEAP_INDEX, the refused-view marker's description). + const std::uint64_t base = ptr(memory); + std::uint32_t w[2]; + std::memcpy(w, heap_bytes, sizeof w); + w[0] = static_cast(base); + w[1] = (w[1] & 0xffff0000u) | static_cast((base >> 32) & 0xffff); + std::memcpy(heap_bytes, w, sizeof w); + } + } + std::memcpy(heap_bytes + 128, heap_bytes, 32); + std::uint32_t copied[4]; + std::memcpy(copied, heap_bytes + 128, sizeof copied); + std::printf("membuf entry words: %08x %08x %08x %08x\n", copied[0], copied[1], copied[2], copied[3]); + std::fflush(stdout); + return 0; +} + +// A 64 KiB placed buffer over `memory` (title memory of a resource for CopyBufferRegion). +void* memory_buffer(void* guest, void* memory) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 65536; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return placed(guest, memory, desc); +} +void hardware_descriptor(Word cpu, Word base, std::uint32_t stride = 0) +{ + // gfx10 buffer descriptor: base [47:0], stride [61:48] (0 unless given), 256 records, word 3 a marker the shader + // checks. With a stride the record count is in records: 16 records of `stride` bytes. + const std::uint32_t words[8] = {static_cast(base), (static_cast(base >> 32) & 0xffff) | stride << 16, + stride ? 16u : 256u, 0x12345678u}; + std::memcpy(reinterpret_cast(cpu), words, sizeof(words)); +} +void* copy_dest; +void* copy_source; +Word copy_dest_offset, copy_source_offset; +std::uint32_t* copy_memory; // allocation of the copy destination +} + +// X2W_TEST_DRAW_UAV=. aligned|misaligned|uavbase: entry 0 is a hardware buffer descriptor at title + 64 +// or + 68 of a private allocation. Two draws, one column each. +int draw_uav_stores(ID3D12Device* desktop, void* guest, void* list) +{ + D3D12_FEATURE_DATA_EXISTING_HEAPS heaps{}; + if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &heaps, sizeof(heaps))) || !heaps.Supported) return 77; + GetEnvironmentVariableW(L"X2W_TEST_DRAW_UAV", uav_mode, 32); + const bool heap_texture_mode = mode_is(L"heaptex"); + const bool membuf_mode = std::wcsncmp(uav_mode, L"membuf", 6) == 0; + const bool heap_mode = mode_is(L"heap") || heap_texture_mode || membuf_mode; + // Heap draws need the console's 32-byte view slots (the title's own shader arithmetic). + std::printf("view increment %u\n", desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + std::fflush(stdout); + const bool copy_mode = std::wcsncmp(uav_mode, L"copy", 4) == 0; + void* heap = view_heap(guest, heap_mode ? private_pages() : nullptr, membuf_mode ? 5 : copy_mode ? 2 : 1); + if (!heap) return 42; + const Word cpu = invoke(heap, 9); + if (!cpu) return 42; + if (membuf_mode) { + if (const int rc = bind_memory_buffer_entries(guest, cpu, desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV))) + return rc; + } else if (heap_texture_mode) { + if (const int rc = bind_heap_texture_entry(guest, cpu)) return rc; + } else if (std::wcsncmp(uav_mode, L"tex", 3) == 0) { + if (const int rc = bind_texture_entry(guest, cpu)) return rc; + } else if (heap_mode) { + if (const int rc = bind_heap_entry(guest, cpu)) return rc; + } else if (copy_mode) { + // copy-*: entry 0 (uav 0) = title + 64 of allocation A, entry 1 (srv 0) = title + 0x400 of A (copy-same) or + // of a second allocation B. Between the two draws the list copies A + 64 (128 bytes) to the srv range. + uav_memory = private_pages(); + std::uint32_t* other = mode_is(L"copy-two") ? private_pages() : uav_memory; + if (!uav_memory || !other) return 45; + copy_memory = other; + copy_source = memory_buffer(guest, uav_memory); + copy_dest = other == uav_memory ? copy_source : memory_buffer(guest, other); + if (!copy_source || !copy_dest) return 47; + copy_source_offset = 64; + copy_dest_offset = 0x400; + hardware_descriptor(cpu, ptr(uav_memory) + 64); + hardware_descriptor(cpu + 32, ptr(other) + 0x400); + } else { + uav_memory = private_pages(); + if (!uav_memory) return 45; + const bool stride_mode = std::wcsncmp(uav_mode, L"stride", 6) == 0; + hardware_descriptor(cpu, ptr(uav_memory) + (mode_is(L"aligned") || stride_mode ? 64 : 68), mode_is(L"stride16") ? 16u : 0u); + } + invoke(list, 32, 1, ptr(&heap)); + invoke(list, 36, 0, invoke(heap, 10)); + // copy-twice: three strips; a second copy after draw 2 takes A + 68 (what draw 2 stored), and draw 3 reads it. + const LONG strips = mode_is(L"copy-twice") ? 3 : 2; + for (LONG x = 0; x < strips; ++x) { + const D3D12_RECT strip{x, 0, x + 1, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + // CopyBufferRegion(dest, dest offset, source, source offset, bytes); copy-none: no copy (negative control) + if (x < strips - 1 && copy_dest && !mode_is(L"copy-none")) + invoke(list, 15, ptr(copy_dest), copy_dest_offset, ptr(copy_source), copy_source_offset + 4 * x, 128); + } + return 0; +} + +// After the list completed: the title memory as the CPU sees it. +void report_uav_stores() +{ + if (!uav_memory) return; + std::printf("uav memory:"); + for (int i = 0; i < 64; ++i) std::printf(" %u", uav_memory[i]); + if (copy_dest) { // copy-*: the copied range as the CPU sees it (title + 0x400 of the destination allocation) + const auto* copied = copy_memory + 0x100; + std::printf("\ncopied:"); + for (int i = 0; i < 32; ++i) std::printf(" %u", copied[i]); + } + std::printf("\n"); + std::fflush(stdout); +} diff --git a/tests/startup_draw_uav_check.py b/tests/startup_draw_uav_check.py new file mode 100644 index 0000000000..d875bc650b --- /dev/null +++ b/tests/startup_draw_uav_check.py @@ -0,0 +1,289 @@ +"""Startup draw uav check.""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_stream_draw_check import gfx2hlsl, pixel, vertex + +MARK = 0x12345678 +CLEAR = bytes((0, 0, 255, 255)) + + +def buffer_hlsl(count, base): + uds = " ".join(f"uint ud{i};" for i in range(count + (3 if base else 2))) + offset = f"ud{count + 2} + " if base else "" + return ( + f"cbuffer entry : register(b0) {{ {uds} }};\n" + "ByteAddressBuffer t0 : register(t0);\n" + "RWByteAddressBuffer u0 : register(u0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint2 q = uint2(p.xy);\n" + " uint i = q.y * 8 + q.x;\n" + " uint seen = t0.Load(q.y * 32);\n" # what an earlier draw stored for column 0 of this row + f" uint marks = (ud{count} == {MARK}u ? 0u : 500000u) + (ud{count + 1} == {MARK}u ? 0u : 900000u);\n" + f" u0.Store({offset}i * 4, seen + 1000 + i + marks);\n" + " return float4(seen ? 1 : 0, 1, 0, 1);\n" + "}\n" + ) + + +def stride_hlsl(count): + """Startup draw uav check.""" + uds = " ".join(f"uint ud{i};" for i in range(count + 1)) + return ( + f"cbuffer entry : register(b0) {{ {uds} }};\n" + "RWByteAddressBuffer u0 : register(u0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + f" u0.Store(0u * ud{count}, 111u);\n" + f" u0.Store(1u * ud{count}, 222u);\n" + " return float4(0, 1, 0, 1);\n" + "}\n" + ) + + +TEX_HLSL = ( + "RWTexture2D u0 : register(u0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " u0[uint2(p.xy)] = float4(0.25, 0.5, 0.75, 1);\n" + " return float4(0, 1, 0, 1);\n" + "}\n" +) + +HEAP_HLSL = ( + "ByteAddressBuffer heapmem : register(t0, space1);\n" + "ByteAddressBuffer vinfo : register(t1, space1);\n" + "ByteAddressBuffer heapbuf[720008] : register(t0, space6);\n" + "uint vid(uint h) { return heapmem.Load(h) == 0x56573258u ? heapmem.Load(h + 4) : 0xffffffffu; }\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint i = vid(0);\n" + " uint k = i < 90000u ? 8u + 8u * i + 4u : 4u;\n" + " uint v = heapbuf[NonUniformResourceIndex(k)].Load(0);\n" + " return float4(v / 255.0, i < 90000u ? 1 : 0, 0, 1);\n" + "}\n" +) + + +HEAP_TEXTURE_MODES = {"heaptex": {"X2W_HEAP_TEXTURE_UPLOAD": "1"}, "heaptex-off": {}, + "heaptex-detile": {"X2W_HEAP_TEXTURE_UPLOAD": "1", "X2W_MEMORY_SRV_DETILE": "1"}, + "heaptex-detile-noupload": {"X2W_MEMORY_SRV_DETILE": "1"}} +HEAP_TEXTURE_HLSL = ( + "ByteAddressBuffer heapmem : register(t0, space1);\n" + "ByteAddressBuffer vinfo : register(t1, space1);\n" + "Texture2D heaptex2d[720008] : register(t0, space2);\n" + "uint vid(uint h) { return heapmem.Load(h) == 0x56573258u ? heapmem.Load(h + 4) : 0xffffffffu; }\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint i = vid(0);\n" + " uint k = i < 90000u ? 8u + 8u * i : 0u;\n" + " return heaptex2d[NonUniformResourceIndex(k)].Load(int3(uint2(p.xy), 0));\n" + "}\n" +) +# BC1 solid blocks, id = x | y << 6 at mip 0 (tests/gfx10_layout_check.cpp pattern); 8 pixels x 512 blocks each. +HEAP_DETILE_HLSL = ( + "ByteAddressBuffer heapmem : register(t0, space1);\n" + "ByteAddressBuffer vinfo : register(t1, space1);\n" + "Texture2D heaptex2d[720008] : register(t0, space2);\n" + "uint vid(uint h) { return heapmem.Load(h) == 0x56573258u ? heapmem.Load(h + 4) : 0xffffffffu; }\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint i = vid(0);\n" + " uint k = i < 90000u ? 8u + 8u * i : 0u;\n" + " uint2 q = uint2(p.xy);\n" + " uint bad = 0, n = 0;\n" + " [loop] for (uint b = q.y * 2u + q.x; b < 4096u; b += 8u) {\n" + " uint x = b % 64u, y = b / 64u;\n" + " float4 c = heaptex2d[NonUniformResourceIndex(k)].Load(int3(4 * x, 4 * y, 0));\n" + " uint id = (uint(round(c.r * 31)) << 11) | (uint(round(c.g * 63)) << 5) | uint(round(c.b * 31));\n" + " if (id != (x | (y << 6))) bad++;\n" + " n++;\n" + " }\n" + " return float4(bad ? 0 : 1, n == 512u ? 1 : 0, 0, 1);\n" + "}\n" +) + +MEMBUF_HLSL = ( + "ByteAddressBuffer t0 : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint v = t0.Load(0);\n" + " return float4(v & 255u, (v >> 8) & 255u, (v >> 16) & 255u, v >> 24) / 255.0;\n" + "}\n" +) + +COPY_ENV = {"copy-same": "gpu", "copy-two": "gpu", "copy-twice": "gpu", "copy-none": "gpu", "copy-cpu": "1"} + + +def run_mode(directory, consumer, backend, mode, extra_env=None): + cache = directory / mode / "cache" + cache.mkdir(parents=True) + vs, ps, root, output = (directory / mode / name for name in ("vs", "ps", "root", "pixels")) + vs.write_bytes(vertex()) + ps.write_bytes(pixel(False)) + env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_D3D12_DEBUG="0", X2W_D3D12_DEVICE_NOOP="1", X2W_SHADER_CACHE=str(cache), + X2W_TEST_DRAW_UAV="copy-same" if mode == "copy-cpu" else "heaptex" if mode in HEAP_TEXTURE_MODES else mode, + X2W_TRAP_LOG=str(directory / mode / "trap.log")) + if mode in COPY_ENV: + env["X2W_D3D12_COPY_BUFFER"] = COPY_ENV[mode] + env.update(HEAP_TEXTURE_MODES.get(mode, {})) + env.update(extra_env or {}) + args = [consumer, vs, ps, root] + subprocess.run(args, env=env, check=True) + subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True) + manifest, = cache.glob("*.txt") + text = manifest.read_text(encoding="ascii") + count = len(re.findall(r"^udsrc ", text, re.M)) + if re.search(r"^(srv|uav|heap) ", text, re.M): + raise AssertionError(f"the synthetic manifest already binds resources:\n{text}") + if mode.startswith("tex"): + lines, hlsl = ["uav 0 tex2d table 0 0"], TEX_HLSL + elif mode == "heap": + lines, hlsl = ["heap 1"], HEAP_HLSL + elif mode.startswith("stride"): + lines, hlsl = ["uav 0 buf table 0 0", f"udsrc {count} uavstride 0"], stride_hlsl(count) + elif mode in HEAP_TEXTURE_MODES: + lines, hlsl = ["heap 1"], HEAP_DETILE_HLSL if "detile" in mode else HEAP_TEXTURE_HLSL + elif mode.startswith("membuf"): + lines, hlsl = ["srv 0 buf table 0 128"], MEMBUF_HLSL + else: + base = mode == "uavbase" + lines = ["uav 0 buf table 0 0", "srv 0 buf table 0 32" if mode in COPY_ENV else "srv 0 buf table 0 0", f"udsrc {count} uavword3 0", f"udsrc {count + 1} bufword3 0"] + if base: + lines.append(f"udsrc {count + 2} uavbase 0") + hlsl = buffer_hlsl(count, base) + manifest.write_text(text.rstrip("\n") + "\n" + "\n".join(lines) + "\n", encoding="ascii") + source = manifest.with_suffix(".ps.hlsl") + source.write_text(hlsl) + subprocess.run([env["X2W_FXC"], "/nologo", "/T", "ps_5_1", "/E", "main", "/Fo", manifest.with_suffix(".ps.cso"), source], + check=True, stdout=subprocess.DEVNULL) + result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True, timeout=60) + print(result.stdout, end="") + if result.returncode == 77: + return None + if result.returncode: + raise RuntimeError(f"{mode}: consumer failed ({result.returncode})\n{result.stderr[-5000:]}") + found = re.search(r"^uav memory:((?: \d+)+)$", result.stdout, re.M) + memory = [int(v) for v in found.group(1).split()] if found else None + copied = re.search(r"^copied:((?: \d+)+)$", result.stdout, re.M) + if copied: + memory = (memory, [int(v) for v in copied.group(1).split()]) + return memory, output.read_bytes(), result.stderr + "\n" + result.stdout + + +def need(log, mode, *needles): + for needle in needles: + if needle not in log: + raise AssertionError(f"{mode}: log lacks {needle!r}\n{log[-4000:]}") + + +def check(directory, consumer, backend): + results = {} + for mode in ("aligned", "misaligned", "uavbase", "tex", "tex-noflag", "tex-uint", "heap", "copy-same", "copy-two", "copy-twice", "copy-none", "copy-cpu", + "stride16", "stride0"): + got = run_mode(directory, consumer, backend, mode) + if got is None: + print("no existing-heap support or no adapter: skip") + return 77 + results[mode] = got + # aligned: the view starts at title + 64 (dword 16). Draw 1 stores 1000 + i for column 0; draw 2 reads that + # value in place (srv over the range draw 1 wrote) and adds it. Word 3 reached both entry values (marks 0). + memory, image, log = results["aligned"] + expected = [0] * 64 + for y in range(4): + expected[16 + y * 8] = 1000 + y * 8 + expected[16 + y * 8 + 1] = (1000 + y * 8) + 1000 + y * 8 + 1 + if memory != expected: + raise AssertionError(f"aligned: memory {memory}\nexpected {expected}") + if image[:8] != bytes((0, 255, 0, 255, 255, 255, 0, 255)): + raise AssertionError(f"aligned: pixels {image[:16].hex()} (column 0 must read 0, column 1 the earlier store)") + need(log, "aligned", "x2w-draw-rt first draw with uavs", "from descriptor", "bound in place at window", ": bound") + # misaligned without uavbase: a null view, nothing stored (negative control for the stores above). + memory, image, log = results["misaligned"] + if any(memory): + raise AssertionError(f"misaligned: memory changed {memory}") + need(log, "misaligned", "NULL (not 16-byte aligned, no uavbase)") + # uavbase: the view starts at title + 64 and ud carries 4, so the stores land at title + 68 (dword 17). + # The srv over the written range is misaligned: it keeps the record-time copy (zeros), counted as stale. + memory, image, log = results["uavbase"] + expected = [0] * 64 + for y in range(4): + expected[17 + y * 8] = 1000 + y * 8 + expected[17 + y * 8 + 1] = 1000 + y * 8 + 1 + if memory != expected: + raise AssertionError(f"uavbase: memory {memory}\nexpected {expected}") + # tex: drawn (green columns 0 and 1) through a bound RGBA8 texture UAV; the others are skipped (clear). + green = bytes((0, 255, 0, 255)) + memory, image, log = results["tex"] + if image[:8] != green * 2 or image[8:12] != CLEAR: + raise AssertionError(f"tex: pixels {image[:16].hex()}") + need(log, "tex", "uav 0 texture: ", "format 28 mip 0: bound", "typed UAV store supported", "first draw with uavs") + for mode, reason in (("tex-noflag", "texture without ALLOW_UNORDERED_ACCESS"), + ("tex-uint", "format not a float/unorm format of the texture")): + memory, image, log = results[mode] + if image[:8] != CLEAR * 2: + raise AssertionError(f"{mode}: the draw was not skipped: {image[:16].hex()}") + need(log, mode, f"draw skipped: texture uav: {reason}") + if "first draw with uavs" in log: + raise AssertionError(f"{mode}: a skipped draw was recorded") + # heap: heapmem gave view id i of entry 0 (green 1) and heapbuf[8 + 8 i + 4] its first dword (77). + # With a view increment other than the console's 32 bytes the draw must be skipped instead (WARP). + memory, image, log = results["heap"] + need(log, "heap", "heap 1 in root parameters") + increment = int(re.search(r"^view increment (\d+)$", log, re.M).group(1)) + if increment == 32: + if image[:8] != bytes((77, 255, 0, 255)) * 2: + raise AssertionError(f"heap: pixels {image[:16].hex()}") + need(log, "heap", "x2w-draw-rt first heap draw") + heap = "heap draw reads view id and buffer" + else: + if image[:8] != CLEAR * 2: + raise AssertionError(f"heap: increment {increment} but drawn: {image[:16].hex()}") + need(log, "heap", "heap draw skipped: descriptor increment is not 32") + heap = f"heap draw NOT exercised (view increment {increment}; skipped as required)" + # copy-*: GPU order against two controls. Simulated: draw x stores A[16 + 8y + x] = B[8y] + 1000 + 8y + x; + # after draw x (not the last) the list copies 128 bytes from A + 64 + 4x to B. copy-twice: the second copy reads + # what draw 2 stored, through a window draw 2 read in place (read state -> UAV for the copy). + def simulate(strips, copies): + a, b = [0] * 64, [0] * 32 + for x in range(strips): + for y in range(4): + a[16 + y * 8 + x] = b[y * 8] + 1000 + y * 8 + x + if copies and x < strips - 1: + b = a[16 + x:16 + x + 32] + return a, b + for mode in ("copy-same", "copy-two", "copy-twice", "copy-none", "copy-cpu"): + (memory, copied), image, log = results[mode] + gpu = mode in ("copy-same", "copy-two", "copy-twice") + strips = 3 if mode == "copy-twice" else 2 + expected, expected_copy = simulate(strips, gpu) + if memory != expected: + raise AssertionError(f"{mode}: memory {memory}\nexpected {expected}") + if copied != expected_copy: + raise AssertionError(f"{mode}: copied range {copied}\nexpected {expected_copy}") + row = b"".join(bytes((255 if x and gpu else 0, 255, 0, 255)) for x in range(strips)) + if image[:4 * strips] != row: + raise AssertionError(f"{mode}: pixels {image[:16].hex()}") + if gpu: + need(log, mode, "runs on the GPU in list order", "x2w-copy-gpu CopyBufferRegion", ": on the GPU, window") + if "record-time fallback" in log: + raise AssertionError(f"{mode}: copy fell back\n{log[-3000:]}") + elif mode == "copy-cpu": + need(log, mode, "copies title memory at record time") + for mode, want in (("stride16", {16: 111, 20: 222}), ("stride0", {16: 222})): + memory, image, log = results[mode] + expected = [want.get(i, 0) for i in range(64)] + if memory != expected: + raise AssertionError(f"{mode}: memory {memory}\nexpected {expected}") + need(log, mode, "from descriptor", "first draw with uavs") + print(f"{backend}: udsrc uavstride passes the descriptor's record stride (16: two idxen records both land; " + f"stride 0 control: the second overwrites the first)") + print(f"{backend}: CopyBufferRegion on the GPU in list order (same window, two windows, copy-draw-copy-draw): each draw reads the " + f"bytes the draw before it stored; controls without the copy and with the record-time copy read zeros") + print(f"{backend}: draw UAV buffer stores reach title memory (aligned, in-place re-read, uavbase; misaligned " + f"control stores nothing); texture UAV bound, two refusals skip the draw; {heap}") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_dstorage_status_stats_check.cpp b/tests/startup_dstorage_status_stats_check.cpp new file mode 100644 index 0000000000..4ea9f7c764 --- /dev/null +++ b/tests/startup_dstorage_status_stats_check.cpp @@ -0,0 +1,98 @@ +// The DirectStorage stand-in's status wait diagnostics (src/startup_stubs/dstorage_status_stats.h): +// completions and their wait, IsComplete polls, an index enqueued again before its status was written +// ("reused") and the older status's write landing afterwards ("stale"), and the listing of an index +// pending for over a second. `--mutate no-stale` skips the stale check in on_complete's caller +// contract (it passes generation 0 for every write), so the stale count stays 0: the negative control. +#include "startup_stubs/dstorage_status_stats.h" + +#include +#include +#include +#include + +namespace { + +std::vector lines; + +void capture(const char* format, ...) +{ + char line[1024]; + va_list args; + va_start(args, format); + std::vsnprintf(line, sizeof(line), format, args); + va_end(args); + lines.emplace_back(line); + std::printf(" | %s\n", line); +} + +int failures = 0; + +void expect(bool ok, const char* what) +{ + std::printf("%s %s\n", ok ? "ok " : "FAIL", what); + if (!ok) ++failures; +} + +bool logged(const char* text) +{ + for (const auto& l : lines) + if (l.find(text) != std::string::npos) return true; + return false; +} + +constexpr LONG pending = static_cast(0x8000000A); + +} // namespace + +int main(int argc, char** argv) +{ + const bool no_stale = argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "no-stale") == 0; + namespace st = x2w_dstorage_stats; + auto queue_text = [](void* queue, char* out, std::size_t size) { std::snprintf(out, size, "queue %p", queue); }; + const auto report = [&](int second) { + lines.clear(); + st::report(second, pending, [](const char* f, auto... a) { capture(f, a...); }, queue_text); + }; + + volatile LONG results[2] = {pending, pending}; + st::StatusStats* s = st::make(2, results); + expect(s != nullptr, "make: stats for a capacity-2 array"); + if (!s) return 1; + int queue = 0; + + // One normal batch: enqueue, polled pending three times, completed, polled complete once. + LONG gen = st::on_enqueue(s, 0, &queue); + results[0] = pending; + for (int i = 0; i < 3; ++i) st::on_poll(s, false, nullptr); + st::on_complete(s, 0, no_stale ? 0 : gen); + results[0] = S_OK; + st::on_poll(s, true, nullptr); + report(10); + expect(logged(no_stale ? "completions 0" : "completions 1,"), "a completed status is counted"); + expect(logged("polls (approximate) pending 3 complete 1"), "IsComplete polls are counted by outcome"); + expect(logged("reused before complete 0, stale writes 0"), "no reuse in a normal batch"); + + // Index 0 enqueued again (gen a), then again before a's status was written (gen b): reused. a's write + // then lands on the index b set pending: stale (the title would see b complete early). + const LONG a = st::on_enqueue(s, 0, &queue); + results[0] = pending; + const LONG b = st::on_enqueue(s, 0, &queue); + results[0] = pending; + st::on_complete(s, 0, no_stale ? 0 : a); + results[0] = S_OK; + report(20); + expect(logged("reused before complete 1"), "an index enqueued again before its status was written counts as reused"); + expect(logged("stale writes 1"), "the older status's write after that counts as stale"); + st::on_complete(s, 0, no_stale ? 0 : b); + + // Index 1 pending for over a second is listed with its queue; index 0 (complete) is not. + st::on_enqueue(s, 1, &queue); + results[1] = pending; + Sleep(1100); + report(30); + expect(logged("status PENDING array #0 index 1 for 1."), "an index pending for over a second is listed"); + expect(!logged("index 0 for"), "a complete index is not listed"); + + std::printf("%s\n", failures ? "FAILED" : "PASSED"); + return failures ? 1 : 0; +} diff --git a/tests/startup_execz_join_check.py b/tests/startup_execz_join_check.py new file mode 100644 index 0000000000..3b04e6852a --- /dev/null +++ b/tests/startup_execz_join_check.py @@ -0,0 +1,51 @@ +"""A join where one register is symbolic only on the s_cbranch_execz edge, then ANDed with exec in place.""" +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_scalar_bits_check import sop1, stage # noqa: E402 + +CMP_VCC = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 +SAVE32 = sop1(0x3c, 20, 106) # s_and_saveexec_b32 s20, vcc_lo +NOP = 0xbf800000 + + +def sop2(op, dst, a, b): + return 0x80000000 | op << 23 | dst << 16 | b << 8 | a + + +def program(branch_op=8, before_use=(), use=None): + use = use if use is not None else sop2(0x0e, 13, 13, 126) # s_and_b32 s13, s13, exec_lo + return [sop1(3, 13, 0), CMP_VCC, SAVE32, 0xbf800000 | branch_op << 16 | 2, + sop2(0x0e, 13, 106, 126), NOP] + list(before_use) + [use] + + +def refused(words, label): + try: + stage(words) + except G.Unsupported as error: + assert 'conflict' in str(error) or 'execzero' in str(error), (label, str(error)) + return 1 + raise AssertionError('accepted: ' + label) + + +def main(): + s = stage(program()) + body = [line for _, lines, _ in s.blocks for line in lines] + assert 's13 = (s13 & exec) & 1;' in body, body + for v0, want in ((0, 0), (2, 1)): + exec_bit = int(1 < v0) + s13 = 0x5678 if not exec_bit else 1 + assert (s13 & exec_bit) & 1 == want + controls = refused(program(branch_op=4), 's_cbranch_scc0 edge') + controls += refused(program(before_use=[sop1(3, 126, 20)]), 'exec written before the AND') + controls += refused(program(use=sop2(0x1e, 5, 13, 0x81)), 's_lshl_b32 use') # s_lshl_b32 s5, s13, 1 + print('execz_join: in-place AND with exec after an execz-only conflict reads the run-time variable (0 on the ' + 'taken path, the mask on the other); %d controls refused' % controls) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_fmt_load_table_check.py b/tests/startup_fmt_load_table_check.py new file mode 100644 index 0000000000..5a0a8edd52 --- /dev/null +++ b/tests/startup_fmt_load_table_check.py @@ -0,0 +1,169 @@ +"""x2w_fmt_load in its table form gives the per-format chain's values (tools/startup/gfx2hlsl.py). + +The emitted helper (HELPERS['x2w_fmt_load'] = buf_format_helper_table()) looks the FORMAT code of V# word 3 up in a +constant table of channel widths and kind and decodes the channel with one routine; the older helper +(buf_format_helper(), kept as the reference) had one if-arm per format, which fxc compiled for minutes per call site. + +Checked in Python, over every FORMAT code 0..127, every DST_SEL value 0..7 for each of the four result channels, and +32 element addresses (all four byte alignments) of a pseudo-random buffer that also holds the most negative SNORM +fields: +- the reference: each format's channel expressions exactly as the old chain emits them (buf_format_channel), run + by a small evaluator, with the old helper's fills (unknown code: 0; selector 0/2/3: 0; 1: 1 or 1.0; a channel + the format lacks: 0, w: one); +- the new helper: its table parsed from the emitted HLSL text, and a line-for-line Python transcription of its + decoder, whose HLSL lines are asserted verbatim so the transcription cannot drift. +Float results are compared as binary32 bits; the division is rounded to binary32 once in both (on the GPU the +chain divided by a literal and the table form divides by a run-time value: equal results there are ASSUMED). +Negative controls: a table with one width changed, and a decoder with the SNORM clamp dropped, both mismatch. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +M = 0xffffffff +DATA = bytearray(((i * 0x9e3779b1) >> 13) & 0xff for i in range(256)) +DATA[2:5] = bytes((0x00, 0x80, 0x80)) # the most negative SNORM fields: -32768 at a = 2, -128 at a = 4 +ADDRS = list(range(0, 64, 2)) + + +def f32(x): + return struct.unpack('> 31 else x + + +def chain_channel(code, k, a): + """The old chain's expression for channel k of `code`, evaluated.""" + widths, kind = G.BUF_FORMATS[code] + text = G.buf_format_channel(widths, kind, k) + py = re.sub(r'(0x[0-9a-f]+|\d+)u\b', r'\1', text) + py = py.replace('b.Load(', 'load(').replace('ldu(b, ', 'ldu(').replace('uint(int(', 'u32(s32(') + py = py.replace('float(int(', 'float(s32(').replace('U(', 'ubits(') + env = {'a': a, 'load': load, 'ldu': ldu, 's32': s32, 'u32': lambda x: x & M, 'max': max, + 'ubits': lambda x: bits(x) if isinstance(x, float) else x & M, 'f16tof32': half, + 'float': float, '__builtins__': {}} + return eval(py, env) & M + + +def chain_load(code, a, w3, c): + s = (w3 >> (3 * c)) & 7 + if code not in G.BUF_FORMATS or s in (0, 2, 3): + return 0 + widths, kind = G.BUF_FORMATS[code] + one = 1 if kind in ('uint', 'sint') else 0x3f800000 + if s == 1: + return one + k = s - 4 + if k >= len(widths): + return one if k == 3 else 0 + return chain_channel(code, k, a) + + +DECODER = [ + 'uint x2w_fmt_chan(ByteAddressBuffer b, uint a, uint d, uint k, uint one) {', + ' uint n = (d >> (6u * k)) & 63u;', + ' if (n == 0u) return k == 3u ? one : 0u;', + ' uint pos = (k > 0u ? (d & 63u) : 0u) + (k > 1u ? ((d >> 6) & 63u) : 0u) + (k > 2u ? ((d >> 12) & 63u) : 0u);', + ' uint kind = (d >> 24) & 7u, sh = 32u - n;', + ' uint raw = n == 32u ? b.Load(a + pos / 8u) : ((ldu(b, a + 4u * (pos / 32u)) >> (pos % 32u)) & ((1u << n) - 1u));', + ' int sv = int(raw << sh) >> sh;', + ' if (kind == 0u || (kind == 4u && n == 32u)) return raw;', + ' if (kind == 1u) return uint(sv);', + ' if (kind == 2u) return U(float(raw) / float((1u << n) - 1u));', + ' if (kind == 3u) return U(max(float(sv) / float((1u << (n - 1u)) - 1u), -1.0));', + ' return U(f16tof32(n == 16u ? raw : raw << (15u - n))); }', + 'uint x2w_fmt_load(ByteAddressBuffer b, uint a, uint w3, uint c) {', + ' uint f = (w3 >> 12) & 127u, s = (w3 >> (3u * c)) & 7u;', + ' uint d = f < 78u ? x2w_fmt_tab[f] : 0u;', + ' if (d == 0u || s == 0u || s == 2u || s == 3u) return 0u;', + ' uint one = ((d >> 24) & 7u) <= 1u ? 1u : 0x3f800000u;', + ' return s == 1u ? one : x2w_fmt_chan(b, a, d, s - 4u, one); }'] + + +def table_chan(a, d, k, one, clamp=True): + """Line-for-line transcription of DECODER's x2w_fmt_chan (HLSL shifts take the low 5 bits of the count).""" + n = (d >> (6 * k)) & 63 + if n == 0: + return one if k == 3 else 0 + pos = ((d & 63) if k > 0 else 0) + (((d >> 6) & 63) if k > 1 else 0) + (((d >> 12) & 63) if k > 2 else 0) + kind, sh = (d >> 24) & 7, (32 - n) & 31 + raw = load(a + pos // 8) if n == 32 else (ldu(a + 4 * (pos // 32)) >> (pos % 32)) & ((1 << n) - 1) + sv = s32(raw << sh) >> sh + if kind == 0 or (kind == 4 and n == 32): + return raw + if kind == 1: + return sv & M + if kind == 2: + return bits(float(raw) / float((1 << n) - 1)) + if kind == 3: + q = float(sv) / float((1 << (n - 1)) - 1) + return bits(max(q, -1.0) if clamp else q) + return bits(half(raw if n == 16 else raw << (15 - n))) + + +def table_load(tab, a, w3, c, clamp=True): + f, s = (w3 >> 12) & 127, (w3 >> (3 * c)) & 7 + d = tab[f] if f < len(tab) else 0 + if d == 0 or s in (0, 2, 3): + return 0 + one = 1 if (d >> 24) & 7 <= 1 else 0x3f800000 + return one if s == 1 else table_chan(a, d, s - 4, one, clamp) + + +def mismatches(tab, clamp=True): + bad = [] + for code in range(128): + for c in range(4): + for s in range(8): + w3 = code << 12 | s << (3 * c) + for a in ADDRS: + if table_load(tab, a, w3, c, clamp) != chain_load(code, a, w3, c): + bad.append((code, c, s, a)) + return bad + + +def main(): + text = G.HELPERS['x2w_fmt_load'] + assert text == G.buf_format_helper_table(), 'the emitted helper is the table form' + lines = text.split('\n') + m = re.fullmatch(r'static const uint x2w_fmt_tab\[(\d+)\] = \{ (.*) \};', lines[0]) + assert m and lines[1:] == DECODER, lines[1:] + tab = [int(x[:-1], 16) for x in m.group(2).split(', ')] + assert len(tab) == int(m.group(1)) == 78 + bad = mismatches(tab) + assert not bad, bad[:5] + checked = 128 * 4 * 8 * len(ADDRS) + wrong = list(tab) + wrong[56] = (wrong[56] & ~63) | 7 # 8_8_8_8_UNORM x read as 7 bits + assert mismatches(wrong), 'a wrong width escaped' + assert mismatches(tab, clamp=False), 'a dropped SNORM clamp escaped' + print('fmt_load_table: table helper equals the per-format chain on %d (code, channel, selector, address) cases ' + '(%d formats); wrong-width and no-clamp controls caught' % (checked, len(G.BUF_FORMATS))) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_format_load_check.py b/tests/startup_format_load_check.py new file mode 100644 index 0000000000..3b8319ab71 --- /dev/null +++ b/tests/startup_format_load_check.py @@ -0,0 +1,111 @@ +"""buffer_load_format_* through a descriptor-table entry, behind X2W_DRAW_FEATURES=bufword3 (tools/startup/gfx2hlsl.py). + +The format and DST_SEL are in the descriptor's word 3, which the draw runtime passes as `udsrc bufword3 ` +(draw-rt RUNTIME_DONE.md). Checked here, on synthetic register states: +1. feature off: refused with the old message (the op name), so --requests output does not change; +2. feature on: idxen address index * stride + offset, one x2w_fmt_load per destination with the word-3 constant; + a root or vertex-buffer source (word 3 is 0 there) and an unknown modifier are refused; +3. BUF_FORMATS covers exactly the buffer FORMAT codes gfx10_view_words.h can synthesize (list copied below from its + gfx10_buffer_format cases with a nonzero element size), and the channel layout of a few formats; +4. with fxc available (X2W_FXC or the SDK default), the helper compiles for ps_5_1 in a minimal shader. +Not checked: the decoded values on a GPU (no readback here); the 0 / 0001 fills are assumptions. +""" +import os +import subprocess +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +# gfx10_view_words.h gfx10_buffer_format: codes with a nonzero element size (the buffer-capable ones) +HEADER_BUFFER_CODES = {77, 75, 76, 74, 72, 73, 71, 65, 69, 66, 70, 64, 62, 63, 50, 54, 36, 56, 60, 57, 61, + 29, 23, 27, 24, 28, 22, 20, 21, 14, 18, 15, 19, 13, 7, 11, 8, 12, 1, 5, 2, 6} + + +class Pipe: + sampler_heap = False + root = {'params': [], 'flags': 0} + + def __init__(self, features): + self.features = frozenset(features) + self.resources, self.uds, self.modified = {}, [], set() + + def resource(self, key, kind): + r = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) + return 'r%d' % r['index'] + + def ud(self, source): + if source not in self.uds: + self.uds.append(source) + return self.uds.index(source) + + +def stage(features, source=('table', 0)): + s = G.Stage(Pipe(features), 'ps', b'') + s.lines = [] + for i in range(4): + s.sym[16 + i] = ('desc', source, 0x20, i) + s.pc = 0 + return s + + +def main(): + try: + stage(()).op_buffer_load_format_x(['v2', 'v1', 's[16:19]', '0'], ['idxen']) + except G.Unsupported as error: + assert str(error) == 'buffer_load_format_x', str(error) + else: + raise AssertionError('accepted with the feature off') + + s = stage(('bufword3',)) + s.op_buffer_load_format_xy(['v[2:3]', 'v1', 's[16:19]', '0'], ['idxen', 'offset:8']) + assert s.pipe.uds == [('stride', 0), ('bufword3', 0)], s.pipe.uds + assert s.lines[0] == 'a = v1 * ud0 + 8;', s.lines + assert s.lines[1:] == ['v2 = x2w_fmt_load(r0, a, ud1, 0u);', 'v3 = x2w_fmt_load(r0, a, ud1, 1u);'], s.lines + for source, mods, want in ((('root', 2), ['offen'], 'through root'), (('vbtab',), ['idxen'], 'through vbtab'), + (('table', 0), ['tfe'], 'modifier tfe')): + try: + stage(('bufword3',), source).op_buffer_load_format_x(['v2', 'v1', 's[16:19]', '0'], mods) + except G.Unsupported as error: + assert want in str(error), (want, str(error)) + else: + raise AssertionError('accepted: %s %s' % (source, mods)) + print('format load: feature off refused as before; idxen address and word-3 constant; root/vb/tfe refused') + + assert set(G.BUF_FORMATS) == HEADER_BUFFER_CODES, sorted(set(G.BUF_FORMATS) ^ HEADER_BUFFER_CODES) + ch = G.buf_format_channel + assert ch((8, 8, 8, 8), 'unorm', 2) == 'U(float(((ldu(b, a + 0u) >> 16u) & 0xffu)) / 255.0)' + assert ch((10, 10, 10, 2), 'unorm', 3) == 'U(float(((ldu(b, a + 0u) >> 30u) & 0x3u)) / 3.0)' + assert ch((11, 11, 10), 'float', 2) == 'U(f16tof32((((ldu(b, a + 0u) >> 22u) & 0x3ffu) << 5u)))' + assert ch((11, 11, 10), 'float', 0) == 'U(f16tof32((((ldu(b, a + 0u) >> 0u) & 0x7ffu) << 4u)))' + assert ch((16,) * 4, 'float', 3) == 'U(f16tof32(((ldu(b, a + 4u) >> 16u) & 0xffffu)))' + assert ch((32,) * 4, 'sint', 2) == 'b.Load(a + 8u)' + assert ch((8,), 'sint', 0) == 'uint(int(((ldu(b, a + 0u) >> 0u) & 0xffu) << 24u) >> 24u)' + assert ch((16, 16), 'snorm', 1) == 'U(max(float(int(((ldu(b, a + 0u) >> 16u) & 0xffffu) << 16u) >> 16u) / 32767.0, -1.0))' + print('formats: %d codes, the header buffer set exactly; channel layouts as listed' % len(G.BUF_FORMATS)) + + fxc = G.find_fxc() + if not fxc: + print('fxc not found: compile step skipped') + return + src = '\n'.join(['#define U(x) asuint(x)', + 'uint ldu(ByteAddressBuffer b, uint a) { uint k = (a & 3) * 8, lo = b.Load(a & ~3u); if (k == 0) return lo; ' + 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }', + G.HELPERS['x2w_fmt_load'], + 'cbuffer entry : register(b0) { uint ud0; uint ud1; };', + 'ByteAddressBuffer r0 : register(t0);', + 'float4 main(float4 p : SV_Position) : SV_Target { uint a = uint(p.x) * 4u;', + ' return float4(asfloat(x2w_fmt_load(r0, a, ud0, 0u)), asfloat(x2w_fmt_load(r0, a, ud0, 1u)),', + ' asfloat(x2w_fmt_load(r0, a, ud1, 2u)), asfloat(x2w_fmt_load(r0, a, ud1, 3u))); }']) + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'f.hlsl') + open(path, 'w').write(src) + r = subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', os.path.join(tmp, 'f.cso'), path], + capture_output=True, text=True) + assert r.returncode == 0, r.stderr[-2000:] + print('helper compiles with fxc ps_5_1') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_format_store_check.py b/tests/startup_format_store_check.py new file mode 100644 index 0000000000..ab9485711b --- /dev/null +++ b/tests/startup_format_store_check.py @@ -0,0 +1,105 @@ +"""buffer_store_format_* to a typed buffer UAV, behind X2W_DRAW_FEATURES=uav,uavfmt (tools/startup/gfx2hlsl.py). + +Measured form (a title 1x1 pass): `buffer_store_format_xyzw v[20:23], v1, s[8:11], 0 idxen`, the descriptor a table +entry. RDNA 2 ISA MUBUF addressing: base + soffset + inst offset + stride * index (+ the offen VGPR); the format is +V# word 3 [18:12]. Checked on synthetic register states: +1. feature off (uav only): refused with the op name, as before; +2. on: `a = ud + v1 * ud + offset`, then x2w_fmt_store(u0, a, ud, data, count), + the exec guard when exec is not the entry mask, idxen + offen as index * stride + offset VGPR, an SGPR soffset; +3. the helper writes exactly the formats of BUF_FORMATS whose channels are all 32 bits (codes 20-22, 62-64, + 72-77), as many channels as the format has and the instruction gives; a Python model of the helper is run on + every code 0..127 against that rule. Negative control: a model that also writes 16-bit-channel formats + (71, 16_16_16_16_FLOAT) differs; +4. refusals: tfe, a vertex-buffer source, a modified descriptor. +ASSUMED (not measured): DST_SEL does not reorder a store; the index is in range. +""" +import os +import re +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + sampler_heap = False + root = {'params': [], 'flags': 0} + uav = G.Pipeline.uav + resource = G.Pipeline.resource + + def __init__(self, features): + self.features = frozenset(features) + self.resources, self.uds, self.modified, self.heapvars, self.notes = {}, [], set(), [], set() + + def ud(self, source): + if source not in self.uds: + self.uds.append(source) + return self.uds.index(source) + + +def stage(features=('uav', 'uavfmt'), source=('table', 1)): + s = G.Stage(Pipe(features), 'ps', b'') + s.lines = [] + for i in range(4): + s.sym[8 + i] = ('desc', source, 0x60, i) + s.pc = 0 + return s + + +def refused(s, ops, mods, want): + try: + s.op_buffer_store_format_xyzw(ops, mods) + except G.Unsupported as error: + assert want in str(error), (want, str(error)) + else: + raise AssertionError('accepted: %s %s' % (ops, mods)) + + +def helper_model(code, given, wide=False): + """Channels the helper writes for format code `code` and `given` data components.""" + ranges = re.findall(r'f >= (\d+)u && f <= (\d+)u\) \? (\d)u', G.HELPERS['x2w_fmt_store']) + n = 0 + for lo, hi, count in ranges: + if int(lo) <= code <= int(hi): + n = int(count) + if wide and code == 71: + n = 4 + return min(n, given) + + +def rule(code, given): + widths = G.BUF_FORMATS.get(code, ((),))[0] + return min(len(widths), given) if widths and all(w == 32 for w in widths) else 0 + + +def main(): + STORE = ['v[20:23]', 'v1', 's[8:11]', '0'] + refused(stage(('uav',)), STORE, ['idxen'], 'buffer_store_format_xyzw') + s = stage() + s.op_buffer_store_format_xyzw(STORE, ['idxen']) + assert s.lines == ['a = ud0 + v1 * ud2 + 0;', 'x2w_fmt_store(u0, a, ud1, uint4(v20, v21, v22, v23), 4u);'], s.lines + assert s.pipe.uds == [('uavbase', 0), ('uavword3', 0), ('uavstride', 0)], s.pipe.uds + s = stage() + s.exec_known = False + s.op_buffer_store_format_xy(['v[4:5]', 'v[1:2]', 's[8:11]', 's3'], ['idxen', 'offen', 'offset:8']) + assert s.lines == ['a = ud0 + s3 + v1 * ud2 + v2 + 8;', + 'if (exec & 1) x2w_fmt_store(u0, a, ud1, uint4(v4, v5, 0u, 0u), 2u);'], s.lines + refused(stage(), STORE, ['idxen', 'tfe'], 'modifier tfe') + refused(stage(source=('vbtab',)), STORE, ['idxen'], 'through vbtab') + s = stage() + s.pipe.modified.add((('table', 1), 0x60)) + refused(s, STORE, ['idxen'], 'modified descriptor') + checked = 0 + for code in range(128): + for given in (1, 2, 3, 4): + assert helper_model(code, given) == rule(code, given), (code, given) + checked += 1 + assert any(helper_model(c, g, wide=True) != rule(c, g) for c in range(128) for g in (1, 2, 3, 4)) + assert 'x2w_fmt_store' in G.HELPERS and 'RWByteAddressBuffer b' in G.HELPERS['x2w_fmt_store'] + print('format_store: feature off refused; idxen / idxen+offen / soffset addresses with uavbase, uavword3, ' + 'uavstride; exec guard; helper writes the 32-bit-channel formats only (%d code x count cases); ' + 'negative control caught; tfe, vertex buffer, modified descriptor refused' % checked) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_frame_copy.cpp b/tests/startup_frame_copy.cpp index 738fccae7b..0eacb1d840 100644 --- a/tests/startup_frame_copy.cpp +++ b/tests/startup_frame_copy.cpp @@ -1,7 +1,9 @@ #include #include +#include #include +#include #include #include @@ -12,17 +14,53 @@ // memory between the draws: // changed the colour is rewritten in place (red, then blue) // same the memory is left alone (red both times) +namespace { +constexpr int frame_slots = 8; +alignas(256) float frame_constants_by_slot[frame_slots][64]; +std::atomic next_frame_slot{0}; +int frame_slot() +{ + thread_local const int slot = next_frame_slot.fetch_add(1) % frame_slots; + return slot; +} +alignas(256) float filler_constants[64] = {}; +void* reuse_heap = nullptr; +StreamWord reuse_table = 0, reuse_step = 0; +void* reuse_guest = nullptr; + +void filler_draws(void* list, int count, int salt) +{ + const D3D12_RECT none{0, 0, 0, 0}; + invoke(list, 22, 1, reinterpret_cast(&none)); + invoke(list, 36, 0, reuse_table + reuse_step); // the filler buffer + for (int i = 0; i < count; ++i) { + filler_constants[0] = 1.0f; // yellow, a different alpha each time: a fresh copy per draw + filler_constants[1] = 1.0f; + filler_constants[2] = 0.0f; + filler_constants[3] = static_cast(salt + i + 1) / 256.0f; + invoke(list, 12, 3, 1); + } +} +} // namespace + int draw_frame_copies(ID3D12Device* desktop, void* guest, void* list, UINT width, UINT height) { char mode[16]{}; GetEnvironmentVariableA("X2W_TEST_FRAME_COPY", mode, sizeof(mode)); const bool changed = !std::strcmp(mode, "changed"); - if (!changed && std::strcmp(mode, "same")) return 2; + const bool wrap = !std::strcmp(mode, "wrap"); + const bool reuse = !std::strcmp(mode, "reuse"); + if (!changed && !wrap && !reuse && std::strcmp(mode, "same")) return 2; - alignas(256) static float constants[64] = {1.0f, 0.0f, 0.0f, 1.0f}; + const int slot = frame_slot(); + float* const constants = frame_constants_by_slot[slot]; + std::memset(constants, 0, sizeof(frame_constants_by_slot[slot])); + constants[0] = 1.0f; // red; set on every call, as "changed" leaves blue here for the next repeat + constants[3] = 1.0f; const UINT increment = desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - const UINT entries = (32 + increment - 1) / increment; - static std::vector views; + const UINT entries = (32 + increment - 1) / increment + (reuse ? 2 : 0); + static std::vector views_by_slot[frame_slots]; + std::vector& views = views_by_slot[slot]; views.assign(static_cast(entries) * increment, 0); const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; @@ -35,14 +73,41 @@ int draw_frame_copies(ID3D12Device* desktop, void* guest, void* list, UINT width reinterpret_cast(&heap))))) return 41; const StreamWord cpu = invoke(heap, 9); if (cpu != reinterpret_cast(views.data())) return 42; - const D3D12_CONSTANT_BUFFER_VIEW_DESC view{reinterpret_cast(constants), sizeof(constants)}; + const D3D12_CONSTANT_BUFFER_VIEW_DESC view{reinterpret_cast(constants), sizeof(frame_constants_by_slot[slot])}; invoke(guest, 17, reinterpret_cast(&view), cpu); // CreateConstantBufferView const StreamWord table = invoke(heap, 10); if (!table) return 43; + if (reuse) { + const D3D12_CONSTANT_BUFFER_VIEW_DESC filler{reinterpret_cast(filler_constants), sizeof(filler_constants)}; + invoke(guest, 17, reinterpret_cast(&filler), cpu + increment); + reuse_heap = heap; + reuse_table = table; + reuse_step = increment; + reuse_guest = guest; + } invoke(list, 32, 1, reinterpret_cast(&heap)); // SetDescriptorHeaps invoke(list, 36, 0, table); // SetGraphicsRootDescriptorTable invoke(list, 12, 3, 1); // draw into the left half + if (reuse) { + filler_draws(list, 100, 0); // the second half of the frame is recorded by draw_frame_copies_again + return 0; + } + if (wrap) { + const D3D12_RECT none{0, 0, 0, 0}; + invoke(list, 22, 1, reinterpret_cast(&none)); + for (int i = 0; i < 64; ++i) { + constants[0] = 1.0f; // yellow, a different alpha each time: a fresh copy per draw + constants[1] = 1.0f; + constants[2] = 0.0f; + constants[3] = static_cast(i + 1) / 128.0f; + invoke(list, 12, 3, 1); + } + constants[0] = 0.0f; // green + constants[1] = 1.0f; + constants[2] = 0.0f; + constants[3] = 1.0f; + } if (changed) { constants[0] = 0.0f; // the same address now holds blue constants[2] = 1.0f; @@ -52,3 +117,40 @@ int draw_frame_copies(ID3D12Device* desktop, void* guest, void* list, UINT width invoke(list, 12, 3, 1); // draw into the right half return 0; } + +// reuse, the second list (the caller has executed the first, waited for it, and Reset the list with the target and +// pipeline bound again). +int draw_frame_copies_again(void* list, UINT width, UINT height) +{ + if (!reuse_heap) return 44; + const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; + invoke(list, 21, 1, reinterpret_cast(&viewport)); + const D3D12_RECT right{static_cast(width / 2), 0, static_cast(width), static_cast(height)}; + invoke(list, 22, 1, reinterpret_cast(&right)); + invoke(list, 32, 1, reinterpret_cast(&reuse_heap)); + invoke(list, 36, 0, reuse_table); // the red constants, unchanged since list A: a frame-copy cache hit + invoke(list, 12, 3, 1); + filler_draws(list, 64, 100); + return 0; +} + +// reuse: the ring counters after the second list, for the check script. +int write_ring_counters() +{ + char path[MAX_PATH]{}; + if (!GetEnvironmentVariableA("X2W_TEST_RING_COUNTERS", path, sizeof(path))) return 0; + HMODULE module = nullptr; + // The module that implements the guest device (its vtable lives there). + if (!reuse_guest || !GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + *static_cast(reuse_guest), &module)) + return 45; + using Counter = unsigned long long (*)(int); + const auto counter = reinterpret_cast(GetProcAddress(module, "x2w_upload_ring_test")); + if (!counter) return 46; + FILE* file = nullptr; + if (fopen_s(&file, path, "w") || !file) return 47; + std::fprintf(file, "reserved=%llu\nchunks=%llu\nmade=%llu\nrepinned=%llu\nstale=%llu\nrefused=%llu\n", counter(0), counter(4), + counter(8), counter(9), counter(5), counter(1)); + std::fclose(file); + return 0; +} diff --git a/tests/startup_frame_copy_check.py b/tests/startup_frame_copy_check.py index 02986af126..d97b0bcb8f 100644 --- a/tests/startup_frame_copy_check.py +++ b/tests/startup_frame_copy_check.py @@ -1,4 +1,9 @@ -"""A constant buffer the title rewrites between two draws of one frame reaches the second draw with its new contents.""" +"""A constant buffer the title rewrites between two draws of one frame reaches the second draw with its new contents. + +Upload ring (wrap mode, a 16 KiB test ring): 64 more copies than the ring holds, all in one list, must not overwrite the +first draw's copy (chain, the default); the legacy ring (X2W_UPLOAD_RING=legacy, the negative control) does overwrite it; +a chain capped at 2 chunks refuses the copies past the cap and does not issue the draw that needed one. +""" from pathlib import Path import sys import tempfile @@ -13,16 +18,18 @@ ) RED = bytes((255, 0, 0, 255)) BLUE = bytes((0, 0, 255, 255)) +GREEN = bytes((0, 255, 0, 255)) -def run(directory, consumer, backend, mode): - folder = directory / mode +def run(directory, consumer, backend, mode, name=None, env=None): + folder = directory / (name or mode) folder.mkdir() log = folder / "trap.log" - pixels = draw_texture(folder, consumer, backend, HLSL, {"X2W_TEST_FRAME_COPY": mode, "X2W_TRAP_LOG": str(log)}, + pixels = draw_texture(folder, consumer, backend, HLSL, + {"X2W_TEST_FRAME_COPY": mode, "X2W_TRAP_LOG": str(log), **(env or {})}, binding="srv 0 buf table 0 0") - refreshed = [line for line in log.read_text(errors="replace").splitlines() if "frame copy of" in line] if log.exists() else [] - return pixels, refreshed + lines = log.read_text(errors="replace").splitlines() if log.exists() else [] + return pixels, lines def check(directory, consumer, backend): @@ -32,14 +39,91 @@ def check(directory, consumer, backend): ("same", RED * 8 * 4, 0), # untouched: both draws red, no new copy ) for mode, expected, refreshed_lines in cases: - pixels, refreshed = run(directory, consumer, backend, mode) + pixels, lines = run(directory, consumer, backend, mode) if pixels is None: return 77 + refreshed = [line for line in lines if "frame copy of" in line] if pixels != expected: raise AssertionError(f"{mode}: actual {pixels.hex()} expected {expected.hex()}") if len(refreshed) != refreshed_lines: raise AssertionError(f"{mode}: {len(refreshed)} refresh log lines, expected {refreshed_lines}:\n" + "\n".join(refreshed)) print(f"{backend} {mode}: 32 pixels exact, {refreshed_lines} refresh log lines") + + ring = {"X2W_UPLOAD_RING_TEST_KIB": "16"} + wanted = (RED * 4 + GREEN * 4) * 4 + + def has(lines, text): + return any(text in line for line in lines) + + pixels, lines = run(directory, consumer, backend, "wrap", "wrap_chain", ring) + if pixels is None: + return 77 + if pixels != wanted: + raise AssertionError(f"wrap chain: actual {pixels.hex()} expected {wanted.hex()}") + if not has(lines, "x2w-upload ring: chain") or not has(lines, "x2w-upload ring (chain): first copy past the old ring's size"): + raise AssertionError("wrap chain: missing the chain / would-have-wrapped log lines:\n" + "\n".join(l for l in lines if "upload ring" in l)) + print(f"{backend} wrap chain: 32 pixels exact (left red after 64 more copies than the test ring holds); would-have-wrapped logged") + + # Negative control: the legacy ring reuses the first draw's slot before the list has executed. + pixels, lines = run(directory, consumer, backend, "wrap", "wrap_legacy", {**ring, "X2W_UPLOAD_RING": "legacy"}) + if pixels is None: + return 77 + left = b"".join(pixels[row * 32: row * 32 + 16] for row in range(4)) + if left == RED * 16: + raise AssertionError("wrap legacy (negative control): the left half is still red; the control did not trip") + if not has(lines, "x2w-upload ring (legacy): first copy written over ring data the GPU had not read yet"): + raise AssertionError("wrap legacy: no overwrite log line") + print(f"{backend} wrap legacy (negative control): left half {left[:4].hex()} instead of red; overwrite logged") + + # Cap: 2 chunks of 16 KiB hold 64 copies; the rest are refused, and the green draw that needed one is not issued. + pixels, lines = run(directory, consumer, backend, "wrap", "wrap_cap", {**ring, "X2W_UPLOAD_RING_TEST_CAP_CHUNKS": "2"}) + if pixels is None: + return 77 + capped = (RED * 4 + BLUE * 4) * 4 + if pixels != capped: + raise AssertionError(f"wrap cap: actual {pixels.hex()} expected {capped.hex()} (left red, right not drawn)") + if not has(lines, "is free yet; the copy fails") or not has(lines, "not issued at frame"): + raise AssertionError("wrap cap: missing the refusal / draw-not-issued log lines") + print(f"{backend} wrap cap: left red, right not drawn (clear colour); refusal and draw-not-issued logged") + + def counters(folder): + path = directory / folder / "ring.txt" + if not path.exists(): + raise AssertionError(f"{folder}: no ring counters written") + return {k: int(v) for k, v in (line.split("=") for line in path.read_text().split())} + + def reuse(folder, env): + target = directory / folder / "ring.txt" + return run(directory, consumer, backend, "reuse", folder, {**ring, "X2W_TEST_RING_COUNTERS": str(target), **env}) + + pixels, lines = reuse("reuse_chain", {}) + if pixels is None: + return 77 + c = counters("reuse_chain") + chunk = 16 << 10 + if pixels != RED * 8 * 4: + raise AssertionError(f"reuse chain: actual {pixels.hex()} expected all red; counters {c}") + if c["repinned"] < 1 or not has(lines, "first cached copy bound again from a chunk waiting for its fences"): + raise AssertionError(f"reuse chain: the cache hit did not re-pin a fenced chunk; counters {c}") + if c["reserved"] <= c["made"] * chunk: + raise AssertionError(f"reuse chain: no chunk was recycled (reserved {c['reserved']} bytes in {c['made']} chunks)") + if c["refused"]: + raise AssertionError(f"reuse chain: copies refused; counters {c}") + print(f"{backend} reuse chain: 32 pixels red (the second list's cache hit kept its chunk); {c['reserved'] >> 10} KiB " + f"reserved in {c['made']} chunks of 16 KiB (recycled), re-pinned {c['repinned']}") + + # Negative control: without the re-pin the recycled chunk 0 is overwritten by fillers before list B executes. + pixels, lines = reuse("reuse_norepin", {"X2W_UPLOAD_RING_TEST_NO_REPIN": "1"}) + if pixels is None: + return 77 + c = counters("reuse_norepin") + right = b"".join(pixels[row * 32 + 16: row * 32 + 32] for row in range(4)) + if right == RED * 16: + raise AssertionError(f"reuse no-repin (negative control): the right half is still red; the control did not trip; counters {c}") + if c["repinned"]: + raise AssertionError(f"reuse no-repin: re-pinned {c['repinned']} although the switch is set") + print(f"{backend} reuse no-repin (negative control): right half {right[:4].hex()} instead of red; " + f"{c['reserved'] >> 10} KiB in {c['made']} chunks") return 0 diff --git a/tests/startup_front_face_check.py b/tests/startup_front_face_check.py new file mode 100644 index 0000000000..a3d180b01d --- /dev/null +++ b/tests/startup_front_face_check.py @@ -0,0 +1,126 @@ +"""The SPI input FRONT_FACE (SPI_PS_INPUT_ENA bit 12) in gfx2hlsl pixel stages, draw and mesh pipelines. + + (no arguments) translation controls, pure Python (dxc ps_6_0 compile when M.DXC exists) + draw [fxc] + translate, compile, draw one pixel (the startup_flat_param renderer) + +The VGPR holds +1.0 for a front face and -1.0 for a back face: Mesa nir_intrinsics.py front_face_fsign +"front_face ? 1.0 : -1.0", loaded as the front_face argument itself by ac_nir_lower_intrinsics_to_args.c (and +load_front_face as fgt(arg, 0)). The lowering is U(i.ff ? 1.0 : -1.0) over `bool ff : SV_IsFrontFace` (a pixel +input only, never in the vertex/mesh output), and the manifest says `frontface 1`: which face D3D calls front is the +PSO's FrontCounterClockwise, i.e. the runtime's cull convention, not the translator's. + +Synthetic pixel stage `exp mrt0 vA, vB, vC, vD done vm` (entry reads only). Layouts: ENA 0x1000 (front_face v0), +0x9002 (persp_center v0-v1, front_face v2, pos_fixed_pt v3), 0x1001 (persp_sample v0-v1, front_face v2: per-sample, but front face is not a +position input, so it is taken). +Controls: before the change the read was refused ("front_face ... not lowered"; reproduced by removing bit 12 from +PS_INPUT_HLSL); a pixel stage without the read has no SV_IsFrontFace and no `frontface` line; the mesh stage's +output struct never carries it; ancillary (bit 13) stays refused. The draw checks that the drawn word is +1.0 or +-1.0 and that the inverted expression draws the other one (the input is live, whichever face the renderer draws). +""" +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_mesh_spi_input_check import pixel_words, mesh # noqa: E402 +from startup_image_3d_check import VS_WORDS, root_blob # noqa: E402 + +LINE = ' v%d = U(i.ff ? 1.0 : -1.0); // SPI input front_face' +FIELD = ' bool ff : SV_IsFrontFace;' + + +def draw_pipe(ps, masks): + return G.Pipeline(VS_WORDS, ps, root_blob(), ps_hw_inputs=masks) + + +def refused(build, ps, masks, text): + try: + build(ps, masks).hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (text, str(error)) + return + raise AssertionError('accepted %s' % (masks,)) + + +def controls(): + assert G.ps_input_layout(0x1000, 0x1000) == {0: 12} + assert G.ps_input_layout(0x9002, 0x9002) == {0: 1, 1: 1, 2: 12, 3: 15} + texts = {} + for name, build in (('draw', draw_pipe), ('mesh', mesh)): + pipe = build(pixel_words(0, 0, 0, 0), (0x1000, 0x1000)) + ps = pipe.hlsl_ps() + assert LINE % 0 in ps.split('\n') and FIELD in ps.split('\n'), ps + assert 'frontface 1' in pipe.manifest().split('\n'), pipe.manifest() + texts[name] = ps + both = build(pixel_words(2, 3, 2, 3), (0x9002, 0x9002)).hlsl_ps() + assert LINE % 2 in both.split('\n') and 'v3 = (uint(i.pos.x) & 0xffffu)' in both, both + assert LINE % 2 in build(pixel_words(2, 2, 2, 2), (0x1001, 0x1001)).hlsl_ps() + plain = build(pixel_words(3, 3, 3, 3), (0x9002, 0x9002)) + assert 'SV_IsFrontFace' not in plain.hlsl_ps() and 'frontface' not in plain.manifest(), plain.hlsl_ps() + refused(build, pixel_words(0, 0, 0, 0), (0x2000, 0x2000), 'ancillary (v0) at 0x0: not lowered') + assert 'SV_IsFrontFace' not in draw_pipe(pixel_words(0, 0, 0, 0), (0x1000, 0x1000)).hlsl_vs() + saved = G.PS_INPUT_HLSL.pop(G.FRONT_FACE) + try: + refused(draw_pipe, pixel_words(0, 0, 0, 0), (0x1000, 0x1000), 'front_face (v0) at 0x0: not lowered') + finally: + G.PS_INPUT_HLSL[G.FRONT_FACE] = saved + compiled = 'dxc not found' + if os.path.isfile(M.DXC): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'ps.hlsl') + open(path, 'w').write(texts['mesh']) + r = subprocess.run([M.DXC, '-nologo', '-T', 'ps_6_0', '-E', 'main', '-Fo', path + '.cso', path], + capture_output=True, text=True) + assert r.returncode == 0, r.stderr + compiled = 'dxc ps_6_0 ok' + print('front_face: U(i.ff ? 1.0 : -1.0) over SV_IsFrontFace in draw and mesh pipelines, manifest frontface 1; ' + '%s; controls: refused before, absent when unread, not in the VS, ancillary refused' % compiled) + + +def check_draw(dxc, renderer, adapter, fxc=None): + from startup_flat_param_check import VS_WORDS as FLAT_VS, root_blob as flat_root, compile_hlsl, draw + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + words = {'+1.0': ','.join(['3f800000'] * 4), '-1.0': ','.join(['bf800000'] * 4)} + pipe = G.Pipeline(FLAT_VS, pixel_words(0, 0, 0, 0), flat_root(), ps_hw_inputs=(0x1000, 0x1000)) + good = pipe.hlsl_ps() + inverted = good.replace('i.ff ? 1.0 : -1.0', 'i.ff ? -1.0 : 1.0') + assert inverted != good + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + def build(name, source, profile): + return compile_hlsl(compiler, kind, source, '%s_%s' % (name, kind), profile, directory) + vs = build('vs', pipe.hlsl_vs(), vs_profile) + seen = [] + for label, source in (('translated', good), ('inverted', inverted)): + ps = build('ps_' + label, source, ps_profile) + match = [face for face, expected in words.items() if draw(renderer, adapter, vs, ps, expected).returncode == 0] + if len(match) != 1: + raise AssertionError('%s %s stage drew neither +1.0 nor -1.0' % (kind, label)) + seen.append(match[0]) + print('%s %s stage: every word %s' % (kind, label, match[0]), flush=True) + if seen[0] == seen[1]: + raise AssertionError('%s: the inverted expression drew the same word' % kind) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx10_view_words_check.cpp b/tests/startup_gfx10_view_words_check.cpp new file mode 100644 index 0000000000..72cfcbb203 --- /dev/null +++ b/tests/startup_gfx10_view_words_check.cpp @@ -0,0 +1,233 @@ +// Checks src/startup_stubs/gfx10_view_words.h without a device: buffer view layouts (typed views step by the +// element size), GFX10_FORMAT codes, V# and T# words decoded with an independent field table (bit positions of +// Mesa src/amd/registers/gfx10-rsrc.json), and the view descriptions read from real D3D12 SDK structs. +// --mutate legacy | width | order | uint: the helper's answer replaced the way a wrong helper would answer (the +// old `stride ? stride : 4` layout, the whole width - 1 in word 2, R10G10B10A2 as 10_10_10_2, an R32_FLOAT +// integer UAV); each must fail on the rows it concerns. +#include "startup_stubs/gfx10_view_words.h" + +#include +#include + +namespace { +int failures, checks; +const char* mutation = ""; +using namespace x2w_startup; + +void expect(const char* name, unsigned long long got, unsigned long long wanted) +{ + ++checks; + if (got != wanted) { + ++failures; + std::printf("FAIL %s: got 0x%llx (%llu), wanted 0x%llx (%llu)\n", name, got, got, wanted, wanted); + } +} + +std::uint32_t field(const std::uint32_t* w, int word, int lo, int hi) { return (w[word] >> lo) & ((hi - lo == 31) ? ~0u : ((1u << (hi - lo + 1)) - 1)); } + +BufferViewLayout layout(DXGI_FORMAT f, std::uint64_t first, std::uint32_t count, std::uint32_t stride, std::uint32_t flags) +{ + return buffer_view_layout(f, first, count, stride, flags, !std::strcmp(mutation, "legacy")); +} + +void image_words(const ImageViewFacts& v, std::uint32_t w[8], bool* unmapped = nullptr) +{ + gfx10_image_words(v, w, unmapped); + if (!std::strcmp(mutation, "width")) { // a wrong split: all of width - 1 in word 2 + const std::uint32_t width = static_cast(v.width - 1); + w[1] &= ~(3u << 30); + w[2] = (w[2] & ~0xfffu) | (width & 0xfff); + } +} + +std::uint32_t format_code(DXGI_FORMAT f) +{ + if (!std::strcmp(mutation, "order") && f == DXGI_FORMAT_R10G10B10A2_UNORM) return 44; + return gfx10_format(f).code; +} + +void buffers() +{ + // Typed R16_UINT view, FirstElement 3: element 2 bytes, starts at byte 6, 10 elements = 20 bytes. + BufferViewLayout l = layout(DXGI_FORMAT_R16_UINT, 3, 10, 0, 0); + expect("r16 typed kind", static_cast(l.kind), static_cast(BufferViewKind::typed)); + expect("r16 offset", l.offset, 6); + expect("r16 bytes", l.bytes, 20); + expect("r16 index stride", l.index_stride, 2); + expect("r16 format", l.format.code, 11); + // R32G32B32A32_FLOAT typed view: 16-byte elements. + l = layout(DXGI_FORMAT_R32G32B32A32_FLOAT, 2, 4, 0, 0); + expect("rgba32f offset", l.offset, 32); + expect("rgba32f bytes", l.bytes, 64); + expect("rgba32f index stride", l.index_stride, 16); + // R32_UINT typed: the old layout had the right base but index stride 0. + l = layout(DXGI_FORMAT_R32_UINT, 5, 8, 0, 0); + expect("r32u offset", l.offset, 20); + expect("r32u index stride", l.index_stride, 4); + // RAW and structured views keep the old layout. + l = layout(DXGI_FORMAT_R32_TYPELESS, 4, 64, 0, 1); + expect("raw kind", static_cast(l.kind), static_cast(BufferViewKind::raw)); + expect("raw offset", l.offset, 16); + expect("raw bytes", l.bytes, 256); + expect("raw index stride", l.index_stride, 0); + expect("raw num_records (bytes)", l.num_records, 256); + l = buffer_view_layout(DXGI_FORMAT_UNKNOWN, 7, 3, 36, 0); + expect("structured offset", l.offset, 252); + expect("structured index stride", l.index_stride, 36); + expect("structured num_records (elements)", l.num_records, 3); + + // V# of the R16_UINT view: STRIDE [16,29] = 2, NUM_RECORDS = 10, FORMAT [12,18] = 16_UINT, DST_SEL X001. + std::uint32_t w[8]; + gfx10_buffer_words(layout(DXGI_FORMAT_R16_UINT, 3, 10, 0, 0), w); + expect("v# word0 (no address)", w[0], 0); + expect("v# stride", field(w, 1, 16, 29), 2); + expect("v# base hi (no address)", field(w, 1, 0, 15), 0); + expect("v# num_records", w[2], 10); + expect("v# dst_sel_x", field(w, 3, 0, 2), 4); + expect("v# dst_sel_y", field(w, 3, 3, 5), 0); + expect("v# dst_sel_w", field(w, 3, 9, 11), 1); + expect("v# format", field(w, 3, 12, 18), 11); + expect("v# oob_select", field(w, 3, 28, 29), 0); + expect("v# type", field(w, 3, 30, 31), 0); + // Raw view V# as ac_build_raw_buffer_descriptor: 32_FLOAT, XYZW, OOB_SELECT_RAW, NUM_RECORDS in bytes. + gfx10_buffer_words(buffer_view_layout(DXGI_FORMAT_R32_TYPELESS, 0, 64, 0, 1), w); + expect("raw v# stride", field(w, 1, 16, 29), 0); + expect("raw v# num_records", w[2], 256); + expect("raw v# format", field(w, 3, 12, 18), 22); + expect("raw v# dst_sel", field(w, 3, 0, 11), 4 | 5 << 3 | 6 << 6 | 7 << 9); + expect("raw v# oob_select", field(w, 3, 28, 29), 3); + + // The record offsets against the SDK structs. + D3D12_SHADER_RESOURCE_VIEW_DESC s{}; + s.Format = DXGI_FORMAT_R8_UNORM; + s.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + s.Buffer.FirstElement = 9; + s.Buffer.NumElements = 100; + unsigned char bytes[64] = {}; + std::memcpy(bytes, &s, sizeof(s)); + expect("srv desc parsed", buffer_view_layout_from_desc(false, bytes, sizeof(s), l, !std::strcmp(mutation, "legacy")), 1); + expect("srv r8 offset", l.offset, 9); + expect("srv r8 bytes", l.bytes, 100); + D3D12_UNORDERED_ACCESS_VIEW_DESC u{}; + u.Format = DXGI_FORMAT_R32_TYPELESS; + u.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + u.Buffer.FirstElement = 12; + u.Buffer.NumElements = 4; + u.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + std::memset(bytes, 0, sizeof(bytes)); + std::memcpy(bytes, &u, sizeof(u)); + expect("uav desc parsed", buffer_view_layout_from_desc(true, bytes, sizeof(u), l), 1); + expect("uav raw kind", static_cast(l.kind), static_cast(BufferViewKind::raw)); + expect("uav raw offset", l.offset, 48); + u.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; + u.Format = DXGI_FORMAT_R16G16_FLOAT; + std::memcpy(bytes, &u, sizeof(u)); + buffer_view_layout_from_desc(true, bytes, sizeof(u), l, !std::strcmp(mutation, "legacy")); + expect("uav r16g16f index stride", l.index_stride, 4); + expect("uav r16g16f format", l.format.code, 29); +} + +void formats() +{ + expect("R10G10B10A2_UNORM = 2_10_10_10_UNORM", format_code(DXGI_FORMAT_R10G10B10A2_UNORM), 50); + expect("R11G11B10_FLOAT = 10_11_11_FLOAT", format_code(DXGI_FORMAT_R11G11B10_FLOAT), 36); + expect("R8G8B8A8_UNORM", format_code(DXGI_FORMAT_R8G8B8A8_UNORM), 56); + expect("R32_FLOAT", format_code(DXGI_FORMAT_R32_FLOAT), 22); + expect("R16G16B16A16_FLOAT", format_code(DXGI_FORMAT_R16G16B16A16_FLOAT), 71); + expect("BC7_UNORM", format_code(DXGI_FORMAT_BC7_UNORM), 181); + expect("typeless is unmapped", format_code(DXGI_FORMAT_R8G8B8A8_TYPELESS), 0); + expect("B8G8R8A8 swizzle ZYXW", gfx10_format(DXGI_FORMAT_B8G8R8A8_UNORM).dst_sel, 6 | 5 << 3 | 4 << 6 | 7 << 9); +} + +void images() +{ + // 2D 1920x1080, 11 mips, RGBA8 SRV of mips 2..: built from an SDK struct. + D3D12_SHADER_RESOURCE_VIEW_DESC s{}; + s.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + s.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + s.Texture2D.MostDetailedMip = 2; + s.Texture2D.MipLevels = UINT(-1); + unsigned char bytes[64] = {}; + std::memcpy(bytes, &s, sizeof(s)); + ImageViewFacts v{}; + expect("srv texture2d parsed", image_view_from_desc(false, bytes, sizeof(s), v), 1); + v.dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + v.width = 1920; + v.height = 1080; + v.depth_or_array = 1; + v.mip_levels = 11; + std::uint32_t w[8]; + bool unmapped = true; + image_words(v, w, &unmapped); + expect("t# format mapped", unmapped, 0); + const std::uint32_t width = field(w, 1, 30, 31) | field(w, 2, 0, 11) << 2; + expect("t# width - 1 (WIDTH_LO | WIDTH_HI << 2)", width, 1919); + expect("t# height - 1", field(w, 2, 14, 27), 1079); + expect("t# format", field(w, 1, 20, 28), 56); + expect("t# word1 nonzero (null test)", w[1] != 0, 1); + expect("t# base level", field(w, 3, 12, 15), 2); + expect("t# last level", field(w, 3, 16, 19), 10); + expect("t# type 2D", field(w, 3, 28, 31), 9); + expect("t# depth", field(w, 4, 0, 12), 0); + expect("t# max mip", field(w, 5, 4, 7), 10); + expect("t# word0 (no address)", w[0], 0); + expect("t# words 6-7", w[6] | w[7], 0); + // Hand-computed constants for the same view (word1 = 56 << 20 | 3 << 30; word2 = 479 | 1079 << 14). + expect("t# word1 exact", w[1], 0xc3800000u); + expect("t# word2 exact", w[2], 0x010dc1dfu); + + // 2D array UAV, slices 3..6 of 8, mip 1; 3D SRV depth 32. + D3D12_UNORDERED_ACCESS_VIEW_DESC u{}; + u.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + u.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + u.Texture2DArray = {1, 3, 4, 0}; + std::memset(bytes, 0, sizeof(bytes)); + std::memcpy(bytes, &u, sizeof(u)); + v = {}; + expect("uav array parsed", image_view_from_desc(true, bytes, sizeof(u), v), 1); + v.dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + v.width = 512; + v.height = 256; + v.depth_or_array = 8; + v.mip_levels = 4; + image_words(v, w); + expect("array type", field(w, 3, 28, 31), 13); + expect("array base level = last level", field(w, 3, 12, 15) * 16 + field(w, 3, 16, 19), 1 * 16 + 1); + expect("array base_array", field(w, 4, 16, 28), 3); + expect("array depth = last layer", field(w, 4, 0, 12), 6); + v = {}; + v.dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + v.view_dimension = D3D12_SRV_DIMENSION_TEXTURE3D; + v.format = DXGI_FORMAT_R11G11B10_FLOAT; + v.width = 64, v.height = 64, v.depth_or_array = 32, v.mip_levels = 1, v.level_count = UINT(-1); + image_words(v, w); + expect("3d type", field(w, 3, 28, 31), 10); + expect("3d depth - 1", field(w, 4, 0, 12), 31); + expect("3d array pitch (srv)", field(w, 5, 0, 3), 0); + // A view the synthesizer cannot describe yields zeros (the runtime treats it as null). + v.view_dimension = D3D12_SRV_DIMENSION_TEXTURE2D; + expect("2D view of a 3D resource refused", gfx10_image_words(v, w), 0); + expect("refused words zero", w[1] | w[2] | w[3], 0); +} + +void integer_uav() +{ + DXGI_FORMAT got = integer_uav_format(DXGI_FORMAT_R32_TYPELESS); + if (!std::strcmp(mutation, "uint")) got = DXGI_FORMAT_R32_FLOAT; + expect("R32_TYPELESS resource -> R32_UINT UAV", got, DXGI_FORMAT_R32_UINT); + expect("R32_UINT resource -> R32_UINT UAV", integer_uav_format(DXGI_FORMAT_R32_UINT), DXGI_FORMAT_R32_UINT); + expect("R32_FLOAT resource refused", integer_uav_format(DXGI_FORMAT_R32_FLOAT), DXGI_FORMAT_UNKNOWN); + expect("R8G8B8A8_TYPELESS resource refused", integer_uav_format(DXGI_FORMAT_R8G8B8A8_TYPELESS), DXGI_FORMAT_UNKNOWN); +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && !std::strcmp(argv[1], "--mutate")) mutation = argv[2]; + buffers(); + formats(); + images(); + integer_uav(); + std::printf("startup_gfx10_view_words%s%s: %d checks, %d failures\n", *mutation ? " --mutate " : "", mutation, checks, failures); + return failures ? 1 : 0; +} diff --git a/tests/startup_gfx2hlsl_coverage_check.py b/tests/startup_gfx2hlsl_coverage_check.py new file mode 100644 index 0000000000..6e05fc287b --- /dev/null +++ b/tests/startup_gfx2hlsl_coverage_check.py @@ -0,0 +1,685 @@ +"""Lowerings added to tools/startup/gfx2hlsl.py for the startup pipeline requests, pure Python. + +Each case hand-encodes gfx1013 words (no title data), checks the shared disassembler prints the form the lowering +parses, and checks the translated statement. The integer helpers (64-bit shifts, the high word of a product and the +IEEE class of a binary32 or binary16 value) are evaluated by the integer HLSL evaluator of +startup_gfx2hlsl_bit_alu_check over edge grids and compared with references written from the ISA description with +Python integers and struct, not with the lowering's own expressions. Each lowering also has refusal controls for the +forms it does not prove. + +Semantics sources: LLVM AMDGPU (SIDefines.h ClassFlags, llvm.amdgcn.class(value, mask); GCNSubtarget +zeroesHigh16BitsOfDest for the gfx10 16-bit results; SIFoldOperands "Clamp is applied after omod"; +ConstantFoldAMDGCNCubeIntrinsic for v_cube*; SIInstrInfo s_and/s_cmp -> s_bitcmp folds; SOPInstructions.td for +the s_lshlN_add / s_abs / s_pack_ll patterns and which scalar ops define SCC; SIShrinkInstructions for the signed +SOPK immediate; AMDGPUISelDAGToDAG SelectVOP3PMadMixModsImpl and VOP3PInstructions.td VOP3P_Mix_Profile for the +mix operands; SIISelLowering packImage16bitOpsToDwords for a16) and Mesa main 13ebbc00 (ACO selection of +pack_[us]norm_2x16 to v_cvt_pknorm_*, nir_constant_expressions pack_[us]norm_1x16, util/macros.h CLAMP). +""" +import math +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +failures = [] + + +def check(label, ok): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + failures.append(label) + + +class FakePipe: + """The pipeline services one stage needs: resources, samplers, entry constants and the render-target kinds.""" + root = {'params': [{'type': 0}], 'flags': 0} + sampler_heap = False + uses_sampler_heap = False + ps_float_mode = 0xc0 # the pixel stage's launch FLOAT_MODE (a .psin third field 000000c0): MODE 0 rounding + + def __init__(self): + self.resources, self.samplers, self.modified, self.notes = {}, {}, set(), set() + + def resource(self, key, kind): + r = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) + assert r['kind'] == kind + return 'r%d' % r['index'] + + def sampler(self, key, comparison=False): + return 'q%d' % self.samplers.setdefault(key, len(self.samplers)) + + def ud(self, source): + return 0 + + def mrt_kind(self, slot): + return 'float' + + +def words_bytes(words): + return struct.pack('<%dI' % len(words), *words) + + +def stage(words, kind='ps'): + """Translate a whole program (s_endpgm appended).""" + return G.Stage(FakePipe(), kind, words_bytes(list(words) + [0xbf810000])) + + +def asm_of(words): + return G.decode(words_bytes(words))[0][3] + + +def lines(words, kind='ps', setup=None): + """Translate one instruction on a fresh stage after an optional setup(stage); returns its statements.""" + s = stage([], kind) + if setup: + setup(s) + s.lines = [] + _, n, name, asm = G.decode(words_bytes(words))[0] + s.pc = 0 + s.one(name, asm) + return s, '\n'.join(s.lines) + + +def refused(asm, kind='ps', setup=None, words=None): + s = stage([], kind) + if setup: + setup(s) + try: + if words is not None: + _, n, name, asm = G.decode(words_bytes(words))[0] + else: + name = asm.split(' ', 1)[0] + s.one(name, asm) + except G.Unsupported: + return True + return False + + +def helper_expr(name): + text = G.HELPERS[name] + return Expr(text[text.index('return ') + 7:text.rindex(';')]) + + +# ---- exports ------------------------------------------------------------------------------------- +def exports(): + w = [0xf8000000 | 0x3 | 1 << 10 | 1 << 11 | 1 << 12, 0x00000100] + check('exp compr with the zw pair off prints as v0, v0, off, off', asm_of(w) == 'exp mrt0 v0, v0, off, off done compr vm') + s, text = lines(w) + check(' x, y from the halves of v0; z, w read 0', 'o.mrt0 = float4(f16tof32(v0), f16tof32(v0 >> 16), 0.0, 0.0);' in text) + w = [0xf8000000 | 0xc | 1 << 10 | 1 << 11, 0x00000100] + check('exp compr with the xy pair off prints as off, off, v1, v1', asm_of(w) == 'exp mrt0 off, off, v1, v1 done compr') + check(' z, w from the halves of v1', 'float4(0.0, 0.0, f16tof32(v1), f16tof32(v1 >> 16))' in lines(w)[1]) + check('exp compr with an unpaired enable mask refused', + refused(None, words=[0xf8000000 | 0x1 | 1 << 10 | 1 << 11, 0x00000100])) + w = [0xf8000000 | 0x1 | 8 << 4 | 1 << 11 | 1 << 12, 5] + check('exp mrtz depth alone', asm_of(w) == 'exp mrtz v5, off, off, off done vm' and 'o.depth = F(v5);' in lines(w)[1]) + check('exp mrtz with stencil refused', refused(None, words=[0xf8000000 | 0x3 | 8 << 4 | 1 << 11, 0x0605])) + check('exp mrtz in a vertex stage refused', refused(None, 'vs', words=w)) + w = [0xf8000000 | 9 << 4 | 1 << 11 | 1 << 12, 0] + check('exp null with no data is a no-op', asm_of(w) == 'exp null off, off, off, off done vm' and lines(w)[1] == '') + check('exp null with data refused', refused(None, words=[0xf8000000 | 0x1 | 9 << 4 | 1 << 11, 0])) + # A whole pixel stage that exports depth and colour declares SV_Depth next to SV_Target0. + pipe = G.Pipeline.__new__(G.Pipeline) + pipe.rtv_formats = () + pipe.packed_position_vgpr = None # set by Pipeline.__init__ since upstream #1634 + pipe.resources, pipe.samplers, pipe.uds, pipe.uses_sampler_heap, pipe.helper_text = {}, {}, [], False, None + pipe.vs = pipe.ps = None + pipe.root = FakePipe.root + pipe.ps = G.Stage(pipe, 'ps', words_bytes([0xf8000000 | 0x1 | 8 << 4, 1, 0xf8000000 | 0xf | 1 << 11 | 1 << 12, 0x03020100, + 0xbf810000])) + pipe.vs = pipe.ps + pipe.params, pipe.flat = [], [] + text = pipe.hlsl_ps() + check('depth and colour: SV_Depth and SV_Target0 declared', + 'float depth : SV_Depth;' in text and 'float4 mrt0 : SV_Target0;' in text and 'o.depth = F(v1);' in text) + + +# ---- output modifiers ------------------------------------------------------------------------------ +def output_modifiers(): + w = [0xd4000000 | 0x185 << 16, 256 | 1 << 27] + check('v_cvt_f32_i32 omod prints mul:2', asm_of(w) == 'v_cvt_f32_i32_e64 v0, v0 mul:2') + # Upstream #1707 (VEC_U_TO_F) scales the float value directly, without the U()/F() round trip. + check(' the converted value is doubled', 'v0 = U((float(int(v0))) * 2.0);' in lines(w)[1]) + check('omod on an integer result refused', refused('v_add_nc_u32_e64 v0, v0, v1 mul:2')) + check('clamp on an integer result refused', refused('v_add_nc_u32_e64 v0, v0, v1 clamp')) + w = [0xd4000000 | 0x14b << 16 | 1 << 15 | 1, 258 | 259 << 9 | 0xf2 << 18 | 3 << 27 | 1 << 29] + check('v_fma_f32 clamp div:2 printed with clamp first', asm_of(w) == 'v_fma_f32 v1, -v2, v3, 1.0 clamp div:2') + check(' the clamp applies after the output modifier', + 'v1 = U(saturate((x2w_fma_exact((-F(v2)), F(v3), 1.0)) * 0.5));' in lines(w)[1]) # fused: X2W_DRAW_FMA exact + + +# ---- bit-exact selects and 16-bit results --------------------------------------------------------------- +def selects_and_halves(): + w = [0xd4000000 | 0x101 << 16 | 31, 286 | 286 << 9 | 106 << 18 | 2 << 29] + check('v_cndmask_b32 with -v30 prints the modifier', asm_of(w) == 'v_cndmask_b32_e64 v31, v30, -v30, vcc_lo') + check(' negation flips the sign bit of the selected word', 'v31 = (vcc & 1) ? (v30 ^ 0x80000000u) : v30;' in lines(w)[1]) + w = [0xd4000000 | 0x101 << 16 | 2 << 8 | 3, 259 | 260 << 9 | 106 << 18] + check(' abs clears it', 'v3 = (vcc & 1) ? (v4 & 0x7fffffffu) : v3;' in lines(w)[1]) + w = [0x3a << 25 | 21 << 17 | 21 << 9 | 0xff, 0x7bff] + check('v_min_f16 keeps D[31:16] (gfx10)', asm_of(w) == 'v_min_f16_e32 v21, 0x7bff, v21' and + 'v21 = (v21 & 0xffff0000u) | f32tof16(min(f16tof32(0x00007bffu), f16tof32(v21)));' in lines(w)[1]) + w = [0x39 << 25 | 21 << 17 | 21 << 9 | 0xf2] + check('v_max_f16 takes inline 1.0 in half form', asm_of(w) == 'v_max_f16_e32 v21, 1.0, v21' and + 'f16tof32(0x3c00u)' in lines(w)[1]) + check('v_min_f16 with clamp refused', refused('v_min_f16_e64 v1, v2, v3 clamp')) + check('v_min_f16 with a negated source refused', refused('v_min_f16_e64 v1, -v2, v3')) + w = [0x7e000000 | 5 << 17 | 0xa << 9 | 262] + check('v_cvt_f16_f32 keeps D[31:16] (gfx10)', asm_of(w) == 'v_cvt_f16_f32_e32 v5, v6' and + 'v5 = (v5 & 0xffff0000u) | x2w_f32tof16_rne(F(v6));' in lines(w)[1]) + w = [0xcc000000 | 0x11 << 16 | 1 << 14 | 3, 259 | 0xff << 9 | 1 << 27, 0x7bef] + check('v_pk_min_f16 op_sel_hi:[1,0] prints', asm_of(w) == 'v_pk_min_f16 v3, v3, 0x7bef op_sel_hi:[1,0]') + check(' low from both low halves, high from v3.hi and the literal low half', + lines(w)[1] == 'v3 = f32tof16(min(f16tof32(v3), f16tof32(0x00007befu))) | ' + '(f32tof16(min(f16tof32(v3 >> 16), f16tof32(0x00007befu))) << 16);') + check('v_pk_min_f16 reading a literal high half refused', + refused(None, words=[0xcc000000 | 0x11 << 16 | 1 << 14 | 3, 259 | 0xff << 9 | 3 << 27, 0x7bef])) + check('v_pk_min_f16 with neg_lo refused', refused('v_pk_min_f16 v3, v3, v4 neg_lo:[1,0]')) + + +# ---- integer helpers ---------------------------------------------------------------------------------- +EDGES = [0, 1, 2, 3, 0x7fff, 0x8000, 0xffff, 0x10000, 0x12345678, 0x7fffffff, 0x80000000, 0x80000001, 0xaaaaaaab, + 0xdeadbeef, 0xfffeffff, 0xffff0000, 0xfffffffe, MASK] + + +def integer_helpers(): + e = helper_expr('x2w_mul_hi_u32') + bad = [(a, b) for a in EDGES for b in EDGES if e.run({'a': a, 'b': b})[0] != (a * b) >> 32] + check('x2w_mul_hi_u32 matches (a * b) >> 32 on %d pairs' % len(EDGES) ** 2, not bad) + w = [0xd4000000 | 0x16a << 16 | 1, 256 | 0xff << 9, 0xaaaaaaab] + check('v_mul_hi_u32 lowers to the helper', asm_of(w) == 'v_mul_hi_u32 v1, v0, 0xaaaaaaab' and + 'v1 = x2w_mul_hi_u32(v0, 0xaaaaaaabu);' in lines(w)[1]) + pairs = [(l, h) for l in (0, 1, 0x80000000, 0x12345678, MASK) for h in (0, 1, 0x80000000, 0xdeadbeef, MASK)] + for helper, ref in (('x2w_lshr64', lambda v, n: v >> n), ('x2w_lshl64', lambda v, n: (v << n) & (2 ** 64 - 1))): + lo, hi = helper_expr(helper + '_lo'), helper_expr(helper + '_hi') + bad = [] + for l, h in pairs: + for n in list(range(64)) + [64, 65, 95, 0xffffffc1]: + want = ref(h << 32 | l, n & 63) + env = {'l': l, 'h': h, 'n': n} + if (lo.run(env)[0], hi.run(env)[0]) != (want & MASK, want >> 32): + bad.append((l, h, n)) + check('%s matches the 64-bit reference for counts 0..63 and wrapped counts' % helper, not bad) + w = [0xd4000000 | 0x300 << 16 | 10, 0x80 | 0x80 << 9] + check('v_lshrrev_b64 v[10:11], 0, 0', asm_of(w) == 'v_lshrrev_b64 v[10:11], 0, 0' and + 'q = uint2(x2w_lshr64_lo(0x00000000u, 0x00000000u, 0x00000000u), ' + 'x2w_lshr64_hi(0x00000000u, 0x00000000u, 0x00000000u));\nv10 = q.x;\nv11 = q.y;' in lines(w)[1]) + w = [0xd4000000 | 0x2ff << 16 | 2, 257 | 258 << 9] + check('v_lshlrev_b64 v[2:3], v1, v[2:3] reads both words before writing', + lines(w)[1] == 'q = uint2(x2w_lshl64_lo(v2, v3, v1), x2w_lshl64_hi(v2, v3, v1));\nv2 = q.x;\nv3 = q.y;') + check('a negative inline 64-bit constant is sign-extended', + 'x2w_lshr64_lo(0xffffffffu, 0xffffffffu, v1)' in lines([0xd4000000 | 0x300 << 16 | 10, 257 | 0xc1 << 9])[1]) + # A 32-bit literal in a 64-bit integer operand: only bit 31 decides zero- vs sign-extension, so a literal + # with bit 31 set stays refused and one with bit 31 clear reads a zero high dword (startup_lit64_check.py). + check('a 64-bit literal operand with bit 31 set refused', refused('v_lshrrev_b64 v[10:11], v1, 0x92345678')) + check('a 64-bit literal operand with bit 31 clear has a zero high dword', + not refused('v_lshrrev_b64 v[10:11], v1, 0x12345678')) + w = [0xbf000000 | 0xd << 16 | 0x81 << 8 | 11] + s, text = lines(w) + check('s_bitcmp1_b32 s11, 1 sets SCC from bit 1', asm_of(w) == 's_bitcmp1_b32 s11, 1' and + text == 'scc = ((s11 >> (0x00000001u & 31u)) & 1u) == 1u;') + e = Expr(text[len('scc = '):-1].replace('s11', 'x')) + check(' SCC is S0[S1[4:0]] for every bit', all(e.run({'x': x})[0] == (x >> 1) & 1 for x in EDGES)) + check('s_bitcmp0_b32 tests for zero', 'scc = ((s3 >> (s4 & 31u)) & 1u) == 0u;' in lines([0xbf000000 | 0xc << 16 | 4 << 8 | 3])[1]) + w = [0x80000000 | 0x25 << 23 | 44 << 16 | (0x80 + 54) << 8 | 0x82] + s, text = lines(w) + check('s_bfm_b64 s[44:45], 2, 54 folds to 0x00c00000:00000000', asm_of(w) == 's_bfm_b64 s[44:45], 2, 54' and + s.sym.get(44) == ('const', 0) and s.sym.get(45) == ('const', 0x00c00000)) + check('s_bfm_b64 with a run-time count refused', refused('s_bfm_b64 s[4:5], s6, 0')) + + +def ref_class(x, half): + """IEEE class bit (SIDefines.h ClassFlags order) of a binary32 or binary16 pattern.""" + if half: + x &= 0xffff + value, quiet, sign, tiny = struct.unpack('> 9 & 1, x >> 15, 2.0 ** -14 + else: + value, quiet, sign, tiny = struct.unpack('> 22 & 1, x >> 31, 2.0 ** -126 + if math.isnan(value): + return 1 if quiet else 0 + if math.isinf(value): + return 2 if sign else 9 + if value == 0: + return 5 if sign else 6 + if abs(value) >= tiny: + return 3 if sign else 8 + return 4 if sign else 7 + + +CLASS32 = [0, 0x80000000, 1, 0x80000001, 0x007fffff, 0x807fffff, 0x00800000, 0x80800000, 0x3f800000, 0xbf800000, + 0x7f7fffff, 0xff7fffff, 0x7f800000, 0xff800000, 0x7f800001, 0xff800001, 0x7fbfffff, 0x7fc00000, 0xffc00000, + MASK, 0x7fffffff] +CLASS16 = [0, 0x8000, 1, 0x8001, 0x3ff, 0x83ff, 0x400, 0x8400, 0x3c00, 0xbc00, 0x7bff, 0xfbff, 0x7c00, 0xfc00, 0x7c01, + 0xfc01, 0x7dff, 0x7e00, 0xfe00, 0xffff, 0x7fff, 0x12340000 | 0x7c01] + + +def classes(): + for name, grid, half in (('x2w_class_f32', CLASS32, False), ('x2w_class_f16', CLASS16, True)): + e = helper_expr(name) + bad = [(x, bit) for x in grid for bit in range(10) + if e.run({'x': x, 'mask': 1 << bit})[0] != int(ref_class(x, half) == bit)] + bad += [x for x in grid if e.run({'x': x, 'mask': 0xfffffc00})[0]] # mask bits above 9 never match + check('%s matches the IEEE class of %d patterns for every mask bit' % (name, len(grid)), not bad) + w = [0x7c000000 | 0x88 << 17 | 0xc1] + check('v_cmp_class_f32 vcc_lo, -1, v0: value -1, mask v0', asm_of(w) == 'v_cmp_class_f32_e32 vcc_lo, -1, v0' and + 'vcc = x2w_class_f32(0xffffffffu, v0);' in lines(w)[1]) + w = [0x7c000000 | 0x8f << 17 | 0xff, 0x7c01] + check('v_cmp_class_f16 with a literal value', asm_of(w) == 'v_cmp_class_f16_e32 vcc_lo, 0x7c01, v0' and + 'vcc = x2w_class_f16(0x00007c01u, v0);' in lines(w)[1]) + w = [0xd4000000 | 0x88 << 16 | 32, 0xc1 | 260 << 9] + s, text = lines(w) + check('v_cmp_class_f32_e64 writes an SGPR mask', 's32 = x2w_class_f32(0xffffffffu, v4);' in text and 32 in s.masks) + check(' -|v| sets the f32 sign bit', '((v2 & 0x7fffffffu) ^ 0x80000000u)' in lines([0xd4000000 | 0x88 << 16 | 1 << 8 | 32, + 258 | 260 << 9 | 1 << 29])[1]) + check('v_cmpx_class_f32 writes exec', 'exec = x2w_class_f32(v1, v2);' in lines([0x7c000000 | 0x98 << 17 | 2 << 9 | 257])[1]) + check('v_cmp_lt_f16 still refused', refused('v_cmp_lt_f16_e32 vcc_lo, v1, v2')) + + +# ---- cube-map face selection --------------------------------------------------------------------------- +def ref_cube(s0, s1, s2): + """(id, sc, tc, ma) as LLVM's ConstantFoldAMDGCNCubeIntrinsic computes them.""" + def negative(x): + return math.copysign(1.0, x) < 0 and x != 0 and not math.isnan(x) + if abs(s2) >= abs(s0) and abs(s2) >= abs(s1): + face, sc, tc, ma = (5, -s0, -s1, s2) if negative(s2) else (4, s0, -s1, s2) + elif abs(s1) >= abs(s0): + face, sc, tc, ma = (3, s0, -s2, s1) if negative(s1) else (2, s0, s2, s1) + else: + face, sc, tc, ma = (1, s2, -s1, s0) if negative(s0) else (0, -s2, -s1, s0) + return float(face), sc, tc, ma + ma + + +def cube_helper(): + """The HLSL of x2w_cube as a Python function: if/return statements, ternaries on 'x < 0.0', float4 tuples.""" + text = G.HELPERS['x2w_cube'] + body = text[text.index('{') + 1:text.rindex('}')] + body = re.sub(r'(\w) < 0\.0 \? ([^,]+?) : ([^,)]+)', r'(\2 if \1 < 0.0 else \3)', body) + body = body.replace('&&', 'and').replace('float4(', '(') + source = 'def cube(a, b, c):\n' + for statement in filter(None, (s.strip() for s in body.split(';'))): + if statement.startswith('if'): + cond, ret = re.fullmatch(r'if \((.*)\) (return .*)', statement).groups() + source += ' if %s:\n %s\n' % (cond, ret) + else: + source += ' %s\n' % statement + space = {} + exec(source, space) + return space['cube'] + + +def cubes(): + cube = cube_helper() + values = [0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 2.0, -2.0, 3.0, float('inf'), float('-inf'), float('nan')] + bad = [] + for a in values: + for b in values: + for c in values: + got, want = cube(a, b, c), ref_cube(a, b, c) + if any(not (x == y or (math.isnan(x) and math.isnan(y))) or math.copysign(1, x) != math.copysign(1, y) + for x, y in zip(got, want)): + bad.append((a, b, c, got, want)) + check('x2w_cube matches LLVM cube folding on %d inputs (ties, -0, inf, NaN)' % len(values) ** 3, not bad) + s, text = lines([0xd4000000 | 0x147 << 16 | 23, 276 | 278 << 9 | 274 << 18]) + check('v_cubema_f32 lowers to x2w_cube(...).w', text == 'v23 = U(x2w_cube(F(v20), F(v22), F(v18)).w);') + + +# ---- image_gather4_lz and the typed 16x4 float fetch --------------------------------------------------------- +def gather_setup(s): + for i in range(8): + s.sym[24 + i] = ('desc', ('table', 0), 0x40, i) + for i in range(4): + s.sym[16 + i] = ('const', 0x100 * (i + 1)) + + +def gather(): + base = 0xf0000000 | (0x47 & 0x7f) << 18 | 1 << 3 + w1 = 2 | 8 << 8 | (24 // 4) << 16 | (16 // 4) << 21 + for dmask, channel in ((1, 'Red'), (2, 'Green'), (4, 'Blue'), (8, 'Alpha')): + w = [base | dmask << 8, w1] + _, text = lines(w, setup=gather_setup) + check('image_gather4_lz dmask %#x reads Gather%s into four VGPRs' % (dmask, channel), + 'dmask:0x%x dim:SQ_RSRC_IMG_2D' % dmask in asm_of(w) and + text == 't = r0.Gather%s(q0, float2(F(v2), F(v3)));\nv8 = U(t.x);\nv9 = U(t.y);\nv10 = U(t.z);\nv11 = U(t.w);' % channel) + check('image_gather4_lz with two channels refused', refused(None, setup=gather_setup, words=[base | 3 << 8, w1])) + check('image_gather4_lz tfe refused', refused(None, setup=gather_setup, words=[base | 2 << 8 | 1 << 16, w1])) + check('image_gather4_lz d16 refused', refused(None, setup=gather_setup, words=[base | 2 << 8, w1 | 1 << 31])) + check('image_gather4_lz on a 2D array refused', + refused(None, setup=gather_setup, words=[(base & ~(7 << 3)) | 5 << 3 | 2 << 8, w1])) + check('image_gather4 (implicit level) still refused', refused(None, setup=gather_setup, + words=[0xf0000000 | (0x40 & 0x7f) << 18 | 1 << 3 | 1 << 8, w1])) + + +def typed_fetch(): + def setup(s): + for i in range(4): + s.sym[20 + i] = ('desc', ('table', 0), 0x80, i) + s = stage([]) + setup(s) + s.lines = [] + s.one('tbuffer_load_format_xyzw', 'tbuffer_load_format_xyzw v[0:3], v4, s[20:23], 0 format:[BUF_FMT_16_16_16_16_FLOAT] offen') + text = '\n'.join(s.lines) + check('BUF_FMT_16_16_16_16_FLOAT: four halves from two dwords', + text == 'a = v4 + 0;\nw = ldu(r0, a);\nv0 = U(f16tof32(w));\nv1 = U(f16tof32(w >> 16));\n' + 'v2 = U(f16tof32(ldu(r0, a + 4)));\nv3 = U(f16tof32(ldu(r0, a + 4) >> 16));') + + +# ---- control-flow joins --------------------------------------------------------------------------------- +JOIN = [0xf4000000 | 2 << 18 | 12 << 6 | 4, 125 << 25 | 0x20, # s_load_dwordx4 s[12:15], s[8:9], 0x20 + 0xbf000000 | 6 << 16 | 0x80 << 8 | 20, # s_cmp_eq_u32 s20, 0 + 0xbf840000 | 3, # s_cbranch_scc0 +0x1c + 0xf4000000 | 0xa << 18 | 12 << 6 | 6, 125 << 25 | 0x50, # s_buffer_load_dwordx4 s[12:15], s[12:15], 0x50 + 0xbf820000 | 2, # s_branch +0x24 + 0xf4000000 | 8 << 18 | 16 << 6 | 6, 125 << 25 | 0x10] # s_buffer_load_dword s16, s[12:15], 0x10 + + +def joins(): + s = stage(JOIN) + text = '\n'.join(line for block in s.blocks for line in block[1]) + check('a branch target reached only by the branch keeps the descriptor the branch saw', + 's16 = r0.Load(0x00000010u + 0);' in text and s.pipe.resources == {(('table', 0), 0x20): dict(index=0, kind='buf')}) + fall = JOIN[:6] + [0xbf800000] + JOIN[7:] # s_nop instead of s_branch: the clobbered path falls through + try: + stage(fall) + except G.Unsupported as error: + check('a join of a descriptor and a loaded word refused (%s)' % error, 'conflict' in str(error)) + else: + check('a join of a descriptor and a loaded word refused', False) + + +# ---- v_cvt_pknorm_{u16,i16}_f32 --------------------------------------------------------------------------- +def f32(x): + return struct.unpack(' MIN ? (X > MAX ? MAX : X) + : MIN, so NaN takes MIN; the product is a binary32 multiply. + """ + lo, scale = (-1.0, 32767.0) if signed_form else (0.0, 65535.0) + clamped = (1.0 if x > 1.0 else x) if x > lo else lo + return int(roundeven(f32(clamped * scale))) & 0xffff + + +def pknorm_helper(name): + """The HLSL of x2w_pknorm_[ui]16 as a Python function over a binary32 value (the bits come in as a float).""" + text = G.HELPERS[name] + body = text[text.index('{') + 1:text.rindex('}')] + body = re.sub(r'\b(0x[0-9a-f]+|\d+)u\b', r'\1', body) + body = re.sub(r'round\((.*) \* ([\d.]+)\)', r'rne(f32(\1 * \2))', body) + source = 'def helper(x):\n' + for statement in filter(None, (s.strip() for s in body.split(';'))): + m = re.fullmatch(r'if \((.*)\) (return .*)', statement) + source += (' if %s:\n %s\n' % m.groups()) if m else ' %s\n' % statement + space = dict(asuint=lambda v: struct.unpack(' 32768, snorm 0.5 -> 16384', + pknorm_helper('x2w_pknorm_u16')(0.5) == 32768 and pknorm_helper('x2w_pknorm_i16')(0.5) == 16384) + vop3 = lambda op, extra=0, w1extra=0: [0xd4000000 | op << 16 | extra | 7, (256 + 7) | (256 + 4) << 9 | w1extra] + w = vop3(0x369) + _, text = lines(w) + check('v_cvt_pknorm_u16_f32: S0 in the low half, S1 in the high half', + asm_of(w) == 'v_cvt_pknorm_u16_f32 v7, v7, v4' and + text == 'v7 = x2w_pknorm_u16(F(v7)) | (x2w_pknorm_u16(F(v4)) << 16);') + w = vop3(0x368, w1extra=1 << 29) + _, text = lines(w) + check('v_cvt_pknorm_i16_f32 applies the source neg before packing', + asm_of(w) == 'v_cvt_pknorm_i16_f32 v7, -v7, v4' and + text == 'v7 = x2w_pknorm_i16((-F(v7))) | (x2w_pknorm_i16(F(v4)) << 16);') + check('v_cvt_pknorm_u16_f32 clamp refused', refused(None, words=vop3(0x369, 1 << 15))) + check('v_cvt_pknorm_u16_f32 omod refused', refused(None, words=vop3(0x369, 0, 1 << 27))) + + +# ---- scalar ALU: shift-add, abs, SOPK arithmetic, pack, and the SCC liveness check ------------------------- +SOP2 = lambda op, d, a, b: 0x80000000 | op << 23 | d << 16 | b << 8 | a +LSHL2_ADD = SOP2(0x2f, 20, 21, 22) # s_lshl2_add_u32 s20, s21, s22 +CSELECT = SOP2(0x0a, 23, 20, 21) # s_cselect_b32 s23, s20, s21 (reads SCC) +CMP_EQ = 0xbf000000 | 6 << 16 | 21 << 8 | 20 # s_cmp_eq_u32 s20, s21 (writes SCC) +NOP = 0xbf800000 +SOPP = lambda op, n: 0xbf800000 | op << 16 | (n & 0xffff) # s_branch 2, s_cbranch_scc1 5, vccz 6, vccnz 7 + + +class SignedExpr(Expr): + """Expr plus the signed max of s_abs_i32's lowering.""" + @staticmethod + def call(name, args): + if name == 'max': + (a, sa), (b, sb) = args + assert sa and sb + return max(G_signed(a), G_signed(b)) & MASK, True + return Expr.call(name, args) + + +def G_signed(v): + return v - (1 << 32) if v >> 31 else v + + +def translates(words): + try: + stage(words) + except G.Unsupported as error: + return str(error) + return None + + +def scalar_alu(): + grid = [0, 1, 2, 0x7fff, 0x8000, 0xffff, 0x10000, 0x12345678, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffffe, MASK] + _, text = lines([LSHL2_ADD]) + check('s_lshl2_add_u32 is (S0 << 2) + S1', asm_of([LSHL2_ADD]) == 's_lshl2_add_u32 s20, s21, s22' and + text == 's20 = (s21 << 2) + s22;') + e = Expr(text.split(' = ', 1)[1].rstrip(';')) + check('s_lshl2_add_u32 wraps modulo 2^32 on the grid', + all(e.run({'s21': a, 's22': b})[0] == ((a << 2) + b) & MASK for a in grid for b in grid)) + for n, op in ((1, 0x2e), (3, 0x30), (4, 0x31)): + _, text = lines([SOP2(op, 20, 21, 22)]) + check('s_lshl%d_add_u32 shifts by %d' % (n, n), text == 's20 = (s21 << %d) + s22;' % n) + w = 0xbe800000 | 20 << 16 | 0x34 << 8 | 21 + _, text = lines([w]) + e = SignedExpr(text.split(' = ', 1)[1].rstrip(';')) + check('s_abs_i32 is smax(x, -x): INT_MIN stays INT_MIN (LLVM selects it for that pattern)', + asm_of([w]) == 's_abs_i32 s20, s21' and + all(e.run({'s21': a})[0] == (abs(G_signed(a)) & MASK) for a in grid) and + e.run({'s21': 0x80000000})[0] == 0x80000000) + w = SOP2(0x32, 20, 21, 22) + _, text = lines([w]) + e = Expr(text.split(' = ', 1)[1].rstrip(';')) + check('s_pack_ll_b32_b16 puts S0[15:0] low and S1[15:0] high', + asm_of([w]) == 's_pack_ll_b32_b16 s20, s21, s22' and + all(e.run({'s21': a, 's22': b})[0] == (a & 0xffff) | (b & 0xffff) << 16 for a in grid for b in grid)) + for op, name, sym in ((0xf, 's_addk_i32', '+'), (0x10, 's_mulk_i32', '*')): + w = 0xb0000000 | op << 23 | 20 << 16 | 0xfff0 + _, text = lines([w]) + check('%s sign-extends its simm16 (0xfff0 is -16)' % name, + asm_of([w]) == '%s s20, 0xfff0' % name and text == 's20 = s20 %s 0xfffffff0u;' % sym) + w = 0xb0000000 | op << 23 | 20 << 16 | 0x150 + _, text = lines([w]) + check('%s with a positive simm16' % name, text == 's20 = s20 %s 0x00000150u;' % sym) + # SCC: refused only when an unmodelled SCC value can reach a reader + addk = 0xb0000000 | 0xf << 23 | 20 << 16 | 4 + mulk = 0xb0000000 | 0x10 << 23 | 20 << 16 | 4 + cases = [ + ('unmodelled SCC read straight after', [LSHL2_ADD, CSELECT], True), + ('SCC redefined by s_cmp before the read', [LSHL2_ADD, CMP_EQ, CSELECT], False), + ('no reader at all', [LSHL2_ADD, NOP], False), + ('s_cbranch_scc1 reads it', [LSHL2_ADD, SOPP(5, 0), NOP], True), + ('a branch around the redefinition reaches the reader', + [LSHL2_ADD, SOPP(6, 1), CMP_EQ, CSELECT], True), + ('both paths redefine it', [LSHL2_ADD, SOPP(6, 2), CMP_EQ, SOPP(2, 1), CMP_EQ, CSELECT], False), + ('a loop carries it back to a reader at the head', [CSELECT, LSHL2_ADD, SOPP(7, -3)], True), + ('a loop that redefines it at the head', [CMP_EQ, CSELECT, LSHL2_ADD, SOPP(7, -4)], False), + ('s_addk_i32 defines SCC (signed overflow, not modelled)', [addk, CSELECT], True), + ('s_mulk_i32 does not define SCC', [CMP_EQ, mulk, CSELECT], False), + ('src_scc as an operand is a reader', [LSHL2_ADD, SOP2(0x00, 23, 0xfd, 21)], True), + ] + for label, words, want_refused in cases: + reason = translates(words) + check('SCC liveness: %s -> %s%s' % (label, 'refused' if want_refused else 'translated', + (' (%s)' % reason) if reason else ''), + (reason is not None and 'SCC of' in reason) if want_refused else reason is None) + + +# ---- v_fma_mix_f32 and the f16 operands of the mix family ------------------------------------------------- +def mix_word(op, vdst, srcs, op_sel=0, op_sel_hi=0, neg=0, absolute=0, clamp=0): + return [0xcc000000 | op << 16 | (op_sel_hi >> 2 & 1) << 14 | op_sel << 11 | absolute << 8 | clamp << 15 | vdst, + srcs[0] | srcs[1] << 9 | srcs[2] << 18 | (op_sel_hi & 3) << 27 | neg << 29] + + +def mixes(): + # op_sel / op_sel_hi as [src0, src1, src2] bit 0, 1, 2 + cases = [ + (mix_word(0x20, 1, (258, 20, 128), op_sel=2, op_sel_hi=2, neg=4), + 'v_fma_mix_f32 v1, v2, s20, -0 op_sel:[0,1,0] op_sel_hi:[0,1,0]', + 'v1 = U(F(v2) * f16tof32(s20 >> 16) + (-0.0));', + 'f32 result; op_sel_hi makes src1 an f16 and op_sel takes its high half; -0 is +0 negated'), + (mix_word(0x20, 1, (242, 32, 268), op_sel_hi=2, neg=6), + 'v_fma_mix_f32 v1, 1.0, -s32, -v12 op_sel_hi:[0,1,0]', + 'v1 = U(1.0 * (-f16tof32(s32)) + (-F(v12)));', + 'neg applies to the converted f16 and to the f32 operand'), + (mix_word(0x20, 1, (258, 259, 260), op_sel_hi=1, absolute=1, clamp=1), + 'v_fma_mix_f32 v1, |v2|, v3, v4 op_sel_hi:[1,0,0] clamp', + 'v1 = U(saturate(abs(f16tof32(v2)) * F(v3) + F(v4)));', + 'abs on a low-half f16 source, clamp on the f32 result'), + (mix_word(0x21, 1, (242, 258, 240), op_sel_hi=4), + 'v_fma_mixlo_f16 v1, 1.0, v2, 0.5 op_sel_hi:[0,0,1]', + 'v1 = (v1 & 0xffff0000u) | x2w_f32tof16_rne(1.0 * F(v2) + f16tof32(0x3800u));', + 'an inline 0.5 read as f16 is 0x3800 (not the low half of the f32 0x3f000000)'), + ] + for words, want_asm, want_text, label in cases: + got_asm = asm_of(words) + _, text = lines(words) if got_asm == want_asm else (None, None) + check('fma_mix: %s' % label, got_asm == want_asm and text == want_text) + check('fma_mix: op_sel on an f32 operand refused', + refused(None, words=mix_word(0x20, 1, (258, 259, 260), op_sel=1))) + check('fma_mix: high half of an inline f16 constant refused', + refused(None, words=mix_word(0x20, 1, (240, 259, 260), op_sel=1, op_sel_hi=1))) + # A literal f16 operand reads the half op_sel selects (LLVM SIFoldOperands::tryFoldImmWithOpSel; + # tests/startup_literal_halves_check.py). Formerly refused here. + check('fma_mix: literal f16 operand reads its low half', + lines(mix_word(0x20, 1, (255, 259, 260), op_sel_hi=1) + [0x3c00])[1] + == 'v1 = U(f16tof32(0x3c00u) * F(v3) + F(v4));') + check('fma_mix: literal f16 operand with op_sel reads its high half', + lines(mix_word(0x20, 1, (255, 259, 260), op_sel=1, op_sel_hi=1) + [0x3c00])[1] + == 'v1 = U(f16tof32(0x0000u) * F(v3) + F(v4));') + check('fma_mix: inline 1/(2*pi) refused', refused(None, words=mix_word(0x20, 1, (248, 259, 260)))) + + +# ---- SDWA select and compare, null-export classification, a16 image addresses, entry VGPR reads ------------- +def sdwa_and_misc(): + w = [0x1 << 25 | 10 << 17 | 10 << 9 | 0xf9, 10 | 6 << 8 | 4 << 16 | 5 << 24] + _, text = lines(w) + check('v_cndmask_b32_sdwa selects between the source fields by vcc', + asm_of(w) == 'v_cndmask_b32_sdwa v10, v10, v10, vcc_lo dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 ' + 'src1_sel:WORD_1' and + text == 'v10 = (vcc & 1) ? ((v10 >> 16u) & 0xffffu) : ((v10 >> 0u) & 0xffffu);') + w = [0x7c000000 | 0x95 << 17 | 15 << 9 | 0xf9, 20 | 6 << 16 | 1 << 23 | 4 << 24] + _, text = lines(w) + check('v_cmpx_ne_i32_sdwa compares the selected fields and writes exec', + asm_of(w) == 'v_cmpx_ne_i32_sdwa s20, v15 src0_sel:DWORD src1_sel:WORD_0' and + text == 'exec = ((int(s20) != int(((v15 >> 0u) & 0xffffu))) ? 1u : 0u);') + w = [0x7c000000 | 0x85 << 17 | 15 << 9 | 0xf9, 20 | 6 << 16 | 1 << 23 | 4 << 24 | 1 << 27] + _, text = lines(w) + check('v_cmp_ne_i32_sdwa with sext() sign-extends the field into vcc', + asm_of(w) == 'v_cmp_ne_i32_sdwa vcc_lo, s20, sext(v15) src0_sel:DWORD src1_sel:WORD_0' and + text == 'vcc = ((int(s20) != int(asuint(asint(v15 << 16u) >> 16u))) ? 1u : 0u);') + check('v_cmp_lt_f32_sdwa (a float SDWA compare) refused', + refused(None, words=[0x7c000000 | 0x01 << 17 | 15 << 9 | 0xf9, 20 | 6 << 16 | 1 << 23 | 4 << 24])) + null = words_bytes([0xf8000000 | 9 << 4 | 1 << 11 | 1 << 12, 0, 0xbf810000]) + check('a stage whose only export is "exp null ... done vm" is a pixel stage', G.classify(null) == 'ps') + + load = [0xf0000000 | 3 << 8 | 1 << 3, 2 | 8 << 8 | (24 // 4) << 16 | 1 << 30] + _, text = lines(load, setup=gather_setup) + check('image_load a16 takes x and y from the halves of one address dword', + asm_of(load).endswith('dim:SQ_RSRC_IMG_2D a16') and + text == 't = r0.Load(int3((v2 & 0xffffu), (v2 >> 16), 0));\nv8 = U(t.x);\nv9 = U(t.y);') + sample = [0xf0000000 | 0x20 << 18 | 3 << 8 | 1 << 3, 2 | 8 << 8 | (24 // 4) << 16 | (16 // 4) << 21 | 1 << 30] + _, text = lines(sample, setup=gather_setup) + check('image_sample a16 takes binary16 u and v from the halves of one address dword', + 'f16tof32(v2), f16tof32(v2 >> 16)' in text and 'v3' not in text) + load1d = [0xf0000000 | 1 << 8, 2 | 8 << 8 | (24 // 4) << 16] + s, text = lines(load1d, setup=gather_setup) + check('image_load on a 1D image is Texture1D.Load(int2(x, 0)) with manifest kind tex1d', + asm_of(load1d).endswith('dmask:0x1 dim:SQ_RSRC_IMG_1D') and + text == 't = r0.Load(int2(v2, 0));\nv8 = U(t.x);' and list(s.pipe.resources.values())[0]['kind'] == 'tex1d') + _, text = lines([sample[0], sample[1] | 1 << 31], setup=gather_setup) + check('image_sample d16 packs two binary16 results into one VGPR (gfx9+ packed D16)', + text.endswith('v8 = f32tof16(t.x) | (f32tof16(t.y) << 16);') and 'v9' not in text) + check('image_sample unorm refused', refused(None, setup=gather_setup, words=[sample[0] | 1 << 12, sample[1]])) + check('image_load tfe refused', refused(None, setup=gather_setup, words=[load[0] | 1 << 16, load[1]])) + + mov = 0x7e000000 | 3 << 17 | 1 << 9 | (256 + 1) # v_mov_b32 v3, v1 + s = stage([0x7e000000 | 1 << 17 | 1 << 9 | 0x80, mov]) # v_mov_b32 v1, 0 first + t = stage([mov]) + check('a pixel read of a VGPR before any write is recorded as an entry (SPI input) read', + s.entry_reads == {} and t.entry_reads == {1: 0}) + # A whole request: the interpolated v0..v11 then four moves into the exported v12..v15. Reading v20, which no + # instruction writes, is a read of an SPI input: translate_to writes a .fail instead of a result. + import tempfile + import startup_gfx2hlsl_bit_alu_check as B + def moves(sources): + return words_bytes([0x7e000000 | (12 + i) << 17 | 1 << 9 | (256 + r) for i, r in enumerate(sources)]) + vs = B.vs_words([(0, 0, 0)] * 4) + results = {} + with tempfile.TemporaryDirectory() as directory: + for label, sources in (('control', (0, 1, 2, 3)), ('entry', (0, 1, 20, 3))): + ps = B.PRE_WORDS + moves(sources) + B.POST_WORDS + outcome = G.translate_to(directory, 1, vs, ps, B.root_blob(), check=False) + results[label] = (outcome, Path(directory, '%016x.txt' % 1).exists()) + for leftover in Path(directory).iterdir(): + leftover.unlink() + check('translate_to refuses a pixel stage that reads an entry VGPR (%s); its control translates' + % results['entry'][0], + results['control'] == ('ok', True) and results['entry'][1] is False and 'entry VGPR v20' in results['entry'][0]) + + +def main(): + exports() + output_modifiers() + selects_and_halves() + integer_helpers() + classes() + cubes() + gather() + typed_fetch() + joins() + pknorm() + scalar_alu() + mixes() + sdwa_and_misc() + if failures: + raise SystemExit('FAILED: %s' % '; '.join(failures)) + print('startup gfx2hlsl coverage checks: 0 failed') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_f32_lg_local_check.py b/tests/startup_gfx2hlsl_f32_lg_local_check.py new file mode 100644 index 0000000000..c642f52e61 --- /dev/null +++ b/tests/startup_gfx2hlsl_f32_lg_local_check.py @@ -0,0 +1,747 @@ +"""f32 VOPC conditions in tools/startup/gfx2hlsl.py, lg and nlg on NaN operands among them (#1920). + + (no arguments) translation controls, pure Python + binary assemble the decoded text of every checked form and of the pixel fixtures with + llvm-mc and compare with the words built here + decode disassemble the same words with LLVM's C API and compare with + tools/disasm_rdna2.py + draw [fxc] + compile the pixel fixtures with FXC ps_5_1 when given and with DXC ps_6_0, + draw 16 x 16 pixels each and compare every pixel with the ISA reference + (needs tests/offscreen_check.cpp built as offscreen_check) + +In the gfx10 ISA V_CMP_LG_F32 is "less or greater": ordered and not equal, false when either source is NaN. +V_CMP_NLG_F32 is its negation, true when either source is NaN. HLSL != is unordered (true with a NaN), so the old +lowering `a != b` and `!(a != b)` gave the opposite result whenever a source was NaN. The lowering is now +`(ORDERED && (a < b || a > b))` and its negation, ORDERED testing both source words for NaN on their bits: DXC +marks float compares fast unless -Gis, and the draw records whether the same text without the bit test holds. + +The reference is written here from the ISA definitions with integer arithmetic on the bit patterns: a NaN is an +exponent of all ones with a non-zero mantissa; ordered sources compare by sign and magnitude, with +0 equal to -0 and +denormals kept; lt, eq, le, gt, lg and ge are false when a source is NaN; the n-forms are their negations; o is both +sources ordered and u either unordered; f and t are constant. + +Controls: every f32 condition in the compare table (v_cmp and v_cmpx; the e32 form and the e64 form under every +neg/abs combination on both sources) is decoded from words built here, translated, and the emitted HLSL is evaluated +on the CPU with IEEE binary32 comparisons over every pair of 16 source words: +-0, +-min denormal, +-1.0, +-max +finite, +-inf, +-quiet NaN, +-signalling NaN and +-NaN with a payload. The same forms with the old `!=` lowering +restored must disagree with the reference. The f32 SDWA compares stay refused. + +The draws: a source-built pixel program builds one of those 16 words from the pixel's x and one from its y with +integer operations, so 16 x 16 pixels cover every pair: finite unequal, equal (+0 and -0 among them), infinite and +NaN sources. Fixture `cmp` writes four v_cmp results as 1.0 or 0.0: v_cmp_lg_f32_e32, v_cmp_nlg_f32_e64 (-a, |b|), +v_cmp_lg_f32_e64 (-|a|, -b) and v_cmp_nlg_f32_e32. Each `cmpx_*` fixture keeps a pixel when its v_cmpx form holds +and exports the packed position; a discarded pixel keeps the clear value -1.0. D3D lets a backend flush binary32 +denormal sources of a compare to signed zero, so every fixture must match the reference image with denormals kept +or the one with them flushed, the same choice for all fixtures of one compiler and adapter. Each translation with +the old `!=` lowering restored must fail its draw against both images and match its own image. +""" +import math +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble # noqa: E402 +from startup_gfx2hlsl_vopc_sdwa_check import COMPARES, Probe, source, vopc_sdwa # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +MASK = 0xffffffff +SIGN = 0x80000000 +SGPR_DST = 6 +# The 16 source words: each class with the sign bit clear and set. +CLASSES = [0x00000000, 0x00000001, 0x3f800000, 0x7f7fffff, 0x7f800000, 0x7fc00000, 0x7f800001, 0x7fc12345] +VALUES = [c | sign for c in CLASSES for sign in (0, SIGN)] +PAIRS = [(a, b) for a in VALUES for b in VALUES] +# Every f32 condition the compare table lowers; v_cmp_class_f32 and v_cmp_tru_f32 stay refused. +F32_OPS = sorted(op for op, (_, cond, typ) in COMPARES.items() if typ == 'f32' and cond not in ('class', 'tru')) +MODIFIERS = [(neg, absolute) for neg in (False, True) for absolute in (False, True)] + + +# ---- the ISA reference, on bit patterns ------------------------------------------------------------------------- +def is_nan(bits): + return (bits & 0x7fffffff) > 0x7f800000 + + +def key(bits): + """Order of an ordered binary32 word: sign and magnitude, +0 and -0 equal, denormals kept.""" + magnitude = bits & 0x7fffffff + return -magnitude if bits & SIGN else magnitude + + +def modified(bits, neg, absolute): + """The VOP3/SDWA source modifiers: abs clears the sign bit, then neg flips it.""" + if absolute: + bits &= 0x7fffffff + return bits ^ SIGN if neg else bits + + +ORDERED = {'lt': lambda x, y: x < y, 'eq': lambda x, y: x == y, 'le': lambda x, y: x <= y, + 'gt': lambda x, y: x > y, 'lg': lambda x, y: x != y, 'ge': lambda x, y: x >= y} + + +def reference(cond, a, b): + unordered = is_nan(a) or is_nan(b) + if cond in ('f', 't'): + return int(cond == 't') + if cond in ('o', 'u'): + return int(unordered == (cond == 'u')) + if cond in ORDERED: + return int(not unordered and ORDERED[cond](key(a), key(b))) + assert cond[0] == 'n' and cond[1:] in ORDERED, cond + return 1 - reference(cond[1:], a, b) + + +def old_reference(cond, a, b): + """The lowering before #1920: lg as unordered not-equal, nlg its negation.""" + if cond in ('lg', 'nlg'): + ne = is_nan(a) or is_nan(b) or key(a) != key(b) + return int(ne != (cond == 'nlg')) + return reference(cond, a, b) + + +# ---- a small evaluator for the compare HLSL the lowering emits (uint words, binary32 floats, bools) ------------- +TOKEN = re.compile(r'\s*(0x[0-9a-fA-F]+u?|\d+\.\d+|\d+u?|[A-Za-z_]\w*|<=|>=|==|!=|\|\||&&|[-&!<>?:(),])') +LEVELS = [['||'], ['&&'], ['&'], ['==', '!='], ['<', '>', '<=', '>=']] + + +def as_float(word): + return struct.unpack('': a > b, '<=': a <= b, '>=': a >= b}[kind]) + + @staticmethod + def truth(value): + kind, v = value + assert kind in ('b', 'u'), value + return v != 0 + + +# ---- encoding --------------------------------------------------------------------------------------------------- +VGPR = 256 +VCC_LO = 106 +INLINE = {0: 128, 1: 129, 15: 143, 16: 144, 31: 159, 0x3f800000: 242} # integers and 1.0 + + +def operand(value): + """(source code, literal or None) of a 32-bit constant.""" + if value in INLINE: + return INLINE[value], None + if 1 <= value <= 64: + return 128 + value, None + return 255, value + + +def vop1_mov(vdst, value): + code, literal = operand(value) + return struct.pack(' Y))` with ORDERED the bit test of both source words, and the old one, +# `(X != Y)`: X and Y are F(vN) under optional abs() and negation, so neither holds a ' < ', ' > ' or '||'. +ORDERED_TEXT = r'\((?P\w+) & 0x7fffffffu\) <= 0x7f800000u' +LG_TEXT = re.compile(r'\(%s && %s && \((?P[^<>|]+?) < (?P[^<>|]+?) \|\| (?P=x) > (?P=y)\)\)' % ( + ORDERED_TEXT.format(0), ORDERED_TEXT.format(1))) + + +def old_lowering(text): + """The same text with lg and nlg lowered as before #1920.""" + return LG_TEXT.sub(lambda m: '(%s != %s)' % (m.group('x'), m.group('y')), text) + + +def unguarded(text): + """lg as less or greater without the bit test: exact in HLSL, not under DXC's fast compares on every driver.""" + return LG_TEXT.sub(lambda m: '(%s < %s || %s > %s)' % (m.group('x'), m.group('y'), m.group('x'), m.group('y')), + text) + + +def first_mismatch(expr, cond, mods, model=reference): + (neg0, abs0), (neg1, abs1) = mods + for a, b in PAIRS: + want = model(cond, modified(a, neg0, abs0), modified(b, neg1, abs1)) + got = expr.run({'v1': a, 'v2': b}) + if got != want: + return a, b, got, want + return None + + +# The lowering of every other condition before #1920, for v_cmp_*_f32_e32 vcc_lo, v1, v2. nlt, nle, ngt, nge, o and u +# changed with #1936 and are checked in tests/startup_gfx2hlsl_f32_nan_check.py. +UNCHANGED = {'f': 'false', 'lt': 'F(v1) < F(v2)', 'eq': 'F(v1) == F(v2)', 'le': 'F(v1) <= F(v2)', + 'gt': 'F(v1) > F(v2)', 'ge': 'F(v1) >= F(v2)', 'neq': '!(F(v1) == F(v2))'} +NAN_FORMS = ('nlt', 'nle', 'ngt', 'nge', 'o', 'u') + + +def controls(): + # 1. The value set and the reference. + check('16 source words: +-0, +-min denormal, +-1.0, +-max finite, +-inf, +-quiet, signalling and payload NaN', + len(set(VALUES)) == 16 and sum(map(is_nan, VALUES)) == 6 + and sum(math.isnan(as_float(v)) for v in VALUES) == 6 + and {as_float(v) for v in VALUES if not is_nan(v)} == {0.0, 2.0 ** -149, -2.0 ** -149, 1.0, -1.0, + as_float(0x7f7fffff), -as_float(0x7f7fffff), + math.inf, -math.inf}) + ordered = [(a, b) for a, b in PAIRS if not is_nan(a) and not is_nan(b)] + check('reference: the ordered relations match IEEE binary32 on every ordered pair', all( + reference(cond, a, b) == int(ORDERED[cond](as_float(a), as_float(b))) for cond in ORDERED for a, b in ordered)) + check('reference: +0 and -0 are equal, the min denormals are not', + reference('eq', 0, SIGN) and not reference('lg', 0, SIGN) and reference('lg', 1, SIGN | 1) + and reference('lt', SIGN | 1, 0)) + nan_pairs = [(a, b) for a, b in PAIRS if is_nan(a) or is_nan(b)] + check('reference: %d pairs with a NaN: lg false, nlg true, u true, o false' % len(nan_pairs), all( + (reference('lg', a, b), reference('nlg', a, b), reference('u', a, b), reference('o', a, b)) == (0, 1, 1, 0) + for a, b in nan_pairs)) + check('reference: the old lowering differs on exactly the NaN pairs', all( + (old_reference(cond, a, b) != reference(cond, a, b)) == (is_nan(a) or is_nan(b)) + for cond in ('lg', 'nlg') for a, b in PAIRS)) + check('every f32 condition of the table is checked (%d opcodes)' % len(F32_OPS), len(F32_OPS) == 30 and sorted( + {COMPARES[op][1] for op in F32_OPS}) == sorted(set(UNCHANGED) | {'lg', 'nlg'} | set(NAN_FORMS))) + + # 2. The new lowering's text; every other condition keeps its text. + asm, stage = translate(compare_code(0x05, 'e32')) + ordered = '(v1 & 0x7fffffffu) <= 0x7f800000u && (v2 & 0x7fffffffu) <= 0x7f800000u' + check('v_cmp_lg_f32_e32: %s' % stage.lines, stage.lines == [ + 'vcc = (((%s && (F(v1) < F(v2) || F(v1) > F(v2)))) ? 1u : 0u);' % ordered]) + asm, stage = translate(compare_code(0x0a, 'e32')) + check('v_cmp_nlg_f32_e32: %s' % stage.lines, stage.lines == [ + 'vcc = ((!(%s && (F(v1) < F(v2) || F(v1) > F(v2)))) ? 1u : 0u);' % ordered]) + asm, stage = translate(compare_code(0x1a, 'e64', ((True, True), (False, True)))) + check('v_cmpx_nlg_f32_e64 tests the words under the modifiers: %s' % stage.lines, stage.lines == [ + 'exec = ((!(%s && ((-abs(F(v1))) < abs(F(v2)) || (-abs(F(v1))) > abs(F(v2))))) ? 1u : 0u);' % ordered]) + changed = [] + for op in F32_OPS: + cmpx, cond, _ = COMPARES[op] + if cmpx or cond in ('lg', 'nlg') + NAN_FORMS: + continue + asm, stage = translate(compare_code(op, 'e32')) + if stage.lines != ['vcc = ((%s) ? 1u : 0u);' % UNCHANGED[cond]]: + changed.append((asm, stage.lines)) + check('the %d other conditions keep their lowering' % len(UNCHANGED), not changed, str(changed)) + + # 3. Every form of every condition equals the reference on every pair; the old lg/nlg lowering does not. + forms = evaluations = 0 + wrong, caught, missed, first = [], 0, [], None + for op, form, mods, destination in all_forms(): + cmpx, cond, _ = COMPARES[op] + asm, stage = translate(compare_code(op, form, mods)) + target = {'exec': 'exec', 'vcc': 'vcc', 'sgpr': 's%d' % SGPR_DST}[destination] + if (len(stage.lines) != 1 or not stage.lines[0].startswith(target + ' = ') + or (destination == 'sgpr') != (SGPR_DST in stage.masks) or stage.exec_known == cmpx): + wrong.append((asm, stage.lines, 'destination')) + continue + text = stage.lines[0][len(target) + 3:-1] + forms += 1 + evaluations += len(PAIRS) + miss = first_mismatch(Expr(text), cond, mods) + if miss: + wrong.append((asm, ['%08x' % miss[0], '%08x' % miss[1]], miss[2:])) + if cond in ('lg', 'nlg'): + # Under IEEE comparisons the bit test changes nothing; it is there for fast compares. + loose = unguarded(text) + if loose == text or first_mismatch(Expr(loose), cond, mods): + wrong.append((asm, 'without the bit test', loose)) + old = old_lowering(text) + miss = first_mismatch(Expr(old), cond, mods) if old != text else None + if miss and not first_mismatch(Expr(old), cond, mods, old_reference): + caught += 1 + first = first or '%s with %s: a=%08x b=%08x gives %d, the ISA %d' % (asm, old, *miss) + else: + missed.append(asm) + check('%d f32 forms x %d pairs (%d evaluations) equal the ISA reference' % (forms, len(PAIRS), evaluations), + not wrong and forms == len(F32_OPS) * 17, str(wrong[:3])) + check('old != lowering fails %d of %d lg/nlg forms against the reference and matches its own model' % ( + caught, caught + len(missed)), caught == 4 * 17 and not missed, str(missed[:3])) + print(' first: ' + str(first)) + + # 4. EXEC already reduced: the compare result is masked by the lane's EXEC bit. + wrong = [] + for op in F32_OPS: + cmpx, cond, _ = COMPARES[op] + if cond not in ('lg', 'nlg'): + continue + for form in ('e32', 'e64'): + mods = ((True, False), (False, True)) + asm, stage = translate(compare_code(op, form, mods), exec_known=False) + expr = Expr(stage.lines[0].split(' = ', 1)[1][:-1]) + for a, b in PAIRS: + for lane in (0, 1): + want = lane & reference(cond, modified(a, True, False), modified(b, False, True)) + if form == 'e32': + want = lane & reference(cond, a, b) + if expr.run({'v1': a, 'v2': b, 'exec': lane}) != want: + wrong.append((asm, hex(a), hex(b), lane)) + check('inactive lane: lg/nlg results masked by EXEC in the e32 and e64 forms', not wrong, str(wrong[:3])) + + # 5. The f32 SDWA compares stay refused (#1906): lg and nlg, v_cmp and v_cmpx, with and without modifiers. + refused = [] + for op in F32_OPS: + cmpx, cond, _ = COMPARES[op] + if cond not in ('lg', 'nlg'): + continue + for neg, absolute in MODIFIERS: + name, asm = decode_one(vopc_sdwa(op, source('v', 1, neg=neg, absolute=absolute), source('v', 2), + None if cmpx else SGPR_DST)) + try: + Probe().one(name, asm) + refused.append((asm, None)) + except G.Unsupported as error: + refused.append((asm, str(error))) + check('f32 SDWA lg/nlg compares stay refused (%d forms)' % len(refused), len(refused) == 16 and all( + error == '%s: f32 SDWA compares are not lowered' % asm.split()[0] for asm, error in refused), str(refused[:3])) + + +# ---- the pixel fixtures ----------------------------------------------------------------------------------------- +WIDTH = HEIGHT = 16 +CLEAR = 0xbf800000 # -1.0, the target's clear value: a discarded pixel keeps it +ONE = 0x3f800000 +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 + + +def build_value(dst, index): + """dst = CLASSES[index >> 1] with the sign bit (index & 1), from integer operations; v5 is scratch.""" + text = 'v_lshrrev_b32_e32 v5, 1, v%d\nv_mov_b32_e32 v%d, 0\n' % (index, dst) + words = vop2(V_LSHRREV, 5, 1, index) + vop1_mov(dst, 0) + for k in range(1, 8): + constant = {1: '1', ONE: '1.0'}.get(CLASSES[k], '0x%x' % CLASSES[k]) + text += 'v_cmp_ne_u32_e32 vcc_lo, %d, v5\nv_cndmask_b32_e32 v%d, %s, v%d, vcc_lo\n' % (k, dst, constant, dst) + words += vopc_e32(V_CMP_NE_U32, k, 5) + vop2(V_CNDMASK, dst, CLASSES[k], dst) + text += 'v_lshlrev_b32_e32 v5, 31, v%d\nv_xor_b32_e32 v%d, v%d, v5\n' % (index, dst, dst) + words += vop2(V_LSHLREV, 5, 31, index) + vop2(V_XOR, dst, ('v', dst), 5) + return text, words + + +def prologue(): + """v3 = VALUES[x], v4 = VALUES[y] for the packed position x | y << 16 in v0.""" + text = 'v_and_b32_e32 v1, 15, v0\nv_lshrrev_b32_e32 v2, 16, v0\n' + words = vop2(V_AND, 1, 15, 0) + vop2(V_LSHRREV, 2, 16, 0) + for dst, index in ((3, 1), (4, 2)): + t, w = build_value(dst, index) + text, words = text + t, words + w + return text, words + + +EXPORT_PACKED = ('exp mrt0 v0, v0, v0, v0 done vm\ns_endpgm\n', struct.pack(' (body text, body words, [(condition, src0 modifiers, src1 modifiers)] per exported word, or one for v_cmpx) +FIXTURES = { + 'cmp': ( + 'v_cmp_lg_f32_e32 vcc_lo, v3, v4\nv_cndmask_b32_e64 v6, 0, 1.0, vcc_lo\n' + 'v_cmp_nlg_f32_e64 s6, -v3, |v4|\nv_cndmask_b32_e64 v7, 0, 1.0, s6\n' + 'v_cmp_lg_f32_e64 s8, -|v3|, -v4\nv_cndmask_b32_e64 v8, 0, 1.0, s8\n' + 'v_cmp_nlg_f32_e32 vcc_lo, v3, v4\nv_cndmask_b32_e64 v9, 0, 1.0, vcc_lo\n' + 'exp mrt0 v6, v7, v8, v9 done vm\ns_endpgm\n', + vopc_e32(0x05, ('v', 3), 4) + cndmask_e64(6, VCC_LO) + + vop3_compare(0x0a, 6, 3, 4, (True, False), (False, True)) + cndmask_e64(7, 6) + + vop3_compare(0x05, 8, 3, 4, (True, True), (True, False)) + cndmask_e64(8, 8) + + vopc_e32(0x0a, ('v', 3), 4) + cndmask_e64(9, VCC_LO) + + struct.pack(' %d, equal -> %d, NaN -> %d; pixels %s' % ( + name, index, cond, *(min(want[k]) for k in ('unequal', 'equal', 'nan')), counts), seen == want, + str(seen)) + for denormals in DENORMALS: + good, bad = image(name, denormals=denormals), image(name, old_reference, denormals) + differing = sum(good[i:i + 4] != bad[i:i + 4] for i in range(0, len(good), 4)) + check('%s (%s denormals): the old lowering changes %d of %d pixels' % ( + name, denormals, differing, WIDTH * HEIGHT), differing == 156) + ieee, flush = image(name), image(name, denormals='flushed') + differing = [(i // 4 % WIDTH, i // 4 // WIDTH) for i in range(0, len(ieee), 4) + if ieee[i:i + 4] != flush[i:i + 4]] + check('%s: flushing denormals changes %d pixels, each with a denormal source and no NaN' % ( + name, len(differing)), bool(differing) and all( + any(VALUES[c] & 0x7f800000 == 0 and VALUES[c] & 0x7fffff for c in (x, y)) + and not is_nan(VALUES[x]) and not is_nan(VALUES[y]) for x, y in differing)) + good = ieee + if name != 'cmp': + kept = sum(good[i] != CLEAR for i in range(0, len(good), 4)) + check('%s: reference keeps %d of %d pixels' % (name, kept, WIDTH * HEIGHT), 0 < kept < WIDTH * HEIGHT) + # The evaluator on each pixel stage's compare lines reads the same decisions as the images. + for name in FIXTURES: + for old in (False, True): + lines = [ln.strip() for ln in pixel_hlsl(name, old).splitlines() + if re.match(r'\s*(vcc|exec|s6|s8) = .*F\(v3\)', ln)] + model = old_reference if old else reference + results = FIXTURES[name][2] + ok = len(lines) == len(results) + for line, (cond, m0, m1) in zip(lines, results): + expr = Expr(line.split(' = ', 1)[1][:-1]) + ok = ok and all(expr.run({'v3': a, 'v4': b}) == model(cond, modified(a, *m0), modified(b, *m1)) + for a, b in PAIRS) + check('%s%s: evaluated compares equal the %s' % (name, ' (old)' if old else '', + 'old model' if old else 'ISA reference'), ok, str(lines)) + + +def all_codes(): + return [compare_code(op, form, mods) for op, form, mods, _ in all_forms()] + + +def check_binary(llvm_mc): + codes = all_codes() + source_text = ''.join(llvm_text(decode_one(code)[1]) + '\n' for code in codes) + built = assemble(llvm_mc, source_text) + check('llvm-mc assembles %d decoded f32 compare forms to the same words' % len(codes), built == b''.join(codes)) + for name in FIXTURES: + text, words = fixture(name) + check('llvm-mc assembles the %s fixture to the same words' % name, assemble(llvm_mc, text) == words) + + +def check_decode(library): + from pixel_aot import disassemble + codes = all_codes() + texts = disassemble(b''.join(codes), library) + ours = [llvm_text(decode_one(code)[1]) for code in codes] + wrong = [(a, b) for a, b in zip(texts, ours) if a != b] + check('LLVM disassembles %d f32 compare forms as tools/disasm_rdna2.py does' % len(codes), + len(texts) == len(codes) and not wrong, str(wrong[:3])) + for name in FIXTURES: + text, words = fixture(name) + check('LLVM disassembles the %s fixture as its source' % name, disassemble(words, library) == text.splitlines()) + + +def words_file(directory, name, words): + path = directory / ('%s.bin' % name) + path.write_bytes(struct.pack('<%dI' % len(words), *words)) + return path + + +def draw(renderer, adapter, vs, ps, expected): + run = subprocess.run([renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), + str(expected)], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + """Each fixture must match the ISA image with denormals kept or flushed (the same choice for every fixture of + one compiler and adapter); the old != lowering must match neither and must match its own image.""" + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + modes = set() + for name in FIXTURES: + files = {d: words_file(directory, '%s_%s' % (name, d), image(name, denormals=d)) for d in DENORMALS} + ps = compile_hlsl(compiler, kind, pixel_hlsl(name), 'ps_%s_%s' % (name, kind), ps_profile, directory) + matched, report = None, [] + for denormals in DENORMALS: + run = draw(renderer, adapter, vs, ps, files[denormals]) + report.append(run.stdout + run.stderr) + if run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout: + matched = denormals + break + print(' ' + ' '.join(ln for ln in run.stdout.splitlines() + if ln.startswith(('backend=', 'adapter=', 'driver=', 'debug_errors=')))) + modes.add(matched) + check('%s %s %s: all %d pixels match the ISA reference (%s denormals)' % ( + kind, adapter, name, WIDTH * HEIGHT, matched), matched is not None, '\n'.join(report)) + bad = compile_hlsl(compiler, kind, pixel_hlsl(name, old=True), 'ps_%s_old_%s' % (name, kind), + ps_profile, directory) + for denormals in DENORMALS: + run = draw(renderer, adapter, vs, bad, files[denormals]) + lines = [ln for ln in run.stderr.splitlines() if 'pixel' in ln] + check('%s %s %s old != lowering fails against the %s image: %s' % ( + kind, adapter, name, denormals, ' / '.join(lines)), + run.returncode != 0 and lines and lines[0].startswith('pixel mismatch'), + run.stdout + run.stderr) + own = words_file(directory, name + '_old', image(name, old_reference, matched or 'ieee')) + run = draw(renderer, adapter, vs, bad, own) + check('%s %s %s old != lowering matches its own image' % (kind, adapter, name), + run.returncode == 0, run.stdout + run.stderr) + # Recorded, not checked: the same less-or-greater without the bit test of the source words. + loose = compile_hlsl(compiler, kind, unguarded(pixel_hlsl(name)), 'ps_%s_loose_%s' % (name, kind), + ps_profile, directory) + run = draw(renderer, adapter, vs, loose, files[matched or 'ieee']) + print(' recorded: %s %s %s without the NaN bit test: %s' % (kind, adapter, name, ' / '.join( + ln for ln in (run.stdout + run.stderr).splitlines() if 'pixel' in ln))) + check('%s %s: one denormal behaviour across the fixtures: %s' % (kind, adapter, sorted(map(str, modes))), + len(modes) == 1 and None not in modes) + +def main(): + if len(sys.argv) == 1: + controls() + check_fixtures() + else: + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'decode': + check_decode(*args) + elif mode == 'draw': + check_fixtures() + check_draw(*args) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_root_local_check.py b/tests/startup_gfx2hlsl_root_local_check.py new file mode 100644 index 0000000000..fa151fa634 --- /dev/null +++ b/tests/startup_gfx2hlsl_root_local_check.py @@ -0,0 +1,83 @@ +"""A malformed root signature blob is refused per request by tools/startup/gfx2hlsl.py --pending. + +Each bad request gets a .fail file with a reason; the run exits 0 and still translates a valid +request that sorts after a bad one. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools/startup")) +import gfx2hlsl + + +def code(target): + return struct.pack("<4I", 0x7e000280, 0xf800080f | target << 4, 0, 0xbf810000) + + +def container(parts): + """DXBC header (hash zeroed) followed by (fourcc, body) parts.""" + base = 32 + 4 * len(parts) + offsets, body = [], b"" + for fourcc, data in parts: + offsets.append(base + len(body)) + body += fourcc + struct.pack(" (root blob, expected .fail text) +BAD = { + "empty": (b"", "root signature blob missing"), + "truncated header": (b"DXBC" + bytes(8), TRUNCATED), + "part count past end": (b"DXBC" + bytes(16) + struct.pack(" min(keys[name] for name in BAD), "valid request does not sort after a bad one" + # The empty X2W_FXC publishes the manifest without compiling, so the valid request is + # translated the same way on a host without fxc.exe. + result = subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", str(directory)], + capture_output=True, text=True, env=dict(os.environ, X2W_FXC="")) + output = result.stdout + result.stderr + assert result.returncode == 0, output + for name, (_, reason) in BAD.items(): + fail = directory / ("%016x.fail" % keys[name]) + assert fail.is_file(), "%s: no .fail file\n%s" % (name, output) + assert reason in fail.read_text(), (name, fail.read_text()) + assert not (directory / ("%016x.txt" % keys[name])).exists(), name + assert (directory / ("%016x.txt" % keys["valid"])).is_file(), \ + "valid request after bad ones was not translated\n" + output + assert not (directory / ("%016x.fail" % keys["valid"])).exists() + print("malformed root blobs refused per request, valid request still translated") + + +if __name__ == "__main__": + main() diff --git a/tests/startup_heap_texture_check.py b/tests/startup_heap_texture_check.py new file mode 100644 index 0000000000..43c60b396e --- /dev/null +++ b/tests/startup_heap_texture_check.py @@ -0,0 +1,75 @@ +"""Startup heap texture check.""" +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_draw_uav_check import run_mode + +CLEAR = (0, 0, 255, 255) + + +def expected(): + return bytes(c for y in range(4) for x in range(8) + for c in ((10 + 20 * x, 30 + 40 * y, 7, 255) if x < 2 else CLEAR)) + + +def expected_detile(): + return bytes(c for y in range(4) for x in range(8) for c in ((255, 255, 0, 255) if x < 2 else CLEAR)) + + +def surface(directory, layout_check): + path = directory / "bc1_256_9mips_4k_s.bin" + result = subprocess.run([layout_check, "--write-tiled", "bc1_256_9mips_4k_s", path, "--addrlib"], capture_output=True, text=True) + if result.returncode == 0: + return path, "addrlib" + if result.returncode != 77: + raise AssertionError(f"--write-tiled --addrlib failed ({result.returncode}): {result.stdout}{result.stderr}") + subprocess.run([layout_check, "--write-tiled", "bc1_256_9mips_4k_s", path], check=True, capture_output=True) + return path, "gfx10_layout.h (plumbing only: built without addrlib)" + + +def check(directory, consumer, backend, layout_check=None): + results = {} + for mode in ("heaptex", "heaptex-off"): + got = run_mode(directory, consumer, backend, mode) + if got is None: + print("no existing-heap support or no adapter: skip") + return 77 + results[mode] = got + _, image, log = results["heaptex"] + increment = int(re.search(r"^view increment (\d+)$", log, re.M).group(1)) + if increment != 32: + if "heap draw skipped: descriptor increment is not 32" not in log: + raise AssertionError(f"increment {increment}: the heap draw was not skipped") + print(f"{backend}: heap texture upload NOT exercised (view increment {increment}; heap draws skipped as required)") + return 77 + if image != expected(): + raise AssertionError(f"switch on: pixels {image.hex()}\n expected {expected().hex()}") + for needle in ("X2W_HEAP_TEXTURE_UPLOAD=1", "x2w-draw heap textures: frame", "x2w-draw-rt first heap draw"): + if needle not in log: + raise AssertionError(f"switch on: log lacks {needle!r}\n{log[-4000:]}") + _, off_image, off_log = results["heaptex-off"] + if off_image[:8] == expected()[:8] or "x2w-draw heap textures" in off_log or "X2W_HEAP_TEXTURE_UPLOAD" in off_log: + raise AssertionError(f"switch off: the heap texture was uploaded: {off_image[:16].hex()}") + print(f"{backend}: heap-only texture uploaded and sampled (16 texels exact); switch off: not uploaded " + f"(columns 0-1 read {off_image[:8].hex()})") + if not layout_check: + return 0 + path, source = surface(directory, layout_check) + extra = {"X2W_TEST_HEAPTEX_SURFACE": str(path)} + _, image, log = run_mode(directory, consumer, backend, "heaptex-detile", extra) + if image != expected_detile() or "x2w-memsrv detiled memory SRV" not in log or "x2w-draw heap textures: frame" not in log: + raise AssertionError(f"detile + heap upload: pixels {image[:64].hex()} (expected every block to match)\n{log[-3000:]}") + _, control, control_log = run_mode(directory, consumer, backend, "heaptex-detile-noupload", extra) + if control[:8] == expected_detile()[:8] or "x2w-memsrv detiled memory SRV" not in control_log: + raise AssertionError(f"detile without heap upload: pixels {control[:16].hex()} (expected mismatches)") + print(f"{backend}: memory SRV 0x105 BC1 9 mips through the heap: all 4096 mip-0 blocks match with DETILE + " + f"HEAP_TEXTURE_UPLOAD ({source}); DETILE alone: published, not uploaded, mismatches") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_image_3d_check.py b/tests/startup_image_3d_check.py index 0cfc30d79e..4c6fa29e42 100644 --- a/tests/startup_image_3d_check.py +++ b/tests/startup_image_3d_check.py @@ -103,10 +103,13 @@ def controls(): assert 'srv 0 tex2d table 0 0' in manifest, manifest print('dim 2D (same words, dim field changed): Texture2D r0, float2(F(v0), F(v1)); manifest srv 0 tex2d') + # dim:SQ_RSRC_IMG_1D is a Texture1D sampled at u alone, never as 2D (2D arrays: startup_image_2d_array_check.py). pipe = translate(WORDS_1D) - assert 'Texture1D r0' in pipe.hlsl_ps() - assert 'r0.Sample(q0, F(v0))' in pipe.hlsl_ps() - assert 'srv 0 tex1d table 0 0' in pipe.manifest() + ps, manifest = pipe.hlsl_ps(), pipe.manifest() + assert 'Texture1D r0 : register(t0);' in ps and 'Texture2D' not in ps and 'Texture3D' not in ps, ps + assert 't = r0.Sample(q0, F(v0));' in ps, ps + assert 'srv 0 tex1d table 0 0' in manifest, manifest + print('dim 1D (same words, dim field changed): Texture1D r0, Sample(q0, F(v0)); manifest srv 0 tex1d') unsupported = WORDS_1D.replace(bytes.fromhex('000f80f0'), bytes.fromhex('180f80f0')) try: translate(unsupported) diff --git a/tests/startup_image_d16_check.py b/tests/startup_image_d16_check.py new file mode 100644 index 0000000000..d90a98bdfc --- /dev/null +++ b/tests/startup_image_d16_check.py @@ -0,0 +1,87 @@ +"""Packed D16 results of image_sample / image_sample_lz in tools/startup/gfx2hlsl.py. + +Synthetic gfx1013 words: the 2D form of the startup_image_3d_check fixture with its image_sample word changed to +dmask 0x3 (0x7 for the three-channel case) and the D16 bit (MIMG gfx10 bit 63, LLVM MIMGInstructions.td +`Inst{63} = d16`) set, writing v0 (v[0:1] for three channels). + +Semantics (gfx9+ packed D16, LLVM GCNSubtarget::hasPackedD16VMem, SIISelLowering::adjustLoadValueType): every +enabled channel of the result is converted to binary16 and two channels share one VGPR, the first in bits 15:0. +After an odd channel count the high half of the last VGPR is undefined; the translation writes 0 there. +Checked on the emitted HLSL text (the binary16 conversion is HLSL f32tof16; its rounding against the hardware's is +NOT verified here). +Controls (refused): d16 on image_load (an integer texel format would be converted as a float); d16 on +image_sample_l (its own modifier list). +Negative control: the same words without the D16 bit give four unpacked VGPR writes, not the packed one. +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_image_3d_check as T # noqa: E402 + +BASE = bytes.fromhex('080f80f00000c400') # image_sample v[0:3], v[0:1], s[16:23], s[24:27] dmask:0xf 2D + + +def words(word0, word1): + return T.WORDS_2D.replace(BASE, struct.pack('<2I', word0, word1)) + + +def asm(ws): + return [x[3] for x in G.decode(ws) if x[3].startswith('image')][0] + + +def ps_of(ws): + return T.translate(ws).hlsl_ps() + + +def refused(ws, label): + try: + ps_of(ws) + except G.Unsupported as error: + return str(error) + raise AssertionError('accepted: %s (%s)' % (label, asm(ws))) + + +def main(): + two = words(0xf0800308, 0x80c40000) + assert asm(two) == 'image_sample v0, v[0:1], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_2D d16', asm(two) + ps = ps_of(two) + line = 'v0 = f32tof16(t.x) | (f32tof16(t.y) << 16);' + assert line in ps and 'v1 = U(t.y)' not in ps, ps + three = words(0xf0800708, 0x80c40000) + assert asm(three) == 'image_sample v[0:1], v[0:1], s[16:23], s[24:27] dmask:0x7 dim:SQ_RSRC_IMG_2D d16', asm(three) + ps3 = ps_of(three) + assert 'v0 = f32tof16(t.x) | (f32tof16(t.y) << 16);' in ps3 and 'v1 = f32tof16(t.z);' in ps3, ps3 + # lz form (image_sample_lz opcode 0x27): same packing + lz = words(0xf09c0308, 0x80c40000) + assert asm(lz) == 'image_sample_lz v0, v[0:1], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_2D d16', asm(lz) + assert 't = r0.SampleLevel(q0, float2(F(v0), F(v1)), 0);' in ps_of(lz) and line in ps_of(lz), ps_of(lz) + + # Controls. + load = words(0xf0001308, 0x80040000) # image_load v0, v[0:1], s[16:23] dmask:0x3 unorm d16 + assert asm(load).startswith('image_load v0, v[0:1], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D') and 'd16' in asm(load), asm(load) + assert 'modifier d16' in refused(load, 'image_load d16') + wide = words(0xf0800308, 0x80c40000).replace(struct.pack('<2I', 0xf0800308, 0x80c40000), + struct.pack('<2I', 0xf0800f08, 0x80c40000)) # dmask 0xf into v[0:1] ok + assert asm(wide) == 'image_sample v[0:1], v[0:1], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D d16', asm(wide) + ps4 = ps_of(wide) + assert 'v1 = f32tof16(t.z) | (f32tof16(t.w) << 16);' in ps4, ps4 + samplel = words(0xf0900308, 0x80c40000) # image_sample_l ... d16 + assert asm(samplel).startswith('image_sample_l ') and 'd16' in asm(samplel), asm(samplel) + assert 'image_sample_l modifier d16' in refused(samplel, 'image_sample_l d16') + + # Negative control: without D16 the result is four unpacked writes. + plain = words(0xf0800f08, 0x00c40000) + assert 'd16' not in asm(plain) + ps0 = ps_of(plain) + assert 'v0 = U(t.x);' in ps0 and 'f32tof16' not in ps0, ps0 + print('image d16: sample and sample_lz pack 2 and 3 and 4 channels into binary16 halves; ' + 'image_load d16 and image_sample_l d16 refused; plain words unpacked') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_get_lod_check.py b/tests/startup_image_get_lod_check.py new file mode 100644 index 0000000000..36527abb7b --- /dev/null +++ b/tests/startup_image_get_lod_check.py @@ -0,0 +1,116 @@ +"""image_get_lod on a 2D texture in tools/startup/gfx2hlsl.py. + +image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp (Mesa +nir_texop_lod, emitted by ACO as image_get_lod; GLSL textureQueryLod x/y). Lowered as HLSL CalculateLevelOfDetail / +CalculateLevelOfDetailUnclamped, which take implicit derivatives like Sample, so the stage must be straight-line +with every lane active, or X2W_PS_QUAD_DIVERGENT=1 (forward control flow; marked in the manifest). + +Fixture: the recorded c_lz stage of startup_image_sample_c_check with the MIMG opcode set to 0x60 (image_get_lod; +the decoder reads it back with a 2-register address) and, for the second form, dmask 0x3. +Checks: dmask 0x1 and 0x3 lower to the two calls on the sampler; controls (refused): dmask 0x4, a 2D array, the +stage after a branch without the switch (accepted with it, `quaddivergent 1`), and without op_image_get_lod +(negative control: refused as before). + draw [fxc]: compile the dmask 0x3 stage with dxc ps_6_0 (and fxc ps_5_1). +""" +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_image_sample_c_check as C # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, root_blob # noqa: E402 + +AT = 0x34 # the MIMG instruction of the c_lz fixture + + +def stage(dmask=1, dim=1, branch=False): + w = bytearray(C.WORDS['lz']) + w0, w1 = struct.unpack_from(' 1: + if sys.argv[1] != 'draw': + raise SystemExit(__doc__) + compile_check(*sys.argv[2:]) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_invariant_check.py b/tests/startup_image_invariant_check.py new file mode 100644 index 0000000000..04cd70e107 --- /dev/null +++ b/tests/startup_image_invariant_check.py @@ -0,0 +1,99 @@ +"""Lane-invariant image reads and the s_brev_b32 constant fold (tools/startup/gfx2hlsl.py). + +1. image_load / image_sample_lz of a bound texture (rN) through a fixed sampler at lane-invariant coordinates gives + the same value in every lane (no implicit derivatives: same texel or same filtered value), so the destination + VGPRs join uniform_v and a later v_readfirstlane_b32 of them is exact (measured form: a 1x1 pass loading texel + (0, 0) with a16 and v0 = 0, then sampling a 1D texture at a coordinate computed from it). Controls: a + coordinate VGPR not proven invariant, and image_sample (implicit derivatives), leave the destination out. +2. s_brev_b32 of an inline constant or a constant SGPR is folded (RDNA 2 ISA SOP1 S_BREV_B32: D = S0 with bits + reversed; 40 -> 0x14000000, an inline sampler word); a run-time source keeps reversebits(). +""" +import os +import struct +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, '..', 'tools', 'startup')) +sys.path.insert(0, HERE) +import gfx2hlsl as G # noqa: E402 +from startup_scalar_bits_check import sop1 # noqa: E402 + + +class Pipe: + sampler_heap = False + root = {'params': [], 'flags': 0} + resource = G.Pipeline.resource + + def __init__(self): + self.features = frozenset() + self.resources, self.uds, self.modified, self.heapvars, self.notes = {}, [], set(), [], set() + self.samplers = {} + + def ud(self, source): + if source not in self.uds: + self.uds.append(source) + return self.uds.index(source) + + def sampler(self, key, comparison=False): + return 'q0' + + +def stage(): + s = G.Stage(Pipe(), 'ps', b'') + s.lines, s.pc = [], 0 + s.uniform_v, s.partial_uniform, s.lane_s, s.masks = set(), {}, set(), set() + s.exec_known = True + for i in range(8): + s.sym[24 + i] = ('desc', ('table', 1), 0x20, i) + for i in range(4): + s.sym[20 + i] = ('const', 0) + for i in range(8): + s.sym[32 + i] = ('desc', ('table', 1), 0x40, i) # a 1D texture + return s + + +def main(): + s = stage() + s.set_v(0, '0u') + assert 0 in s.uniform_v + s.one('image_load', 'image_load v[2:3], v[0:1], s[24:31] dmask:0xa dim:SQ_RSRC_IMG_2D unorm a16') + assert {2, 3} <= s.uniform_v, (s.lines, s.uniform_v) + s.one('image_sample_lz', 'image_sample_lz v1, v2, s[32:39], s[20:23] dmask:0x1 dim:SQ_RSRC_IMG_1D') + assert 1 in s.uniform_v, (s.lines, s.uniform_v) + s.one('v_readfirstlane_b32', 'v_readfirstlane_b32 s22, v1') + assert s.lines[-1] == 's22 = v1;', s.lines + t = stage() + t.one('image_load', 'image_load v[2:3], v[5:6], s[24:31] dmask:0xa dim:SQ_RSRC_IMG_2D unorm a16') + assert not {2, 3} & t.uniform_v, t.uniform_v + try: + t.one('v_readfirstlane_b32', 'v_readfirstlane_b32 s22, v2') + except G.Unsupported as error: + assert 'proven uniform' in str(error) + else: + raise AssertionError('readfirstlane of a lane-dependent load accepted') + u = stage() + u.set_v(0, '0u') + u.one('image_sample', 'image_sample v1, v0, s[32:39], s[20:23] dmask:0x1 dim:SQ_RSRC_IMG_1D') + assert 1 not in u.uniform_v, u.uniform_v + print('image_invariant: load and lz at invariant coordinates join uniform_v (readfirstlane exact); a ' + 'lane-dependent coordinate and an implicit-derivative sample do not') + + for words, want in (([sop1(0x0b, 10, 0x80 + 40)], ('const', 0x14000000)),): + _, _, name, text = G.decode(struct.pack(' 0x14000000); run-time source unchanged') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_sample_b_local_check.py b/tests/startup_image_sample_b_local_check.py new file mode 100644 index 0000000000..553fc827e8 --- /dev/null +++ b/tests/startup_image_sample_b_local_check.py @@ -0,0 +1,82 @@ +"""image_sample_b (sample with an LOD bias) in tools/startup/gfx2hlsl.py. + +The fixture is the source-built pixel stage of startup_image_sample_l_check.py (v0 = 0.5, v1 = 0.25, v2 = 1.0, +v3 = 2.0; texture from descriptor table 0, all-zero constant sampler) with its MIMG opcode set to 0x25, which the +decoder names image_sample_b (LLVM MIMGInstructions.td, gfx10 IMAGE_SAMPLE_B). The bias is the FIRST address dword, +before the coordinates (LLVM AMDGPUImageDimIntrinsics: sample_b has ExtraAddrArgs [bias]), so v[0:2] is +bias v0, u v1, v v2 and the lowering must be SampleBias(q0, float2(F(v1), F(v2)), F(v0)). + +SampleBias needs implicit derivatives like Sample, so it is lowered only where Sample is (straight-line code with +every lane active); elsewhere it is refused, not sampled at level 0 (which would drop the bias). +Controls: before the change the stage refused `image_sample_b` (reproduced by removing the handler); a branch +before the sample and a16 are refused; the plain image_sample of the same words keeps its +Sample lowering. +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_sample_l_check import WORDS # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, root_blob # noqa: E402 + +LWE = bytes.fromhex('080f92f0') # the sample_l lwe word of the fixture, at offset 0x30 + + +def program(op, flags=0, prefix_branch=False): + w = bytearray(WORDS['lwe']) + i = w.find(LWE) + assert i == 0x30, i + w[i:i + 4] = struct.pack('dh for each coordinate, then ddv). So v0, +v1 are the horizontal (ddx) gradient, v2, v3 the vertical (ddy) one, and v4, v5 are u and v: +SampleGrad(q0, float2(F(v4), F(v5)), float2(F(v0), F(v1)), float2(F(v2), F(v3))). + +SampleGrad needs no implicit derivatives, so unlike Sample and SampleBias it is lowered after a branch too. +Controls: without the handler the stage refuses `image_sample_d` as before; a16 is refused (the gradients would be +packed too). The pixel HLSL compiles with dxc ps_6_0 and, when found, fxc ps_5_1. +""" +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_sample_b_local_check import program, ps_text, refused # noqa: E402 + +EXPECTED = 't = r0.SampleGrad(q0, float2(F(v4), F(v5)), float2(F(v0), F(v1)), float2(F(v2), F(v3)));' + + +def compile_ps(text): + results = [] + fxc = os.path.join(os.path.dirname(M.DXC), 'fxc.exe') + for tool, args in ((M.DXC, ['-nologo', '-T', 'ps_6_0']), (fxc, ['/nologo', '/T', 'ps_5_1'])): + if not os.path.isfile(tool): + results.append('%s not found' % os.path.basename(tool)) + continue + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, 'ps.hlsl') + open(path, 'w').write(text) + r = subprocess.run([tool] + args + ['-E' if tool == M.DXC else '/E', 'main', + '-Fo' if tool == M.DXC else '/Fo', path + '.cso', path], capture_output=True, text=True) + assert r.returncode == 0, (tool, r.stdout, r.stderr) + results.append('%s %s ok' % (os.path.basename(tool)[:3], args[-1])) + return ', '.join(results) + + +def main(): + code = program(0x22) + asm = G.decode(code)[10][3] + assert asm == 'image_sample_d v[4:7], v[0:5], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D', asm + ps = ps_text(code) + assert EXPECTED in ps, ps + for comp, reg in zip('xyzw', range(4, 8)): + assert 'v%d = U(t.%s);' % (reg, comp) in ps, ps + # after a branch (not straight-line): still SampleGrad, explicit derivatives + branched = ps_text(program(0x22, prefix_branch=True)) + assert EXPECTED in branched, branched + compiled = compile_ps(ps) + # controls + saved = G.Stage.op_image_sample_d + del G.Stage.op_image_sample_d + try: + refused(code, 'image_sample_d') + finally: + G.Stage.op_image_sample_d = saved + a16 = bytearray(code) + a16[0x34:0x38] = struct.pack(' r0' in one and 'Texture2D' not in one, one + assert re.search(r'\w+\.SampleLevel\(\w+, F\(v0\), F\(v1\)\);', one), one for name in RESERVED: refused(name, 'image_sample_l modifier reserved') # bits LLVM ignores must not be silently accepted - print('refused: offset, compare, gather, cube, 1D, MSAA, unorm, a16, tfe, lwe, d16, r128, dmask 0, reserved bits') + print('refused: offset, compare, gather, cube, MSAA, unorm, a16, tfe, lwe, d16, r128, dmask 0, reserved bits; ' + '1D: Texture1D SampleLevel(u, level)') # Cache-policy bits do not change the sampled value: same lowering as the plain form. for name in ('glc', 'slc', 'dlc'): diff --git a/tests/startup_indirect_dispatch.hlsl b/tests/startup_indirect_dispatch.hlsl new file mode 100644 index 0000000000..7976cc94c3 --- /dev/null +++ b/tests/startup_indirect_dispatch.hlsl @@ -0,0 +1,19 @@ +// Shaders for tests/startup_indirect_dispatch.cpp. Root signature (built by the test): +// [0] root UAV u0 (raw buffer), [1] four 32-bit constants b0. +RWByteAddressBuffer target : register(u0); +cbuffer Values : register(b0) { uint4 values; }; + +// Writer: stores a Dispatch argument record (values.xyz) at byte offset values.w of u0. +[numthreads(1, 1, 1)] +void Writer() +{ + target.Store3(values.w, values.xyz); +} + +// Counter: every thread group adds 1 at byte offset values.w of u0. +[numthreads(1, 1, 1)] +void Counter() +{ + uint before; + target.InterlockedAdd(values.w, 1, before); +} diff --git a/tests/startup_indirect_dispatch_local.cpp b/tests/startup_indirect_dispatch_local.cpp new file mode 100644 index 0000000000..e9e84fbdb5 --- /dev/null +++ b/tests/startup_indirect_dispatch_local.cpp @@ -0,0 +1,311 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "startup_indirect_writer.h" +#include "startup_indirect_counter.h" + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) unsigned long long x2w_upload_ring_test(int what); +extern "C" __declspec(dllimport) void x2w_d3d12_record_trace_report(); + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e, f); +} +bool ok(Word hr) { return SUCCEEDED(static_cast(hr)); } +std::uint64_t fnv(const void* data, std::size_t bytes, std::uint64_t hash = 1469598103934665603ull) +{ + for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ static_cast(data)[i]) * 1099511628211ull; + return hash; +} +bool write_file(const std::wstring& path, const void* data, std::size_t bytes) +{ + FILE* f = _wfopen(path.c_str(), L"wb"); + if (!f) return false; + const bool written = std::fwrite(data, 1, bytes, f) == bytes; + return std::fclose(f) == 0 && written; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) return 2; + std::string mode = argv[2]; + const bool huge = mode == "huge", huge_product = mode == "huge-product"; + const bool wrap = mode == "wrap", wrap_legacy = mode == "wrap-legacy", wrap_cap = mode == "wrap-cap"; + const std::string ring_mode = mode; + if (wrap || wrap_legacy || wrap_cap) { + SetEnvironmentVariableA("X2W_INDIRECT_RING_TEST_KIB", "1"); + if (wrap_legacy) SetEnvironmentVariableA("X2W_INDIRECT_RING", "legacy"); + if (wrap_cap) SetEnvironmentVariableA("X2W_INDIRECT_RING_TEST_CAP_CHUNKS", "2"); + mode = "gpu"; // the gpu case, plus the extra calls below + } + const int extra_calls = wrap || wrap_legacy || wrap_cap ? 40 : 0; + const bool rectrace = mode == "rectrace", rectrace_off = mode == "rectrace-off"; + if (mode != "gpu" && mode != "no-writer" && mode != "zero" && mode != "off" && !huge && !huge_product && !rectrace && !rectrace_off) + return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + std::printf("adapter=%ls mode=%s\n", adapter_desc.Description, mode.c_str()); + + // Capability: the stand-in's windows need OpenExistingHeapFromAddress on this adapter. + { + ComPtr probe; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&probe)))) return 4; + void* block = VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + ComPtr heap; + const HRESULT hr = block ? probe->OpenExistingHeapFromAddress(block, IID_PPV_ARGS(&heap)) : E_OUTOFMEMORY; + heap.Reset(); + if (block) VirtualFree(block, 0, MEM_RELEASE); + if (FAILED(hr)) { + std::printf("OpenExistingHeapFromAddress -> 0x%08lx: capability skip\n", static_cast(hr)); + return 77; + } + } + + // Shader cache with the two container pipelines, keyed as the stand-in keys slot-62 pipelines. + wchar_t temp[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, temp)) return 5; + const std::wstring cache = std::wstring(temp) + L"x2w_indirect_" + std::to_wstring(GetCurrentProcessId()); + CreateDirectoryW(cache.c_str(), nullptr); + SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()); + const std::wstring log_path = cache + L"\\trap.log"; + if (rectrace || rectrace_off) SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + + D3D12_ROOT_PARAMETER parameters[2]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameters[1].Constants.Num32BitValues = 4; + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, parameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr root_blob; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &root_blob, nullptr))) return 5; + const auto cache_file = [&](const unsigned char* code, std::size_t bytes) { + wchar_t name[32]; + swprintf(name, 32, L"\\%016llx.cs.dxbc", static_cast(fnv(root_blob->GetBufferPointer(), root_blob->GetBufferSize(), fnv(code, bytes)))); + return write_file(cache + name, code, bytes); + }; + if (!cache_file(startup_indirect_writer, sizeof(startup_indirect_writer)) || + !cache_file(startup_indirect_counter, sizeof(startup_indirect_counter))) + return 5; + + std::array device_parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), device_parameters.data(), __uuidof(ID3D12Device), &device))) return 6; + + void* root = nullptr; + if (!ok(invoke(device, 16, 0, arg(root_blob->GetBufferPointer()), root_blob->GetBufferSize(), arg(&__uuidof(ID3D12RootSignature)), arg(&root)))) + return 7; + void *writer = nullptr, *counter = nullptr; + D3D12_COMPUTE_PIPELINE_STATE_DESC pipeline{}; + pipeline.pRootSignature = static_cast(root); + pipeline.CS = {startup_indirect_writer, sizeof(startup_indirect_writer)}; + if (!ok(invoke(device, 62, arg(&pipeline), 0, 0, arg(&__uuidof(ID3D12PipelineState)), arg(&writer)))) return 8; + pipeline.CS = {startup_indirect_counter, sizeof(startup_indirect_counter)}; + if (!ok(invoke(device, 62, arg(&pipeline), 0, 0, arg(&__uuidof(ID3D12PipelineState)), arg(&counter)))) return 8; + + D3D12_INDIRECT_ARGUMENT_DESC argument{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH}; + const D3D12_COMMAND_SIGNATURE_DESC signature_desc{12, 1, &argument, 0}; + void* signature = nullptr; + if (!ok(invoke(device, 41, arg(&signature_desc), 0, arg(&__uuidof(ID3D12CommandSignature)), arg(&signature)))) return 9; + + // Title memory: arguments at +0x1c20 (not 64 KiB-aligned), counter at +0x10000. + auto* memory = static_cast(VirtualAlloc(nullptr, 2u << 20, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!memory) return 10; + unsigned char* const args_memory = memory + 0x1c20; + auto* const counter_word = reinterpret_cast(memory + 0x10000); + const std::uint32_t sentinel[2][3] = {{rectrace || rectrace_off ? 0u : 7u, 1, 1}, {5, 1, 1}}; + std::memcpy(args_memory, sentinel[0], 12); + std::memcpy(args_memory + 0x14, sentinel[1], 12); + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 64, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + void* args = nullptr; + if (!ok(invoke(device, 133, arg(args_memory), arg(&buffer), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&args)))) + return 11; + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *queue = nullptr, *fence = nullptr, *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 12; + + if (rectrace || rectrace_off) { + const std::uint32_t reset[4] = {0, 1, 1, 0}, at_zero[4] = {0, 0, 0, 0}, at_counter[4] = {0, 0, 0, 0}; + void *allocator2 = nullptr, *list2 = nullptr; + if (!ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator2))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator2), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list2)))) + return 12; + invoke(list, 139, arg(allocator)); + invoke(list, 33, arg(root)); + invoke(list, 25, arg(writer)); + invoke(list, 45, 0, arg(args_memory)); // root UAV over the record + invoke(list, 39, 1, 4, arg(reset), 0); + invoke(list, 14, 1, 1, 1); // reset pass: {0, 1, 1} at offset 0 + invoke(list, 9); + invoke(list2, 139, arg(allocator2)); + invoke(list2, 33, arg(root)); + invoke(list2, 25, arg(counter)); + invoke(list2, 45, 0, arg(args_memory)); + invoke(list2, 39, 1, 4, arg(at_zero), 0); + invoke(list2, 14, 3, 1, 1); // raise pass: X += 3 + invoke(list2, 45, 0, arg(memory + 0x10000)); + invoke(list2, 39, 1, 4, arg(at_counter), 0); + invoke(list2, 61, arg(signature), 1, arg(args), 0, 0, 0); // ExecuteIndirect(sig, 1, args, 0) + invoke(list2, 9); + for (int n = 0; n < 2; ++n) { + void* one[] = {n ? list2 : list}; + invoke(queue, 10, 1, arg(one)); + if (!ok(invoke(queue, 14, arg(fence), n + 1))) return 13; + const auto until = GetTickCount64() + 10000; + while (invoke(fence, 8) < static_cast(n + 1)) { + if (GetTickCount64() >= until) return 14; + Sleep(1); + } + } + x2w_d3d12_record_trace_report(); + std::uint32_t record[3]; + std::memcpy(record, args_memory, 12); + const std::uint32_t got = *counter_word; + std::printf("record in title memory: {%u %u %u}; counter %u (expected 3)\n", record[0], record[1], record[2], got); + if (record[0] != 3 || record[1] != 1 || record[2] != 1) return 15; + if (got != 3) return 16; + std::ifstream log_file(log_path, std::ios::binary); + const std::string log{std::istreambuf_iterator(log_file), {}}; + const auto count = [&](const std::string& text) { + std::size_t n = 0; + for (std::size_t at = log.find(text); at != std::string::npos; at = log.find(text, at + 1)) ++n; + return n; + }; + char args_hex[32], args_ptr[32], writer_ptr[32], counter_ptr[32]; + std::snprintf(args_hex, sizeof(args_hex), "0x%llx", static_cast(reinterpret_cast(args_memory))); + std::snprintf(args_ptr, sizeof(args_ptr), "%p", static_cast(args_memory)); + std::snprintf(writer_ptr, sizeof(writer_ptr), "%p", writer); + std::snprintf(counter_ptr, sizeof(counter_ptr), "%p", counter); + const std::string range = std::string(": run: R p0+0x0 ") + args_hex + " "; + const std::string writers = std::string("x2w-frame record writers args ") + args_ptr + ": "; + const std::size_t reset_lines = count(std::string("(1, 1, 1) pipeline ") + writer_ptr + range); + const std::size_t raise_lines = count(std::string("(3, 1, 1) pipeline ") + counter_ptr + range); + const std::size_t record_lines = + count(std::string(" args ") + args_ptr + "+0x0 (wrapper ") == 1 && + count(": at record 00000000 00000001 00000001 00000000, at end 00000003 00000001 00000001 00000000") == 1; + const std::size_t totals = count("x2w-frame record totals type 2 dsv 0000000000000000: calls 1, X > 0 at record 0, at end 1, unreadable 0"); + const std::size_t writers_head = count(writers + "1 records (X > 0 at end 1), "); + const std::size_t writer_reset = count(std::string(" pipeline ") + writer_ptr + " R p0+0x0 " + args_hex + " ") >= 1 ? 1 : 0; + const std::size_t writer_raise = count(std::string(" pipeline ") + counter_ptr + " R p0+0x0 " + args_hex + " ") >= 1 ? 1 : 0; + const std::size_t any = count("x2w-frame cx-uav ") + count("x2w-frame record "); + std::printf("%s: reset lines %zu, raise lines %zu, record %zu, totals %zu, writers %zu (reset %zu, raise %zu), trace lines %zu\n", + mode.c_str(), reset_lines, raise_lines, record_lines, totals, writers_head, writer_reset, writer_raise, any); + if (rectrace && (reset_lines != 1 || raise_lines != 1 || !record_lines || totals != 1 || writers_head != 1 || !writer_reset || !writer_raise)) + return 20; + if (rectrace_off && any) return 21; + std::printf("PASS %s\n", mode.c_str()); + return 0; + } + // huge: the first record has 70000 groups in x (over the desktop's 65535); huge-product: 512*256*256 = + // 2^25 groups (each dimension legal, product over the guard's 2^24). The guard must zero the record on + // the GPU, so only the second record ({1, 1, 1}) runs: counter 1. + std::uint32_t written[2][4] = {{mode == "zero" ? 0u : 3u, mode == "zero" ? 1u : 2u, 1, 0}, + {mode == "zero" ? 0u : 1u, 1, 1, 0x14}}; + if (huge) written[0][0] = 70000, written[0][1] = 1, written[0][2] = 1; + if (huge_product) written[0][0] = 512, written[0][1] = 256, written[0][2] = 256; + const std::uint32_t count_at[4] = {0, 0, 0, 0}; + invoke(list, 139, arg(allocator)); // Reset + invoke(list, 33, arg(root)); // SetComputeRootSignature + if (mode != "no-writer") { + invoke(list, 25, arg(writer)); // SetPipelineState + invoke(list, 45, 0, arg(args_memory)); // SetComputeRootUnorderedAccessView(0, title address) + for (const auto& record : written) { + invoke(list, 39, 1, 4, arg(record), 0); // SetComputeRoot32BitConstants(1, 4, record, 0) + invoke(list, 14, 1, 1, 1); // Dispatch(1, 1, 1) + } + } + invoke(list, 25, arg(counter)); + invoke(list, 45, 0, arg(memory + 0x10000)); + invoke(list, 39, 1, 4, arg(count_at), 0); + invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); // ExecuteIndirect(sig, 1, args, 0, null, 0) + invoke(list, 61, arg(signature), 1, arg(args), 0x14, 0, 0); // ExecuteIndirect(sig, 1, args, 0x14, null, 0) + for (int i = 0; i < extra_calls; ++i) invoke(list, 61, arg(signature), 1, arg(args), 0x14, 0, 0); + invoke(list, 9); // Close + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), 1))) return 13; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < 1) { + if (GetTickCount64() >= deadline) return 14; + Sleep(1); + } + + std::uint32_t records[2][3]; + std::memcpy(records[0], args_memory, 12); + std::memcpy(records[1], args_memory + 0x14, 12); + const std::uint32_t got = *counter_word; + std::uint32_t wanted = mode == "gpu" ? 7 : mode == "no-writer" ? 12 : huge || huge_product ? 1 : 0; + if (extra_calls) wanted += wrap_cap ? 6 : extra_calls; + std::printf("records in title memory: {%u %u %u} {%u %u %u}\n", records[0][0], records[0][1], records[0][2], records[1][0], + records[1][1], records[1][2]); + std::printf("counter: %u (expected %u)\n", got, wanted); + bool records_ok = true; + for (int r = 0; r < 2; ++r) + for (int i = 0; i < 3; ++i) + records_ok &= records[r][i] == (mode == "no-writer" ? sentinel[r][i] : written[r][i]); + if (!records_ok) { + std::printf("the records in title memory are not what the %s wrote\n", mode == "no-writer" ? "CPU" : "writer"); + return 15; + } + ComPtr desktop; + if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) + std::printf("device removed reason: 0x%08lx\n", static_cast(desktop->GetDeviceRemovedReason())); + if (got != wanted) return 16; + if (extra_calls) { + // Indirect ring counters (x2w_upload_ring_test 100 + index): reserved bytes, refusals at the cap, slot bytes + // reused while held (legacy), would-have-wrapped bytes, chunks made, legacy flag. + const auto counter_of = [](int what) { return x2w_upload_ring_test(100 + what); }; + const unsigned long long reserved = counter_of(0), refused = counter_of(1), reused = counter_of(2), would = counter_of(3), + made = counter_of(8), legacy = counter_of(6); + std::printf("%s: indirect ring reserved %llu bytes, refused %llu, reused while held %llu bytes, would have wrapped %llu " + "bytes, chunks made %llu, legacy %llu\n", + ring_mode.c_str(), reserved, refused, reused, would, made, legacy); + if (wrap && (legacy || refused || reused || !would || made < 10 || reserved != 42 * 256)) return 17; + if (wrap_legacy && (!legacy || refused || !reused)) return 18; // the control: the old ring reuses held slots + if (wrap_cap && (legacy || refused != 34 || made != 2)) return 19; + std::printf("PASS %s\n", ring_mode.c_str()); + } + return 0; +} diff --git a/tests/startup_int_three_operand_check.py b/tests/startup_int_three_operand_check.py new file mode 100644 index 0000000000..6106233a81 --- /dev/null +++ b/tests/startup_int_three_operand_check.py @@ -0,0 +1,68 @@ +"""v_min3/v_max3/v_med3 _i32/_u32: the lowered HLSL expression against a sorted reference. + +Synthetic VOP3 words (gfx10 opcodes 0x152..0x159 except the f32 ones; the decoder's names are asserted). The +expression the translator emits is evaluated with 32-bit int()/uint() semantics on a grid of signed and unsigned +edge values. Reference: RDNA2 ISA (min/max/median of the three sources as signed or unsigned 32-bit integers). +Control: a mutated reference (median replaced by the maximum) must disagree. +""" +import itertools +import re +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +MASK = 0xffffffff +OPS = {0x152: 'v_min3_i32', 0x153: 'v_min3_u32', 0x155: 'v_max3_i32', 0x156: 'v_max3_u32', + 0x158: 'v_med3_i32', 0x159: 'v_med3_u32'} +GRID = [0, 1, 2, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffffe, MASK, 0x12345678] + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def s32(x): + x &= MASK + return x - (1 << 32) if x >> 31 else x + + +def run(expr, env): + py = re.sub(r'\buint\(', 'U32(', re.sub(r'(? [fxc] + translate, compile (FXC vs_5_1/ps_5_1 when given, DXC vs_6_0/ps_6_0), + draw one pixel (the startup_flat_param renderer) and compare the words + +The vertex stage is startup_flat_param_check's full-screen triangle with four constant param0 words, each +holding two binary16 values. The pixel stage interpolates every half of attr0 (p1ll + p2_f16, `high` for bits +31:16) and packs the two results of a channel back into one VGPR: the low half with a plain p2_f16, the high half +with op_sel bit 3 set (Mesa aco_assembler.cpp emit_vintrp_instruction: v_interp_p2_hi_f16 is v_interp_p2_f16 with +opsel 0x8; LLVM 15 and the decoder do not print the bit). A constant attribute interpolates to itself, so mrt0 must +read the exported words. + +Encodings (hand-assembled, no llvm-mc here; the decoder reads them back): VOP3 word 0 = 0b110101 << 26 | +opcode << 16 | op_sel << 11 | vdst, word 1 = attribute | channel << 6 | high << 8 | src1 << 9 | src2 << 18 (Mesa +aco_assembler.cpp, gfx10 opcodes p1ll 0x342, p2 0x35a from aco_opcodes.py). + +Controls: without the p2 handler the stage refuses as before; with op_sel bit 3 cleared the high halves are lost +(text, and the draw mismatches); another op_sel bit, and clamp, are refused; a pixel stage that reads attr0 only +as f32 gets no half copies; the mesh pipeline drops the half copies of attributes the pixel stage does not read. +""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_flat_param_check import LINEAR_PS_WORDS, VS_WORDS as FLAT_VS, root_blob, compile_hlsl, draw # noqa: E402 + +# binary16 pairs (high, low): (-2.5, 1.0), (65504, 0.5), (2^-24 denormal, 2^-14), (0.333, -1.0) +WORDS = (0xc1003c00, 0x7bff3800, 0x00010400, 0x3555bc00) +EXPECTED = ','.join('%08x' % w for w in WORDS) + + +def v_mov_literal(reg, value): + return struct.pack('> 16), f16tof32((v7) >> 16), f16tof32((v8) >> 16), ' \ + 'f16tof32((v9) >> 16));' in vs, vs + assert ' o.loparam0 = p.loparam0 + r.loparam0 - q.loparam0;' in vs, vs # the rectangle-list corner + for chan, d in zip('xyzw', range(2, 6)): + assert ' v%d = (v%d & 0xffff0000u) | x2w_f32tof16_rne(i.loparam0.%s);' % (d, d, chan) in ps, ps + assert ' v%d = (v%d & 0xffffu) | (x2w_f32tof16_rne(i.hiparam0.%s) << 16);' % (d, d, chan) in ps, ps + print('interp f16: VS exports loparam0/hiparam0 (f16tof32 of each half); PS packs both halves rounded to nearest even (x2w_f32tof16_rne)') + + # controls + saved = G.Stage.op_v_interp_p2_f16 + del G.Stage.op_v_interp_p2_f16 + try: + refused(pixel_words(), 'v_interp_p2_f16') + finally: + G.Stage.op_v_interp_p2_f16 = saved + lost = pipe(pixel_words(hi_opsel=0)).hlsl_ps() + assert '(x2w_f32tof16_rne(i.hiparam0.x) << 16)' not in lost and ' v2 = (v2 & 0xffff0000u) | x2w_f32tof16_rne(i.hiparam0.x);' \ + in lost, lost + refused(pixel_words(hi_opsel=1), 'v_interp_p2_f16 with op_sel 0x1') + refused(pixel_words(clamp=1), 'v_interp_p2_f16 with clamp') + # A compressed param export (upstream PR #2052's form, `exp param0 v6, v6, v7, v7 compr`) puts each half in its + # own channel, so the words are not halves: a binary16 read of it is refused, not read as halves of f32 bits. + plain_exp = bytes.fromhex('0f0200f806070809') + vs = vertex_words() + assert vs.count(plain_exp) == 1 + compr_vs = vs.replace(plain_exp, struct.pack('> 16), 0.0, 0.0, 0.0); }' + + class StubMesh: + def __init__(self, pipe, code): + self.exports, self.exported_prim = {'pos': ['0'] * 4, 'param0': ['0'] * 4}, True + self.broadcasts, self.lds_used, self.wave_any, self.used_v = 0, False, [], set() + + def __getattr__(self, name): # other per-wave tables hlsl_ms reads (scc_any, ...): empty + return [] + + def body(self): + return [' ' + line] + + def declarations(self): + return [] + saved = M.MeshStage + M.MeshStage = StubMesh + try: + kept = M.MeshPipeline(b'', pixel_words(), root_blob(), ps_hw_inputs=(None, None, 0xc0)).hlsl_ms() + dropped = M.MeshPipeline(b'', LINEAR_PS_WORDS, root_blob()).hlsl_ms() + finally: + M.MeshStage = saved + assert 'o.loparam0 = ' in kept and 'o.hiparam0 = ' in kept and 'float4 loparam0 : LOPARAM0;' in kept, kept + assert 'loparam0' not in dropped and 'hiparam0' not in dropped and 'o.param0 = ' in dropped, dropped + print('controls: refused without the p2 handler; op_sel cleared loses the high halves; op_sel 0x1, clamp and a compr export ' + 'refused; no half copies for an f32-only reader; mesh stage keeps them only when read') + + +def check_draw(dxc, renderer, adapter, fxc=None): + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + good, lost = pipe(pixel_words()), pipe(pixel_words(hi_opsel=0)) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + def build(name, source, profile): + return compile_hlsl(compiler, kind, source, '%s_%s' % (name, kind), profile, directory) + vs = build('vs', good.hlsl_vs(), vs_profile) + run = draw(renderer, adapter, vs, build('ps', good.hlsl_ps(), ps_profile), EXPECTED) + if run.returncode: + raise AssertionError('%s translated pair\n%s\n%s' % (kind, run.stdout, run.stderr)) + print('%s translated pair: %s' % (kind, EXPECTED), flush=True) + run = draw(renderer, adapter, build('vs_lost', lost.hlsl_vs(), vs_profile), + build('ps_lost', lost.hlsl_ps(), ps_profile), EXPECTED) + if run.returncode == 0: + raise AssertionError('%s control with op_sel cleared matched' % kind) + print('%s control, op_sel cleared: mismatches as expected (%s)' % (kind, run.stderr.strip()[-80:]), + flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_lane_invariant_check.py b/tests/startup_lane_invariant_check.py new file mode 100644 index 0000000000..8737daf9b0 --- /dev/null +++ b/tests/startup_lane_invariant_check.py @@ -0,0 +1,165 @@ +"""v_readfirstlane_b32 of a lane-invariant value, and the carry forms v_{add,sub,subrev}_co[_ci]_u32. + +Synthetic gfx1013 words only. The readfirstlane case is the shape LLVM AMDGPU emits for a 32-bit unsigned +division by a uniform divisor (AMDGPUCodeGenPrepare expandDivRem32: v_cvt_f32_u32 of the SGPR divisor, v_rcp, +v_mul by 0x4f7ffffe = 2^32 - 512, v_cvt_u32, then v_readfirstlane_b32 back to an SGPR), here behind a scalar +branch that is allowed now. Controls refuse: a source written from an SGPR assigned on only one side of a join, a +source behind a loop head, a source built from vcc, and a source read at a branch target. + +The carry forms are evaluated by the integer HLSL evaluator of startup_gfx2hlsl_bit_alu_check over an edge grid and +compared with 33-bit Python references written from the AMD RDNA 2 ISA description (V_ADD_CO_CI_U32: D = S0 + S1 + +CI, carry out; V_SUB_CO_CI_U32: D = S0 - S1 - CI, borrow when S1 + CI > S0; SUBREV swaps S0 and S1). +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +LITERAL = 255 + + +class TestPipeline: + root = {'params': [{'type': 2}], 'flags': 0} + + def resource(self, key, kind): + assert key == (('root', 0), None) and kind == 'buf' + return 'r0' + + def ud(self, source): + return 0 + + +def vop1(op, dst, src): + return 0x7e000000 | dst << 17 | op << 9 | src + + +def vop2(op, dst, src0, vsrc1): + return op << 25 | dst << 17 | vsrc1 << 9 | src0 + + +SBL = [0xf4000000 | 8 << 18 | 7 << 6 | 4, 125 << 25 | 12] # s_buffer_load_dword s7, s[8:11], 12 + + +def udiv(divisor_sgpr): + # v_cvt_f32_u32 v1, sD; v_rcp_f32 v1, v1; v_mul_f32 v1, 0x4f7ffffe, v1; v_cvt_u32_f32 v1, v1; v_readfirstlane s10, v1 + return [vop1(6, 1, divisor_sgpr), vop1(0x2a, 1, 257), vop2(8, 1, LITERAL, 1), 0x4f7ffffe, vop1(7, 1, 257), + vop1(2, 10, 257)] + + +S_CMP_EQ_U32_S7_0 = 0xbf000000 | 6 << 16 | 128 << 8 | 7 +S_MOV_B32_S12_1 = 0xbe800000 | 12 << 16 | 3 << 8 | 129 + + +def stage(words): + return G.Stage(TestPipeline(), 'vs', struct.pack('<%dI' % (len(words) + 1), *words, 0xbf810000)) + + +def asm(words): + return [x[3] for x in G.decode(struct.pack('<%dI' % len(words), *words))] + + +def refused(words, label): + try: + stage(words) + except G.Unsupported as error: + assert 'requires a proven uniform source' in str(error), (label, str(error)) + return + raise AssertionError('accepted: ' + label) + + +def body(s): + return '\n'.join(line for block in s.blocks for line in block[1]) + + +def readfirstlane(): + words = SBL + udiv(7) + assert asm(udiv(7))[:3] == ['v_cvt_f32_u32_e32 v1, s7', 'v_rcp_f32_e32 v1, v1', 'v_mul_f32_e32 v1, 0x4f7ffffe, v1'], asm(udiv(7)) + assert asm(udiv(7))[-1] == 'v_readfirstlane_b32 s10, v1' + assert 's10 = v1;' in body(stage(words)) + # A scalar branch around an SGPR write before the division: the divisor s7 was loaded before the branch. + branchy = SBL + [S_CMP_EQ_U32_S7_0, 0xbf840001, S_MOV_B32_S12_1] + udiv(7) # s_cbranch_scc0 over the s_mov + assert asm([0xbf840001])[0].startswith('s_cbranch_scc0'), asm([0xbf840001]) + assert 's10 = v1;' in body(stage(branchy)) + # Controls. + refused(SBL + [S_CMP_EQ_U32_S7_0, 0xbf840001, S_MOV_B32_S12_1] + udiv(12), + 'divisor assigned on one side of a join') + refused(SBL + udiv(7) + [0xbf85fff9], 'divisor behind a loop head') # s_cbranch_scc1 back to udiv + assert G.decode(struct.pack('<%dI' % len(SBL + udiv(7) + [0xbf85fff9]), *SBL, *udiv(7), 0xbf85fff9))[-1][3] \ + == 's_cbranch_scc1 label_0x8', 'loop branch target' + refused(SBL + [vop2(1, 1, 128, 0x101 - 256)] + [vop1(2, 10, 257)], 'v_cndmask_b32 v1, 0, v1, vcc') + refused(SBL + [vop1(6, 1, 7), 0xbf820000, vop1(2, 10, 257)], 'read at a branch target') + refused(SBL + [vop1(6, 1, 256)] + udiv(7)[1:], 'per-lane source v0') + print('readfirstlane: lane-invariant division accepted with and without a scalar branch; 5 controls refused') + + +def ref(kind, a, b, c): + if kind == 'subrev': + a, b = b, a + if kind == 'add': + total = a + b + c + return total & MASK, total >> 32 + return (a - b - c) & MASK, int(b + c > a) + + +def carry_text(words): + s = stage([]) + s.lines = [] + _, n, name, text = G.decode(struct.pack('<%dI' % len(words), *words))[0] + s.pc = 0 + s.one(name, text) + return s, '\n'.join(s.lines) + + +def carries(): + grid = [0, 1, 2, 0x7fffffff, 0x80000000, 0xfffffffe, MASK, 0x12345678] + bad = [] + forms = [] + for kind, op32, op64 in (('add', 0x28, 0x128), ('sub', 0x29, 0x129), ('subrev', 0x2a, 0x12a)): + e32 = [vop2(op32, 2, 256 + 4, 3)] # v_X_co_ci_u32_e32 v2, vcc_lo, v4, v3, vcc_lo + assert asm(e32)[0] == 'v_%s_co_ci_u32_e32 v2, vcc_lo, v4, v3, vcc_lo' % kind, asm(e32) + e64 = [0xd4000000 | op64 << 16 | 18 << 8 | 2, (256 + 4) | (256 + 3) << 9 | 106 << 18] + assert asm(e64)[0] == 'v_%s_co_ci_u32_e64 v2, s18, v4, v3, vcc_lo' % kind, asm(e64) + co_op = {'add': 0x30f, 'sub': 0x310, 'subrev': 0x319}[kind] + co = [0xd4000000 | co_op << 16 | 18 << 8 | 2, (256 + 4) | (256 + 3) << 9] + assert asm(co)[0] == 'v_%s_co_u32 v2, s18, v4, v3' % kind, asm(co) + for words, carry_in, sdst in ((e32, True, 'vcc'), (e64, True, 's18'), (co, False, 's18')): + s, text = carry_text(words) + lines = text.split('\n') + assert lines[0].startswith('q = uint2(') and lines[1] == 'v2 = q.x;', text + assert lines[2] == ('vcc = q.y;' if sdst == 'vcc' else 's18 = q.y;'), text + if sdst == 's18': + assert 18 in s.masks, 'carry-out SGPR is a mask' + value, carry = G.split_top(lines[0][len('q = uint2('):-2]) + value, carry = Expr(value), Expr(carry) + for a in grid: + for b in grid: + for c in ((0, 1) if carry_in else (0,)): + env = {'v4': a, 'v3': b, 'vcc': c} + got = value.run(env)[0], carry.run(env)[0] + if got != ref(kind, a, b, c): + bad.append((kind, words, a, b, c, got, ref(kind, a, b, c))) + forms.append(asm(words)[0].split(' ')[0]) + assert not bad, bad[:5] + # Refusals: clamp, and a carry-in that is not a lane mask. + clamp = [0xd4000000 | 0x128 << 16 | 1 << 15 | 18 << 8 | 2, (256 + 4) | (256 + 3) << 9 | 106 << 18] + numeric_ci = [0xd4000000 | 0x128 << 16 | 18 << 8 | 2, (256 + 4) | (256 + 3) << 9 | 20 << 18] # CI = s20 + for words, why in ((clamp, 'clamp'), (numeric_ci, 'lane mask')): + try: + carry_text(words) + except G.Unsupported as error: + assert why in str(error), (why, str(error), asm(words)) + else: + raise AssertionError('accepted %s' % asm(words)) + print('carry forms: %d forms match the 33-bit references on %d inputs each; 2 controls refused' + % (len(forms), len(grid) ** 2 * 2)) + + +if __name__ == '__main__': + readfirstlane() + carries() diff --git a/tests/startup_lit64_check.py b/tests/startup_lit64_check.py new file mode 100644 index 0000000000..b71b1df6a4 --- /dev/null +++ b/tests/startup_lit64_check.py @@ -0,0 +1,49 @@ +"""A 32-bit literal in a 64-bit integer operand: accepted when bit 31 is clear (high dword 0 under either extension). + +Synthetic VOP3 words: v_lshrrev_b64 v[5:6], 0, (op 0x300, src0 = inline 0, src1 = 255 + literal). LLVM +AMDGPUDisassembler::decodeLiteralConstant zero-extends a literal for OPERAND_REG_IMM_INT64 (with a ToDo on +signedness) and the assembler encodes Lo_32; zero- and sign-extension agree exactly when bit 31 is clear. +Controls: 0x80000000 (the readings differ) stays refused; the inline constant 1 keeps its old lowering. +""" +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def one(words): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + _, n, name, text = G.decode(struct.pack('<%dI' % len(words), *words))[0] + s.pc = 0 + s.one(name, text) + return text, '\n'.join(s.lines) + + +def main(): + text, body = one([0xd7000005, 128 | 255 << 9, 0x3f800000]) + assert text == 'v_lshrrev_b64 v[5:6], 0, 0x3f800000', text + assert 'x2w_lshr64_lo(0x3f800000u, 0x00000000u, 0x00000000u)' in body, body + assert 'x2w_lshr64_hi(0x3f800000u, 0x00000000u, 0x00000000u)' in body, body + try: + one([0xd7000005, 128 | 255 << 9, 0x80000000]) + except G.Unsupported as error: + assert '64-bit literal operand 0x80000000' in str(error), str(error) + else: + raise AssertionError('literal with bit 31 set accepted') + text, body = one([0xd7000005, 128 | 129 << 9]) + assert text == 'v_lshrrev_b64 v[5:6], 0, 1' and 'x2w_lshr64_lo(0x00000001u, 0x00000000u, 0x00000000u)' in body, body + print('lit64: bit-31-clear literal -> high dword 0; 0x80000000 refused; inline 1 unchanged') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_literal_halves_check.py b/tests/startup_literal_halves_check.py new file mode 100644 index 0000000000..b7a934f7a8 --- /dev/null +++ b/tests/startup_literal_halves_check.py @@ -0,0 +1,67 @@ +"""f16 halves of literals in VOP3P sources: v_fma_mix_* with a 32-bit literal, v_pk_* with the inline integer 0. + +Synthetic words. A VOP3P literal is read through op_sel like a register: LLVM SIFoldOperands::tryFoldImmWithOpSel +takes a packed operand's halves as ImmVal >> (OP_SEL_0 ? 16 : 0) and ImmVal >> (OP_SEL_1 ? 16 : 0), which is how a +compiler encodes two different f16 constants in the one literal (here 0x4600 = 6.0 low, 0xc200 = -3.0 high: +6 * |x| - 3). The inline integer 0 has no set bit, so every half selection of it reads +0.0. Controls: a literal +read as an f32 mix operand keeps its full 32 bits, and a non-zero inline constant in a packed f16 operand with a +high-half selection stays refused. +""" +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def one(words): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + _, n, name, text = G.decode(struct.pack('<%dI' % len(words), *words))[0] + s.pc = 0 + s.one(name, text) + return text, '\n'.join(s.lines) + + +def half(bits): + return struct.unpack('> 16), f16tof32(0x00000000u))) << 16);'), body + # inline 1.0 (242) read through its high half: its packed layout is not pinned down here, so refused + one_hi = [0xcc000000 | 0x12 << 16 | 14, (256 + 14) | 242 << 9 | 1 << 27 | 1 << 28] + try: + one(one_hi) + except G.Unsupported as error: + assert 'packed f16 operand 1.0' in str(error), str(error) + else: + raise AssertionError('accepted %s' % one(one_hi)[0]) + print('literal halves: fma_mix literal halves 6.0 / -3.0, f32 literal control, pk inline 0, inline 1.0 refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_log_cap_check.cpp b/tests/startup_log_cap_check.cpp new file mode 100644 index 0000000000..2e4529a04b --- /dev/null +++ b/tests/startup_log_cap_check.cpp @@ -0,0 +1,71 @@ +// x2w_local::first_calls (src/startup_stubs/log_cap.h): a log cap that never wraps. Checks the first +// `limit` calls pass and no later one does, from several threads at once (exact count), that the counter +// stops at limit + 1, and that a counter near LONG_MAX stays closed. `--mutate wrap` runs the same +// checks against the old `InterlockedIncrement(&c) <= limit` pattern, which wraps: the negative control. +#include "startup_stubs/log_cap.h" + +#include +#include +#include +#include +#include + +namespace { + +bool use_old = false; + +bool cap(volatile LONG& counter, LONG limit) +{ + return use_old ? InterlockedIncrement(&counter) <= limit : x2w_local::first_calls(counter, limit); +} + +int failures = 0; + +void expect(bool ok, const char* what) +{ + std::printf("%s %s\n", ok ? "ok " : "FAIL", what); + if (!ok) ++failures; +} + +} // namespace + +int main(int argc, char** argv) +{ + use_old = argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "wrap") == 0; + + { + volatile LONG counter = 0; + int passed = 0; + for (int i = 0; i < 100; ++i) passed += cap(counter, 4); + expect(passed == 4, "single thread: 4 of 100 calls pass a cap of 4"); + expect(use_old || counter == 5, "single thread: the counter stops at limit + 1"); + } + { + constexpr int threads = 8, calls = 200000; + constexpr LONG limit = 1000; + volatile LONG counter = 0; + std::vector passed(threads, 0); + std::vector pool; + for (int t = 0; t < threads; ++t) + pool.emplace_back([&, t] { for (int i = 0; i < calls; ++i) passed[t] += cap(counter, limit); }); + for (auto& th : pool) th.join(); + long total = 0; + for (long p : passed) total += p; + expect(total == limit, "8 threads: exactly 1000 of 1.6 million calls pass a cap of 1000"); + expect(use_old || counter == limit + 1, "8 threads: the counter stops at limit + 1"); + } + { + // A counter that has already counted to LONG_MAX (2^31 - 1 calls): the next calls must stay closed. + volatile LONG counter = LONG_MAX; + int passed = 0; + for (int i = 0; i < 1000; ++i) passed += cap(counter, 4); + expect(passed == 0, "a counter at LONG_MAX stays closed (the old pattern wraps and passes here)"); + } + { + expect(x2w_local::first_of(1, 4) && x2w_local::first_of(4, 4), "first_of: counts 1..limit pass"); + expect(!x2w_local::first_of(5, 4) && !x2w_local::first_of(LONG_MIN, 4) && !x2w_local::first_of(-1, 4) && !x2w_local::first_of(0, 4), + "first_of: past the limit and wrapped counts do not"); + } + std::printf("%s\n", failures ? "FAILED" : "PASSED"); + return failures ? 1 : 0; +} diff --git a/tests/startup_loop_carried_check.py b/tests/startup_loop_carried_check.py new file mode 100644 index 0000000000..95e3354758 --- /dev/null +++ b/tests/startup_loop_carried_check.py @@ -0,0 +1,117 @@ +"""Loop-carried SGPRs: at a loop head the translation drops what the entry state knew about registers the loop writes.""" +import re +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_scalar_bits_check import stage # noqa: E402 + + +def sop1(op, d, s): + return 0xbe800000 | d << 16 | op << 8 | s + + +def sop2(op, d, a, b): + return 0x80000000 | op << 23 | d << 16 | b << 8 | a + + +def sopc(op, a, b): + return 0xbf000000 | op << 16 | b << 8 | a + + +def sopp(op, words_back): + return 0xbf800000 | op << 16 | (-words_back) & 0xffff # target = next instruction - 4 * words_back bytes + + +MOV, ADD, CMP_LG, SCC1 = 3, 0, 7, 5 +INLINE = lambda n: 128 + n # noqa: E731 inline integer constants 0..64 +V_MOV_V0 = lambda s: 0x7e000200 | s # noqa: E731 v_mov_b32 v0, s + + +def program(kind): + if kind == 'counter': + return [sop1(MOV, 14, INLINE(0)), sop1(MOV, 15, INLINE(0)), + sop2(ADD, 14, 14, INLINE(1)), sop2(ADD, 15, 15, 14), sopc(CMP_LG, 14, INLINE(5)), sopp(SCC1, 4), + V_MOV_V0(15)] + if kind == 'bound': + return [sop1(MOV, 20, INLINE(7)), sop1(MOV, 14, INLINE(0)), sop1(MOV, 15, INLINE(0)), + sop2(ADD, 14, 14, INLINE(1)), sop2(ADD, 15, 15, 14), sopc(CMP_LG, 14, 20), sopp(SCC1, 4), + V_MOV_V0(15)] + if kind == 'nested': + return [sop1(MOV, 10, INLINE(0)), sop1(MOV, 15, INLINE(0)), + sop1(MOV, 11, INLINE(0)), # O: inner counter reset + sop2(ADD, 11, 11, INLINE(1)), sop2(ADD, 15, 15, INLINE(1)), # I: inner pass, total += 1 + sopc(CMP_LG, 11, INLINE(3)), sopp(SCC1, 4), + sop2(ADD, 10, 10, INLINE(1)), sopc(CMP_LG, 10, INLINE(4)), sopp(SCC1, 8), + V_MOV_V0(15)] + raise ValueError(kind) + + +def c_to_py(expr): + expr = re.sub(r'\b(0x[0-9a-f]+|\d+)u\b', r'\1', expr) + expr = expr.replace('&&', ' and ').replace('||', ' or ') + expr = re.sub(r'!(?!=)', ' not ', expr) + m = re.fullmatch(r'\((.*)\) \? (.*) : (.*)', expr) + if m: + expr = '(%s if %s else %s)' % (m.group(2), m.group(1), m.group(3)) + return expr + + +def run(s, limit=1000): + env = {'exec': 1, 'scc': False, 'vcc': 0} + order = [b[0] for b in s.blocks] + i, visits = 0, 0 + while i is not None and i < len(s.blocks): + visits += 1 + if visits > limit: + return None, visits + off, lines, term = s.blocks[i] + for line in lines: + m = re.fullmatch(r'(?:if \(exec & 1\) )?(\w+) = (.*);', line.strip()) + assert m, line + value = eval(c_to_py(m.group(2)), {}, env) + env[m.group(1)] = value if isinstance(value, bool) else value & 0xffffffff + nxt = i + 1 + if term and term[0] == 'end': + break + if term and term[0] == 'jump': + nxt = order.index(term[1]) + elif term and term[0] == 'branch': + if eval(c_to_py(term[1]), {}, env): + nxt = order.index(term[2]) + i = nxt + return env.get('v0'), visits + + +def main(): + want = {'counter': 15, 'bound': 28, 'nested': 12} + for kind, value in want.items(): + s = stage(program(kind)) + got, visits = run(s) + assert got == value, (kind, got, visits, s.blocks) + bound = stage(program('bound')) + assert any('s14 != 0x00000007u' in line for _, lines, _ in bound.blocks for line in lines), bound.blocks + # A loop-written register whose entry value is symbolic only (a descriptor: its HLSL variable was never + # assigned) becomes a conflict that any use refuses; a run-time-backed constant is simply forgotten. + probe = stage(program('counter')) + probe.sym = {14: ('desc', 0, 0, 0), 15: ('const', 0), 20: ('desc', 0, 0, 0)} + probe.forget_loop_writes(8, 20) # loop head = word 2, back edge = word 5 + assert probe.sym == {14: ('conflict',), 20: ('desc', 0, 0, 0)}, probe.sym + saved = G.Stage.forget_loop_writes + G.Stage.forget_loop_writes = lambda self, head, last: None + try: + old = stage(program('counter')) + got, visits = run(old) + assert got is None, (got, visits, old.blocks) # the old form never leaves the loop + assert any('0x00000000u + 0x00000001u' in line for _, lines, _ in old.blocks for line in lines) + finally: + G.Stage.forget_loop_writes = saved + print('loop_carried: counter loop 15 (5 passes), constant bound not written in the loop still folds (28), ' + 'nested 4 x 3 = 12; old behaviour (entry constants kept at the head) never exits: negative control') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_loop_regions_check.py b/tests/startup_loop_regions_check.py new file mode 100644 index 0000000000..6d52275e61 --- /dev/null +++ b/tests/startup_loop_regions_check.py @@ -0,0 +1,169 @@ +"""Stage.body: only the back-edge regions of the block graph run inside a dispatch loop.""" +import random +import re +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +LIMIT = 300 + + +class Fake: + body = G.Stage.body + LOOP_PASSES = 10 ** 6 # the trace comparison checks the control flow; the bound is checked on its own + + def __init__(self, blocks): + self.blocks = blocks + + +class Bounded(Fake): + LOOP_PASSES = G.Stage.LOOP_PASSES + + +def make(rng, n): + blocks = [] + for i in range(n): + kind = rng.random() + if i == n - 1 and kind < 0.3: + term = ('end',) + elif kind < 0.35: + term = None + elif kind < 0.45: + term = ('end',) + elif kind < 0.6: + term = ('jump', 0x10 * rng.randrange(n)) + else: + term = ('branch', 'c%d' % i, 0x10 * rng.randrange(n)) + blocks.append((0x10 * i, ['trace(%d);' % i], term)) + return blocks + + +class Conds: + def __init__(self, seed): + self.seed, self.visits = seed, {} + + def __call__(self, block): + k = self.visits[block] = self.visits.get(block, 0) + 1 + return random.Random(self.seed * 100003 + block * 1009 + k).random() < 0.5 + + +def reference(blocks, conds): + trace, pc = [], 0 + while pc != 0xffff and len(trace) < LIMIT: + _, _, term = blocks[pc] + trace.append(pc) + nxt = pc + 1 if pc + 1 < len(blocks) else 0xffff + if not term: + pc = nxt + elif term[0] == 'end': + pc = 0xffff + elif term[0] == 'jump': + pc = term[1] // 0x10 + else: + pc = term[2] // 0x10 if conds(pc) else nxt + return trace + + +def parse(lines): + """[('block', i, pc_line)] and [('loop', lo, hi, [blocks])] in order.""" + items, cur, loop = [], None, None + for line in lines: + s = line.strip() + m = re.match(r'\[loop\] for \(uint guard = 0; guard < (\d+)u && pc >= (\d+) && pc <= (\d+); \+\+guard\) \{', s) + if m: + loop = ('loop', int(m.group(2)), int(m.group(3)), [], int(m.group(1))) + items.append(loop) + continue + m = re.match(r'(?:else )?if \(pc == (\d+)\) \{', s) + if m: + cur = [int(m.group(1)), None] + (loop[3] if loop else items).append(('block', cur)) + continue + if s.startswith('pc = ') and cur is not None: + cur[1] = s + elif s == '}' and cur is None and loop is not None: + loop = None + elif s == '}': + cur = None + return items + + +def run_pc(line, i, conds): + m = re.fullmatch(r'pc = \((c\d+)\) \? (\d+) : (\d+);', line) + if m: + return int(m.group(2)) if conds(i) else int(m.group(3)) + return 0xffff if line == 'pc = 0xffffu;' else int(re.fullmatch(r'pc = (\d+);', line).group(1)) + + +def emitted(lines, conds, loops=True, limit=LIMIT): + trace, pc = [], 0 + + def block(b): + nonlocal pc + trace.append(b[0]) + pc = run_pc(b[1], b[0], conds) + for item in parse(lines): + if item[0] == 'block': + if pc == item[1][0] and len(trace) < limit: + block(item[1]) + else: + _, lo, hi, members, bound = item + guard = 0 + while lo <= pc <= hi and guard < bound and len(trace) < limit: + guard += 1 + for _, b in members: + if pc == b[0]: + block(b) + break + if not loops: + break + return trace + + +def main(): + rng = random.Random(11) + looped = differ = 0 + for seed in range(3000): + blocks = make(rng, rng.randrange(3, 15)) + lines = Fake(blocks).body() + want = reference(blocks, Conds(seed)) + got = emitted(lines, Conds(seed)) + assert got == want, (seed, blocks, lines, want[:20], got[:20]) + if any('[loop]' in x for x in lines): + looped += 1 + differ += emitted(lines, Conds(seed), loops=False) != want + assert looped > 500 and differ > 100, (looped, differ) + straight = [(0x10 * i, ['trace(%d);' % i], ('branch', 'c', 0x10 * (i + 2)) if i < 8 else None) for i in range(10)] + assert not any('[loop]' in x for x in Fake(straight).body()) + measured = [(0x10 * i, ['x;'], None) for i in range(40)] + measured[12] = (0xc0, ['x;'], ('branch', 'scc', 0xc0)) + measured[20] = (0x140, ['x;'], ('branch', 'scc', 0x130)) + lines = Fake(measured).body() + heads = [x.strip() for x in lines if '[loop]' in x] + assert heads == ['[loop] for (uint guard = 0; guard < 1000000u && pc >= 12 && pc <= 12; ++guard) {', + '[loop] for (uint guard = 0; guard < 2000000u && pc >= 19 && pc <= 20; ++guard) {'], heads + always = lambda block: True # noqa: E731 + spins = { + 'self jump': [(0x0, ['a;'], None), (0x10, ['b;'], ('jump', 0x10)), (0x20, ['c;'], ('end',))], + 'cycle': [(0x0, ['a;'], None), (0x10, ['b;'], None), (0x20, ['c;'], ('jump', 0x10)), (0x30, ['d;'], ('end',))], + 'taken branch': [(0x0, ['a;'], ('branch', 'c0', 0x0)), (0x10, ['d;'], ('end',))], + } + for name, graph in spins.items(): + lines = Bounded(graph).body() + bounds = [int(re.search(r'guard < (\d+)u', x).group(1)) for x in lines if '[loop]' in x] + size = len(graph) - (2 if name != 'taken branch' else 1) + assert bounds == [64 * size], (name, bounds) + trace = emitted(lines, always, limit=10 ** 7) + assert len(trace) <= 64 * size + 2, (name, len(trace)) + unbounded = emitted(Fake(graph).body(), always, limit=10 ** 4) + assert len(unbounded) == 10 ** 4, name + print('loop_regions: %d random graphs run the same block trace as one dispatch loop (%d with loops; the ' + 'one-pass negative control differs on %d); loop-free graph has no loop; two waterfall loops get two ' + 'loops of 1 and 2 blocks; 3 never-exiting loops stop after 64 passes (the unbounded control runs ' + 'into the cut)' % (3000, looped, differ)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_memory_srv_announced_check.py b/tests/startup_memory_srv_announced_check.py new file mode 100644 index 0000000000..d01994ec01 --- /dev/null +++ b/tests/startup_memory_srv_announced_check.py @@ -0,0 +1,109 @@ +"""Memory SRVs of console-swizzled (layout 0x105) textures whose memory the XG stand-in filled. + +X2W_MEMORY_SRV_ANNOUNCED=1: views of announced addresses are drawn from the linear (desktop footprint) bytes, +both mips; a texture with the same description and bytes that XG did not announce is refused. Without the +switch every call is refused and the draws read a null view (negative control). +""" +from pathlib import Path +import sys +import tempfile + +from startup_address_srv_check import draw_texture + +HLSL = ("Texture2D t : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint2 q = uint2(p.xy);\n" + " if (q.y < 2) return t.Load(int3(q.x % 2, q.y, 0));\n" + " return t.Load(int3(0, 0, 1));\n}\n") + + +def texel(which, mip, x, y): + if mip: + return (9, 99, 199, 255) if which == 1 else (5, 6, 7, 255) + return (100 + 20 * x + 50 * y, 50, 150, 255) if which == 1 else (10 + 40 * x + 80 * y, 200, 30, 255) + + +def expected_on(): + # Columns publish A B C A B C A A; C is refused, so the previous view (B) stays. + effective = (0, 1, 1, 0, 1, 1, 0, 0) + return bytes(c for y in range(4) for x in range(8) + for c in (texel(effective[x], 0, x % 2, y) if y < 2 else texel(effective[x], 1, 0, 0))) + + +def run(directory, consumer, backend, switch, census=False): + modes = {"X2W_TEST_ANNOUNCED_SRV": "1", "X2W_TRAP_LOG": str(directory / "trap.log")} + if switch: + modes["X2W_MEMORY_SRV_ANNOUNCED"] = "1" + if census: + modes["X2W_TEXTURE_CENSUS"] = "1" + modes["X2W_TEXTURE_CENSUS_EVERY"] = "1" + pixels = draw_texture(directory, consumer, backend, HLSL, modes) + return pixels, (directory / "trap.log").read_text(errors="replace") if pixels is not None else "" + + +def last_census(log, prefix): + lines = [line for line in log.splitlines() if line.startswith("x2w-texcensus " + prefix)] + return lines[-1] if lines else "" + + +def check_census(log, label, slot70, refusal_classes, draws): + """The last cumulative X2W_TEXTURE_CENSUS lines of a run (X2W_TEXTURE_CENSUS_EVERY=1).""" + want_calls = f"slot70 calls 8 (threshold, cumulative): {slot70}" + if want_calls not in last_census(log, "slot70 calls"): + raise AssertionError(f"{label}: last slot-70 census line {last_census(log, 'slot70 calls')!r}, expected {want_calls!r}") + lines = log.splitlines() + head = max(i for i, line in enumerate(lines) if line.startswith("x2w-texcensus slot70 refusals")) + classes = [line.removeprefix("x2w-texcensus ") for line in lines[head + 1:head + 1 + len(refusal_classes)]] + if classes != refusal_classes: + raise AssertionError(f"{label}: refusal classes {classes}, expected {refusal_classes}") + want_draws = f"draw textures binding (cumulative): {draws}" + if want_draws not in last_census(log, "draw textures"): + raise AssertionError(f"{label}: last draw census line {last_census(log, 'draw textures')!r}, expected {want_draws!r}") + words = " ".join(f"{0x61000000 + i:08x}" for i in range(16)) + slot61 = [line for line in lines if line.startswith("x2w-texcensus Device::slot61")] + if len(slot61) != 1 or "r8=0x5150 r9=0x1 words " + words not in slot61[0]: + raise AssertionError(f"{label}: slot-61 lines {slot61}") + + +def check(root, consumer, backend): + on_dir, off_dir, census_dir = root / "on", root / "off", root / "census" + on_dir.mkdir() + off_dir.mkdir() + census_dir.mkdir() + actual, log = run(on_dir, consumer, backend, True, census=True) + if actual is None: + return 77 + if actual != expected_on(): + raise AssertionError(f"switch on: actual {actual.hex()}\n expected {expected_on().hex()}") + if "X2W_MEMORY_SRV_ANNOUNCED=1" not in log: + raise AssertionError("switch on: no X2W_MEMORY_SRV_ANNOUNCED line") + refusals = [line for line in log.splitlines() if "Device::slot70" in line and "reason=" in line] + if len(refusals) != 2 or not all("layout=0x105" in line for line in refusals): + raise AssertionError("switch on: expected the two unannounced calls refused:\n" + "\n".join(refusals)) + unannounced = "2 x unsupported_description dim 3 layout 0x105 fmt 28 mips>1 not-announced nonzero" + check_census(log, "switch on, census", "linear 0, announced-linear 6, tiled/bc64 0, buffer 0, stand-in buffer 0, detiled 0, refused 2", + [unannounced], "real 8 (linear memory srv 8, tiled address 0, other 0, detiled 0), null; real by format 28:8") + # Census without the announced switch: all 8 calls refused (6 at announced addresses), 8 null bindings. + census_off, census_log = run(census_dir, consumer, backend, False, census=True) + if census_off != bytes(4 * 8 * 4): + raise AssertionError(f"census, switch off: expected null views (all zero), got {census_off.hex()}") + check_census(census_log, "census, switch off", "linear 0, announced-linear 0, tiled/bc64 0, buffer 0, stand-in buffer 0, detiled 0, refused 8", + ["6 x unsupported_description dim 3 layout 0x105 fmt 28 mips>1 announced nonzero", unannounced], + "real 0 (linear memory srv 0, tiled address 0, other 0, detiled 0), null cause2:8; real by format") + off, off_log = run(off_dir, consumer, backend, False) + if off != bytes(4 * 8 * 4): + raise AssertionError(f"switch off: expected null views (all zero), got {off.hex()}") + off_refusals = [line for line in off_log.splitlines() if "Device::slot70" in line and "reason=" in line] + if len(off_refusals) != 8: + raise AssertionError(f"switch off: {len(off_refusals)} refusal lines, expected 8") + if "x2w-texcensus" in off_log: + raise AssertionError("census off: x2w-texcensus lines logged") + print(f"{backend}: announced 0x105 views drawn (2 mips, 32 RGBA pixels exact), unannounced refused; " + "switch off: 8 refusals, null views; census counts exact (8 real / 8 null, refusal classes, slot 61), " + "census off: no census lines, slot 61 no-op") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_memory_srv_detile_check.py b/tests/startup_memory_srv_detile_check.py new file mode 100644 index 0000000000..ba318b8d9c --- /dev/null +++ b/tests/startup_memory_srv_detile_check.py @@ -0,0 +1,174 @@ +"""Startup memory srv detile check.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +from startup_address_srv_check import draw_texture + +SIDE = 64 +PIXELS = SIDE * SIDE +BC1_UNORM, BC3_UNORM, RGBA16F = 71, 77, 10 +TEX2D, TEX3D = 3, 4 + +# name, layout, dimension, format, width, height, depth or array size, mips (pixels; BC shapes are 4x4 blocks in the layout check) +CASES = [ + ("bc1_256_9mips_4k_s", 0x105, TEX2D, BC1_UNORM, 256, 256, 1, 9), + ("bc1_256x128x2_8mips_64k_d", 0x10A, TEX2D, BC1_UNORM, 256, 128, 2, 8), + # BC3 0x105 256x256 is a tiled_bc_srv description; the tiled paths take single mips only, so the chain is detiled + ("bc3_256_9mips_4k_s", 0x105, TEX2D, BC3_UNORM, 256, 256, 1, 9), + ("rgba16f_17cubed_3d_5mips", 0x105, TEX3D, RGBA16F, 17, 17, 17, 5), + ("rgba16f_100x60_3mips_linear", 0x100, TEX2D, RGBA16F, 100, 60, 1, 3), + ("bc1_132_8mips_4k_s", 0x105, TEX2D, BC1_UNORM, 132, 132, 1, 8), + ("bc3_132x68x2_8mips_64k_d", 0x10A, TEX2D, BC3_UNORM, 132, 68, 2, 8), +] +# Refused with the switch on, and the decline the census names: 4-byte elements in a D mode (chip-dependent equation). +DECLINED = [ + (("bc1_132_8mips_4k_s", 0x106, TEX2D, 28, 64, 64, 1, 1), "layout or element size"), +] + + +def levels(case): + """(mip, slice, width, height, depth) in elements, D3D extents (floor per level; BC blocks round up).""" + _, _, dimension, fmt, width, height, depth, mips = case + out = [] + for mip in range(mips): + w, h = max(1, width >> mip), max(1, height >> mip) + if fmt in (BC1_UNORM, BC3_UNORM): + w, h = (w + 3) // 4, (h + 3) // 4 + if dimension == TEX3D: + out.append((mip, 0, w, h, max(1, depth >> mip))) + else: + out.extend((mip, s, w, h, 1) for s in range(depth)) + return out + + +def view_kind(case): + return "tex3d" if case[2] == TEX3D else "tex2da" if case[6] > 1 else "tex2d" + + +def shader(case): + kind = view_kind(case) + bc = case[3] in (BC1_UNORM, BC3_UNORM) + bc3 = case[3] == BC3_UNORM + declaration = {"tex2d": "Texture2D", "tex2da": "Texture2DArray", "tex3d": "Texture3D"}[kind] + body = [] + for mip, s, w, h, d in levels(case): + count = w * h * d + if kind == "tex3d": + load = f"t.Load(int4(x, y, z, {mip}))" + elif kind == "tex2da": + load = f"t.Load(int4({'4 * x, 4 * y' if bc else 'x, y'}, {s}, {mip}))" + else: + load = f"t.Load(int3({'4 * x, 4 * y' if bc else 'x, y'}, {mip}))" + if bc: + alpha = f" || uint(round(c.a * 255)) != {16 * (mip + 8 * s) + 5}u" if bc3 else "" + test = (f"float4 c = {load}; uint id = (uint(round(c.r * 31)) << 11) | (uint(round(c.g * 63)) << 5) | " + f"uint(round(c.b * 31)); if (id != (x | (y << 6) | ({mip + 8 * s}u << 12)){alpha}) bad++;") + else: + test = f"if (any({load} != float4(x, y, z, {mip + 1}))) bad++;" + body.append(f" [loop] for (uint i = p; i < {count}u; i += {PIXELS}u) {{ uint x = i % {w}u, y = (i / {w}u) % {h}u, " + f"z = i / {w * h}u; {test} n++; }}") + return (f"{declaration} t : register(t0);\n" + "float4 main(float4 q : SV_Position) : SV_Target {\n" + f" uint p = uint(q.y) * {SIDE}u + uint(q.x), bad = 0, n = 0;\n" + "\n".join(body) + "\n" + " return float4(bad ? 0 : 1, n / 255.0, 0, 1);\n}\n") + + +def write_surface(layout_check, case, path): + result = subprocess.run([layout_check, "--write-tiled", case[0], path, "--addrlib"], capture_output=True, text=True) + if result.returncode == 0: + return "addrlib" + if result.returncode != 77: + raise AssertionError(f"{case[0]}: --write-tiled --addrlib failed ({result.returncode}): {result.stdout}{result.stderr}") + subprocess.run([layout_check, "--write-tiled", case[0], path], check=True, capture_output=True) + return "gfx10_layout.h (plumbing only: built without addrlib)" + + +def run(directory, consumer, backend, case, surface, switch, layout=None): + directory.mkdir() + name, case_layout, dimension, fmt, width, height, depth, mips = case + modes = {"X2W_TEST_DETILE_SRV": str(surface), "X2W_TRAP_LOG": str(directory / "trap.log"), + "X2W_TEST_DETILE_DESC": f"{layout or case_layout:x} {dimension} {fmt} {width} {height} {depth} {mips}", + "X2W_TEXTURE_CENSUS": "1", "X2W_TEXTURE_CENSUS_EVERY": "1"} + if switch: + modes["X2W_MEMORY_SRV_DETILE"] = "1" + pixels = draw_texture(directory, consumer, backend, shader(case), modes, view_kind(case)) + if pixels is None: + return None + if len(pixels) != PIXELS * 4: + raise AssertionError(f"{name}: {len(pixels)} bytes read back, expected {PIXELS * 4}") + bad = sum(1 for i in range(PIXELS) if pixels[4 * i] != 255) + checked = sum(pixels[4 * i + 1] for i in range(PIXELS)) + return bad, checked, (directory / "trap.log").read_text(errors="replace") + + +def census_line(log, prefix): + lines = [line for line in log.splitlines() if line.startswith("x2w-texcensus " + prefix)] + return lines[-1] if lines else "" + + +def check(root, consumer, backend, layout_check): + source = None + for index, case in enumerate(CASES): + name = case[0] + surface = root / f"{name}.bin" + source = write_surface(layout_check, case, surface) + expected = sum(w * h * d for _, _, w, h, d in levels(case)) + result = run(root / f"on{index}", consumer, backend, case, surface, True) + if result is None: + return 77 + bad, checked, log = result + if checked != expected: + raise AssertionError(f"{name}: {checked} elements checked by the shader, expected {expected}") + if bad: + raise AssertionError(f"{name}: {bad} of {PIXELS} pixels saw a mismatching element\n" + "\n".join( + line for line in log.splitlines() if "slot70" in line or "memsrv" in line)) + if f"layout 0x{case[1]:x}" not in log or "x2w-memsrv detiled memory SRV" not in log: + raise AssertionError(f"{name}: no detiled memory SRV line") + # Two calls, both detiled; one desktop texture (the second call reuses it). + if "stand-in buffer 0, detiled 2, refused 0" not in census_line(log, "slot70 calls"): + raise AssertionError(f"{name}: slot-70 census {census_line(log, 'slot70 calls')!r}") + if "detiled 1)" not in census_line(log, "draw textures"): + raise AssertionError(f"{name}: draw census {census_line(log, 'draw textures')!r}") + print(f"{backend}: {name} layout 0x{case[1]:x}: {expected} elements, every one matches ({source})") + # Negative control 1: the switch off. The calls are refused and the null view reads zeros. + case = CASES[0] + bad, checked, log = run(root / "off", consumer, backend, case, root / f"{case[0]}.bin", False) + refusals = [line for line in log.splitlines() if "Device::slot70" in line and "reason=" in line] + if not bad or len(refusals) != 2 or "x2w-memsrv detiled" in log: + raise AssertionError(f"switch off: {bad} mismatching pixels, {len(refusals)} refusals (expected mismatches and 2)") + # Negative control 2: the 0x105 bytes described as 0x109 (64 KiB standard; the fixture memory has 1 MiB of slack, so + # the larger surface is readable): detiled, but with the wrong addresses. + bad_layout, checked_layout, log = run(root / "wrong", consumer, backend, case, root / f"{case[0]}.bin", True, 0x109) + if not bad_layout or "x2w-memsrv detiled memory SRV" not in log: + raise AssertionError(f"wrong layout: {bad_layout} mismatching pixels (expected some), detile line " + f"{'x2w-memsrv detiled memory SRV' in log}") + print(f"{backend}: controls: switch off: {bad} of {PIXELS} pixels mismatch, 2 refusals; " + f"0x105 bytes as 0x109: {bad_layout} of {PIXELS} pixels mismatch") + # The same control for the chains with partial edge blocks (one per layout): bytes placed for 0x105 / 0x10a, + # described as 0x109. + for case in CASES[-2:]: + bad_wrong, _, log = run(root / f"wrong_{case[0]}", consumer, backend, case, root / f"{case[0]}.bin", True, 0x109) + if not bad_wrong or "x2w-memsrv detiled memory SRV" not in log: + raise AssertionError(f"{case[0]} as 0x109: {bad_wrong} mismatching pixels (expected some)") + print(f"{backend}: control: {case[0]} bytes (0x{case[1]:x}) as 0x109: {bad_wrong} of {PIXELS} pixels mismatch") + # Refusals that the switch declines name the reason (census class, decline counters, the class's first call). + for case, decline in DECLINED: + surface = root / f"{case[0]}.bin" + write_surface(layout_check, case, surface) + bad_declined, _, log = run(root / f"declined_{case[0]}", consumer, backend, case, surface, True) + classes = [line for line in log.splitlines() if line.startswith("x2w-texcensus 2 x ")] + counters = census_line(log, "detile declines of refused texture calls") + first = [line for line in log.splitlines() if "new refusal class" in line] + if (not bad_declined or "x2w-memsrv detiled" in log or not classes or f"detile: {decline}" not in classes[-1] + or f"{decline} 2" not in counters or len(first) != 1 or f"detile: {decline};" not in first[0]): + raise AssertionError(f"{case[0]}: declined control: {bad_declined} mismatches, classes {classes[-1:]}, counters {counters!r}, " + f"first-call lines {first}") + print(f"{backend}: {case[0]}: refused, detile declined ({decline}): {classes[-1].removeprefix('x2w-texcensus ')}") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_mesh_barrier_ranges_check.py b/tests/startup_mesh_barrier_ranges_check.py new file mode 100644 index 0000000000..1420e80fc2 --- /dev/null +++ b/tests/startup_mesh_barrier_ranges_check.py @@ -0,0 +1,76 @@ +"""Check that tools/startup/mesh2hlsl.py runs a group-uniform execz range that holds a phase barrier instead of""" +import os +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 (encoder, prologue, assembler) + +I, ins, exp = E.I, E.ins, E.exp + +PROGRAM = E.PROLOGUE + [ + I('s_mov_b32 s40, 7', 'sop1', 's_mov_b32', d=40, s0='7'), + I('s_mov_b32 s41, 3', 'sop1', 's_mov_b32', d=41, s0='3'), + E.CMPX_N, + ('s_cbranch_execz AFTER', 'execz'), + I('s_mov_b32 s40, 11', 'sop1', 's_mov_b32', d=40, s0='11'), + E.CMPX_T, + ('s_cbranch_execz INNER', 'execz'), + I('s_mov_b32 s41, 13', 'sop1', 's_mov_b32', d=41, s0='13'), + E.V1_9, + ('INNER:', None), + ('AFTER:', None), + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('s_mov_b32 m0, 0x80080', 'sop1', 's_mov_b32', d=124, s0='0x80080'), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + I('v_mov_b32_e32 v4, s40', 'vop1', 'v_mov_b32_e32', d=4, s0='s40'), + I('v_mov_b32_e32 v6, s41', 'vop1', 'v_mov_b32_e32', d=6, s0='s41'), + I('v_cvt_f32_u32_e32 v2, v0', 'vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0'), + I('v_mov_b32_e32 v3, 0', 'vop1', 'v_mov_b32_e32', d=3, s0='0'), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v1, v0, v4, v6', lambda: exp(32, ['v1', 'v0', 'v4', 'v6'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] + + +def translate(path, env): + return E.translate(path, dict({'X2W_MESH_BARRIER_RANGES': '1'}, **env)) + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_barrier_ranges') + os.makedirs(out_dir, exist_ok=True) + code, texts = E.assemble(PROGRAM) + path = os.path.join(out_dir, 'nested.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + E.check('decodes to the intended %d instructions' % len(texts), [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = translate(path, {}) + E.check('translates with the rule on', on.startswith('OK'), on[:300]) + skips = [k for k in range(4) if '(x2w_any[%d][0] | x2w_any[%d][1]) == 0u' % (k, k) in on] + E.check('two group-uniform ranges published', 'x2w_any[1][wave] = 1u' in on and 'x2w_any[2][wave]' not in on, '') + E.check('outer range (k 0, holds the inner publish barrier) is not skipped; inner (k 1) keeps its skip', + skips == [1], 'skip branches for k = %s' % skips) + E.check('s40 restored for a wave with no lane in the outer range', 'x2w_any[0][wave] == 0u) s40 = ' in on, '') + E.check('s41 restored for a wave with no lane in the inner range', 'x2w_any[1][wave] == 0u) s41 = ' in on, '') + off = translate(path, {'X2W_MESH_BARRIER_RANGES': '0'}) + E.check('negative control: X2W_MESH_BARRIER_RANGES=0 refuses again', + # f37ad9f8 refused in barrier_count; since 28020dea (uniform skips over translator barriers) the skip + # check in body() refuses first, because the inner range's publish barrier is not a lane-SCC one + off.startswith(('REFUSED paths cross different numbers of barriers', + 'REFUSED s_barrier inside a group-uniform execz range')), off[:200]) + print('program written to %s (difftest: python -B difftest.py %s --groups 4 --seed 1)' % (path, path)) + if E.failures: + print('%d check(s) failed' % len(E.failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_descword_check.py b/tests/startup_mesh_descword_check.py new file mode 100644 index 0000000000..8a486b3ec2 --- /dev/null +++ b/tests/startup_mesh_descword_check.py @@ -0,0 +1,106 @@ +"""Table descriptor words read as numbers in the mesh-stage translator (mesh2hlsl MeshStage.dw_*, +X2W_MESH_FEATURES=descword; runtime: d3d12_draw.inl `udsrc descword `, X2W_MESH_DESCWORD=1). + +Hand-assembled NGG mesh programs (no cache bytes), RDNA 2 ISA encodings; root parameter 0 is a descriptor table +(s16 = its pointer: the mesh stage's user SGPRs start at s16), parameter 1 a root constant: + + 0x00 s_load_dwordx4 s[20:23], s[16:17], 0x20 a V# from table 0 entry 1 (byte 0x20): s22 = word 2 (NUM_RECORDS) + 0x08 s_waitcnt lgkmcnt(0) + 0x0c s_mul_i32 s24, s22, 3 a number computed from word 2 (byte 0x28) + 0x10 s_lshr_b32 s25, s21, 16 from word 1 (byte 0x24), never read: dead + 0x14 v_cvt_f32_u32 v1, s24 the numeric use; then exp pos0 v1 / prim, s_endpgm + +Checks: + lazy translates; the manifest has `udsrc descword 0 40` and no entry value for byte 36; the HLSL computes + s24 from that entry value (ud * 3) and s25 from 0u + edit 0x0c-0x10 become s_or_b32 s22, s22, 1 (an in-place edit) then s_mul_i32 s24, s22, 3: refused ("edited + descriptor word": the table's word is no longer the register's value); the same with s_or_b32 s22, s22, s17 + (the other operand a root constant) + reload as edit, then the same s_load again before the multiply: translates (a fresh load is the table's word) +Negative control: without X2W_MESH_FEATURES=descword `lazy` is refused ("numeric use of s24 holding descnum"; run in +a child). +""" +import os +import re +import struct +import subprocess +import sys + +if os.environ.get('X2W_DESCWORD_CHILD') != '1': + os.environ['X2W_MESH_FEATURES'] = 'descword' + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import root_blob # noqa: E402 + +LOAD = (0xf4080508, 0xfa000020) # s_load_dwordx4 s[20:23], s[16:17], 0x20 +WAIT = (0xbf8cc07f,) # s_waitcnt lgkmcnt(0) +MUL = (0x93188316,) # s_mul_i32 s24, s22, 3 +DEAD = (0x90199015,) # s_lshr_b32 s25, s21, 16 +EDIT = (0x88168116,) # s_or_b32 s22, s22, 1 +EDIT_UD = (0x88161116,) # s_or_b32 s22, s22, s17 (s17 = the root constant) +USE = (0x7e020c18,) # v_cvt_f32_u32 v1, s24 +TAIL = (0x7e040280, # v_mov_b32 v2, 0 + 0xb07c1003, # s_movk_i32 m0, 0x1003 + 0xbf900009, # s_sendmsg 0x9 + 0xf80008cf, 0x02020201, # exp pos0 v1, v2, v2, v2 done + 0xf8000941, 0x00000002, # exp prim v2 done + 0xbf810000) # s_endpgm + + +def program(*parts): + words = [w for p in parts for w in p] + list(TAIL) + return struct.pack('<%dI' % len(words), *words) + + +LAZY = program(LOAD, WAIT, MUL, DEAD, USE) +EDITED = program(LOAD, WAIT, EDIT, MUL, USE) +EDITED_UD = program(LOAD, WAIT, EDIT_UD, MUL, USE) +RELOAD = program(LOAD, WAIT, EDIT, LOAD, WAIT, MUL, USE) +TEXT = ['s_load_dwordx4 s[20:23], s[16:17], 0x20', 's_waitcnt lgkmcnt(0)', 's_mul_i32 s24, s22, 3', + 's_lshr_b32 s25, s21, 16', 'v_cvt_f32_u32_e32 v1, s24'] + + +def translate(code): + try: + pipe = M.MeshPipeline(code, None, root_blob()) + return pipe.hlsl_ms(), pipe.manifest() + except G.Unsupported as e: + return str(e), None + + +def check(): + text = [x[3] for x in G.decode(LAZY)][:len(TEXT)] + assert text == TEXT, text + assert [x[3] for x in G.decode(EDITED)][2] == 's_or_b32 s22, s22, 1' + hlsl, manifest = translate(LAZY) + assert manifest is not None, ('lazy', hlsl) + used = re.search(r'^udsrc (\d+) descword 0 40$', manifest, re.M) + assert used and not re.search(r'descword 0 36$', manifest, re.M), manifest + assert re.search(r'\bs24 = ud%s \* 0x00000003u;' % used.group(1), hlsl), hlsl + assert re.search(r'\bs25 = 0u >> ', hlsl) and 'X2W_DW' not in hlsl, hlsl + assert [x[3] for x in G.decode(EDITED_UD)][2] == 's_or_b32 s22, s22, s17' + for name, code in (('edit', EDITED), ('edit by a root constant', EDITED_UD)): + got = translate(code) + assert got[1] is None and 'edited descriptor word' in got[0], (name, got[0][:200]) + got = translate(RELOAD) + assert got[1] is not None and re.search(r'^udsrc \d+ descword 0 40$', got[1], re.M), ('reload', got[0][:200]) + return 'word 2 an entry value, dead word 1 0u; in-place edit refused; reload after the edit translates' + + +def main(): + if os.environ.get('X2W_DESCWORD_CHILD') == '1': # child of the negative control: the feature is off + check() + return + summary = check() + env = dict(os.environ, X2W_DESCWORD_CHILD='1', X2W_MESH_FEATURES='') + r = subprocess.run([sys.executable, '-B', os.path.abspath(__file__)], env=env, capture_output=True, text=True) + assert r.returncode != 0 and 'holding descnum' in r.stderr, ('negative control passed', r.stdout, r.stderr) + print('mesh descword: %s; without X2W_MESH_FEATURES=descword refused (%s)' + % (summary, r.stderr.strip().splitlines()[-1][:100])) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_mesh_dispatch.cpp b/tests/startup_mesh_dispatch.cpp new file mode 100644 index 0000000000..51ba5d8c88 --- /dev/null +++ b/tests/startup_mesh_dispatch.cpp @@ -0,0 +1,1299 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "startup_mesh_descword_ms.h" +#include "startup_mesh_heap_ms.h" +#include "startup_mesh_ms.h" +#include "startup_mesh_ps.h" +#include "startup_mesh_smp_ps.h" +#include "startup_mesh_uint_ps.h" +#include "startup_mesh_store_ps.h" +#include "startup_mesh_writer.h" + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) unsigned x2w_d3d12_traced_targets(unsigned* out, unsigned capacity); +extern "C" __declspec(dllimport) int x2w_d3d12_summarise_traced_targets(); +extern "C" __declspec(dllimport) void x2w_d3d12_mesh_stats_report(); +extern "C" __declspec(dllimport) void x2w_d3d12_record_trace_report(); +extern "C" __declspec(dllimport) void x2w_d3d12_mesh_frame_stats_report(); // X2W_MESH_STATS_FRAMES: close the frame, report +extern "C" __declspec(dllimport) void x2w_d3d12_mesh_frame_stats_present(); // X2W_MESH_STATS_FRAMES: what a present does + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e, f); +} +bool ok(Word hr) { return SUCCEEDED(static_cast(hr)); } +std::uint64_t fnv(const void* data, std::size_t bytes, std::uint64_t hash = 1469598103934665603ull) +{ + for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ static_cast(data)[i]) * 1099511628211ull; + return hash; +} +bool write_file(const std::wstring& path, const void* data, std::size_t bytes) +{ + FILE* f = _wfopen(path.c_str(), L"wb"); + if (!f) return false; + const bool written = std::fwrite(data, 1, bytes, f) == bytes; + return std::fclose(f) == 0 && written; +} +std::wstring hex_key(std::uint64_t key) +{ + wchar_t name[24]; + swprintf(name, 24, L"%016llx", static_cast(key)); + return name; +} +// A slot-55 patch record (kind 2 = blend description), as the title passes them. +struct Patch { UINT tag; D3D12_BLEND_DESC blend; }; +static_assert(sizeof(Patch) == 0x14c); + +// Desktop-side work on the test's own queue: clear the depth target, or read a texture back. +struct Observer { + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + UINT64 value = 0; + bool open(ID3D12Device* device) + { + D3D12_COMMAND_QUEUE_DESC desc{}; + return SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue))) && + SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) && + SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list))) && + SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); + } + bool run() + { + if (const HRESULT hr = list->Close(); FAILED(hr)) { + std::printf("observer list Close -> 0x%08lx\n", static_cast(hr)); + return false; + } + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), ++value))) return false; + const auto deadline = GetTickCount64() + 10000; + while (fence->GetCompletedValue() < value) { + if (GetTickCount64() >= deadline) return false; + Sleep(1); + } + return SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.Get(), nullptr)); + } +}; +void barrier(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); +} +// Copies subresource 0 of `texture` (in COMMON) and returns the first 4 bytes of each requested pixel. +bool read_pixels(ID3D12Device* device, Observer& o, ID3D12Resource* texture, bool depth, const std::vector>& at, + std::vector& out) +{ + const D3D12_RESOURCE_DESC desc = texture->GetDesc(); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 total = 0; + device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, total, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + ComPtr readback; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback)))) + return false; + if (depth) barrier(o.list.Get(), texture, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION dst{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION src{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + o.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + if (depth) barrier(o.list.Get(), texture, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + if (!o.run()) return false; + void* mapped = nullptr; + if (FAILED(readback->Map(0, nullptr, &mapped))) return false; + for (const auto& p : at) { + std::uint32_t v = 0; + std::memcpy(&v, static_cast(mapped) + footprint.Footprint.RowPitch * p.second + 4 * p.first, 4); + out.push_back(v); + } + readback->Unmap(0, nullptr); + return true; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) return 2; + const std::string mode = argv[2]; + if (mode != "gpu" && mode != "derived" && mode != "zero" && mode != "huge" && mode != "off" && mode != "missing" && mode != "depth" && + mode != "words16" && mode != "words32" && mode != "wordsraw" && mode != "wordsoob" && mode != "fmaprecise" && mode != "fmabad" && mode != "notargets" && + mode != "rtvuint" && mode != "smpheap" && mode != "smpheapswap" && mode != "statez" && mode != "statezge" && mode != "statezoff" && + mode != "statecull" && mode != "stateculloff" && mode != "statedepth" && mode != "statecullflip" && mode != "statecullnone" && + mode != "statezrepeat" && mode != "statezuncleared" && mode != "statezlateclear" && mode != "async" && mode != "asyncone" && mode != "rtvvariant" && + mode != "uavtex" && mode != "uavtexnoflag" && mode != "rtvnops" && mode != "stateclip" && mode != "stateclipon" && mode != "stateclipkeep" && + mode != "rectrace" && mode != "rectraceapart" && mode != "descword" && mode != "descwordoff") + return 2; + const bool rectrace = mode == "rectrace" || mode == "rectraceapart"; + if (rectrace) SetEnvironmentVariableW(L"X2W_MESH_RECORD_TRACE", L"1"); + // stateclip / stateclipon / stateclipkeep (X2W_DRAW_STATE_DEPTHCLIP, without X2W_MESH_STATE): the triangles at z 1.5, + // beyond the far plane. stateclip: PA_CL_CLIP_CNTL ZCLIP_NEAR + FAR_DISABLE and the switch: depth clip off, drawn. + // stateclipon (control): the same words, switch unset: default depth clip on, dropped. stateclipkeep (control): + // switch set, clip bits clear: the decoded depth clip is on, dropped. + const bool clipmode = mode.compare(0, 9, "stateclip") == 0; + if (mode == "stateclip" || mode == "stateclipkeep") SetEnvironmentVariableW(L"X2W_DRAW_STATE_DEPTHCLIP", L"1"); + // statecullflip: X2W_MESH_STATE_CULL_FLIP=1, the other triangle culled; statecullnone: X2W_MESH_STATE_NOCULL=1, both + // drawn. statezrepeat: 32 calls with render target + depth, then 32 with the render target only: exactly two PSO + // lines (dsv 40, dsv 0), i.e. the calls after the first of each pass take the PSO kept with the binding. + // state modes: the slot-57 record carries a state block A in the mesh layout (A+0x004 = 6, fields 0x54 later). + // statez / statezge / statezoff: render target + D32 depth cleared to 0.5; DB_DEPTH_CONTROL test + write, LESS + // (statez, statezoff) or GEQUAL (statezge); the triangles are at z 0.25. statecull / stateculloff: cull back, the + // right triangle wound the other way. statedepth: the depth-only pipeline, LESS + write over a depth of 1.0. + // X2W_MESH_STATE=1 except in the *off modes. The UNSHIFTED offsets hold contradicting values (ZFUNC NEVER, cull + // front), so a decode that misses the shift fails. + const bool state_mode = mode.compare(0, 5, "state") == 0; + const bool state_on = state_mode && mode != "statezoff" && mode != "stateculloff" && mode.compare(0, 9, "stateclip") != 0; + const bool zmode = mode.compare(0, 6, "statez") == 0; // render target and depth target + const bool cullmode = mode.compare(0, 9, "statecull") == 0; + if (state_on) SetEnvironmentVariableW(L"X2W_MESH_STATE", L"1"); + if (mode == "statecullflip") SetEnvironmentVariableW(L"X2W_MESH_STATE_CULL_FLIP", L"1"); + if (mode == "statecullnone") SetEnvironmentVariableW(L"X2W_MESH_STATE_NOCULL", L"1"); + const bool repeat = mode == "statezrepeat"; + const bool async = mode.compare(0, 5, "async") == 0; + if (async) SetEnvironmentVariableW(L"X2W_MESH_ASYNC", L"1"); + // The depth target of the z modes and statedepth is initialised by a FORWARDED guest clear (list slot 51, + // X2W_DRAW_STATE_DEPTH_CLEAR=1) over a different desktop pre-clear: renderstate 7c0d4cae applies no depth test to a + // target no forwarded clear has marked. statezuncleared (the control): no slot 51 clear, so the decoded LESS test + // and write stay off: drawn, depth unchanged at the pre-clear 0.5. + const bool guest_clear = (mode.compare(0, 6, "statez") == 0 && mode != "statezuncleared") || mode == "statedepth"; + if (guest_clear) SetEnvironmentVariableW(L"X2W_DRAW_STATE_DEPTH_CLEAR", L"1"); + // smpheap / smpheapswap: the pixel stage samples title sampler-heap entry 65 (`smpheap 2048 1 fallback 2047`); + // entry 65 is point and 64 linear (smpheap), or the other way round (smpheapswap, the control). + const bool smp = mode.compare(0, 7, "smpheap") == 0; + const bool depth = mode == "depth" || mode == "statedepth"; // depth-only pipeline, depth target only + const bool no_ps = depth || mode == "rtvnops"; // no pixel stage (rtvnops: with an R32_UINT render target) + const bool words = mode.compare(0, 5, "words") == 0; // heap descriptor + vdesc (`heap 1`, `heapwords 1`) + const bool uavtex = mode.compare(0, 6, "uavtex") == 0; // `uav 0 tex2d table 1 <2 increments>`, PixelStore + const bool descword = mode.compare(0, 8, "descword") == 0; // `udsrc 2 descword 1 8`, MeshDescword + if (mode == "descword") SetEnvironmentVariableW(L"X2W_MESH_DESCWORD", L"1"); + UINT view_increment = 0; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + LARGE_INTEGER driver{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls driver=%u.%u.%u.%u mode=%s\n", adapter_desc.Description, HIWORD(driver.HighPart), LOWORD(driver.HighPart), + HIWORD(driver.LowPart), LOWORD(driver.LowPart), mode.c_str()); + + // Capabilities: mesh shaders (tier 1, shader model 6.5) and existing heaps over process memory (the windows). + // (A probe device only: the stand-in enables the debug layer before it creates its device.) + { + ComPtr desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 4; + D3D12_FEATURE_DATA_D3D12_OPTIONS7 options7{}; + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_5}; + const HRESULT hr7 = desktop->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &options7, sizeof(options7)); + const HRESULT hrm = desktop->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model)); + std::printf("MeshShaderTier %d (0x%08lx), highest shader model 0x%x (0x%08lx)\n", SUCCEEDED(hr7) ? static_cast(options7.MeshShaderTier) : -1, + static_cast(hr7), SUCCEEDED(hrm) ? static_cast(model.HighestShaderModel) : 0u, + static_cast(hrm)); + if (FAILED(hr7) || options7.MeshShaderTier < D3D12_MESH_SHADER_TIER_1 || FAILED(hrm) || model.HighestShaderModel < D3D_SHADER_MODEL_6_5) { + std::printf("no mesh shader support: capability skip\n"); + return 77; + } + void* block = VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + ComPtr heap; + const HRESULT hr = block ? desktop->OpenExistingHeapFromAddress(block, IID_PPV_ARGS(&heap)) : E_OUTOFMEMORY; + heap.Reset(); + if (block) VirtualFree(block, 0, MEM_RELEASE); + if (FAILED(hr)) { + std::printf("OpenExistingHeapFromAddress -> 0x%08lx: capability skip\n", static_cast(hr)); + return 77; + } + view_increment = desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + std::printf("view increment %u\n", view_increment); + } + // `heap 1` draws need the console's 32-byte view slots (d3d12_draw.inl draw_translated); with another increment + // (WARP) the words modes check that the call is skipped as required and then report a capability skip. + const bool words_skip = words && view_increment != 32; + if (no_ps && std::strcmp(argv[1], "warp") == 0) { // depth, statedepth and rtvnops + std::printf("WARP removes the device for a mesh pipeline without a pixel stage: capability skip\n"); + return 77; + } + + // Shader cache and log of this process. + wchar_t temp[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, temp)) return 5; + // Process id + tick count: a reused process id must not find an earlier run's manifest (mode missing failed so). + const std::wstring cache = std::wstring(temp) + L"x2w_mesh_" + std::to_wstring(GetCurrentProcessId()) + L"_" + + std::to_wstring(GetTickCount64()); + CreateDirectoryW(cache.c_str(), nullptr); + SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()); + const std::wstring log_path = cache + L"\\trap.log"; + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + + // The writer: a container compute pipeline, keyed as the stand-in keys slot-62 pipelines. + D3D12_ROOT_PARAMETER writer_params[2]{}; + writer_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + writer_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + writer_params[1].Constants = {1, 0, 4}; + const D3D12_ROOT_SIGNATURE_DESC writer_root_desc{2, writer_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr writer_blob; + if (FAILED(D3D12SerializeRootSignature(&writer_root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &writer_blob, nullptr))) return 5; + if (!write_file(cache + L"\\" + hex_key(fnv(writer_blob->GetBufferPointer(), writer_blob->GetBufferSize(), fnv(startup_mesh_writer, sizeof(startup_mesh_writer)))) + + L".cs.dxbc", startup_mesh_writer, sizeof(startup_mesh_writer))) + return 5; + // rectrace: the cull stand-in's root signature (the writer's two parameters, then a table and two constants): a + // cache file too, so its desktop pipeline exists; the table argument keeps it from running. + D3D12_DESCRIPTOR_RANGE cull_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 8, 0, 0, 0}; + D3D12_ROOT_PARAMETER cull_params[4]{writer_params[0], writer_params[1]}; + cull_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + cull_params[2].DescriptorTable = {1, &cull_range}; + cull_params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + cull_params[3].Constants = {2, 0, 2}; + const D3D12_ROOT_SIGNATURE_DESC cull_root_desc{4, cull_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr cull_blob; + if (rectrace) { + if (FAILED(D3D12SerializeRootSignature(&cull_root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &cull_blob, nullptr))) return 5; + if (!write_file(cache + L"\\" + hex_key(fnv(cull_blob->GetBufferPointer(), cull_blob->GetBufferSize(), fnv(startup_mesh_writer, sizeof(startup_mesh_writer)))) + + L".cs.dxbc", startup_mesh_writer, sizeof(startup_mesh_writer))) + return 5; + } + + // The title's graphics root signature of the mesh record: [0] constants, [1] a table, [2] constants. Its bytes go + // into the key; the translated root signature is built from the manifest. + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 4, 0, 0, 0}; + D3D12_ROOT_PARAMETER title_params[3]{}; + title_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + title_params[0].Constants = {0, 0, 4}; + title_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + title_params[1].DescriptorTable = {1, &range}; + title_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + title_params[2].Constants = {1, 0, 4}; + const D3D12_ROOT_SIGNATURE_DESC title_root_desc{3, title_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr title_blob; + if (FAILED(D3D12SerializeRootSignature(&title_root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &title_blob, nullptr))) return 5; + + // Fake console code blobs (the stand-in only hashes them). + static unsigned char mesh_code[256], pixel_code[128]; + for (int i = 0; i < 256; ++i) mesh_code[i] = static_cast(0xA0 ^ i); + for (int i = 0; i < 128; ++i) pixel_code[i] = static_cast(0x5C ^ (i * 7)); + constexpr char revision[] = "x2w-startup-shader-3"; + std::uint64_t key = fnv(revision, sizeof(revision) - 1); + if (!no_ps) key = fnv(pixel_code, sizeof(pixel_code), key); + key = fnv(mesh_code, sizeof(mesh_code), key); + key = fnv(title_blob->GetBufferPointer(), title_blob->GetBufferSize(), key); + // trace_statez / trace_zero, and dump_statez / dump_zero (X2W_TEST_MESH_DUMP=1, NOT traced: the dump does not need + // the traced frame): X2W_MESH_DUMP_INPUTS lists this key (read by the stand-in at the first mesh call with groups). + char dump_env[8]{}; + const bool dump_test = (mode == "statez" || mode == "zero") && + ((GetEnvironmentVariableA("X2W_D3D12_TRACE_ALL", dump_env, sizeof(dump_env)) && dump_env[0] == '1') || + (GetEnvironmentVariableA("X2W_TEST_MESH_DUMP", dump_env, sizeof(dump_env)) && dump_env[0] == '1')); + { + char key_hex[24]; + if (dump_test) { + std::snprintf(key_hex, sizeof(key_hex), "%016llx", static_cast(key)); + // A list: another key first, then this one (each listed key is dumped once). + SetEnvironmentVariableA("X2W_MESH_DUMP_INPUTS", (std::string("0000000000000001, ") + key_hex).c_str()); + } + } + std::printf("mesh key %016llx\n", static_cast(key)); + if (mode != "missing") { + const std::string fma = mode == "derived" ? "" : mode == "fmaprecise" ? "fma precise\n" : mode == "fmabad" ? "fma fused\n" : "fma exact\n"; + const std::string manifest = + words ? "x2w-manifest 1\nudsrc 0 rect\nudsrc 1 rootconst 2 0\nudsrc 2 rootconst 0 0\nheap 1\nheapwords 1\n" + fma + "stage mesh\nms 3 3 1\n" + // smp: srv 1 is the table's second descriptor (the table offset is in bytes: one view increment). + : smp ? "x2w-manifest 1\nudsrc 0 rect\nudsrc 1 rootconst 2 0\nsrv 0 buf table 1 0\nsrv 1 tex2d table 1 " + std::to_string(view_increment) + + "\nsmpheap 2048 1 fallback 2047\n" + fma + "stage mesh\nms 3 3 1\n" + : uavtex ? "x2w-manifest 1\nudsrc 0 rect\nudsrc 1 rootconst 2 0\nsrv 0 buf table 1 0\nuav 0 tex2d table 1 " + + std::to_string(2 * view_increment) + "\n" + fma + "stage mesh\nms 3 3 1\n" + : descword ? "x2w-manifest 1\nudsrc 0 rect\nudsrc 1 rootconst 2 0\nudsrc 2 descword 1 8\nsrv 0 buf table 1 0\n" + fma + "stage mesh\nms 3 3 1\n" + // statez: entry value 2 = root constant 0.1 (the dump's bit-28 heap reference; MeshMain ignores it). + : "x2w-manifest 1\nudsrc 0 rect\nudsrc 1 rootconst 2 0\n" + std::string(mode == "statez" || rectrace ? "udsrc 2 rootconst 0 1\n" : "") + + "srv 0 buf table 1 0\n" + fma + "stage mesh\nms 3 3 1\n"; + const std::wstring base = cache + L"\\" + hex_key(key); + if (!(words ? write_file(base + L".ms.cso", startup_mesh_heap_ms, sizeof(startup_mesh_heap_ms)) + : descword ? write_file(base + L".ms.cso", startup_mesh_descword_ms, sizeof(startup_mesh_descword_ms)) + : write_file(base + L".ms.cso", startup_mesh_ms, sizeof(startup_mesh_ms))) || + (!no_ps && !(smp ? write_file(base + L".ps.cso", startup_mesh_smp_ps, sizeof(startup_mesh_smp_ps)) + : uavtex ? write_file(base + L".ps.cso", startup_mesh_store_ps, sizeof(startup_mesh_store_ps)) + : write_file(base + L".ps.cso", startup_mesh_ps, sizeof(startup_mesh_ps)))) || + !write_file(base + L".txt", manifest.data(), manifest.size())) + return 5; + } + // RTV variant of the key for an R32_UINT target (the draw path's contract, d3d12_draw.inl translation_for_targets): + // request "rtv1 42", variant key = fnv of the request text. rtvvariant publishes the variant (the same + // mesh stage, PixelUint, the manifest + the rtv1 line); rtvuint (control) publishes none and must find the + // stand-in's request req_.rtv with that text. + const std::string rtv_request = "rtv1 " + std::to_string(key) + " 42"; + const std::uint64_t variant_key = fnv(rtv_request.data(), rtv_request.size()); + if (mode == "rtvvariant") { + const std::string manifest = + "x2w-manifest 1\nudsrc 0 rect\nudsrc 1 rootconst 2 0\nsrv 0 buf table 1 0\nfma exact\nstage mesh\nms 3 3 1\n" + rtv_request + "\n"; + const std::wstring base = cache + L"\\" + hex_key(variant_key); + if (!write_file(base + L".ms.cso", startup_mesh_ms, sizeof(startup_mesh_ms)) || + !write_file(base + L".ps.cso", startup_mesh_uint_ps, sizeof(startup_mesh_uint_ps)) || + !write_file(base + L".txt", manifest.data(), manifest.size())) + return 5; + } + + std::array device_parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), device_parameters.data(), __uuidof(ID3D12Device), &device))) return 6; + ComPtr desktop; // the same device object as the stand-in's (one device per adapter) + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 6; + + void *writer_root = nullptr, *title_root = nullptr, *writer = nullptr, *pipeline = nullptr; + if (!ok(invoke(device, 16, 0, arg(writer_blob->GetBufferPointer()), writer_blob->GetBufferSize(), arg(&__uuidof(ID3D12RootSignature)), arg(&writer_root))) || + !ok(invoke(device, 16, 0, arg(title_blob->GetBufferPointer()), title_blob->GetBufferSize(), arg(&__uuidof(ID3D12RootSignature)), arg(&title_root)))) + return 7; + D3D12_COMPUTE_PIPELINE_STATE_DESC compute{}; + compute.pRootSignature = static_cast(writer_root); + compute.CS = {startup_mesh_writer, sizeof(startup_mesh_writer)}; + if (!ok(invoke(device, 62, arg(&compute), 0, 0, arg(&__uuidof(ID3D12PipelineState)), arg(&writer)))) return 8; + void *cull_root = nullptr, *cull = nullptr; // rectrace: the cull stand-in + if (rectrace) { + if (!ok(invoke(device, 16, 0, arg(cull_blob->GetBufferPointer()), cull_blob->GetBufferSize(), arg(&__uuidof(ID3D12RootSignature)), arg(&cull_root)))) + return 7; + compute.pRootSignature = static_cast(cull_root); + if (!ok(invoke(device, 62, arg(&compute), 0, 0, arg(&__uuidof(ID3D12PipelineState)), arg(&cull)))) return 8; + } + // The slot-57 mesh record. + alignas(8) static unsigned char record[0x300]; + Word record_words[16] = {}; + record_words[0] = arg(title_root); + if (!no_ps) record_words[5] = arg(pixel_code), record_words[6] = sizeof(pixel_code); + record_words[13] = arg(mesh_code), record_words[14] = sizeof(mesh_code); + // state modes: state block A at [1]/[2] (pipeline_state_decode.h read_words; REG_LAYOUT 2a). + alignas(4) static unsigned char state_a[0x180]; + if (state_mode) { + const auto put = [](std::size_t at, std::uint32_t v) { std::memcpy(state_a + at, &v, 4); }; + constexpr std::size_t shift = 0x54; + put(0x004, 6); // mesh layout + put(0x078 + shift, 0xf); // CB_SHADER_MASK: target 0 all channels + put(0x0cc + shift, 0xf); // CB_TARGET_MASK + put(0x0d0 + shift, 0); // CB_BLEND0: blend off + // PA_CL_CLIP_CNTL: depth clip on; stateclip / stateclipon: ZCLIP_NEAR_DISABLE (26) + ZCLIP_FAR_DISABLE (27). + put(0x09c + shift, mode == "stateclip" || mode == "stateclipon" ? 0x0c000000u : 0u); + put(0x09c, mode == "stateclipkeep" ? 0x0c000000u : 0u); // unshifted: the opposite (a missed shift fails) + // DB_DEPTH_CONTROL: Z_ENABLE (1) | Z_WRITE_ENABLE (2) | ZFUNC (4-6): 1 LESS, 6 GEQUAL; none in the cull / clip modes. + put(0x0b8 + shift, cullmode || clipmode ? 0u : 0x2u | 0x4u | ((mode == "statezge" ? 6u : 1u) << 4)); + put(0x0a0 + shift, cullmode ? 0x2u : 0u); // PA_SU_SC_MODE_CNTL: CULL_BACK (bit 1), FACE 0 + put(0x0b8, 0x2u); // unshifted: Z on, ZFUNC NEVER (a missed shift draws nothing) + put(0x0a0, 0x1u); // unshifted: cull front + record_words[1] = arg(state_a), record_words[2] = sizeof(state_a); + } + std::memcpy(record, record_words, sizeof(record_words)); + if (!ok(invoke(device, 57, arg(record), arg(&__uuidof(ID3D12PipelineState)), arg(&pipeline)))) return 8; + if (mode == "derived") { + Patch patch{2}; + for (auto& t : patch.blend.RenderTarget) + t = {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}; + void* derived = nullptr; + if (!ok(invoke(device, 55, arg(pipeline), 1, arg(&patch), arg(&__uuidof(ID3D12PipelineState)), arg(&derived))) || !derived) return 8; + pipeline = derived; + } + D3D12_INDIRECT_ARGUMENT_DESC argument{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; + const D3D12_COMMAND_SIGNATURE_DESC signature_desc{12, 1, &argument, 0}; + void* signature = nullptr; + if (!ok(invoke(device, 41, arg(&signature_desc), 0, arg(&__uuidof(ID3D12CommandSignature)), arg(&signature)))) return 9; + + // Title memory: arguments at +0x1c20 (not 64 KiB-aligned: a private copy backs the wrapper), vertices at +0x30000. + auto* memory = static_cast(VirtualAlloc(nullptr, 2u << 20, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!memory) return 10; + unsigned char* const args_memory = memory + 0x1c20; + // zero: X = 0 already at record time (the X2W_MESH_DUMP_INPUTS control: a call without groups is not dumped). + const std::uint32_t sentinel[3] = {mode == "zero" ? 0u : 1u, 1, 1}; + std::memcpy(args_memory, sentinel, 12); + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 64, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + void* args = nullptr; + if (!ok(invoke(device, 133, arg(args_memory), arg(&buffer), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&args)))) return 11; + // Group 0: a triangle over the left half; group 1: over the right half (clip space). + const float vertices[12] = {-0.9f, -0.9f, -0.9f, 0.9f, -0.1f, 0.0f, 0.1f, 0.0f, 0.9f, 0.9f, 0.9f, -0.9f}; + unsigned char* const vertex_memory = memory + 0x30000; + std::memcpy(vertex_memory, vertices, sizeof(vertices)); + if (cullmode) { // the right triangle's last two vertices swapped: the other winding + const float swapped[4] = {0.9f, -0.9f, 0.9f, 0.9f}; + std::memcpy(vertex_memory + 32, swapped, sizeof(swapped)); + } + if (mode == "words16") { // the same positions as half2 (all exactly representable: +-0.875, +-0.125, 0) + const float halves[12] = {-0.875f, -0.875f, -0.875f, 0.875f, -0.125f, 0.0f, 0.125f, 0.0f, 0.875f, 0.875f, 0.875f, -0.875f}; + std::uint16_t packed[12]; + for (int i = 0; i < 12; ++i) { + std::uint32_t b = 0; + std::memcpy(&b, &halves[i], 4); + packed[i] = halves[i] == 0.0f ? 0 : static_cast(((b >> 16) & 0x8000) | ((((b >> 23) & 0xff) - 112) << 10) | ((b >> 13) & 0x3ff)); + } + std::memcpy(vertex_memory, packed, sizeof(packed)); + } + + // Targets: a desktop texture with a view made through the stand-in (as the title's views are wrapped). + constexpr UINT size = 32; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr target; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } target_heap_desc{{depth ? D3D12_DESCRIPTOR_HEAP_TYPE_DSV : D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}; + void* target_heap = nullptr; + if (!ok(invoke(device, 14, arg(&target_heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&target_heap)))) return 12; + const Word target_handle = invoke(target_heap, 9); + Observer observer; + if (!observer.open(desktop.Get())) return 12; + // A D32 depth texture with a view made through the stand-in at `handle`, cleared to `value` on the test's own + // queue (the stand-in drops depth clears by default). + const auto make_depth = [&](ComPtr& texture, Word handle, float value) { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, size, size, 1, 1, DXGI_FORMAT_D32_FLOAT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}; + const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_D32_FLOAT, {value, 0}}; + if (FAILED(desktop->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, &clear, + IID_PPV_ARGS(&texture)))) return false; + D3D12_DEPTH_STENCIL_VIEW_DESC view{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D}; + invoke(device, 21, arg(texture.Get()), arg(&view), handle); + ComPtr own_dsv; + const D3D12_DESCRIPTOR_HEAP_DESC own_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; + if (FAILED(desktop->CreateDescriptorHeap(&own_desc, IID_PPV_ARGS(&own_dsv)))) return false; + desktop->CreateDepthStencilView(texture.Get(), &view, own_dsv->GetCPUDescriptorHandleForHeapStart()); + barrier(observer.list.Get(), texture.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE); + observer.list->ClearDepthStencilView(own_dsv->GetCPUDescriptorHandleForHeapStart(), D3D12_CLEAR_FLAG_DEPTH, value, 0, 0, nullptr); + barrier(observer.list.Get(), texture.Get(), D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COMMON); + return observer.run(); + }; + // z modes: a depth target next to the render target, cleared to 0.5. + ComPtr depth_target; + Word depth_handle = 0; + if (zmode) { + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } dsv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}, 0, 0}; + void* dsv_heap = nullptr; + if (!ok(invoke(device, 14, arg(&dsv_heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&dsv_heap)))) return 12; + depth_handle = invoke(dsv_heap, 9); + if (!make_depth(depth_target, depth_handle, guest_clear ? 0.0f : 0.5f)) return 12; // guest clear: slot 51 sets 0.5 + } + if (depth) { + if (!make_depth(target, target_handle, guest_clear ? 0.0f : 1.0f)) return 12; // statedepth: slot 51 sets 1.0 + } else { + // rtvuint: an integer target (R32_UINT, 4 bytes per pixel like RGBA8): the call must be refused ("rtv variant"). + const DXGI_FORMAT format = mode == "rtvuint" || mode == "rtvvariant" || mode == "rtvnops" ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R8G8B8A8_UNORM; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, size, size, 1, 1, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE clear{format, {0, 0, 0, 0}}; + if (FAILED(desktop->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, &clear, + IID_PPV_ARGS(&target)))) return 12; + D3D12_RENDER_TARGET_VIEW_DESC view{format, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + invoke(device, 20, arg(target.Get()), arg(&view), target_handle); + } + // The view heap with one hardware buffer descriptor: base, stride 0, 48 records (bytes), over the vertices. + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } view_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, rectrace ? 8u : 4u, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + mode == "wordsoob" ? arg(memory + 0x60000) : Word{0}, mode == "wordsoob" ? Word{4 * 32} : Word{0}}; + void* view_heap = nullptr; + if (!ok(invoke(device, 14, arg(&view_heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&view_heap)))) return 12; + const Word view_cpu = invoke(view_heap, 9), view_gpu = invoke(view_heap, 10); + if (!view_cpu || !view_gpu) return 12; + const Word vertex_address = arg(vertex_memory); + const std::uint32_t descriptor[8] = {static_cast(vertex_address), static_cast(vertex_address >> 32) & 0xffff, + sizeof(vertices), 0}; + std::memcpy(reinterpret_cast(view_cpu), descriptor, sizeof(descriptor)); + // words modes: a title buffer view in heap slot 2 (the stand-in writes its view token there), over a placed + // buffer on the vertices: 16_16_FLOAT (words16), 32_32_FLOAT (words32) or raw (wordsraw: no typed format). + constexpr std::uint32_t heap_slot = 2; + // wordsoob: the shader indexes slot 4, one past the 4-slot heap, where the test copied slot 2's token and id. + const std::uint32_t shader_slot = mode == "wordsoob" ? 4u : heap_slot; + void* vertex_buffer = nullptr; + if (words) { + D3D12_RESOURCE_DESC vb{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + D3D12_RESOURCE_FLAG_NONE}; + if (!ok(invoke(device, 133, arg(vertex_memory), arg(&vb), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&vertex_buffer)))) + return 12; + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Format = mode == "words16" ? DXGI_FORMAT_R16G16_FLOAT : mode == "words32" || mode == "wordsoob" ? DXGI_FORMAT_R32G32_FLOAT : DXGI_FORMAT_R32_TYPELESS; + view.Buffer.NumElements = mode == "wordsraw" ? 12 : 6; + view.Buffer.Flags = mode == "wordsraw" ? D3D12_BUFFER_SRV_FLAG_RAW : D3D12_BUFFER_SRV_FLAG_NONE; + invoke(device, 18, arg(vertex_buffer), arg(&view), view_cpu + 32 * heap_slot); + std::uint32_t token[2] = {}; + std::memcpy(token, reinterpret_cast(view_cpu + 32 * heap_slot), 8); + if (mode == "wordsoob") std::memcpy(reinterpret_cast(view_cpu + 32 * 4), reinterpret_cast(view_cpu + 32 * heap_slot), 32); + std::printf("heap slot %u: %08x %08x (view token X2WV = 56573258 + view id)\n", heap_slot, token[0], token[1]); + } + // smp modes: a 2x1 RGBA8 texture placed on title memory (the stand-in backs it with a desktop texture and uploads + // it from that memory at the draw; texel 0 red, texel 1 blue), its SRV at the table's second descriptor, and a + // shader-visible title sampler heap of 128 raw 16-byte S# entries: 64 and 65 clamp, one point, one linear. + void *smp_texture = nullptr, *sampler_heap = nullptr; + if (smp) { + const std::uint32_t texels[2] = {0xff0000ffu, 0xffff0000u}; + std::memcpy(memory + 0x40000, texels, sizeof(texels)); + D3D12_RESOURCE_DESC tex{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 2, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + D3D12_RESOURCE_FLAG_NONE}; + if (!ok(invoke(device, 133, arg(memory + 0x40000), arg(&tex), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), + arg(&smp_texture)))) + return 12; + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Texture2D.MipLevels = 1; + invoke(device, 18, arg(smp_texture), arg(&view), view_cpu + view_increment); + constexpr UINT sampler_count = 128; + static std::uint32_t sampler_words[sampler_count][4]; + const std::uint32_t clamp = 2u | (2u << 3) | (2u << 6); + const auto filter = [](std::uint32_t f) { return (f << 20) | (f << 22); }; // mag, min; 0 point, 1 linear + sampler_words[64][0] = sampler_words[65][0] = clamp; + sampler_words[65][2] = filter(mode == "smpheap" ? 0 : 1); + sampler_words[64][2] = filter(mode == "smpheap" ? 1 : 0); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } sampler_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, sampler_count, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + arg(sampler_words), sizeof(sampler_words)}; + if (!ok(invoke(device, 14, arg(&sampler_heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&sampler_heap)))) return 12; + } + // uavtex modes: a 32x32 RGBA8 texture placed on title memory at the table's third descriptor. uavtex: the texture + // allows unordered access and has an RGBA8 UAV (slot 19); uavtexnoflag (control): no unordered access, an SRV there. + void* uav_texture = nullptr; + if (uavtex) { + const bool flag = mode == "uavtex"; + D3D12_RESOURCE_DESC tex{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 32, 32, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + flag ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE}; + if (!ok(invoke(device, 133, arg(memory + 0x50000), arg(&tex), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), + arg(&uav_texture)))) + return 12; + if (flag) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(device, 19, arg(uav_texture), 0, arg(&view), view_cpu + 2 * view_increment); + } else { + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Texture2D.MipLevels = 1; + invoke(device, 18, arg(uav_texture), arg(&view), view_cpu + 2 * view_increment); + } + } + // rectrace: heap slots 1-4 (see the mode comment at the top of main). + void* trace_texture = nullptr; + unsigned char* const trace_texels = memory + 0x40000; // 256-byte aligned: a T# base + unsigned char* const other_memory = memory + 0x70000; + if (rectrace) { + const std::uint32_t texels[2] = {0xff0000ffu, 0xffff0000u}; + std::memcpy(trace_texels, texels, sizeof(texels)); + D3D12_RESOURCE_DESC tex{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 2, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + if (!ok(invoke(device, 133, arg(trace_texels), arg(&tex), D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&trace_texture)))) + return 12; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + invoke(device, 18, arg(trace_texture), arg(&srv), view_cpu + view_increment); + // A raw T# (gfx10 SQ_IMG_RSRC words): base >> 8, FORMAT 56, WIDTH 2, HEIGHT 1, TYPE 9 (2D), levels 0-0. + const Word base = arg(trace_texels) >> 8; + const std::uint32_t tsharp[8] = {static_cast(base), (static_cast(base >> 32) & 0xff) | (56u << 20) | (1u << 30), 0, 9u << 28}; + std::memcpy(reinterpret_cast(view_cpu + 2 * view_increment), tsharp, sizeof(tsharp)); + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(device, 19, arg(trace_texture), 0, arg(&uav), view_cpu + 3 * view_increment); + const Word other = arg(other_memory); + const std::uint32_t vsharp[8] = {static_cast(other), static_cast(other >> 32) & 0xffff, 64, 0}; + std::memcpy(reinterpret_cast(view_cpu + 4 * view_increment), vsharp, sizeof(vsharp)); + const std::uint32_t integer[8] = {5}; // slot 5: "integer + 7 zero words" (neither buffer nor image: an `other` line) + std::memcpy(reinterpret_cast(view_cpu + 5 * view_increment), integer, sizeof(integer)); + } + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *queue = nullptr, *fence = nullptr, *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 13; + + const std::uint32_t x = mode == "zero" ? 0u : mode == "huge" ? 70000u : 2u; + const std::uint32_t record_values[4] = {x, 1, 1, 0}; + const std::uint32_t colour = clipmode ? 0x01ff40c0u : 0x00ff40c0u; // R c0, G 40, B ff; bit 24: z 1.5 (MeshMain) + const float clear_colour[4] = {0, 0, 0, 0}; + invoke(list, 139, arg(allocator)); // Reset + invoke(list, 33, arg(writer_root)); // SetComputeRootSignature + invoke(list, 25, arg(writer)); // SetPipelineState (writer) + invoke(list, 45, 0, arg(args_memory)); // SetComputeRootUnorderedAccessView(0, title address) + invoke(list, 39, 1, 4, arg(record_values), 0); // SetComputeRoot32BitConstants(1, 4, record, 0) + invoke(list, 14, 1, 1, 1); // Dispatch: the writer stores {x, 1, 1} + if (rectrace) { // the cull stand-in, twice (skipped: c62 table argument) + const std::uint32_t far_values[4] = {0x100, 0x100, 0x100, 0x100}; // over the heap's 8 slots: no heap index + const std::uint32_t heap_index[2] = {mode == "rectrace" ? 0u : 4u, 0x100}; + void* const cull_heaps[1] = {view_heap}; + invoke(list, 33, arg(cull_root)); + invoke(list, 25, arg(cull)); + invoke(list, 32, 1, arg(cull_heaps)); // SetDescriptorHeaps + invoke(list, 45, 0, arg(memory + 0x80000)); // root UAV past the vertices and slot 4's memory + invoke(list, 39, 1, 4, arg(far_values), 0); + invoke(list, 35, 2, view_gpu + (mode == "rectrace" ? 0 : view_increment)); // SetComputeRootDescriptorTable(2, slot 0 / 1) + invoke(list, 39, 3, 2, arg(heap_index), 0); + invoke(list, 14, 1, 1, 1); + invoke(list, 14, 1, 1, 1); + } + if (depth) { + invoke(list, 50, 0, 0, 0, arg(&target_handle)); // OMSetRenderTargets(0, null, FALSE, &dsv) + } else { + invoke(list, 52, target_handle, arg(clear_colour)); // ClearRenderTargetView + if (zmode) invoke(list, 50, 1, arg(&target_handle), 0, arg(&depth_handle)); // OMSetRenderTargets(1, &rtv, FALSE, &dsv) + else if (mode != "notargets") invoke(list, 50, 1, arg(&target_handle)); // OMSetRenderTargets(1, &rtv); notargets: none + } + const bool late_clear = mode == "statezlateclear"; + const auto slot51_clear = [&] { + // List slot 51 ClearDepthStencilView, typed (the depth value is a float argument in xmm3, which invoke cannot pass). + using ClearDepth = void(WINAPI*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, FLOAT, UINT8, UINT, const D3D12_RECT*); + const D3D12_CPU_DESCRIPTOR_HANDLE dsv{static_cast(depth ? target_handle : depth_handle)}; + reinterpret_cast((*static_cast(list))[51])(list, dsv, D3D12_CLEAR_FLAG_DEPTH, depth ? 1.0f : 0.5f, 0, 0, nullptr); + }; + if (guest_clear && !late_clear) slot51_clear(); + const D3D12_VIEWPORT viewport{0, 0, static_cast(size), static_cast(size), 0, 1}; + const D3D12_RECT scissor{0, 0, static_cast(size), static_cast(size)}; + invoke(list, 21, 1, arg(&viewport)); + invoke(list, 22, 1, arg(&scissor)); + invoke(list, 34, arg(title_root)); // SetGraphicsRootSignature + void* const heaps[2] = {view_heap, sampler_heap}; + invoke(list, 32, smp ? 2 : 1, arg(heaps)); // SetDescriptorHeaps (smp: and the sampler heap) + invoke(list, 36, 1, view_gpu); // SetGraphicsRootDescriptorTable(1, heap start) + invoke(list, 40, 2, 1, arg(&colour), 0); // SetGraphicsRoot32BitConstants(2, 1, &colour, 0) + if (words) invoke(list, 40, 0, 1, arg(&shader_slot), 0); // SetGraphicsRoot32BitConstants(0, 1, &slot, 0): entry value 2 + // statez: root constant [0][1] (read by the translation) = bit 28 + heap index 0 (srv 0's view, the vertices): the + // dump's heap buffer case. [0][2] = bit 28 + index 3 is NOT read by the translation (the control): no heap3 files. + const std::uint32_t heap_reference[2] = {0x10000000u, 0x10000003u}; + if (mode == "statez" || rectrace) invoke(list, 40, 0, 2, arg(heap_reference), 1); // SetGraphicsRoot32BitConstants(0, 2, refs, 1) + invoke(list, 25, arg(pipeline)); // SetPipelineState (the mesh pipeline) + invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); // ExecuteIndirect(mesh signature, 1, args, 0) + if (mode == "async") { + bool compiled = false; + for (const auto until = GetTickCount64() + 20000; !compiled && GetTickCount64() < until; Sleep(10)) { + std::ifstream f(log_path, std::ios::binary); + const std::string text{std::istreambuf_iterator(f), {}}; + compiled = text.find("compiled in ") != std::string::npos && text.find("(X2W_MESH_ASYNC worker)") != std::string::npos; + } + std::printf("async: worker PSO line seen before the second call: %d\n", compiled); + invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); + } + if (late_clear) { // the first call ran against the uncleared target (depth off); now the clear, then a second call + slot51_clear(); + invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); + } + if (repeat) { + for (int i = 1; i < 32; ++i) invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); + invoke(list, 50, 1, arg(&target_handle)); // OMSetRenderTargets(1, &rtv): no depth view + for (int i = 0; i < 32; ++i) invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); + } + invoke(list, 9); // Close + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), 1))) return 14; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < 1) { + if (GetTickCount64() >= deadline) return 14; + Sleep(1); + } + + std::uint32_t stored[3]; + std::memcpy(stored, args_memory, 12); + std::printf("record in title memory: {%u %u %u} (writer stored {%u 1 1})\n", stored[0], stored[1], stored[2], x); + std::vector pixels; + const std::vector> at = {{8, 16}, {24, 16}, {16, 2}}; // left triangle, right triangle, outside both + if (!read_pixels(desktop.Get(), observer, target.Get(), depth, at, pixels)) { + ComPtr messages; + if (SUCCEEDED(desktop.As(&messages))) + for (UINT64 i = 0; i < messages->GetNumStoredMessages(); ++i) { + SIZE_T bytes = 0; + messages->GetMessage(i, nullptr, &bytes); + std::vector storage(bytes); + auto* message = reinterpret_cast(storage.data()); + if (bytes && SUCCEEDED(messages->GetMessage(i, message, &bytes))) std::printf("debug: %s\n", message->pDescription); + } + return 15; + } + int failures = 0; + if (stored[0] != x || stored[1] != 1 || stored[2] != 1) { + std::printf("the record in title memory is not what the writer stored\n"); + ++failures; + } + const bool drawn_expected = mode == "gpu" || mode == "derived" || mode == "fmaprecise" || smp || mode == "statez" || mode == "statezoff" || + mode == "stateculloff" || mode == "statecullnone" || mode == "stateclip" || repeat || mode == "statezuncleared" || mode == "statezlateclear" || mode == "async" || mode == "rtvvariant" || mode == "uavtex" || rectrace || (!words_skip && (mode == "words16" || mode == "words32")) || mode == "descword"; + // RGBA8 little-endian: R c0, G 40, B ff, A ff. words modes: G = the FORMAT code in vdesc word 3 (29 = 0x1d, 64 = 0x40). + // smpheap: entry 65 point -> texel 0 (red ff0000ff); smpheapswap: entry 65 linear at u = 0.375 -> 0.75 red + 0.25 + // blue (R bf, B 40, A ff; filtering precision allows +-3 per channel). + // descword: G = the descriptor's NUM_RECORDS low byte (48 = 0x30). + const std::uint32_t drawn = mode == "rtvvariant" ? 0x00ff40c0u : mode == "words16" ? 0xffff1dc0u : mode == "descword" ? 0xffff30c0u : mode == "smpheap" ? 0xff0000ffu : mode == "smpheapswap" ? 0xff4000bfu : 0xffff40c0u; + const auto matches = [&](std::uint32_t got, std::uint32_t want) { + if (mode != "smpheapswap" || !want) return got == want; + for (int s = 0; s < 32; s += 8) { + const int d = static_cast((got >> s) & 255) - static_cast((want >> s) & 255); + if (d < -3 || d > 3) return false; + } + return true; + }; + // Depth values: left, right, outside, against what the mode wants (statez / statedepth: the triangles wrote 0.25). + const auto check_depth = [&](const float (&values)[3], float cleared, bool written) { + const float want = written ? 0.25f : cleared; + const bool good = std::fabs(values[0] - want) < 1e-4f && std::fabs(values[1] - want) < 1e-4f && values[2] == cleared; + std::printf("depth: left %g right %g outside %g (cleared %g; want %g under the triangles)\n", values[0], values[1], values[2], cleared, want); + if (!good) { + std::printf("FAIL: depth values do not match mode %s\n", mode.c_str()); + ++failures; + } + }; + if (depth) { + float values[3]; + std::memcpy(values, pixels.data(), sizeof(values)); + if (mode == "statedepth") check_depth(values, 1.0f, true); + else std::printf("depth: left %g right %g outside %g (cleared 1; the default state has depth off, so not checked)\n", values[0], + values[1], values[2]); + } else { + std::printf("pixels: left %08x right %08x outside %08x (drawn = %08x, cleared = 00000000)\n", pixels[0], pixels[1], pixels[2], drawn); + const std::uint32_t want = drawn_expected ? drawn : 0u; + const std::uint32_t want_right = mode == "statecull" ? drawn : mode == "statecullflip" ? 0u : want; + const std::uint32_t want_left = mode == "statecull" ? 0u : mode == "statecullflip" ? drawn : want; + if (!matches(pixels[0], want_left) || !matches(pixels[1], want_right) || pixels[2] != 0) { + std::printf("FAIL: expected left %08x right %08x, outside 00000000\n", want_left, want_right); + ++failures; + } + } + if (zmode) { + std::vector depth_words; + if (!read_pixels(desktop.Get(), observer, depth_target.Get(), true, at, depth_words)) return 15; + float values[3]; + std::memcpy(values, depth_words.data(), sizeof(values)); + check_depth(values, 0.5f, mode == "statez" || repeat || late_clear); + } + + // The log: the per-key lines and the debug layer. + std::ifstream log_file(log_path, std::ios::binary); + const std::string log{std::istreambuf_iterator(log_file), {}}; + char key_text[24]; + std::snprintf(key_text, sizeof(key_text), "%016llx", static_cast(key)); + const auto has = [&](const std::string& text) { return log.find(text) != std::string::npos; }; + const bool issued = has(std::string("x2w-mesh pipeline ") + key_text + ": first call issued"); + const bool missing = has(std::string("x2w-mesh pipeline ") + key_text + ": no translation"); + const bool any_mesh = has("x2w-mesh "); + std::string bound_line; + if (const std::size_t p = log.find(std::string("x2w-mesh key ") + key_text + " first bound frame "); p != std::string::npos) + bound_line = log.substr(p, log.find('\n', p) - p); + const bool bound_ok = bound_line.find(mode == "missing" ? "(cache: missing)" : mode == "fmabad" ? "(cache: fail)" : "(cache: ok)") != std::string::npos; + // Refusal modes: the once-per-key reason line (d3d12_mesh.inl mesh_refusal_line / load_mesh_stages). + const std::string pipeline_line = std::string("x2w-mesh pipeline ") + key_text + ": "; + const bool refusal_mode = mode == "fmabad" || mode == "notargets" || mode == "rtvuint" || mode == "uavtexnoflag"; + const std::string reason = mode == "fmabad" ? "translation failed (unknown fma rule \"fused\")" + : mode == "notargets" ? "call refused (no targets: " + : mode == "rtvuint" ? "call refused (rtv variant: target formats 42;" + : mode == "uavtexnoflag" ? "call refused (bind refused by draw_translated" + : ""; + const bool reason_ok = refusal_mode && has(pipeline_line + reason); + if (refusal_mode) std::printf("log: refusal line \"%s%s\" %d\n", pipeline_line.c_str(), reason.c_str(), reason_ok); + // The fma rule each loaded translation reports, and the capability line for exact / unstated. + const char* fma_rule = mode == "derived" ? "fma unstated" : mode == "fmaprecise" ? "fma precise" : "fma exact"; + const bool fma_checked = mode != "off" && mode != "missing" && mode != "fmabad" && mode != "descwordoff"; + const bool fma_ok = !fma_checked || (has(std::string(", ") + fma_rule) && (mode == "fmaprecise" || has("x2w-mesh DoublePrecisionFloatShaderOps 1 "))); + if (fma_checked) std::printf("log: mesh stage line ends \"%s\" and capability line as required: %d\n", fma_rule, fma_ok); + if (!fma_ok) { + std::printf("FAIL: the fma lines do not match mode %s\n", mode.c_str()); + ++failures; + } + std::printf("log: issued %d, no translation %d, any x2w-mesh line %d, first bound line \"%s\"\n", issued, missing, any_mesh, + bound_line.c_str()); + int async_pso_lines = 0; + for (std::size_t p = log.find("x2w-mesh desktop pipeline for "); p != std::string::npos; p = log.find("x2w-mesh desktop pipeline for ", p + 1)) ++async_pso_lines; + if (async) std::printf("log: async PSO lines %d\n", async_pso_lines); + // RTV variants (R32_UINT target): rtvvariant finds the variant translation (key fnv("rtv1 42")) and builds the + // PSO from it; the rtvuint control has none, so the call is refused and req_.rtv carries the request. + char variant_text[24]; + std::snprintf(variant_text, sizeof(variant_text), "%016llx", static_cast(variant_key)); + if (mode == "rtvvariant") { + const bool variant_line = has(std::string("x2w-mesh pipeline ") + key_text + ": RTV variant " + variant_text + " for target formats 42 (pixel stage yes)"); + const bool variant_pso = has(std::string("x2w-mesh desktop pipeline for ") + variant_text + ": 1 targets (format 42)"); + const bool refused = has(std::string("x2w-mesh pipeline ") + key_text + ": call refused"); + std::printf("log: RTV variant line %d, PSO from the variant %d, refusal line %d\n", variant_line, variant_pso, refused); + if (!variant_line || !variant_pso || refused) { + std::printf("FAIL: the RTV variant lines do not match\n"); + ++failures; + } + } + if (mode == "rtvnops") { // no variant asked for, no refusal: the call is issued with the base + const bool req = GetFileAttributesW((cache + L"\\req_" + hex_key(variant_key) + L".rtv").c_str()) != INVALID_FILE_ATTRIBUTES; + const bool refused = has(std::string("x2w-mesh pipeline ") + key_text + ": call refused"); + std::printf("log: req_%s.rtv exists %d, refusal line %d\n", variant_text, req, refused); + if (req || refused) { + std::printf("FAIL: a depth-only pipeline asked for an RTV variant\n"); + ++failures; + } + } + if (mode == "rtvuint") { + std::ifstream req_file(cache + L"\\req_" + hex_key(variant_key) + L".rtv", std::ios::binary); + std::string req{std::istreambuf_iterator(req_file), {}}; + while (!req.empty() && (req.back() == '\n' || req.back() == '\r')) req.pop_back(); + std::printf("log: req_%s.rtv \"%s\" (want \"%s\")\n", variant_text, req.c_str(), rtv_request.c_str()); + if (req != rtv_request) { + std::printf("FAIL: the RTV variant request was not published\n"); + ++failures; + } + } + // uavtex: the translation has the uav table and the call binds the texture UAV (RGBA8 = format 28, mip 0); + // uavtexnoflag: the same line over a texture without unordered access skips the call. + if (uavtex) { + const bool table_line = has(std::string("x2w-draw-rt pipeline ") + key_text + ": 1 uavs in root parameter "); + const bool bound_uav = has(std::string("x2w-draw-rt ") + key_text + " uav 0 texture: ") && has("format 28 mip 0: bound"); + const bool skipped_uav = has(std::string("x2w-draw-rt ") + key_text + ": draw skipped: texture uav: texture without ALLOW_UNORDERED_ACCESS"); + std::printf("log: uav table line %d, texture uav bound %d, skipped (no unordered access) %d\n", table_line, bound_uav, skipped_uav); + if (!table_line || bound_uav != (mode == "uavtex") || skipped_uav != (mode == "uavtexnoflag")) { + std::printf("FAIL: the texture uav lines do not match mode %s\n", mode.c_str()); + ++failures; + } + } + const bool skipped_32 = has(std::string("x2w-draw-rt ") + key_text + ": heap draw skipped: descriptor increment is not 32"); + if (words && !words_skip) { // the heap views are bounded: heapmem = the 4-slot title heap (128 bytes) + const bool bounded = has(std::string("x2w-draw-rt ") + key_text + ": bounded heap views: heapmem 128 bytes (title heap 128), vinfo "); + std::printf("log: bounded heap views line (heapmem 128 bytes) %d\n", bounded); + if (!bounded) { + std::printf("FAIL: no bounded heap views line for the key\n"); + ++failures; + } + } + if (words_skip) std::printf("log: heap draw skipped (increment not 32) %d\n", skipped_32); + // descword: the entry value is the title's own dword 2 of table 1 entry 0 (48); descwordoff: the translation refused. + const bool descword_value_line = has(std::string("x2w-draw-rt ") + key_text + " descword 1 8: entry 0x") && has("title word = 0x00000030"); + const bool descword_refused = has(std::string("x2w-draw ") + key_text + ": `udsrc 2 descword 1 8` needs X2W_MESH_DESCWORD=1: translation refused"); + if (descword) { + std::printf("log: descword value line (title word 0x30) %d, refused without the switch %d\n", descword_value_line, descword_refused); + if (descword_value_line != (mode == "descword") || descword_refused != (mode == "descwordoff")) { + std::printf("FAIL: the descword lines do not match mode %s\n", mode.c_str()); + ++failures; + } + } + if (mode == "off" ? any_mesh + : mode == "descwordoff" ? issued + : mode == "missing" ? (!missing || issued || !bound_ok) + : refusal_mode ? (issued || !bound_ok || !reason_ok) + : words_skip ? (issued || !bound_ok || !skipped_32) + : async ? (issued != (mode == "async") || !bound_ok || (mode == "async" && (!has("(X2W_MESH_ASYNC worker)") || async_pso_lines != 1)) || + !has("x2w-mesh X2W_MESH_ASYNC=1: ")) + : (!issued || !bound_ok)) { + std::printf("FAIL: the x2w-mesh lines do not match mode %s\n", mode.c_str()); + ++failures; + } + if (smp) { // the translated sampler heap was built from the title's 128 entries (bound: none unbound) + std::string sampler_line; + if (const std::size_t p = log.find("x2w-draw sampler heap: "); p != std::string::npos) sampler_line = log.substr(p, log.find('\n', p) - p); + std::printf("log: sampler heap line \"%s\"\n", sampler_line.c_str()); + if (sampler_line.find("null_sampler_unbound=0 ") == std::string::npos || sampler_line.find("null_sampler_unreadable=0 ") == std::string::npos) { + std::printf("FAIL: the sampler heap was not built from the title's sampler heap\n"); + ++failures; + } + } + if (state_mode) { // the PSO line says which state it was made with; the switch line only with X2W_MESH_STATE=1 + const bool switch_line = has("x2w-mesh X2W_MESH_STATE=1: "); + const bool decoded_line = has(std::string("x2w-mesh desktop pipeline for ") + key_text) && has("; state decoded (X2W_MESH_STATE)"); + // The clip modes: the PSO line says depth clip alone was decoded (stateclip: off; stateclipkeep: on = the + // default, so no change and a "default" PSO), and the switch line exists when the switch is set. + const bool clip_line = has("; state default + depth clip decoded (X2W_DRAW_STATE_DEPTHCLIP): ") && + has(", cull 1 ccw 0 depthclip 0, "); + const bool clip_switch_line = has("x2w-mesh X2W_DRAW_STATE_DEPTHCLIP=1: "); + std::printf("log: X2W_MESH_STATE line %d, PSO with decoded state %d, depth clip alone %d (switch line %d)\n", switch_line, + decoded_line, clip_line, clip_switch_line); + if (switch_line != state_on || decoded_line != state_on || clip_line != (mode == "stateclip") || + clip_switch_line != (mode == "stateclip" || mode == "stateclipkeep")) { + std::printf("FAIL: the X2W_MESH_STATE lines do not match mode %s\n", mode.c_str()); + ++failures; + } + const bool flip_line = has("(X2W_MESH_STATE_CULL_FLIP: front face inverted)"); + const bool nocull_line = has("(X2W_MESH_STATE_NOCULL: rasterizer default)"); + if (flip_line != (mode == "statecullflip") || nocull_line != (mode == "statecullnone")) { + std::printf("FAIL: flip line %d / nocull line %d do not match mode %s\n", flip_line, nocull_line, mode.c_str()); + ++failures; + } + const std::string pso_line = std::string("x2w-mesh desktop pipeline for ") + key_text + ": "; + int pso_lines = 0; + for (std::size_t p = log.find(pso_line); p != std::string::npos; p = log.find(pso_line, p + 1)) ++pso_lines; + const bool both_passes = has(pso_line + "1 targets (format 28), dsv 40,") && has(pso_line + "1 targets (format 28), dsv 0,"); + std::printf("log: PSO lines for the key %d%s\n", pso_lines, repeat ? (both_passes ? " (dsv 40 and dsv 0)" : " (not both passes)") : ""); + // The binding's PSO serves the calls after the first of a pass: the once-per-process line, only with repeats. + const bool reused = has(std::string("x2w-mesh pipeline ") + key_text + ": PSO kept with the binding reused"); + std::printf("log: binding PSO reused line %d\n", reused); + // Depth state of the PSO: on where a forwarded clear marked the target, off on the uncleared control; + // statezlateclear: one call before the slot 51 clear (depth off), one after (a second PSO, depth on). + const bool depth_on_line = has(pso_line + "1 targets (format 28), dsv 40, depth 1,"); + const bool depth_off_line = has(pso_line + "1 targets (format 28), dsv 40, depth 0,"); + const bool late = mode == "statezlateclear"; + if (zmode && state_on && !repeat) { + const bool want_on = mode != "statezuncleared", want_off = mode == "statezuncleared" || late; + std::printf("log: PSO depth on %d / off %d (want %d / %d)\n", depth_on_line, depth_off_line, want_on, want_off); + if (depth_on_line != want_on || depth_off_line != want_off) { + std::printf("FAIL: PSO depth state does not match mode %s\n", mode.c_str()); + ++failures; + } + } + if (pso_lines != (repeat || late ? 2 : 1) || (repeat && !both_passes) || reused != repeat) { + std::printf("FAIL: PSO lines do not match mode %s\n", mode.c_str()); + ++failures; + } + } + if (words) { // the vdesc root parameter and buffer, and the word the stand-in wrote for the view + const bool root = has(std::string("x2w-vdesc pipeline ") + key_text + ": heapwords 1, vdesc in root parameter "); + const bool buffer = has("x2w-vdesc buffer 90000 ids x 32 bytes"); + std::string view_line; + if (const std::size_t p = log.find("x2w-vdesc view "); p != std::string::npos) view_line = log.substr(p, log.find('\n', p) - p); + std::printf("log: vdesc root parameter %d, vdesc buffer %d, view words \"%s\"\n", root, buffer, view_line.c_str()); + // Skipped (increment not 32): the root parameter exists, but no buffer is made and no view is filled. + if (!root || (words_skip ? buffer || !view_line.empty() : !buffer || view_line.empty())) { + std::printf("FAIL: the x2w-vdesc lines do not match mode %s\n", mode.c_str()); + ++failures; + } + } + // Traced frame (the trace_* tests run with X2W_D3D12_TRACE_ALL=1 X2W_D3D12_TRACE_TARGETS=1): one "x2w-frame mesh" + // line per call with key, targets, depth target, viewport, scissor, depth state and record words, and the targets + // noted for the read-back. Every other run is the negative control: no such line. + std::string log_tail; // lines written by the read-back below (traced runs), for the debug-layer check + char traced_env[8]{}; + const bool traced = GetEnvironmentVariableA("X2W_D3D12_TRACE_ALL", traced_env, sizeof(traced_env)) && traced_env[0] == '1'; + { + std::string frame_line; + if (const std::size_t p = log.find("x2w-frame mesh "); p != std::string::npos) frame_line = log.substr(p, log.find('\n', p) - p); + unsigned noted[4 * 8]{}; + const unsigned notes = x2w_d3d12_traced_targets(noted, 8); + std::printf("log: traced %d, frame line \"%s\", targets noted %u", traced, frame_line.c_str(), notes); + for (unsigned i = 0; i < notes && i < 8; ++i) std::printf(" [%ux%u fmt %u draws %u]", noted[4 * i], noted[4 * i + 1], noted[4 * i + 2], noted[4 * i + 3]); + std::printf("\n"); + bool trace_ok; + if (!traced) { + trace_ok = frame_line.empty() && notes == 0; + } else if (mode == "notargets") { // refused before the bind: a NOT drawn line with the reason, nothing noted + trace_ok = frame_line.find(std::string("x2w-frame mesh NOT drawn key ") + key_text + " targets 0 dsv ") == 0 && + frame_line.find(" viewport 0.0 0.0 32.0 32.0 depth 0.00-1.00 scissor 0 0 32 32") != std::string::npos && + frame_line.find(": no targets") != std::string::npos && notes == 0; + } else if (mode == "statez") { // drawn: RGBA8 target and D32 depth target, LESS + write (decoded), both noted once + trace_ok = frame_line.find(std::string("x2w-frame mesh drawn key ") + key_text + " targets 1 [0 ") == 0 && + frame_line.find(" 32x32 fmt 28] dsv ") != std::string::npos && frame_line.find(" fmt 40 (32x32 res fmt 40, last clear depth 0.5 stencil 0 flags 0x1 frame ") != std::string::npos && + frame_line.find(") query #0 viewport 0.0 0.0 32.0 32.0 depth 0.00-1.00 scissor 0 0 32 32 depth 1 func 2 write 1 stencil ") != std::string::npos && + frame_line.find(" record (max count 1, stride ") != std::string::npos && + frame_line.find(" raster cull ") != std::string::npos && frame_line.find("(from the title; title PA_SU_SC_MODE_CNTL ") != std::string::npos && + notes == 2 && noted[0] == 32 && noted[1] == 32 && noted[2] == 28 && noted[3] == 1 && noted[4] == 32 && noted[6] == 40 && noted[7] == 1; + } else if (mode == "statecull") { // X2W_MESH_STATE: the decoded rasterizer (cull back) in the PSO, with the title's words + trace_ok = frame_line.find(std::string("x2w-frame mesh drawn key ") + key_text + " targets 1 [0 ") == 0 && + frame_line.find(" raster cull 3 ccw ") != std::string::npos && + frame_line.find("(from the title; title PA_SU_SC_MODE_CNTL ") != std::string::npos && notes == 1 && noted[3] == 1; + } else if (mode == "stateculloff") { // the control: X2W_MESH_STATE unset, the default rasterizer (cull none) + trace_ok = frame_line.find(std::string("x2w-frame mesh drawn key ") + key_text + " targets 1 [0 ") == 0 && + frame_line.find(" raster cull 1 ccw 0 depthclip 1 bias 0/") != std::string::npos && + frame_line.find("(default: X2W_MESH_STATE off or NOCULL; title PA_SU_SC_MODE_CNTL ") != std::string::npos && notes == 1 && noted[3] == 1; + } else if (rectrace) { // the gpu call drawn, its target noted + trace_ok = frame_line.find(std::string("x2w-frame mesh drawn key ") + key_text + " targets 1 [0 ") == 0 && notes == 1 && noted[3] == 1; + } else if (mode == "zero") { // issued with 0 groups (the stats control): a drawn line with a query, the target noted + trace_ok = frame_line.find(std::string("x2w-frame mesh drawn key ") + key_text + " targets 1 [0 ") == 0 && + frame_line.find(" query #0 ") != std::string::npos && notes == 1 && noted[2] == 28 && noted[3] == 1; + } else { + trace_ok = false; // no trace expectation for this mode + } + if (!trace_ok) { + std::printf("FAIL: the traced-frame mesh line / noted targets do not match mode %s (traced %d)\n", mode.c_str(), traced); + ++failures; + } + // The end-of-frame read-back of the noted targets (as at the traced frame's present), from the snapshots: + // statez: target 0 (RGBA8, drawn: some texels non-zero) and target 1 (D32, cleared to 0.5 and drawn at 0.25: + // non-zero); notargets: no target line. Then the debug-layer check below covers the read-back too. + if (traced) { + x2w_d3d12_record_trace_report(); + x2w_d3d12_mesh_stats_report(); // the GPU work is complete (the pixels were read back above) + x2w_d3d12_summarise_traced_targets(); + std::ifstream again(log_path, std::ios::binary); + const std::string after{std::istreambuf_iterator(again), {}}; + const auto line_of = [&](const std::string& start) { + const std::size_t p = after.find(start); + return p == std::string::npos ? std::string() : after.substr(p, after.find('\n', p) - p); + }; + const std::string t0 = line_of("x2w-frame target 0 "), t1 = line_of("x2w-frame target 1 "); + std::printf("log: read-back \"%s\" / \"%s\"\n", t0.c_str(), t1.c_str()); + const auto nonzero_share = [](const std::string& line) { + const std::size_t p = line.find("non-zero texels "); + return p == std::string::npos ? -1.0 : std::atof(line.c_str() + p + 16); + }; + const bool bad = after.find("not summarised") != std::string::npos || after.find("read-back timed out") != std::string::npos; + const bool read_ok = mode == "statez" + ? t0.find(" snapshot ") != std::string::npos && t0.find(" 32x32 fmt 28 draws 1:") != std::string::npos && nonzero_share(t0) > 0.0 && + t1.find(" snapshot ") != std::string::npos && t1.find(" 32x32 fmt 40 draws 1:") != std::string::npos && nonzero_share(t1) > 0.0 + : mode == "zero" ? t0.find(" snapshot ") != std::string::npos && t0.find(" 32x32 fmt 28 draws 1:") != std::string::npos && nonzero_share(t0) == 0.0 + : mode == "statecull" || mode == "stateculloff" ? t0.find(" snapshot ") != std::string::npos && nonzero_share(t0) > 0.0 + : rectrace ? true // not what these modes check + : t0.empty(); + if (!read_ok || bad) { + std::printf("FAIL: the traced-target read-back does not match mode %s\n", mode.c_str()); + ++failures; + } + // Pipeline statistics: statez's call has query #0 and a stats line with clipped primitives and pixel + // invocations (two triangles drawn); notargets is refused before the bind: no query, no stats line. + const std::string stats = line_of(std::string("x2w-frame mesh stats #0 key ") + key_text + ": "); + const auto number_after = [](const std::string& line, const char* label) -> long long { + const std::size_t p = line.find(label); + return p == std::string::npos ? -1 : std::atoll(line.c_str() + p + std::strlen(label)); + }; + const long long c_prims = number_after(stats, "clipper invocations "), ps = number_after(stats, "PS invocations "); + const std::size_t clip_at = stats.find("clipper invocations "); + const long long c_primitives = clip_at == std::string::npos ? -1 : number_after(stats.substr(clip_at), " primitives "); + const long long ms_primitives = stats.find("MS invocations ") != std::string::npos ? number_after(stats, " primitives ") : -2; + std::printf("log: stats \"%s\" (clipper invocations %lld primitives %lld, PS %lld, MS primitives %lld; -2: no MS counts)\n", + stats.c_str(), c_prims, c_primitives, ps, ms_primitives); + const bool stats_ok = mode == "statez" + ? frame_line.find(" query #0") != std::string::npos && c_primitives >= 1 && ps >= 1 && (ms_primitives == -2 || ms_primitives >= 1) + : mode == "zero" ? !stats.empty() && c_prims == 0 && c_primitives == 0 && ps == 0 && (ms_primitives == -2 || ms_primitives == 0) + // statecull: 2 triangles emitted, one back-facing and culled. Whether the clipper count includes the + // culled one is what this run measures (printed above); either 1 or 2 passes, one triangle's pixels. + : mode == "statecull" ? !stats.empty() && (ms_primitives == -2 || ms_primitives == 2) && (c_primitives == 1 || c_primitives == 2) && ps >= 1 + : mode == "stateculloff" ? !stats.empty() && (ms_primitives == -2 || ms_primitives == 2) && c_primitives == 2 && ps >= 1 + : rectrace ? !stats.empty() + : stats.empty() && after.find("x2w-frame mesh stats #") == std::string::npos; + if (!stats_ok) { + std::printf("FAIL: the pipeline statistics do not match mode %s\n", mode.c_str()); + ++failures; + } + if (rectrace) { + const auto count_of = [&](const std::string& text) { + std::size_t n = 0; + for (std::size_t p = after.find(text); p != std::string::npos; p = after.find(text, p + 1)) ++n; + return n; + }; + char cull_ptr[32], tex_ptr[32], tsharp_text[96], vertex_text[48], other_text[48]; + std::snprintf(cull_ptr, sizeof(cull_ptr), "pipeline %p: skipped: c62 table argument:", cull); + std::snprintf(tex_ptr, sizeof(tex_ptr), "res %p title ", trace_texture); + std::snprintf(tsharp_text, sizeof(tsharp_text), ": T# 0x%llx 2x1 depth 1 fmt 56 levels 0-0 type 9 sw 0; ", + static_cast(arg(trace_texels))); + std::snprintf(vertex_text, sizeof(vertex_text), "buffer 0x%llx 48 bytes", static_cast(vertex_address)); + std::snprintf(other_text, sizeof(other_text), "buffer 0x%llx 64 bytes", static_cast(arg(other_memory))); + const bool apart = mode == "rectraceapart"; + // Image lines only (the writer's cx-heap lines also describe images: its record words 2, 1, 0 are taken + // as heap indexes, the ASSUMED rule). + const auto img_lines = [&](const std::string& text) { + std::size_t n = 0; + for (std::size_t p = after.find("x2w-frame cx-img #"); p != std::string::npos; p = after.find("x2w-frame cx-img #", p + 1)) { + const std::string line = after.substr(p, after.find('\n', p) - p); + n += line.find(text) != std::string::npos; + } + return n; + }; + const std::size_t cull_lines = count_of(cull_ptr); + const std::size_t srv_images = img_lines("(srv) dim 4 fmt 28 mip 0; " + std::string(tex_ptr)); + const std::size_t uav_images = img_lines(" (uav): view "); + const std::size_t raw_images = img_lines(tsharp_text + std::string(tex_ptr)); + const std::size_t no_writer = img_lines("; content: no writer seen in this frame before this dispatch"); + const std::size_t uav_writer = img_lines("; content: texture uav of key "); + const std::string heap_index = apart ? " index 4 (count 8, increment " : " index 0 (count 8, increment "; + const std::size_t heap_lines = count_of(heap_index) && count_of(apart ? other_text : vertex_text) ? 1 : 0; + // The mesh reads: srv 0 (table 1 + 0) and heap index 0 (root constant [0][1]). + char srv_read[160], heap_read[160]; + std::snprintf(srv_read, sizeof(srv_read), "x2w-frame mesh-read key %s S0 (source 0 1+0x0) 0x%llx 48 bytes, 1 calls: ", key_text, + static_cast(vertex_address)); + std::snprintf(heap_read, sizeof(heap_read), "x2w-frame mesh-read key %s H0 (heap index 0, root constant p0 w1) 0x%llx 48 bytes, 1 calls: ", + key_text, static_cast(vertex_address)); + const std::string verdict = apart ? "run dispatches only" : "INSIDE a skipped dispatch's range"; + const std::size_t srv_ok = count_of(srv_read + verdict), heap_ok = count_of(heap_read + verdict); + const std::size_t totals = count_of(apart ? "2 distinct ranges: 0 inside a skipped dispatch's range (0 inside a skipped table / heap entry, 0 only" + : "2 distinct ranges: 2 inside a skipped dispatch's range (2 inside a skipped table / heap entry, 0 only"); + // The reverse view: rectrace, the table V# entry and the heap entry of the cull pass, each with both reads; apart: none. + char by_entry[160], by_heap[160]; + std::snprintf(by_entry, sizeof(by_entry), " ? p2+0x0 0x%llx 48 bytes, skipped: c62 table argument, 2 dispatches (first #2): 2 distinct mesh reads, 2 calls", + static_cast(vertex_address)); + std::snprintf(by_heap, sizeof(by_heap), " H p3+0x0 0x%llx 48 bytes, skipped: c62 table argument, 2 dispatches (first #2): 2 distinct mesh reads, 2 calls", + static_cast(vertex_address)); + const std::size_t by_lines = count_of("x2w-frame mesh-read by-range "); + const bool by_ok = apart ? by_lines == 0 : by_lines == 2 && count_of(by_entry) == 1 && count_of(by_heap) == 1; + // cx-root: once per skipped dispatch, with the heap and the raw constants; the integer entry's `other` line. + const std::size_t root_lines = count_of(apart ? " p3 constants 2: 00000004 00000100;" : " p3 constants 2: 00000000 00000100;"); + const std::size_t root_heap = count_of(" count 8 increment " + std::to_string(view_increment) + "; p0 kind 4 "); + const std::size_t other_lines = img_lines(": other: words 00000005 00000000 00000000 00000000 00000000 00000000 00000000 00000000 (integer + 7 zero words"); + std::printf("log: rectrace cull lines %zu, images srv %zu uav %zu raw T# %zu, content none %zu / uav writer %zu, heap line %zu, " + "mesh reads srv %zu heap %zu, totals %zu, by-range %zu (%d), cx-root %zu (heap %zu), other %zu\n", + cull_lines, srv_images, uav_images, raw_images, no_writer, uav_writer, heap_lines, srv_ok, heap_ok, totals, by_lines, by_ok, + root_lines, root_heap, other_lines); + // Two dispatches x 3 image entries; the first sees no writer, the second names the first's UAV. + if (cull_lines != 2 || srv_images != 2 || uav_images != 2 || raw_images != 2 || no_writer != 3 || uav_writer != 3 || !heap_lines || + srv_ok != 1 || heap_ok != 1 || totals != 1 || !by_ok || root_lines != 2 || root_heap != 2 || other_lines != 2) { + std::printf("FAIL: the X2W_MESH_RECORD_TRACE lines do not match mode %s\n", mode.c_str()); + ++failures; + } + } + log_tail = after.substr(log.size() < after.size() ? log.size() : after.size()); + } + } + if (dump_test) { // X2W_MESH_DUMP_INPUTS, traced or not (the dump selects the first call with groups in any frame) + // X2W_MESH_DUMP_INPUTS (statez): the dump folder next to the log, the vertex srv bytes equal to the test's + // vertices, entry constants, root constants and the 12-byte record of an issued call. + if (mode == "statez") { + const std::wstring dump = cache + L"\\mesh_dump_" + std::wstring(key_text, key_text + 16) + L"\\"; + const auto read_all = [](const std::wstring& path) { + std::ifstream f(path, std::ios::binary); + return std::string{std::istreambuf_iterator(f), {}}; + }; + const std::string index = read_all(dump + L"index.txt"); + bool vertices_found = false; + for (int s = 0; s < 8 && !vertices_found; ++s) { + const std::string bytes = read_all(dump + L"srv" + std::to_wstring(s) + L".bin"); + vertices_found = bytes.size() == sizeof(vertices) && std::memcmp(bytes.data(), vertices, sizeof(vertices)) == 0; + } + const std::string record = read_all(dump + L"record.bin"); + // The heap buffer named by root constant [0][1] (bit 28, index 0): the vertices again, and its descriptor. + const std::string heap0 = read_all(dump + L"heap0.bin"), heap0_desc = read_all(dump + L"heap0_desc.bin"); + const bool heap_ok = heap0.size() == sizeof(vertices) && std::memcmp(heap0.data(), vertices, sizeof(vertices)) == 0 && + heap0_desc.size() == 32 && index.find("(root constant [0][1] = 0x10000000)") != std::string::npos && + index.find("heap3") == std::string::npos; + const DWORD other = GetFileAttributesW((cache + L"\\mesh_dump_0000000000000001").c_str()); + const bool dump_ok = other == INVALID_FILE_ATTRIBUTES && has("x2w-mesh X2W_MESH_DUMP_INPUTS: 2 key(s)") && heap_ok && + vertices_found && index.find("entry.bin ") != std::string::npos && + index.find("root_constants.bin 512 bytes") != std::string::npos && record.size() == 12 && + index.find("call issued") != std::string::npos && has(std::string("x2w-mesh dump ") + key_text + ":"); + std::printf("log: dump index:\n%s(vertices found %d, record %zu bytes)\n", index.c_str(), vertices_found, record.size()); + if (!dump_ok) { + std::printf("FAIL: the X2W_MESH_DUMP_INPUTS files do not match (heap buffer %d)\n", heap_ok); + ++failures; + } + } + if (mode == "zero") { // the control: the key is listed, but its only call has X = 0 at record time: no dump + const DWORD folder = GetFileAttributesW((cache + L"\\mesh_dump_" + std::wstring(key_text, key_text + 16)).c_str()); + const bool none = folder == INVALID_FILE_ATTRIBUTES && !has(std::string("x2w-mesh dump ") + key_text + ":") && + has("x2w-mesh X2W_MESH_DUMP_INPUTS: 2 key(s)"); + std::printf("log: zero-group call dumped %d\n", !none); + if (!none) { + std::printf("FAIL: a call with X = 0 was dumped\n"); + ++failures; + } + } + } + char frames_env[8]{}, multi_env[8]{}; + const bool fs_multi = GetEnvironmentVariableA("X2W_TEST_FS_MULTI", multi_env, sizeof(multi_env)) && multi_env[0] == '1'; + if (GetEnvironmentVariableA("X2W_MESH_STATS_FRAMES", frames_env, sizeof(frames_env)) && frames_env[0]) { + if (fs_multi) { + UINT64 fence_value = 1; + const auto fs_call = [&](std::uint32_t record_x, std::uint32_t record_y) { + const std::uint32_t record[3] = {record_x, record_y, 1}; + std::memcpy(args_memory, record, 12); // the record at record time, and what the GPU reads + invoke(list, 139, arg(allocator)); // Reset + invoke(list, 50, 1, arg(&target_handle)); + invoke(list, 21, 1, arg(&viewport)); + invoke(list, 22, 1, arg(&scissor)); + invoke(list, 34, arg(title_root)); + invoke(list, 32, smp ? 2 : 1, arg(heaps)); + invoke(list, 36, 1, view_gpu); + invoke(list, 40, 2, 1, arg(&colour), 0); + invoke(list, 25, arg(pipeline)); + invoke(list, 61, arg(signature), 1, arg(args), 0, 0, 0); + invoke(list, 9); // Close + invoke(queue, 10, 1, arg(lists)); + invoke(queue, 14, arg(fence), ++fence_value); + for (const auto until = GetTickCount64() + 10000; invoke(fence, 8) < fence_value && GetTickCount64() < until;) Sleep(1); + }; + const std::uint32_t x1 = mode == "zero" ? 0u : 1u; + x2w_d3d12_mesh_frame_stats_present(); // frame 0 ends + for (int f = 1; f <= 20; ++f) { + fs_call(0, 1); + x2w_d3d12_mesh_frame_stats_present(); + } + fs_call(x1, 1); + fs_call(x1, 0); + x2w_d3d12_mesh_frame_stats_present(); + fs_call(x1, 1); + x2w_d3d12_mesh_frame_stats_present(); + for (int i = 0; i < 9; ++i) x2w_d3d12_mesh_frame_stats_present(); + } else { + x2w_d3d12_mesh_frame_stats_report(); + } + std::ifstream again(log_path, std::ios::binary); + const std::string after{std::istreambuf_iterator(again), {}}; + std::string set_line, total_line; + for (std::size_t p = after.find("x2w-mesh stats frame "); p != std::string::npos && set_line.empty(); p = after.find("x2w-mesh stats frame ", p + 1)) { + const std::string line = after.substr(p, after.find('\n', p) - p); + if (line.find(" set ") != std::string::npos) set_line = line; // a target-set line (not "not counted") + } + if (const std::size_t p = after.find("x2w-mesh stats frames total "); p != std::string::npos) total_line = after.substr(p, after.find('\n', p) - p); + std::printf("log: frame stats \"%s\" / \"%s\"\n", set_line.c_str(), total_line.c_str()); + const auto line_of = [&](const std::string& start) { + const std::size_t p = after.find(start); + return p == std::string::npos ? std::string() : after.substr(p, after.find('\n', p) - p); + }; + std::size_t not_counted = 0; + for (std::size_t p = after.find(" not counted (no record with X > 0"); p != std::string::npos; p = after.find(" not counted (no record with X > 0", p + 1)) + ++not_counted; + const std::string set0 = line_of("x2w-mesh stats frame 0 set "), set21 = line_of("x2w-mesh stats frame 21 set "); + if (fs_multi) + std::printf("log: multi: frame 0 \"%s\", frame 21 \"%s\", not counted lines %zu, frame 22 lines %d\n", set0.c_str(), set21.c_str(), not_counted, + after.find("x2w-mesh stats frame 22 ") != std::string::npos); + const std::string targets = "set targets 1 [fmt 28 32x32] dsv none: "; + const bool set_ok = fs_multi + ? mode == "zero" + ? set_line.empty() && total_line.empty() && not_counted == 8 + : set0.find(targets + "calls 1 (1 with groups), ") != std::string::npos && + set21.find(targets + "calls 2 (1 with groups), ") != std::string::npos && set21.find("clipper invocations 0 ") == std::string::npos && + total_line.find("x2w-mesh stats frames total 1 of 2 frames (frame 0)") == 0 && + line_of("x2w-mesh stats frames total 2 ").find("x2w-mesh stats frames total 2 of 2 frames (frame 21): 1 target sets, calls 2 (1 with groups)") == 0 && + not_counted == 8 && after.find("x2w-mesh stats frame 22 ") == std::string::npos && + after.find("x2w-mesh stats frames total 3 ") == std::string::npos + : mode == "zero" + ? set_line.empty() && after.find("x2w-mesh stats frame 0 not counted (no record with X > 0") != std::string::npos + : set_line.find(" set targets 1 [fmt 28 32x32] dsv none: calls 1 (1 with groups), ") != std::string::npos && + (set_line.find("MS invocations 6 primitives 2, clipper invocations 2 primitives 2, PS invocations ") != std::string::npos || + set_line.find("(no MS counts) clipper invocations 2 primitives 2") != std::string::npos) && + total_line.find("x2w-mesh stats frames total 1 of 1 frames") == 0; + if (!set_ok) { + std::printf("FAIL: the X2W_MESH_STATS_FRAMES lines do not match mode %s\n", mode.c_str()); + ++failures; + } + log_tail += after.substr(log.size() < after.size() ? log.size() : after.size()); + } else if (has("X2W_MESH_STATS_FRAMES") || has("x2w-mesh stats frame")) { // every other run: the switch is off + std::printf("FAIL: frame statistics lines without X2W_MESH_STATS_FRAMES\n"); + ++failures; + } + const std::string debug_log = log + log_tail; + for (std::size_t p = debug_log.find("x2w-d3d12-debug"); p != std::string::npos; p = debug_log.find("x2w-d3d12-debug", p + 1)) { + const std::size_t end = debug_log.find('\n', p); + const std::string line = debug_log.substr(p, end == std::string::npos ? std::string::npos : end - p); + std::printf("%s\n", line.c_str()); + if (line.find("sev=0 ") != std::string::npos || line.find("sev=1 ") != std::string::npos) ++failures; + } + std::printf("device removed reason: 0x%08lx\n", static_cast(desktop->GetDeviceRemovedReason())); + if (desktop->GetDeviceRemovedReason() != S_OK) ++failures; + if (!failures && words_skip) { + std::printf("view increment %u is not 32: skipped as required, vdesc not exercised: capability skip\n", view_increment); + return 77; + } + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; +} diff --git a/tests/startup_mesh_dispatch.hlsl b/tests/startup_mesh_dispatch.hlsl new file mode 100644 index 0000000000..c6933b2a0f --- /dev/null +++ b/tests/startup_mesh_dispatch.hlsl @@ -0,0 +1,117 @@ +// Shaders for tests/startup_mesh_dispatch.cpp (a hand-written stand-in for a translated mesh pipeline). +// +// MeshMain / PixelMain use the translated draw root signature the stand-in builds from the manifest +// (x2w_startup::create_translated_root): b0 = the entry values (udsrc 0 rect, udsrc 1 rootconst), t0 = srv 0. +// One triangle per group: group g reads vertices 3g..3g+2 (float2 each) from t0. Colour from entry value 1 +// (0x00BBGGRR); alpha 1 when the rect entry value is 0 (a mesh call must bind 0 there), else 0.5. +ByteAddressBuffer positions : register(t0); +cbuffer Entry : register(b0) { uint rect; uint colour; }; + +struct Vertex { + float4 param0 : PARAM0; + float4 pos : SV_Position; +}; + +[numthreads(3, 1, 1)] +[outputtopology("triangle")] +void MeshMain(uint3 group : SV_GroupID, uint thread : SV_GroupThreadID, out vertices Vertex verts[3], out indices uint3 tris[1]) +{ + SetMeshOutputCounts(3, 1); + const float2 p = asfloat(positions.Load2((group.x * 3 + thread) * 8)); + // Colour bit 24 (the stateclip modes): z 1.5 = beyond the far plane (z / w > 1), drawn only with depth clip off. + verts[thread].pos = float4(p, (colour >> 24) & 1 ? 1.5 : 0.25, 1.0); + verts[thread].param0 = float4((colour & 255) / 255.0, ((colour >> 8) & 255) / 255.0, ((colour >> 16) & 255) / 255.0, + rect == 0 ? 1.0 : 0.5); + if (thread == 0) tris[0] = uint3(0, 1, 2); +} + +cbuffer HeapEntry : register(b0) { uint heap_rect; uint heap_colour; uint heap_slot; }; +ByteAddressBuffer heapmem : register(t0, space1); +ByteAddressBuffer vdesc : register(t2, space1); +ByteAddressBuffer heapbuf[] : register(t0, space6); + +[numthreads(3, 1, 1)] +[outputtopology("triangle")] +void MeshHeap(uint3 group : SV_GroupID, uint thread : SV_GroupThreadID, out vertices Vertex verts[3], out indices uint3 tris[1]) +{ + const uint h = heap_slot * 32; + const uint id = heapmem.Load(h) == 0x56573258u ? heapmem.Load(h + 4) : 0xffffffffu; + const uint word3 = id < 90000u ? vdesc.Load(id * 32 + 12) : 0u; + const uint format = (word3 >> 12) & 127u; + const bool known = format == 29u || format == 64u; + SetMeshOutputCounts(known ? 3 : 0, known ? 1 : 0); + if (!known) return; + const uint e = group.x * 3 + thread; + const uint k = 8u + 8u * id + 4u; + float2 p; + if (format == 29u) { + const uint v = heapbuf[NonUniformResourceIndex(k)].Load(e * 4); + p = f16tof32(uint2(v & 0xffffu, v >> 16)); + } else { + p = asfloat(heapbuf[NonUniformResourceIndex(k)].Load2(e * 8)); + } + verts[thread].pos = float4(p, 0.25, 1.0); + verts[thread].param0 = float4((heap_colour & 255) / 255.0, format / 255.0, ((heap_colour >> 16) & 255) / 255.0, heap_rect == 0 ? 1.0 : 0.5); + if (thread == 0) tris[0] = uint3(0, 1, 2); +} + +// MeshDescword (modes descword / descwordoff; manifest `udsrc 2 descword 1 8`, mesh2hlsl X2W_MESH_FEATURES=descword): a +// word of a TABLE descriptor read as a number, as a translated mesh stage reads a V# NUM_RECORDS. Entry value 2 is +// dword 2 (byte 8) of the descriptor in table parameter 1 entry 0: the test's hardware buffer descriptor, NUM_RECORDS +// = 48 (0x30). Green = that word's low byte; the triangle is drawn only when the word is 48 (a group reads its +// vertices only within NUM_RECORDS bytes, as the console's bounds check would). +cbuffer DescEntry : register(b0) { uint desc_rect; uint desc_colour; uint desc_word2; }; + +[numthreads(3, 1, 1)] +[outputtopology("triangle")] +void MeshDescword(uint3 group : SV_GroupID, uint thread : SV_GroupThreadID, out vertices Vertex verts[3], out indices uint3 tris[1]) +{ + const uint e = group.x * 3 + thread; + const bool inside = desc_word2 == 48u && (group.x * 3 + 3) * 8 <= desc_word2; + SetMeshOutputCounts(inside ? 3 : 0, inside ? 1 : 0); + if (!inside) return; + const float2 p = asfloat(positions.Load2(e * 8)); + verts[thread].pos = float4(p, 0.25, 1.0); + verts[thread].param0 = float4((desc_colour & 255) / 255.0, (desc_word2 & 255) / 255.0, ((desc_colour >> 16) & 255) / 255.0, + desc_rect == 0 ? 1.0 : 0.5); + if (thread == 0) tris[0] = uint3(0, 1, 2); +} + +Texture2D smp_tex : register(t1); +SamplerState qh[2048] : register(s0, space1); +float4 PixelSampler(Vertex input) : SV_Target0 +{ + return smp_tex.SampleLevel(qh[65u], float2(0.375, 0.5), 0); +} + +float4 PixelMain(Vertex input) : SV_Target0 +{ + return input.param0; +} + +// PixelUint (mode rtvvariant): the RTV variant of PixelMain for an R32_UINT target, as a translator would emit it for +// `rtv1 42`: the colour bytes of param0 packed into one uint (0x00BBGGRR when alpha is 1). +uint4 PixelUint(Vertex input) : SV_Target0 +{ + const uint4 c = uint4(round(saturate(input.param0) * 255.0)); + return uint4(c.x | (c.y << 8) | (c.z << 16) | ((c.w == 255u ? 0u : c.w) << 24), 0, 0, 0); +} + +// PixelStore (modes uavtex / uavtexnoflag): an image_store as the translator lowers it (`uav 0 tex2d table 1 `): +// the colour stored to texel (x, y) of the texture UAV u0 and also returned to the target. +RWTexture2D store0 : register(u0); +float4 PixelStore(Vertex input) : SV_Target0 +{ + store0[uint2(input.pos.xy)] = input.param0; + return input.param0; +} + +// Writer (a console compute pipeline, container path): root [0] UAV u0, [1] four constants b1. +// Stores the DispatchMesh record values.xyz at byte offset values.w of u0. +RWByteAddressBuffer target : register(u0); +cbuffer Values : register(b1) { uint4 values; }; +[numthreads(1, 1, 1)] +void Writer() +{ + target.Store3(values.w, values.xyz); +} diff --git a/tests/startup_mesh_exec_lineage_check.py b/tests/startup_mesh_exec_lineage_check.py new file mode 100644 index 0000000000..227a46e500 --- /dev/null +++ b/tests/startup_mesh_exec_lineage_check.py @@ -0,0 +1,111 @@ +"""Exec lineage in the mesh-stage translator (mesh2hlsl MeshStage.lineage_*, X2W_MESH_EXEC_LINEAGE). + +A VGPR written from uniform values while exec is E holds one value in every lane of E (the other lanes keep their +old value). The epoch rule forgets that at the first exec write that may widen exec; the compiler's usual shape +restores a SAVED copy of an earlier exec, after which only lanes of E can be active again. Hand-assembled NGG mesh +programs (no cache bytes), RDNA 2 ISA encodings, v5 = the vertex id (different in every lane): + + 0x00 v_cmp_lt_u32 vcc, 3, v5; 0x04 s_and_saveexec_b64 s[26:27], vcc E1 = lanes v5 > 3 (s26 = entry exec) + 0x08 v_mov_b32 v1, 1.0 v1 = 1.0 in every lane of E1 + 0x0c v_cmp_lt_u32 vcc, 7, v5; 0x10 s_and_saveexec_b64 s[18:19], vcc E2 = lanes v5 > 7 (s18 = E1) + 0x14 v_mov_b32 v2, 0; 0x18 s_mov_b64 exec, s[18:19] back to E1 (restore) + 0x1c v_cmp_lt_u32 vcc, 5, v5; 0x20 s_and_b64 exec, vcc, exec E3 = lanes v5 > 5, a subset of E1 + 0x24 v_cmp_lt_f32 vcc, 0, v1; 0x28 s_cbranch_vccz 0x30; 0x2c s_nop 0 vcc = 1 in every active lane + 0x30 s_mov_b64 exec, s[26:27]; then v1 = float(s0), exp pos0 / prim, s_endpgm + +Checks: + subset the program translates: v1 is the same in every lane of E3, so the per-lane vccz branch is the wave's + parent 0x18 restores s[26:27] (the entry exec, a superset of E1) instead: refused ("lane-dependent vcc"), + since lanes outside E1 may be active again and hold another v1 + copy 0x14 overwrites s18 (s_mov_b32 s18, 0) before the restore: refused (the restore no longer names E1) + half 0x14 overwrites only s19, the high half of the saved pair: refused as well +The rule is off by default; this check turns it on (X2W_MESH_EXEC_LINEAGE=1, set before the import). +Negative control: with X2W_MESH_EXEC_LINEAGE=0 (the epoch rule only) `subset` is refused (run in a child). +""" +import os +import struct +import subprocess +import sys + +os.environ.setdefault('X2W_MESH_EXEC_LINEAGE', '1') # the child of the negative control passes 0 + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import root_blob # noqa: E402 + +TAIL = (0x7e020c00, # v_cvt_f32_u32 v1, s0 + 0x7e040280, # v_mov_b32 v2, 0 + 0xb07c1003, # s_movk_i32 m0, 0x1003 + 0xbf900009, # s_sendmsg 0x9 + 0xf80008cf, 0x02020201, # exp pos0 v1, v2, v2, v2 done + 0xf8000941, 0x00000002, # exp prim v2 done + 0xbf810000) # s_endpgm +BODY = [0x7d820a83, # 0x00 v_cmp_lt_u32 vcc, 3, v5 + 0xbe9a246a, # 0x04 s_and_saveexec_b64 s[26:27], vcc + 0x7e0202f2, # 0x08 v_mov_b32 v1, 1.0 + 0x7d820a87, # 0x0c v_cmp_lt_u32 vcc, 7, v5 + 0xbe92246a, # 0x10 s_and_saveexec_b64 s[18:19], vcc + 0x7e040280, # 0x14 v_mov_b32 v2, 0 + 0xbefe0412, # 0x18 s_mov_b64 exec, s[18:19] + 0x7d820a85, # 0x1c v_cmp_lt_u32 vcc, 5, v5 + 0x87fe7e6a, # 0x20 s_and_b64 exec, vcc, exec + 0x7c020280, # 0x24 v_cmp_lt_f32 vcc, 0, v1 + 0xbf860001, # 0x28 s_cbranch_vccz 0x30 + 0xbf800000, # 0x2c s_nop 0 + 0xbefe041a] # 0x30 s_mov_b64 exec, s[26:27] +TEXT = ['v_cmp_lt_u32_e32 vcc_lo, 3, v5', 's_and_saveexec_b64 s[26:27], vcc', 'v_mov_b32_e32 v1, 1.0', + 'v_cmp_lt_u32_e32 vcc_lo, 7, v5', 's_and_saveexec_b64 s[18:19], vcc', 'v_mov_b32_e32 v2, 0', + 's_mov_b64 exec, s[18:19]', 'v_cmp_lt_u32_e32 vcc_lo, 5, v5', 's_and_b64 exec, vcc, exec', + 'v_cmp_lt_f32_e32 vcc_lo, 0, v1', 's_cbranch_vccz label_0x30', 's_nop 0', 's_mov_b64 exec, s[26:27]'] + + +def program(**at): + words = list(BODY) + for off, word in at.items(): + words[int(off[1:], 16) // 4] = word + return struct.pack('<%dI' % (len(words) + len(TAIL)), *(words + list(TAIL))) + + +SUBSET = program() +PARENT = program(x18=0xbefe041a) # 0x18 s_mov_b64 exec, s[26:27] +COPY = program(x14=0xbe920380) # 0x14 s_mov_b32 s18, 0 +HALF = program(x14=0xbe930380) # 0x14 s_mov_b32 s19, 0 + + +def translate(code): + try: + M.MeshPipeline(code, None, root_blob()).hlsl_ms() + return 'ok' + except G.Unsupported as e: + return str(e) + + +def check(): + text = [x[3] for x in G.decode(SUBSET)][:len(TEXT)] + assert text == TEXT, text + assert [x[3] for x in G.decode(PARENT)][6] == 's_mov_b64 exec, s[26:27]' + assert [x[3] for x in G.decode(COPY)][5] == 's_mov_b32 s18, 0' + assert [x[3] for x in G.decode(HALF)][5] == 's_mov_b32 s19, 0' + got = translate(SUBSET) + assert got == 'ok', ('subset', got) + for name, code in (('parent', PARENT), ('copy', COPY), ('half', HALF)): + got = translate(code) + assert 'lane-dependent vcc' in got, (name, got) + return 'subset translates; parent restore, overwritten copy and overwritten high half refused' + + +def main(): + if os.environ.get('X2W_MESH_EXEC_LINEAGE') == '0': # child of the negative control + check() + return + summary = check() + env = dict(os.environ, X2W_MESH_EXEC_LINEAGE='0') + r = subprocess.run([sys.executable, '-B', os.path.abspath(__file__)], env=env, capture_output=True, text=True) + assert r.returncode != 0 and 'AssertionError' in r.stderr, ('negative control passed', r.stdout, r.stderr) + print('mesh exec lineage: %s; X2W_MESH_EXEC_LINEAGE=0 fails (%s)' % (summary, r.stderr.strip().splitlines()[-1][:90])) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_mesh_exec_off_check.py b/tests/startup_mesh_exec_off_check.py new file mode 100644 index 0000000000..46d405d48a --- /dev/null +++ b/tests/startup_mesh_exec_off_check.py @@ -0,0 +1,257 @@ +"""Check the exec-off rule of tools/startup/mesh2hlsl.py (MeshStage.merge_exec_off / exec_off_use): a register that""" +import os +import struct +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, '..', 'tools')) +sys.path.insert(0, os.path.join(HERE, '..', 'tools', 'startup')) +import disasm_rdna2 as D # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +# ---- a minimal gfx10 encoder (as tests/startup_mesh_exec_restore_check.py): field layout per format, opcode +# found by decoding ----------------------------------------------------------------------------------------------- +def src(tok): + named = {'vcc_lo': 106, 'vcc_hi': 107, 'm0': 124, 'exec_lo': 126, 'exec_hi': 127} + if tok in named: + return named[tok], None + if tok[0] == 's': + return int(tok[1:]), None + if tok[0] == 'v': + return 256 + int(tok[1:]), None + v = int(tok, 0) + if 0 <= v <= 64: + return 128 + v, None + if -16 <= v < 0: + return 192 - v, None + return 255, v & 0xffffffff + + +def fmt_words(fmt, op, f): + if fmt == 'sop2': + return [(0b10 << 30) | (op << 23) | (f['d'] << 16) | (f['s1'] << 8) | f['s0']] + if fmt == 'sop1': + return [(0x17d << 23) | (f['d'] << 16) | (op << 8) | f['s0']] + if fmt == 'sopc': + return [(0x17e << 23) | (op << 16) | (f['s1'] << 8) | f['s0']] + if fmt == 'sopp': + return [(0x17f << 23) | (op << 16) | (f['imm'] & 0xffff)] + if fmt == 'vop1': + return [(0x3f << 25) | (f['d'] << 17) | (op << 9) | f['s0']] + if fmt == 'vopc': + return [(0x3e << 25) | (op << 17) | ((f['s1'] - 256) << 9) | f['s0']] + if fmt == 'vop3': + return [(0x35 << 26) | (op << 16) | f['d'], f['s0'] | (f['s1'] << 9) | (f.get('s2', 0) << 18)] + if fmt == 'smem': + # gfx10 SMEM: [31:26] 0x3d, [25:18] op, [12:6] sdata, [5:0] sbase / 2; word 1: [20:0] offset, [31:25] soffset + return [(0x3d << 26) | (op << 18) | (f['d'] << 6) | (f['s0'] >> 1), (f['imm'] & 0x1fffff) | (0x7d << 25)] + raise ValueError(fmt) + + +OP_RANGE = {'sop2': 128, 'sop1': 256, 'sopc': 128, 'sopp': 128, 'vop1': 256, 'vopc': 256, 'vop3': 1024, 'smem': 256} +_op_cache = {} + + +def find_op(fmt, mnemonic, fields): + key = (fmt, mnemonic) + if key in _op_cache: + return _op_cache[key] + for op in range(OP_RANGE[fmt]): + words = fmt_words(fmt, op, fields) + code = struct.pack('<%dI' % len(words), *words) + b'\0' * 8 + try: + _, name, _, _ = D.decode_instruction(code, 0) + except Exception: + continue + if name == mnemonic: + _op_cache[key] = op + return op + raise KeyError('%s %s: no opcode decodes to it' % (fmt, mnemonic)) + + +def ins(fmt, mnemonic, **ops): + fields, literal = {}, None + for k, tok in ops.items(): + if k in ('d', 'imm'): + fields[k] = tok if isinstance(tok, int) else src(tok)[0] + continue + code, lit = src(tok) + fields[k] = code + if lit is not None: + literal = lit + words = fmt_words(fmt, find_op(fmt, mnemonic, fields), fields) + return words + ([literal] if literal is not None else []) + + +def exp(target, vals, done=False): + en = sum(1 << i for i, v in enumerate(vals) if v is not None) + w0 = (0x3e << 26) | (int(done) << 11) | (target << 4) | en + w1 = 0 + for i, v in enumerate(vals): + if v is not None: + w1 |= int(v[1:]) << (8 * i) + return [w0, w1] + + +def assemble(items): + off, labels, sized = 0, {}, [] + for text, make in items: + if make is None: + labels[text[:-1]] = off + continue + words = make() if callable(make) else [0] + sized.append((off, text, make, len(words))) + off += 4 * len(words) + out, texts = [], [] + for off, text, make, n in sized: + if callable(make): + words = make() + else: + target = labels[text.split()[1]] + words = ins('sopp', 's_cbranch_' + make if make != 'branch' else 's_branch', imm=(target - off - 4) // 4) + text = '%s label_%#x' % (text.split()[0], target) + out += words + texts.append((off, text)) + return struct.pack('<%dI' % len(out), *out), texts + + +def decoded(code): + off, res = 0, [] + while off + 4 <= len(code): + n, name, asm, _ = D.decode_instruction(code, off) + res.append((off, asm)) + off += n + return res + + +def I(text, fmt, mnemonic, **ops): + return (text, lambda: ins(fmt, mnemonic, **ops)) + + +PROLOGUE = [ + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('v_readfirstlane_b32 s20, v5', 'vop1', 'v_readfirstlane_b32', d=20, s0='v5'), + I('s_lshr_b32 s20, s20, 7', 'sop2', 's_lshr_b32', d=20, s0='s20', s1='7'), + I('s_bfe_u32 s28, s3, 0x40018', 'sop2', 's_bfe_u32', d=28, s0='s3', s1='0x40018'), + I('s_lshl_b32 s29, s28, 6', 'sop2', 's_lshl_b32', d=29, s0='s28', s1='6'), + I('v_mbcnt_lo_u32_b32 v0, -1, s29', 'vop3', 'v_mbcnt_lo_u32_b32', d=0, s0='-1', s1='s29'), + I('v_mbcnt_hi_u32_b32 v0, -1, v0', 'vop3', 'v_mbcnt_hi_u32_b32', d=0, s0='-1', s1='v0'), + I('s_and_b32 s21, s20, 1', 'sop2', 's_and_b32', d=21, s0='s20', s1='1'), + I('s_mul_i32 s21, s21, 60', 'sop2', 's_mul_i32', d=21, s0='s21', s1='60'), + I('s_bfe_u32 s23, s20, 0x10001', 'sop2', 's_bfe_u32', d=23, s0='s20', s1='0x10001'), + I('s_mul_i32 s23, s23, 40', 'sop2', 's_mul_i32', d=23, s0='s23', s1='40'), + I('s_add_u32 s21, s21, s23', 'sop2', 's_add_u32', d=21, s0='s21', s1='s23'), + I('s_and_b32 s22, s20, 3', 'sop2', 's_and_b32', d=22, s0='s20', s1='3'), + I('s_mul_i32 s22, s22, 20', 'sop2', 's_mul_i32', d=22, s0='s22', s1='20'), + I('v_mov_b32_e32 v1, 0x40a00000', 'vop1', 'v_mov_b32_e32', d=1, s0='0x40a00000'), # 5.0 + I('v_mov_b32_e32 v4, 0', 'vop1', 'v_mov_b32_e32', d=4, s0='0'), + # the table pointer (root parameter 0 = user SGPR s16) and its zero high word, as the run programs build it + I('s_mov_b32 s27, 0', 'sop1', 's_mov_b32', d=27, s0='0'), + I('s_mov_b32 s26, s16', 'sop1', 's_mov_b32', d=26, s0='s16'), + # a load through it (its result unused) makes s16 a table for the synthesized root of the differential test + I('s_load_dwordx4 s[32:35], s[26:27], 0x0', 'smem', 's_load_dwordx4', d=32, s0='s26', imm=0), + I('s_mov_b64 s[30:31], exec', 'sop1', 's_mov_b64', d=30, s0='exec_lo'), + I('v_cmpx_gt_u32_e32 s21, v0', 'vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0'), + ('s_cbranch_execz J', 'execz'), + I('v_cmp_gt_u32_e64 s26, s22, v0', 'vop3', 'v_cmp_gt_u32_e64', d=26, s0='s22', s1='v0'), + ('J:', None), +] +EPILOGUE = [ + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('s_mov_b32 m0, 0x80080', 'sop1', 's_mov_b32', d=124, s0='0x80080'), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + I('v_cvt_f32_u32_e32 v2, v0', 'vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0'), + I('v_mov_b32_e32 v3, 0', 'vop1', 'v_mov_b32_e32', d=3, s0='0'), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v1, v0, v4, v0', lambda: exp(32, ['v1', 'v0', 'v4', 'v0'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] +RESTORE = I('s_mov_b64 exec, s[30:31]', 'sop1', 's_mov_b64', d=126, s0='s30') +TAIL = [RESTORE, I('s_and_b64 exec, s[26:27], exec', 'sop2', 's_and_b64', d=126, s0='s26', s1='exec_lo'), + I('v_mov_b32_e32 v1, 0x41100000', 'vop1', 'v_mov_b32_e32', d=1, s0='0x41100000')] # 9.0 + + +def merge_op(mnemonic): + return I('%s s[26:27], s[26:27], exec' % mnemonic, 'sop2', mnemonic, d=26, s0='s26', s1='exec_lo') + + +PROGRAMS = { + 'nand': (True, PROLOGUE + [merge_op('s_nand_b64')] + TAIL + EPILOGUE), + 'orn2': (True, PROLOGUE + [merge_op('s_orn2_b64')] + TAIL + EPILOGUE), + 'or': (False, PROLOGUE + [merge_op('s_or_b64')] + TAIL + EPILOGUE), + 'execw': (False, PROLOGUE + [RESTORE, merge_op('s_nand_b64')] + TAIL + EPILOGUE), + 'load': (False, PROLOGUE + [I('s_load_dwordx4 s[36:39], s[26:27], 0x0', 'smem', 's_load_dwordx4', d=36, + s0='s26', imm=0)] + [merge_op('s_nand_b64')] + TAIL + EPILOGUE), +} +REFUSAL = {'or': 'numeric use of s26 holding conflict', 'execw': 'numeric use of s26 holding conflict', + 'load': 's_load through s26 holding (\'conflict\',)'} + + +def translate(path, env): + """Run the translator in a child process (its switches are read at import): HLSL or the refusal text. Root: + parameter 0 a descriptor table (user SGPR s16), parameter 1 one root constant (s17).""" + child = ('import sys; sys.path[:0] = [%r, %r]\n' + 'import gfx2hlsl as G, mesh2hlsl as M\n' + 'code = open(sys.argv[1], "rb").read()\n' + 'try:\n' + ' p = M.MeshPipeline(code, None, M.synth_layout({16}, set(), {16, 17}, 16), user_sgpr=16)\n' + ' sys.stdout.write("OK\\n" + p.hlsl_ms())\n' + 'except G.Unsupported as e:\n' + ' sys.stdout.write("REFUSED %%s\\n" %% e)\n' + % (os.path.join(HERE, '..', 'tools'), os.path.join(HERE, '..', 'tools', 'startup'))) + e = dict(os.environ) + e.pop('X2W_MESH_EXECOFF', None) + e.update(env) + r = subprocess.run([sys.executable, '-B', '-c', child, path], capture_output=True, text=True, env=e) + if r.returncode: + return 'CRASH ' + (r.stderr.strip().splitlines() or ['?'])[-1] + return r.stdout + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_exec_off') + os.makedirs(out_dir, exist_ok=True) + refused_old = "REFUSED execz range 0x" + for name, (accept, items) in PROGRAMS.items(): + code, texts = assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = translate(path, {}) + if accept: + check('%s: translates with the rule on' % name, on.startswith('OK'), on[:300]) + formula = {'nand': 's26 = (~(s26 & exec)) & 1;', 'orn2': 's26 = (s26 | ~exec) & 1;'}[name] + check('%s: the merge reads the run-time s26 (%s)' % (name, formula), formula in on, + [l.strip() for l in on.splitlines() if 's26 =' in l][:4]) + off = translate(path, {'X2W_MESH_EXECOFF': '0'}) + check('%s: negative control X2W_MESH_EXECOFF=0 refuses again' % name, + off.startswith(refused_old) and "changes s26 from ptr to ('conflict',)" in off, off[:200]) + else: + check('%s: still refused with the rule on (%s)' % (name, REFUSAL[name]), + on.startswith('REFUSED ' + REFUSAL[name]), on[:200]) + print('programs written to %s (difftest: python -B difftest.py /nand.bin --groups 4 --seed 1)' + % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_exec_restore_check.py b/tests/startup_mesh_exec_restore_check.py new file mode 100644 index 0000000000..f4ecd813fe --- /dev/null +++ b/tests/startup_mesh_exec_restore_check.py @@ -0,0 +1,251 @@ +"""Check the exec-restore rule of tools/startup/mesh2hlsl.py for per-lane skipped ranges (MeshStage.exec_copies_at,""" +import os +import struct +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, '..', 'tools')) +sys.path.insert(0, os.path.join(HERE, '..', 'tools', 'startup')) +import disasm_rdna2 as D # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +# ---- a minimal gfx10 encoder (as tests/startup_mesh_lane_scc_check.py): field layout per format, opcode found by +# decoding -------------------------------------------------------------------------------------------------------- +def src(tok): + named = {'vcc_lo': 106, 'vcc_hi': 107, 'm0': 124, 'exec_lo': 126, 'exec_hi': 127} + if tok in named: + return named[tok], None + if tok[0] == 's': + return int(tok[1:]), None + if tok[0] == 'v': + return 256 + int(tok[1:]), None + v = int(tok, 0) + if 0 <= v <= 64: + return 128 + v, None + if -16 <= v < 0: + return 192 - v, None + return 255, v & 0xffffffff + + +def fmt_words(fmt, op, f): + if fmt == 'sop2': + return [(0b10 << 30) | (op << 23) | (f['d'] << 16) | (f['s1'] << 8) | f['s0']] + if fmt == 'sop1': + return [(0x17d << 23) | (f['d'] << 16) | (op << 8) | f['s0']] + if fmt == 'sopc': + return [(0x17e << 23) | (op << 16) | (f['s1'] << 8) | f['s0']] + if fmt == 'sopp': + return [(0x17f << 23) | (op << 16) | (f['imm'] & 0xffff)] + if fmt == 'vop1': + return [(0x3f << 25) | (f['d'] << 17) | (op << 9) | f['s0']] + if fmt == 'vopc': + return [(0x3e << 25) | (op << 17) | ((f['s1'] - 256) << 9) | f['s0']] + if fmt == 'vop3': + return [(0x35 << 26) | (op << 16) | f['d'], f['s0'] | (f['s1'] << 9) | (f.get('s2', 0) << 18)] + raise ValueError(fmt) + + +OP_RANGE = {'sop2': 128, 'sop1': 256, 'sopc': 128, 'sopp': 128, 'vop1': 256, 'vopc': 256, 'vop3': 1024} +_op_cache = {} + + +def find_op(fmt, mnemonic, fields): + key = (fmt, mnemonic) + if key in _op_cache: + return _op_cache[key] + for op in range(OP_RANGE[fmt]): + words = fmt_words(fmt, op, fields) + code = struct.pack('<%dI' % len(words), *words) + b'\0' * 8 + try: + _, name, _, _ = D.decode_instruction(code, 0) + except Exception: + continue + if name == mnemonic: + _op_cache[key] = op + return op + raise KeyError('%s %s: no opcode decodes to it' % (fmt, mnemonic)) + + +def ins(fmt, mnemonic, **ops): + fields, literal = {}, None + for k, tok in ops.items(): + if k in ('d', 'imm'): + fields[k] = tok if isinstance(tok, int) else src(tok)[0] + continue + code, lit = src(tok) + fields[k] = code + if lit is not None: + literal = lit + words = fmt_words(fmt, find_op(fmt, mnemonic, fields), fields) + return words + ([literal] if literal is not None else []) + + +def exp(target, vals, done=False): + en = sum(1 << i for i, v in enumerate(vals) if v is not None) + w0 = (0x3e << 26) | (int(done) << 11) | (target << 4) | en + w1 = 0 + for i, v in enumerate(vals): + if v is not None: + w1 |= int(v[1:]) << (8 * i) + return [w0, w1] + + +def assemble(items): + off, labels, sized = 0, {}, [] + for text, make in items: + if make is None: + labels[text[:-1]] = off + continue + words = make() if callable(make) else [0] + sized.append((off, text, make, len(words))) + off += 4 * len(words) + out, texts = [], [] + for off, text, make, n in sized: + if callable(make): + words = make() + else: + target = labels[text.split()[1]] + words = ins('sopp', 's_cbranch_' + make if make != 'branch' else 's_branch', imm=(target - off - 4) // 4) + text = '%s label_%#x' % (text.split()[0], target) + out += words + texts.append((off, text)) + return struct.pack('<%dI' % len(out), *out), texts + + +def decoded(code): + off, res = 0, [] + while off + 4 <= len(code): + n, name, asm, _ = D.decode_instruction(code, off) + res.append((off, asm)) + off += n + return res + + +def I(text, fmt, mnemonic, **ops): + return (text, lambda: ins(fmt, mnemonic, **ops)) + + +PROLOGUE = [ + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('v_readfirstlane_b32 s20, v5', 'vop1', 'v_readfirstlane_b32', d=20, s0='v5'), + I('s_lshr_b32 s20, s20, 7', 'sop2', 's_lshr_b32', d=20, s0='s20', s1='7'), + I('s_bfe_u32 s28, s3, 0x40018', 'sop2', 's_bfe_u32', d=28, s0='s3', s1='0x40018'), + I('s_lshl_b32 s29, s28, 6', 'sop2', 's_lshl_b32', d=29, s0='s28', s1='6'), + I('v_mbcnt_lo_u32_b32 v0, -1, s29', 'vop3', 'v_mbcnt_lo_u32_b32', d=0, s0='-1', s1='s29'), + I('v_mbcnt_hi_u32_b32 v0, -1, v0', 'vop3', 'v_mbcnt_hi_u32_b32', d=0, s0='-1', s1='v0'), + I('s_and_b32 s21, s20, 1', 'sop2', 's_and_b32', d=21, s0='s20', s1='1'), + I('s_mul_i32 s21, s21, 60', 'sop2', 's_mul_i32', d=21, s0='s21', s1='60'), + I('s_add_u32 s21, s21, 40', 'sop2', 's_add_u32', d=21, s0='s21', s1='40'), + I('s_and_b32 s22, s20, 3', 'sop2', 's_and_b32', d=22, s0='s20', s1='3'), + I('s_mul_i32 s22, s22, 20', 'sop2', 's_mul_i32', d=22, s0='s22', s1='20'), + I('s_mov_b32 s23, 10', 'sop1', 's_mov_b32', d=23, s0='10'), + I('v_mov_b32_e32 v1, 5', 'vop1', 'v_mov_b32_e32', d=1, s0='5'), + I('v_mov_b32_e32 v4, 0', 'vop1', 'v_mov_b32_e32', d=4, s0='0'), +] +EPILOGUE = [ + ('AFTER:', None), + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('s_mov_b32 m0, 0x80080', 'sop1', 's_mov_b32', d=124, s0='0x80080'), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + I('v_cvt_f32_u32_e32 v2, v0', 'vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0'), + I('v_mov_b32_e32 v3, 0', 'vop1', 'v_mov_b32_e32', d=3, s0='0'), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v1, v0, v4, v0', lambda: exp(32, ['v1', 'v0', 'v4', 'v0'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] +CMPX_N = I('v_cmpx_gt_u32_e32 s21, v0', 'vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0') +CMPX_T = I('v_cmpx_gt_u32_e32 s22, v0', 'vopc', 'v_cmpx_gt_u32_e32', s0='s22', s1='v0') +SAVE = I('s_mov_b64 s[30:31], exec', 'sop1', 's_mov_b64', d=30, s0='exec_lo') +RESTORE = I('s_mov_b64 exec, s[30:31]', 'sop1', 's_mov_b64', d=126, s0='s30') +V1_9 = I('v_mov_b32_e32 v1, 9', 'vop1', 'v_mov_b32_e32', d=1, s0='9') +V4_7 = I('v_mov_b32_e32 v4, 7', 'vop1', 'v_mov_b32_e32', d=4, s0='7') + +PROGRAMS = { + 'restore': (True, PROLOGUE + [CMPX_N, SAVE, ('s_cbranch_execz AFTER', 'execz'), CMPX_T, V1_9, RESTORE, V4_7] + + EPILOGUE), + 'shuffle': (True, PROLOGUE + [CMPX_N, SAVE, ('s_cbranch_execz AFTER', 'execz'), + I('s_mov_b64 s[34:35], s[30:31]', 'sop1', 's_mov_b64', d=34, s0='s30'), + I('s_mov_b32 s30, 0', 'sop1', 's_mov_b32', d=30, s0='0'), + CMPX_T, V1_9, + I('s_mov_b64 exec, s[34:35]', 'sop1', 's_mov_b64', d=126, s0='s34'), V4_7] + + EPILOGUE), + 'vccz': (True, PROLOGUE + [CMPX_N, SAVE, + I('v_mov_b32_e32 v6, s22', 'vop1', 'v_mov_b32_e32', d=6, s0='s22'), + I('v_cmp_lt_u32_e32 vcc_lo, 30, v6', 'vopc', 'v_cmp_lt_u32_e32', s0='30', s1='v6'), + ('s_cbranch_vccz AFTER', 'vccz'), + I('v_cmpx_gt_u32_e32 s23, v0', 'vopc', 'v_cmpx_gt_u32_e32', s0='s23', s1='v0'), + V1_9, RESTORE, V4_7] + EPILOGUE), + 'wider': (False, PROLOGUE + [SAVE, CMPX_N, ('s_cbranch_execz AFTER', 'execz'), RESTORE, V4_7] + EPILOGUE), + 'onepath': (False, PROLOGUE + [CMPX_N, I('s_cmp_eq_u32 s22, 0', 'sopc', 's_cmp_eq_u32', s0='s22', s1='0'), + ('s_cbranch_scc1 J', 'scc1'), SAVE, ('J:', None), + ('s_cbranch_execz AFTER', 'execz'), CMPX_T, V1_9, RESTORE, V4_7] + EPILOGUE), + 'clobber': (False, PROLOGUE + [CMPX_N, SAVE, + I('v_cmp_gt_u32_e64 s29, s22, v0', 'vop3', 'v_cmp_gt_u32_e64', d=29, s0='s22', s1='v0'), + ('s_cbranch_execz AFTER', 'execz'), CMPX_T, V1_9, RESTORE, V4_7] + EPILOGUE), +} + + +def translate(path, env): + """Run the translator in a child process (its switches are read at import): HLSL or the refusal text.""" + child = ('import sys; sys.path[:0] = [%r, %r]\n' + 'import gfx2hlsl as G, mesh2hlsl as M\n' + 'code = open(sys.argv[1], "rb").read()\n' + 'try:\n' + ' p = M.MeshPipeline(code, None, M.synth_root(code), user_sgpr=16)\n' + ' sys.stdout.write("OK\\n" + p.hlsl_ms())\n' + 'except G.Unsupported as e:\n' + ' sys.stdout.write("REFUSED %%s\\n" %% e)\n' + % (os.path.join(HERE, '..', 'tools'), os.path.join(HERE, '..', 'tools', 'startup'))) + e = dict(os.environ) + e.pop('X2W_MESH_EXEC_COPIES', None) + e.update(env) + r = subprocess.run([sys.executable, '-B', '-c', child, path], capture_output=True, text=True, env=e) + if r.returncode: + return 'CRASH ' + (r.stderr.strip().splitlines() or ['?'])[-1] + return r.stdout + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_exec_restore') + os.makedirs(out_dir, exist_ok=True) + refused_old = 'REFUSED exec written by s_mov_b64 inside the per-lane skipped range' + for name, (accept, items) in PROGRAMS.items(): + code, texts = assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = translate(path, {}) + if accept: + reg = 's34' if name == 'shuffle' else 's30' + check('%s: translates with the rule on' % name, on.startswith('OK'), on[:300]) + check('%s: exec restored from the saved pair %s' % (name, reg), 'exec = (%s) & 1;' % reg in on, '') + off = translate(path, {'X2W_MESH_EXEC_COPIES': '0'}) + check('%s: negative control X2W_MESH_EXEC_COPIES=0 refuses again' % name, off.startswith(refused_old), off[:200]) + else: + check('%s: still refused with the rule on' % name, on.startswith(refused_old), on[:200]) + print('programs written to %s (difftest: python -B difftest.py /restore.bin --groups 4 --seed 1)' + % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_exec_walk_check.py b/tests/startup_mesh_exec_walk_check.py new file mode 100644 index 0000000000..41e2528ccf --- /dev/null +++ b/tests/startup_mesh_exec_walk_check.py @@ -0,0 +1,94 @@ +"""Check the path-aware exec walk of tools/startup/mesh2hlsl.py (MeshStage.exec_walk, with exec_copies_at tracking""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 +from startup_mesh_exec_restore_check import I # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +def MOV32(d, s): + return I('s_mov_b32 s%d, %s' % (d, s), 'sop1', 's_mov_b32', d=d, s0=s) + + +def XOR(width, d, s0, s1): + """s_xor_b32 / s_xor_b64 on SGPRs (bases d, s0, s1).""" + t = (lambda r: 's%d' % r) if width == 32 else (lambda r: 's[%d:%d]' % (r, r + 1)) + return I('s_xor_b%d %s, %s, %s' % (width, t(d), t(s0), t(s1)), 'sop2', 's_xor_b%d' % width, d=d, s0='s%d' % s0, + s1='s%d' % s1) + + +def SWAP(width, a, b): + return [XOR(width, a, a, b), XOR(width, b, a, b), XOR(width, a, a, b)] + + +COPY34 = I('s_mov_b64 s[34:35], s[30:31]', 'sop1', 's_mov_b64', d=34, s0='s30') +CLEAR34 = I('s_mov_b64 s[34:35], 0', 'sop1', 's_mov_b64', d=34, s0='0') +REST34 = I('s_mov_b64 exec, s[34:35]', 'sop1', 's_mov_b64', d=126, s0='s34') +CMP_T0 = I('s_cmp_eq_u32 s22, 0', 'sopc', 's_cmp_eq_u32', s0='s22', s1='0') +HEAD = E.PROLOGUE + [E.CMPX_N, E.SAVE, ('s_cbranch_execz AFTER', 'execz')] +TAIL = [E.V4_7] + E.EPILOGUE +REFUSE = 'exec written' +PROGRAMS = { + 'clobberskip': ('ok', HEAD + [COPY34, CMP_T0, ('s_cbranch_scc1 R', 'scc1'), CLEAR34, E.CMPX_T, E.V1_9, COPY34, + ('R:', None), REST34] + TAIL), + 'halves': ('ok', HEAD + [MOV32(34, 's30'), MOV32(35, 's31'), E.CMPX_T, E.V1_9, REST34] + TAIL), + 'onepath': (REFUSE, HEAD + [COPY34, CMP_T0, ('s_cbranch_scc1 R', 'scc1'), CLEAR34, E.CMPX_T, E.V1_9, + ('R:', None), REST34] + TAIL), + 'swapped': (REFUSE, HEAD + [MOV32(34, 's31'), MOV32(35, 's30'), E.CMPX_T, E.V1_9, REST34] + TAIL), + 'mixed': (REFUSE, HEAD + [MOV32(34, 's30'), MOV32(35, 's22'), E.CMPX_T, E.V1_9, REST34] + TAIL), + # XOR swaps: s[34:35] = (T, 0) is data; the swap moves the exec copy from s[30:31] into s[34:35] + 'xorswap64': ('ok', HEAD + [MOV32(34, 's22'), MOV32(35, '0')] + SWAP(64, 30, 34) + + [E.CMPX_T, E.V1_9, REST34] + TAIL), + 'xorswap32': ('ok', HEAD + [MOV32(34, 's22'), MOV32(35, '0'), XOR(32, 30, 30, 34), E.V1_9, + XOR(32, 34, 30, 34), XOR(32, 30, 30, 34)] + SWAP(32, 31, 35) + + [E.CMPX_T, E.V1_9, REST34] + TAIL), + 'xorwrong': (REFUSE, HEAD + [MOV32(34, 's22'), MOV32(35, '0')] + SWAP(64, 30, 34) + + [E.CMPX_T, E.V1_9, I('s_mov_b64 exec, s[30:31]', 'sop1', 's_mov_b64', d=126, s0='s30')] + TAIL), + 'xorbroken': (REFUSE, HEAD + [MOV32(34, 's22'), MOV32(35, '0'), XOR(64, 30, 30, 34), MOV32(35, '1'), + XOR(64, 34, 30, 34), XOR(64, 30, 30, 34), E.CMPX_T, E.V1_9, REST34] + TAIL), +} + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_exec_walk') + os.makedirs(out_dir, exist_ok=True) + for name, (want, items) in PROGRAMS.items(): + code, texts = E.assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = E.translate(path, {}) + if want == 'ok': + check('%s: translates' % name, on.startswith('OK'), on[:300]) + if name == 'clobberskip': + off = E.translate(path, {'X2W_MESH_EXEC_COPIES': '0'}) + check('clobberskip: negative control X2W_MESH_EXEC_COPIES=0 refuses', off.startswith('REFUSED'), + off[:300]) + else: + check('%s: refused (%s)' % (name, want), on.startswith('REFUSED') and want in on.splitlines()[0], + on[:200]) + print('programs written to %s' % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_first_lane_check.py b/tests/startup_mesh_first_lane_check.py new file mode 100644 index 0000000000..f126cf4886 --- /dev/null +++ b/tests/startup_mesh_first_lane_check.py @@ -0,0 +1,72 @@ +"""Check the first-active-lane rule of tools/startup/mesh2hlsl.py (MeshStage.first_active_broadcast, NeedGroupRange):""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 +from startup_mesh_exec_restore_check import I # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +CMPX_LE_T = I('v_cmpx_le_u32_e32 s22, v0', 'vopc', 'v_cmpx_le_u32_e32', s0='s22', s1='v0') +V7 = I('v_lshlrev_b32_e64 v7, 1, v0', 'vop3', 'v_lshlrev_b32_e64', d=7, s0='1', s1='v0') +RFL = I('v_readfirstlane_b32 s24, v7', 'vop1', 'v_readfirstlane_b32', d=24, s0='v7') +V1 = I('v_mov_b32_e32 v1, s24', 'vop1', 'v_mov_b32_e32', d=1, s0='s24') +P, EP = E.PROLOGUE, E.EPILOGUE +PROGRAMS = { + 'rflpartial': ('ok', P + [CMPX_LE_T, V7, RFL, V1] + EP), + 'rflrange': ('ok', P + [E.CMPX_N, ('s_cbranch_execz AFTER', 'execz'), CMPX_LE_T, V7, RFL, V1] + EP), + 'rflloop': ('lanes off inside a loop', P + [CMPX_LE_T, I('s_mov_b32 s30, 0', 'sop1', 's_mov_b32', d=30, s0='0'), ('H:', None), + V7, RFL, I('s_add_u32 s30, s30, 1', 'sop2', 's_add_u32', d=30, s0='s30', s1='1'), + I('s_cmp_lt_u32 s30, 2', 'sopc', 's_cmp_lt_u32', s0='s30', s1='2'), + ('s_cbranch_scc1 H', 'scc1'), V1] + EP), + 'rflvccz': ('lanes off', P + [E.CMPX_N, I('v_mov_b32_e32 v6, s22', 'vop1', 'v_mov_b32_e32', d=6, s0='s22'), + I('v_cmp_lt_u32_e32 vcc_lo, 30, v6', 'vopc', 'v_cmp_lt_u32_e32', s0='30', s1='v6'), + ('s_cbranch_vccz AFTER', 'vccz'), CMPX_LE_T, V7, RFL, V1] + EP), +} + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_first_lane') + os.makedirs(out_dir, exist_ok=True) + for name, (want, items) in PROGRAMS.items(): + code, texts = E.assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = E.translate(path, {}) + if want == 'ok': + check('%s: translates with the first-active-lane read' % name, + on.startswith('OK') and 's24 = x2w_rfirst(0u, wbase);' in on and 'x2w_rfe[0][tid] = exec & 1u;' in on, + on[:3000]) + if name == 'rflrange': + check('rflrange: the execz range is run by the group (x2w_any publish)', 'x2w_any[0][wave] = 1u' in on, + on[:3000]) + off = E.translate(path, {'X2W_MESH_RFL_FIRST': '0'}) + check('%s: negative control X2W_MESH_RFL_FIRST=0 refuses (lanes off)' % name, + off.startswith('REFUSED') and 'lanes off' in off.splitlines()[0], off[:200]) + else: + check('%s: refused (%s)' % (name, want), on.startswith('REFUSED') and want in on.splitlines()[0], on[:200]) + print('programs written to %s' % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_heap_sampler_check.py b/tests/startup_mesh_heap_sampler_check.py new file mode 100644 index 0000000000..988a70c2bc --- /dev/null +++ b/tests/startup_mesh_heap_sampler_check.py @@ -0,0 +1,187 @@ +"""Check the constant sampler-heap entry of tools/startup/mesh2hlsl.py (const_heap_sampler, MeshStage.heap_sampler, +MeshPixelStage): four sampler words loaded from the sampler heap at a constant byte offset become entry offset / 16 +of the table the draw path binds for run-time offsets (`SamplerState qh[2048] : register(s0, space1)`, manifest +`smpheap 2048 1 fallback 2047`), opt-in with X2W_SAMPLER_HEAP=1 like that form. + +usage: startup_mesh_heap_sampler_check.py + +Hand-assembled gfx1013 NGG mesh programs (no title bytes; encoded field by field, opcode numbers found by decoding +with tools/disasm_rdna2.py, the decoded text compared with the intended text). Root: parameter 0 a descriptor table, +parameter 1 one root constant, flag 0x800 (SAMPLER_HEAP_DIRECTLY_INDEXED): mesh user SGPRs s16 table, s17 constant, +s18 sampler heap. The run programs read their sampler heap the same way (`s_load_dwordx4 s[..], s[24:25], 0x410`). +Pixel stage of the pair: the source-built fixture of tests/startup_sampler_heap_check.py (CONST_WORDS: llvm-mc +words of `s_load_dwordx4 s[24:27], s[10:11], 0x10` + image_sample), whose s10 is the same sampler heap. + +Hardware meaning (AMD RDNA 2 ISA, S_LOAD_DWORDX4 / IMAGE_SAMPLE): the sampler state is the four dwords at +heap base + offset; the stand-in's table entry n holds the title's heap entry at byte 16 * n (gfx2hlsl contract). + + CONST (accept): offset 0x410 -> qh[65u] + UNALIGNED (accept): offset 0x418 -> qh[2047u] (the reserved fallback entry, as x2w_sampler_entry does) + PAIR (accept): CONST mesh stage + the fixture pixel stage (offset 0x10) -> qh[1u] in the pixel stage + EDITED (refuse): s_and_b32 s42, s42, 0xffff between the load and the sample (sampler word changed in the shader) + MIXED (refuse): s_mov_b32 s41, 0 between the load and the sample (words no longer one heap entry) + +Checks: each program decodes to its intended text; accepted ones translate with X2W_SAMPLER_HEAP=1, name the entry, +declare the table and write the smpheap line, and are refused without the switch (negative control: the switch off +gives the f37ad9f8 behaviour, a refusal, with the reason naming the offset); refused ones are refused with it. +""" +import os +import struct +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, '..', 'tools')) +sys.path.insert(0, os.path.join(HERE, '..', 'tools', 'startup')) +import disasm_rdna2 as D # noqa: E402 +from startup_mesh_exec_off_check import I, assemble, decoded, exp, ins # noqa: E402 (the same encoder) + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +def image_sample(vdata, vaddr, srsrc, ssamp): + """MIMG image_sample, dmask 0xf, dim 2D (word 0 as the fixture's llvm-mc encoding 080f80f0); word 1: vaddr [7:0], + vdata [15:8], srsrc / 4 [20:16], ssamp / 4 [25:21].""" + return [0xf0800f08, vaddr | (vdata << 8) | ((srsrc // 4) << 16) | ((ssamp // 4) << 21)] + + +def program(offset, between=()): + return [ + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('v_readfirstlane_b32 s20, v5', 'vop1', 'v_readfirstlane_b32', d=20, s0='v5'), + I('s_lshr_b32 s20, s20, 7', 'sop2', 's_lshr_b32', d=20, s0='s20', s1='7'), + I('s_bfe_u32 s28, s3, 0x40018', 'sop2', 's_bfe_u32', d=28, s0='s3', s1='0x40018'), + I('s_lshl_b32 s29, s28, 6', 'sop2', 's_lshl_b32', d=29, s0='s28', s1='6'), + I('v_mbcnt_lo_u32_b32 v0, -1, s29', 'vop3', 'v_mbcnt_lo_u32_b32', d=0, s0='-1', s1='s29'), + I('v_mbcnt_hi_u32_b32 v0, -1, v0', 'vop3', 'v_mbcnt_hi_u32_b32', d=0, s0='-1', s1='v0'), + I('s_mov_b32 s11, 0', 'sop1', 's_mov_b32', d=11, s0='0'), + I('s_mov_b32 s10, s16', 'sop1', 's_mov_b32', d=10, s0='s16'), + I('s_load_dwordx8 s[32:39], s[10:11], 0x0', 'smem', 's_load_dwordx8', d=32, s0='s10', imm=0), + I('s_mov_b32 s13, 0', 'sop1', 's_mov_b32', d=13, s0='0'), + I('s_mov_b32 s12, s18', 'sop1', 's_mov_b32', d=12, s0='s18'), + I('s_load_dwordx4 s[40:43], s[12:13], %#x' % offset, 'smem', 's_load_dwordx4', d=40, s0='s12', imm=offset), + ] + list(between) + [ + I('v_mov_b32_e32 v6, 0x3f000000', 'vop1', 'v_mov_b32_e32', d=6, s0='0x3f000000'), + I('v_mov_b32_e32 v7, 0x3f000000', 'vop1', 'v_mov_b32_e32', d=7, s0='0x3f000000'), + ('image_sample v[8:11], v[6:7], s[32:39], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D', + lambda: image_sample(8, 6, 32, 40)), + I('v_mov_b32_e32 v4, 0', 'vop1', 'v_mov_b32_e32', d=4, s0='0'), + I('s_mov_b32 m0, 0x80080', 'sop1', 's_mov_b32', d=124, s0='0x80080'), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + I('v_cvt_f32_u32_e32 v2, v0', 'vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0'), + I('v_mov_b32_e32 v3, 0', 'vop1', 'v_mov_b32_e32', d=3, s0='0'), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v8, v9, v10, v11', lambda: exp(32, ['v8', 'v9', 'v10', 'v11'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), + ] + + +EDIT = I('s_and_b32 s42, s42, 0xffff', 'sop2', 's_and_b32', d=42, s0='s42', s1='0xffff') +MIX = I('s_mov_b32 s41, 0', 'sop1', 's_mov_b32', d=41, s0='0') +PROGRAMS = { + 'const': (65, program(0x410)), + 'unaligned': (2047, program(0x418)), + 'edited': ('sampler heap entry at 0x410 edited in the shader', program(0x410, [EDIT])), + 'mixed': ('sampler operand s[40:43] mixes sampler heap words', program(0x410, [MIX])), +} +# tests/startup_sampler_heap_check.py CONST_WORDS (its PS_WORDS with the sampler load at the constant offset 0x10) +PS_CONST = bytes.fromhex('04040cf4000000fa' '050608f4100000fa' 'ff02007e0000a03f' 'f002027e' '7fc08cbf' + '080f80f00000c400' '703f8cbf' '0f1800f800010203' '000081bf') + + +def root_blob(): + """A DXBC container with one RTS0 part: parameter 0 a descriptor table, parameter 1 one root constant, flag 0x800 + (the layout of tests/startup_sampler_heap_check.py root_blob).""" + params = [(0, 0), (1, 0)] + poff = 24 + coff = poff + 12 * len(params) + rts0 = struct.pack('<6I', 2, len(params), poff, 0, 0, 0x800) + rts0 += struct.pack('<3I', 0, 0, coff + 12) + struct.pack('<3I', 1, 0, coff) + rts0 += struct.pack('<3I', 0, 0, 1) + rts0 += struct.pack('<5I', 0, 0, 0, 0, 0) + part = b'RTS0' + struct.pack(' 30 (groups 2, 3), else 5; lanes v0 >= N: 5. +UNIFORM_B = PROLOGUE + [ + ('v_mov_b32_e32 v1, 5', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='5')), + ('v_mov_b32_e32 v4, s22', lambda: ins('vop1', 'v_mov_b32_e32', d=4, s0='s22')), + ('v_cmpx_gt_u32_e32 s21, v0', lambda: ins('vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0')), + ('s_cbranch_execz AFTER', 'execz'), + ('v_cmp_lt_u32_e32 vcc_lo, 30, v4', lambda: ins('vopc', 'v_cmp_lt_u32_e32', s0='30', s1='v4')), + ('s_and_b64 s[12:13], vcc, exec', lambda: ins('sop2', 's_and_b64', d=12, s0='vcc_lo', s1='exec_lo')), + ('s_cbranch_scc0 AFTER', 'scc0'), + ('v_mov_b32_e32 v1, 60', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='60')), +] + EPILOGUE +# Program C: a lane-dependent SCC inside a per-lane execz range that writes no scalar read after it (a plain +# per-lane range before), then a per-lane vccz branch with an s_branch over the other side, both sides copying +# SCC to s20 (the shape of the run's programs). The publish needs every thread of the group at its barrier, so +# the range becomes group-uniform; the s_lshl on the first side leaves a lane-tainted SCC that the linear scan +# would carry into the other side (the join merge takes the state of the vccz branch instead). +# N = 40 + 60 * (g & 1), T = 30 * (g & 3). Expected param0.x: lanes v0 < N of a wave with a lane v0 < min(N, T): +# 60; every other lane 5. (g = 2: wave 1 has no lane in the range; g = 3: wave 1 lanes 64..99 get 60.) +# Program D: inside a per-lane execz range, an SCC from a saved exec copy and NOT exec (`s_andn2_b64 s, saved, +# exec`): the active lanes' own bits are all 0, the wave's SCC is 1 when the wave has a lane outside the range. Not +# an active-uniform SCC: it must be published. Expected param0.x: lanes v0 < N of a wave with a lane v0 >= N: 60; +# every other lane 5 (g even: lanes 0..39; g odd: lanes 64..99). +ANDN2_D = PROLOGUE + [ + ('v_mov_b32_e32 v1, 5', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='5')), + ('s_mov_b64 s[8:9], exec', lambda: ins('sop1', 's_mov_b64', d=8, s0='exec_lo')), + ('v_cmpx_gt_u32_e32 s21, v0', lambda: ins('vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0')), + ('s_cbranch_execz AFTER', 'execz'), + ('s_andn2_b64 s[12:13], s[8:9], exec', lambda: ins('sop2', 's_andn2_b64', d=12, s0='s8', s1='exec_lo')), + ('s_cbranch_scc0 AFTER', 'scc0'), + ('v_mov_b32_e32 v1, 60', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='60')), +] + EPILOGUE +# Program E: nested group-uniform execz ranges (both write a scalar read after them), so the outer skip jumps over +# the inner range's publish barrier (a barrier the translation adds). N = 50 * (g & 3): group 0 has no active lane +# at all (the group skips the outer range), group 1 has none in wave 1. Expected param0.x per wave (s40 + s41): +# no lane v0 < N: 300; lanes v0 < N but none < 20: 209; lanes v0 < 20 (and < N): 16. +NESTED_E = PROLOGUE[:7] + [ + ('s_and_b32 s21, s20, 3', lambda: ins('sop2', 's_and_b32', d=21, s0='s20', s1='3')), + ('s_mul_i32 s21, s21, 50', lambda: ins('sop2', 's_mul_i32', d=21, s0='s21', s1='50')), + ('s_mov_b32 s40, 0x64', lambda: ins('sop1', 's_mov_b32', d=40, s0='100')), + ('s_mov_b32 s41, 0xc8', lambda: ins('sop1', 's_mov_b32', d=41, s0='200')), + ('v_cmpx_gt_u32_e32 s21, v0', lambda: ins('vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0')), + ('s_cbranch_execz AFTER', 'execz'), + ('s_mov_b32 s40, 9', lambda: ins('sop1', 's_mov_b32', d=40, s0='9')), + ('v_cmpx_gt_u32_e32 20, v0', lambda: ins('vopc', 'v_cmpx_gt_u32_e32', s0='20', s1='v0')), + ('s_cbranch_execz AFTER', 'execz'), + ('s_mov_b32 s41, 7', lambda: ins('sop1', 's_mov_b32', d=41, s0='7')), + EPILOGUE[0], EPILOGUE[1], + ('s_add_u32 s42, s40, s41', lambda: ins('sop2', 's_add_u32', d=42, s0='s40', s1='s41')), + ('v_mov_b32_e32 v1, s42', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='s42')), +] + EPILOGUE[2:] +PROLOGUE_C = PROLOGUE[:-1] + [ + ('s_mul_i32 s22, s22, 30', lambda: ins('sop2', 's_mul_i32', d=22, s0='s22', s1='30')), +] +SPLIT_C = PROLOGUE_C + [ + ('v_mov_b32_e32 v1, 5', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='5')), + ('v_mov_b32_e32 v4, s22', lambda: ins('vop1', 'v_mov_b32_e32', d=4, s0='s22')), + ('v_cmpx_gt_u32_e32 s21, v0', lambda: ins('vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0')), + ('s_cbranch_execz AFTER', 'execz'), + ('v_cmp_gt_u32_e32 vcc_lo, s22, v0', lambda: ins('vopc', 'v_cmp_gt_u32_e32', s0='s22', s1='v0')), + ('s_and_b64 s[12:13], vcc, exec', lambda: ins('sop2', 's_and_b64', d=12, s0='vcc_lo', s1='exec_lo')), + ('v_cmp_lt_u32_e32 vcc_lo, 30, v4', lambda: ins('vopc', 'v_cmp_lt_u32_e32', s0='30', s1='v4')), + ('s_cbranch_vccz ELSE', 'vccz'), + ('s_mov_b32 s20, src_scc', lambda: ins('sop1', 's_mov_b32', d=20, s0='src_scc')), + ('s_lshl_b32 s23, vcc_lo, 2', lambda: ins('sop2', 's_lshl_b32', d=23, s0='vcc_lo', s1='2')), + ('s_branch JOIN', 'branch'), + ('ELSE:', None), + ('s_mov_b32 s20, src_scc', lambda: ins('sop1', 's_mov_b32', d=20, s0='src_scc')), + ('JOIN:', None), + ('s_cmp_lg_i32 s20, 0', lambda: ins('sopc', 's_cmp_lg_i32', s0='s20', s1='0')), + ('s_cbranch_scc0 AFTER', 'scc0'), + ('v_mov_b32_e32 v1, 60', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='60')), +] + EPILOGUE + + +def program(items=None): + """(code bytes, intended text per instruction). Branch targets are resolved in a second pass.""" + if items is not None: + return assemble(items) + items = [ + ('s_mov_b64 exec, -1', lambda: ins('sop1', 's_mov_b64', d=126, s0='-1')), + ('v_readfirstlane_b32 s20, v5', lambda: ins('vop1', 'v_readfirstlane_b32', d=20, s0='v5')), + ('s_lshr_b32 s20, s20, 7', lambda: ins('sop2', 's_lshr_b32', d=20, s0='s20', s1='7')), + ('s_bfe_u32 s28, s3, 0x40018', lambda: ins('sop2', 's_bfe_u32', d=28, s0='s3', s1='0x40018')), + ('s_lshl_b32 s29, s28, 6', lambda: ins('sop2', 's_lshl_b32', d=29, s0='s28', s1='6')), + ('v_mbcnt_lo_u32_b32 v0, -1, s29', lambda: ins('vop3', 'v_mbcnt_lo_u32_b32', d=0, s0='-1', s1='s29')), + ('v_mbcnt_hi_u32_b32 v0, -1, v0', lambda: ins('vop3', 'v_mbcnt_hi_u32_b32', d=0, s0='-1', s1='v0')), + ('s_and_b32 s21, s20, 1', lambda: ins('sop2', 's_and_b32', d=21, s0='s20', s1='1')), + ('s_mul_i32 s21, s21, 60', lambda: ins('sop2', 's_mul_i32', d=21, s0='s21', s1='60')), + ('s_add_u32 s21, s21, 40', lambda: ins('sop2', 's_add_u32', d=21, s0='s21', s1='40')), + ('s_and_b32 s22, s20, 3', lambda: ins('sop2', 's_and_b32', d=22, s0='s20', s1='3')), + ('s_mul_i32 s22, s22, 20', lambda: ins('sop2', 's_mul_i32', d=22, s0='s22', s1='20')), + ('s_mov_b32 s40, 64', lambda: ins('sop1', 's_mov_b32', d=40, s0='64')), + ('v_cmpx_gt_u32_e32 s21, v0', lambda: ins('vopc', 'v_cmpx_gt_u32_e32', s0='s21', s1='v0')), + ('s_cbranch_execz AFTER', 'execz'), + ('v_cmp_gt_u32_e32 vcc_lo, s22, v0', lambda: ins('vopc', 'v_cmp_gt_u32_e32', s0='s22', s1='v0')), + ('s_and_b64 s[12:13], vcc, exec', lambda: ins('sop2', 's_and_b64', d=12, s0='vcc_lo', s1='exec_lo')), + ('s_cselect_b32 s40, 1, 33', lambda: ins('sop2', 's_cselect_b32', d=40, s0='1', s1='33')), + ('s_cbranch_scc0 AFTER', 'scc0'), + ('s_add_u32 s40, s40, 0x64', lambda: ins('sop2', 's_add_u32', d=40, s0='s40', s1='100')), + ('AFTER:', None), + ('s_mov_b64 exec, -1', lambda: ins('sop1', 's_mov_b64', d=126, s0='-1')), + ('s_mov_b32 m0, 0x80080', lambda: ins('sop1', 's_mov_b32', d=124, s0='0x80080')), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + ('v_mov_b32_e32 v1, s40', lambda: ins('vop1', 'v_mov_b32_e32', d=1, s0='s40')), + ('v_cvt_f32_u32_e32 v2, v0', lambda: ins('vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0')), + ('v_mov_b32_e32 v3, 0', lambda: ins('vop1', 'v_mov_b32_e32', d=3, s0='0')), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v1, v0, v1, v0', lambda: exp(32, ['v1', 'v0', 'v1', 'v0'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), + ] + return assemble(items) + + +def assemble(items): + # pass 1: sizes and label offsets + off, labels, sized = 0, {}, [] + for text, make in items: + if make is None: + labels[text[:-1]] = off + continue + words = make() if callable(make) else [0] + sized.append((off, text, make, len(words))) + off += 4 * len(words) + out, texts = [], [] + for off, text, make, n in sized: + if callable(make): + words = make() + else: + target = labels[text.split()[1]] + words = ins('sopp', 's_branch' if make == 'branch' else 's_cbranch_' + make, imm=(target - off - 4) // 4) + text = '%s label_%#x' % (text.split()[0], target) + out += words + texts.append((off, text)) + return struct.pack('<%dI' % len(out), *out), texts + + +def decoded(code): + off, res = 0, [] + while off + 4 <= len(code): + n, name, asm, _ = D.decode_instruction(code, off) + res.append((off, asm)) + off += n + return res + + +def translate(env): + """Run the translator in a child process (its switches are read at import): HLSL or the refusal text.""" + child = ('import sys; sys.path[:0] = [%r, %r]\n' + 'import gfx2hlsl as G, mesh2hlsl as M\n' + 'code = open(sys.argv[1], "rb").read()\n' + 'try:\n' + ' p = M.MeshPipeline(code, None, M.synth_root(code), user_sgpr=16)\n' + ' sys.stdout.write("OK\\n" + p.hlsl_ms())\n' + 'except G.Unsupported as e:\n' + ' sys.stdout.write("REFUSED %%s\\n" %% e)\n' + % (os.path.join(HERE, '..', 'tools'), os.path.join(HERE, '..', 'tools', 'startup'))) + e = dict(os.environ) + e.pop('X2W_MESH_LANE_SCC', None) + e.pop('X2W_MESH_TEST_DROP', None) + e.pop('X2W_MESH_JOIN_TAINT', None) + e.pop('X2W_MESH_CONFINED_SCC', None) + e.pop('X2W_MESH_SKIP_ADDED', None) + e.update(env) + r = subprocess.run([sys.executable, '-B', '-c', child, BIN], capture_output=True, text=True, env=e) + if r.returncode: + return 'CRASH ' + r.stderr.strip().splitlines()[-1] + return r.stdout + + +def main(): + global BIN + code, texts = program() + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_lane_scc') + os.makedirs(out_dir, exist_ok=True) + BIN = os.path.join(out_dir, 'lane_scc.bin') + with open(BIN, 'wb') as f: + f.write(code) + got = decoded(code) + check('decodes to the intended %d instructions' % len(texts), [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1] if i < len(got) else '?') for i, ((o, t), g) + in enumerate(zip(texts, got + [(0, '?')] * len(texts))) if i >= len(got) or got[i][1] != t)) + on = translate({}) + check('translates with the lowering on', on.startswith('OK'), on[:300]) + check('SCC published per wave and read back', 'x2w_sany[0][wave] = 1u' in on and 'scc = x2w_sany[0][wave]' in on, '') + check('hit scalar s40 restored for a wave with no active lane', 'x2w_any[0][wave] == 0u) s40 = ' in on, '') + off = translate({'X2W_MESH_LANE_SCC': '0'}) + check('negative control: X2W_MESH_LANE_SCC=0 refuses again', + off.startswith('REFUSED branch on an SCC that depends on lane masks'), off[:200]) + nopub = translate({'X2W_MESH_TEST_DROP': 'publish'}) + check('negative control switch: publish dropped', nopub.startswith('OK') and 'x2w_sany[0][wave] = 1u' not in nopub, nopub[:200]) + nores = translate({'X2W_MESH_TEST_DROP': 'restore'}) + check('negative control switch: restore dropped', nores.startswith('OK') and ') s40 = ' not in nores, nores[:200]) + print('program written to %s (difftest: python -B difftest.py %s --groups 4 --seed 1)' % (BIN, BIN)) + # program B: active-uniform SCC inside a per-lane range + code_b, texts_b = program(UNIFORM_B) + BIN = os.path.join(out_dir, 'lane_scc_uniform.bin') + with open(BIN, 'wb') as f: + f.write(code_b) + got = decoded(code_b) + check('B decodes to the intended %d instructions' % len(texts_b), [t for _, t in got] == [t for _, t in texts_b], + ' | '.join('%x %s / %s' % (o, t, g) for (o, t), (_, g) in zip(texts_b, got) if t != g)) + on = translate({}) + check('B translates as a per-lane branch, no publish', on.startswith('OK') and 'x2w_sany' not in on, on[:300]) + off = translate({'X2W_MESH_LANE_SCC': '0'}) + check('B negative control: X2W_MESH_LANE_SCC=0 refuses again', + off.startswith('REFUSED branch on an SCC that depends on lane masks'), off[:200]) + print('program B written to %s' % BIN) + # program C: publish inside a formerly per-lane range (made group-uniform) + taint merged at the join + code_c, texts_c = program(SPLIT_C) + BIN = os.path.join(out_dir, 'lane_scc_split.bin') + with open(BIN, 'wb') as f: + f.write(code_c) + got = decoded(code_c) + check('C decodes to the intended %d instructions' % len(texts_c), [t for _, t in got] == [t for _, t in texts_c], + ' | '.join('%x %s / %s' % (o, t, g) for (o, t), (_, g) in zip(texts_c, got) if t != g)) + on = translate({}) + check('C translates: range made group-uniform, SCC published', + on.startswith('OK') and 'x2w_any[0][wave] = 1u' in on and 'x2w_sany[0][wave] = 1u' in on + and 'scc = x2w_sany[0][wave]' in on, on[:300]) + off = translate({'X2W_MESH_LANE_SCC': '0'}) + check('C negative control: X2W_MESH_LANE_SCC=0 refuses again', + off.startswith('REFUSED branch on an SCC that depends on lane masks'), off[:200]) + lin = translate({'X2W_MESH_JOIN_TAINT': '0'}) + # the linear scan carries the s_lshl's active-uniform SCC into the ELSE side and takes the branch per lane + # without a publish: a WRONG translation (the WARP difftest of it must FAIL) + check('C negative control: X2W_MESH_JOIN_TAINT=0 (linear taint) translates WITHOUT the publish', + lin.startswith('OK') and 'x2w_sany' not in lin, lin[:200]) + print('program C written to %s (difftest also with X2W_MESH_TEST_DROP=publish: must FAIL)' % BIN) + # program D: an SCC of the inactive lanes' bits (saved exec & ~exec) is not active-uniform: published + code_d, texts_d = program(ANDN2_D) + BIN = os.path.join(out_dir, 'lane_scc_andn2.bin') + with open(BIN, 'wb') as f: + f.write(code_d) + got = decoded(code_d) + check('D decodes to the intended %d instructions' % len(texts_d), [t for _, t in got] == [t for _, t in texts_d], + ' | '.join('%x %s / %s' % (o, t, g) for (o, t), (_, g) in zip(texts_d, got) if t != g)) + on = translate({}) + check('D translates with the SCC published (not taken per lane)', on.startswith('OK') and 'x2w_sany' in on, on[:300]) + loose = translate({'X2W_MESH_CONFINED_SCC': '0'}) + check('D negative control: X2W_MESH_CONFINED_SCC=0 takes the branch per lane (no publish)', + loose.startswith('OK') and 'x2w_sany' not in loose, loose[:200]) + print('program D written to %s (difftest also with X2W_MESH_CONFINED_SCC=0: must FAIL)' % BIN) + # program E: nested group-uniform ranges; the outer skip jumps over the inner publish barrier + code_e, texts_e = program(NESTED_E) + BIN = os.path.join(out_dir, 'lane_scc_nested.bin') + with open(BIN, 'wb') as f: + f.write(code_e) + got = decoded(code_e) + check('E decodes to the intended %d instructions' % len(texts_e), [t for _, t in got] == [t for _, t in texts_e], + ' | '.join('%x %s / %s' % (o, t, g) for (o, t), (_, g) in zip(texts_e, got) if t != g)) + on = translate({}) + check('E translates: two group branches, s40 and s41 restored', + on.startswith('OK') and 'x2w_any[1][wave] = 1u' in on and ') s40 = ' in on and ') s41 = ' in on, on[:300]) + old = translate({'X2W_MESH_SKIP_ADDED': '0'}) + check('E negative control: X2W_MESH_SKIP_ADDED=0 refuses (barrier inside the outer range)', + old.startswith('REFUSED s_barrier inside a group-uniform execz range'), old[:200]) + print('program E written to %s (difftest also with X2W_MESH_TEST_DROP=restore: must FAIL)' % BIN) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_literal_flow_check.py b/tests/startup_mesh_literal_flow_check.py new file mode 100644 index 0000000000..65b6985b21 --- /dev/null +++ b/tests/startup_mesh_literal_flow_check.py @@ -0,0 +1,99 @@ +"""Offline proofs for scalar literal addressing and SCC-dead SGPR exchange lowering.""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import mesh2hlsl as M + + +def stage(*asm): + s = M.MeshStage.__new__(M.MeshStage) + s.ins = [(4 * i, 4, line.split()[0], line) for i, line in enumerate(asm)] + s.pc = s.ins[-1][0] + s.sym = {} + return s + + +def check_literals(): + prefix = ['s_movk_i32 s8, 0xffff', 's_mov_b32 s12, s8'] + end = 's_endpgm' + assert stage(*prefix, end).copied_constant(12) == 0xffffffff + assert stage(*prefix, 's_addk_i32 s12, 1', end).copied_constant(12) is None + assert stage('s_cbranch_scc0 label_0xc', *prefix, end).copied_constant(12) is None + assert stage('s_mov_b32 s8, 24', 's_cbranch_scc0 label_0x10', 's_mov_b32 s8, 16', + 's_branch label_0x10', end).copied_constant(8) is None + assert stage('s_mov_b32 s8, 24', 'v_cmp_gt_f32_e64 s7, 0, v5', end).copied_constant(8) is None + + extract = 's_bfe_u32 s8, s2, 0x30004' + shift = 's_lshl_b32 s8, s8, 2' + load = 's_buffer_load_dword s4, s[12:15], s8' + assert stage(extract, shift, load, load).scalar_literal_index_bits('s8') == 3 + assert stage('s_branch label_0x8', extract, shift, load).scalar_literal_index_bits('s8') is None + assert stage(extract, shift, load.replace('s4,', 's8,'), load).scalar_literal_index_bits('s8') is None + assert stage(extract, shift.replace(', 2', ', 4'), load).scalar_literal_index_bits('s8') is None + + +def check_exchanges(): + a = 's_xor_b32 s4, s4, s7' + b = 's_xor_b32 s7, s7, s4' + neutral = 'v_mul_f32_e32 v1, v3, v2' + s = stage(a, neutral, b, a, 's_endpgm') + assert s.lower_pair_swaps() == {12} + regs = {'s4': 0xcabb1e, 's7': 0xabcdef} + for _, _, name, asm in s.ins: + if name == 's_mov_b32': + d, source = M.parse(asm)[1] + regs[d] = regs[source] + assert regs['s4'] == 0xabcdef and regs['s7'] == 0xcabb1e + assert not stage(a, 's_mov_b32 s6, s7', b, a).lower_pair_swaps() + assert not stage('s_branch label_0x8', a, b, a).lower_pair_swaps() + assert not stage(a, 's_mov_b32 s5, src_scc', b, a).lower_pair_swaps() + s = stage(a, b, a, 's_cbranch_scc1 label_0x10', 's_endpgm') + s.swap_scc = s.lower_pair_swaps() + try: + s.check_scc(set(), set()) + except M.Unsupported: + pass + else: + raise AssertionError('exchange with live SCC was accepted') + + +def check_conflict_copy(): + s = stage('s_mov_b64 s[16:17], s[64:65]') + s.sym = {64: ('conflict',), 65: ('conflict',)} + s.masks, s.used_s, s.exec_off = set(), set(), {16, 17} + s.execzero = {16: 1, 17: 1} + lines = [] + s.emit = lines.append + s.scalar_inner('s_mov_b64', ['s[16:17]', 's[64:65]']) + assert lines == ['s16 = s64;', 's17 = s65;'] + assert not s.exec_off and not s.execzero + for reg in (16, 17): + assert s.sym[reg] == ('conflict',) + try: + s.S(reg) + except M.Unsupported as refusal: + assert 'holding conflict' in str(refusal) + else: + raise AssertionError('unresolved SGPR copy accepted as a number') + + s.sym = {65: ('conflict',)} + s.masks = {64} + lines.clear() + s.scalar_inner('s_mov_b64', ['s[16:17]', 's[64:65]']) + assert 16 in s.masks and s.sym[17] == ('conflict',) + assert lines[-1] == 's17 = s65;' + assert 's64' in lines[0] and '& 1' in lines[0] + + s.sym = {64: ('conflict',), 65: ('conflict',)} + s.masks.clear() + lines.clear() + s.scalar_inner('s_mov_b64', ['s[65:66]', 's[64:65]']) + assert lines == ['s66 = s65;', 's65 = s64;'] + + +if __name__ == '__main__': + check_literals() + check_exchanges() + check_conflict_copy() + print('Scalar literal copy/bounds and XOR exchange controls passed') diff --git a/tests/startup_mesh_restored_scalar_check.py b/tests/startup_mesh_restored_scalar_check.py new file mode 100644 index 0000000000..3cf7003d70 --- /dev/null +++ b/tests/startup_mesh_restored_scalar_check.py @@ -0,0 +1,80 @@ +"""Check two refinements of the skipped-range scalar rule of tools/startup/mesh2hlsl.py (X2W_MESH_RESTORED_SCALARS):""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 + +I, ins, exp = E.I, E.ins, E.exp + +HEAD = E.PROLOGUE + [ + I('s_mov_b32 s35, s22', 'sop1', 's_mov_b32', d=35, s0='s22'), + I('v_mov_b32_e32 v6, s21', 'vop1', 'v_mov_b32_e32', d=6, s0='s21'), + E.CMPX_N, + ('s_cbranch_execz AFTER', 'execz'), + I('v_cmp_lt_u32_e32 vcc_lo, 50, v6', 'vopc', 'v_cmp_lt_u32_e32', s0='50', s1='v6'), + ('s_cbranch_vccz INNER', 'vccz'), +] +ZERO = I('s_mov_b32 s35, 0', 'sop1', 's_mov_b32', d=35, s0='0') +TAIL = [ + ('AFTER:', None), + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('s_mov_b32 m0, 0x80080', 'sop1', 's_mov_b32', d=124, s0='0x80080'), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + I('v_cvt_f32_u32_e32 v2, v0', 'vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0'), + I('v_mov_b32_e32 v3, 0', 'vop1', 'v_mov_b32_e32', d=3, s0='0'), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v1, v0, v4, v0', lambda: exp(32, ['v1', 'v0', 'v4', 'v0'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] +V4_S35 = I('v_mov_b32_e32 v4, s35', 'vop1', 'v_mov_b32_e32', d=4, s0='s35') +CMP64 = I('v_cmp_gt_u32_e64 s34, s22, v0', 'vop3', 'v_cmp_gt_u32_e64', d=34, s0='s22', s1='v0') +CND = I('v_cndmask_b32_e64 v4, 0, 1, s34', 'vop3', 'v_cndmask_b32_e64', d=4, s0='0', s1='1', s2='s34') +SAVE_MASK = I('v_cmp_gt_u32_e64 s34, s23, v0', 'vop3', 'v_cmp_gt_u32_e64', d=34, s0='s23', s1='v0') + +PROGRAMS = { + 'shuffle': (True, HEAD + [I('s_mov_b32 s33, s35', 'sop1', 's_mov_b32', d=33, s0='s35'), ZERO, E.V1_9, + I('s_mov_b32 s35, s33', 'sop1', 's_mov_b32', d=35, s0='s33'), ('INNER:', None)] + + [V4_S35] + TAIL), + 'masked': (True, HEAD + [ZERO, E.V1_9, ('INNER:', None), CMP64, + I('s_and_b64 s[12:13], s[34:35], exec', 'sop2', 's_and_b64', d=12, s0='s34', s1='exec_lo'), + I('v_cndmask_b32_e64 v4, 0, 1, s12', 'vop3', 'v_cndmask_b32_e64', d=4, s0='0', s1='1', s2='s12')] + + TAIL), + 'live': (False, HEAD + [ZERO, E.V1_9, ('INNER:', None), V4_S35] + TAIL), + 'read': (False, E.PROLOGUE + [SAVE_MASK] + HEAD[len(E.PROLOGUE):] + [ZERO, E.V1_9, ('INNER:', None), CND] + TAIL), +} +OLD = 'REFUSED scalar s35 written in the per-lane skipped range' + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_restored_scalar') + os.makedirs(out_dir, exist_ok=True) + for name, (accept, items) in PROGRAMS.items(): + code, texts = E.assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + E.check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = E.translate(path, {'X2W_MESH_RESTORED_SCALARS': '1'}) + if accept: + E.check('%s: translates with the rule on' % name, on.startswith('OK'), on[:300]) + off = E.translate(path, {'X2W_MESH_RESTORED_SCALARS': '0'}) + E.check('%s: negative control X2W_MESH_RESTORED_SCALARS=0 refuses again' % name, off.startswith(OLD), off[:200]) + else: + E.check('%s: still refused with the rule on' % name, on.startswith(OLD), on[:200]) + print('programs written to %s' % out_dir) + if E.failures: + print('%d check(s) failed' % len(E.failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_rtv_variant_check.py b/tests/startup_mesh_rtv_variant_check.py new file mode 100644 index 0000000000..d6406e5a88 --- /dev/null +++ b/tests/startup_mesh_rtv_variant_check.py @@ -0,0 +1,188 @@ +"""Check the RTV variant request of tools/startup/mesh2hlsl.py translate_request: req_.rtv holds +`rtv1 ` with V = fnv(that text) (gfx2hlsl.translate_request's contract; the mesh runtime +publishes it for a bound integer or 32-bit float target, d3d12_mesh.inl). The variant takes the base request's +blobs, checked against the base key; its pixel exports follow the target formats (Pipeline.mrt_kind) and its +manifest carries the rtv1 line. + +usage: startup_mesh_rtv_variant_check.py [--dxc] + +Hand-assembled gfx1013 programs (no title bytes; encoded field by field with the encoder of +tests/startup_mesh_exec_off_check.py, the decoded text compared with the intended text): an NGG mesh stage +(GS_ALLOC_REQ, pos0, param0, primitive export) and a pixel stage `v_mov_b32 v0, 0x3f800000; v_mov_b32 v1, 0x40000000; +exp mrt0 v0, v1, off, off done vm`. Root: the RTS0 blob of tests/startup_mesh_heap_sampler_check.py. +Without --dxc the DXC step of translate_to is stubbed (pure Python); with --dxc both stages compile. + + BASE (accept): no .rtv -> exports F(x), no rtv1 line, no mrtbits source + R32_FLOAT (accept): `rtv1 41` -> mrt0 F((x) ^ udN), `udsrc N mrtbits`, the rtv1 line; mesh HLSL unchanged + R32_UINT (accept): `rtv1 42` -> mrt0 written as uint4 words + UNORM8 (accept): `rtv1 28` -> pixel HLSL identical to the base (only 32-bit targets change) + negative controls (refuse): file name not fnv(text); malformed text; base key not the blobs' key; + a variant of a depth-only base (no pixel stage) +""" +import os +import shutil +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, '..', 'tools')) +sys.path.insert(0, os.path.join(HERE, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_mesh_exec_off_check import I, assemble, decoded, exp, ins # noqa: E402 (the same encoder) +from startup_mesh_heap_sampler_check import root_blob # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + str(detail)}") + if not condition: + failures.append(label) + + +MESH = [ + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), + I('v_readfirstlane_b32 s20, v5', 'vop1', 'v_readfirstlane_b32', d=20, s0='v5'), + I('s_lshr_b32 s20, s20, 7', 'sop2', 's_lshr_b32', d=20, s0='s20', s1='7'), + I('s_bfe_u32 s28, s3, 0x40018', 'sop2', 's_bfe_u32', d=28, s0='s3', s1='0x40018'), + I('s_lshl_b32 s29, s28, 6', 'sop2', 's_lshl_b32', d=29, s0='s28', s1='6'), + I('v_mbcnt_lo_u32_b32 v0, -1, s29', 'vop3', 'v_mbcnt_lo_u32_b32', d=0, s0='-1', s1='s29'), + I('v_mbcnt_hi_u32_b32 v0, -1, v0', 'vop3', 'v_mbcnt_hi_u32_b32', d=0, s0='-1', s1='v0'), + I('v_mov_b32_e32 v4, 0', 'vop1', 'v_mov_b32_e32', d=4, s0='0'), + I('s_mov_b32 m0, 0x80080', 'sop1', 's_mov_b32', d=124, s0='0x80080'), + ('s_sendmsg 0x9', lambda: ins('sopp', 's_sendmsg', imm=9)), + I('v_cvt_f32_u32_e32 v2, v0', 'vop1', 'v_cvt_f32_u32_e32', d=2, s0='v0'), + I('v_mov_b32_e32 v3, 0', 'vop1', 'v_mov_b32_e32', d=3, s0='0'), + ('exp pos0 v2, v2, v2, v2 done', lambda: exp(12, ['v2', 'v2', 'v2', 'v2'], True)), + ('exp param0 v2, v2, v2, v2', lambda: exp(32, ['v2', 'v2', 'v2', 'v2'])), + ('exp target_20 v3, off, off, off done', lambda: exp(20, ['v3', None, None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] + + +def exp_vm(target, vals, done=False): + w = exp(target, vals, done) + return [w[0] | (1 << 12), w[1]] # VM (valid mask), bit 12 of word 0 + + +PIXEL = [ + I('v_mov_b32_e32 v0, 0x3f800000', 'vop1', 'v_mov_b32_e32', d=0, s0='0x3f800000'), + I('v_mov_b32_e32 v1, 0x40000000', 'vop1', 'v_mov_b32_e32', d=1, s0='0x40000000'), + ('exp mrt0 v0, v1, off, off done vm', lambda: exp_vm(0, ['v0', 'v1', None, None], True)), + ('s_endpgm', lambda: ins('sopp', 's_endpgm', imm=0)), +] + + +def code_of(name, items): + code, texts = assemble(items) + got = decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + return code + + +def write_request(out_dir, key, a, b, root): + for ext, data in (('.a', a), ('.b', b), ('.root', root)): + with open(os.path.join(out_dir, 'req_%016x%s' % (key, ext)), 'wb') as f: + f.write(data) + return key + + +def write_rtv(out_dir, text, key=None): + key = G.fnv(text.encode('ascii')) if key is None else key + with open(os.path.join(out_dir, 'req_%016x.rtv' % key), 'w', encoding='ascii', newline='') as f: + f.write(text) + return key + + +def outputs(out_dir, key): + name = os.path.join(out_dir, '%016x' % key) + res = [] + for ext in ('.ms.hlsl', '.ps.hlsl', '.txt'): + res.append(open(name + ext).read() if os.path.isfile(name + ext) else '') + return res + + +def main(): + if '--dxc' not in sys.argv[1:]: + M.compile_hlsl = lambda path, profile, out: (0, '') # pure Python: the HLSL text is checked, not compiled + out_dir = os.path.join(HERE, '..', 'out', 'startup_mesh_rtv_variant') + shutil.rmtree(out_dir, ignore_errors=True) + os.makedirs(out_dir) + ms, ps, root = code_of('mesh', MESH), code_of('pixel', PIXEL), root_blob() + check('mesh: is_mesh', M.is_mesh(ms) and not M.is_mesh(ps), '') + base = write_request(out_dir, G.pipeline_key(ps, ms, root), ps, ms, root) # runtime order: .a pixel, .b mesh + + r = M.translate_request(out_dir, base) + b_ms, b_ps, b_txt = outputs(out_dir, base) + check('base: translates', r == 'ok', r) + check('base: mrt0 is a plain float export', 'F(' in b_ps and '^ ud' not in b_ps, + [l.strip() for l in b_ps.splitlines() if 'o.mrt0' in l]) + check('base: no rtv1 line, no mrtbits source', 'rtv1' not in b_txt and 'mrtbits' not in b_txt, b_txt) + + text = 'rtv1 %d 41' % base + v = write_rtv(out_dir, text) + r = M.translate_request(out_dir, v) + v_ms, v_ps, v_txt = outputs(out_dir, v) + src = [l for l in v_txt.splitlines() if l.startswith('udsrc ') and l.endswith(' mrtbits')] + ud = src[0].split()[1] if src else '?' + mrt0 = [l.strip() for l in v_ps.splitlines() if 'o.mrt0' in l] + check('R32_FLOAT: translates', r == 'ok', r) + check('R32_FLOAT: manifest carries `%s`' % text, v_txt.endswith('\n' + text + '\n'), v_txt[-200:]) + check('R32_FLOAT: manifest names the mrtbits source', len(src) == 1, v_txt) + check('R32_FLOAT: mrt0 exports the register bits F((x) ^ ud%s)' % ud, + len(mrt0) == 1 and mrt0[0].count('^ ud%s)' % ud) == 2 and 'F((' in mrt0[0], mrt0) + # the stages share one entry constant buffer: the mesh stage declares the added source, nothing else changes + grown = b_ms.replace(' uint ud%d; };' % (int(ud) - 1), ' uint ud%d; uint ud%s; };' % (int(ud) - 1, ud), 1) \ + if ud.isdigit() and int(ud) > 0 else None + check('R32_FLOAT: mesh HLSL equals the base but for the shared entry cbuffer gaining ud%s' % ud, + v_ms == grown and v_ms != b_ms, [l for l in v_ms.splitlines() if l.startswith('cbuffer entry')]) + check('R32_FLOAT: written under the variant key only', os.path.isfile(os.path.join(out_dir, '%016x.txt' % v)) + and outputs(out_dir, base)[2] == b_txt, '') + + v = write_rtv(out_dir, 'rtv1 %d 42' % base) + r = M.translate_request(out_dir, v) + u_ps = outputs(out_dir, v)[1] + mrt0 = [l.strip() for l in u_ps.splitlines() if 'o.mrt0' in l] + check('R32_UINT: translates', r == 'ok', r) + check('R32_UINT: mrt0 is a uint4 of the register words', len(mrt0) == 1 and 'uint4(' in mrt0[0] + and '^ ud' not in mrt0[0], mrt0) + + v = write_rtv(out_dir, 'rtv1 %d 28' % base) + r = M.translate_request(out_dir, v) + n_ps, n_txt = outputs(out_dir, v)[1:] + check('UNORM8: translates', r == 'ok', r) + check('UNORM8: pixel HLSL equals the base (negative control: only 32-bit targets change)', n_ps == b_ps, '') + check('UNORM8: manifest carries the rtv1 line, no mrtbits', n_txt.endswith('rtv1 %d 28\n' % base) + and 'mrtbits' not in n_txt, n_txt[-200:]) + + # negative controls + v = write_rtv(out_dir, text, key=G.fnv(text.encode('ascii')) ^ 1) + r = M.translate_request(out_dir, v) + check('negative: file name not fnv(text) refused', r == 'unsupported: invalid RTV variant request', r) + check('negative: nothing written for it', not any(os.path.isfile(os.path.join(out_dir, '%016x%s' % (v, e))) + for e in ('.txt', '.ps.hlsl', '.fail')), '') + v = write_rtv(out_dir, text + '\n') + r = M.translate_request(out_dir, v) + check('negative: malformed text (trailing newline) refused', r == 'unsupported: invalid RTV variant request', r) + other = write_request(out_dir, base ^ 0x5a5a, ps, ms, root) # the base blobs under a key that is not theirs + v = write_rtv(out_dir, 'rtv1 %d 41' % other) + r = M.translate_request(out_dir, v) + check('negative: base key not the blobs\' key refused', r == 'unsupported: RTV variant source key mismatch', r) + depth = write_request(out_dir, G.pipeline_key(b'', ms, root), b'', ms, root) + check('depth-only base: translates without a variant', M.translate_request(out_dir, depth) == 'ok', '') + v = write_rtv(out_dir, 'rtv1 %d 41' % depth) + r = M.translate_request(out_dir, v) + check('negative: variant of a depth-only base refused', + r == 'unsupported: RTV variant of a mesh pipeline without a pixel stage', r) + + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_salu_check.py b/tests/startup_mesh_salu_check.py new file mode 100644 index 0000000000..4ba27e8080 --- /dev/null +++ b/tests/startup_mesh_salu_check.py @@ -0,0 +1,122 @@ +"""Check plain scalar ALU forms of tools/startup/gfx2hlsl.py (SCA) on the mesh stage: s_sext_i32_i8 / s_sext_i32_i16,""" +import os +import re +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 +from startup_mesh_exec_restore_check import I # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +def translate(path, prelude=''): + child = ('import sys; sys.path[:0] = [%r, %r]\n' + 'import gfx2hlsl as G, mesh2hlsl as M\n%s\n' + 'code = open(sys.argv[1], "rb").read()\n' + 'try:\n' + ' p = M.MeshPipeline(code, None, M.synth_root(code), user_sgpr=16)\n' + ' sys.stdout.write("OK\\n" + p.hlsl_ms())\n' + 'except G.Unsupported as e:\n' + ' sys.stdout.write("REFUSED %%s\\n" %% e)\n' + % (os.path.join(HERE, '..', 'tools'), os.path.join(HERE, '..', 'tools', 'startup'), prelude)) + r = subprocess.run([sys.executable, '-B', '-c', child, path], capture_output=True, text=True) + return 'CRASH ' + (r.stderr.strip().splitlines() or ['?'])[-1] if r.returncode else r.stdout + + +def hlsl_eval(expr, x): + """Evaluate the emitted `uint(int(sN << k) >> k)` for the 32-bit value x (int shifts are arithmetic in HLSL).""" + m = re.fullmatch(r'uint\(int\(\(?s\d+\)? << (\d+)\) >> (\d+)\)', expr) + if not m or m.group(1) != m.group(2): + return None + k = int(m.group(1)) + v = (x << k) & 0xffffffff + v = v - (1 << 32) if v & 0x80000000 else v + return (v >> k) & 0xffffffff + + +PROGRAMS = { + 'sext': E.PROLOGUE + [ + I('s_add_u32 s24, s22, 0x7ff0', 'sop2', 's_add_u32', d=24, s0='s22', s1='0x7ff0'), + I('s_sext_i32_i16 s25, s24', 'sop1', 's_sext_i32_i16', d=25, s0='s24'), + I('s_add_u32 s26, s22, 0x70', 'sop2', 's_add_u32', d=26, s0='s22', s1='0x70'), + I('s_sext_i32_i8 s27, s26', 'sop1', 's_sext_i32_i8', d=27, s0='s26'), + I('v_mov_b32_e32 v1, s25', 'vop1', 'v_mov_b32_e32', d=1, s0='s25'), + I('v_mov_b32_e32 v4, s27', 'vop1', 'v_mov_b32_e32', d=4, s0='s27')] + E.EPILOGUE, + 'bcnt': E.PROLOGUE + [ + I('s_or_b32 s24, s22, 0xf00', 'sop2', 's_or_b32', d=24, s0='s22', s1='0xf00'), + I('s_bcnt1_i32_b32 s25, s24', 'sop1', 's_bcnt1_i32_b32', d=25, s0='s24'), + I('s_and_b32 s27, s22, 0x100', 'sop2', 's_and_b32', d=27, s0='s22', s1='0x100'), + I('s_bcnt1_i32_b32 s28, s27', 'sop1', 's_bcnt1_i32_b32', d=28, s0='s27'), + I('s_cselect_b32 s26, 7, 9', 'sop2', 's_cselect_b32', d=26, s0='7', s1='9'), + I('s_lshl_b32 s29, s25, 16', 'sop2', 's_lshl_b32', d=29, s0='s25', s1='16'), + I('v_mov_b32_e32 v1, s29', 'vop1', 'v_mov_b32_e32', d=1, s0='s29'), + I('v_mov_b32_e32 v4, s26', 'vop1', 'v_mov_b32_e32', d=4, s0='s26')] + E.EPILOGUE, + 'bcntmask': E.PROLOGUE + [ + I('v_cmp_gt_u32_e64 s30, s21, v0', 'vop3', 'v_cmp_gt_u32_e64', d=30, s0='s21', s1='v0'), + I('s_bcnt1_i32_b32 s25, s30', 'sop1', 's_bcnt1_i32_b32', d=25, s0='s30'), + I('v_mov_b32_e32 v1, s25', 'vop1', 'v_mov_b32_e32', d=1, s0='s25')] + E.EPILOGUE, +} + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_salu') + os.makedirs(out_dir, exist_ok=True) + for name, items in PROGRAMS.items(): + code, texts = E.assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = translate(path) + if name == 'bcnt': + line = re.search(r'^\s*s25 = (.*);', on, re.M) if on.startswith('OK') else None + check('bcnt: translates, s25 = countbits(...)', bool(line) and line.group(1).startswith('countbits('), on[:3000]) + check('bcnt: SCC of the second count is set from its result', 'scc = (s28 != 0);' in on or 'scc = s28 != 0;' in on + or re.search(r'scc = .*countbits', on) is not None, on[:3000]) + off = translate(path, "del G.SCA['s_bcnt1_i32_b32']") + check('bcnt: negative control (no SCA entry) refuses s_bcnt1_i32_b32', + off.startswith('REFUSED') and 's_bcnt1_i32_b32' in off.splitlines()[0], off[:200]) + continue + if name == 'bcntmask': + check('bcntmask: refused (a count of a lane mask)', on.startswith('REFUSED') and 'lane mask' in on.splitlines()[0], + on[:200]) + continue + check('sext: translates', on.startswith('OK'), on[:300]) + e16 = re.search(r'^\s*s25 = (uint\(.*\));', on, re.M) + e8 = re.search(r'^\s*s27 = (uint\(.*\));', on, re.M) + check('sext: s25 / s27 are the arithmetic-shift forms', bool(e16 and e8), on[:3000]) + if e16 and e8: + want16 = [0x7ff0, 0xffff8004, 0xffff8018, 0xffff802c] + want8 = [0x70, 0xffffff84, 0xffffff98, 0xffffffac] + got16 = [hlsl_eval(e16.group(1), t + 0x7ff0) for t in (0, 20, 40, 60)] + got8 = [hlsl_eval(e8.group(1), t + 0x70) for t in (0, 20, 40, 60)] + check('sext: s_sext_i32_i16 gives %s' % [hex(w) for w in want16], got16 == want16, + '%s from %s' % (got16, e16.group(1))) + check('sext: s_sext_i32_i8 gives %s' % [hex(w) for w in want8], got8 == want8, + '%s from %s' % (got8, e8.group(1))) + off = translate(path, "del G.SCA['s_sext_i32_i16'], G.SCA['s_sext_i32_i8']") + check('sext: negative control (no SCA entries) refuses s_sext_i32_i16', + off.startswith('REFUSED') and 's_sext_i32_i16' in off.splitlines()[0], off[:200]) + print('programs written to %s (difftest: python -B difftest.py --program /sext.bin)' % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_spi_input_check.py b/tests/startup_mesh_spi_input_check.py new file mode 100644 index 0000000000..ca8e715319 --- /dev/null +++ b/tests/startup_mesh_spi_input_check.py @@ -0,0 +1,116 @@ +"""SPI pixel inputs in mesh pipelines, and the position inputs POS_X/Y/Z/W_FLOAT (gfx2hlsl spi_inputs/spi_reads). + +The mapping of entry VGPRs to SPI inputs (ps_input_layout, Mesa ac_shader_util.c order) used to live in +G.Pipeline.__init__, which MeshPipeline does not call, so a mesh pair's pixel stage refused every SPI input read. +Both pipelines now call the shared Pipeline.spi_inputs / spi_reads. + +Synthetic pixel stage `exp mrt0 vA, vB, vC, vD done vm` (entry reads only); the mesh stage is a stub (this checks +the pixel stage). ENA 0x8c02 is a layout that enables all three position forms: persp_center v0-v1, +pos_z_float v2, pos_w_float v3, pos_fixed_pt v4. +POS_W_FLOAT is SV_Position.w: Mesa ac_nir_lower_intrinsics_to_args.c loads frag_coord_w_rcp from it, +nir_builder.c sets gl_FragCoord.w = frcp(frag_coord_w_rcp), and vkd3d-shader spirv.c (frag_coord_fixup) gives +D3D SV_Position.w = 1 / gl_FragCoord.w. + +Controls: without ENA the mesh translate_to refuses the read (the old behaviour); the barycentric persp_center read +as a value is refused; with a per-sample barycentric enabled the position read is refused; the draw pipeline lowers +the same inputs. translate_request passes req_.psin through (translate_to replaced by a recorder). +""" +import os +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +import mesh2hlsl as M # noqa: E402 +from startup_image_3d_check import VS_WORDS, root_blob # noqa: E402 + + +def pixel_words(a, b, c, d): + return struct.pack('.psin reaches translate_to + seen = [] + saved_to, saved_is = M.translate_to, M.is_mesh + M.translate_to = lambda out, key, ms, p, root, **k: seen.append(k.get('ps_hw_inputs')) or 'recorded' + M.is_mesh = lambda code: code == b'MESH' + try: + with tempfile.TemporaryDirectory() as tmp: + base = os.path.join(tmp, 'req_%016x' % 1) + for ext, blob in (('.a', b'MESH'), ('.b', ps), ('.root', root_blob())): + open(base + ext, 'wb').write(blob) + assert M.translate_request(tmp, 1) == 'recorded' and seen[-1] is None, seen + with open(base + '.psin', 'w', newline='\n') as f: + f.write('spi_ps_input 1 00008c02 00008c02\n') + assert M.translate_request(tmp, 1) == 'recorded' and seen[-1] == (0x8c02, 0x8c02), seen + with open(base + '.psin', 'w', newline='\n') as f: + f.write('spi_ps_input 1 8c02 8c02\n') + assert M.translate_request(tmp, 1) == 'unsupported: invalid SPI input file' + finally: + M.translate_to, M.is_mesh = saved_to, saved_is + print('mesh SPI inputs: pos_z/pos_w/pos_fixed_pt (ENA 0x8c02) and pos_x/pos_y lowered in mesh and draw ' + 'pipelines; %s; 3 refusals; .psin passed through translate_request' % compiled) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_mesh_spill_check.py b/tests/startup_mesh_spill_check.py new file mode 100644 index 0000000000..42c07c08c0 --- /dev/null +++ b/tests/startup_mesh_spill_check.py @@ -0,0 +1,128 @@ +"""Check the SGPR spill lowering of tools/startup/mesh2hlsl.py (MeshStage.lower_spills): v_writelane_b32 /""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 (encoder, prologue, epilogue, translate()) +from startup_mesh_exec_restore_check import I # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +def WL(v, s, lane): + return I('v_writelane_b32 v%d, %s, %s' % (v, s, lane), 'vop3', 'v_writelane_b32', d=v, s0=s, s1=str(lane)) + + +def RL(s, v, lane): + return I('v_readlane_b32 s%d, v%d, %s' % (s, v, lane), 'vop3', 'v_readlane_b32', d=s, s0='v%d' % v, s1=str(lane)) + + +def MOVS(d, s): + return I('s_mov_b32 s%d, %s' % (d, s), 'sop1', 's_mov_b32', d=d, s0=s) + + +def VMOV(d, s): + return I('v_mov_b32_e32 v%d, %s' % (d, s), 'vop1', 'v_mov_b32_e32', d=d, s0=s) + + +EXECZ_AFTER = ('s_cbranch_execz AFTER', 'execz') +CLEAR30 = I('s_mov_b64 s[30:31], 0', 'sop1', 's_mov_b64', d=30, s0='0') +P, EP = E.PROLOGUE, E.EPILOGUE +PROGRAMS = { + 'spill32': ('ok', P + [I('s_mul_i32 s24, s22, 3', 'sop2', 's_mul_i32', d=24, s0='s22', s1='3'), + WL(40, 's24', 5), WL(40, '7', 6), MOVS(24, '0'), RL(25, 40, 5), RL(26, 40, 6), + VMOV(1, 's25'), VMOV(4, 's26')] + EP), + 'spillpair': ('ok', P + [I('s_mul_i32 s24, s22, 3', 'sop2', 's_mul_i32', d=24, s0='s22', s1='3'), + I('s_add_u32 s25, s22, 1', 'sop2', 's_add_u32', d=25, s0='s22', s1='1'), + WL(40, 's24', 2), WL(40, 's25', 3), I('s_mov_b64 s[24:25], 0', 'sop1', 's_mov_b64', d=24, + s0='0'), + RL(26, 40, 2), RL(27, 40, 3), VMOV(1, 's26'), VMOV(4, 's27')] + EP), + 'spillexec': ('ok', P + [E.CMPX_N, E.SAVE, EXECZ_AFTER, WL(40, 's30', 0), WL(40, 's31', 1), CLEAR30, E.CMPX_T, + E.V1_9, RL(30, 40, 0), RL(31, 40, 1), E.RESTORE, E.V4_7] + EP), + 'spillwave': ('ok', P + [WL(40, 's23', 2), E.CMPX_N, ('s_cbranch_execz J', 'execz'), WL(40, '11', 2), ('J:', None), + I('s_mov_b64 exec, -1', 'sop1', 's_mov_b64', d=126, s0='-1'), RL(25, 40, 2), + VMOV(1, 's25')] + EP), + 'datause': ('also used by v_mov_b32', P + [WL(40, 's23', 0), VMOV(1, 'v40')] + EP), + 'lanesgpr': ('is not a constant lane', P + [WL(40, 's23', 's22'), RL(25, 40, 0), VMOV(1, 's25')] + EP), + 'unwritten': ('which no v_writelane_b32 writes', P + [ + I('s_cmp_eq_u32 s22, 0', 'sopc', 's_cmp_eq_u32', s0='s22', s1='0'), ('s_cbranch_scc1 J', 'scc1'), + WL(40, 's23', 3), ('J:', None), RL(25, 40, 3), VMOV(1, 's25')] + EP), + 'vcchalf': ('v_writelane_b32 of vcc_lo alone', P + [ + VMOV(6, 's22'), I('v_cmp_lt_u32_e32 vcc_lo, 30, v6', 'vopc', 'v_cmp_lt_u32_e32', s0='30', s1='v6'), + WL(40, 'vcc_lo', 0), RL(25, 40, 0), VMOV(1, 's25')] + EP), + 'spillhalves': ('ok', P + [E.CMPX_N, E.SAVE, EXECZ_AFTER, WL(40, 's30', 0), WL(40, 's31', 1), CLEAR30, E.CMPX_T, + E.V1_9, RL(30, 40, 0), ('K:', None), RL(31, 40, 1), E.RESTORE, E.V4_7] + EP), + 'splitpair': ('exec written by s_mov_b64 inside the per-lane skipped range', P + [ + E.CMPX_N, E.SAVE, EXECZ_AFTER, WL(40, 's30', 0), WL(40, 's31', 1), CLEAR30, E.CMPX_T, E.V1_9, + RL(30, 40, 0), RL(33, 40, 1), E.RESTORE, E.V4_7] + EP), +} +# the reason the translator gives without the lowering (the base has no v_writelane_b32 / v_readlane_b32) +NO_LOWERING = 'REFUSED v_writelane_b32' +NO_EXEC = 'REFUSED exec written by s_mov_b64 inside the per-lane skipped range' + + +def main(): + out_dir = sys.argv[sys.argv.index('--write') + 1] if '--write' in sys.argv else os.path.join( + HERE, '..', 'out', 'startup_mesh_spill') + os.makedirs(out_dir, exist_ok=True) + for name, (want, items) in PROGRAMS.items(): + code, texts = E.assemble(items) + path = os.path.join(out_dir, name + '.bin') + with open(path, 'wb') as f: + f.write(code) + got = E.decoded(code) + check('%s: decodes to the intended %d instructions' % (name, len(texts)), + [t for _, t in got] == [t for _, t in texts], + '\n'.join('%5x %-40s %s' % (o, t, g[1]) for (o, t), g in zip(texts, got) if g[1] != t)) + on = E.translate(path, {'X2W_MESH_SPILLS': '1'}) + if want == 'ok': + check('%s: translates with the lowering on' % name, on.startswith('OK'), on[:300]) + check('%s: no v_writelane / v_readlane left in the HLSL' % name, 'lane_b32' not in on, '') + if name == 'spill32': + # (lane 6 holds a constant: the base translator's constant tracking carries it through the slot) + check('spill32: slots s1005 / s1006 assigned and read back', + 's1005 = s24;' in on and 's25 = s1005;' in on and 's1006 = 0x00000007u;' in on + and 's26 = 0x00000007u;' in on, on[:2000]) + if name == 'spillpair': + # a plain data pair, fused into one 64-bit spill and reload: both words survive (MeshStage.scalar_inner + # with X2W_MESH_DATA_PAIRS on; off, the high word is lost and the low word cut to bit 0) + check('spillpair: s[24:25] spilled to s[1002:1003] and reloaded into s[26:27] as two words', + 's1002 = s24;' in on and 's1003 = s25;' in on and 's26 = s1002;' in on and 's27 = s1003;' in on, + on[:3000]) + poff = E.translate(path, {'X2W_MESH_DATA_PAIRS': '0'}) + check('spillpair: negative control X2W_MESH_DATA_PAIRS=0 cuts the pair to the lane bit', + 's1002 = (s24) & 1;' in poff, poff[:300]) + if name == 'spillexec': + check('spillexec: the 64-bit spill and reload are one move each, exec restored from s30', + 's1000 = (s30) & 1;' in on and 's30 = (s1000) & 1;' in on and 'exec = (s30) & 1;' in on, + on[:3000]) + if name == 'spillwave': + check('spillwave: the slot written in the skipped range goes through the group-uniform branch', + 'x2w_any' in on and 's1002 = ' in on, on[:3000]) + off = E.translate(path, {'X2W_MESH_SPILLS': '0'}) + # without the lowering SPILLEXEC stops where the class's programs stopped: the skipped-range check sees + # the restore from s[30:31], which the unlowered v_readlane does not make a copy of the saved mask + expect = NO_EXEC if name in ('spillexec', 'spillhalves') else NO_LOWERING + check('%s: negative control X2W_MESH_SPILLS=0 refuses again (%s)' % (name, expect), + off.splitlines()[0].startswith(expect), off[:200]) + else: + check('%s: refused (%s) with the lowering on' % (name, want), + on.startswith('REFUSED') and want in on.splitlines()[0], on[:200]) + print('programs written to %s (difftest: python -B difftest.py /spillexec.bin --groups 4 --seed 1)' + % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh_vcc_data_check.py b/tests/startup_mesh_vcc_data_check.py new file mode 100644 index 0000000000..c6c7ac6cfa --- /dev/null +++ b/tests/startup_mesh_vcc_data_check.py @@ -0,0 +1,136 @@ +"""Check the vcc-as-data rule of tools/startup/mesh2hlsl.py (MeshStage.lower_vcc_data): where vcc holds no lane mask,""" +import os +import struct +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import startup_mesh_exec_restore_check as E # noqa: E402 (encoder, prologue, epilogue, translate()) +from startup_mesh_exec_restore_check import I # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +def WL(v, s, lane): + return I('v_writelane_b32 v%d, %s, %s' % (v, s, lane), 'vop3', 'v_writelane_b32', d=v, s0=s, s1=str(lane)) + + +def RL(s, v, lane): + return I('v_readlane_b32 s%d, v%d, %s' % (s, v, lane), 'vop3', 'v_readlane_b32', d=s, s0='v%d' % v, s1=str(lane)) + + +def VMOV(d, s): + return I('v_mov_b32_e32 v%d, %s' % (d, s), 'vop1', 'v_mov_b32_e32', d=d, s0=s) + + +VCCLO_T7 = I('s_add_u32 vcc_lo, s22, 7', 'sop2', 's_add_u32', d=106, s0='s22', s1='7') +VCCLO_T = I('s_mov_b32 vcc_lo, s22', 'sop1', 's_mov_b32', d=106, s0='s22') +CMP_N = I('v_cmp_gt_u32_e32 vcc_lo, s21, v0', 'vopc', 'v_cmp_gt_u32_e32', s0='s21', s1='v0') +P, EP = E.PROLOGUE, E.EPILOGUE + + +def vop2(text, mnemonic, d, s0, s1): + """VOP2 (v_cndmask_b32_e32: vdst = vcc ? vsrc1 : src0).""" + def make(): + fields = {'d': d, 's0': E.src(s0)[0], 's1': E.src(s1)[0]} + for op in range(64): + w = (op << 25) | (fields['d'] << 17) | ((fields['s1'] - 256) << 9) | fields['s0'] + code = struct.pack(' v0)' in on, on[:4000]) + check('vccdata: negative control X2W_MESH_VCC_DATA=0 gives the base form (refused or cut to the bit)', + off.startswith('REFUSED') or off.startswith('CRASH') or 'vcc = (s22 + 0x00000007u) & 1;' in off, + off[:300]) + elif name == 'vccspill': + # the fused 64-bit spill of s[106:107] copies both words (not a lane mask: no `& 1`) + check('vccspill: the vcc pair is spilled and reloaded through s[1000:1001] as two words', + 's1000 = s106;' in on and 's1001 = 0x00000005u;' in on and 's25 = s1000;' in on + and 's26 = s1001;' in on, on[:4000]) + pairs_off = E.translate(path, {'X2W_MESH_DATA_PAIRS': '0'}) + check('vccspill: negative control X2W_MESH_DATA_PAIRS=0 cuts the 64-bit data move to the lane bit', + 's1000 = (s106) & 1;' in pairs_off, pairs_off[:300]) + check('vccspill: negative control X2W_MESH_VCC_DATA=0 refuses (vcc_hi as data)', + off.startswith('REFUSED') or off.startswith('CRASH'), off[:300]) + elif name == 'vccdead': + check('vccdead: the mask keeps vcc (no s106 rename)', 's106' not in on and 'vcc = ' in on, on[:4000]) + else: + check('vcczero: the data def is s106, the mask stays vcc', 's106 = s22;' in on and 'v1 = s106;' in on, + on[:4000]) + check('vcczero: negative control X2W_MESH_VCC_DATA=0 cuts the value to the lane bit', + 'vcc = (s22) & 1;' in off, off[:300]) + else: + check('%s: refused (%s) with the rule on' % (name, want), + on.startswith('REFUSED') and want in on.splitlines()[0], on[:200]) + print('programs written to %s (difftest: python -B difftest.py --program /vccdata.bin)' % out_dir) + if failures: + print('%d check(s) failed' % len(failures)) + return 1 + print('all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mrt_wide_int_check.py b/tests/startup_mrt_wide_int_check.py new file mode 100644 index 0000000000..1235d4fb97 --- /dev/null +++ b/tests/startup_mrt_wide_int_check.py @@ -0,0 +1,59 @@ +"""Integer render targets with 32 bits per channel beyond R32: R32G32B32A32 / R32G32B32 / R32G32 _UINT and _SINT. + +Pure Python. The pixel fixture of tests/startup_mrt_check.py (v0..v3 = 1, 2, 0x7fc00001, 0x80000001, then +exp mrt0 v0, v1, v2, v3) is translated with each DXGI format as the slot-0 RTV. Expected: the 32-bit-per-channel +integer formats (3, 7, 17, 42 uint; 4, 8, 18, 43 sint) declare uint4 / int4 SV_Target0 and export the four +register words unconverted, exactly as the verified R32 forms do; narrower integer formats (12 R16G16B16A16_UINT, +30 R8G8B8A8_UINT, 57 R16_UINT, 14 R16G16B16A16_SINT) stay refused as "unverified". ASSUMED (not drawn): the colour +buffer stores the export words of these wider formats as it does for R32. +Negative control: the float target (2, R32G32B32A32_FLOAT) declares float4. +""" +import re +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import struct # noqa: E402 +from startup_mrt_check import FLOAT_WORDS # noqa: E402 +from startup_stream_check import gfx2hlsl as G # noqa: E402 +from startup_stream_draw_check import vop1 # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, root_blob # noqa: E402 + + +def pixel_words(values): + """startup_mrt_check.pixel's program without its container: v_mov_b32 vN, literal; exp mrt0 v0..v3 done vm.""" + words = [] + for reg, value in enumerate(values): + words += [vop1(1, reg, 255), value] + words += [0xf800180f, 0x03020100, 0xbf810000] + return struct.pack('<%dI' % len(words), *words) + + +def ps(fmt): + p = G.Pipeline(VS_WORDS, pixel_words(FLOAT_WORDS), root_blob(flags=0), rtv_formats=(fmt,)) + return p.hlsl_ps() + + +def main(): + for fmt, typ in ((3, 'uint4'), (7, 'uint4'), (17, 'uint4'), (42, 'uint4'), + (4, 'int4'), (8, 'int4'), (18, 'int4'), (43, 'int4')): + text = ps(fmt) + assert '%s mrt0 : SV_Target0;' % typ in text, (fmt, text) + line = [l.strip() for l in text.splitlines() if l.strip().startswith('o.mrt0 =')] + want = 'uint4(v0, v1, v2, v3)' + assert line == ['o.mrt0 = %s;' % (want if typ == 'uint4' else 'asint(%s)' % want)], (fmt, line) + for fmt in (12, 30, 57, 14): + try: + ps(fmt) + except G.Unsupported as error: + assert re.search(r'unverified [SU]INT RTV format %d' % fmt, str(error)), str(error) + else: + raise AssertionError('narrow integer format %d accepted' % fmt) + assert 'float4 mrt0 : SV_Target0;' in ps(2) + print('mrt_wide_int: formats 3/7/17/42 -> uint4 and 4/8/18/43 -> int4 with the raw words; 12/30/57/14 refused; ' + 'float control declares float4') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_pack_f16_check.py b/tests/startup_pack_f16_check.py new file mode 100644 index 0000000000..b577166f67 --- /dev/null +++ b/tests/startup_pack_f16_check.py @@ -0,0 +1,87 @@ +"""v_pack_b32_f16 (VOP3): D[15:0] = S0.f16, D[31:16] = S1.f16 (AMD RDNA 2 ISA). + +Synthetic VOP3 words (gfx10 opcode 0x311, op_sel in word 0 [14:11], abs [10:8], neg in word 1 [31:29]), names and +the printed op_sel / modifier forms asserted from the decoder. Measured forms: `v_pack_b32_f16 vD, vA, vB +op_sel:[1,0,0]` (14 title keys) and without op_sel (1). The emitted expression is evaluated in Python for every +op_sel[0..1] / neg / abs combination over sample register pairs and compared with a reference that selects the +half (op_sel[i] = high half of source i) and then applies abs (clear bit 15) and neg (flip bit 15). +Negative control: the halves swapped are caught. Refused: a destination op_sel bit, clamp. +""" +import re +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def vop3(vdst, s0, s1, opsel=0, absm=0, neg=0, clamp=0): + return [0xd4000000 | 0x311 << 16 | clamp << 15 | opsel << 11 | absm << 8 | vdst, + (256 + s0) | (256 + s1) << 9 | neg << 29] + + +def one(words): + s = G.Stage(Pipe(), 'vs', b'') + s.lines, s.pc = [], 0 + _, n, name, text = G.decode(struct.pack('<2I', *words))[0] + s.one(name, text) + return text, s.lines + + +def ev(expr, env): + py = re.sub(r'(0x[0-9a-f]+|\d+)u\b', r'\1', expr) + return eval(py, {}, env) & 0xffffffff + + +def ref(a, b, sel, absm, neg): + out = [] + for i, x in enumerate((a, b)): + h = (x >> 16) & 0xffff if sel >> i & 1 else x & 0xffff + if absm >> i & 1: + h &= 0x7fff + if neg >> i & 1: + h ^= 0x8000 + out.append(h) + return out[0] | out[1] << 16 + + +def main(): + values = [0x00000000, 0x3c00bc00, 0x80017fff, 0xfc007e00, 0x12345678, 0xffff0001] + cases = 0 + for sel in range(4): + for absm in range(4): + for neg in range(4): + text, lines = one(vop3(3, 1, 2, sel, absm, neg)) + assert text.startswith('v_pack_b32_f16 v3, '), text + assert ('op_sel:[%d,%d,0]' % (sel & 1, sel >> 1) in text) == bool(sel), text + m = re.fullmatch(r'v3 = (.*);', lines[0]) + assert m and len(lines) == 1, lines + for a in values: + for b in values: + assert ev(m.group(1), {'v1': a, 'v2': b}) == ref(a, b, sel, absm, neg), (text, hex(a), hex(b)) + cases += 1 + _, lines = one(vop3(3, 1, 2, 1)) + swapped = re.fullmatch(r'v3 = (.*) \| \((.*) << 16\);', lines[0]) + wrong = '%s | (%s << 16)' % (swapped.group(2), swapped.group(1)) + assert any(ev(wrong, {'v1': a, 'v2': b}) != ref(a, b, 1, 0, 0) for a in values for b in values) + for words, why in ((vop3(3, 1, 2, 4), 'form'), (vop3(3, 1, 2, clamp=1), 'modifier clamp')): + try: + one(words) + except G.Unsupported as error: + assert why in str(error), str(error) + else: + raise AssertionError('accepted: %s' % why) + print('pack_f16: %d (op_sel, abs, neg, value) cases match the reference; swapped halves caught; destination ' + 'op_sel and clamp refused' % cases) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_packed_position_check.py b/tests/startup_packed_position_check.py index 9836d28a5b..4f168c3f84 100644 --- a/tests/startup_packed_position_check.py +++ b/tests/startup_packed_position_check.py @@ -35,7 +35,15 @@ def main(dxc, renderer, adapter, fxc=None): ('wrong register', 1, (0x8002, 0x8002), False), ('packed position disabled', 1, (0x0100, 0x0100), False), ): - ps = compile_hlsl(compiler, kind, pixel_shader(reg, masks), 'ps', 'ps_' + profile, folder) + try: + text = pixel_shader(reg, masks) + except G.Unsupported as err: + # The translator maps every entry VGPR to its SPI input and refuses a read of one it does not + # lower (persp_center, an unallocated register): a stronger outcome than a wrong image. + assert not good and ('not lowered' in str(err) or 'past the SPI inputs' in str(err)), str(err) + print(f'{kind} {adapter} {label}: refused at translation ({err})') + continue + ps = compile_hlsl(compiler, kind, text, 'ps', 'ps_' + profile, folder) run = subprocess.run([renderer, adapter, '--startup-packed-position', vs, ps], capture_output=True, text=True) if run.returncode == 77: diff --git a/tests/startup_pipeline_state_local_check.cpp b/tests/startup_pipeline_state_local_check.cpp new file mode 100644 index 0000000000..56bca37ad5 --- /dev/null +++ b/tests/startup_pipeline_state_local_check.cpp @@ -0,0 +1,351 @@ +// Checks src/startup_stubs/pipeline_state_decode.h without a device: hand-built register words (field +// layouts of Mesa's gfx10.json) decoded to D3D12 depth-stencil, rasterizer and blend descriptions, +// the refusals, synthetic state blocks in both layouts, slot 55 records, the depth-target adjustments +// and the switches. No title data. +// +// --mutate winding: expects FACE 0 to mean clockwise front faces (the check must then fail). +// --mutate mesh-shift: expects mesh-layout fields at the vertex-layout offsets (must fail). +#include "startup_stubs/pipeline_state_decode.h" +#include "startup_stubs/state_block_blend.h" + +#include +#include +#include + +namespace { +using namespace x2w_pipeline_state; +int failures, cases; +bool mutate_winding, mutate_shift; + +void check(bool ok, const char* name) +{ + ++cases; + if (!ok) { + std::printf("FAIL %s\n", name); + ++failures; + } +} + +// DB_DEPTH_CONTROL from its fields. +constexpr std::uint32_t depth_control(bool stencil, bool z, bool z_write, bool bounds, unsigned zfunc, bool backface, unsigned sfunc, + unsigned sfunc_bf) +{ + return std::uint32_t{stencil} | std::uint32_t{z} << 1 | std::uint32_t{z_write} << 2 | std::uint32_t{bounds} << 3 | (zfunc & 7) << 4 | + std::uint32_t{backface} << 7 | (sfunc & 7) << 8 | (sfunc_bf & 7) << 20; +} +constexpr std::uint32_t stencil_control(unsigned fail, unsigned zpass, unsigned zfail, unsigned fail_bf, unsigned zpass_bf, unsigned zfail_bf) +{ + return fail | zpass << 4 | zfail << 8 | fail_bf << 12 | zpass_bf << 16 | zfail_bf << 20; +} +constexpr std::uint32_t refmask(unsigned test, unsigned mask, unsigned write, unsigned opval) { return test | mask << 8 | write << 16 | opval << 24; } +constexpr std::uint32_t mode_cntl(bool cull_front, bool cull_back, bool face_cw, unsigned poly_mode, unsigned front_type, unsigned back_type, + bool offset_front, bool offset_back) +{ + return std::uint32_t{cull_front} | std::uint32_t{cull_back} << 1 | std::uint32_t{face_cw} << 2 | poly_mode << 3 | front_type << 5 | + back_type << 8 | std::uint32_t{offset_front} << 11 | std::uint32_t{offset_back} << 12 | 1u << 21; // MULTI_PRIM_IB_ENA +} + +void depth_stencil_cases() +{ + // Depth off: the function the word carries is ignored (canonical ALWAYS), stencil off. + auto d = decode_depth_stencil(depth_control(false, false, false, false, 1, true, 7, 7), 0, refmask(0, 0xff, 0, 1), refmask(0, 0xff, 0, 1)); + check(d.ok && !d.desc.DepthEnable && d.desc.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ZERO && d.desc.DepthFunc == D3D12_COMPARISON_FUNC_ALWAYS && + !d.desc.StencilEnable, "depth off"); + // Reversed depth: GEQUAL read-only. + d = decode_depth_stencil(depth_control(false, true, false, false, 6, true, 7, 7), 0, refmask(0, 0xff, 0, 1), refmask(0, 0xff, 0, 1)); + check(d.ok && d.desc.DepthEnable && d.desc.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ZERO && d.desc.DepthFunc == D3D12_COMPARISON_FUNC_GREATER_EQUAL, + "GEQUAL read"); + // Every compare function in order. + const D3D12_COMPARISON_FUNC funcs[8] = {D3D12_COMPARISON_FUNC_NEVER, D3D12_COMPARISON_FUNC_LESS, D3D12_COMPARISON_FUNC_EQUAL, + D3D12_COMPARISON_FUNC_LESS_EQUAL, D3D12_COMPARISON_FUNC_GREATER, D3D12_COMPARISON_FUNC_NOT_EQUAL, + D3D12_COMPARISON_FUNC_GREATER_EQUAL, D3D12_COMPARISON_FUNC_ALWAYS}; + for (unsigned f = 0; f < 8; ++f) { + d = decode_depth_stencil(depth_control(true, true, true, false, f, true, f, 7 - f), 0, refmask(0, 0xff, 0xff, 1), refmask(0, 0xff, 0xff, 1)); + check(d.ok && d.desc.DepthFunc == funcs[f] && d.desc.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ALL && d.desc.FrontFace.StencilFunc == funcs[f] && + d.desc.BackFace.StencilFunc == funcs[7 - f], "compare function order"); + } + // Stencil: replace on depth pass, both faces, masks. + d = decode_depth_stencil(depth_control(true, true, true, false, 6, true, 7, 7), stencil_control(0, 3, 0, 0, 3, 0), refmask(0, 0xff, 0xff, 1), + refmask(0, 0xff, 0xff, 1)); + check(d.ok && d.desc.StencilEnable && d.desc.StencilReadMask == 0xff && d.desc.StencilWriteMask == 0xff && + d.desc.FrontFace.StencilPassOp == D3D12_STENCIL_OP_REPLACE && d.desc.BackFace.StencilPassOp == D3D12_STENCIL_OP_REPLACE && + d.desc.FrontFace.StencilFailOp == D3D12_STENCIL_OP_KEEP && d.desc.FrontFace.StencilDepthFailOp == D3D12_STENCIL_OP_KEEP, + "stencil replace"); + // Every op with a D3D12 form, front fail / back depth-fail; the add / subtract ops by one. + const struct { unsigned op; D3D12_STENCIL_OP d3d; } ops[] = {{0, D3D12_STENCIL_OP_KEEP}, {1, D3D12_STENCIL_OP_ZERO}, + {3, D3D12_STENCIL_OP_REPLACE}, {5, D3D12_STENCIL_OP_INCR_SAT}, + {6, D3D12_STENCIL_OP_DECR_SAT}, {7, D3D12_STENCIL_OP_INVERT}, + {8, D3D12_STENCIL_OP_INCR}, {9, D3D12_STENCIL_OP_DECR}}; + for (const auto& o : ops) { + d = decode_depth_stencil(depth_control(true, false, false, false, 7, true, 2, 2), stencil_control(o.op, 0, 0, 0, 0, o.op), + refmask(0, 0x28, 0, 1), refmask(0, 0x28, 0, 1)); + check(d.ok && d.desc.FrontFace.StencilFailOp == o.d3d && d.desc.BackFace.StencilDepthFailOp == o.d3d && d.desc.StencilReadMask == 0x28 && + d.desc.StencilWriteMask == 0, "stencil op mapping"); + } + // No back-face state: back faces use the front state (the _BF words are ignored). + d = decode_depth_stencil(depth_control(true, false, false, false, 7, false, 3, 0), stencil_control(0, 8, 0, 9, 9, 9), refmask(0, 0x80, 0x80, 1), + refmask(0, 0, 0, 7)); + check(d.ok && d.desc.BackFace.StencilFunc == D3D12_COMPARISON_FUNC_LESS_EQUAL && d.desc.BackFace.StencilPassOp == D3D12_STENCIL_OP_INCR && + !d.masks_differ, "back faces follow the front"); + // Negative: ops without a form, add by two, colour writes on depth fail. + check(!decode_depth_stencil(depth_control(true, false, false, false, 7, true, 7, 7), stencil_control(2, 0, 0, 0, 0, 0), refmask(0, 0xff, 0xff, 1), + refmask(0, 0xff, 0xff, 1)).ok, "ONES refused"); + check(!decode_depth_stencil(depth_control(true, false, false, false, 7, true, 7, 7), stencil_control(0, 4, 0, 0, 4, 0), refmask(0, 0xff, 0xff, 1), + refmask(0, 0xff, 0xff, 1)).ok, "REPLACE_OP refused"); + check(!decode_depth_stencil(depth_control(true, false, false, false, 7, true, 7, 7), stencil_control(0, 8, 0, 0, 8, 0), refmask(0, 0xff, 0xff, 2), + refmask(0, 0xff, 0xff, 2)).ok, "add by two refused"); + check(!decode_depth_stencil(depth_control(true, false, false, false, 7, true, 7, 7), stencil_control(0, 0, 0, 0, 12, 0), refmask(0, 0xff, 0xff, 1), + refmask(0, 0xff, 0xff, 1)).ok, "back-face XOR refused"); + check(!decode_depth_stencil(depth_control(false, true, true, false, 6, false, 7, 7) | 1u << 30, 0, 0, 0).ok, "colour writes on depth fail refused"); + // An unusable op on a disabled stencil does not refuse the depth state. + check(decode_depth_stencil(depth_control(false, true, true, false, 1, true, 7, 7), stencil_control(2, 2, 2, 2, 2, 2), 0, 0).ok, + "ops of a disabled stencil ignored"); + // Flags. + d = decode_depth_stencil(depth_control(false, true, false, true, 3, false, 7, 7), 0, 0, 0); + check(d.ok && d.depth_bounds, "depth bounds flagged"); + d = decode_depth_stencil(depth_control(true, false, false, false, 7, true, 7, 7), 0, refmask(0, 0xff, 0xff, 1), refmask(0, 0x0f, 0xff, 1)); + check(d.ok && d.masks_differ && d.desc.StencilReadMask == 0xff, "back masks differ flagged, front kept"); +} + +void rasterizer_cases() +{ + const bool ccw_for_face0 = !mutate_winding; + auto r = decode_rasterizer(mode_cntl(false, false, false, 0, 2, 2, true, true), 0x00080000, 0, 0, 0, false); + check(r.ok && r.desc.CullMode == D3D12_CULL_MODE_NONE && (r.desc.FrontCounterClockwise != 0) == ccw_for_face0 && r.desc.DepthClipEnable && + r.desc.FillMode == D3D12_FILL_MODE_SOLID && r.desc.DepthBias == 0 && r.desc.SlopeScaledDepthBias == 0, "no cull, FACE 0"); + r = decode_rasterizer(mode_cntl(false, true, false, 0, 2, 2, true, true), 0x00080000, 0, 0, 0, false); + check(r.ok && r.desc.CullMode == D3D12_CULL_MODE_BACK, "cull back"); + r = decode_rasterizer(mode_cntl(true, false, false, 0, 2, 2, true, true), 0x00080000, 0, 0, 0, false); + check(r.ok && r.desc.CullMode == D3D12_CULL_MODE_FRONT, "cull front"); + r = decode_rasterizer(mode_cntl(false, true, true, 0, 2, 2, true, true), 0x00080000, 0, 0, 0, false); + check(r.ok && (r.desc.FrontCounterClockwise != 0) == !ccw_for_face0, "FACE 1"); + r = decode_rasterizer(mode_cntl(false, true, false, 0, 2, 2, true, true), 0x00080000, 0, 0, 0, true); + check(r.ok && (r.desc.FrontCounterClockwise != 0) == !ccw_for_face0, "flip switch"); + // Polygon offset: clamp, scale (slope * 16), offset in the hardware register order. + r = decode_rasterizer(mode_cntl(false, true, false, 0, 2, 2, true, true), 0x00080000, 0.003f, 29.0f, 1.0f, false); + check(r.ok && r.desc.DepthBias == 1 && r.desc.DepthBiasClamp == 0.003f && r.desc.SlopeScaledDepthBias == 29.0f / 16.0f && !r.bias_rounded, + "polygon offset"); + r = decode_rasterizer(mode_cntl(false, true, false, 0, 2, 2, false, false), 0x00080000, 0.003f, 29.0f, 1.0f, false); + check(r.ok && r.desc.DepthBias == 0 && r.desc.SlopeScaledDepthBias == 0 && r.desc.DepthBiasClamp == 0, "offset disabled ignores values"); + r = decode_rasterizer(mode_cntl(false, false, false, 0, 2, 2, true, true), 0x00080000, 0, 0, 2.5f, false); + check(r.ok && r.bias_rounded, "fractional offset flagged"); + // Depth clip. + r = decode_rasterizer(mode_cntl(false, false, false, 0, 2, 2, true, true), 0x0c080000, 0, 0, 0, false); + check(r.ok && !r.desc.DepthClipEnable && !r.clip_split, "zclip disabled"); + r = decode_rasterizer(mode_cntl(false, false, false, 0, 2, 2, true, true), 0x04080000, 0, 0, 0, false); + check(r.ok && r.desc.DepthClipEnable && r.clip_split, "one zclip plane flagged, clipping kept"); + // Polygon modes. + r = decode_rasterizer(mode_cntl(false, false, false, 1, 1, 1, true, true), 0x00080000, 0, 0, 0, false); + check(r.ok && r.desc.FillMode == D3D12_FILL_MODE_WIREFRAME, "line mode"); + check(!decode_rasterizer(mode_cntl(false, false, false, 1, 0, 0, true, true), 0x00080000, 0, 0, 0, false).ok, "point mode refused"); + check(!decode_rasterizer(mode_cntl(false, false, false, 1, 1, 2, true, true), 0x00080000, 0, 0, 0, false).ok, "mixed modes refused"); + check(!decode_rasterizer(mode_cntl(true, true, false, 0, 2, 2, true, true), 0x00080000, 0, 0, 0, false).ok, "both faces culled refused"); + check(!decode_rasterizer(mode_cntl(false, false, false, 0, 2, 2, true, false), 0x00080000, 0, 0, 0, false).ok, "one-face offset refused"); +} + +void blend_cases() +{ + using x2w_cb_blend::control_word; + const std::uint32_t straight = control_word(4, 0, 5, 1, 0, 5, true, true), off = 0x80000000; + const std::uint32_t dual = control_word(1, 0, 15, 1, 0, 17, true, true); + std::uint32_t words[8] = {straight, off, off, off, off, off, off, off}; + // Masks: CB_TARGET_MASK & CB_SHADER_MASK per target nibble. + auto b = decode_blend(words, 0x77777777, 0xff, true, false); + check(b.ok && b.desc.RenderTarget[0].RenderTargetWriteMask == 7 && b.desc.RenderTarget[1].RenderTargetWriteMask == 7 && + b.desc.RenderTarget[2].RenderTargetWriteMask == 0 && b.desc.RenderTarget[0].BlendEnable && !b.desc.RenderTarget[1].BlendEnable && + b.masked_targets == 0xff && !b.dual_source, "write masks"); + b = decode_blend(words, 0xffffffff, 0xf, true, false); + check(b.ok && b.desc.RenderTarget[0].RenderTargetWriteMask == 0xf && b.desc.RenderTarget[1].RenderTargetWriteMask == 0 && b.masked_targets == 0xfe, + "shader mask limits the targets"); + b = decode_blend(words, 0, 0xf, false, false); + check(b.ok && b.desc.RenderTarget[3].RenderTargetWriteMask == 0xf && !b.masked_targets, "masks not applied"); + for (auto& w : words) w = dual; + b = decode_blend(words, 0xf, 0xff, true, false); + check(b.ok && b.dual_source && b.desc.RenderTarget[0].DestBlend == D3D12_BLEND_SRC1_COLOR && b.desc.RenderTarget[0].DestBlendAlpha == D3D12_BLEND_SRC1_ALPHA, + "dual source"); + words[3] = control_word(11, 0, 1, 1, 0, 0, false, true); // BOTH_SRC_ALPHA + b = decode_blend(words, 0xffffffff, 0xffffffff, true, false); + check(!b.ok && b.refused_targets == 0x8 && b.reason, "refused target"); + // The unmasked form is what state_block_blend.h answered before: compare on a synthetic block. + std::vector block(388, 0xA5); + const std::uint32_t mix[8] = {straight, off, control_word(1, 0, 1, 1, 0, 1, false, true), control_word(1, 3, 1, 1, 2, 1, true, true), off, off, straight, off}; + std::memcpy(block.data() + x2w_startup::state_block_blend_offset, mix, sizeof(mix)); + D3D12_BLEND_DESC old{}; + const bool old_ok = x2w_startup::state_block_blend(block.data(), block.size(), false, &old); + bool same = old_ok && old.IndependentBlendEnable && !old.AlphaToCoverageEnable; + for (unsigned t = 0; t < 8 && same; ++t) { + const auto ref = x2w_cb_blend::decode(mix[t], 0xF, false); + same = ref.ok && std::memcmp(&ref.desc, &old.RenderTarget[t], sizeof(ref.desc)) == 0; + } + check(same, "state_block_blend equals the per-target decoder"); +} + +void block_cases() +{ + // Vertex layout (+0x004 = 4) and mesh layout (+0x004 = 6, fields 0x54 later from +0x058). + for (int mesh = 0; mesh < 2; ++mesh) { + std::vector a(mesh ? 0x1d0 : 0x184, 0x5a); + const std::uint32_t kind = mesh ? 6 : 4; + std::memcpy(a.data() + 4, &kind, 4); + const std::size_t s = mesh && !mutate_shift ? mesh_shift : 0; + auto put = [&](std::size_t off, std::uint32_t v) { std::memcpy(a.data() + off + s, &v, 4); }; + const float bias[3] = {0.5f, 32.0f, 3.0f}; + put(a_shader_mask, 0xff); + put(a_clip, 0x0c080000); + put(a_mode, 0x00201a42); + std::memcpy(a.data() + a_bias + s, bias, sizeof(bias)); + put(a_depth, 0x007007e7); + put(a_stencil, 0x00030030); + put(a_refmask, 0x0100ff00); + put(a_refmask_bf, 0x0100fe00); + put(a_target_mask, 0x77); + for (unsigned t = 0; t < 8; ++t) put(a_blend + 4 * t, 0x80000000u + t); + Words w; + const bool ok = read_words(a.data(), a.size(), w); + check(ok && w.mesh == (mesh != 0) && w.shader_mask == 0xff && w.clip == 0x0c080000 && w.mode == 0x00201a42 && w.depth == 0x007007e7 && + w.stencil == 0x00030030 && w.refmask == 0x0100ff00 && w.refmask_bf == 0x0100fe00 && w.target_mask == 0x77 && + w.blend[7] == 0x80000007 && w.bias_clamp == 0.5f && w.bias_scale == 32.0f && w.bias_offset == 3.0f, + mesh ? "mesh layout words" : "vertex layout words"); + Words short_words; + check(!read_words(a.data(), (mesh ? mesh_shift : 0) + a_blend + 31, short_words), "short block refused"); + } +} + +void add_record(std::vector& list, std::uint32_t part, const void* desc, std::size_t bytes, unsigned char fill) +{ + const std::size_t at = list.size(); + list.resize(at + record_size, fill); + std::memcpy(list.data() + at, &part, 4); + std::memcpy(list.data() + at + 4, desc, bytes); +} + +void derived_cases() +{ + D3D12_DEPTH_STENCIL_DESC a{}, b{}; + a.DepthEnable = TRUE; + a.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + a.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + a.FrontFace = a.BackFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}; + b = a; + b.DepthFunc = D3D12_COMPARISON_FUNC_GREATER_EQUAL; + b.StencilEnable = 7; // a non-canonical TRUE + b.StencilReadMask = 0xff; + b.StencilWriteMask = 0x10; + b.FrontFace.StencilPassOp = D3D12_STENCIL_OP_REPLACE; + unsigned char with_pad[sizeof(D3D12_DEPTH_STENCIL_DESC)]; + std::memcpy(with_pad, &b, sizeof(b)); + with_pad[offsetof(D3D12_DEPTH_STENCIL_DESC, StencilWriteMask) + 1] = 0xcc; // garbage in the padding + D3D12_RASTERIZER_DESC r{D3D12_FILL_MODE_SOLID, D3D12_CULL_MODE_BACK, 9, 0, 0, 0, TRUE, FALSE, FALSE, 0, D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF}; + D3D12_BLEND_DESC blend{}; + std::vector list; + add_record(list, part_depth_stencil, &a, sizeof(a), 0xee); + add_record(list, part_blend, &blend, sizeof(blend), 0xee); + add_record(list, part_depth_stencil, with_pad, sizeof(with_pad), 0xee); + add_record(list, part_rasterizer, &r, sizeof(r), 0xee); + D3D12_DEPTH_STENCIL_DESC got{}; + D3D12_RASTERIZER_DESC got_r{}; + check(derived_depth_stencil(list.data(), list.size(), got) && got.DepthFunc == D3D12_COMPARISON_FUNC_GREATER_EQUAL && got.StencilEnable == TRUE && + got.StencilWriteMask == 0x10 && got.FrontFace.StencilPassOp == D3D12_STENCIL_OP_REPLACE, "last depth-stencil part"); + D3D12_DEPTH_STENCIL_DESC canonical{}; + std::memcpy(&canonical, &got, sizeof(got)); + D3D12_DEPTH_STENCIL_DESC rebuilt{}; + rebuilt.DepthEnable = TRUE; + rebuilt.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + rebuilt.DepthFunc = D3D12_COMPARISON_FUNC_GREATER_EQUAL; + rebuilt.StencilEnable = TRUE; + rebuilt.StencilReadMask = 0xff; + rebuilt.StencilWriteMask = 0x10; + rebuilt.FrontFace = b.FrontFace; + rebuilt.BackFace = b.BackFace; + check(std::memcmp(&canonical, &rebuilt, sizeof(rebuilt)) == 0, "padding cleaned (state hash stable)"); + check(derived_rasterizer(list.data(), list.size(), got_r) && got_r.CullMode == D3D12_CULL_MODE_BACK && got_r.FrontCounterClockwise == TRUE, + "rasterizer part"); + check(last_part(list.data(), list.size(), part_blend) == record_size + 4, "blend part offset"); + check(last_part(list.data(), list.size() - 1, part_blend) == SIZE_MAX, "partial list refused"); + // Out-of-range fields refuse the part. + std::vector bad; + D3D12_DEPTH_STENCIL_DESC c = a; + c.DepthFunc = static_cast(9); + add_record(bad, part_depth_stencil, &c, sizeof(c), 0); + D3D12_RASTERIZER_DESC rr = r; + rr.CullMode = static_cast(4); + add_record(bad, part_rasterizer, &rr, sizeof(rr), 0); + check(!derived_depth_stencil(bad.data(), bad.size(), got), "bad depth func refused"); + check(!derived_rasterizer(bad.data(), bad.size(), got_r), "bad cull mode refused"); + std::vector none; + add_record(none, part_blend, &blend, sizeof(blend), 0); + check(!derived_depth_stencil(none.data(), none.size(), got) && !derived_rasterizer(none.data(), none.size(), got_r), "no part"); +} + +void target_cases() +{ + auto ds = decode_depth_stencil(depth_control(true, true, true, false, 6, true, 7, 7), stencil_control(0, 3, 0, 0, 3, 0), refmask(0, 0xff, 0xff, 1), + refmask(0, 0xff, 0xff, 1)).desc; + auto d = ds; + check(adjust_for_target(d, false, false, false) == adjust_no_target && !d.DepthEnable && !d.StencilEnable, "no depth target"); + d = ds; + check(adjust_for_target(d, true, false, false) == adjust_no_stencil && d.DepthEnable && !d.StencilEnable, "no stencil plane"); + d = ds; + check(adjust_for_target(d, true, true, true) == adjust_read_only && d.DepthEnable && d.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ZERO && + d.StencilWriteMask == 0, "read-only target"); + d = ds; + check(adjust_for_target(d, true, true, false) == 0 && std::memcmp(&d, &ds, sizeof(d)) == 0, "matching target unchanged"); +} + +void switch_cases() +{ + auto s = parse_switches(nullptr, nullptr, nullptr, nullptr, nullptr); + check(!s.depth && !s.cull && !s.flip && !s.blend, "defaults off"); + s = parse_switches(nullptr, "1", "1", "1", "1"); + check(s.depth && s.cull && s.flip && s.blend, "all on"); + s = parse_switches("0", "1", "1", "1", "1"); + check(!s.depth && !s.cull && !s.flip && !s.blend, "X2W_DRAW_STATE=0 wins"); + s = parse_switches("1", nullptr, nullptr, nullptr, "1"); + check(!s.cull && !s.flip, "flip needs cull"); + s = parse_switches(nullptr, "10", "yes", "", nullptr); + check(!s.depth && !s.cull && !s.blend, "only \"1\" turns a group on"); + check(!s.depth_clear, "depth clears default off"); + s = parse_switches(nullptr, nullptr, nullptr, nullptr, nullptr, "1"); + check(s.depth_clear && !s.depth, "depth clears on their own switch"); + s = parse_switches("0", nullptr, nullptr, nullptr, nullptr, "1"); + check(!s.depth_clear, "X2W_DRAW_STATE=0 turns depth clears off"); + check(!s.uncleared, "uncleared depth tests default off"); + s = parse_switches(nullptr, "1", nullptr, nullptr, nullptr, nullptr, "1"); + check(s.depth && s.uncleared, "uncleared depth tests on with depth"); + s = parse_switches(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "1"); + check(!s.uncleared, "uncleared depth tests need the depth group"); + s = parse_switches("0", "1", nullptr, nullptr, nullptr, nullptr, "1"); + check(!s.uncleared, "X2W_DRAW_STATE=0 turns uncleared depth tests off"); + check(!s.depthclip, "depth clip default off"); + s = parse_switches(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "1"); + check(s.depthclip && !s.cull && !s.depth && !s.blend, "depth clip on its own switch"); + s = parse_switches("0", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "1"); + check(!s.depthclip, "X2W_DRAW_STATE=0 turns depth clip off"); + s = parse_switches(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "yes"); + check(!s.depthclip, "only \"1\" turns depth clip on"); +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc > 2 && std::strcmp(argv[1], "--mutate") == 0) { + mutate_winding = std::strcmp(argv[2], "winding") == 0; + mutate_shift = std::strcmp(argv[2], "mesh-shift") == 0; + if (!mutate_winding && !mutate_shift) { + std::printf("unknown mutation\n"); + return 2; + } + } else if (argc > 1) { + std::printf("usage: startup_pipeline_state_check [--mutate winding|mesh-shift]\n"); + return 2; + } + depth_stencil_cases(); + rasterizer_cases(); + blend_cases(); + block_cases(); + derived_cases(); + target_cases(); + switch_cases(); + std::printf("%d of %d checks failed\n", failures, cases); + return failures ? 1 : 0; +} diff --git a/tests/startup_placed_fast.cpp b/tests/startup_placed_fast.cpp new file mode 100644 index 0000000000..8b0f994746 --- /dev/null +++ b/tests/startup_placed_fast.cpp @@ -0,0 +1,113 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e, f); +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) return 2; + const std::string mode = argv[2]; + if (mode != "fast" && mode != "walk") return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + { + ComPtr desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 4; + void* block = VirtualAlloc(nullptr, 65536, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + ComPtr heap; + const HRESULT hr = block ? desktop->OpenExistingHeapFromAddress(block, IID_PPV_ARGS(&heap)) : E_OUTOFMEMORY; + heap.Reset(); + if (block) VirtualFree(block, 0, MEM_RELEASE); + if (FAILED(hr)) { + std::printf("OpenExistingHeapFromAddress -> 0x%08lx: capability skip\n", static_cast(hr)); + return 77; + } + } + wchar_t temp[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, temp)) return 5; + const std::wstring log_path = std::wstring(temp) + L"x2w_placed_fast_" + std::to_wstring(GetCurrentProcessId()) + L"_" + + std::to_wstring(GetTickCount64()) + L".log"; + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + + std::array device_parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), device_parameters.data(), __uuidof(ID3D12Device), &device))) return 6; + auto* memory = static_cast(VirtualAlloc(nullptr, 4u << 20, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!memory) return 7; + struct Place { const char* name; std::size_t offset, width; bool decommit_first; }; + const Place places[] = {{"A", 0, 64u << 10, false}, {"B", 1u << 20, 1u << 20, false}, {"C", 3u << 20, 2u << 20, false}}; + std::vector made; + for (const Place& p : places) { + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, p.width, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + void* resource = nullptr; + const Word hr = invoke(device, 133, arg(memory + p.offset), arg(&buffer), D3D12_RESOURCE_STATE_COMMON, 0, + arg(&__uuidof(ID3D12Resource)), arg(&resource)); + std::printf("%s: +0x%zx width 0x%zx -> 0x%08llx\n", p.name, p.offset, p.width, static_cast(hr)); + made.push_back(resource); + } + + std::ifstream file(log_path, std::ios::binary); + const std::string log{std::istreambuf_iterator(file), {}}; + // The slot-133 lines in call order: their placement word. + std::vector placement; + for (std::size_t p = log.find("Device::slot133(CreatePlacedResourceX?) address="); p != std::string::npos; + p = log.find("Device::slot133(CreatePlacedResourceX?) address=", p + 1)) { + const std::string line = log.substr(p, log.find('\n', p) - p); + placement.push_back(line.find(" not aliased") != std::string::npos ? "not aliased" : line.find(" aliased") != std::string::npos ? "aliased" : "?"); + } + int fast_calls = 0; + if (const std::size_t p = log.find("slot133 X2W_PLACED_FAST: "); p != std::string::npos) + for (std::size_t q = p; q != std::string::npos; q = log.find("slot133 X2W_PLACED_FAST: ", q + 1)) + fast_calls = std::atoi(log.c_str() + q + std::strlen("slot133 X2W_PLACED_FAST: ")); + int failures = 0; + const char* want[] = {"aliased", "aliased", "not aliased"}; + for (std::size_t i = 0; i < 3; ++i) { + const std::string got = i < placement.size() ? placement[i] : "missing"; + std::printf("%s placement: %s (want %s)\n", places[i].name, got.c_str(), want[i]); + if (got != want[i]) ++failures; + } + std::printf("X2W_PLACED_FAST calls logged: %d (want %d)\n", fast_calls, mode == "fast" ? 1 : 0); + if (fast_calls != (mode == "fast" ? 1 : 0)) ++failures; + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; +} diff --git a/tests/startup_present_producer.cpp b/tests/startup_present_producer.cpp index 32f6fe0b6e..5fa7c93a64 100644 --- a/tests/startup_present_producer.cpp +++ b/tests/startup_present_producer.cpp @@ -26,6 +26,13 @@ bool ok(Word result) { return SUCCEEDED(static_cast(result)); } int main(int argc, char** argv) { + const bool title_mode = argc >= 2 && std::strcmp(argv[1], "title-window") == 0; + HWND title = nullptr; + if (title_mode) { + title = CreateWindowExW(WS_EX_NOACTIVATE, L"STATIC", L"Fixture title", WS_POPUP | WS_VISIBLE, + -31000, -31000, 120, 80, nullptr, nullptr, GetModuleHandleW(nullptr), nullptr); + if (!title) return 16; + } const bool reverse = argc >= 2 && std::strcmp(argv[1], "reverse") == 0; const bool use_magenta = argc >= 2 && std::strcmp(argv[1], "auto-magenta") == 0; const bool automatic = use_magenta || (argc >= 2 && std::strcmp(argv[1], "auto") == 0); @@ -148,6 +155,21 @@ int main(int argc, char** argv) if (!finish() || !present() || !present()) return 11; } } + if (title_mode) { + if (!SetWindowPos(title, nullptr, 0, 0, 160, 90, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER) || !present()) return 17; + unsigned output_windows = 0; + EnumWindows([](HWND window, LPARAM count) -> BOOL { + wchar_t name[64]{}; + DWORD pid = 0; + GetWindowThreadProcessId(window, &pid); + if (pid == GetCurrentProcessId() && GetClassNameW(window, name, 64) && !lstrcmpW(name, L"X2WOutputWindow")) + ++*reinterpret_cast(count); + return TRUE; + }, reinterpret_cast(&output_windows)); + wchar_t text[64]{}; + if (output_windows || !IsWindowVisible(title) || !GetWindowTextW(title, text, 64) || lstrcmpW(text, L"Fixture title")) return 18; + DestroyWindow(title); + } if (FAILED(desktop->GetDeviceRemovedReason())) return 12; ComPtr messages; if (debug && SUCCEEDED(desktop.As(&messages))) { diff --git a/tests/startup_present_producer_check.py b/tests/startup_present_producer_check.py index 9307ffcddc..79076b2c10 100644 --- a/tests/startup_present_producer_check.py +++ b/tests/startup_present_producer_check.py @@ -12,6 +12,8 @@ def run(mode, rgb=""): env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", X2W_PRESENT_SIGNATURE_EVERY="1", X2W_RED_PRODUCER_FRAMES="", X2W_RED_PRODUCER_AUTO="", X2W_RED_PRODUCER_RGB=rgb) + if mode == "title-window": + env["X2W_PRESENT_IN_TITLE_WINDOW"] = "1" if mode.startswith("auto"): env["X2W_RED_PRODUCER_AUTO"] = "4,2" else: @@ -61,6 +63,10 @@ def check_barriers(): if __name__ == "__main__" and OPTIONS == ["barriers"]: check_barriers() +elif __name__ == "__main__" and OPTIONS == ["title-window"]: + logs, _, adapter = run("title-window") + assert "first flip on the original window" in logs, logs + print(f"Original window received the flip and retained its title after resize ({adapter})") elif __name__ == "__main__": check(False) check(True) diff --git a/tests/startup_probe_cache.cpp b/tests/startup_probe_cache.cpp new file mode 100644 index 0000000000..a05f425307 --- /dev/null +++ b/tests/startup_probe_cache.cpp @@ -0,0 +1,77 @@ +#include "startup_stubs/local_log.h" + +#include +#include +#include + +namespace { +volatile LONG violations; +LONG CALLBACK count_violation(EXCEPTION_POINTERS* e) +{ + if (e->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) InterlockedIncrement(&violations); + return EXCEPTION_CONTINUE_SEARCH; +} +int failures; +void expect(const char* what, long long got, long long want) +{ + std::printf("%s: %lld (want %lld)%s\n", what, got, want, got == want ? "" : " <-- FAIL"); + if (got != want) ++failures; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + const std::string mode = argv[1]; + if (mode != "cache" && mode != "nocache") return 2; + const bool cache = mode == "cache"; + if (x2w_local::probe_cache_on() != cache) { + std::printf("X2W_PROBE_CACHE is %s, mode %s\n", x2w_local::probe_cache_on() ? "on" : "off", mode.c_str()); + return 3; + } + AddVectoredExceptionHandler(1, count_violation); + auto* base = static_cast(VirtualAlloc(nullptr, 1u << 20, MEM_RESERVE, PAGE_READWRITE)); + if (!base || !VirtualAlloc(base, 64u << 10, MEM_COMMIT, PAGE_READWRITE)) return 4; + std::memset(base, 1, 64u << 10); + const auto b = reinterpret_cast(base); + + bool all = true; + for (int i = 0; i < 100; ++i) all = all && x2w_local::probe_readable(b, 128u << 10) == (64u << 10); + expect("1. 100 probes of 128 KiB, all 64 KiB readable", all, 1); + expect("1. access violations", violations, cache ? 1 : 100); + + LONG before = violations; + all = true; + for (int i = 0; i < 100; ++i) all = all && x2w_local::probe_readable(b + (512u << 10), 4096) == 0; + expect("2. 100 probes in the reserved part, all 0", all, 1); + expect("2. access violations added", violations - before, cache ? 0 : 100); + + if (!VirtualAlloc(base + (64u << 10), 64u << 10, MEM_COMMIT, PAGE_READWRITE)) return 5; + expect("3. committed +64 KiB, no invalidation: readable", static_cast(x2w_local::probe_readable(b, 128u << 10)), + cache ? (64u << 10) : (128u << 10)); + x2w_local::invalidate_probe_cache(); + expect("4. after invalidate_probe_cache: readable", static_cast(x2w_local::probe_readable(b, 128u << 10)), 128u << 10); + + x2w_local::invalidate_probe_cache(); + before = violations; + x2w_local::probe_readable(b + (512u << 10), 4096); + expect("5. first probe after invalidation: violations", violations - before, 1); + before = violations; + x2w_local::probe_readable(b + (512u << 10), 4096); + expect("5. second probe: violations", violations - before, cache ? 0 : 1); + Sleep(150); + before = violations; + x2w_local::probe_readable(b + (512u << 10), 4096); + expect("5. after 150 ms (expiry 100 ms): violations", violations - before, 1); + + VirtualFree(base, 0, MEM_RELEASE); + x2w_local::invalidate_probe_cache(); + expect("6. released: readable", static_cast(x2w_local::probe_readable(b, 4096)), 0); + + const x2w_local::ProbeCache& c = x2w_local::probe_cache(); + std::printf("cache counters: hits %lld faults %lld queries %lld (%.3f ms total) ranges kept %lld\n", c.hits, c.faults, c.queries, + [&] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return static_cast(c.query_ticks) * 1000.0 / static_cast(f.QuadPart); }(), + c.cached); + std::printf("%s\n", failures ? "FAIL" : "PASS"); + return failures ? 16 : 0; +} diff --git a/tests/startup_quad_divergent_check.py b/tests/startup_quad_divergent_check.py new file mode 100644 index 0000000000..906172e728 --- /dev/null +++ b/tests/startup_quad_divergent_check.py @@ -0,0 +1,86 @@ +"""X2W_PS_QUAD_DIVERGENT=1 in tools/startup/gfx2hlsl.py: quad reads and image_sample_b where a lane may skip them. + +Off (the default), a quad read (DPP quad_perm) on a path some lane avoids and an image_sample_b after a branch are +refused, as before. On, both are lowered in forward control flow. That is exact only where the four lanes of each +quad take the same path: D3D leaves quad reads and implicit derivatives undefined for lanes outside the control +flow, while the hardware reads inactive lanes (DPP fi:1). Loops stay refused either way, and a pipeline that used +the switch says `quaddivergent 1` in its manifest; one that did not use it has no such line even with the switch on. + +Fixtures: startup_quad_dpp_check's stage with s_cbranch_execz over the first quad read, and its backward-branch +loop; startup_image_sample_b_local_check's stage with an s_cbranch_scc0 before the sample, and a loop form of it. The +environment variable is read when the stage is built, so the test sets and clears it around each pipeline. +""" +import os +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_quad_dpp_check as Q # noqa: E402 +import startup_image_sample_b_local_check as B # noqa: E402 + +FLAG = 'X2W_PS_QUAD_DIVERGENT' + + +def build(make, value): + saved = os.environ.pop(FLAG, None) + if value is not None: + os.environ[FLAG] = value + try: + return make() + finally: + os.environ.pop(FLAG, None) + if saved is not None: + os.environ[FLAG] = saved + + +def refused(make, value, text): + try: + build(make, value).hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (text, str(error)) + return + raise AssertionError('accepted with %s=%s, expected %r' % (FLAG, value, text)) + + +def main(): + skip = Q.program(prefix=struct.pack('> 1) + return 8 * py + px + (1000 if neighbor != skipped else 0) + return source(lane ^ 1) + 2 * source(lane ^ 2) + 4 * source(skipped) + + +def draw_fixture(directory, compiler, renderer, skipped, wrong): + s = G.Stage.__new__(G.Stage) + reads = ['uint a = QuadReadAcrossX(v);', 'uint b = QuadReadAcrossY(v);', + 'uint c = QuadReadLaneAt(v, %du);' % skipped] + s.uniform_dpp = set(reads) + s.blocks = [(0, [], ('branch', 'lane == %du' % skipped, 2)), + (1, ['v += 1000u;'] + reads + ['result = a + 2u * b + 4u * c;'], None), + (2, ['++visits;'], ('branch', 'visits < 1u + lane', 2)), + (3, [], ('end',))] + expected = [reference(x, y, skipped) for y in range(8) for x in range(8)] + src = directory / 'test.hlsl' + obj = directory / 'test.cso' + raw = directory / 'test.raw' + src.write_text('static const uint ref[64] = {%s};\n' % ','.join(map(str, expected)) + + 'float4 main(float4 uv : TEXCOORD0, float4 pos : SV_Position) : SV_Target {\n' + 'uint x = uint(pos.x), y = uint(pos.y), p = 8*y + x;\n' + 'uint lane = (x & 1u) + 2u*(y & 1u), v = p, result = 2000u + p, visits = 0u;\n' + + ('if (lane == %du) v += 3000u;\n' % skipped if wrong else '') + + '\n'.join(s.body()) + + '\nreturn result == ref[p] ? float4(0,1,0,1) : float4(1,0,0,1); }\n') + subprocess.run([compiler, '-nologo', '-T', 'ps_6_0', '-E', 'main', '-Fo', obj, src], check=True) + raw.unlink(missing_ok=True) + run = subprocess.run([renderer, 'warp', '--check-pixel-quad-lod', obj, raw], capture_output=True) + assert raw.exists(), (run.returncode, run.stdout, run.stderr) + pixels = list(struct.iter_unpack('<4f', raw.read_bytes())) + assert len(pixels) == 64 + for y in range(8): + for x in range(8): + lane = (x & 1) + 2 * (y & 1) + expected_pixel = (-1,-1,-1,-1) if x+y > 6 else (1,0,0,1) if wrong and lane != skipped else (0,1,0,1) + assert pixels[8*y+x] == expected_pixel, (skipped, wrong, x, y, pixels[8*y+x], expected_pixel) + assert bool(run.returncode) == wrong, (run.stdout, run.stderr) + + +def main(): + os.environ.pop('X2W_PS_QUAD_DIVERGENT', None) + os.environ['X2W_PS_QUAD_UNIFORM'] = '1' + stage = Q.mesh_pipeline(Q.program(prefix=struct.pack('; if (exec & 1) v1 = xv1;`, the first reading s22, each later one + reading xv1, and `s23 = xv1;`. The shadow is declared `uint xv1 = 0;`. +2. A two-register chain (v_cvt_f32_u32 v1, s22; v_rcp_f32 v2, v1): both v1 and v2 get shadows, xv2 reads xv1. +Controls (refused): a link that reads a per-lane value (v_mul_f32 v1, v0, v1); exec written inside the chain +(epoch changes); exec written between the chain and the read; a branch target inside the chain. +Negative control of the change: with partial_shadow limited to lane-invariant expressions (the earlier rule, which +accepted one write only), case 1 is refused again. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class TestPipeline: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def vop1(op, vdst, src0): + return 0x7e000000 | vdst << 17 | op << 9 | src0 + + +def vop2(op, vdst, src0, vsrc1): + return op << 25 | vdst << 17 | vsrc1 << 9 | src0 + + +V = lambda n: 256 + n # noqa: E731 VGPR source operand +CVT_F32_U32, CVT_U32_F32, RCP_F32, READFIRSTLANE, MOV = 6, 7, 0x2a, 2, 1 +MUL_F32 = 8 +LITERAL = 255 + +V_CMP_LT_U32_VCC_V0 = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 +AND_SAVEEXEC = 0xbe800000 | 20 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[20:21], vcc +AND_SAVEEXEC2 = 0xbe800000 | 24 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[24:25], vcc +RESTORE_EXEC = 0xbe800000 | 126 << 16 | 0x04 << 8 | 20 # s_mov_b64 exec, s[20:21] +NOP_BRANCH = 0xbf820000 # s_branch to the next instruction +READ = vop1(READFIRSTLANE, 23, V(1)) # v_readfirstlane_b32 s23, v1 (vdst is the SGPR) +READ_V2 = vop1(READFIRSTLANE, 23, V(2)) # v_readfirstlane_b32 s23, v2 +USE = vop1(MOV, 3, 23) # v_mov_b32 v3, s23 + +C1 = vop1(CVT_F32_U32, 1, 22) # v_cvt_f32_u32 v1, s22 +C2 = vop1(RCP_F32, 1, V(1)) # v_rcp_f32 v1, v1 +C3 = [vop2(MUL_F32, 1, LITERAL, 1), 0x4f7ffffe] # v_mul_f32 v1, 0x4f7ffffe, v1 +C3_LANE = vop2(MUL_F32, 1, V(0), 1) # v_mul_f32 v1, v0, v1 +C4 = vop1(CVT_U32_F32, 1, V(1)) # v_cvt_u32_f32 v1, v1 +ENTER = [V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC] +CHAIN = [C1, C2] + C3 + [C4] + + +def stage(words): + return G.Stage(TestPipeline(), 'vs', struct.pack('<%dI' % (len(words) + 1), *words, 0xbf810000)) + + +def asm(words): + return [x[3] for x in G.decode(struct.pack('<%dI' % len(words), *words))] + + +def body(s): + return [line for block in s.blocks for line in block[1]] + + +def refused(words, label): + try: + stage(words) + except G.Unsupported as error: + assert 'requires a proven uniform source' in str(error), (label, str(error)) + return + raise AssertionError('accepted: ' + label) + + +def main(): + got = asm(ENTER + CHAIN + [READ, USE, READ_V2, C3_LANE]) + assert got == ['v_cmp_lt_u32_e32 vcc_lo, 1, v0', 's_and_saveexec_b64 s[20:21], vcc', 'v_cvt_f32_u32_e32 v1, s22', + 'v_rcp_f32_e32 v1, v1', 'v_mul_f32_e32 v1, 0x4f7ffffe, v1', 'v_cvt_u32_f32_e32 v1, v1', + 'v_readfirstlane_b32 s23, v1', 'v_mov_b32_e32 v3, s23', 'v_readfirstlane_b32 s23, v2', + 'v_mul_f32_e32 v1, v0, v1'], got + + # 1. the reciprocal chain + s = stage(ENTER + CHAIN + [READ, USE]) + lines = body(s) + shadowed = [line for line in lines if line.startswith('xv1 = ')] + assert len(shadowed) == 4, lines + for line in shadowed: + assert line.endswith('; if (exec & 1) v1 = xv1;'), line + assert 's22' in shadowed[0] and not re.search(r'\bv\d+\b', shadowed[0].split(';')[0]), shadowed + for line in shadowed[1:]: + rhs = line.split(';')[0] + assert 'xv1' in rhs[len('xv1 = '):] and not re.search(r'\bv\d+\b', rhs), line + assert 's23 = xv1;' in lines, lines + assert lines.index(shadowed[-1]) < lines.index('s23 = xv1;'), lines + assert 'uint xv1 = 0;' in '\n'.join(s.declarations()), s.declarations() + + # 2. a chain through two registers + two = ENTER + [C1, vop1(RCP_F32, 2, V(1)), READ_V2, USE] + lines = body(stage(two)) + first = [line for line in lines if line.startswith('xv1 = ')] + second = [line for line in lines if line.startswith('xv2 = ')] + assert len(first) == 1 and len(second) == 1, lines + assert 'xv1' in second[0].split(';')[0][len('xv2 = '):], second + assert lines.index(first[0]) < lines.index(second[0]) < lines.index('s23 = xv2;'), lines + + # Controls. + refused(ENTER + [C1, C2, C3_LANE, C4, READ], 'a link reads a per-lane VGPR') + refused(ENTER + [C1, C2, V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC2] + C3 + [C4, READ], 'exec written inside the chain') + refused(ENTER + CHAIN + [RESTORE_EXEC, READ], 'exec written between the chain and the read') + refused(ENTER + [C1, C2, NOP_BRANCH] + C3 + [C4, READ], 'branch target inside the chain') + + # Negative control: the earlier rule (a shadow only for an expression with no VGPR at all). + original = G.Stage.partial_shadow + + def single(self, expr): + return (expr, []) if self.lane_invariant(expr) else None + G.Stage.partial_shadow = single + try: + refused(ENTER + CHAIN + [READ, USE], 'chain shadow disabled') + finally: + G.Stage.partial_shadow = original + print('readfirstlane_chain: 4-write reciprocal chain and a 2-register chain read via shadows xv1/xv2; ' + '4 controls refused; negative control (single-write rule) refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_readfirstlane_exec_check.py b/tests/startup_readfirstlane_exec_check.py new file mode 100644 index 0000000000..a7412d826e --- /dev/null +++ b/tests/startup_readfirstlane_exec_check.py @@ -0,0 +1,124 @@ +"""v_readfirstlane_b32 of a buffer word loaded from a lane-invariant address, also under a partial exec. + +Synthetic gfx1013 words only. The shape is what the run's pixel programs use for a constant read through a +typed or raw buffer inside a branch: `buffer_load_* vN, off, s[..]` (no VGPR address, so every lane reads the +same address) followed by `v_readfirstlane_b32 sM, vN` to move the word to an SGPR. + +AMD RDNA 2 ISA: V_READFIRSTLANE_B32 copies S0 of the first active lane (lane 0 when exec is zero) to the SGPR. +A VGPR write under a partial exec changes only the active lanes, so the first active lane holds the loaded value +as long as exec has not been written between the load and the read. The SGPR belongs to the wave, so the +translation gives every lane that value from a shadow variable assigned in all lanes at the load (lanes that are +inactive keep their own VGPR value). + +1. exec known (entry mask): a load with no VGPR address is lane-invariant, so readfirstlane reads it directly. +2. exec partial (after s_and_saveexec_b64): the load's line becomes `xv1 = ...; if (exec & 1) v1 = xv1;` and the + SGPR takes xv1. +Controls (refused): a VGPR address (offen v0); exec written between the load and the read; the read at a branch +target; a partial-exec value that is not lane-invariant (v0). Negative control of the whole change: with the +shadow record dropped after every VGPR write, case 2 is refused again. +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class TestPipeline: + root = {'params': [{'type': 2}], 'flags': 0} + + def resource(self, key, kind): + assert key == (('root', 0), None) and kind == 'buf', (key, kind) + return 'r0' + + def ud(self, source): + return 0 + + +def load_off(vdst, offset): # buffer_load_dword vD, off, s[8:11], 0 offset:N + return [0xe0000000 | 12 << 18 | offset, vdst << 8 | 2 << 16 | 128 << 24] + + +def load_offen(vdst, vaddr): # buffer_load_dword vD, vA, s[8:11], 0 offen + return [0xe0000000 | 12 << 18 | 1 << 12, vaddr | vdst << 8 | 2 << 16 | 128 << 24] + + +V_CMP_LT_U32_VCC_V0 = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 +AND_SAVEEXEC = 0xbe800000 | 20 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[20:21], vcc +RESTORE_EXEC = 0xbe800000 | 126 << 16 | 0x04 << 8 | 20 # s_mov_b64 exec, s[20:21] +READ = 0x7e000000 | 10 << 17 | 2 << 9 | 257 # v_readfirstlane_b32 s10, v1 +READ_V0 = 0x7e000000 | 10 << 17 | 2 << 9 | 256 # v_readfirstlane_b32 s10, v0 +V_MOV_V1_V0 = 0x7e000000 | 1 << 17 | 1 << 9 | 256 # v_mov_b32 v1, v0 +USE = 0x7e000000 | 2 << 17 | 1 << 9 | 10 # v_mov_b32 v2, s10 +NOP_BRANCH = 0xbf820000 # s_branch to the next instruction + + +def stage(words): + return G.Stage(TestPipeline(), 'vs', struct.pack('<%dI' % (len(words) + 1), *words, 0xbf810000)) + + +def asm(words): + return [x[3] for x in G.decode(struct.pack('<%dI' % len(words), *words))] + + +def body(s): + return '\n'.join(line for block in s.blocks for line in block[1]) + + +def refused(words, label): + try: + stage(words) + except G.Unsupported as error: + assert 'requires a proven uniform source' in str(error), (label, str(error)) + return + raise AssertionError('accepted: ' + label) + + +def main(): + assert asm(load_off(1, 16)) == ['buffer_load_dword v1, off, s[8:11], 0 offset:16'], asm(load_off(1, 16)) + assert asm(load_offen(1, 0)) == ['buffer_load_dword v1, v0, s[8:11], 0 offen'], asm(load_offen(1, 0)) + assert asm([V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC, RESTORE_EXEC, READ]) == [ + 'v_cmp_lt_u32_e32 vcc_lo, 1, v0', 's_and_saveexec_b64 s[20:21], vcc', 's_mov_b64 exec, s[20:21]', + 'v_readfirstlane_b32 s10, v1'], asm([V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC, RESTORE_EXEC, READ]) + + # 1. exec known + text = body(stage(load_off(1, 16) + [READ, USE])) + assert 's10 = v1;' in text, text + + # 2. exec partial + partial = [V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC] + load_off(1, 16) + [READ, RESTORE_EXEC, USE] + text = body(stage(partial)) + assert 'xv1 = r0.Load(a + 0); if (exec & 1) v1 = xv1;' in text, text + assert 's10 = xv1;' in text, text + lines = text.split('\n') + assert lines.index('a = 16;') < lines.index('xv1 = r0.Load(a + 0); if (exec & 1) v1 = xv1;'), text + s = stage(partial) + assert 'uint xv1 = 0;' in '\n'.join(s.declarations()), s.declarations() + + # Controls. + refused(load_offen(1, 0) + [READ], 'VGPR address, exec known') + refused([V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC] + load_offen(1, 0) + [READ], 'VGPR address, exec partial') + refused([V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC] + load_off(1, 16) + [RESTORE_EXEC, READ], + 'exec written between the load and the read') + refused([V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC] + load_off(1, 16) + [NOP_BRANCH, READ], 'read at a branch target') + refused([V_CMP_LT_U32_VCC_V0, AND_SAVEEXEC, V_MOV_V1_V0, READ], 'per-lane value under partial exec') + + # Negative control: without the shadow the partial-exec case is the old refusal. + original = G.Stage.set_v + + def no_shadow(self, n, expr): + original(self, n, expr) + self.partial_uniform.clear() + G.Stage.set_v = no_shadow + try: + refused(partial, 'shadow disabled') + finally: + G.Stage.set_v = original + print('readfirstlane_exec: invariant-address load read with exec known and partial (shadow xv1); ' + '5 controls refused; negative control (shadow off) refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index fa6fbaf4c5..4f32d7ab6f 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -55,6 +55,8 @@ extern "C" __declspec(dllimport) BOOL x2w_d3d12_written_probe(void*, unsigned lo extern "C" __declspec(dllimport) void x2w_d3d12_bc7_4k_s_written(void*, UINT, UINT); extern "C" __declspec(dllimport) void x2w_d3d12_list_copy_texture_stats(LONG*, LONG*); +extern "C" __declspec(dllimport) int WINAPI x2w_memory_counters(char*, int); + namespace { using namespace x2w_budget; @@ -371,7 +373,7 @@ constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel constexpr int draw_seed = 77; constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM -constexpr char draw_revision[] = "x2w-startup-shader-17"; // d3d12_draw.inl cached_translation +constexpr char draw_revision[] = "x2w-startup-shader-3"; // d3d12_draw.inl cached_translation constexpr char draw_vertex_shader[] = R"( struct Varying { float4 position : SV_Position; }; @@ -973,12 +975,68 @@ bool case7_draw_samples_slot133_texture(Context& c, void* title_mem) return check_target("readback after the texture left the budget", target_bytes.data(), row_pitch); } +// Count successful desktop priority changes and verify the same resource survives an observed reuse. +bool cold_texture_check(Context& c, void* address, bool enabled) +{ + auto expect = [&](unsigned cold, unsigned restored) { + char text[2048]{}; + if (!x2w_memory_counters(text, sizeof(text))) return false; + if (!enabled) return !std::strstr(text, "cold-priority"); + char expected[192]{}; + std::snprintf(expected, sizeof(expected), "cold-priority bytes/count %llu/%u, restored %llu/%u, failures 0", + c.texture_bytes * cold, cold, c.texture_bytes * restored, restored); + if (std::strstr(text, expected)) return true; + std::printf("FAIL: expected %s in %s\n", expected, text); + return false; + }; + Res& texture = c.make_slot133("cold texture", address); + IUnknown* guest = texture.guest.Get(); + auto original = desktop_object(c.guest, c.device, guest); + if (!original || !expect(0, 0)) return false; + c.release(texture); + if (!expect(1, 0)) return false; + guest->AddRef(); + if (!expect(0, 1)) return false; + auto same = desktop_object(c.guest, c.device, guest); + if (same.Get() != original.Get()) return false; + guest->Release(); + if (!expect(0, 1)) return false; + // An actual SRV creation is an observed reuse even when the guest never AddRefs the wrapper. + Res& viewed = c.make_slot133("cold sampled SRV", address); + auto* raw = viewed.guest.Get(); + c.release(viewed); + if (!expect(1, 1)) return false; + const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 address, bytes; } + heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}, 0, 0}; + ComPtr heap; + if (!require(invoke(c.guest, 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap.GetAddressOf()), "cold test SRV heap")) return false; + const auto handle = invoke(heap.Get(), 9); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + invoke(c.guest, 18, raw, &srv, handle); + if (!expect(0, 2)) return false; + Res& ordinary = c.make_committed("ordinary committed texture"); + c.release(ordinary); + c.desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + Res& target = c.make_slot133("render target", address); + c.desc.Flags = D3D12_RESOURCE_FLAG_NONE; + c.release(target); + if (!expect(0, 2)) return false; + // A copy behind a held queue still reads the original pixels after the source's last guest Release. + if (!case1_slot133_copy_and_upload(c, false, address)) return false; + std::puts("cold texture priority: lower, restore, stable object and fenced texture readback passed"); + return true; +} + } // namespace int main(int argc, char** argv) { if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || - (argc == 3 && std::strcmp(argv[2], "off"))) + (argc == 3 && std::strcmp(argv[2], "off") && std::strcmp(argv[2], "cold") && std::strcmp(argv[2], "cold-off"))) return 2; ComPtr factory; if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; @@ -1014,6 +1072,7 @@ int main(int argc, char** argv) char switch_value[2]{}; const bool switch_on = GetEnvironmentVariableA("X2W_D3D12_RELEASE_RETIRED", switch_value, sizeof(switch_value)) == 1 && switch_value[0] == '1'; + const bool cold_mode = argc == 3 && (!std::strcmp(argv[2], "cold") || !std::strcmp(argv[2], "cold-off")); const bool off_mode = argc == 3; if (switch_on == off_mode) return 2; const bool on = !off_mode; @@ -1048,22 +1107,26 @@ int main(int argc, char** argv) if (!c.make_queue(c.direct) || !c.make_queue(c.gated) || !c.make_list(c.drain_list) || !c.close(c.drain_list)) return 4; if (!x2w_d3d12_budget_snapshot(&c.base, sizeof(c.base))) return 4; - if (!case1_slot133_copy_and_upload(c, on, mem1)) return 5; - std::puts("1 slot 133 copy and upload: held across closed list and gated submit, readback ok, retired"); - if (!case2_same_address_and_slot70_reuse(c, on, mem1)) return 5; - std::puts("2 same-address and slot 70 reuse: existing_memory_texture + resource_address_index ok"); - if (!case3_written_textures_cleanup(c, on, mem1, mem2)) return 5; - std::puts("3 written_textures cleanup: stale bc7_width cleared on address reuse"); - if (!case4_descriptor_and_view_reuse(c, on, mem1, mem2)) return 5; - std::puts("4 descriptor and view reuse: tracked slot-18 SRV holds and retires on overwrite/heap release"); - if (!on) { - if (!case5_ordinary_upload_switch_off(c)) return 5; - std::puts("5 switch-off ordinary texture copy: upload still recorded for a resource outside the retire class"); + if (cold_mode) { + if (!cold_texture_check(c, mem1, !std::strcmp(argv[2], "cold"))) return 5; } else { - if (!case6_written_generation_preserved(c, mem3)) return 5; - std::puts("6 written_textures generation: newer generation of an address kept by the older one's retirement"); - if (!case7_draw_samples_slot133_texture(c, mem1)) return 5; - std::puts("7 translated draw: slot 133 texture sampled through a descriptor table, held until the recording drained"); + if (!case1_slot133_copy_and_upload(c, on, mem1)) return 5; + std::puts("1 slot 133 copy and upload: held across closed list and gated submit, readback ok, retired"); + if (!case2_same_address_and_slot70_reuse(c, on, mem1)) return 5; + std::puts("2 same-address and slot 70 reuse: existing_memory_texture + resource_address_index ok"); + if (!case3_written_textures_cleanup(c, on, mem1, mem2)) return 5; + std::puts("3 written_textures cleanup: stale bc7_width cleared on address reuse"); + if (!case4_descriptor_and_view_reuse(c, on, mem1, mem2)) return 5; + std::puts("4 descriptor and view reuse: tracked slot-18 SRV holds and retires on overwrite/heap release"); + if (!on) { + if (!case5_ordinary_upload_switch_off(c)) return 5; + std::puts("5 switch-off ordinary texture copy: upload still recorded for a resource outside the retire class"); + } else { + if (!case6_written_generation_preserved(c, mem3)) return 5; + std::puts("6 written_textures generation: newer generation of an address kept by the older one's retirement"); + if (!case7_draw_samples_slot133_texture(c, mem1)) return 5; + std::puts("7 translated draw: slot 133 texture sampled through a descriptor table, held until the recording drained"); + } } } catch (int code) { VirtualFree(mem1, 0, MEM_RELEASE); @@ -1077,6 +1140,6 @@ int main(int argc, char** argv) const UINT64 errors = debug ? debug->GetNumStoredMessages() : 0; std::printf("debug_errors_or_warnings=%llu\n", errors); if (errors || FAILED(device->GetDeviceRemovedReason())) return 4; - std::puts(on ? "release-retired title checks passed" : "switch-off title checks passed"); + if (!cold_mode) std::puts(on ? "release-retired title checks passed" : "switch-off title checks passed"); return 0; } diff --git a/tests/startup_root_cbv.cpp b/tests/startup_root_cbv.cpp index 9af9dfb7de..a04f920a23 100644 --- a/tests/startup_root_cbv.cpp +++ b/tests/startup_root_cbv.cpp @@ -39,6 +39,8 @@ int draw_root_cbv(void* list) } else if (!std::strcmp(mode, "wrong_type")) { invoke(list, 42, 0, address); invoke(list, 42, 0, address); + } else if (!std::strcmp(mode, "root_srv")) { + invoke(list, 44, 0, address); } else if (std::strcmp(mode, "unbound")) { return 2; } diff --git a/tests/startup_root_srv_lazy_check.py b/tests/startup_root_srv_lazy_check.py new file mode 100644 index 0000000000..c42a5baec0 --- /dev/null +++ b/tests/startup_root_srv_lazy_check.py @@ -0,0 +1,38 @@ +"""Startup root srv lazy check.""" +from pathlib import Path +import sys +import tempfile + +from startup_address_srv_check import draw_texture +from startup_root_cbv_check import CLEAR, HLSL + + +def check(directory, consumer, backend): + yellow = bytes((255, 255, 0, 255)) + expected = (yellow * 4 + CLEAR * 4) * 4 + for lazy in (False, True): + folder = directory / ("lazy" if lazy else "copy") + folder.mkdir() + log_path = folder / "trap.log" + env = {"X2W_TEST_ROOT_CBV": "root_srv", "X2W_TRAP_LOG": str(log_path)} + if lazy: + env["X2W_ROOT_SRV_LAZY"] = "1" + pixels = draw_texture(folder, consumer, backend, HLSL, env, binding="srv 0 buf root 0") + if pixels is None: + return 77 + log = log_path.read_text(errors="replace") if log_path.exists() else "" + copied = "x2w-render root SRV 0 at title" in log + deferred = "X2W_ROOT_SRV_LAZY=1: root SRVs are copied at a real-pipeline draw only" in log + print(f"{backend} lazy={int(lazy)}: pixels {'exact' if pixels == expected else 'DIFFER'}, record-time copy line {int(copied)}, " + f"deferred line {int(deferred)}") + if pixels != expected: + raise AssertionError(f"lazy={lazy}: actual {pixels.hex()} expected {expected.hex()}") + if copied == lazy or deferred != lazy: + raise AssertionError(f"lazy={lazy}: copy line {copied}, deferred line {deferred}") + print("PASS") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_round_mode_check.py b/tests/startup_round_mode_check.py new file mode 100644 index 0000000000..6f31c53250 --- /dev/null +++ b/tests/startup_round_mode_check.py @@ -0,0 +1,389 @@ +"""s_round_mode (MODE[3:0], the f32 and f16/f64 rounding) in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + draw [fxc] + translate, compile (FXC ps_5_1 when given, DXC ps_6_0), draw one pixel (the + startup_flat_param renderer) and compare the words + +MODE[1:0] rounds f32 results and MODE[3:2] f16 and f64 results; 0 is nearest even, 3 toward zero (LLVM SIDefines.h +FP_ROUND_MODE_SP / FP_ROUND_MODE_DP and FP_ROUND_ROUND_TO_*; Mesa aco_ir.h struct float_mode round32 / round16_64). +The form the pixel stages use is 0xc: f32 to nearest even, f16/f64 toward zero. + +The pixel stage (hand-assembled, the decoder reads it back) starts with s_round_mode 0xc, rounds eight f32 values to +binary16 with v_fma_mixlo_f16 / v_fma_mixhi_f16 (x * 1.0 + 0, f32 operands) and v_cvt_f16_f32, and exports the four +packed words to mrt0. The expected words are computed here by truncating the f32 mantissa (an independent rule, not +the helper's step-back); three of the values round differently to nearest even. v_interp_p2_f16 (the stage of +startup_interp_f16_check with s_round_mode 0xc first) is checked as text. + +Without s_round_mode (MODE 0) the same stage rounds to nearest even through x2w_f32tof16_rne, and its draw must give +the nearest-even words. MEASURED (fxc ps_5_1 and dxc ps_6_0, WARP and an RX 9070 XT): HLSL f32tof16 alone rounds +these values toward zero (70000 -> 0x7bff), which is why both helpers exist; the draw prints that as information. +Controls: without the s_round_mode handler the stage refuses as before; the toward-zero stage does not match the +nearest-even words (the comparison separates the roundings); both helpers' rules are checked on the CPU over f32tof16 +modelled toward zero and nearest even (the draw cannot exercise the toward-zero helper's step-back there). s_round_mode 0x1 (f32 toward +inf), 0x4 (f16 toward ++inf) are refused; one after a branch is lowered when every path sets it, refused when a path skips it; an f16 instruction that rounds and is not lowered for the mode (the SDWA +v_cvt_f16_f32) is refused under 0xc and accepted without it. + +The launch FLOAT_MODE (SPI_SHADER_PGM_RSRC1_PS bits 19:12, the optional third .psin field) starts MODE: 0xcc rounds +f16 toward zero without any s_round_mode, 0xc0 and a request without the field round to nearest even; other modes are +refused. Control: with launch_mode disabled the 0xcc stage stays nearest even. The draw also checks the 0xcc stage. +""" +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import VS_WORDS, root_blob, compile_hlsl, draw # noqa: E402 + +# f32 inputs: 1 + 0.75 ulp(f16), its negative, 70000 (above the binary16 range), 1/3, 0.1, -1000.7, 1.5 * 2^-14, pi +VALUES = (0x3f801800, 0xbf801800, 0x4788b800, 0x3eaaaaab, 0x3dcccccd, 0xc47a2ccd, 0x38c00000, 0x40490fdb) + + +def f16_toward_zero(bits): + """binary16 of an f32 rounded toward zero, by truncation; only finite values whose result is normal or the + largest finite binary16 (overflow) are used here.""" + sign, exp, mant = bits >> 31, (bits >> 23) & 0xff, bits & 0x7fffff + e = exp - 127 + 15 + assert exp != 0xff and e >= 1, hex(bits) + h = 0x7bff if e >= 31 else e << 10 | mant >> 13 + return sign << 15 | h + + +def f16_nearest(bits): + try: + return struct.unpack('> 31) << 15 | 0x7c00 + + +def words(rule): + h = [rule(v) for v in VALUES] + return [h[i] | h[i + 1] << 16 for i in range(0, 8, 2)] + + +EXPECTED = ','.join('%08x' % w for w in words(f16_toward_zero)) + + +def v_mov_literal(reg, value): + return struct.pack(' a: + t -= 1 + if t & 0x7c00 == 0x7c00: + return t + lo = abs(f16_value(t)) + if a == lo: + return t + u = t + 1 + hi = 65536.0 if u & 0x7fff == 0x7c00 else abs(f16_value(u)) + dl, dh = a - lo, hi - a + return u if dh < dl or (dh == dl and t & 1) else t + + +def check_rne_rule(): + """x2w_f32tof16_rne against Python's binary16 (struct 'e', round to nearest even, OverflowError past 65519.99) + for f32tof16 modelled both ways: toward zero (MEASURED on WARP and an RX 9070 XT) and nearest even. The cases + cover normal, subnormal (2^-24 .. 2^-14) and overflow (65504 .. 2^17) results and the exact ties.""" + import random + rng = random.Random(2) + def truncate(bits): # toward zero, for any finite value (subnormals and overflow included) + h = f16_nearest(bits) + x = struct.unpack(' abs(x) else h + ties = [struct.unpack(' abs(x) else h + stepped += got != h + assert got == f16_toward_zero(bits), (hex(bits), base.__name__, hex(got)) + assert stepped > 5000, stepped + print('x2w_f32tof16_rtz rule: %d values, nearest-even and toward-zero f32tof16, %d step-backs, all match ' + 'truncation' % (len(cases), stepped)) + print('s_round_mode 0xc: f16 results of fma_mix and v_cvt_f16_f32 round toward zero (x2w_f32tof16_rtz); ' + 'without it, or with 0, nearest even (x2w_f32tof16_rne)') + saved = G.Stage.op_s_round_mode + del G.Stage.op_s_round_mode + try: + refused(pixel_words(), 's_round_mode') + finally: + G.Stage.op_s_round_mode = saved + refused(pixel_words(mode=0x1), 's_round_mode 0x1 (only f32 nearest even') + refused(pixel_words(mode=0x4), 's_round_mode 0x4 (only f32 nearest even') + assert G.decode(pixel_words(branch=True))[0][3].startswith('s_cbranch_scc0') + # after a branch that every path follows to the mode: the mode is known (round_mode_flow), lowered toward zero + assert 'x2w_f32tof16_rtz(F(v12))' in pipe(pixel_words(branch=True)).hlsl_ps() + # a path that skips the s_round_mode reaches the f16 ops with launch 0 and 3: refused + assert G.decode(pixel_words(skip=True))[0][3].startswith('s_cbranch_scc1') + refused(pixel_words(skip=True), 'v_fma_mixlo_f16 at 0x') + refused(pixel_words(skip=True), 'reached under MODE f16 roundings [0, 3] (the translation uses 3)') + # ... and with the launch mode 0xcc both paths bring toward zero: accepted + assert 'x2w_f32tof16_rtz(F(v12))' in pipe(pixel_words(skip=True), launch=0xcc).hlsl_ps() + # negative control: without round_mode_flow the skipped path is lowered as toward zero (wrong for it) + saved_flow = G.Stage.round_mode_flow + G.Stage.round_mode_flow = lambda self: {} + try: + assert 'x2w_f32tof16_rtz(F(v12))' in pipe(pixel_words(skip=True)).hlsl_ps() + finally: + G.Stage.round_mode_flow = saved_flow + # s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 4), 12 (SOPK 0x15) after the mode: a MODE write the tracking misses + setreg = struct.pack('.vsregs or the per-state + dumps .<8 hex>.vsregs when they agree; and translate_request's use of it (.psin without the field).""" + def block(mode, size=0x100): + b = bytearray(size) + if size >= 0x50: + struct.pack_into(' +#include +#include +#include + +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) unsigned x2w_d3d12_target_bind_stats(unsigned* counts, unsigned capacity); + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e); +} +bool ok(Word hr) { return SUCCEEDED(static_cast(hr)); } + +// TargetBind order in d3d12_xs_device.cpp. +enum Outcome { bound, single_bound, not_recording, over_8, unreadable, past_heap, wrong_kind, unresolved, empty, + depth_kind, depth_unknown, depth_plane, outcome_count }; +const char* const names[] = {"bound", "single-range bound", "not recording", "count over 8", "handles unreadable", + "range past heap", "wrong kind", "unresolved", "empty", "depth wrong kind", + "depth unknown", "depth one plane"}; + +struct Stats { + unsigned n[outcome_count] = {}; + static Stats read() + { + Stats s; + x2w_d3d12_target_bind_stats(s.n, outcome_count); + return s; + } +}; + +// Exactly one new outcome since `before`, and it is `want` (or `also`, when given). +bool step(const char* name, Outcome want, Stats& before, int also = -1) +{ + const Stats now = Stats::read(); + unsigned total = 0; + int got = -1; + for (int i = 0; i < outcome_count; ++i) { + const unsigned added = now.n[i] - before.n[i]; + total += added; + if (added) got = i; + } + before = now; + const bool good = total == 1 && (got == want || got == also); + std::printf("%s: %u new outcome(s), last %s (expected %s%s%s)\n", name, total, got >= 0 ? names[got] : "none", names[want], + also >= 0 ? " or " : "", also >= 0 ? names[also] : ""); + return good; +} + +UINT64 debug_errors(ID3D12Device* desktop) +{ + ComPtr info; + if (FAILED(desktop->QueryInterface(IID_PPV_ARGS(&info)))) return 0; + UINT64 errors = 0; + for (UINT64 i = 0, n = info->GetNumStoredMessages(); i < n; ++i) { + SIZE_T bytes = 0; + if (FAILED(info->GetMessage(i, nullptr, &bytes))) continue; + std::vector storage(bytes); + auto* message = reinterpret_cast(storage.data()); + if (FAILED(info->GetMessage(i, message, &bytes))) continue; + if (message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { + ++errors; + std::printf("debug layer: %.*s\n", static_cast(message->DescriptionByteLength), message->pDescription); + } + } + return errors; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + std::printf("adapter=%ls\n", adapter_desc.Description); + + std::array parameters{}; + void* device = nullptr; + ComPtr desktop; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &device))) return 4; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 4; + + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC target_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0, 0, 0, 0}}; + ComPtr targets[2]; + for (auto& target : targets) + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_COMMON, + &clear, IID_PPV_ARGS(&target)))) return 5; + + // The RTV heap: views 0 and 1 over the two targets, slot 2 empty; and a one-descriptor staging heap. + const auto make_heap = [&](UINT count, void** out) { + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, count}, 0, 0}; + return ok(invoke(device, 14, arg(&desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(out))); + }; + void *rtv_heap = nullptr, *staging_heap = nullptr; + if (!make_heap(3, &rtv_heap) || !make_heap(1, &staging_heap)) return 6; + // The title's stride: the stand-in forwards GetDescriptorHandleIncrementSize (device slot 15). + const UINT stride = static_cast(invoke(device, 15, D3D12_DESCRIPTOR_HEAP_TYPE_RTV)); + std::printf("RTV stride as the title sees it: %u (desktop %u)\n", stride, + desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)); + const D3D12_CPU_DESCRIPTOR_HANDLE first{static_cast(invoke(rtv_heap, 9))}; + const std::array rtv{{first, {first.ptr + stride}, {first.ptr + 2 * stride}}}; + const D3D12_CPU_DESCRIPTOR_HANDLE staging{static_cast(invoke(staging_heap, 9))}; + D3D12_RENDER_TARGET_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + invoke(device, 20, arg(targets[0].Get()), arg(&view), rtv[0].ptr); + invoke(device, 20, arg(targets[1].Get()), arg(&view), rtv[1].ptr); + invoke(device, 20, arg(targets[0].Get()), arg(&view), staging.ptr); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *queue = nullptr, *fence = nullptr, *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 7; + if (!ok(invoke(list, 139, arg(allocator), 0))) return 8; + + const D3D12_CPU_DESCRIPTOR_HANDLE pair[] = {rtv[0], rtv[1]}; + Stats seen = Stats::read(); + invoke(list, 50, 1, arg(&rtv[0]), FALSE, 0); + if (!step("1 one handle", bound, seen)) return 10; + invoke(list, 50, 1, arg(&rtv[0]), TRUE, 0); + if (!step("2 single range, count 1", single_bound, seen)) return 11; + invoke(list, 50, 2, arg(&rtv[0]), TRUE, 0); + if (!step("3 single range, count 2", single_bound, seen)) return 12; + invoke(list, 50, 2, arg(pair), FALSE, 0); + if (!step("4 two handles", bound, seen)) return 13; + invoke(list, 50, 3, arg(&rtv[0]), TRUE, 0); + if (!step("5 single range reaching the empty view", unresolved, seen)) return 14; + invoke(list, 50, 4, arg(&rtv[0]), TRUE, 0); + if (!step("6 single range past the heap end", past_heap, seen, unresolved)) return 15; + invoke(list, 50, 1, arg(&rtv[2]), FALSE, 0); + if (!step("7 the empty view alone", unresolved, seen)) return 16; + invoke(list, 50, 0, 0, TRUE, 0); + if (!step("8 single range, count 0, null handles", empty, seen)) return 17; + invoke(list, 50, 9, arg(&rtv[0]), TRUE, 0); + if (!step("9 count above 8", over_8, seen)) return 18; + invoke(device, 24, 1, rtv[2].ptr, staging.ptr, D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + invoke(list, 50, 1, arg(&rtv[2]), FALSE, 0); + if (!step("10 copied view in the empty slot", bound, seen)) return 19; + + // An RTV heap over title memory: title handles differ from desktop ones and each target of a single range + // must be mapped on its own; the heap's end is known, so a range past it has its own reason. + void* backing = VirtualAlloc(nullptr, 3 * stride, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } backed_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 3}, reinterpret_cast(backing), Word{3} * stride}; + void* backed_heap = nullptr; + if (!backing || !ok(invoke(device, 14, arg(&backed_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&backed_heap)))) return 30; + const D3D12_CPU_DESCRIPTOR_HANDLE title_first{static_cast(invoke(backed_heap, 9))}; + std::printf("backed heap: title start 0x%llx, backing 0x%llx\n", static_cast(title_first.ptr), + static_cast(reinterpret_cast(backing))); + if (title_first.ptr != reinterpret_cast(backing)) return 31; + invoke(device, 20, arg(targets[0].Get()), arg(&view), title_first.ptr); + invoke(device, 20, arg(targets[1].Get()), arg(&view), title_first.ptr + stride); + invoke(list, 50, 2, arg(&title_first), TRUE, 0); + if (!step("11 backed heap, single range, count 2", single_bound, seen)) return 32; + invoke(list, 50, 3, arg(&title_first), TRUE, 0); + if (!step("12 backed heap, single range reaching the empty view", unresolved, seen)) return 33; + invoke(list, 50, 4, arg(&title_first), TRUE, 0); + if (!step("13 backed heap, single range past the heap end", past_heap, seen)) return 34; + + if (!ok(invoke(list, 9))) return 20; + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), 1))) return 21; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < 1) { + if (GetTickCount64() >= deadline) return 22; + Sleep(1); + } + const HRESULT removed = desktop->GetDeviceRemovedReason(); + const UINT64 errors = debug_errors(desktop.Get()); + std::printf("device removed reason: 0x%08lx, debug layer errors: %llu\n", static_cast(removed), + static_cast(errors)); + return removed == S_OK && errors == 0 ? 0 : 70; +} diff --git a/tests/startup_sample_c_border_check.py b/tests/startup_sample_c_border_check.py new file mode 100644 index 0000000000..aacefa7fa2 --- /dev/null +++ b/tests/startup_sample_c_border_check.py @@ -0,0 +1,70 @@ +"""image_sample_c_lz with SQ_TEX_CLAMP_BORDER (6) in sampler word 0 CLAMP_X / CLAMP_Y.""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import pixel_aot # noqa: E402 +import startup_image_sample_c_check as C # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, root_blob # noqa: E402 + +MEASURED = (0x30b6, 0x00c00000, 0x18500000, 0x80000000) + + +def s_mov(reg, value): + return struct.pack(' transparent black"); + expect(decode_sampler({0, 0x300u | 0x100u << 12, 0, 0}, 0, false, false, true).MaxLOD == 3.0f, "max below min raised to min"); + // Negative control: without the fields the old values stay (no bias, no LOD limit, transparent black). + const auto plain = decode_sampler({0, 0x180u | 0x280u << 12, 0x18503f80, 2u << 30}, 0, false, false, false); + expect(plain.MipLODBias == 0.0f && plain.MinLOD == 0.0f && plain.MaxLOD == D3D12_FLOAT32_MAX && + plain.BorderColor == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK, "fields dropped when off"); + const auto dynamic = x2w_startup::dynamic_sampler({0, 0, 0, 2u << 30}, true); + expect(dynamic.BorderColor[0] == 1.0f && dynamic.BorderColor[3] == 1.0f, "dynamic border white"); + const auto fallback = x2w_startup::border_sampler(); + expect(fallback.MaxLOD == D3D12_FLOAT32_MAX, "fallback sampler unlimited"); + } // An smpl line (image_sample_b) carries MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12), u4.8, to MinLOD and // MaxLOD; the same words on an smp line keep MinLOD 0 and an unbounded MaxLOD. x2w_startup::TranslatedSamplers limits; diff --git a/tests/startup_sampler_x.cpp b/tests/startup_sampler_x.cpp index a64ce2bd77..b9b58656d5 100644 --- a/tests/startup_sampler_x.cpp +++ b/tests/startup_sampler_x.cpp @@ -3,6 +3,7 @@ // translated sampler must reproduce: filter, per-axis address mode, border colour and LOD limits. #include "desktop_gpu.h" #include "startup_sampler_x_cs.h" +#include "startup_stubs/translated_sampler_bindings.h" #include #include @@ -59,6 +60,15 @@ constexpr std::array samplers{{ D3D12_FLOAT32_MAX}, }}; constexpr UINT word_count = static_cast(2 * point_probes.size() + linear_probes.size()); +// The three samplers above as SQ_IMG_SAMP words (word 0: CLAMP_X 2:0, CLAMP_Y 5:3; word 1: MIN_LOD 11:0, MAX_LOD 23:12, +// u4.8; word 2: XY_MAG 21:20, XY_MIN 23:22, MIP 27:26; word 3: BORDER_COLOR_TYPE 31:30, 2 = opaque white), for the +// words variants: the desktop samplers are then the translation (translated_sampler_bindings.h dynamic_sampler). +constexpr std::uint32_t white = 2u << 30; +constexpr std::array sampler_words{{ + {0u | 1u << 3, 256u | 512u << 12, 0u, white}, // wrap / mirror, LOD 1..2 + {2u | 6u << 3, 0u, 0u, white}, // clamp / border, LOD 0..0 + {2u | 2u << 3, 0xfffu << 12, 1u << 20 | 1u << 22 | 2u << 26, white}, // trilinear, clamp, no limit +}}; bool is_linear(const SamplerCase& s) { @@ -219,7 +229,9 @@ ComPtr create_root(ID3D12Device* device) } } -bool check_startup_sampler_x(ID3D12Device* device, bool swapped) +// words: 0 desktop samplers; 1 translated from sampler_words with the LOD and border fields; 2 translated without +// them (the negative control: MIN_LOD, MAX_LOD and the white border are lost, so the readback must differ). +bool check_startup_sampler_x(ID3D12Device* device, bool swapped, int words) { check_probe_coverage(); D3D12_FEATURE_DATA_FORMAT_SUPPORT support{DXGI_FORMAT_R32_FLOAT}; @@ -272,7 +284,7 @@ bool check_startup_sampler_x(ID3D12Device* device, bool swapped) for (UINT i = 0; i < samplers.size(); ++i) { auto handle = sampler_heap->GetCPUDescriptorHandleForHeapStart(); handle.ptr += SIZE_T{bound_case(i)} * sampler_stride; - const auto desc = desktop_sampler(samplers[i]); + const auto desc = words ? x2w_startup::dynamic_sampler(sampler_words[i], words == 1) : desktop_sampler(samplers[i]); device->CreateSampler(&desc, handle); } @@ -345,8 +357,8 @@ bool check_startup_sampler_x(ID3D12Device* device, bool swapped) } std::printf("\n"); } - std::printf("startup_sampler_x swapped=%u mismatches=%u of %u\n", static_cast(swapped), mismatches, - word_count); + std::printf("startup_sampler_x swapped=%u words=%d mismatches=%u of %u\n", static_cast(swapped), words, + mismatches, word_count); if (mismatches) throw std::runtime_error("Sampler contract readback differs from reference"); return true; } diff --git a/tests/startup_saveexec_same_reg_check.py b/tests/startup_saveexec_same_reg_check.py new file mode 100644 index 0000000000..3e56c52e10 --- /dev/null +++ b/tests/startup_saveexec_same_reg_check.py @@ -0,0 +1,58 @@ +"""s_and_saveexec_b64 whose destination is its own source: S0 is read before D is written.""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_scalar_bits_check import asm, sop1, stage # noqa: E402 + +CMP_VCC = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 + + +def lines(words): + s = stage([]) + s.lines = [] + for i, (_, n, name, text) in enumerate(G.decode(struct.pack('<%dI' % len(words), *words))): + s.pc = i + s.one(name, text) + return s, s.lines + + +def run(body, v0): + env = {'v0': v0, 'exec': 1} + for line in body: + for stmt in filter(None, (x.strip() for x in line.split(';'))): + py = re.sub(r'(0x[0-9a-f]+|\d+)u\b', r'\1', stmt) + py = re.sub(r'\(\((.*)\) \? 1 : 0\)', r'int(\1)', py) + name, expr = py.split(' = ', 1) + env[name] = eval(expr, {}, env) + return env + + +def main(): + same = [CMP_VCC, sop1(4, 6, 106), sop1(0x24, 6, 6)] + assert asm(same)[2] == 's_and_saveexec_b64 s[6:7], s[6:7]', asm(same) + s, body = lines(same) + assert 'xsave = s6;' in body and s.uses_xsave, body + assert ' uint xsave = 0;' in s.declarations(), s.declarations() + for v0, want in ((0, 0), (2, 1)): + env = run(body, v0) + assert env['exec'] == want and env['s6'] == 1, (v0, env) + other = [CMP_VCC, sop1(4, 8, 106), sop1(0x24, 6, 8)] + s2, body2 = lines(other) + assert not s2.uses_xsave and not any('xsave' in x for x in body2), body2 + for v0, want in ((0, 0), (2, 1)): + assert run(body2, v0)['exec'] == want + old = [x for x in body if not x.startswith('xsave')] + old = [x.replace('xsave', 's6') for x in old] + assert run(old, 0)['exec'] == 1 # the bug the fix removes: the lane enters with a false condition + print('saveexec_same_reg: S0 read before D (exec 0 / 1 for a false / true condition, s6 = old exec); ' + 'distinct-register control unchanged; the old order lets the lane in (negative control)') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scalar_bits_check.py b/tests/startup_scalar_bits_check.py new file mode 100644 index 0000000000..120fc69c16 --- /dev/null +++ b/tests/startup_scalar_bits_check.py @@ -0,0 +1,155 @@ +"""s_bitset0/1_b32, s_bcnt0/1_i32_b32 and v_xor3_b32. + +Synthetic gfx1013 words only. References written from the AMD RDNA 2 ISA descriptions: +- S_BITSET0_B32 / S_BITSET1_B32: D.u[S0.u[4:0]] = 0 / 1, the other bits of D kept; SCC not written (LLVM + SOPInstructions.td: D tied as an input, no SCC def). +- S_BCNT0_I32_B32 / S_BCNT1_I32_B32: D = number of zero / one bits in S0; SCC = (D != 0). +- V_XOR3_B32 (gfx10 VOP3 0x178): D = S0 ^ S1 ^ S2. +The emitted HLSL is evaluated with the integer evaluator of startup_gfx2hlsl_bit_alu_check over an edge grid. +Controls (refused): s_bitset1_b32 into a lane-mask SGPR; s_bcnt1_i32_b32 of exec_lo and of a mask SGPR (a lane +count the one-lane model cannot give). Constant folding: s_bitset1_b32 on a constant SGPR keeps a constant. +Negative control: the evaluator finds a mismatch for a deliberately wrong expression of each form. +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +GRID = [0, 1, 2, 31, 32, 33, 0x7fffffff, 0x80000000, 0xfffffffe, MASK, 0x12345678, 0x0000ffff] + + +class TestPipeline: + root = {'params': [{'type': 2}], 'flags': 0} + + def resource(self, key, kind): + return 'r0' + + def ud(self, source): + return 0 + + +def sop1(op, dst, src): + return 0xbe800000 | dst << 16 | op << 8 | src + + +def stage(words): + return G.Stage(TestPipeline(), 'vs', struct.pack('<%dI' % (len(words) + 1), *words, 0xbf810000)) + + +def asm(words): + return [x[3] for x in G.decode(struct.pack('<%dI' % len(words), *words))] + + +def lines_of(words): + """The lines one instruction emits, on a bare stage with nothing known about its registers.""" + s = stage([]) + s.lines = [] + _, n, name, text = G.decode(struct.pack('<%dI' % len(words), *words))[0] + s.pc = 0 + s.one(name, text) + return s, s.lines + + +def rhs(line, reg): + assert line.startswith('%s = ' % reg) and line.endswith(';'), line + return line[len(reg) + 3:-1] + + +def refs(): + return { + 's_bitset0_b32': lambda d, s: d & ~(1 << (s & 31)) & MASK, + 's_bitset1_b32': lambda d, s: (d | 1 << (s & 31)) & MASK, + 's_bcnt0_i32_b32': lambda d, s: 32 - bin(s).count('1'), + 's_bcnt1_i32_b32': lambda d, s: bin(s).count('1'), + } + + +def mismatches(expr, ref, scc_expr=None): + bad = [] + for d in GRID: + for s in GRID: + got = expr.run({'s5': d, 's6': s})[0] & MASK + if got != ref(d, s): + bad.append((d, s, got, ref(d, s))) + if scc_expr is not None: + scc = bool(scc_expr.run({'s5': got})[0]) + if scc != (ref(d, s) != 0): + bad.append(('scc', d, s)) + return bad + + +def check_scalar(): + forms = 0 + for name, op in (('s_bcnt0_i32_b32', 0x0d), ('s_bcnt1_i32_b32', 0x0f), ('s_bitset0_b32', 0x1b), + ('s_bitset1_b32', 0x1d)): + words = [sop1(op, 5, 6)] + assert asm(words) == ['%s s5, s6' % name], asm(words) + _, lines = lines_of(words) + expr = rhs(lines[0], 's5') + scc = None + if name.startswith('s_bcnt'): + assert len(lines) == 2 and lines[1] == 'scc = s5 != 0;', lines + scc = Expr('s5 != 0') + else: + assert len(lines) == 1, lines # no SCC write + bad = mismatches(Expr(expr), refs()[name], scc) + assert not bad, (name, expr, bad[:4]) + # negative control: a wrong expression is caught + wrong = expr.replace('countbits', '31u - countbits') if 'countbits' in expr else expr.replace('& 31', '& 15') + assert wrong != expr and mismatches(Expr(wrong), refs()[name]), (name, wrong) + forms += 1 + # constant folding: s_mov_b32 s5, 0x10; s_bitset1_b32 s5, 3 -> constant 0x18 + words = [sop1(0x03, 5, 0x90), sop1(0x1d, 5, 0x83)] + assert asm(words) == ['s_mov_b32 s5, 16', 's_bitset1_b32 s5, 3'], asm(words) + s = stage(words) + assert s.sym.get(5) == ('const', 0x18), s.sym.get(5) + return forms + + +def check_xor3(): + words = [0xd4000000 | 0x178 << 16 | 2, 256 | 257 << 9 | 258 << 18] + assert asm(words) == ['v_xor3_b32 v2, v0, v1, v2'], asm(words) + _, lines = lines_of(words) + expr = Expr(rhs(lines[0], 'v2')) + for a in GRID: + for b in GRID: + for c in (0, 1, MASK, 0x5a5a5a5a): + assert expr.run({'v0': a, 'v1': b, 'v2': c})[0] & MASK == a ^ b ^ c, (a, b, c) + wrong = Expr(rhs(lines[0], 'v2').replace('^', '|', 1)) + assert any(wrong.run({'v0': a, 'v1': b, 'v2': 0})[0] != a ^ b for a in GRID for b in GRID) + + +def refused(words, why, label): + try: + stage(words) + except G.Unsupported as error: + assert why in str(error), (label, str(error)) + return + raise AssertionError('accepted: ' + label) + + +def controls(): + cmp_vcc = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 + save = 0xbe800000 | 20 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[20:21], vcc (s20 mask) + refused([cmp_vcc, save, sop1(0x1d, 20, 0x83)], 'destination', 's_bitset1_b32 into a mask SGPR') + refused([sop1(0x0f, 5, 126)], 'lane mask', 's_bcnt1_i32_b32 of exec_lo') + refused([cmp_vcc, save, sop1(0x0f, 5, 20)], 'lane mask', 's_bcnt1_i32_b32 of a mask SGPR') + assert asm([sop1(0x0f, 5, 126)]) == ['s_bcnt1_i32_b32 s5, exec_lo'], asm([sop1(0x0f, 5, 126)]) + + +def main(): + forms = check_scalar() + check_xor3() + controls() + print('scalar_bits: %d scalar forms and v_xor3_b32 match the ISA references on %d inputs; constant fold kept; ' + '3 controls refused; negative controls caught' % (forms, len(GRID) ** 2)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scalar_complement_mask_check.py b/tests/startup_scalar_complement_mask_check.py new file mode 100644 index 0000000000..b1fad05bf6 --- /dev/null +++ b/tests/startup_scalar_complement_mask_check.py @@ -0,0 +1,90 @@ +"""s_nand_b32, s_nor_b32, s_xnor_b32 on a lane mask or on descriptor data: refused. + +Synthetic gfx1013 SOP2 words only. AMD RDNA 2 ISA: D = ~(S0 op S1) on 32 bits, SCC = (D != 0). A vcc_lo/exec_lo +operand or destination, or an SGPR that holds a compare mask, is the whole wave's mask; SCC then depends on every +lane's bit of the complemented result, and the one-lane model keeps only this lane's bit, so these forms stay +refused. A source the translator holds as descriptor data (sym desc/descnum/ptr) takes the symbolic path, which +emits no SCC; the complement there is refused too. (Same rule as upstream 9b620015 and 34105de4, re-implemented.) + +Accepted control: numeric SGPR operands give ~(s11 op s12) and SCC = D != 0, checked with the integer evaluator of +startup_gfx2hlsl_bit_alu_check on an edge grid. Negative control: the evaluator catches the expression without ~. +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 +from startup_scalar_bits_check import stage, asm, sop1 # noqa: E402 + +MASK = 0xffffffff +OPCODE = {name: op for op, (name, _) in D.SOP2_OPS.items()} +REF = {'s_nand_b32': lambda a, b: ~(a & b) & MASK, 's_nor_b32': lambda a, b: ~(a | b) & MASK, + 's_xnor_b32': lambda a, b: ~(a ^ b) & MASK} +GRID = [0, 1, 0x7fffffff, 0x80000000, 0xfffffffe, MASK, 0xaaaaaaaa, 0x55555555, 0x12345678] +VCC_LO, EXEC_LO = 106, 126 +CMP_VCC = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 +SAVE = 0xbe800000 | 20 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[20:21], vcc (s20 mask) + + +def sop2(name, sdst, s0, s1): + return 0x80000000 | OPCODE[name] << 23 | sdst << 16 | s1 << 8 | s0 + + +def one(words, sym=None): + s = stage([]) + s.lines = [] + s.sym.update(sym or {}) + for _, _, name, text in G.decode(struct.pack('<%dI' % len(words), *words)): + s.one(name, text) + return s.lines + + +def refused(words, why, label, sym=None): + try: + one(words, sym) if sym else stage(words) + except G.Unsupported as error: + assert why in str(error), (label, str(error)) + return 1 + raise AssertionError('accepted: ' + label) + + +def main(): + accepted = refusals = 0 + for name, ref in REF.items(): + words = [sop2(name, 13, 11, 12)] + assert asm(words) == ['%s s13, s11, s12' % name], asm(words) + lines = one(words) + assert len(lines) == 2 and lines[0].startswith('s13 = ') and lines[1] == 'scc = s13 != 0;', lines + expr = Expr(lines[0][len('s13 = '):-1]) + for a in GRID: + for b in GRID: + got = expr.run({'s11': a, 's12': b})[0] & MASK + assert got == ref(a, b), (name, a, b, got) + wrong = Expr(lines[0][len('s13 = '):-1].replace('~', '', 1)) + assert any(wrong.run({'s11': a, 's12': b})[0] & MASK != ref(a, b) for a in GRID for b in GRID), name + accepted += 1 + + assert asm([sop2(name, 13, VCC_LO, 12)]) == ['%s s13, vcc_lo, s12' % name] + refusals += refused([sop2(name, 13, VCC_LO, 12)], 'on a lane mask', name + ' of vcc_lo') + refusals += refused([sop2(name, 13, 11, EXEC_LO)], 'on a lane mask', name + ' of exec_lo') + refusals += refused([sop2(name, VCC_LO, 11, 12)], 'on a lane mask', name + ' into vcc_lo') + refusals += refused([sop2(name, EXEC_LO, 11, 12)], 'on a lane mask', name + ' into exec_lo') + refusals += refused([CMP_VCC, SAVE, sop2(name, 13, 20, 12)], 'on a lane mask', name + ' of a mask SGPR') + refusals += refused([sop2(name, 13, 6, 12)], 'scc from descriptor data', name + ' of a descriptor word', + sym={6: ('descnum',)}) + # the sibling s_and_b32 of a descriptor word keeps its symbolic path (not refused) + lines = one([sop2('s_and_b32', 13, 6, 12)], sym={6: ('descnum',)}) + assert lines == [], lines + print('scalar_complement_mask: %d numeric forms match ~(a op b) and SCC on %d inputs (negative control caught); ' + '%d lane-mask / descriptor forms refused; s_and_b32 of a descriptor word unchanged' + % (accepted, len(GRID) ** 2, refusals)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scalar_const_fold_check.py b/tests/startup_scalar_const_fold_check.py new file mode 100644 index 0000000000..67fc7e016d --- /dev/null +++ b/tests/startup_scalar_const_fold_check.py @@ -0,0 +1,63 @@ +"""s_brev_b32 of a constant operand folds to a known word in tools/startup/gfx2hlsl.py (Stage.scalar).""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import VS_WORDS, root_blob # noqa: E402 + + +def sop2(op, d, s0, s1): + return struct.pack('> i) & 1) << (31 - i) for i in range(32)) + + +def main(): + asm = [a for _, _, _, a in G.decode(program())] + assert asm[:4] == ['s_bfm_b32 s0, 2, 22', 's_brev_b32 s1, 1', 's_brev_b32 s2, s5', 's_brev_b32 s3, s0'], asm + bfm = sum(1 << i for i in range(22, 24)) + want = {0: bfm, 1: reverse(1), 3: reverse(bfm)} + assert (bfm, want[1], want[3]) == (0x00c00000, 0x80000000, 0x00000300) + pipe = G.Pipeline(VS_WORDS, program(), root_blob()) + ps = pipe.hlsl_ps() + for n, value in want.items(): + assert pipe.ps.is_const(n) == value, (n, pipe.ps.sym.get(n)) + assert ' s%d = 0x%08xu;' % (n, value) in ps.split('\n'), ps + assert pipe.ps.is_const(2) is None and ' s2 = reversebits(s5);' in ps.split('\n'), ps + saved = dict(G.SCALAR_CONST_FOLD) + G.SCALAR_CONST_FOLD.clear() + try: + old = G.Pipeline(VS_WORDS, program(), root_blob()) + old.hlsl_ps() + assert old.ps.is_const(0) == bfm and all(old.ps.is_const(n) is None for n in (1, 2, 3)), old.ps.sym + finally: + G.SCALAR_CONST_FOLD.update(saved) + print('scalar const fold: s_brev_b32 1 = 0x80000000, brev of the folded s_bfm_b32 2, 22 (0x00c00000) = ' + '0x00000300; controls: unknown operand keeps reversebits, no brev constants without the table') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scalar_ff_check.py b/tests/startup_scalar_ff_check.py new file mode 100644 index 0000000000..d651acafb6 --- /dev/null +++ b/tests/startup_scalar_ff_check.py @@ -0,0 +1,44 @@ +"""s_ff1_i32_b32 and s_ff0_i32_b32 on a value that is not a lane mask. + +Synthetic gfx1013 SOP1 words. Reference (AMD RDNA 2 ISA SOP1): S_FF1_I32_B32 D = the index of the lowest one bit +of S0, -1 if S0 has none; S_FF0_I32_B32 the same for the lowest zero bit; SCC is not written (LLVM +SOPInstructions.td: no SCC def). The emitted HLSL is evaluated with the integer evaluator of +startup_gfx2hlsl_bit_alu_check over an edge grid (its firstbitlow returns 0xffffffff for 0, as HLSL documents). +Controls (refused): s_ff1_i32_b32 of exec_lo and of a mask SGPR (a lane index the one-lane model cannot give). +Negative control: an expression without the -1 case (0 for no bit) is caught. +""" +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 +from startup_scalar_bits_check import GRID, MASK, asm, lines_of, refused, rhs, sop1 # noqa: E402 + + +def lowest(x): + return (x & -x).bit_length() - 1 if x else MASK + + +def main(): + grid = GRID + [1 << n for n in range(32)] + [MASK ^ (1 << n) for n in range(32)] + for name, op, ref in (('s_ff0_i32_b32', 0x11, lambda s: lowest(~s & MASK)), ('s_ff1_i32_b32', 0x13, lowest)): + words = [sop1(op, 5, 6)] + assert asm(words) == ['%s s5, s6' % name], asm(words) + _, lines = lines_of(words) + assert len(lines) == 1, lines # no SCC write + expr = rhs(lines[0], 's5') + bad = [s for s in grid if Expr(expr).run({'s6': s})[0] & MASK != ref(s)] + assert not bad, (name, expr, bad[:4]) + wrong = Expr('(%s == 0u ? 0u : %s)' % ('s6' if op == 0x13 else '~s6', expr)) + assert any(wrong.run({'s6': s})[0] & MASK != ref(s) for s in grid), name + cmp_vcc = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 + save = 0xbe800000 | 20 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[20:21], vcc (s20 mask) + refused([sop1(0x13, 5, 126)], 'lane mask', 's_ff1_i32_b32 of exec_lo') + refused([cmp_vcc, save, sop1(0x13, 5, 20)], 'lane mask', 's_ff1_i32_b32 of a mask SGPR') + print('scalar_ff: s_ff0/s_ff1_i32_b32 match the ISA reference on %d inputs (-1 for none, SCC kept); exec_lo and ' + 'mask-SGPR sources refused; negative control caught' % len(grid)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scalar_nand_check.py b/tests/startup_scalar_nand_check.py new file mode 100644 index 0000000000..df372bef76 --- /dev/null +++ b/tests/startup_scalar_nand_check.py @@ -0,0 +1,70 @@ +"""s_nand_b32 / s_nor_b32 / s_xnor_b32 (SOP2), the 32-bit forms of the existing b64 entries. + +Synthetic words (SOP2: op [29:23], sdst [22:16], ssrc1 [15:8], ssrc0 [7:0]; gfx10 opcodes 0x18, 0x1a, 0x1c, names +asserted from the decoder). RDNA2 ISA: D = ~(S0 & S1), ~(S0 | S1), ~(S0 ^ S1); SCC = (D != 0). The emitted +expression is evaluated on a value grid; a lane-mask source (vcc_lo) is refused (SCC would need every lane's bit). +Control: the existing s_and_b32 output is unchanged. +""" +import itertools +import re +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +MASK = 0xffffffff +OPS = {0x18: ('s_nand_b32', lambda a, b: ~(a & b)), 0x1a: ('s_nor_b32', lambda a, b: ~(a | b)), + 0x1c: ('s_xnor_b32', lambda a, b: ~(a ^ b))} +GRID = [0, 1, 0x80000000, 0x0f0f0f0f, 0xfffffffe, MASK] + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def stage(): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + s.pc = 0 + return s + + +def run_one(s, word): + _, n, name, text = G.decode(struct.pack('> 16) | (b & 0xffff0000) + + +def evaluate(expr, a, b): + py = expr.replace('u)', ')').replace('u ', ' ') + py = re.sub(r'(0x[0-9a-f]+)u', r'\1', py) + return eval(py, {'__builtins__': {}}, {'s0': a, 's1': b}) & MASK + + +def run(s, op): + _, _, name, text = G.decode(struct.pack('> 16) | (S1 & 0xffff0000), no SCC write; ' + 'control refuses without the entry, swapped halves mismatch; lane-mask sources refused' + % (op, len(GRID) ** 2)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_scmp_u64_check.py b/tests/startup_scmp_u64_check.py new file mode 100644 index 0000000000..abb2e220bd --- /dev/null +++ b/tests/startup_scmp_u64_check.py @@ -0,0 +1,115 @@ +"""s_cmp_eq_u64 / s_cmp_lg_u64 on 64-bit data pairs. + +Synthetic gfx1013 words only. The shape is a pixel program testing a 64-bit value read from a constant buffer +against zero before using it (`s_mov_b64 s[26:27], 0` ... `s_cmp_lg_u64 s[38:39], s[26:27]`; s_cbranch_scc0). +RDNA 2 ISA, SOPC: SCC = (S0 == S1) or (S0 != S1) on the 64-bit values. + +The emitted SCC is evaluated in Python for value pairs that differ in the low dword only, the high dword only, +both, and neither (an equality on the low dword alone would pass the first and fail the second). +Controls (refused): exec as an operand; a pair holding a copy of exec (s_mov_b64 s[26:27], exec); a pair holding +a lane mask (v_cmp into s[26:27]); a 64-bit literal. Negative control: without the handlers the compare is the +old refusal. +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class TestPipeline: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def sop1(op, d, s): + return 0xbe800000 | d << 16 | op << 8 | s + + +def sopc(op, a, b): + return 0xbf000000 | op << 16 | b << 8 | a + + +MOV_B32, MOV_B64 = 3, 4 +CMP_EQ_U64, CMP_LG_U64 = 0x12, 0x13 +EXEC = 126 +INLINE0 = 128 +V_CMP_LT_U32_S26 = [0xd4c10000 | 26, 0x00020081] # v_cmp_lt_u32_e64 s26, 1, v0 (wave32: the mask is s26) + + +def stage(words): + return G.Stage(TestPipeline(), 'vs', struct.pack('<%dI' % (len(words) + 1), *words, 0xbf810000)) + + +def asm(words): + return [x[3] for x in G.decode(struct.pack('<%dI' % len(words), *words))] + + +def scc_line(words): + s = stage(words) + lines = [line for block in s.blocks for line in block[1] if line.startswith('scc = ')] + assert len(lines) == 1, s.blocks + return lines[0][len('scc = '):-1] + + +def evaluate(expr, env): + py = expr.replace('&&', ' and ').replace('||', ' or ') + import re + py = re.sub(r'\b(0x[0-9a-f]+|\d+)u\b', r'\1', py) + return bool(eval(py, {}, env)) + + +def refused(words, label, text): + try: + stage(words) + except G.Unsupported as error: + assert text in str(error), (label, str(error)) + return + raise AssertionError('accepted: ' + label) + + +def main(): + zero = [sop1(MOV_B64, 26, INLINE0)] + lg = sopc(CMP_LG_U64, 38, 26) + eq = sopc(CMP_EQ_U64, 38, 26) + got = asm(zero + [lg, eq, sop1(MOV_B64, 26, EXEC), sopc(CMP_LG_U64, EXEC, 26)] + V_CMP_LT_U32_S26) + assert got == ['s_mov_b64 s[26:27], 0', 's_cmp_lg_u64 s[38:39], s[26:27]', 's_cmp_eq_u64 s[38:39], s[26:27]', + 's_mov_b64 s[26:27], exec', 's_cmp_lg_u64 exec, s[26:27]', 'v_cmp_lt_u32_e64 s26, 1, v0'], got + + # s[26:27] = 0 folds to constants; s38/s39 stay run-time registers. + lg_expr, eq_expr = scc_line(zero + [lg]), scc_line(zero + [eq]) + assert 's38' in lg_expr and 's39' in lg_expr, lg_expr + for lo, hi in ((0, 0), (5, 0), (0, 5), (5, 5), (0xffffffff, 0xffffffff)): + env = {'s38': lo, 's39': hi} + assert evaluate(lg_expr, env) == ((lo | hi << 32) != 0), (lg_expr, lo, hi) + assert evaluate(eq_expr, env) == ((lo | hi << 32) == 0), (eq_expr, lo, hi) + # Two run-time pairs. + both = scc_line([sopc(CMP_EQ_U64, 38, 40)]) + for a, b in (((1, 2), (1, 2)), ((1, 2), (1, 3)), ((1, 2), (0, 2))): + env = {'s38': a[0], 's39': a[1], 's40': b[0], 's41': b[1]} + assert evaluate(both, env) == (a == b), (both, a, b) + + # Controls. + refused([sopc(CMP_LG_U64, EXEC, 26)], 'exec operand', '64-bit operand') + refused([sop1(MOV_B64, 26, EXEC), lg], 'copy of exec', 'on a lane mask') + refused(V_CMP_LT_U32_S26 + [lg], 'v_cmp lane mask', 'on a lane mask') + # (a literal with bit 31 clear has high dword 0 under either extension and is accepted by Stage.pair) + refused([sopc(CMP_LG_U64, 38, 255), 0x92345678], '64-bit literal, bit 31 set', '64-bit literal operand') + + # Negative control: without the handlers the compare is refused as an unknown instruction. + saved = G.Stage.op_s_cmp_lg_u64, G.Stage.op_s_cmp_eq_u64 + del G.Stage.op_s_cmp_lg_u64, G.Stage.op_s_cmp_eq_u64 + try: + refused(zero + [lg], 'handlers removed', 's_cmp_lg_u64') + finally: + G.Stage.op_s_cmp_lg_u64, G.Stage.op_s_cmp_eq_u64 = saved + print('scmp_u64: eq/lg on data pairs evaluated for low-only, high-only, both and equal values; ' + 'exec, exec copy, v_cmp mask and literal refused; negative control (no handlers) refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_sdwa_cvt_check.py b/tests/startup_sdwa_cvt_check.py new file mode 100644 index 0000000000..5c90a25fe4 --- /dev/null +++ b/tests/startup_sdwa_cvt_check.py @@ -0,0 +1,68 @@ +"""SDWA forms of the float-result conversions (v_cvt_f32_u32, _i32, _ubyte*, _f16) after #1707 moved them out of VEC_U. + +Synthetic VOP1 SDWA words: v_cvt_f32_u32 v2, v1 with src0_sel BYTE_1 (op 6, src0 = 0xf9, SDWA dword: v1, dst_sel DWORD, +UNUSED_PAD, src0_sel BYTE_1). The lowering must be the expression VEC_U used to give, U(float()), as +before the integration merge; v_cvt_f32_f16 likewise with WORD_1. SDWA output modifiers (omod, clamp) on these +conversions are lowered with dst_sel DWORD (they used to be refused; that control is now an acceptance check) and +stay refused with a partial destination field. +""" +import os +import struct +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def one(words): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + _, n, name, text = G.decode(struct.pack('<%dI' % len(words), *words))[0] + s.pc = 0 + s.used_v.update((1, 2)) + s.one(name, text) + return text, '\n'.join(s.lines) + + +def sdwa(op, src_sel, omod=0): + return [0x7e000000 | 2 << 17 | op << 9 | 0xf9, 1 | 6 << 8 | omod << 14 | src_sel << 16] + + +def main(): + text, body = one(sdwa(6, 1)) + assert text.startswith('v_cvt_f32_u32_sdwa v2, v1') and 'src0_sel:BYTE_1' in text, text + assert body == 'v2 = U(float(((v1 >> 8u) & 0xffu)));', body + text, body = one(sdwa(0x0b, 5)) # v_cvt_f32_f16, WORD_1 + assert text.startswith('v_cvt_f32_f16_sdwa v2, v1') and 'src0_sel:WORD_1' in text, text + assert body == 'v2 = U(f16tof32(((v1 >> 16u) & 0xffffu)));', body + # Output modifiers (SDWA9 omod [15:14], clamp [13]) on a float-result conversion with dst_sel DWORD: the + # binary32 result is scaled, then clamped, as in VOP3 (set_vf). + for omod, factor in ((1, '2.0'), (2, '4.0'), (3, '0.5')): + text, body = one(sdwa(6, 4, omod=omod)) + assert text.startswith('v_cvt_f32_u32_sdwa v2, v1') and 'src0_sel:WORD_0' in text, text + assert body == 'v2 = U((float(((v1 >> 0u) & 0xffffu))) * %s);' % factor, body + text, body = one([sdwa(6, 4, omod=1)[0], sdwa(6, 4, omod=1)[1] | 1 << 13]) + assert 'clamp' in text, text + assert body == 'v2 = U(saturate((float(((v1 >> 0u) & 0xffffu))) * 2.0));', body + # Control: an output modifier with a partial destination field. (On an integer operation such as v_not_b32 + # the disassembler itself rejects the omod bits as an invalid SDWA encoding.) + for words, why in (([0x7e000000 | 2 << 17 | 6 << 9 | 0xf9, 1 | 4 << 8 | 1 << 14 | 4 << 16], 'dst_sel:WORD_0'),): + try: + one(words) + except G.Unsupported as error: + assert why in str(error), (why, str(error)) + else: + raise AssertionError('accepted %s' % one(words)[0]) + print('sdwa cvt: v_cvt_f32_u32 BYTE_1 and v_cvt_f32_f16 WORD_1 lowered as before; mul:2/mul:4/div:2/clamp ' + 'lowered with dst_sel DWORD; 1 control refused') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_sdwa_mov_check.py b/tests/startup_sdwa_mov_check.py new file mode 100644 index 0000000000..fd943718ad --- /dev/null +++ b/tests/startup_sdwa_mov_check.py @@ -0,0 +1,101 @@ +"""v_mov_b32_sdwa: the selected source field, placed by dst_sel / dst_unused. + +Synthetic VOP1 SDWA words (VOP1 op 1, src0 = 0xf9; SDWA dword: [7:0] source, [10:8] dst_sel, [12:11] dst_unused, +[18:16] src0_sel, [19] sext, [23] source is an SGPR). Reference (AMD RDNA 2 ISA, SDWA section; LLVM +VOP1Instructions.td gives V_MOV_B32 an SDWA form with integer input modifiers, sext only): the source field at +src0_sel is zero- or sign-extended to 32 bits; dst_sel DWORD writes it; a partial dst_sel writes its low bits into +that field and the rest of the register is 0 (UNUSED_PAD) or kept (UNUSED_PRESERVE). + +The emitted expression is evaluated in Python for every src0_sel x dst_sel x {PAD, PRESERVE} x sext on a value +grid, against a reference written here from those rules. An SGPR source is accepted. A PRESERVE destination not yet written is recorded as an entry VGPR read. Refused: UNUSED_SEXT (no +lowering), the neg bit (not an integer input modifier; the decoder flags it). Negative control: a reference that +ignores sext (or PRESERVE) is caught. +""" +import re +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_sdwa_cvt_check import one # noqa: E402 + +SEL = {0: (0, 8), 1: (8, 8), 2: (16, 8), 3: (24, 8), 4: (0, 16), 5: (16, 16), 6: (0, 32)} +GRID = [0, 0x80, 0x7f, 0x8000, 0xffffffff, 0x12345678, 0x89abcdef, 0x00ff00ff] +OLD = 0xa5a55a5a + + +def words(dsel, unused, ssel, sext=0, neg=0, sgpr=0, src=1): + return [0x7e000000 | 2 << 17 | 1 << 9 | 0xf9, + src | dsel << 8 | unused << 11 | ssel << 16 | sext << 19 | neg << 20 | sgpr << 23] + + +def s32(x): + x &= 0xffffffff + return x - (1 << 32) if x >> 31 else x + + +def evaluate(body, v1, v2): + m = re.fullmatch(r'v2 = (.*);', body) + assert m, body + expr = re.sub(r'(0x[0-9a-f]+|\d+)u\b', r'\1', m.group(1)).replace('asuint(', 'u32(').replace('asint(', 's32(') + return eval(expr, {'u32': lambda x: x & 0xffffffff, 's32': s32, '__builtins__': {}}, + {'v1': v1, 'v2': v2, 's3': v1}) & 0xffffffff + + +def reference(v1, old, dsel, unused, ssel, sext, ignore_sext=False, ignore_preserve=False): + off, width = SEL[ssel] + field = (v1 >> off) & ((1 << width) - 1) + if sext and not ignore_sext and width < 32 and field >> (width - 1): + field |= ~((1 << width) - 1) & 0xffffffff + doff, dwidth = SEL[dsel] + if dwidth == 32: + return field + placed = (field & ((1 << dwidth) - 1)) << doff + if unused == 2 and not ignore_preserve: + placed |= old & ~(((1 << dwidth) - 1) << doff) & 0xffffffff + return placed + + +def main(): + forms = caught_sext = caught_preserve = 0 + for ssel in SEL: + for dsel in SEL: + for unused in (0, 2): + for sext in (0, 1): + text, body = one(words(dsel, unused, ssel, sext)) + assert text.startswith('v_mov_b32_sdwa v2, %sv1' % ('sext(' if sext else '')), text + for v in GRID: + want = reference(v, OLD, dsel, unused, ssel, sext) + assert evaluate(body, v, OLD) == want, (text, body, hex(v)) + caught_sext += any(evaluate(body, v, OLD) != reference(v, OLD, dsel, unused, ssel, sext, True) + for v in GRID) + caught_preserve += any(evaluate(body, v, OLD) != reference(v, OLD, dsel, unused, ssel, sext, + ignore_preserve=True) for v in GRID) + forms += 1 + assert caught_sext > 0 and caught_preserve > 0, (caught_sext, caught_preserve) + text, body = one(words(4, 0, 0, sgpr=1, src=3)) + assert text.startswith('v_mov_b32_sdwa v2, s3'), text + assert all(evaluate(body, v, OLD) == reference(v, OLD, 4, 0, 0, 0) for v in GRID), body + for label, w, why in (('UNUSED_SEXT', words(0, 1, 4), 'UNUSED_SEXT'), ('neg', words(6, 0, 1, neg=1), 'SDWA')): + try: + one(w) + except G.Unsupported as error: + assert why in str(error), (label, str(error)) + else: + raise AssertionError('accepted: ' + label) + # UNUSED_PRESERVE reads the destination: in a pixel stage a destination not yet written is an entry (SPI + # input) VGPR read and must be recorded; PAD does not read it. + from startup_scalar_bits_check import TestPipeline + import struct + for unused, want in ((2, {2: 4}), (0, {})): + code = [0x7e000000 | 1 << 17 | 1 << 9 | 128] + words(4, unused, 5) + [0xbf810000] + stage = G.Stage(TestPipeline(), 'ps', struct.pack('<%dI' % len(code), *code)) + assert stage.entry_reads == want, (unused, stage.entry_reads) + print('sdwa_mov: %d v_mov_b32_sdwa forms match the SDWA rules on %d values (sext caught in %d, PRESERVE in %d); ' + 'SGPR source accepted; UNUSED_SEXT and neg refused; PRESERVE records an entry read' % (forms, len(GRID), caught_sext, caught_preserve)) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_smem_overlap_mask_check.py b/tests/startup_smem_overlap_mask_check.py new file mode 100644 index 0000000000..05e7c92362 --- /dev/null +++ b/tests/startup_smem_overlap_mask_check.py @@ -0,0 +1,76 @@ +"""s_buffer_load with its offset register inside the destination range, an SGPR offset plus offset:N, and a load""" +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + sampler_heap = False + root = {'params': [], 'flags': 0} + + def resource(self, key, kind): + return 'r0' + + def ud(self, source): + return 0 + + +DESC = {16: ('desc', ('table', 0), 0x20, 0), 17: ('desc', ('table', 0), 0x20, 1), + 18: ('desc', ('table', 0), 0x20, 2), 19: ('desc', ('table', 0), 0x20, 3)} + + +def stage(): + s = G.Stage(Pipe(), 'ps', b'') + s.lines = [] + s.sym.update(DESC) + s.pc = 0 + return s + + +def load(s, text): + ops, mods = text.split(' ', 1)[1], [] + parts = ops.split(', ') + last = parts[-1].split(' ') + parts[-1], mods = last[0], last[1:] + getattr(s, 'op_' + text.split(' ')[0])(parts, mods) + + +def main(): + s = stage() + load(s, 's_buffer_load_dwordx2 s[4:5], s[16:19], s4') + assert s.lines == ['s5 = r0.Load(s4 + 4);', 's4 = r0.Load(s4 + 0);'], s.lines + s = stage() + load(s, 's_buffer_load_dwordx2 s[6:7], s[16:19], s4') + assert s.lines == ['s6 = r0.Load(s4 + 0);', 's7 = r0.Load(s4 + 4);'], s.lines + print('overlap: offset register written last; control keeps the order') + + s = stage() + load(s, 's_buffer_load_dword s0, s[16:19], s4 offset:0x10') + assert s.lines == ['s0 = r0.Load(s4 + 16);'], s.lines + try: + load(stage(), 's_buffer_load_dword s0, s[16:19], s4 slc') + except G.Unsupported as error: + assert 'modifier slc' in str(error), str(error) + else: + raise AssertionError('unknown modifier accepted') + print('offset:N added to the SGPR offset; unknown modifier refused') + + for with_load in (True, False): + s = stage() + s.masks.add(6) # as after v_cmp_* s6, ... + if with_load: + load(s, 's_buffer_load_dword s6, s[16:19], 0x0') + s.lines = [] + s.one('s_or_b32', 's_or_b32 s8, s6, s7') + text = '\n'.join(s.lines) + if with_load: + assert '& 1' not in text and 8 not in s.masks and 6 not in s.masks, (text, s.masks) + else: + assert '& 1' in text and 8 in s.masks, (text, s.masks) + print('mask mark: cleared by a load into the register; control keeps the mask OR') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_sopk_sign_check.py b/tests/startup_sopk_sign_check.py new file mode 100644 index 0000000000..45e7961b67 --- /dev/null +++ b/tests/startup_sopk_sign_check.py @@ -0,0 +1,39 @@ +"""SOPK immediates: s_movk_i32 and s_cmpk_*_i32 sign-extend SIMM16, s_cmpk_*_u32 zero-extends (picked 56eee135). + +Synthetic SOPK words (0xb0000000 | op << 23 | sdst << 16 | simm16). Reference: RDNA 2 ISA SOPK; LLVM +SOPInstructions.td s16imm for s_movk_i32 / s_cmpk_*_i32, u16imm for s_cmpk_*_u32. The disassembler prints the field +unsigned, so 0xf000 / 0x8000 are the cases that differ. Negative control: a lowering that keeps the printed value +(the old behaviour) gives 0x0000f000 for s_movk_i32 0xf000. +""" +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_scalar_bits_check import asm, lines_of # noqa: E402 + + +def sopk(op, sdst, simm): + return [0xb0000000 | op << 23 | sdst << 16 | simm] + + +def main(): + cases = [ + (0, 0xf000, 's_movk_i32 s5, 0xf000', ['s5 = 0xfffff000u;']), + (0, 0x7fff, 's_movk_i32 s5, 0x7fff', ['s5 = 0x00007fffu;']), + (3, 0x8000, 's_cmpk_eq_i32 s5, 0x8000', ['scc = int(s5) == int(0xffff8000u);']), + (9, 0x8000, 's_cmpk_eq_u32 s5, 0x8000', ['scc = s5 == 0x00008000u;']), + ] + for op, simm, text, want in cases: + words = sopk(op, 5, simm) + assert asm(words) == [text], asm(words) + s, lines = lines_of(words) + assert lines == want, (text, lines) + s, _ = lines_of(sopk(0, 5, 0xf000)) + assert s.sym.get(5) == ('const', 0xfffff000), s.sym.get(5) + assert s.sym.get(5) != ('const', 0xf000) # the old, unsigned value + print('sopk_sign: s_movk_i32 / s_cmpk_eq_i32 sign-extend, s_cmpk_eq_u32 zero-extends; constant 0xfffff000 kept') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_spi_input_check.py b/tests/startup_spi_input_check.py new file mode 100644 index 0000000000..9cf92fc318 --- /dev/null +++ b/tests/startup_spi_input_check.py @@ -0,0 +1,96 @@ +"""Map pixel-stage entry VGPRs to SPI inputs from SPI_PS_INPUT_ENA/ADDR; lower only POS_FIXED_PT. + +Synthetic code only: a vertex stage that exports a position and a pixel stage `exp mrt0 vN, vN, vN, vN done vm` +that reads entry VGPR vN. Without the masks the read is refused (the request does not carry the layout); with +them, vN must be the enabled POS_FIXED_PT input, placed by the ADDR bits (Mesa ac_shader_util.c). +""" +import os +import struct +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import VS_WORDS, root_blob # noqa: E402 + + +def pixel_words(reg): + # exp mrt0 vN, vN, vN, vN done vm; s_endpgm + return struct.pack(' v4. + for reg, masks in ((1, (0x8100, 0x8100)), (2, (0x8002, 0x8002)), (4, (0x8002, 0x8003)), + (0, (0x8000, 0x8000)), (4, (0x8008, 0x8108))): # pull model (3) + pos_x_float (1) + ps = G.Pipeline(VS_WORDS, pixel_words(reg), root_blob(), ps_hw_inputs=masks).hlsl_ps() + assert packed(reg) in ps, (reg, masks, ps) + assert 'o.mrt0 = float4(F(v%d), F(v%d), F(v%d), F(v%d));' % ((reg,) * 4) in ps, ps + # Refused, each with its own reason. + refused(1, (0x8100, 0x8000), 'enable/address') # ENA outside ADDR (upstream #1634's control) + refused(1, (0x18000, 0x18000), 'enable/address') # not a 16-bit mask + refused(1, (0x8002, 0x8002), 'persp_center (v1) at 0x0: not lowered') + refused(0, (0x2000, 0x2000), 'ancillary (v0) at 0x0: not lowered') # packed position disabled + # (front_face, refused here before, is lowered as SV_IsFrontFace: tests/startup_front_face_check.py) + # (pos_x_float, refused here before, is lowered as SV_Position.x: tests/startup_mesh_spi_input_check.py) + refused(0, (0x8002, 0x8003), 'persp_sample (v0) at 0x0, allocated but not enabled') + refused(3, (0x0002, 0x0002), 'past the SPI inputs (ADDR allocates 2)') + try: + G.Pipeline(VS_WORDS, pixel_words(0), root_blob(), ps_hw_inputs=(0x0000, 0x8000)).hlsl_ps() + except G.Unsupported as error: + assert 'pos_fixed_pt (v0) at 0x0, allocated but not enabled' in str(error), str(error) + else: + raise AssertionError('read an allocated but disabled POS_FIXED_PT') + # Without masks nothing changes: no packed line, and translate_to still refuses the read. + assert 'i.pos.x' not in G.Pipeline(VS_WORDS, pixel_words(1), root_blob()).hlsl_ps() + + # Requests: the optional req_.psin file (not part of the key) supplies the masks. + G.FXC = os.path.join(tempfile.gettempdir(), 'no-such-fxc.exe') # translation only, no compiler + with tempfile.TemporaryDirectory() as tmp: + ps_code = pixel_words(2) + key = G.pipeline_key(VS_WORDS, ps_code, root_blob()) + base = os.path.join(tmp, 'req_%016x' % key) + for ext, blob in (('.a', VS_WORDS), ('.b', ps_code), ('.root', root_blob())): + open(base + ext, 'wb').write(blob) + result = G.translate_request(tmp, key) + assert result == 'unsupported: pixel stage reads entry VGPR v2 (an SPI input; layout not in the request) at 0x0', result + for text, expect in (('spi_ps_input 1 00008002 00008002\n', 'ok'), + ('spi_ps_input 1 00008002 00008003\n', 'unsupported: pixel stage reads SPI input persp_center'), + ('spi_ps_input 1 00008002 00008002\nvs_input 1 1 00000000\n', 'ok'), + ('spi_ps_input 1 8002 8002\n', 'unsupported: invalid SPI input file'), + ('spi_ps_input 1 00008002 00008002', 'unsupported: invalid SPI input file'), + ('spi_ps_input 2 00008002 00008002\n', 'unsupported: invalid SPI input file')): + for ext in ('.txt', '.fail'): + if os.path.exists(os.path.join(tmp, '%016x%s' % (key, ext))): + os.remove(os.path.join(tmp, '%016x%s' % (key, ext))) + with open(base + '.psin', 'w', newline='\n') as file: + file.write(text) + result = G.translate_request(tmp, key) + assert result.startswith(expect), (text, result) + if expect == 'ok': + assert packed(2) in open(os.path.join(tmp, '%016x.ps.hlsl' % key)).read() + print('SPI input layout: 5 accepted layouts, 7 refusals, request .psin read (2 accepted, 4 refused)') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_stream_check.py b/tests/startup_stream_check.py index ce33bf935d..2239881b2b 100644 --- a/tests/startup_stream_check.py +++ b/tests/startup_stream_check.py @@ -11,10 +11,16 @@ import gfx2hlsl +V_MOV_V0_ONE = 0x7e0002f2 # v_mov_b32 v0, 1.0 + + def container(stage, words=None): - # One straight-line export (pos0 or mrt0) followed by s_endpgm and section padding. + # One straight-line export (pos0 or mrt0) followed by s_endpgm and section padding. The pixel stage first sets + # v0 = 1.0: its entry VGPRs are SPI inputs, and a stream request carries no SPI input layout, so a pixel stage + # that exports an entry VGPR is refused (gfx2hlsl 6f5a7071; the negative control below keeps that form). target = 12 if stage == 1 else 0 - words = words if words is not None else [0xf800080f | target << 4, 0, 0xbf810000] + if words is None: + words = ([] if stage == 1 else [V_MOV_V0_ONE]) + [0xf800080f | target << 4, 0, 0xbf810000] code = struct.pack("<%dI" % len(words), *words) extent = (40 + len(code) + 4 + 15) & ~15 image = bytearray(248 + extent) @@ -74,7 +80,15 @@ def translate(): translate() assert "Unexpected shader stage" in (cache / (bad + ".fail")).read_text() assert not (cache / (bad + ".txt")).exists() - print("WARP stream request, stage order, compiled VS/PS, truncated and swapped controls passed") + # Negative control: the pixel stage exporting its entry VGPR v0 directly is refused, not translated as 0. + entry = container(0, [0xf800080f, 0, 0xbf810000]) + raw = "%016x" % gfx2hlsl.pipeline_key(vs, entry, root.read_bytes()) + for ext, data in ((".a", vs), (".b", entry), (".root", root.read_bytes())): + (cache / ("req_" + raw + ext)).write_bytes(data) + translate() + assert "reads entry VGPR v0" in (cache / (raw + ".fail")).read_text() + assert not (cache / (raw + ".txt")).exists() + print("WARP stream request, stage order, compiled VS/PS, truncated, swapped and entry-VGPR controls passed") if __name__ == "__main__": diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index e7dcab0a22..90faf28a3c 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -5,9 +5,11 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -89,6 +91,12 @@ static bool create_slot57(void* device, const char* vs_path, const char* ps_path pipeline; } +static UINT env_uint(const wchar_t* name) +{ + wchar_t value[16] = L""; + return GetEnvironmentVariableW(name, value, 16) ? static_cast(std::wcstoul(value, nullptr, 10)) : 0u; +} + // Binds the pipeline on a guest list and records `calls` ExecuteIndirect calls (list slot 61) with a Draw or a // Dispatch signature. No root or target is bound, so every call is refused and nothing is drawn. static bool bind_and_execute_indirect(void* device, void* pipeline, bool dispatch, int calls) @@ -310,6 +318,31 @@ int main(int argc, char** argv) if (!MoveFileW((std::wstring(manifest) + L".pending").c_str(), manifest)) return 61; Sleep(1100); } + wchar_t hold_name[128], release[16]; + const DWORD hold_length = GetEnvironmentVariableW(L"X2W_CX_TEST_HOLD_EVENT", hold_name, 128); + const DWORD release_length = GetEnvironmentVariableW(L"X2W_TEST_HOLD_RELEASE", release, 16); + if (hold_length && hold_length < 128 && release_length && release_length < 16) { + static HANDLE hold = CreateEventW(nullptr, TRUE, FALSE, hold_name); + static DWORD delay = 0; + if (!hold) return 62; + const bool after_first = std::wcscmp(release, L"first") == 0; + if (!after_first) { + delay = static_cast(std::wcstoul(release, nullptr, 10)); + const auto later = [](void*) -> DWORD { + Sleep(delay); + SetEvent(hold); + return 0; + }; + if (const HANDLE t = CreateThread(nullptr, 0, later, nullptr, 0, nullptr)) CloseHandle(t); + else return 62; + } + const std::string first = std::string(argv[5]) + ".first"; + if (const int rc = check_stream_draw(adapter.Get(), device, pso, first.c_str(), nullptr, format)) return rc; + if (after_first) SetEvent(hold); + else WaitForSingleObject(hold, 30000); + Sleep(1500); + return check_stream_draw(adapter.Get(), device, pso, argv[5], nullptr, format); + } if (GetEnvironmentVariableW(L"X2W_TEST_PLACED_VERTEX", nullptr, 0)) { extern void release_placed_vertices(bool); const std::string first = std::string(argv[5]) + ".first"; @@ -320,5 +353,23 @@ int main(int argc, char** argv) release_placed_vertices(true); return rc; } + if (const UINT threads = env_uint(L"X2W_TEST_THREADS"); threads >= 2 && threads <= 8 && !bc7.blocks) { + const UINT repeat = env_uint(L"X2W_TEST_REPEAT") ? env_uint(L"X2W_TEST_REPEAT") : 1; + std::vector workers; + std::vector results(threads, 0); + for (UINT t = 0; t < threads; ++t) + workers.emplace_back([&, t] { + const std::string out = std::string(argv[5]) + ".t" + std::to_string(t); + for (UINT k = 0; k < repeat && !results[t]; ++k) + results[t] = check_stream_draw(adapter.Get(), device, pso, out.c_str(), nullptr, format, export_word, two_targets); + }); + for (auto& w : workers) w.join(); + using LockTimes = std::uint64_t(WINAPI*)(int, std::uint64_t, std::uint64_t); + if (const HMODULE xs = GetModuleHandleW(L"d3d12_xs.dll")) + if (const auto report = reinterpret_cast(GetProcAddress(xs, "x2w_draw_lock_times_test"))) report(1, 0, 0); + for (int r : results) + if (r) return r; + return 0; + } return check_stream_draw(adapter.Get(), device, pso, argv[5], bc7.blocks ? &bc7 : nullptr, format, export_word, two_targets); } diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 34a837861c..3641472c7d 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -289,8 +289,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* // The translated MRT formats draw one pixel; the other formats keep the 8x4 target. const bool single = typed; const bool legacy = !single; - const UINT width = bc_chain ? 384 : bc7 ? (bc7->small4k ? 48 : bc7->width) : bc ? 4 * 128 : single ? 1 : 8; - const UINT height = bc_chain ? 32 : bc7 ? bc7->height : bc ? 128 : single ? 1 : 4; + const bool detile = GetEnvironmentVariableW(L"X2W_TEST_DETILE_SRV", nullptr, 0) != 0; // a 64x64 check target + const UINT width = detile ? 64 : bc_chain ? 384 : bc7 ? (bc7->small4k ? 48 : bc7->width) : bc ? 4 * 128 : single ? 1 : 8; + const UINT height = detile ? 64 : bc_chain ? 32 : bc7 ? bc7->height : bc ? 128 : single ? 1 : 4; ComPtr desktop; if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 20; Bc7Binding binding; @@ -302,7 +303,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* StreamTarget frame; if (two_targets) frame.count = 2; // a second RGBA8 target of the same size, written after the first if (const int rc = open_stream_target(desktop.Get(), guest, pso, width, height, format, - legacy && !bc7 && !bc_chain ? width / 2 : width, frame)) return rc; + legacy && !bc7 && !bc_chain && !detile ? width / 2 : width, frame)) return rc; auto* list = frame.list; auto* queue = frame.queue; auto* fence = frame.fence; @@ -326,6 +327,15 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_SRV", nullptr, 0)) { extern int draw_address_srvs(ID3D12Device*, void*, void*); if (const int result = draw_address_srvs(desktop.Get(), guest, list)) return result; + } else if (detile) { + extern int draw_detile_srvs(void*, void*); + if (const int result = draw_detile_srvs(guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_ANNOUNCED_SRV", nullptr, 0)) { + extern int draw_announced_srvs(ID3D12Device*, void*, void*); + if (const int result = draw_announced_srvs(desktop.Get(), guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_DRAW_UAV", nullptr, 0)) { + extern int draw_uav_stores(ID3D12Device*, void*, void*); + if (const int result = draw_uav_stores(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_MEMORY_SRV_DIAG", nullptr, 0)) { extern int draw_memory_srv_diagnostics(ID3D12Device*, void*, void*); if (const int result = draw_memory_srv_diagnostics(desktop.Get(), guest, list)) return result; @@ -491,7 +501,32 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* invoke(list, 12, 3, 1); last = 2; } + // X2W_TEST_FRAME_COPY=reuse: execute the first list, wait, and record the second half of the frame on the same + // list after Reset (startup_frame_copy.cpp). + char copy_mode[8] = ""; + GetEnvironmentVariableA("X2W_TEST_FRAME_COPY", copy_mode, sizeof(copy_mode)); + const bool copy_reuse = std::strcmp(copy_mode, "reuse") == 0; + if (copy_reuse) { + if (const int rc = submit(1)) return rc; + D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast(invoke(frame.rtv_heap, 9))}; + if (FAILED(static_cast(invoke(frame.allocator, 8))) || + FAILED(static_cast(invoke(list, 139, arg(frame.allocator))))) return 35; + invoke(list, 50, 1, arg(&rtv)); + invoke(list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(list, 25, arg(pso)); + extern int draw_frame_copies_again(void*, UINT, UINT); + if (const int result = draw_frame_copies_again(list, width, height)) return result; + last = 2; + } if (const int rc = submit(last)) return rc; + if (copy_reuse) { + extern int write_ring_counters(); + if (const int result = write_ring_counters()) return result; + } + if (GetEnvironmentVariableW(L"X2W_TEST_DRAW_UAV", nullptr, 0)) { + extern void report_uav_stores(); + report_uav_stores(); + } if (GetEnvironmentVariableW(L"X2W_TEST_ROOT_CBV", nullptr, 0)) { extern int root_heap_report(); if (const int rc = root_heap_report()) return rc; diff --git a/tests/startup_stream_setup.cpp b/tests/startup_stream_setup.cpp index 09a1ad6c00..3c812be1fe 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -163,7 +163,7 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char D3D12_ROOT_PARAMETER root_cbv{}; char cbv_mode[16]{}; if (!textured && GetEnvironmentVariableA("X2W_TEST_ROOT_CBV", cbv_mode, sizeof(cbv_mode))) { - root_cbv.ParameterType = std::strcmp(cbv_mode, "wrong_type") == 0 ? D3D12_ROOT_PARAMETER_TYPE_SRV + root_cbv.ParameterType = (std::strcmp(cbv_mode, "wrong_type") == 0 || std::strcmp(cbv_mode, "root_srv") == 0) ? D3D12_ROOT_PARAMETER_TYPE_SRV : D3D12_ROOT_PARAMETER_TYPE_CBV; root_cbv.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; root_desc.NumParameters = 1; diff --git a/tests/startup_tbuffer_uint_snorm_check.py b/tests/startup_tbuffer_uint_snorm_check.py new file mode 100644 index 0000000000..15b9993bff --- /dev/null +++ b/tests/startup_tbuffer_uint_snorm_check.py @@ -0,0 +1,122 @@ +"""tbuffer_load_format_* with BUF_FMT_8_8_8_8_UINT, 16_16_SNORM, 16_16_UINT, 2_10_10_10_UNORM (gfx10 60, 24, 27, 50).""" +import math +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_sampler_heap_check import root_blob # noqa: E402 +from startup_stream_check import gfx2hlsl # noqa: E402 + +DATA = bytearray(b''.join(struct.pack('> 31 else x + + +def ldu(a): + return int.from_bytes(DATA[a:a + 4], 'little') + + +def lines(name): + code, _, offset = FORMATS[name] + words = (0xf4080400, 0xfa000010, 0xe8032000 | offset | code << 19, 0x80040400, 0xf80008cf, 0x07060504, 0xbf810000) + pipe = gfx2hlsl.Pipeline(struct.pack('<7I', *words), struct.pack('<3I', 0xf800180f, 0, 0xbf810000), + root_blob(flags=0)) + text = [x[3] for x in gfx2hlsl.decode(struct.pack('<7I', *words))][1] + assert 'format:[%s]' % name in text, text + assert 'srv 0 buf vb 1' in pipe.manifest().splitlines() + out = [l.strip() for l in pipe.hlsl_vs().split('\n')] + return [l for l in out if re.match(r'(a|w|v[4-7]) = ', l)] + + +def to_py(expr): + expr = re.sub(r'(\d)u\b', r'\1', expr) + expr = expr.replace('ldu(r0, a)', 'ldu(a)').replace('asint(', 's32(').replace('U(', 'ubits(') + return expr.replace('float(', 'float(') + + +def ubits(x): + return bits(f32(x)) if isinstance(x, float) else x & 0xffffffff + + +def run(body, vertex, stride): + env = {'v0': vertex, 'ud4': stride} + g = {'ldu': ldu, 's32': s32, 'ubits': ubits, 'max': max, 'float': float, '__builtins__': {}} + for line in body: + m = re.fullmatch(r'(\w+) = (.*);', line) + expr = to_py(m.group(2)) + # binary32 division: the dividend is an exact integer, the quotient rounded once + expr = re.sub(r'float\((.*?)\) / 32767\.0', r'f32(float(\1) / 32767.0)', expr) + g['f32'] = f32 + env[m.group(1)] = eval(expr, g, env) & 0xffffffff if m.group(1) in ('a', 'w') else eval(expr, g, env) + return [ubits(env['v%d' % i]) for i in range(4, 8)] + + +def reference(name, vertex, swap=False): + _, stride, offset = FORMATS[name] + a = vertex * stride + offset + if name == 'BUF_FMT_8_8_8_8_UINT': + f = list(DATA[a:a + 4]) + if swap: + f[0], f[1] = f[1], f[0] + return f + if name == 'BUF_FMT_16_16_UINT': + f = [struct.unpack('> s) & m for s, m in ((0, 1023), (10, 1023), (20, 1023), (30, 3))] + if swap: + f[0], f[1] = f[1], f[0] + return [bits(f32(c / float(m))) for c, m in zip(f, (1023, 1023, 1023, 3))] + if name == 'BUF_FMT_16_SNORM': + offset = a + 2 if swap else a + scalar = struct.unpack_from(' -F(v2)' in text.replace('(-F(v2))', '-F(v2)'), text + try: + Q.mesh_pipeline(ps, quad_ops=False).hlsl_ps() + except G.Unsupported as error: + assert 'v_cmp_gt_f32_dpp' in str(error), error + else: + raise AssertionError('VOPC DPP accepted without quad_ops') + print('vopc dpp: synthetic v_cmp_gt_f32 DPP16 word decoded (quad_perm [2,3,0,1], src1 neg); u32 row_shr, cmpx and ' + 'DPP8 decoded; f64, integer modifiers and an invalid control refused; the pixel stage reads src0 through ' + 'QuadReadAcrossY; refused with quad_ops off (control)') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_vsregs_state_check.py b/tests/startup_vsregs_state_check.py new file mode 100644 index 0000000000..897e3289b1 --- /dev/null +++ b/tests/startup_vsregs_state_check.py @@ -0,0 +1,87 @@ +"""SPI_PS_INPUT_ENA and PA_CL_VS_OUT_CNTL read from the runtime's req_.vsregs dump (state block A).""" +import os +import struct +import sys +import tempfile + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import VS_WORDS, root_blob # noqa: E402 +from startup_clip_distance_check import VS as CLIP_VS # noqa: E402 +from startup_spi_input_check import pixel_words, packed # noqa: E402 + + +def dump(ena=0, cntl=0, size=0x184): + blob = bytearray(size) + if size >= 0x5a: + struct.pack_into('= 0x9c: + struct.pack_into(' 0, wrong + + s, lines = lines_of([vop1(0x65, 3, 256 + 3)]) + assert lines == [] and not s.uses_swap, lines + + # uniformity: v2 = 7 is lane-uniform; after the swap v1 holds it, v2 holds the old (non-uniform) v1 + s = stage([]) + s.lines, s.pc = [], 0 + s.lane_s = set() + for _, _, name, text in G.decode(struct.pack('<2I', vop1(1, 2, 128 + 7), swap[0])): + s.one(name, text) + assert 1 in s.uniform_v and 2 not in s.uniform_v, s.uniform_v + + vop3 = [0xd5000000 | (0x180 + 0x65) << 16 | 1, 256 + 2] + assert asm(vop3) == ['v_swap_b32 '], asm(vop3) + try: + lines_of(vop3) + except G.Unsupported: + pass + else: + raise AssertionError('VOP3A v_swap_b32 accepted') + print('vswap: v_swap_b32 matches tmp/D/S0 on %d pairs with exec known, 1 and 0; self-swap emits nothing; ' + 'uniformity follows the moved value; VOP3A refused; reordered statements caught' % len(GRID) ** 2) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_waterfall_check.py b/tests/startup_waterfall_check.py new file mode 100644 index 0000000000..07c792975a --- /dev/null +++ b/tests/startup_waterfall_check.py @@ -0,0 +1,223 @@ +"""Waterfall loops (a VGPR descriptor index made scalar one value at a time) and s_nor_b32 of lane masks.""" +import random +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_scalar_bits_check import stage # noqa: E402 + +LOOP = ['v_readfirstlane_b32 s13, v46', 'v_cmpx_eq_i32_e32 s13, v46', 's_lshl_b32 s13, s13, 5', + 's_load_dwordx8 s[32:39], s[10:11], s13', 's_and_saveexec_b32 s13, s12', 's_waitcnt lgkmcnt(0)', + 'image_sample v44, v[40:41], s[32:39], s[20:23] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 's_or_saveexec_b32 s26, s13', 's_andn2_wrexec_b32 s25, s25', 's_cbranch_scc1 label_0x%x'] + + +def wave(index, exec_, s12, heap): + """The loop on a 32-lane wave: v44 per lane (None = not written).""" + v44 = [None] * 32 + s25, rounds = exec_, 0 + while True: + rounds += 1 + assert rounds <= 33 + first = (exec_ & -exec_).bit_length() - 1 if exec_ else 0 + s13 = index[first] + exec_ &= sum(1 << l for l in range(32) if index[l] == s13) + desc = heap[(s13 << 5) >> 5] + s13, exec_ = exec_, s12 & exec_ + for l in range(32): + if exec_ >> l & 1: + v44[l] = desc + exec_ |= s13 + exec_ = s25 & ~exec_ & 0xffffffff + s25 = exec_ + if not exec_: + return v44 + + +def one_lane(own, active, s12bit, heap, first_lane_index=None, passes=4): + """The same loop in the one-lane model: exec is this lane's bit; readfirstlane gives own (or a forced index). + passes=1 is the emitted form: the body once, the back edge dropped.""" + v44, exec_, s25 = None, active, active + for _ in range(passes): + if passes == 1: # as emitted: an inactive lane's index is 0 (its stale value never reaches a heap read) + s13 = (own if active else 0) if first_lane_index is None else first_lane_index + exec_ &= int(s13 == own) + desc = heap[(s13 << 5) >> 5] + s13, exec_ = exec_, s12bit & exec_ + if exec_: + v44 = desc + return v44 + s13 = own if first_lane_index is None else first_lane_index + exec_ &= int(s13 == own) + desc = heap[(s13 << 5) >> 5] + s13, exec_ = exec_, s12bit & exec_ + if exec_: + v44 = desc + exec_ |= s13 + exec_ = s25 & ~exec_ & 1 + s25 = exec_ + if not exec_: + return v44 + return 'no exit' # (only the negative control's forced index gets here) + + +def semantics(): + rng = random.Random(7) + heap = {i: 1000 + i for i in range(16)} + trials = 0 + for _ in range(400): + index = [rng.choice((0, 3, 3, 5, 9, 15)) for _ in range(32)] + exec_ = rng.getrandbits(32) | (1 << rng.randrange(32)) + s12 = rng.getrandbits(32) | rng.choice((0, 0xffffffff)) + hw = wave(index, exec_, s12, heap) + for l in range(32): + assert hw[l] == one_lane(index[l], exec_ >> l & 1, s12 >> l & 1, heap), (index, hex(exec_), l) + assert hw[l] == one_lane(index[l], exec_ >> l & 1, s12 >> l & 1, heap, passes=1), (index, l) + trials += 1 + # the looped one-lane form never exits under a wrong index (the hang shape); the one-pass form ends regardless + assert one_lane(5, 1, 1, heap, first_lane_index=3) == 'no exit' + assert one_lane(5, 1, 1, heap, first_lane_index=3, passes=1) is None + index = [3] + [5] * 31 + hw = wave(index, 0xffffffff, 0xffffffff, heap) + assert any(hw[l] != one_lane(index[l], 1, 1, heap, first_lane_index=index[0]) for l in range(32)) + return trials + + +def ins_of(text_lines, at=0x100): + out, off = [], at + for text in text_lines: + name = text.split(' ', 1)[0] + n = 8 if name.startswith(('s_load', 'image_', 'v_cmpx_eq_i32_e64')) else 4 + out.append((off, n, name, text)) + off += n + return out + + +def build(body, head=0x100, prefix=('s_mov_b32 s25, exec_lo',), after=('s_endpgm',)): + pre = ins_of(prefix, head - 4 * len(prefix)) + loop = ins_of([x % head if '%x' in x else x for x in body], head) + post = ins_of(after, loop[-1][0] + loop[-1][1]) + return pre + loop + post + + +def readfirstlane(ins, pc): + s = stage([]) + s.ins, s.pc, s.lines = ins, pc, [] + s.uniform_v, s.partial_uniform = set(), {} + s.one('v_readfirstlane_b32', [t for o, _, _, t in ins if o == pc][0]) + return s.lines + + +def refused(ins, pc, why): + try: + readfirstlane(ins, pc) + except G.Unsupported as error: + assert why in str(error), (why, str(error)) + return + raise AssertionError('accepted: ' + why) + + +def one_pass(): + """The proven loop's s_cbranch_scc1 is emitted as fall-through (no back edge, so no dispatch loop); an + s_cbranch_scc1 elsewhere, or in a stage where no waterfall was proven, is still a branch.""" + ins = build(LOOP) + back = [(o, t) for o, _, n, t in ins if n == 's_cbranch_scc1'][0] + s = stage([]) + s.ins, s.pc, s.lines = ins, 0x100, [] + s.uniform_v, s.partial_uniform = set(), {} + s.one('v_readfirstlane_b32', 'v_readfirstlane_b32 s13, v46') + s.pc, s.lines = back[0], [] + assert s.one('s_cbranch_scc1', back[1]) is None and 'not taken' in s.lines[0], s.lines + s.pc = back[0] + 8 + assert s.one('s_cbranch_scc1', back[1]) == ('branch', 'scc', 0x100) + fresh = stage([]) + fresh.pc, fresh.lines = back[0], [] + assert fresh.one('s_cbranch_scc1', back[1]) == ('branch', 'scc', 0x100) + + +def translation(): + one_pass() + assert readfirstlane(build(LOOP), 0x100) == ['s13 = ((exec & 1) != 0 ? v46 : 0u);'] + wide = ['s_waitcnt vmcnt(0)', 'v_readfirstlane_b32 s10, v28', 'v_cmpx_eq_i32_e32 s10, v28', + 's_lshl_b32 s10, s10, 5', 's_load_dwordx8 s[48:55], s[30:31], s10', 's_waitcnt lgkmcnt(0)', + 'image_sample_lz v21, v[21:22], s[48:55], s[32:35] dmask:0x8 dim:SQ_RSRC_IMG_2D', + 's_andn2_wrexec_b64 s[44:45], s[44:45]', 's_cbranch_scc1 label_0x%x'] + assert readfirstlane(build(wide), 0x104) == ['s10 = ((exec & 1) != 0 ? v28 : 0u);'] + controls = 0 + no_cmpx = [x for x in LOOP if not x.startswith('v_cmpx')] + refused(build(no_cmpx), 0x100, 'requires a proven uniform source'); controls += 1 + carried = LOOP[:2] + ['s_add_u32 s40, s40, 1'] + LOOP[2:] + refused(build(carried), 0x100, 'carries s40'); controls += 1 + refused(build(LOOP, after=('s_mov_b32 s5, s26', 's_endpgm')), 0x100, 's26 read after'); controls += 1 + refused(build(LOOP, after=('s_cbranch_scc0 label_0x138', 's_endpgm', 's_lshl_b32 s5, s13, 1', 's_endpgm')), + 0x100, 's13 read after'); controls += 1 + branchy = LOOP[:3] + ['s_cbranch_execz label_0x200'] + LOOP[3:] + refused(build(branchy), 0x100, 'another branch'); controls += 1 + store = LOOP[:3] + ['s_store_dword s13, s[0:1], 0x0'] + LOOP[3:] + refused(build(store), 0x100, 'body with s_store_dword'); controls += 1 + unclosed = [x for x in LOOP if 'wrexec' not in x] + refused(build(unclosed), 0x100, 'not closed by s_andn2_wrexec'); controls += 1 + # written again before any read on every exit path: accepted + assert readfirstlane(build(LOOP, after=('s_mov_b32 s13, 0', 's_mov_b32 s26, 1', 's_mov_b32 s5, s13', + 's_endpgm')), 0x100) == ['s13 = ((exec & 1) != 0 ? v46 : 0u);'] + return controls + + +def sop2(op, dst, a, b): + return 0x80000000 | op << 23 | dst << 16 | b << 8 | a + + +def nor(): + cmp_vcc = 0x7c000000 | 0xc1 << 17 | 0 << 9 | 129 # v_cmp_lt_u32 vcc, 1, v0 + save = 0xbe800000 | 20 << 16 | 0x24 << 8 | 106 # s_and_saveexec_b64 s[20:21], vcc (s20 a mask) + words = [cmp_vcc, save, sop2(0x1a, 5, 20, 20)] # s_nor_b32 s5, s20, s20 + text = [x[3] for x in G.decode(struct.pack('<3I', *words))] + assert text[2] == 's_nor_b32 s5, s20, s20', text + s = stage(words) + body = [line for _, lines, _ in s.blocks for line in lines] + line = [x for x in body if x.startswith('s5 = ')] + assert line == ['s5 = (~(s20 | s20)) & 1;'], body + assert not any(x.startswith('scc') for x in body[body.index(line[0]):]), body + for a in (0, 1): + for b in (0, 1): + assert (~(a | b)) & 1 == int(not (a or b)) + # a 0 / 0xffffffff operand (s_cselect_b32 s10, -1, 0) has every lane's bit equal: accepted with a mask + splat = [cmp_vcc, sop2(0x0a, 10, 0xc1, 0x80), sop2(0x1a, 5, 106, 10)] + text = [x[3] for x in G.decode(struct.pack('<3I', *splat))] + assert text[1:] == ['s_cselect_b32 s10, -1, 0', 's_nor_b32 s5, vcc_lo, s10'], text + body = [line for _, lines, _ in stage(splat).blocks for line in lines] + assert 's5 = (~(vcc | s10)) & 1;' in body, body + for value, lane in ((0, 0), (0, 1), (0xffffffff, 0), (0xffffffff, 1)): + assert (~(lane | value)) & 1 == int(not (lane or value & 1)) + # a plain number with a mask (bit i is not lane i's) stays refused + try: + stage([cmp_vcc, sop2(0x1a, 5, 106, 11)]) + except G.Unsupported as error: + assert 'on a lane mask' in str(error), str(error) + else: + raise AssertionError('s_nor_b32 of vcc_lo and a number accepted') + branch = 0xbf850000 | 1 # s_cbranch_scc1 +1 + try: + stage(words + [branch, 0xbf800000]) + except G.Unsupported as error: + assert 'scc' in str(error).lower(), str(error) + else: + raise AssertionError('SCC of s_nor_b32 on a mask read') + + +def main(): + trials = semantics() + controls = translation() + nor() + print('waterfall: wave and one-lane models agree on %d random (index, exec, s12) patterns x 32 lanes; ' + 'lane-0 readfirstlane caught (negative control); b32 and b64 forms translate to sN = vM; %d controls ' + 'refused; one pass (back edge dropped) matches the wave on every lane and ends under a wrong index where the ' + 'looped form never exits; s_nor_b32 of a mask is the lane bit with no SCC (SCC read refused)' % (trials, controls)) + + +if __name__ == '__main__': + main() diff --git a/tests/tile_mapping_shared_heap_check.cpp b/tests/tile_mapping_shared_heap_check.cpp new file mode 100644 index 0000000000..3ebe42b505 --- /dev/null +++ b/tests/tile_mapping_shared_heap_check.cpp @@ -0,0 +1,205 @@ +#include +#include +#include +#include + +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT64 page = 65536; +constexpr struct { int heap; UINT tile; } mapping[3] = {{0, 2}, {1, 0}, {0, 1}}; + +void drain(ID3D12Device* device) +{ + ComPtr queue; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&queue)))) return; + for (UINT64 i = 0; i < queue->GetNumStoredMessages() && i < 8; ++i) { + SIZE_T bytes = 0; + queue->GetMessage(i, nullptr, &bytes); + auto* message = static_cast(std::malloc(bytes)); + if (message && SUCCEEDED(queue->GetMessage(i, message, &bytes))) + std::printf("debug sev=%d id=%d %s\n", message->Severity, message->ID, message->pDescription); + std::free(message); + } + queue->ClearStoredMessages(); +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) +{ + return {D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags}; +} + +ComPtr committed(ID3D12Device* device, D3D12_HEAP_TYPE type, UINT64 bytes, D3D12_RESOURCE_STATES state) +{ + const D3D12_HEAP_PROPERTIES properties{type}; + const D3D12_RESOURCE_DESC desc = buffer_desc(bytes); + ComPtr buffer; + device->CreateCommittedResource(&properties, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&buffer)); + return buffer; +} + +UINT pattern(int heap, UINT64 byte) { return (static_cast(heap + 1) << 28) | static_cast(byte); } +} // namespace + +int main(int argc, char** argv) +{ + std::setvbuf(stdout, nullptr, _IONBF, 0); + if (argc < 3) return 2; + const bool hardware = !std::strcmp(argv[1], "hardware"); + const bool shared = !std::strcmp(argv[2], "shared"); + if ((!hardware && std::strcmp(argv[1], "warp")) || (!shared && std::strcmp(argv[2], "plain"))) return 2; + const bool debug_layer = !(argc > 3 && !std::strcmp(argv[3], "nodebug")); + ComPtr debug; + if (debug_layer && SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) debug->EnableDebugLayer(); + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (hardware) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(hr) || FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { + adapter = candidate; + break; + } + } + } else if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + LARGE_INTEGER driver{}; + adapter->GetDesc(&adapter_desc); + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls driver=%u.%u.%u.%u mode=%s debug layer %s\n", adapter_desc.Description, HIWORD(driver.HighPart), + LOWORD(driver.HighPart), HIWORD(driver.LowPart), LOWORD(driver.LowPart), argv[2], debug_layer ? "on" : "off"); + ComPtr device; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) return 77; + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)); + std::printf("tiled resources tier %d\n", static_cast(options.TiledResourcesTier)); + if (options.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_1) return 77; + + ComPtr heaps[2]; + unsigned char* views[2] = {}; + for (int i = 0; i < 2; ++i) { + HRESULT hr; + if (shared) { + const HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 4 * page, nullptr); + views[i] = section ? static_cast(MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 4 * page)) : nullptr; + if (!views[i]) return 4; + for (UINT64 b = 0; b < 4 * page; b += 4) *reinterpret_cast(views[i] + b) = pattern(i, b); + hr = device->OpenExistingHeapFromFileMapping(section, IID_PPV_ARGS(&heaps[i])); + } else { + const D3D12_HEAP_DESC desc{4 * page, {D3D12_HEAP_TYPE_DEFAULT}, 0, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS}; + hr = device->CreateHeap(&desc, IID_PPV_ARGS(&heaps[i])); + } + const D3D12_HEAP_DESC got = SUCCEEDED(hr) ? heaps[i]->GetDesc() : D3D12_HEAP_DESC{}; + std::printf("heap %d (%s) -> 0x%08lx size 0x%llx flags 0x%x%s\n", i, shared ? "OpenExistingHeapFromFileMapping" : "CreateHeap", + static_cast(hr), got.SizeInBytes, got.Flags, + got.Flags & D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER ? " (SHARED_CROSS_ADAPTER)" : ""); + if (FAILED(hr)) return 5; + if (shared && !(got.Flags & D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER)) { + std::printf("FAIL: an opened file-mapping heap without SHARED_CROSS_ADAPTER: the gate's assumption is wrong\n"); + return 6; + } + } + const D3D12_RESOURCE_DESC reserved_desc = buffer_desc(3 * page, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + ComPtr reserved; + HRESULT hr = device->CreateReservedResource(&reserved_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&reserved)); + std::printf("CreateReservedResource -> 0x%08lx\n", static_cast(hr)); + if (FAILED(hr)) return 7; + ComPtr queue; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + if (FAILED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)))) return 8; + for (UINT t = 0; t < 3; ++t) { + const D3D12_TILED_RESOURCE_COORDINATE coordinate{t, 0, 0, 0}; + const D3D12_TILE_REGION_SIZE region{1, FALSE, 0, 0, 0}; + const D3D12_TILE_RANGE_FLAGS flags = D3D12_TILE_RANGE_FLAG_NONE; + const UINT start = mapping[t].tile, count = 1; + queue->UpdateTileMappings(reserved.Get(), 1, &coordinate, ®ion, heaps[mapping[t].heap].Get(), 1, &flags, &start, &count, + D3D12_TILE_MAPPING_FLAG_NONE); + } + const HRESULT removed_after_mapping = device->GetDeviceRemovedReason(); + std::printf("after UpdateTileMappings: device removed reason 0x%08lx\n", static_cast(removed_after_mapping)); + drain(device.Get()); + if (shared && removed_after_mapping != S_OK) { + std::printf("shared: tile mapping onto opened file-mapping heaps refused (device removed 0x%08lx): as measured; PASS\n", + static_cast(removed_after_mapping)); + return 0; + } + + ComPtr allocator; + ComPtr list; + ComPtr fence; + if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) || + FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) + return 9; + ComPtr readback[2]; + ComPtr upload, placed[2]; + if (shared) { + readback[0] = committed(device.Get(), D3D12_HEAP_TYPE_READBACK, 3 * page, D3D12_RESOURCE_STATE_COPY_DEST); + if (!readback[0]) return 10; + list->CopyBufferRegion(readback[0].Get(), 0, reserved.Get(), 0, 3 * page); + } else { + upload = committed(device.Get(), D3D12_HEAP_TYPE_UPLOAD, 3 * page, D3D12_RESOURCE_STATE_GENERIC_READ); + UINT* words = nullptr; + if (!upload || FAILED(upload->Map(0, nullptr, reinterpret_cast(&words)))) return 10; + for (UINT t = 0; t < 3; ++t) + for (UINT64 b = 0; b < page; b += 4) words[(t * page + b) / 4] = pattern(mapping[t].heap, mapping[t].tile * page + b); + upload->Unmap(0, nullptr); + list->CopyBufferRegion(reserved.Get(), 0, upload.Get(), 0, 3 * page); + D3D12_RESOURCE_BARRIER barrier{D3D12_RESOURCE_BARRIER_TYPE_ALIASING}; // the reserved buffer's writes reach the heaps + barrier.Aliasing = {nullptr, nullptr}; + list->ResourceBarrier(1, &barrier); + for (int i = 0; i < 2; ++i) { + const D3D12_RESOURCE_DESC desc = buffer_desc(4 * page); + if (FAILED(device->CreatePlacedResource(heaps[i].Get(), 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&placed[i])))) return 11; + readback[i] = committed(device.Get(), D3D12_HEAP_TYPE_READBACK, 4 * page, D3D12_RESOURCE_STATE_COPY_DEST); + if (!readback[i]) return 11; + list->CopyBufferRegion(readback[i].Get(), 0, placed[i].Get(), 0, 4 * page); + } + } + list->Close(); + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + queue->Signal(fence.Get(), 1); + for (const ULONGLONG deadline = GetTickCount64() + 30000; fence->GetCompletedValue() < 1;) { + if (GetTickCount64() >= deadline || device->GetDeviceRemovedReason() != S_OK) break; + Sleep(1); + } + drain(device.Get()); + const HRESULT removed = device->GetDeviceRemovedReason(); + std::printf("device removed reason 0x%08lx\n", static_cast(removed)); + if (removed != S_OK) return 12; + int bad = 0; + for (UINT t = 0; t < 3; ++t) { + const int heap = mapping[t].heap; + const UINT* words = nullptr; + const D3D12_RANGE all{0, (shared ? 3 : 4) * page}; + ID3D12Resource* source = readback[shared ? 0 : heap].Get(); + if (FAILED(source->Map(0, &all, reinterpret_cast(const_cast(&words))))) return 13; + for (UINT64 b = 0; b < page; b += 4) { + const UINT got = shared ? words[(t * page + b) / 4] : words[(mapping[t].tile * page + b) / 4]; + const UINT want = pattern(heap, mapping[t].tile * page + b); + if (got != want && bad++ < 4) std::printf("tile %u (heap %d tile %u) +0x%llx: %08x, want %08x\n", t, heap, mapping[t].tile, b, got, want); + } + source->Unmap(0, nullptr); + } + if (shared) { + std::printf("FAIL: tile mapping onto opened file-mapping heaps WORKED (%s, %d bad dwords). Revisit X2W_RANGE_ALIAS's gate.\n", + bad ? "with wrong data" : "exact", bad); + return 14; + } + std::printf("plain: 3 tiles mapped out of order onto 2 CreateHeap heaps, written through the reserved buffer: %s (%d bad dwords)\n", + bad ? "MISMATCH" : "exact", bad); + std::printf("%s\n", bad ? "FAIL" : "PASS"); + return bad ? 15 : 0; +} diff --git a/tests/xmem_scatter_refusal_check.py b/tests/xmem_scatter_refusal_check.py new file mode 100644 index 0000000000..727a918a03 --- /dev/null +++ b/tests/xmem_scatter_refusal_check.py @@ -0,0 +1,273 @@ +"""Refused scatter maps in the permissive xmem shim (X2W_XMEM_PERMISSIVE=1): the run-shaped batch, two threads""" +import ctypes as C +import os +from pathlib import Path +import subprocess +import sys +import threading +import time + +PAGE = 0x10000 +PHYSICAL_64K = 0x20400000 +STARTUP_RESERVE = 0x20402000 +MEM_RELEASE = 0x8000 +MEM_REPLACE_PLACEHOLDER, MEM_PRESERVE_PLACEHOLDER = 0x4000, 0x2 +# The 25 destination ranges (pages) of the refused batch of the startup run, in its order; offsets are synthetic. +RANGES = [1, 13, 6, 3, 7, 1, 9, 2, 5, 5, 8, 117, 7, 120, 8, 119, 6, 1, 17, 7, 112, 7, 132, 3, 1] +assert sum(RANGES) == 717 + + +class Shim: + def __init__(self, path): + lib = C.WinDLL(str(Path(path).resolve()), use_last_error=True, winmode=0x900) + k = C.WinDLL("kernelbase.dll", use_last_error=True) + vp, n, dw = C.c_void_p, C.c_size_t, C.c_ulong + def bind(owner, name, args, res): + f = getattr(owner, name) + f.argtypes, f.restype = args, res + return f + self.allocate = bind(lib, "XMemAllocatePhysicalPages", [n, C.POINTER(n), C.POINTER(n)], C.c_int) + self.scatter_raw = bind(lib, "XMemMapPhysicalPagesScatter", [C.POINTER(vp), n, C.POINTER(n)], C.c_int) + self.virtual_alloc = bind(lib, "XMemVirtualAlloc", [vp, n, dw, n, dw], vp) + self.map3 = bind(k, "MapViewOfFile3", [vp, vp, vp, C.c_ulonglong, n, dw, dw, vp, dw], vp) + self.unmap2 = bind(k, "UnmapViewOfFile2", [vp, vp, dw], C.c_int) + self.mapping = bind(k, "CreateFileMappingW", [vp, vp, dw, dw, dw, vp], vp) + self.process = bind(k, "GetCurrentProcess", [], vp)() + self.base = self.virtual_alloc(None, 16 << 30, STARTUP_RESERVE, 0x21, 4) + assert self.base, C.get_last_error() + + def pages(self, count): + got, tokens = C.c_size_t(count), (C.c_size_t * count)() + assert self.allocate(PHYSICAL_64K, C.byref(got), tokens) and got.value == count, C.get_last_error() + return list(tokens) + + def scatter(self, addresses, tokens): + a = (C.c_void_p * len(addresses))(*addresses) + t = (C.c_size_t * len(tokens))(*tokens) + ok = self.scatter_raw(a, len(addresses), t) + return ok, C.get_last_error() + + +def batch_addresses(base): + """717 page addresses in 25 ranges spread over the reservation, in the run's (unsorted) range order.""" + order = [5, 1, 14, 22, 9, 13, 15, 2, 8, 17, 12, 19, 7, 20, 0, 18, 10, 3, 6, 11, 21, 23, 4, 16, 24] + addresses = [] + for slot, pages in zip(order, RANGES): + start = base + 0x10000000 + slot * 0x18000000 # 384 MiB apart, 256 MiB in + addresses += [start + i * PAGE for i in range(pages)] + return addresses + + +def word(address): + return C.c_uint32.from_address(address) + + +def child(case, dll, log): + shim = Shim(dll) + addresses = batch_addresses(shim.base) + tokens = shim.pages(len(addresses) + 16) + pages = tokens[:len(addresses)] + if case == "shape": + home = shim.base + 0x3F0000000 # the pages' first view, as the title's contiguous mapping + ok, err = shim.scatter([home + i * PAGE for i in range(len(pages))], pages) + assert ok, f"first views refused: {err}" + for i in range(len(pages)): + word(home + i * PAGE).value = 0xA5000000 + i + ok, err = shim.scatter(addresses, pages) + assert ok, f"the run-shaped batch was refused: error {err}" + bad = [i for i, a in enumerate(addresses) if word(a).value != 0xA5000000 + i] + assert not bad, f"second views do not show the pages' bytes at entries {bad[:5]}" + word(addresses[0]).value = 0x12345678 + assert word(home).value == 0x12345678, "a write through the second view is not seen through the first" + print("shape ok: 717 pages, 25 ranges, unsorted, second views agree") + return 0 + if case == "race": + other = tokens[len(addresses):] + target = addresses[400] + stop = time.perf_counter() + float(os.environ.get("RACE_SECONDS", "6")) + result = {"a_calls": 0, "a_fail": [], "b_calls": 0, "b_fail": []} + def a(): + while time.perf_counter() < stop: + for toks in (pages, [0] * len(pages)): + ok, err = shim.scatter(addresses, toks) + result["a_calls"] += 1 + if not ok: result["a_fail"].append(err) + def b(): + i = 0 + while time.perf_counter() < stop: + ok, err = shim.scatter([target], [other[i % len(other)] if i % 2 == 0 else 0]) + result["b_calls"] += 1 + if not ok: result["b_fail"].append(err) + i += 1 + threads = [threading.Thread(target=a), threading.Thread(target=b)] + for t in threads: t.start() + for t in threads: t.join() + fails = result["a_fail"] + result["b_fail"] + print(f"race calls A={result['a_calls']} B={result['b_calls']} failures A={len(result['a_fail'])} " + f"B={len(result['b_fail'])} errors={sorted(set(fails))}") + return 3 if fails else 0 + if case == "foreign": + target = addresses[0] + # A view elsewhere in the reservation keeps the shim from coalescing its placeholders after the unmap below. + ok, err = shim.scatter([shim.base + 0x3F0000000], [pages[5]]) + assert ok, err + ok, err = shim.scatter([target], [pages[0]]) + assert ok, err + ok, err = shim.scatter([target], [0]) # unmapped again: a 64 KiB placeholder stays + assert ok, err + section = shim.mapping(C.c_void_p(-1), None, 4, 0, PAGE, None) + assert section + view = shim.map3(section, shim.process, target, 0, PAGE, MEM_REPLACE_PLACEHOLDER, 4, None, 0) + assert view == target, f"the test could not put its own view there: {C.get_last_error()}" + second = target + 0x1000000 # above the target: the target is entry 0 of the sorted call + ok, err = shim.scatter([second, target], [pages[1], pages[0]]) + print(f"foreign view at the target: ok={ok} error={err}") + assert not ok and err == 87, (ok, err) + assert shim.unmap2(shim.process, target, MEM_PRESERVE_PLACEHOLDER) + ok, err = shim.scatter([second, target], [pages[1], pages[0]]) + assert ok, f"after the foreign view is gone the same call must map: {err}" + return 0 + if case == "remap": + lib = C.WinDLL(str(Path(dll).resolve()), use_last_error=True, winmode=0x900) + k = C.WinDLL("kernelbase.dll", use_last_error=True) + k.VirtualQuery.argtypes = [C.c_void_p, C.c_void_p, C.c_size_t] + k.VirtualQuery.restype = C.c_size_t + settled = getattr(lib, "x2w_xmem_write_settled", None) + event = getattr(lib, "x2w_xmem_page_event", None) + if settled: + settled.argtypes, settled.restype = [C.c_void_p, C.c_void_p, C.c_size_t, C.c_size_t], C.c_int + u32, u64 = C.POINTER(C.c_ulong), C.POINTER(C.c_ulonglong) + event.argtypes, event.restype = [C.c_void_p, u32, u64, u32, u64, u64, u64], C.c_int + target = addresses[200] + ok, err = shim.scatter([shim.base + 0x3F0000000], [pages[5]]) # keeps the reservation from coalescing + assert ok, err + ok, err = shim.scatter([target], [pages[0]]) + assert ok, err + stop = time.perf_counter() + float(os.environ.get("RACE_SECONDS", "4")) + counts = {"remaps": 0, "remap_fail": 0, "checks": 0, "gap": 0, "settled": 0, "settled_fail": 0} + def a(): + i = 0 + while time.perf_counter() < stop: + ok, _ = shim.scatter([target], [pages[1 + (i % 2)]]) # P -> Q -> P ...: unmap + map in one call + counts["remaps"] += 1 + counts["remap_fail"] += not ok + i += 1 + def b(): + info = (C.c_ubyte * 48)() + payload = (C.c_ubyte * 16)(*range(16)) + while time.perf_counter() < stop: + assert k.VirtualQuery(target, info, 48) == 48 + state = int.from_bytes(bytes(info[32:36]), "little") + counts["checks"] += 1 + counts["gap"] += state != 0x1000 + if settled: + counts["settled"] += 1 + counts["settled_fail"] += not settled(target, payload, 16, PAGE) + threads = [threading.Thread(target=a), threading.Thread(target=b)] + for t in threads: t.start() + for t in threads: t.join() + line = " ".join(f"{key}={value}" for key, value in counts.items()) + if not settled: + print(f"remap (no x2w_xmem_write_settled in this build): {line}") + return 0 if counts["gap"] else 4 + kind, thread = C.c_ulong(), C.c_ulong() + page, age, serial, remaps = C.c_ulonglong(), C.c_ulonglong(), C.c_ulonglong(), C.c_ulonglong() + view = event(target, C.byref(kind), C.byref(page), C.byref(thread), C.byref(age), C.byref(serial), C.byref(remaps)) + ok, err = shim.scatter([target], [0]) + assert ok, err + view_after = event(target, C.byref(kind), C.byref(page), C.byref(thread), C.byref(age), C.byref(serial), None) + never = C.c_ulong() + view_never = event(shim.base + 0x3E0000000, C.byref(never), None, None, None, None, None) + print(f"remap: {line}; page_event mapped={view} remaps={remaps.value}; after unmap view={view_after} " + f"kind={kind.value} page=0x{page.value:x}; untouched address view={view_never} kind={never.value}") + good = (counts["gap"] > 0 and counts["settled_fail"] == 0 and counts["remap_fail"] == 0 and view == 1 and + remaps.value >= counts["remaps"] - 1 and view_after == 0 and kind.value == 2 and page.value == pages[1 + ((counts["remaps"] - 1) % 2)] >> 4 + and view_never == 0 and never.value == 0) + return 0 if good else 5 + if case == "wait": + lib = C.WinDLL(str(Path(dll).resolve()), use_last_error=True, winmode=0x900) + wait = lib.x2w_xmem_write_settled_wait + wait.argtypes = [C.c_void_p, C.c_void_p, C.c_size_t, C.c_size_t, C.c_ulong, C.POINTER(C.c_ulong)] + wait.restype = C.c_int + ok, err = shim.scatter([shim.base + 0x3F0000000], [pages[5]]) # keeps the reservation from coalescing + assert ok, err + target, never = addresses[300], addresses[301] + payload = (C.c_ubyte * 16)(*range(0xA0, 0xB0)) + def late_map(): + time.sleep(0.05) + ok, err = shim.scatter([target], [pages[2]]) + assert ok, err + mapper = threading.Thread(target=late_map) + waited = C.c_ulong() + mapper.start() + served = wait(target, payload, 16, PAGE, 250, C.byref(waited)) + mapper.join() + content = bytes((C.c_ubyte * 16).from_address(target)) if served else b"" + waited_never = C.c_ulong() + refused = not wait(never, payload, 16, PAGE, 250, C.byref(waited_never)) + print(f"wait: late-mapped destination served={served} after {waited.value} ms content_ok={content == bytes(payload)}; " + f"never-mapped destination refused={refused} after {waited_never.value} ms") + good = served and 45 <= waited.value < 250 and content == bytes(payload) and refused and waited_never.value >= 250 + return 0 if good else 6 + if case == "unowned": + ok, err = shim.scatter([addresses[0], addresses[1]], [pages[0], (max(tokens) >> 4 << 4) + (1000 << 4)]) + print(f"unowned token: ok={ok} error={err}") + assert not ok and err == 87, (ok, err) + return 0 + raise SystemExit(f"unknown case {case}") + + +def run(case, dll, log): + if log.exists(): log.unlink() + env = dict(os.environ, X2W_XMEM_PERMISSIVE="1", X2W_XMEM_GPU_POOL="0", X2W_TRAP_LOG=str(log)) + for name in ("X2W_XMEM_SLAB_DIR", "X2W_XMEM_SLAB_BUDGET_MIB", "X2W_XMEM_SHARED_VIEWS", "X2W_XMEM_GPU_MIRROR"): + env.pop(name, None) + done = subprocess.run([sys.executable, "-B", __file__, "--child", case, str(dll), str(log)], env=env, + capture_output=True, text=True, timeout=180) + text = log.read_text(errors="replace") if log.exists() else "" + return done.returncode, done.stdout.strip(), text + + +def main(): + if sys.argv[1] == "--child": + return child(sys.argv[2], sys.argv[3], sys.argv[4]) + dll = Path(sys.argv[1]).resolve() + control = "--control" in sys.argv + logs = Path(os.environ.get("XMEM_CHECK_LOGS", Path(dll).parent)) + results = {} + cases = ["shape", "race", "foreign", "unowned", "remap"] + ([] if control else ["wait"]) + for case in cases: + code, out, text = run(case, dll, logs / f"scatter_{case}.log") + refused = [line for line in text.splitlines() if "x2w-xmem REFUSED" in line] + results[case] = (code, out, refused, text) + print(f"[{case}] exit {code}: {out}") + for line in refused[:2]: + print(f" {line[:700]}") + failures = [] + if not control: + if results["shape"][0]: failures.append("shape refused") + if results["race"][0]: failures.append("race: a call failed") + code, out, refused, _ = results["foreign"] + if code: failures.append("foreign: wrong outcome") + need = ("entry 0 of 2", "MapViewOfFile3 err 487", "split err 87", "state 0x1000", "type 0x40000", "no view") + if not refused or not all(n in refused[0] for n in need): + failures.append(f"foreign: REFUSED line missing or incomplete (needs {need})") + code, out, refused, _ = results["unowned"] + if code: failures.append("unowned: wrong outcome") + if not refused or "NOT granted" not in refused[0] or "not granted (era_physical::owns)" not in refused[0]: + failures.append("unowned: REFUSED line missing or does not name the check") + if results["remap"][0]: failures.append("remap: gap not seen, or a settled write / page event was wrong") + if results["wait"][0]: failures.append("wait: late map not served after the wait, or never-mapped not refused after the bound") + print("FAIL: " + "; ".join(failures) if failures else "PASS xmem_scatter_refusal (shape, race, foreign, unowned, remap, wait)") + else: + if results["shape"][0]: failures.append("shape refused on the control build too") + if not results["race"][0]: failures.append("race did not fail on the control build") + if results["foreign"][2] or results["unowned"][2]: failures.append("control build printed REFUSED lines") + if results["remap"][0]: failures.append("remap: the gap was not seen on the control build") + print("FAIL control: " + "; ".join(failures) if failures else + "PASS control: the build without the fix fails the race and logs no cause") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/bcpack_bcn.py b/tools/bcpack_bcn.py new file mode 100644 index 0000000000..f325a8a72b --- /dev/null +++ b/tools/bcpack_bcn.py @@ -0,0 +1,219 @@ +"""Reference BCPack block reconstruction for BC3, BC4 and BC5, kept in step with bcpack_decoder.h.""" +import ast +import re +from pathlib import Path + +from _bcpack_rans import BCPackError, decode_lanes + +ROOT = Path(__file__).resolve().parents[1] +TABLES = ROOT / "src" / "startup_stubs" / "bcpack_tables_bcn.inl" + +# format: (alphabet bits per lane = symbol width - 1, block bytes, symbols per lane per block) +LAYOUTS = { + 3: ((3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7), 16, 2), + 4: ((7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5), 8, 1), + 5: ((3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5), 16, 2), + 6: ((3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4), 16, 2), +} + +ALPHA_CODE = (0, 2, 3, 4, 5, 6, 7, 1) # ramp position -> BC4 index code +COLOUR_CODE = (0, 2, 3, 1) # ramp position -> BC1 index code +ALPHA_POSITION = tuple(ALPHA_CODE.index(c) for c in range(8)) +COLOUR_POSITION = tuple(COLOUR_CODE.index(c) for c in range(4)) + +_TABLE_CACHE = {} + + +def _array(text, name): + m = re.search(r"\b" + re.escape(name) + r"\s*(?:\[[^\]]*\])*\s*=\s*\{", text) + if not m: + raise ValueError("table %s not found in %s" % (name, TABLES.name)) + depth = 0 + for i in range(m.end() - 1, len(text)): + if text[i] == "{": + depth += 1 + elif text[i] == "}": + depth -= 1 + if not depth: + body = text[m.end() - 1:i + 1] + break + else: + raise ValueError("table %s: unbalanced braces" % name) + return ast.literal_eval(body.replace("{", "[").replace("}", "]")) + + +def tables(): + """Rank tables and dictionaries parsed from bcpack_tables_bcn.inl (cached).""" + if not _TABLE_CACHE: + text = re.sub(r"//[^\n]*", "", TABLES.read_text(encoding="utf-8")) + for name in ("RANK_PAIR_BC4", "RANK_PAIR_BC5", "RANK_PAIR_BC3_ALPHA", "RANK_QUAD_BC3_COLOUR", + "BC4_DICTIONARY", "BC5_DICTIONARY", "BC3_DICTIONARY"): + _TABLE_CACHE[name] = _array(text, name) + return _TABLE_CACHE + + +def zigzag(v): + return 2 * v if v >= 0 else -2 * v - 1 + + +def unzigzag(v): + return -((v + 1) >> 1) if v & 1 else v >> 1 + + +def residual(sym, bits): + return unzigzag(sym) & ((1 << bits) - 1) + + +def interleave(even, odd): + out = 0 + for k in range(4): + out |= ((even >> k) & 1) << (2 * k) | ((odd >> k) & 1) << (2 * k + 1) + return out + + +def deinterleave(byte): + even = odd = 0 + for k in range(4): + even |= ((byte >> (2 * k)) & 1) << k + odd |= ((byte >> (2 * k + 1)) & 1) << k + return even, odd + + +def pack_alpha(e0, e1, positions): + v = (e0 ^ 0x80) | (e1 ^ 0x80) << 8 + for p in range(16): + v |= ALPHA_CODE[positions[p] & 7] << (16 + 3 * p) + return v.to_bytes(8, "little") + + +def pack_colour(ep, positions): + c0 = ep[0] << 11 | ep[1] << 5 | ep[2] + c1 = ep[3] << 11 | ep[4] << 5 | ep[5] + w = 0 + for p in range(16): + w |= COLOUR_CODE[positions[p] & 3] << (2 * p) + return c0.to_bytes(2, "little") + c1.to_bytes(2, "little") + w.to_bytes(4, "little") + + +def _source(hist, dictionary, i, r, n_ep, n_ix): + if r == 0: + return [0] * n_ep, [0] * n_ix + if r <= i: + return hist[i - r] + k = r - i - 1 + if k < len(dictionary): + ep, ix = dictionary[k] + return list(ep), list(ix) + return [0] * n_ep, [0] * n_ix + + +def _references(syms, i, per): + if per == 1: + d, x = syms[0][i] & 0xFF, syms[1][i] & 0xFF + else: + d = interleave(syms[0][2 * i], syms[0][2 * i + 1]) + x = interleave(syms[1][2 * i], syms[1][2 * i + 1]) + return (x + unzigzag(d)) & 0xFF, x + + +def blocks_bc4(syms, n): + t = tables() + pairs, dic = t["RANK_PAIR_BC4"], t["BC4_DICTIONARY"] + hist, out = [], bytearray() + for i in range(n): + er, xr = _references(syms, i, 1) + ep_ref, _ = _source(hist, dic, i, er, 2, 16) + _, ix_ref = _source(hist, dic, i, xr, 2, 16) + ep = [(ep_ref[e] + residual(syms[2 + e][i], 8)) & 0xFF for e in range(2)] + ix = [0] * 16 + for k in range(8): + a, b = pairs[syms[4 + k][i] & 63] + ix[2 * k] = (ix_ref[2 * k] + a) & 7 + ix[2 * k + 1] = (ix_ref[2 * k + 1] + b) & 7 + hist.append((ep, ix)) + out += pack_alpha(ep[0], ep[1], ix) + return bytes(out) + + +def blocks_bc5(syms, n): + t = tables() + pairs, dic = t["RANK_PAIR_BC5"], t["BC5_DICTIONARY"] + hist, out = [], bytearray() + for i in range(n): + er, xr = _references(syms, i, 2) + ep_ref, _ = _source(hist, dic, i, er, 4, 32) + _, ix_ref = _source(hist, dic, i, xr, 4, 32) + ep, ix = [0] * 4, [0] * 32 + for c in range(2): + for e in range(2): + ep[2 * c + e] = (ep_ref[2 * c + e] + residual(syms[2 + c][2 * i + e], 8)) & 0xFF + for l in range(4): + for h in range(2): + a, b = pairs[syms[4 + 4 * c + l][2 * i + h] & 63] + p = 16 * c + 4 * l + 2 * h + ix[p] = (ix_ref[p] + a) & 7 + ix[p + 1] = (ix_ref[p + 1] + b) & 7 + hist.append((ep, ix)) + out += pack_alpha(ep[0], ep[1], ix[:16]) + pack_alpha(ep[2], ep[3], ix[16:]) + return bytes(out) + + +QUAD_ORIGIN = ((0, 0), (2, 0), (0, 2), (2, 2)) # TL, TR, BL, BR +QUAD_STEP = ((0, 0), (1, 0), (0, 1), (1, 1)) + + +def blocks_bc3(syms, n): + t = tables() + pairs, quads, dic = t["RANK_PAIR_BC3_ALPHA"], t["RANK_QUAD_BC3_COLOUR"], t["BC3_DICTIONARY"] + widths = (5, 6, 5) + hist, out = [], bytearray() + for i in range(n): + er, xr = _references(syms, i, 2) + ep_ref, _ = _source(hist, dic, i, er, 8, 32) + _, ix_ref = _source(hist, dic, i, xr, 8, 32) + ep, ix = [0] * 8, [0] * 32 + for e in range(2): + ep[e] = (ep_ref[e] + residual(syms[2][2 * i + e], 8)) & 0xFF + for l in range(4): + for h in range(2): + a, b = pairs[syms[3 + l][2 * i + h] & 63] + p = 4 * l + 2 * h + ix[p] = (ix_ref[p] + a) & 7 + ix[p + 1] = (ix_ref[p + 1] + b) & 7 + for c in range(3): + mask = (1 << widths[c]) - 1 + ep[2 + c] = (ep_ref[2 + c] + residual(syms[7 + c][2 * i], widths[c])) & mask + ep[5 + c] = (ep_ref[5 + c] + residual(syms[7 + c][2 * i + 1], widths[c])) & mask + for q in range(4): + sym = syms[10 + (q >> 1)][2 * i + (q & 1)] & 0xFF + ox, oy = QUAD_ORIGIN[q] + for k in range(4): + dx, dy = QUAD_STEP[k] + p = 16 + 4 * (oy + dy) + ox + dx + ix[p] = (ix_ref[p] + quads[sym][k]) & 3 + hist.append((ep, ix)) + out += pack_alpha(ep[0], ep[1], ix[:16]) + pack_colour(ep[2:8], ix[16:]) + return bytes(out) + + +RECONSTRUCT = {3: blocks_bc3, 4: blocks_bc4, 5: blocks_bc5} + + +def lane_symbols(data, fmt, output_size): + """Entropy-decode one interval into per-lane symbols for `output_size` bytes of blocks.""" + ab, block, per = LAYOUTS[fmt] + if output_size <= 0 or output_size % block: + raise ValueError("output size is not a whole number of %d-byte blocks" % block) + n = output_size // block + result = decode_lanes(data, list(ab), [n * per] * len(ab)) + if any(data[result["consumed"]:]): + raise BCPackError("non-zero trailing data after byte %d" % result["consumed"]) + return result["syms"], n + + +def decode(data, fmt, output_size): + """Decode a BCPack BC3/BC4/BC5 stream into `output_size` bytes of BCn blocks.""" + if fmt not in RECONSTRUCT: + raise ValueError("BCPack format %d has no block reconstruction here" % fmt) + syms, n = lane_symbols(data, fmt, output_size) + return RECONSTRUCT[fmt](syms, n) diff --git a/tools/disasm_rdna2.py b/tools/disasm_rdna2.py index 131cb807fe..d1a00b33c4 100644 --- a/tools/disasm_rdna2.py +++ b/tools/disasm_rdna2.py @@ -1687,6 +1687,49 @@ def _decode_vop2_dpp(w1: int, vdst: int, vsrc1: int, src0: int, op: int, op_name return (8, dpp_name, asm, comment) +def _decode_vopc_dpp(w1: int, vsrc1: int, src0: int, op_name: str, comment: str) -> tuple[int, str, str, str]: + """Decode a GFX10 VOPC DPP8 (src0=233/234) or DPP16 (src0=250) 8-byte instruction. + + The second dword has the VOP2 DPP layout (src0 VGPR [7:0], DPP16 control [16:8], fi 18, bound_ctrl 19, src0 + neg/abs 20/21, src1 neg/abs 22/23, bank_mask [27:24], row_mask [31:28]; DPP8 lane selects [31:8]); the result + goes to VCC (v_cmp) or EXEC (v_cmpx), as in the e32 form. LLVM 15 does not decode VOPC DPP for GFX10 (LLVM has + VOPC DPP from GFX11 on, printed `v_cmp__dpp vcc_lo, ...`, the spelling used here). Evidence for GFX10: + compiled pixel programs carry VOPC words with src0 250 followed by a dword of this layout (fi and bound_ctrl + set, row/bank masks 0xf, a quad_perm control) and read VCC afterwards. 64-bit compares are refused, as are + float modifiers on integer compares and src1 modifiers on v_cmp_class.""" + is_dpp8 = src0 in (233, 234) + form = "DPP8" if is_dpp8 else "DPP16" + kind = "vopc_dpp8" if is_dpp8 else "vopc_dpp16" + if op_name.startswith("v_vopc_") or op_name.endswith(("_f64_e32", "_i64_e32", "_u64_e32")): + return (8, kind, f"{op_name} ", f"VOPC {form} is not supported for this opcode") + base = op_name[:-4] if op_name.endswith("_e32") else op_name + dpp_name = f"{base}_dpp" + is_float = base.endswith(("_f32", "_f16")) and "_class_" not in base + src0_vgpr = w1 & 0xff + if is_dpp8: + ctrl = _format_dpp8_ctrl(w1, 1 if src0 == 234 else 0) + src0_str, src1_str = f"v{src0_vgpr}", f"v{vsrc1}" + else: + dpp_ctrl_str = _format_dpp16_ctrl((w1 >> 8) & 0x1ff) + if dpp_ctrl_str is None: + return (8, kind, f"{op_name} ", "Invalid GFX10 DPP16 control") + fi, bound_ctrl = (w1 >> 18) & 1, (w1 >> 19) & 1 + src0_neg, src0_abs, src1_neg, src1_abs = ((w1 >> b) & 1 for b in (20, 21, 22, 23)) + if not is_float and (src0_neg or src0_abs or src1_neg or src1_abs): + return (8, kind, f"{op_name} ", "Invalid VOPC DPP16 modifier") + if "_class_" in base and (src1_neg or src1_abs): + return (8, kind, f"{op_name} ", "Invalid VOPC DPP16 modifier") + src0_str = _format_operand_modifiers(f"v{src0_vgpr}", src0_abs, src0_neg) + src1_str = _format_operand_modifiers(f"v{vsrc1}", src1_abs, src1_neg) + ctrl = (f"{dpp_ctrl_str} row_mask:0x{(w1 >> 28) & 0xf:x} bank_mask:0x{(w1 >> 24) & 0xf:x}" + f"{' bound_ctrl:1' if bound_ctrl else ''}{' fi:1' if fi else ''}") + if base.startswith("v_cmpx_"): + asm = f"{dpp_name} {src0_str}, {src1_str} {ctrl}" + else: + asm = f"{dpp_name} vcc_lo, {src0_str}, {src1_str} {ctrl}" + return (8, dpp_name, asm, comment) + + def _vop_extension(data: bytes, offset: int, encoding: str, op_name: str, src0: int) -> tuple[int, str, str, str]: """Consume a DPP8, DPP16 or SDWA instruction as one 8-byte record; its operands are not decoded.""" form = VOP_EXTENSION_FORMS[src0] @@ -2556,8 +2599,6 @@ def sopc_operand(reg_id: int, wide: bool) -> str: op_name, comment = op_info length = 4 literal = None - if src0 in (233, 234, 250): - return _vop_extension(data, offset, "vopc", op_name, src0) if src0 in (249, 255): extension = "SDWA" if src0 == 249 else "literal" if offset + 8 > len(data): @@ -2567,6 +2608,11 @@ def sopc_operand(reg_id: int, wide: bool) -> str: return _decode_vopc_sdwa(w1, vsrc1, op_name, comment) literal, = struct.unpack_from(" len(data): + return (4, "vopc_truncated", f"{op_name} ", "Incomplete VOPC DPP") + w1, = struct.unpack_from(" +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +static ID3D12InfoQueue* g_info = nullptr; + +static void dump_messages() { + if (!g_info) return; + UINT64 n = g_info->GetNumStoredMessages(); + for (UINT64 i = 0; i < n && i < 64; ++i) { + SIZE_T size = 0; + g_info->GetMessage(i, nullptr, &size); + std::vector buf(size); + auto* m = reinterpret_cast(buf.data()); + g_info->GetMessage(i, m, &size); + std::printf("debug-layer: severity %d id %d: %.*s\n", (int)m->Severity, (int)m->ID, (int)m->DescriptionByteLength, + m->pDescription); + } + std::printf("debug-layer messages: %llu\n", (unsigned long long)n); +} + +#define CHECK(x) \ + do { \ + HRESULT hr_ = (x); \ + if (FAILED(hr_)) { \ + std::fprintf(stderr, "%s failed: 0x%08lx (line %d)\n", #x, hr_, __LINE__); \ + dump_messages(); \ + return 1; \ + } \ + } while (0) + +template struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T** operator&() { return &p; } + T* operator->() const { return p; } + operator T*() const { return p; } +}; + +static std::vector read_file(const std::string& path) { + std::ifstream f(path, std::ios::binary); + return std::vector((std::istreambuf_iterator(f)), std::istreambuf_iterator()); +} + +static D3D12_RESOURCE_DESC buffer_desc(UINT64 size, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = size < 16 ? 16 : (size + 15) & ~15ull; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + return d; +} + +static D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3D12_RESOURCE_STATES b) { + D3D12_RESOURCE_BARRIER x{}; + x.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + x.Transition.pResource = r; + x.Transition.StateBefore = a; + x.Transition.StateAfter = b; + x.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + return x; +} + +typedef LONG(WINAPI* RtlGetVersionFn)(OSVERSIONINFOW*); + +struct View { UINT slot = 0; bool uav = false; UINT res = 0; UINT64 offset = 0, bytes = 0; }; +struct HView { UINT id = 0, kind = 4, res = 0; UINT64 offset = 0, bytes = 0; }; + +int main(int argc, char** argv) { + if (argc < 2) { + std::fprintf(stderr, "usage: compute_harness [--debug] | --caps\n"); + return 2; + } + std::setvbuf(stdout, nullptr, _IONBF, 0); // a crash must not lose the progress lines + const bool caps_only = std::string(argv[1]) == "--caps"; + bool debug = false; + for (int i = 2; i < argc; ++i) debug |= std::string(argv[i]) == "--debug"; + std::string cs_path, out; + UINT groups[3] = {1, 1, 1}, nres = 0; + std::vector consts; + std::map res_files; + std::vector views; + std::vector hviews; + std::string heapmem_path, vinfo_path; + if (!caps_only) { + std::ifstream cfg(argv[1]); + if (!cfg) { std::fprintf(stderr, "cfg: cannot read %s\n", argv[1]); return 2; } + std::string line; + while (std::getline(cfg, line)) { + std::istringstream s(line); + std::string key; + s >> key; + if (key == "cs") std::getline(s >> std::ws, cs_path); + else if (key == "groups") s >> groups[0] >> groups[1] >> groups[2]; + else if (key == "consts") { UINT n = 0; s >> n; consts.resize(n); for (auto& c : consts) s >> c; } + else if (key == "nres") s >> nres; + else if (key == "res") { UINT k; std::string p; s >> k; std::getline(s >> std::ws, p); res_files[k] = p; } + else if (key == "view") { View v; std::string t; s >> v.slot >> t >> v.res >> v.offset >> v.bytes; v.uav = t == "uav"; views.push_back(v); } + else if (key == "heap") s >> heapmem_path >> vinfo_path; + else if (key == "hview") { HView v; s >> v.id >> v.kind >> v.res >> v.offset >> v.bytes; hviews.push_back(v); } + else if (key == "out") std::getline(s >> std::ws, out); + else if (!key.empty() && key[0] != '#') { std::fprintf(stderr, "cfg: unknown line '%s'\n", line.c_str()); return 2; } + } + if (cs_path.empty() || out.empty()) { std::fprintf(stderr, "cfg: needs cs and out\n"); return 2; } + for (const auto& v : views) + if (v.slot >= nres || !res_files.count(v.res) || (v.offset & 15)) { std::fprintf(stderr, "cfg: bad view slot %u\n", v.slot); return 2; } + for (const auto& v : hviews) + if (v.id >= 90000 || (v.kind != 4 && v.kind != 7) || !res_files.count(v.res) || (v.offset & 15)) { + std::fprintf(stderr, "cfg: bad hview %u\n", v.id); + return 2; + } + if (consts.empty()) consts.push_back(0); + } + const bool heap = !heapmem_path.empty(); + + OSVERSIONINFOW os{sizeof(os)}; + if (auto fn = (RtlGetVersionFn)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion")) fn(&os); + std::printf("windows %lu.%lu.%lu\n", os.dwMajorVersion, os.dwMinorVersion, os.dwBuildNumber); + if (debug) { + Ref dbg; + if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&dbg)))) dbg->EnableDebugLayer(); + } + std::printf("debug layer: %s\n", debug ? "on" : "off"); + Ref factory; + CHECK(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory))); + Ref adapter; + CHECK(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))); // WARP ONLY + DXGI_ADAPTER_DESC1 ad{}; + adapter->GetDesc1(&ad); + if (!(ad.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { std::fprintf(stderr, "not a software adapter: refusing\n"); return 1; } + LARGE_INTEGER umd{}; + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &umd); + std::printf("adapter: %ls (vendor %04x device %04x) driver %u.%u.%u.%u\n", ad.Description, ad.VendorId, ad.DeviceId, + HIWORD(umd.HighPart), LOWORD(umd.HighPart), HIWORD(umd.LowPart), LOWORD(umd.LowPart)); + Ref device; + CHECK(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device))); + if (debug && SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&g_info)))) g_info->SetMuteDebugOutput(FALSE); + D3D12_FEATURE_DATA_D3D12_OPTIONS1 o1{}; + device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &o1, sizeof(o1)); + D3D12_FEATURE_DATA_D3D12_OPTIONS opt{}; + device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &opt, sizeof(opt)); + D3D12_FEATURE_DATA_SHADER_MODEL sm{D3D_SHADER_MODEL_6_7}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &sm, sizeof(sm)))) { + sm.HighestShaderModel = D3D_SHADER_MODEL_6_6; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &sm, sizeof(sm)))) sm.HighestShaderModel = D3D_SHADER_MODEL_5_1; + } + std::printf("caps: wave ops %d lanes %u-%u, shader model 0x%x, resource binding tier %d\n", (int)o1.WaveOps, + o1.WaveLaneCountMin, o1.WaveLaneCountMax, (unsigned)sm.HighestShaderModel, (int)opt.ResourceBindingTier); + if (caps_only) return 0; + if (heap && sm.HighestShaderModel < D3D_SHADER_MODEL_6_6) { std::printf("capability skip: no SM 6.6\n"); return 77; } + + // root signature (d3d12_compute.inl load_compute layout, bounded space1 views: see the header) + const UINT n = nres; + D3D12_DESCRIPTOR_RANGE1 ranges[2] = {}; + ranges[0] = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, n, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, 0}; + ranges[1] = {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, n, 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, n}; + D3D12_DESCRIPTOR_RANGE1 space1{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 2, 0, 1, D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, 0}; + std::vector params; + D3D12_ROOT_PARAMETER1 p{}; + p.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + p.Constants.Num32BitValues = (UINT)consts.size(); + params.push_back(p); + UINT space1_param = 0, table_param = 0; + if (heap) { + D3D12_ROOT_PARAMETER1 q{}; + q.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + q.DescriptorTable = {1, &space1}; + space1_param = (UINT)params.size(); + params.push_back(q); + } + if (n) { + D3D12_ROOT_PARAMETER1 q{}; + q.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + q.DescriptorTable = {2, ranges}; + table_param = (UINT)params.size(); + params.push_back(q); + } + D3D12_VERSIONED_ROOT_SIGNATURE_DESC rsd{}; + rsd.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + rsd.Desc_1_1 = {(UINT)params.size(), params.data(), 0, nullptr, + heap ? D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED : D3D12_ROOT_SIGNATURE_FLAG_NONE}; + Ref rs_blob, rs_err; + if (FAILED(D3D12SerializeVersionedRootSignature(&rsd, &rs_blob, &rs_err))) { + std::fprintf(stderr, "root signature: %s\n", rs_err ? (const char*)rs_err->GetBufferPointer() : "?"); + return 1; + } + Ref root; + CHECK(device->CreateRootSignature(0, rs_blob->GetBufferPointer(), rs_blob->GetBufferSize(), IID_PPV_ARGS(&root))); + auto cs = read_file(cs_path); + if (cs.empty()) { std::fprintf(stderr, "missing %s\n", cs_path.c_str()); return 2; } + D3D12_COMPUTE_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root; + pd.CS = {cs.data(), cs.size()}; + Ref pso; + HRESULT pso_hr = device->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pso)); + std::printf("pipeline: 0x%08lx\n", (unsigned long)pso_hr); + if (FAILED(pso_hr)) { dump_messages(); return 1; } + + // resources + D3D12_HEAP_PROPERTIES up{D3D12_HEAP_TYPE_UPLOAD}, def{D3D12_HEAP_TYPE_DEFAULT}, rb{D3D12_HEAP_TYPE_READBACK}; + std::map> res, staging, back; + std::map res_size; + auto upload = [&](const std::vector& data, UINT64 at_least, Ref& r) -> HRESULT { + auto d = buffer_desc(data.size() > at_least ? data.size() : at_least); + HRESULT hr = device->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&r)); + if (FAILED(hr)) return hr; + void* m = nullptr; + if (FAILED(hr = r->Map(0, nullptr, &m))) return hr; + std::memset(m, 0, (size_t)d.Width); + if (!data.empty()) std::memcpy(m, data.data(), data.size()); + r->Unmap(0, nullptr); + return S_OK; + }; + for (const auto& kv : res_files) { + auto data = read_file(kv.second); + if (data.empty()) { std::fprintf(stderr, "missing or empty %s\n", kv.second.c_str()); return 2; } + auto d = buffer_desc(data.size(), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + res_size[kv.first] = d.Width; + CHECK(device->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&res[kv.first]))); + CHECK(upload(data, d.Width, staging[kv.first])); + auto r = buffer_desc(d.Width); + CHECK(device->CreateCommittedResource(&rb, D3D12_HEAP_FLAG_NONE, &r, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&back[kv.first]))); + } + Ref heapmem_res, vinfo_res; + std::vector heapmem_data, vinfo_data; + if (heap) { + heapmem_data = read_file(heapmem_path); + vinfo_data = read_file(vinfo_path); + CHECK(upload(heapmem_data, 16, heapmem_res)); + CHECK(upload(vinfo_data, 16, vinfo_res)); + } + + // one shader-visible heap: [0, 2n) the table, [2n, 2n + 2) space1, the view-id region from 262144 + const UINT region = 262144, heap_size = heap ? region + 8 + 8 * 90000 : (2 * n ? 2 * n : 1); + Ref dheap; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, heap_size, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + CHECK(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&dheap))); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + auto at = [&](UINT i) { D3D12_CPU_DESCRIPTOR_HANDLE h = dheap->GetCPUDescriptorHandleForHeapStart(); h.ptr += SIZE_T{i} * step; return h; }; + auto srv_view = [&](ID3D12Resource* r, UINT64 offset, UINT64 bytes, D3D12_CPU_DESCRIPTOR_HANDLE h) { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Buffer.FirstElement = offset / 4; + v.Buffer.NumElements = (UINT)((bytes + 3) / 4); + v.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(v.Buffer.NumElements ? r : nullptr, &v, h); + }; + auto uav_view = [&](ID3D12Resource* r, UINT64 offset, UINT64 bytes, D3D12_CPU_DESCRIPTOR_HANDLE h) { + D3D12_UNORDERED_ACCESS_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + v.Buffer.FirstElement = offset / 4; + v.Buffer.NumElements = (UINT)((bytes + 3) / 4); + v.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(v.Buffer.NumElements ? r : nullptr, nullptr, &v, h); + }; + for (UINT i = 0; i < n; ++i) { + srv_view(nullptr, 0, 0, at(i)); + uav_view(nullptr, 0, 0, at(n + i)); + } + for (const auto& v : views) { + if (v.offset + v.bytes > res_size[v.res]) { std::fprintf(stderr, "view %u past its resource\n", v.slot); return 2; } + if (v.uav) uav_view(res[v.res], v.offset, v.bytes, at(n + v.slot)); + else srv_view(res[v.res], v.offset, v.bytes, at(v.slot)); + } + if (heap) { + srv_view(heapmem_res, 0, heapmem_data.size(), at(2 * n)); + srv_view(vinfo_res, 0, vinfo_data.size(), at(2 * n + 1)); + // empty views (kinds 4 and 7 only: the harness builds buffer heaps) and the listed ids' views + for (UINT k = 0; k < 8; ++k) srv_view(nullptr, 0, 0, at(region + k)); + uav_view(nullptr, 0, 0, at(region + 7)); + // every id's buffer slots start null: the translation indexes the heap with whatever id heapmem holds (any + // id < 90000), and an unwritten descriptor is undefined (WARP crashed with an access violation on one) + for (UINT id = 0; id < 90000; ++id) { + srv_view(nullptr, 0, 0, at(region + 8 + 8 * id + 4)); + uav_view(nullptr, 0, 0, at(region + 8 + 8 * id + 7)); + } + for (const auto& v : hviews) { + if (v.offset + v.bytes > res_size[v.res]) { std::fprintf(stderr, "hview %u past its resource\n", v.id); return 2; } + if (v.kind == 7) uav_view(res[v.res], v.offset, v.bytes, at(region + 8 + 8 * v.id + 7)); + else srv_view(res[v.res], v.offset, v.bytes, at(region + 8 + 8 * v.id + 4)); + } + } + std::printf("bound: %u table slots (%zu views), %zu resources, heap %s (%zu views)\n", n, views.size(), res.size(), + heap ? "yes" : "no", hviews.size()); + + D3D12_COMMAND_QUEUE_DESC qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + Ref queue; + CHECK(device->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&queue))); + Ref alloc; + CHECK(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc))); + Ref list; + CHECK(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc, nullptr, IID_PPV_ARGS(&list))); + for (auto& kv : res) { + list->CopyBufferRegion(kv.second, 0, staging[kv.first], 0, res_size[kv.first]); + auto b = transition(kv.second, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->ResourceBarrier(1, &b); + } + ID3D12DescriptorHeap* heaps[] = {dheap}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(root); + list->SetPipelineState(pso); + list->SetComputeRoot32BitConstants(0, (UINT)consts.size(), consts.data(), 0); + if (heap) { + D3D12_GPU_DESCRIPTOR_HANDLE g = dheap->GetGPUDescriptorHandleForHeapStart(); + g.ptr += UINT64{2 * n} * step; + list->SetComputeRootDescriptorTable(space1_param, g); + } + if (n) list->SetComputeRootDescriptorTable(table_param, dheap->GetGPUDescriptorHandleForHeapStart()); + list->Dispatch(groups[0], groups[1], groups[2]); + D3D12_RESOURCE_BARRIER ub{}; + ub.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &ub); + for (auto& kv : res) { + auto b = transition(kv.second, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &b); + list->CopyBufferRegion(back[kv.first], 0, kv.second, 0, res_size[kv.first]); + } + CHECK(list->Close()); + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + Ref fence; + CHECK(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); + CHECK(queue->Signal(fence, 1)); + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + CHECK(fence->SetEventOnCompletion(1, ev)); + const DWORD t0 = GetTickCount(); + const DWORD waited = WaitForSingleObject(ev, 60000); + std::printf("gpu wait: %s after %lu ms, fence %llu\n", waited == WAIT_OBJECT_0 ? "done" : "TIMEOUT", + (unsigned long)(GetTickCount() - t0), (unsigned long long)fence->GetCompletedValue()); + std::fflush(stdout); + if (waited != WAIT_OBJECT_0) { + std::fprintf(stderr, "the GPU did not finish within 60 s (fatal)\n"); + ExitProcess(3); + } + CHECK(device->GetDeviceRemovedReason()); + for (auto& kv : back) { + void* m = nullptr; + D3D12_RANGE r{0, (SIZE_T)res_size[kv.first]}; + CHECK(kv.second->Map(0, &r, &m)); + std::ofstream f(out + ".res" + std::to_string(kv.first), std::ios::binary); + f.write((const char*)m, (std::streamsize)res_size[kv.first]); + kv.second->Unmap(0, nullptr); + } + dump_messages(); + std::printf("ok\n"); + return 0; +} diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 5bc7afa6e9..b6b94c8b2f 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -181,6 +181,9 @@ def log(text): k32.AssignProcessToJobObject(wt.HANDLE(job), wt.HANDLE(pi.hProcess)) k32.DebugSetProcessKillOnExit(True) k32.ResumeThread(wt.HANDLE(pi.hThread)) + if env.get("X2W_PRESENT_IN_TITLE_WINDOW") == "1": + import window_status + window_status.start(pi.dwProcessId, trap_log) if opts.get("--console", "1") == "1": # Live debug console in its own window: follows this run's logs (live_view.py). import subprocess diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ea79572647..76d1a835d9 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -25,6 +25,14 @@ class Unsupported(Exception): pass +class StoredSrv(Unsupported): + """A descriptor first read as an SRV and later stored to; translate_to retries with it in rw_keys.""" + + def __init__(self, key, message): + super().__init__(message) + self.key = key + + PREFETCH = bytes.fromhex('0300a0bf') # DPP16 quad pair broadcasts (quad_perm of one lane of every horizontal or vertical pair into the other). The lanes of @@ -388,6 +396,14 @@ def stream_interface(vs_container, ps_container): INTERP_DST_HIGH = 'op_sel:[0,0,0,1]' +LDS_UNUSED_W1_MASK = { + 'ds_write2_b32': 0xff000000, 'ds_write2st64_b32': 0xff000000, 'ds_read2st64_b32': 0x00ffff00, + **dict.fromkeys(('ds_add_u32', 'ds_min_u32', 'ds_max_u32', 'ds_and_b32', 'ds_or_b32'), 0xffff0000), + **dict.fromkeys(('ds_add_rtn_u32', 'ds_min_rtn_u32', 'ds_max_rtn_u32', 'ds_and_rtn_b32', + 'ds_or_rtn_b32', 'ds_wrxchg_rtn_b32'), 0x00ff0000), +} + + def check_encoding(code, off, n, name, asm): # These SOP1 forms have an unused field that the disassembler does not print. # Only the ordinary four-byte encodings (no literal or hidden operand) are used @@ -397,18 +413,6 @@ def check_encoding(code, off, n, name, asm): unused = word & (0xff if name == 's_getpc_b64' else 0x7f0000) if n != 4 or unused: raise Unsupported('s_setpc_b64: unsupported %s encoding at +0x%x' % (name, off)) - if name in ('v_interp_p1ll_f16', 'v_interp_p2_f16'): - # The shared disassembler ignores op_sel (w0[14:11]) here, as LLVM 15 does (its VOP3Interp_gfx10 encoding - # leaves bits 14:11 undefined). Only Mesa ACO states a meaning: v_interp_p2_hi_f16 is p2 with op_sel 0x8 (bit - # 14, aco_assembler.cpp), which writes the high half of the destination; register allocation turns p2 into it - # for a 16-bit value at byte 2 of a register that holds another 16-bit value. It is passed on as the printed - # LLVM modifier `op_sel:[0,0,0,1]`. The attribute half `high` is a different bit (w1[8]) and is printed. - sel = struct.unpack_from('> 11 & 15 - if sel == 8 and name == 'v_interp_p2_f16': - return asm + ' ' + INTERP_DST_HIGH - if sel: - raise Unsupported('%s with op_sel 0x%x: only the plain form and, on v_interp_p2_f16, op_sel 0x8 ' - '(destination high half) are lowered' % (name, sel)) if name == 'image_load_mip': # The shared disassembler does not expose these gfx10 MIMG flags. word0, word1 = struct.unpack_from('<2I', code, off) @@ -823,6 +827,66 @@ def smem_offset(tok): return '0' if tok == 'off' else tok +SGPR_NAMES = {'vcc_lo': (106,), 'vcc_hi': (107,), 'vcc': (106, 107), 'm0': (124,)} +# SALU forms whose first operand is written and not read (D = f(S0, S1)); others that name D first also read it +# (s_addk_i32, s_mulk_i32, s_cmovk_i32, s_cmov_*, s_bitset*, s_movrel*) or do not write it (compares, stores). +SALU_NO_DST = ('s_cmp', 's_bitcmp', 's_cbranch', 's_branch', 's_store', 's_buffer_store', 's_atomic', 's_buffer_atomic', + 's_scratch_store', 's_waitcnt', 's_nop', 's_setpc', 's_setreg', 's_sendmsg', 's_endpgm', 's_clause', + 's_inst_prefetch', 's_dcache', 's_barrier', 's_sleep', 's_set', 's_ttrace', 's_icache', 's_denorm', + 's_round', 's_trap', 's_decperflevel', 's_incperflevel', 's_code_end') +SALU_READS_DST = ('s_addk', 's_mulk', 's_cmovk', 's_cmov_', 's_bitset', 's_movrel', 's_getreg') + + +def sgpr_access(name, asm): + """(SGPRs read, SGPRs written) by one instruction, vcc and m0 included, exec and SCC left out. + + Conservative where the form is not listed: a register operand that is not known to be written only counts as + read, so a caller that refuses on a read never misses one.""" + def regs(tok): + r = reg_range(tok) + if r: + return set(range(r[1], r[2] + 1)) if r[0] == 's' else set() + return set(SGPR_NAMES.get(tok, ())) + _, ops, _ = parse(asm) + reads, writes = set(), set() + for t in ops: + reads |= regs(t) + first = regs(ops[0]) if ops else set() + base = re.sub(r'_(e32|e64|sdwa|dpp)$', '', name) + if name.startswith('s_'): + if not name.startswith(SALU_NO_DST) and not name.startswith(SALU_READS_DST): + writes, reads = first, reads - first if ops[1:] and not any(regs(t) & first for t in ops[1:]) else reads + elif (base in ('v_readfirstlane_b32', 'v_readlane_b32') or + (base.startswith('v_cmp_') and name.endswith(('_e64', '_sdwa')))) and first: + writes = first + reads = set().union(*(regs(t) for t in ops[1:])) if ops[1:] else set() + if name.startswith('v_cmp_') and name.endswith('_e32'): + writes |= {106} + if name.startswith('v_') and name.endswith('_e32') and re.search(r'cndmask|addc|subb|_co_|div_fmas', name): + reads |= {106, 107} + if name.startswith('s_cbranch_vcc'): + reads |= {106, 107} + return reads, writes + + +def sopk_simm(tok): + """A SOPK SIMM16 operand sign-extended to 32 bits, as a hex token (upstream #2116, open). Refuses anything that + is not a 16-bit literal.""" + if not re.fullmatch(r'0x[0-9a-f]{1,4}|\d+', tok) or int(tok, 0) > 0xffff: + raise Unsupported('SOPK immediate %s' % tok) + value = int(tok, 0) + return '0x%08x' % ((value - 0x10000 if value & 0x8000 else value) & 0xffffffff) + + +def smem_imm_refuse(base, ops, mods): + """Refuse a negative SMEM immediate offset (upstream #1984 / ed7d09a4). OFFSET[20:0] is signed on RDNA 2: + disasm_rdna2 prints a negative one as -0x.., an older decoder as 0x100000..0x1fffff; either would otherwise + be added as a positive byte offset.""" + toks = [ops[2]] if len(ops) > 2 else [] + toks += [m[7:] for m in mods if m.startswith('offset:')] + for tok in toks: + if re.fullmatch(r'-?(0[xX][0-9a-fA-F]+|\d+)', tok) and not 0 <= int(tok, 0) <= 0xfffff: + raise Unsupported('%s: SMEM immediate offset %s' % (base, tok)) def smem_mods(mods): """Non-negative 21-bit signed immediate byte offset from SMEM modifiers, refusing unknown or negative forms.""" imm = None @@ -1619,6 +1683,9 @@ def lands(key, index, what): class Stage: """Translates one stage. Shares the resource and entry-constant registries of its pipeline.""" + uses_q = False + uses_swap = False + uses_xsave = False # Immutable fallbacks for unit probes that bypass __init__; __init__ and translate() assign fresh # per-instance sets, so nothing is shared across Stage instances. @@ -1641,51 +1708,42 @@ class Stage: def __init__(self, pipe, kind, code, refusals=None, decoded=None): self.pipe, self.kind = pipe, kind + self.raw = strip_header(code) # instruction words, for encoding bits the decoder does not print self.refusals = refusals self.raw_code = strip_header(code) if refusals is None: - self.ins = decode(self.raw_code) + self.ins = decode(self.raw) else: - self.ins = decode(self.raw_code, refusals) if decoded is None else decoded - if kind == 'ms': - self.mesh_vcc_branches = {} - self.ins = mesh_skeleton(self.ins, self.mesh_vcc_branches) - # A loop header is translated before the back edges into it, so whether a back edge brings the symbol kept - # there is known only afterwards: translate again with that register read at run time or refused there. A - # register only moves from kept to 'run' to 'refuse', so this ends. - self.force_joined = {} # branch target -> register -> 'run' | 'refuse' - first_refusal = len(refusals) if refusals is not None else 0 - while True: - self.lines = [] # body statements (per block) - self.sym = {} # scalar register -> symbolic value - self.used_s, self.used_v = set(), set() - self.used_atomic = set() - self.exec_known = True # exec still equals the entry mask (the lane is active) - self.wqm_exec = False # exec is proven whole-quad: an s_wqm of exec into itself ran while exec_known - self.exports = {} # 'pos0' / 'paramN' / 'mrtN' -> [4 expressions] - self.write_masks = {} # 'mrtN' -> channels the export writes (bit c = channel c), see export() - self.attrs = {} # pixel: attr index -> 'linear' | 'flat' | 'f16' - self.compr_params = set() # vertex: param indices exported with the compr flag (packed binary16 pairs) - self.plain_params = {} # vertex: param index -> channels exported as `off` by its latest plain export - self.f16_plain = {} # pixel: attr index -> channels read as binary16 halves of a plain export - self.uses_pos = False - self.masks = set() # scalar registers currently holding lane masks - self.fetched = False # vertex: the entry call into the fetch routine was translated as loads - self.defined_uniform_s = set() - self.bad_sgprs = set() - self._uniform_written = set() - self.setup_entry() - self.translate() - grown = False - for t, regs in self.back_force.items(): - have = self.force_joined.setdefault(t, {}) - for reg, kind in regs.items(): - if have.get(reg) not in (kind, 'refuse'): - have[reg], grown = kind, True - if not grown: - break - if refusals is not None: - del refusals[first_refusal:] + self.ins = decode(self.raw, refusals) if decoded is None else decoded + if kind == 'ms' and getattr(pipe, 'uses_mesh_skeleton', False): + self.ins = mesh_skeleton(self.ins) + self.lines = [] # body statements (per block) + self.sym = {} # scalar register -> symbolic value + self.used_s, self.used_v = set(), set() + self.exec_known = True # exec still equals the entry mask (the lane is active) + self.wqm_exec = False # exec is proven whole-quad: an s_wqm of exec into itself ran while exec_known + self.exports = {} # 'pos0' / 'paramN' / 'mrtN' -> [4 expressions] + self.write_masks = {} # 'mrtN' -> channels the export writes (bit c = channel c), see export() + self.attrs = {} # pixel: attr index -> 'linear' | 'flat' | 'half' + self.compr_params = set() # vertex: param indices exported with the compr flag (packed binary16 pairs) + self.plain_params = {} # vertex: param index -> channels exported as `off` by its latest plain export + self.f16_plain = {} # pixel: attr index -> channels read as binary16 halves of a plain export + self.uses_pos = False + self.masks = set() # scalar registers currently holding lane masks + self.splat = set() # scalar registers holding 0 or 0xffffffff, a value every lane's bit agrees on + self.uses_q = False # the uint2 temporary of the 64-bit operations + self.used_h = set() # heap descriptor offsets h this stage assigns (manifest `heap 1`) + self.written_v = set() # VGPRs assigned so far in program order + self.entry_reads = {} # VGPR read before any write (its entry value) -> offset of the first such read + self.pc = 0 + # MODE.round[3:2], the f16/f64 rounding (see op_s_round_mode). A pixel stage starts it from the launch + # FLOAT_MODE when the request passes it (launch_mode); otherwise 0 (nearest even) at launch is ASSUMED. + self.round16 = 0 + if kind == 'ps': + self.launch_mode(getattr(pipe, 'ps_float_mode', None)) + self.fetched = False # vertex: the entry call into the fetch routine was translated as loads + self.setup_entry() + self.translate() # ---- entry state --------------------------------------------------------------------- def setup_entry(self): @@ -1782,12 +1840,20 @@ def u(self, tok, *, low16_only=False): if m: raise Unsupported('numeric use of m0 holding %s' % m[0]) return 'm0' + if tok == 'src_scc': + # SCC read as a 32-bit operand (0 or 1) + return '(scc ? 1u : 0u)' + if tok in getattr(self, 'dpp_names', ()): + return tok # the quad-read source of a DPP instruction (quad_dpp) r = reg_range(tok) if r: if r[0] == 'v': - for reg in range(r[1], r[2] + 1): - self.used_v.add(reg) - if not low16_only: + written = getattr(self, 'written_v', None) # absent on the tests' bare one-instruction stages + if written is not None and r[1] not in written: + self.entry_reads.setdefault(r[1], self.pc) + self.used_v.add(r[1]) + if not low16_only: + for reg in range(r[1], r[2] + 1): self.note_whole_read(reg) return 'v%d' % r[1] return self.S(r[1]) @@ -1839,6 +1905,27 @@ def f(self, tok): text = 'abs(%s)' % text return '(-%s)' % text if neg else text + def u_mod(self, tok, sign=0x80000000): + """uint expression for an operand with VOP3 neg/abs applied as sign-bit operations (no float rounding).""" + neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) + if neg: + tok = tok[1:] + absolute = tok.startswith('|') and tok.endswith('|') + if absolute: + tok = tok[1:-1] + text = self.u(tok) + if absolute: + text = '(%s & %#xu)' % (text, ~sign & 0xffffffff) + if neg: + text = '(%s ^ %#xu)' % (text, sign) + return text + + def h(self, tok): + """uint expression whose low 16 bits are a binary16 operand: inline float constants take their half form.""" + if tok in FLOATS: + return '0x%04xu' % struct.unpack('= 1 into the target - while todo: - b = todo.pop() - if b not in reach: - reach.add(b) - todo += pred[b] - regs = set() - above_dominators = sorted(b for b in dom[t] - {t} if b < t) - for b in range(len(bounds)): - if b < t and b not in dom[t]: - regs |= writes[b] # above the target but not on every path into it - if b in reach and b >= t: - regs |= writes[b] # a loop body or a later block that comes back - # Writes in dominating blocks hold on every path only if their textual order is their execution order. - non_chain = any(not (a in dom[c]) for a, c in zip(above_dominators, above_dominators[1:])) - if non_chain: - regs |= set().union(*(writes[b] for b in above_dominators)) - joined[target] = regs - if with_cfg: - above_set = dom[t] - {t} - split_blks, stodo = set(), [p for p in pred[t] if p < t and p not in above_set] - while stodo: - b = stodo.pop() - if b not in split_blks: - split_blks.add(b) - stodo += [p for p in pred[b] if p < t and p not in above_set] - fwd = set().union(*(writes[b] for b in split_blks)) if split_blks else set() - if non_chain: - fwd |= set().union(*(writes[b] for b in above_dominators)) - forward_splits[target] = fwd - if not with_cfg: - return joined - pdom = [set(range(len(bounds))) if succ[b] else {b} for b in range(len(bounds))] - changed = True - while changed: - changed = False - for b in range(len(bounds) - 1, -1, -1): - if not succ[b]: - continue - new = {b} | set.intersection(*(pdom[s] for s in succ[b])) - if new != pdom[b]: - pdom[b], changed = new, True - div_targets = {} - for b, (lo, hi) in enumerate(bounds): - off, _n, name, asm = ins[hi - 1] - if not name.startswith('s_cbranch'): - continue - tgt = target_of(off, name, asm) - if tgt is None: + # Symbolic values that are also assigned to their HLSL variable, so a path where the register holds one of them + # and a path where it holds a plain run-time number agree on the variable's value. + RUNTIME_BACKED = ('const', 'fixed_buffer_word', 'execcopy') + + def snapshot(self): + return dict(self.sym), set(self.masks), self.exec_known, set(self.lane_s) + + def merge(self, states): + """The symbolic state at a join of forward edges: what every incoming path agrees on. + + A register whose paths disagree keeps working as a number when every path also assigned it at run time; + otherwise it becomes ('conflict',), which any later use refuses (a descriptor on one path and a loaded + word on the other has no single translation). A mask on any path stays a mask, and exec is the entry + mask only when it is on every path. + """ + sym = {} + self.execzero = {} # conflict registers symbolic only on s_cbranch_execz edges -> exec_writes at the join + for reg in set().union(*(s[0] for s in states)): + values = [s[0].get(reg) for s in states] + if all(v == values[0] for v in values): + sym[reg] = values[0] + elif not all(v is None or v[0] in self.RUNTIME_BACKED for v in values): + # Symbolic only on s_cbranch_execz edges: the run-time variable is right wherever exec is 1, so an + # AND with exec before exec is written again may read it (see scalar); any other use refuses. + symbolic = [s for s, v in zip(states, values) if not (v is None or v[0] in self.RUNTIME_BACKED)] + sym[reg] = ('conflict',) + if all(any(s is e for e in getattr(self, 'execz_snaps', ())) for s in symbolic): + self.execzero[reg] = getattr(self, 'exec_writes', 0) + self.sym = sym + self.masks = set().union(*(s[1] for s in states)) + self.exec_known = all(s[2] for s in states) + self.lane_s = set().union(*(s[3] for s in states)) # lane-dependent on any incoming path + + # Instructions whose SGPR result is a lane mask (bit i = lane i): compares into an SGPR pair, save-exec forms, + # wrexec forms and a copy of exec. + LOOP_MASK_WRITER = re.compile(r'^v_cmpx?_|saveexec|wrexec') + + def loop_writes(self, head, last): + """(SGPRs written, SGPRs written by something other than a lane-mask writer, exec written) over the + instructions at offsets [head, last].""" + written, non_mask, exec_written = set(), set(), False + for off, n, name, asm in self.ins: + if not head <= off <= last: continue - if tgt <= off: - t_blk = block_of[index[tgt]] if tgt in index else b - loop_blks = range(min(t_blk, b), b + 1) - regs = set().union(*(writes[w] for w in loop_blks)) - affected = {off_of[w] for w in loop_blks} & all_targets - else: - stop = pdom[b] - {b} - ipd = max(stop, key=lambda x: len(pdom[x])) if stop else None - div, dtodo = set(), list(succ[b]) - while dtodo: - w = dtodo.pop() - if w == ipd or w in div: - continue - div.add(w) - dtodo += succ[w] - regs = set().union(*(writes[w] for w in div)) if div else set() - affected = ({off_of[w] for w in div} | ({off_of[ipd]} if ipd is not None else set())) & all_targets - div_targets[off] = (regs, affected) - self.flow = (index, block_of, succ, dom, writes, {}) - return joined, forward_splits, div_targets + _, writes = sgpr_access(name, asm) + ops = parse(asm)[1] + first = ops[0] if ops else '' + if writes: + written |= writes + mask = self.LOOP_MASK_WRITER.search(name) or ( + name.startswith('s_mov_b') and len(ops) > 1 and ops[1].startswith('exec')) + if not mask: + non_mask |= writes + if (first.startswith('exec') and name.startswith('s_')) or re.search(r'saveexec|wrexec|^v_cmpx_', name): + exec_written = True + return written, non_mask, exec_written + + def forget_loop_writes(self, head, last): + """At a loop head: drop what the entry state says about registers the loop body writes (see translate).""" + written, non_mask, exec_written = self.loop_writes(head, last) + for reg in written: + value = self.sym.pop(reg, None) + if value is not None and value[0] not in self.RUNTIME_BACKED: + # The entry value lives only in the symbolic state (a descriptor, a pointer): its HLSL variable was + # never assigned, so a first-pass read of the run-time variable would be wrong. As at a forward + # join of a symbolic and a run-time value, any use refuses. + self.sym[reg] = ('conflict',) + self.masks -= non_mask + if exec_written: + self.exec_known = False def unjoined(self, target, last_write, regs): """The registers of regs whose program-order state is not proven at a branch target. A lane-mask mark or a @@ -2321,274 +2451,150 @@ def translate(self): raise refusals.append((str(reason), self.kind)) self.calculated_pc = {} - targets = set() + targets, sources = set(), {} + skipped = [] # compute: (branch, target) of each s_cbranch_execz targets.update(target for target in self.calculated_pc.values() if target is not None) - # (branch, target) of every branch, the proven s_setpc_b64 jumps included - branches = [(pc, target) for pc, target in self.calculated_pc.items() if target is not None] + for at, target in self.calculated_pc.items(): + if target is not None: + sources.setdefault(target, []).append(at) for off, n, name, asm in self.ins: if name.startswith('s_cbranch') or name == 's_branch': target = int(parse(asm)[1][0].split('_')[1], 16) targets.add(target) - branches.append((off, target)) - # Targets that only forward s_cbranch_execz branches (and the fall-through) enter: on a taken edge the lane's - # exec bit is 0 at the target. Compute stages have their own execz handling and are left out. - names = {off: name for off, _n, name, _asm in self.ins} - execz_targets = set() if getattr(self, 'kind', None) == 'cs' else { - t for t in targets if all(pc < t and names[pc] == 's_cbranch_execz' for pc, to in branches if to == t)} - self.mesh_allocation_block = None - splits = set(targets) - if getattr(self, 'kind', None) == 'ms' and targets: - at = next(i for i, item in enumerate(self.ins) if item[2] == 'x2w_mesh_counts') - self.mesh_allocation_block = self.ins[at][0] - # The exchange and its EXEC restore always run. Keep the group barrier and allocation outside - # the pc dispatch even when the preceding region took different paths. - splits.update((self.mesh_allocation_block, self.ins[at + 2][0])) - join_writes = self.join_writes(branches) - refused = self.execz_refusals() if getattr(self, 'kind', None) == 'cs' else {} # probes skip __init__ - joined, forward_splits, div_targets = self.joined_registers(with_cfg=True) - init_sym = dict(self.sym) - init_exec_known = getattr(self, 'exec_known', True) - init_wqm_exec = getattr(self, 'wqm_exec', False) - init_masks = set(getattr(self, 'masks', ())) - init_attrs = dict(getattr(self, 'attrs', {})) - init_used_s = set(getattr(self, 'used_s', ())) - init_used_v = set(getattr(self, 'used_v', ())) - init_entry_uniform = set(getattr(self, 'entry_uniform_s', ())) | { - k for k, v in init_sym.items() - if isinstance(k, int) and v and ( - (v[0] == 'const' and len(v) == 2) or v[0] in ('ud', 'fixed_buffer_word') - ) - } - entry_ud = {reg: sym for reg, sym in init_sym.items() if sym[0] == 'ud'} - forced = getattr(self, 'force_joined', {}) - force_unproven = set() - force_at = {} - first_refusal = len(refusals) if refusals is not None else 0 - every_sgpr = set(range(106)) | {'m0'} - init_entry = [r for r in set(init_sym) | init_used_s if isinstance(r, int)] - init_written = set(range(max(init_entry + [-1 if getattr(self, 'kind', None) == 'cs' else 15]) + 1)) | {'m0'} - - for _ in range(max(4, len(self.ins) + 2)): - scc_effects = {} - uniform_vcc_compares = set() - self.lines = [] - self.blocks = [] # (offset, [lines], terminator) - self.sym = dict(init_sym) - self.exec_known = init_exec_known - self.wqm_exec = init_wqm_exec - self.masks = set(init_masks) - self.join_masks = set() # marked SGPRs whose mark is not proven on every path (unjoined) - last_write = {} # SGPR -> offset of its last write in program order - self.attrs = dict(init_attrs) - self.used_s, self.used_v = set(init_used_s), set(init_used_v) - self.exports = {} - self.write_masks = {} - self.compr_params = set() - self.plain_params = {} - self.f16_plain = {} - self.uses_pos = False - self.fetched = False - self.uniform_v = set() - self.varying_s = set() - self.scc_uniform = True - self.low16_only_v = set() # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load - self.pinned_low16_v = set() # low16_only_v live across basic-block boundaries - self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer - self.float_const_s = {} # SGPR -> 32-bit pattern from s_mov_b32 of an inline float constant - self.has_branches = bool(targets) - self.entry_table_pointers = { - reg: sym[1] for reg, sym in init_sym.items() - if isinstance(reg, int) and sym[0] == 'ptr' and sym[1][0] == 'table' - } - self.descriptor_block_first = 0 - self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it - self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) - self.defined_uniform_s = set(init_entry_uniform) - self.bad_sgprs = set() - bad_at_target = {} - tentative_kept = set() - materialize = {} - incoming = {} - kept = {} - self.back_force = {} - written = set(init_written) - falls = True - start = 0 - raised_unsupported = None - - for instruction_index, (off, n, name, asm) in enumerate(self.ins): - if off in splits and off != start: - self.pinned_low16_v.update(self.low16_only_v) - self.blocks.append((start, self.lines, None)) - self.lines, start = [], off - self.descriptor_block_first = instruction_index - self.pc = off - self.descriptor_instruction_index = instruction_index - self.scc_effect = None - # Before the first branch target or terminator every path has run exactly the instructions above, so - # the program-order tracking is exact there even in a program with branches. Code after s_endpgm in a - # branch-free program is past it too (dead code). - self.past_entry = bool(self.blocks) or 0 in targets - if off in targets: - pre_uniform = { - r for r in (self.defined_uniform_s if self.since_join is None else self.since_join) - if r not in self.varying_s and r not in self.masks - } - kept[off] = {} - here = joined.get(off, set()) - arriving = ([({reg: self.sym.get(reg) for reg in here}, written & here)] if falls else []) + \ - incoming.get(off, []) - written = (written - here) | set().union(*(w for _, w in arriving)) - for reg in here: - paths = [s[reg] for s, w in arriving if reg in w] - force = forced.get(off, {}).get(reg) - if any(reg not in w for _, w in arriving) and any(p and not run_time_symbol(p) for p in paths): - self.sym[reg] = ('joined at a branch target',) - continue - if force is None and paths and names_one_value(paths[0]) and all(p == paths[0] for p in paths): - self.sym[reg] = kept[off][reg] = paths[0] - continue - if force == 'refuse' or any(p and not run_time_symbol(p) for p in paths): - self.sym[reg] = ('joined at a branch target',) - continue - if reg in entry_ud: - materialize[reg] = 'ud%d' % entry_ud[reg][1] - self.sym.pop(reg, None) - if reg != 'm0': - self.used_s.add(reg) - # A joined register the fall-through wrote as a plain run-time number: every other path into - # this target has exec bit 0, so the instruction at the target may AND it with exec (scalar()). A register that still holds a plain - # variable reads the same either way. - self.exec_zero_join = (off, { - reg for reg in here - if falls and off in execz_targets and reg in arriving[0][1] and arriving[0][0][reg] is None}) - clobber = here if off in joined else every_sgpr - self.join_masks |= self.unjoined(off, last_write, self.masks) - fwd_clobber = forward_splits.get(off, clobber) - blocked = force_unproven | force_at.get(off, set()) - kept_u = { - r for r in pre_uniform - if r not in clobber or (r not in fwd_clobber and r not in blocked) - } - tentative_kept.update((kept_u & clobber) - blocked) - self.uniform_v.clear() - self.since_join, self.scc_uniform = kept_u, False - # A constant is only known here if no other path into the join writes the register: a loop counter - # set before the loop and incremented in it reaches the loop head with a new value on every pass. - # set_s also assigns constants at run time, so the register reads its real value once it is dropped. - # clobber also holds the writes of every earlier block off the dominator chain; a constant written - # after those, by a block every path runs, with no later write on any path, is still known. - consts = {reg for reg in join_writes.get(off, set()) | (clobber & every_sgpr) - if (self.sym.get(reg) or ('',))[0] == 'const'} - for reg in self.unjoined(off, last_write, consts): - del self.sym[reg] - fconsts = (join_writes.get(off, set()) | (clobber & every_sgpr)) & set(self.float_const_s) - for reg in self.unjoined(off, last_write, fconsts): - self.float_const_s.pop(reg, None) - self.defined_uniform_s = set(kept_u) | { - k for k, v in self.sym.items() - if isinstance(k, int) and v and ( - (v[0] == 'const' and len(v) == 2) or v[0] in ('ud', 'fixed_buffer_word') - ) - } - if name.startswith('s_cbranch') or name == 's_branch' or ( - name == 's_setpc_b64' and self.calculated_pc.get(off) is not None): - b_target = self.calculated_pc[off] if name == 's_setpc_b64' else int(parse(asm)[1][0].split('_')[1], 16) - there = joined.get(b_target, set()) - if b_target > off: - incoming.setdefault(b_target, []).append(({reg: self.sym.get(reg) for reg in there}, written & there)) - else: - for reg in there & written: - back, sym = self.sym.get(reg), kept.get(b_target, {}).get(reg) - if back and not run_time_symbol(back) and back != sym: - self.back_force.setdefault(b_target, {})[reg] = 'refuse' - elif sym is not None and back != sym: - self.back_force.setdefault(b_target, {}).setdefault( - reg, 'run' if run_time_symbol(sym) else 'refuse') - falls = name not in ('s_branch', 's_setpc_b64', 's_endpgm') - dests = scalar_destinations(name, asm) - written |= every_sgpr if 'any' in dests else dests - last_write.update(dict.fromkeys(every_sgpr if 'any' in dests else dests, off)) - self._pre_fconst = dict(self.float_const_s) - if 'any' in dests: - self.float_const_s.clear() + sources.setdefault(target, []).append(off) + if name == 's_cbranch_execz' and self.kind == 'cs': + skipped.append((off, target)) + # The first branch or branch target: before it the program is one straight-line path (op_s_round_mode). + self.uses_round_mode = any(name == 's_round_mode' for off, n, name, asm in self.ins) + # X2W_PS_QUAD_DIVERGENT=1 (default off, read when the stage is built): quad reads (DPP quad_perm) and + # image_sample_b are also lowered where a lane may skip them in forward control flow. That is exact only + # where the four lanes of each quad take the same path (D3D leaves quad reads and implicit derivatives + # undefined otherwise, while the hardware reads the inactive lanes, fi:1); loops stay refused. Each use is + # listed in quad_divergent_used and the manifest says `quaddivergent 1`. + self.quad_divergent = self.kind == 'ps' and os.environ.get('X2W_PS_QUAD_DIVERGENT') == '1' + self.quad_divergent_used = [] + self.has_loop = any(src >= t for t, srcs in sources.items() for src in srcs) + self.cf_first = min([off for off, n, name, asm in self.ins if name.startswith('s_cbranch') or name == 's_branch'] + + list(targets) + [1 << 32]) + if self.kind == 'ms' and self.uses_round_mode: + # A mesh request supplies no launch FLOAT_MODE. Limit the first supported profile to + # the common mixed-precision emitters that consult round16. Mesh-specific d16 image + # packing and the other half-precision forms require their own audit. + for _, _, op, _ in self.ins: + if re.search(r'[fd]16|f64', op) and op not in ('v_fma_mixlo_f16', 'v_fma_mixhi_f16'): + raise Unsupported('mesh round mode with %s' % op) + self.launch_unknown = True + self.mode_at = self.round_mode_flow() if self.kind in ('ps', 'ms') and self.uses_round_mode else {} + self.blocks = [] # (offset, [lines], terminator) + self.waterfall_back = set() # back edges of proven waterfall loops, emitted as fall-through (waterfall) + self.execz_snaps = [] # the snapshots on taken s_cbranch_execz edges (see merge) + self.uniform_v = set() # VGPRs proven to hold one value in every lane (see set_v) + self.partial_uniform = {} # VGPRs holding one value in every lane active at their write (see set_v) + self.shadow_v = set() # shadow variables xvN that v_readfirstlane_b32 introduced + self.lane_s = set() # SGPR variables that may differ between lanes in the one-lane model (see set_s) + self.s_written_at = {} # instruction offset -> SGPRs it assigns at run time + self.varying_s = set() + self.scc_uniform = True + self.low16_only_v = set() # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load + self.pinned_low16_v = set() # low16_only_v live across basic-block boundaries + self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer + self.has_branches = bool(targets) + self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it + self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) + start = 0 + incoming = {} # branch target -> symbolic states of the forward branches seen so far + previous = None + self.execz_fallthrough_epoch = None + scc_written, scc_unknown = set(), set() + self.entry_table_pointers = {reg: sym[1] for reg, sym in self.sym.items() + if isinstance(reg, int) and sym[0] == 'ptr' and sym[1][0] == 'table'} + self.descriptor_block_first = 0 + for instruction_index, (off, n, name, asm) in enumerate(self.ins): + self.descriptor_instruction_index = instruction_index + if off in targets or off == start: + self.descriptor_block_first = instruction_index + if off in targets and off != start: + self.pinned_low16_v.update(self.low16_only_v) + self.blocks.append((start, self.lines, None)) + self.lines, start = [], off + # The scan is linear, so at a join the state left by the instruction above is only one of the + # incoming paths (and none after an unconditional branch). Merge the states of every incoming + # edge when they are all forward; a loop head merges its entry edges and forgets the body's writes. + if off in targets and all(src < off for src in sources[off]): + states = list(incoming.get(off, [])) + if previous not in (None, 's_branch', 's_endpgm'): + states.append(self.snapshot()) + if states: + self.merge(states) + elif off in targets: + # A loop head: the entry edges (fall-through and forward branches) are merged as at any join, and + # the back edges carry whatever the loop body left. Every SGPR the body writes anywhere in + # [head, last back-edge source] loses its symbolic value (a constant known on entry is the first + # pass's value only: a counter `s14 = 0` must not fold into `0 + 1` on every pass), a register the + # body writes with anything but a lane mask stops being a mask, and exec is no longer the entry + # mask if the body writes it. + states = list(incoming.get(off, [])) + if previous not in (None, 's_branch', 's_endpgm'): + states.append(self.snapshot()) + if states: + self.merge(states) + self.forget_loop_writes(off, max(sources[off])) + if off in targets: + # Lane invariance is not merged across edges for VGPRs; at a loop head the linear state misses the + # back edges, so every SGPR becomes suspect until it is written again. + self.uniform_v.clear() + self.splat.clear() + self.partial_uniform.clear() + self.a_invariant = False + self.t_invariant = False + if not all(src < off for src in sources[off]): + self.lane_s = set(range(128)) else: - for reg in dests: - self.float_const_s.pop(reg, None) - try: - if off in refused: - raise Unsupported(refused[off]) - base = re.sub(r'_e(32|64)$', '', name) - if off in vcc_compares and all( - not mesh_vregs([tok]) and self.uniform_source(tok) - for tok in parse(asm)[1][1:] - ): - uniform_vcc_compares.add(off) - if base.startswith('s_cbranch_'): - cond = base[10:] - cond_uniform = cond in ('scc0', 'scc1') and self.scc_uniform - if off in vcc_branches: - if not vcc_branches[off] <= uniform_vcc_compares: - raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) - cond_uniform = True - if not cond_uniform: - b_target = int(parse(asm)[1][0].split('_')[1], 16) - regs, affected = div_targets.get(off, (set(), set())) - regs = {r for r in regs if isinstance(r, int)} - if b_target <= off: - regs.update(r for r in joined.get(b_target, ()) if isinstance(r, int)) - for tgt_off in affected: - bad_at_target.setdefault(tgt_off, set()).update(regs) - term = self.one(name, asm) - except Unsupported as reason: - if refusals is None: - if not hasattr(reason, 'instruction'): - reason.instruction = name # for fail_reason(); the message itself is unchanged - raised_unsupported = reason - break - refusals.append((str(reason), self.kind)) - continue - except Exception as error: - if refusals is None: - raise - refusals.append((handler_error(name, error, refusals), self.kind)) - continue - # A write proves the mark again: every path from here on runs it. s_movreld can write any SGPR. - self.join_masks = (self.join_masks | every_sgpr) if 'any' in dests else self.join_masks - dests - if self.scc_effect: - scc_effects[off] = self.scc_effect - if term: - self.pinned_low16_v.update(self.low16_only_v) - self.blocks.append((start, self.lines, term)) - self.lines, start = [], off + n - self.descriptor_block_first = instruction_index + 1 - - new_bad = self.bad_sgprs - force_unproven - new_at = {k: v - force_at.get(k, set()) for k, v in bad_at_target.items() if v - force_at.get(k, set())} - if (new_bad or new_at) and tentative_kept: - force_unproven.update(new_bad) - for k, v in new_at.items(): - force_at.setdefault(k, set()).update(v) - if refusals is not None: - del refusals[first_refusal:] + # In the one-lane model a branch condition (scc, vccz, execz) may differ between lanes, so an + # SGPR assigned on only some paths into this join may too, however invariant each value is. + first = min(sources[off]) + for at, regs in self.s_written_at.items(): + if first <= at < off: + self.lane_s |= regs + if off in targets: + self.execz_fallthrough_epoch = None + self.pc = off + self.past_entry = bool(self.blocks) or 0 in targets + if off in targets: + self.since_join, self.scc_uniform = set(), False + before = len(self.lines) + try: + term = self.one(name, asm) + except Unsupported as reason: + if refusals is None: + raise + refusals.append((str(reason), self.kind)) continue - if raised_unsupported is not None: - raise raised_unsupported - break - else: - reason = 'v_readfirstlane_b32 uniformity proof exceeded pass limit' - if refusals is None: - raise Unsupported(reason) - refusals.append((reason, self.kind)) + except Exception as error: + if refusals is None: + raise + refusals.append((handler_error(name, error, refusals), self.kind)) + continue + if any('scc = ' in line for line in self.lines[before:]): + scc_written.add(off) + elif re.sub(r'_e(32|64)$', '', name) in SCC_UNMODELLED or (name in SCA and SCA[name][1]): + # a hardware SCC write the HLSL did not make (or, for an SCA op with an SCC rule, one that a + # descriptor or m0 path skipped) + scc_unknown.add(off) + previous = name + if name.startswith('s_cbranch') or name == 's_branch': + snap = self.snapshot() + if name == 's_cbranch_execz': + self.execz_snaps.append(snap) # the taken edge: this lane's exec bit is 0 there (merge) + incoming.setdefault(int(parse(asm)[1][0].split('_')[1], 16), []).append(snap) + if term: + self.pinned_low16_v.update(self.low16_only_v) + self.blocks.append((start, self.lines, term)) + self.lines, start = [], off + n if self.lines: self.blocks.append((start, self.lines, None)) - self.materialized = materialize # declarations() assigns these before the body (and before any loop) - if set(scc_effects.values()) - {'emitted'}: - for kind, name in self.descriptor_scc_reads(dict(branches), scc_effects): - reason = 'scc from %s in %s' % ('descriptor data' if kind == 'descriptor' else kind, name) - if refusals is None: - raise Unsupported(reason) - refusals.append((reason, self.kind)) + self.check_scc(scc_written, scc_unknown) + self.check_quad_ops() self.pinned_low16_v.update(self.low16_only_v) leak = self.pinned_low16_v & self.whole_read_v if leak: @@ -2597,46 +2603,49 @@ def translate(self): raise Unsupported(reason) refusals.append((reason, self.kind)) - def descriptor_scc_reads(self, branches, effects): - """Find reads reachable with an elided SCC write, including through joins and back edges.""" - instructions = {off: (size, name, asm) for off, size, name, asm in self.ins} - pending = [(0, None)] # stale: None, or the scc_effect of the write that left the emitted scc behind - seen = set() - while pending: - off, stale = pending.pop() - if (off, stale) in seen or off not in instructions: + def check_scc(self, written, unknown): + """Refuse when an SCC value the translation does not compute can be read. + + The instructions in `unknown` write SCC in hardware but the HLSL leaves `scc` as it was. That is only + a wrong translation if some path from one of them reaches an SCC reader before an instruction whose + translation assigns `scc` (one in `written`). Paths follow fall-through and branch targets, loops + included; s_endpgm and s_branch end the fall-through. + """ + if not unknown: + return + order = [ins[0] for ins in self.ins] + info = {off: (name, asm) for off, n, name, asm in self.ins} + following = dict(zip(order, order[1:])) + calc = getattr(self, 'calculated_pc', None) or {} + + def successors(off): + name, asm = info[off] + if off in calc: + return [calc[off]] if calc[off] in info else [following[off]] if off in following else [] + if name == 's_endpgm': + return [] + nxt = [following[off]] if off in following else [] + if name == 's_branch': + nxt = [] + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + return [o for o in nxt if o in info] + for start in sorted(unknown): + if start in calc: continue - seen.add((off, stale)) - size, name, asm = instructions[off] - if stale and off not in self.calculated_pc and reads_scc(name, asm): - yield stale, name - if off in effects: - stale = effects[off] if effects[off] != 'emitted' else None - if off in branches: - pending.append((branches[off], stale)) - if name not in ('s_branch', 's_setpc_b64', 's_endpgm'): - pending.append((off + size, stale)) - - def join_writes(self, branches): - """Branch target -> the scalar registers another path can write before it reaches the target: the loop body - [target, branch] for a backward branch, and the skipped instructions (branch, target) for a forward one.""" - offs, written = [], [] # per instruction, once: a program has hundreds of branches over thousands of instructions - for off, _n, name, asm in self.ins: - regs = set(range(128)) if name.startswith('s_movreld') else set() # M0 picks the destination - for tok in destinations(name, parse(asm)[1]): - r = reg_range(tok) - if r and r[0] == 's': - regs.update(range(r[1], r[2] + 1)) - elif tok == 'm0': - regs.add('m0') - offs.append(off) - written.append(regs) - writes = {} - for branch, target in branches: - lo, hi = ((bisect.bisect_left(offs, target), bisect.bisect_right(offs, branch)) if target <= branch else - (bisect.bisect_right(offs, branch), bisect.bisect_left(offs, target))) - writes.setdefault(target, set()).update(*written[lo:hi]) - return writes + seen, todo = set(), list(successors(start)) + while todo: + off = todo.pop() + if off in seen: + continue + seen.add(off) + name, asm = info[off] + if reads_scc(name, asm) and off not in calc: + raise Unsupported('SCC of %s at %#x (not modelled) is read by %s at %#x' + % (info[start][0], start, name, off)) + if off in written or off in unknown: + continue + todo.extend(successors(off)) def tracks_uniformity(self): return all(hasattr(self, name) for name in ('uniform_v', 'varying_s', 'scc_uniform')) @@ -2670,54 +2679,12 @@ def one(self, name, asm): if name.endswith('_e32') and name[:-4] in VOP3_ONLY_VEC_U: raise Unsupported(name) base = re.sub(r'_e(32|64)$', '', name) - # Compute the proof before lowering, since a destination can also be a source. - dst = None - self._uniform_written = set() + if base.startswith('s_setreg') and 'HW_REG_MODE' in asm and (self.uses_round_mode or self.round16): + raise Unsupported('%s writes MODE in a program that uses s_round_mode or a non-zero launch mode' % base) if self.tracks_uniformity() and hasattr(self, 'uniform_expr'): - wrote_s = {r for r in self.forget_writes(name, ops, drop_since=False) if isinstance(r, int)} - else: - wrote_s = set() - # Unit probes build a Stage without __init__: without the tracking state, prove nothing. - # Past the entry block of a program with branches the read recomputes the defining expression, so the - # proof no longer needs a known exec (see op_v_readfirstlane_b32). - if (base in UNIFORM_VALU and ops and self.tracks_uniformity() and - (getattr(self, 'past_entry', False) and hasattr(self, 'uniform_expr') or - not getattr(self, 'past_entry', True) and getattr(self, 'exec_known', False)) and - (not mods or (base in VEC_F or base in VEC_U_TO_F) and - all(m in ('clamp', 'mul:2', 'mul:4', 'div:2') for m in mods))): - candidate = reg_range(ops[0]) - if candidate and candidate[0] == 'v' and candidate[1] == candidate[2]: - sources = ops[1:] - if base in VEC_F: - sources = [re.sub(r'^-(?=[^\d.])', '', tok).strip('|') for tok in sources] - if sources and all(self.uniform_source(tok) for tok in sources): - dst = candidate[1] + self.forget_writes(name, ops) self.last_v = None - term = self.lower(base, asm, ops, mods) - uniform_written = self._uniform_written - if self.tracks_uniformity() and getattr(self, 'since_join', None) is not None and wrote_s: - self.since_join -= (wrote_s - uniform_written) - if wrote_s and self.bad_sgprs is not None: - for r in wrote_s - uniform_written: - sym = self.sym.get(r) - if (r in self.varying_s or r in getattr(self, 'masks', ()) or - (sym is not None and sym[0] not in ('const', 'ud', 'fixed_buffer_word')) or - (self.defined_uniform_s is not None and r not in self.defined_uniform_s)): - if self.defined_uniform_s is not None: - self.defined_uniform_s.discard(r) - self.bad_sgprs.add(r) - if dst is not None: - self.uniform_v.add(dst) - if hasattr(self, 'uniform_expr'): - # Proven sources are scalars, constants and VGPRs; each VGPR needs its own current expression. - expr = self.last_v[1] if self.last_v and self.last_v[0] == dst else None - vs = [int(n) for n in re.findall(r'\bv(\d+)\b', expr or '')] - if expr is None or any(n not in self.uniform_expr for n in vs): - self.uniform_expr.pop(dst, None) - else: - self.uniform_expr[dst] = re.sub(r'\bv(\d+)\b', lambda m: '(%s)' % self.uniform_expr[int(m[1])], - expr) - return term + return self.lower(base, asm, ops, mods, name) def dpp_pair(self, base, asm, ops, mods): """A DPP16 spelling whose SRC0 is a quad pair broadcast (#2125 item C). @@ -2785,7 +2752,9 @@ def forget_writes(self, name, ops, drop_since=True): del self.uniform_expr[v] return regs - def lower(self, base, asm, ops, mods): + def lower(self, base, asm, ops, mods, name=None): + if name is None: + name = base pc = getattr(self, 'pc', None) calculated = getattr(self, 'calculated_pc', {}) if pc in calculated: @@ -2815,64 +2784,43 @@ def lower(self, base, asm, ops, mods): if base in ('s_wqm_b32', 's_wqm_b64'): if ops[0] in ('exec', 'exec_lo') and ops[1:] == ops[:1] and getattr(self, 'exec_known', False): self.wqm_exec = True # every lane of a touched quad is now active, helper lanes included - if hasattr(self, 'uniform_v'): - self.uniform_v.clear() if hasattr(self, 'scc_uniform'): self.scc_uniform = False # the hardware SCC result is not modelled - return None - if base == 's_setreg_imm32_b32': - # The write itself changes nothing the lowering models, except MODE[1:0] (the binary32 rounding mode): - # v_cvt_pk_u8_f32 and the other conversions are lowered for round-to-nearest-even, and the hardware - # follows MODE.round (round toward zero truncates). s_round_mode and s_setreg_b32 are refused already. - field = re.fullmatch(r'hwreg\((HW_REG_MODE|1)(?:,\s*(\d+),\s*(\d+))?\)', ops[0].strip()) if ops else None - if field and int(field.group(2) or 0) < 2: # shortcut: an offset >= 2 cannot reach MODE[1:0] - # The immediate is known: the write is harmless when it leaves MODE[1:0] at 0 (nearest even). - offset, width = int(field.group(2) or 0), int(field.group(3) or 32) - try: - value = int(ops[1], 0) & 0xffffffff - except IndexError: - value = None - except ValueError: - # The disassembler prints some inline constants as floats (1.0, 0.5): take their binary32 bits. - try: - value = struct.unpack(' 105: + raise Unsupported('s_ff1_i32_b32 requires one unmodified SGPR destination') + if self.past_entry or not self.exec_known: + raise Unsupported('s_ff1_i32_b32 requires the compute entry EXEC mask') + # Even the final partial group starts with lane zero active. FF1 preserves SCC. + self.set_s(dst[1], '0u', ('const', 0)) + return None handler = getattr(self, 'op_' + base, None) if handler: return handler(ops, mods) - if base in MUBUF_ATOMIC_OPS: - return self.buffer_atomic(base, ops, mods) - if base in LDS_DUAL_OPS: - return self.lds_dual(base, ops, mods) - if base in LDS_ATOMIC_OPS: - return self.lds_atomic(base, ops, mods) - if base.endswith('_dpp'): - return self.dpp(base[:-len('_dpp')], ops, mods) if base.startswith('v_cmp'): - # Before the VOP1/VOP2 SDWA route below: VOPC SDWA names also end in _sdwa. return self.compare(base, ops, mods) if base.endswith('_sdwa'): return self.sdwa(base[:-len('_sdwa')], ops, mods) @@ -2941,6 +2887,16 @@ def lower(self, base, asm, ops, mods): args = [self.f(o) for o in ops[1:1 + arity]] if base in ('v_fmac_f32', 'v_mac_f32'): args.append(self.f(ops[0])) + if base in FMA_FUSED or base in FMA_UNFUSED: + # The multiply-add rule (lead 000800 answer; the same rule as mesh2hlsl's): a fused op is one + # rounding, an unfused one rounds the product first; both made deterministic so a depth pre-pass and + # a colour pass of the same geometry agree bit for bit. Recorded in the manifest as `fma `. + pipe = getattr(self, 'pipe', None) # the tests' bare stages have none + if hasattr(pipe, 'fma_rule'): + pipe.fma_rule = DRAW_FMA + helper = 'x2w_fma_exact' if base in FMA_FUSED and DRAW_FMA == 'exact' else 'x2w_mad_precise' + if DRAW_FMA != 'legacy': + return self.set_vf(reg_range(ops[0])[1], '%s(%s, %s, %s)' % ((helper,) + tuple(args)), mods) return self.set_vf(reg_range(ops[0])[1], text.format(*args), mods) if base in VEC_U_TO_F: arity, text_f = VEC_U_TO_F[base] @@ -2956,8 +2912,6 @@ def lower(self, base, asm, ops, mods): return None if base in VEC_U: arity, text = VEC_U[base] - if mods: - raise Unsupported('%s with %s' % (base, mods)) if len(ops) != arity + 1: raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), arity + 1)) if base in VOP3_ONLY_VEC_U: @@ -2988,7 +2942,14 @@ def lower(self, base, asm, ops, mods): pipe = getattr(self, 'pipe', None) if pipe is not None and isinstance(getattr(pipe, 'uses_sad', None), set): pipe.uses_sad.add(base) - return self.set_v(reg_range(ops[0])[1], text.format(*args)) + result = text.format(*args) + if mods: + # VOP3 output modifiers (omod, clamp) act on a binary32 result, so they are only taken on the + # integer-source conversions that produce one; set_vf applies omod and then the clamp. + if base not in FLOAT_RESULT_U or any(m not in ('clamp', 'mul:2', 'mul:4', 'div:2') for m in mods): + raise Unsupported('%s with %s' % (base, mods)) + return self.set_vf(reg_range(ops[0])[1], 'F(%s)' % result, mods) + return self.set_v(reg_range(ops[0])[1], result) if base in SCA: return self.scalar(base, ops) if base == 's_getpc_b64': @@ -2999,6 +2960,102 @@ def lower(self, base, asm, ops, mods): raise Unsupported('%s: the shader load address is only elided for a program that also calculates a branch target' % base) raise Unsupported(base) + # DPP16 quad permutations in a pixel stage: src0 is read from lane perm[lane & 3] of the lane's 2x2 quad, the + # rest of the instruction is the plain VOP1/VOP2 operation. LLVM AMDGPUModifierSyntax.md: quad_perm is a "full + # permute of 4 threads"; fi:1 "fetch pre-existing values from inactive lanes"; bound_ctrl only acts on invalid + # lanes, which a quad permutation never names. Quad lane 1 is +x and lane 2 is +y (Mesa ACO + # aco_select_nir_intrinsics.cpp: ddx_coarse = v_subrev_f32 with quad_perm(0,0,0,0) then v_mov_b32 + # quad_perm(1,1,1,1), ddy_coarse with (2,2,2,2)), the order of D3D QuadReadLaneAt (0 top-left, 1 top-right, + # 2 bottom-left, 3 bottom-right). The HLSL quad reads need SM 6.0 (the mesh pipelines' dxc ps_6_0, which sets + # pipe.quad_ops; draws compile with fxc ps_5_1 and refuse), and every lane of the quad must execute them: + # each read is its own statement outside the exec guard, and check_quad_ops refuses one that a lane can skip. + QUAD_READS = {(1, 0, 3, 2): 'QuadReadAcrossX({0})', (2, 3, 0, 1): 'QuadReadAcrossY({0})', + (3, 2, 1, 0): 'QuadReadAcrossDiagonal({0})'} + + def quad_dpp(self, base, ops, mods): + if base in VOP3_ONLY_VEC_U: + raise Unsupported('DPP form of %s' % base) + if self.kind != 'ps' or not getattr(self.pipe, 'quad_ops', False): + raise Unsupported('%s_dpp' % base) # as before: no lane reads outside an SM 6.0 pixel stage + control = mods[0] if mods else 'no control' + m = re.fullmatch(r'quad_perm:\[([0-3]),([0-3]),([0-3]),([0-3])\]', control) + if not m: + raise Unsupported('%s_dpp with %s (not a quad permutation)' % (base, control)) + rest = set(mods[1:]) + if len(rest) != len(mods) - 1 or not {'row_mask:0xf', 'bank_mask:0xf', 'fi:1'} <= rest \ + or rest - {'row_mask:0xf', 'bank_mask:0xf', 'fi:1', 'bound_ctrl:1'}: + raise Unsupported('%s_dpp with %s' % (base, ' '.join(mods[1:]))) + perm = tuple(int(x) for x in m.groups()) + src = re.fullmatch(r'(-?\|?)(v\d+)(\|?)', ops[1]) if len(ops) > 1 else None + if not src: + raise Unsupported('%s_dpp source %s' % (base, ops[1] if len(ops) > 1 else None)) + value = self.u(src.group(2)) + if len(set(perm)) == 1: + expr = 'QuadReadLaneAt(%s, %du)' % (value, perm[0]) + elif perm in self.QUAD_READS: + expr = self.QUAD_READS[perm].format(value) + else: + raise Unsupported('%s_dpp with %s' % (base, control)) + names = self.__dict__.setdefault('dpp_names', []) + name = 'dpp%d' % len(names) + names.append(name) + self.__dict__.setdefault('dpp_at', []).append(self.pc) + statement = 'uint %s = %s;' % (name, expr) + self.__dict__.setdefault('dpp_statements', set()).add(statement) + self.emit(statement) + return self.one(base, '%s %s' % (base, ', '.join([ops[0], src.group(1) + name + src.group(3)] + ops[2:]))) + + def check_quad_ops(self): + """Refuse a quad read (quad_dpp) that some lane of the HLSL may not execute: the program has a loop (the + dispatch loop lets lanes reach a block in different iterations), or a path from the entry to the end + avoids the instruction (a per-lane branch around it).""" + at = getattr(self, 'dpp_at', ()) + if not at: + return + info = {off: (name, asm) for off, n, name, asm in self.ins} + order = [ins[0] for ins in self.ins] + following = dict(zip(order, order[1:])) + def successors(off): + name, asm = info[off] + if name == 's_endpgm': + return [] + nxt = [] if name == 's_branch' else [following[off]] if off in following else [] + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + return [o for o in nxt if o in info] + uniform = os.environ.get('X2W_PS_QUAD_UNIFORM') == '1' + last_quad = max(at) + for off in order: + if any(t <= off and (not uniform or t <= last_quad) for t in successors(off) if t != following.get(off)): + raise Unsupported('quad read (DPP) at %#x in a program with a loop (branch at %#x)' % (at[0], off)) + if uniform: + # Forward dispatch visits each block once, in guest instruction order. Leave + # VGPR writes and consumers predicated, but read every lane's retained VGPR + # outside the guest PC guard (fi:1). A prior discard can disable a source lane. + killed = False + for _, lines, _ in self.blocks: + depth = 0 + for line in lines: + if line in self.dpp_statements and (killed or depth): + raise Unsupported('uniform quad read after discard or inside a nested scope') + killed |= bool(re.search(r'\b(discard|return)\b', line)) + depth += line.count('{') - line.count('}') + self.uniform_dpp = self.dpp_statements + return + for target in at: + seen, todo = set(), [order[0]] + while todo: + off = todo.pop() + if off in seen or off == target: + continue + seen.add(off) + nxt = successors(off) + if not nxt: + if self.quad_divergent: + self.quad_divergent_used.append(target) + break + raise Unsupported('quad read (DPP) at %#x is skipped on a path to %#x' % (target, off)) + todo.extend(nxt) # VOP1/VOP2 with DPP16 quad broadcast (#2125 item A): quad_perm:[k,k,k,k] makes every lane read SRC0 from # lane k of its own quad (RDNA 2 ISA, "DPP": a lane reads lane (lane & ~3) | perm[lane & 3] of the row; LLVM 15 # AMDGPU DPP quad_perm). A pixel stage's four consecutive lanes are a 2x2 pixel quad (lane = x & 1 | (y & 1) << 1), @@ -3145,28 +3202,36 @@ def sdwa(self, base, ops, mods): if base in ('v_cvt_off_f32_i4', *VOP3_ONLY_VEC_U): raise Unsupported('SDWA form of %s' % base) fields = {} - out_mods = [] - float_result = base in VEC_U_TO_F + outmods = [] for m in mods: - if float_result and m in ('clamp', 'mul:2', 'mul:4', 'div:2'): - out_mods.append(m) + key, _, value = m.partition(':') + if key in ('src0_sel', 'src1_sel', 'src2_sel', 'dst_sel', 'dst_unused') and value: + fields[key] = value + elif m in ('clamp', 'mul:2', 'mul:4', 'div:2') and base in VEC_U_TO_F: + # The SDWA9 encoding (gfx9+, LLVM VOPInstructions.td VOP_SDWA9 has omod and clamp for VOP1/VOP2) + # carries the output modifiers; on a float-result conversion they act on the binary32 result as + # in VOP3. Taken only with dst_sel:DWORD (below), where no field placement follows them. + outmods.append(m) else: - key, _, value = m.partition(':') - if key in ('src0_sel', 'src1_sel', 'src2_sel', 'dst_sel', 'dst_unused') and value: - fields[key] = value - else: - raise Unsupported('%s with SDWA modifier %s' % (base, m)) - if float_result: - arity, text = VEC_U_TO_F[base] - elif base in VEC_U: - arity, text = VEC_U[base] + raise Unsupported('%s with SDWA modifier %s' % (base, m)) + if base == 'v_cndmask_b32': + # VOP2 SDWA select: the mask is always vcc; the selected source fields are moved as bits. + if len(ops) != 4 or ops[3] not in ('vcc', 'vcc_lo'): + raise Unsupported('SDWA v_cndmask_b32 form %s' % ops) + arity, text = 2, '(vcc & 1) ? {1} : {0}' elif base == 'v_mov_b32': + # VOP1 SDWA move (LLVM VOP1Instructions.td V_MOV_B32 has an SDWA form): the selected source field, + # placed by dst_sel / dst_unused like every integer SDWA result. arity, text = 1, '{0}' - # A lane mask is one bit per lane here, so a byte or word of it is not the hardware's field. - if fields.get('src0_sel') != 'DWORD' and self.is_lane_mask(ops[1].removeprefix('sext(').removesuffix(')')): - raise Unsupported('v_mov_b32 SDWA %s of lane mask %s' % (fields.get('src0_sel'), ops[1])) - else: + elif base in VEC_U_TO_F: + # The float-result conversions moved out of VEC_U (#1707) keep their SDWA form: the same expression + # as the bits, as VEC_U had it ('U(float({0}))' and so on). No output modifier is accepted above. + arity, text_f = VEC_U_TO_F[base] + text = 'U(%s)' % text_f + elif base not in VEC_U: raise Unsupported('SDWA form of %s' % base) + else: + arity, text = VEC_U[base] sources = [] for index in range(arity): token = ops[1 + index] @@ -3180,21 +3245,25 @@ def sdwa(self, base, ops, mods): selection == 'DWORD' and not sext and base in ('v_cvt_f32_f16', 'v_cvt_f32_ubyte0', 'v_cvt_f32_ubyte1')) sources.append(sdwa_source(self.u(token, low16_only=low16), selection, sext)) result = text.format(*sources) - if float_result: - # Output modifiers scale and then clamp the float value; dst_sel writes its bit pattern. - result = 'U(%s)' % self.f_mods(result, out_mods) select = fields.get('dst_sel') if not select: raise Unsupported('%s SDWA without dst_sel' % base) + if outmods: + if select != 'DWORD': + raise Unsupported('%s SDWA with %s and dst_sel:%s' % (base, ' '.join(outmods), select)) + return self.set_vf(reg_range(ops[0])[1], text_f.format(*sources), outmods) # The operation's HLSL carries its own operators, so it has to be grouped before the # destination field masks it: "v7 | v8 & 0xffff" would otherwise bind as "v7 | (v8 & 0xffff)". if SDWA_SEL[select][1] < 32: result = '(%s)' % result destination = reg_range(ops[0])[1] unused = fields.get('dst_unused', 'UNUSED_PAD') + # UNUSED_PRESERVE reads the destination's other bits: read it as an operand, so a pixel stage's entry + # (SPI input) VGPR read is recorded like any other read + old = self.u(ops[0]) if unused == 'UNUSED_PRESERVE' and SDWA_SEL[select][1] < 32 else 'v%d' % destination keep_low16 = (unused == 'UNUSED_PRESERVE' and select not in ('DWORD', 'WORD_1') and destination in self.low16_only_v) - self.set_v(destination, sdwa_dest(result, select, unused, 'v%d' % destination), low16_only=keep_low16) + self.set_v(destination, sdwa_dest(result, select, unused, old), low16_only=keep_low16) # scalar ALU with descriptor-word bookkeeping def exec_absorbed_source(self, base, srcs): @@ -3234,64 +3303,73 @@ def low(tok): r = reg_range(tok) return ('s%d' % r[1]) if r and r[0] == 's' and r[1] != r[2] else tok srcs = [low(t) for t in srcs] - dname = low(ops[0]) if base == 's_movk_i32': - srcs = [str(sopk_imm(srcs[0], True))] # D.i32 = signext(SIMM16) - shift_add = base in SHIFT_ADD - word_complement = base in ('s_nand_b32', 's_nor_b32', 's_xnor_b32') - lane_complement = False - # s_mul_hi_u32 needs the whole 32-bit word of each source, like the halfword pack. - word_pack = base in PACK_B16 or base in ('s_sext_i32_i8', 's_sext_i32_i16', 's_mul_hi_u32') - word_absdiff = base == 's_absdiff_i32' - if shift_add or word_complement or word_pack or word_absdiff: - # The per-lane mask cannot supply the full word needed by these operations. s_mul_hi_u32 into an - # SGPR that held a mask replaces it with a plain word (set_s drops the mark), so only vcc/exec count. - mask_dest = (dname in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') if base == 's_mul_hi_u32' - else self.is_lane_mask(dname)) - # Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask the lane's - # bit of the result is exact. Only an SGPR destination is taken; a mixed mask and plain word is not. - def mask_source(tok): - r = reg_range(tok) - return tok in ('vcc', 'vcc_lo', 'exec', 'exec_lo') or bool( - r and r[0] == 's' and r[1] == r[2] and r[1] in self.masks) - lane_complement = (word_complement and bool(dst) and dst[0] == 's' and dst[1] == dst[2] and dst[1] <= 105 - and all(mask_source(t) for t in srcs)) - if not lane_complement and (mask_dest or any(self.is_lane_mask(t) for t in srcs)): + # D.i32 = signext(SIMM16) (RDNA 2 ISA SOPK; LLVM s16imm); disasm_rdna2 prints the field unsigned. + srcs = [sopk_simm(srcs[0])] + dname = low(ops[0]) + # Upstream: s_sext_i32_i8 / s_sext_i32_i16 (SCA) need the whole word of their source, not a lane mask. + pack_or_absdiff = base in PACK_B16 or base == 's_absdiff_i32' + if pack_or_absdiff or base in ('s_sext_i32_i8', 's_sext_i32_i16'): + if self.is_lane_mask(dname) or any(self.is_lane_mask(t) for t in srcs): raise Unsupported('%s on a lane mask' % base) - if lane_complement and any(reg_range(t) and reg_range(t)[1] in getattr(self, 'join_masks', ()) - for t in srcs): - raise Unsupported('%s on a lane mask joined at a branch target' % base) - if shift_add and dname != 'm0' and (not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105): - raise Unsupported('%s destination %s' % (base, dname)) - if word_pack: if dname != 'm0' and (dst is None or dst[0] != 's' or dst[1] > 105): raise Unsupported('%s destination %s' % (base, dname)) for source in srcs: reg = reg_range(source) if reg and (reg[0] != 's' or reg[1] > 105): raise Unsupported('%s source %s' % (base, source)) - if pair and ('m0' in srcs or dname == 'm0'): - raise Unsupported('64-bit scalar operand m0') - def src_sym(t): - if t == 'm0': - return self.sym.get('m0') - r = reg_range(t) - return self.sym.get(r[1]) if r and r[0] == 's' else None - syms = [src_sym(t) for t in srcs] + word_complement = base in ('s_nand_b32', 's_nor_b32', 's_xnor_b32') + if word_complement: + # A lane mask operand or destination is the whole wave's mask, and SCC is set when any bit of the + # complemented 32-bit result is set; the one-lane projection keeps only this lane's bit. + def lane_mask(t): + r = reg_range(t) + return t in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or bool(r and r[0] == 's' and r[1] in self.masks) + def per_lane(t): + # a value whose bit i is lane i's: a mask, or 0 / 0xffffffff (every bit the same) + r = reg_range(t) + return (lane_mask(t) or t in ('0', '-1') or + bool(r and r[0] == 's' and r[1] in getattr(self, 'splat', ()))) + if lane_mask(dname) or any(lane_mask(t) for t in srcs): + if not all(per_lane(t) for t in srcs): + raise Unsupported('%s on a lane mask' % base) + # Every operand's bit i is lane i's, so the lane's own bit of ~(a op b) is ~(a_i op b_i), which the + # one-lane value below gives (as for s_not_b32). SCC is not: lanes outside the wave's active set + # (0 in a compare result) are 1 after the complement. No SCC is written, so check_scc refuses any + # read of it. + scc = None + if dname == 'm0' and not pack_or_absdiff: + return None + if (base == 's_andn2_b64' and dst and dst[0] == 's' and dst[2] == dst[1] + 1 + and ops[0] == ops[1] and ops[2] == 'exec' and self.sym.get(dst[1]) == ('conflict',) + and getattr(self, 'execz_fallthrough_epoch', None) == getattr(self, 'exec_writes', 0)): + # Each executing lane computes D_i & ~1. Lanes skipping the block already retain + # their old bit. Leave the wave-wide SCC unmodelled; check_scc rejects a live read. + self.set_s(dst[1], '0u') + self.set_s(dst[2], '0u') + self.masks.add(dst[1]) + return None + if base in ('s_and_b32', 's_and_b64') and any(t in ('exec', 'exec_lo') for t in srcs) and reg_range(dname): + # D = D & exec where D is symbolic only on s_cbranch_execz edges into a join (merge) and exec has not + # been written since: on those paths this lane's exec bit is 0, so the result is 0 whatever D held, + # and on the others D's run-time variable is its value. + d0 = reg_range(dname)[1] + regs = (d0, d0 + 1) if pair else (d0,) + def execzero(r): + return (self.sym.get(r) == ('conflict',) and + getattr(self, 'execzero', {}).get(r, -1) == getattr(self, 'exec_writes', 0)) + if dname in srcs and all(self.sym.get(r) is None or self.sym[r][0] in self.RUNTIME_BACKED + or execzero(r) for r in regs): + for r in regs: + if execzero(r): + self.sym.pop(r) + syms = [self.sym.get(reg_range(t)[1]) if reg_range(t) and reg_range(t)[0] == 's' else None for t in srcs] if any(s and s[0] in ('desc', 'descnum', 'ptr', 'ptrhi') for s in syms): - if scc or base in SCC_UNMODELLED: - self.scc_effect = 'descriptor' - if self.tracks_uniformity(): - self.scc_uniform = False - if shift_add or word_complement or word_absdiff: - raise Unsupported('scc from descriptor data') - if word_pack: + if pack_or_absdiff: raise Unsupported('%s on descriptor data' % base) - if dname == 'm0': - if scc: - raise Unsupported('scc from descriptor data') - self.sym['m0'] = syms[0] if base == 's_mov_b32' else ('descnum',) - return None + if word_complement: + # the descriptor path below records the word symbolically and emits no SCC + raise Unsupported('scc from descriptor data') if dname in ('exec', 'vcc', 'exec_lo', 'vcc_lo'): raise Unsupported('mask from descriptor data') d = reg_range(dname)[1] @@ -3319,15 +3397,19 @@ def src_sym(t): self.pipe.modified.add(desc_key(raw)) elif own and own[0] in ('desc', 'ptr', 'ptrhi') and any(s == own for s in syms): if own[0] == 'desc': - self.pipe.modified.add(desc_key(own)) - # Keep the resource identity for loads; stores refuse the unproved value. - self.sym[d] = own[:4] + ('modified',) - getattr(self.pipe, 'other_modified', set()).add(desc_key(own)) - else: - self.sym[d] = own if len(own) > 2 else own + ('added',) # the added offset is not tracked + self.pipe.modified.add((own[1], own[2])) + # which word changed and how (buffer_store accepts edits that keep the base address) + other = [t for t, s in zip(srcs, syms) if s != own] + self.pipe.__dict__.setdefault('modified_words', {}).setdefault((own[1], own[2]), []).append( + (own[3], base, tuple(other))) else: self.sym[d] = ('descnum',) return None + if base.startswith(('s_bcnt', 's_ff0', 's_ff1')) and any(t in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or + (reg_range(t) and reg_range(t)[0] == 's' and reg_range(t)[1] in self.masks) + for t in srcs): + # a lane count or a lane index: the one-lane model keeps only this lane's bit of a mask + raise Unsupported('%s of a lane mask' % base) # The table templates name their sources as {0}, {1}, ...; a short operand list would make # str.format raise IndexError, which the single-shader path records as a translator crash # rather than a refusal. The arity guards above cover the table entries that spell a count, so @@ -3341,10 +3423,6 @@ def src_sym(t): self.used_s.add(reg_range(srcs[absorbed])[1]) values = [t if i == absorbed else self.u(t) for i, t in enumerate(srcs)] expr = text.format(*values) - if shift_add: - # carry = bits shifted out of S0, or a wrap of the 32-bit sum; read before the destination is written - n = SHIFT_ADD[base] - self.set_scc('(%s >> %d) != 0 || (%s) < %s' % (values[0], 32 - n, expr, values[1])) if dname == 'm0': self.sym.pop('m0', None) self.emit('m0 = %s;' % expr) @@ -3379,8 +3457,8 @@ def src_sym(t): self.masks.discard(d) return None if base in SCALAR_CONST_FOLD: - # Constant operands give a known word, so a descriptor built from them (an inline sampler from - # s_movk_i32, s_bfm_b32, s_mov_b32 and s_brev_b32 into s[N:N+3]) is a constant descriptor. + # Constant operands give a known word, so a descriptor built from them (an inline sampler: s_movk_i32, + # s_bfm_b32 (op_s_bfm_b32), s_mov_b32, s_brev_b32 into s[N:N+3]) is a constant descriptor. def known(tok): r = reg_range(tok) if r and r[0] == 's' and r[1] == r[2]: @@ -3395,7 +3473,6 @@ def known(tok): if None not in operands: value = SCALAR_CONST_FOLD[base](*operands) & 0xffffffff self.set_s(d, '0x%08xu' % value, ('const', value)) - self.masks.discard(d) return None if base in ('s_mov_b64', 's_mov_b32') and srcs[0] in ('exec', 'exec_lo') and self.exec_known: self.set_s(d, 'exec') @@ -3415,17 +3492,7 @@ def known(tok): high_source = 's%d' % high if high is not None else srcs[0] high_uniform = (self.tracks_uniformity() and high != d and self.uniform_source(high_source)) - self.set_s(d, expr, scc=None if lane_complement else scc) - if base == 's_mov_b32' and srcs[0] in FLOATS and not is_mask: - # Keep the runtime SGPR assignment intact while letting const_words() read inline float patterns - # such as 0x40000000 (OPAQUE_BLACK, encoded as inline 244 / '2.0'). - self.__dict__.setdefault('float_const_s', {})[d] = fbits(FLOATS[srcs[0]]) - if lane_complement: - # The guest SCC is (the whole complemented word != 0), which the bits of every other lane decide (an - # idle lane's bit is set). It is not emitted: translate() refuses a program that can read it. - self.scc_effect = 'a lane-mask complement' - if self.tracks_uniformity(): - self.scc_uniform = False + self.set_s(d, expr, scc=scc) if is_mask: self.masks.add(d) if pair and base != 's_mov_b64': @@ -3448,19 +3515,21 @@ def op_s_and_saveexec_b64(self, ops, mods, text='exec & {0}'): if not dst or dst[0] != 's': raise Unsupported('saveexec destination %s' % ops[0]) d = dst[1] - src_reg = reg_range(ops[1]) - src = ops[1] if not src_reg else 's%d' % src_reg[1] - # S0 is read at issue, before D is written (RDNA 2 ISA SOP1 S_AND_SAVEEXEC: D = EXEC; EXEC = S0 & EXEC). - # With D == S0 (s_and_saveexec_b64 s[6:7], s[6:7]) writing D first would make the new exec exec & exec, so - # S0 is copied to the scratch word w before D is written. - if src_reg and src_reg[0] == 's' and src_reg[1] == d: - self.emit('w = %s;' % self.u(src)) - value = 'w' + src = ops[1] if not reg_range(ops[1]) else 's%d' % reg_range(ops[1])[1] + # S0 is read before D is written: with D == S0 (s_and_saveexec_b64 s[6:7], s[6:7]) the new exec is + # exec & old S0, not exec & exec (RDNA 2 ISA SOP1: D = EXEC; EXEC = S0 & EXEC, with S0 the value read at issue). + if reg_range(ops[1]) and reg_range(ops[1])[0] == 's' and reg_range(ops[1])[1] == d: + self.uses_xsave = True + self.lines.append('xsave = %s;' % self.u(src)) # every lane: a temporary read only below + value = 'xsave' else: value = self.u(src) self.set_s(d, 'exec') self.masks.add(d) - self.set_exec_scc(text.format(value)) + self.exec_known = False + self.emit('exec = (%s) & 1; scc = exec != 0;' % text.format(value)) + if hasattr(self, 'scc_uniform'): + self.scc_uniform = False op_s_and_saveexec_b32 = op_s_and_saveexec_b64 @@ -3486,55 +3555,47 @@ def op_s_andn2_wrexec_b64(self, ops, mods): op_s_andn2_wrexec_b32 = op_s_andn2_wrexec_b64 - def scalar_accumulate(self, base, ops, mods): - """s_addk_i32 / s_mulk_i32: D = D op signext(SIMM16), the destination is also the source. + # SOPK s_addk_i32 / s_mulk_i32: D = D op sext(simm16). LLVM's SIShrinkInstructions forms them from s_add_i32 / + # s_mul_i32 only when isInt<16> of the constant, so the immediate is signed. s_addk_i32 defines SCC (signed + # overflow, not modelled: see SCC_UNMODELLED); s_mulk_i32 does not. + def sopk_arith(self, ops, op): + d = reg_range(ops[0]) + if not d or d[0] != 's' or d[1] != d[2]: + raise Unsupported('SOPK destination %s' % ops[0]) + imm = int(ops[1], 0) & 0xffff + imm = (imm - 0x10000 if imm & 0x8000 else imm) & 0xffffffff + self.masks.discard(d[1]) + self.set_s(d[1], '%s %s 0x%08xu' % (self.S(d[1]), op, imm)) + + # s_bitset0_b32 / s_bitset1_b32: D[S0[4:0]] = 0 / 1, the other bits of D kept (AMD RDNA 2 ISA SOP1; LLVM + # SOPInstructions.td defines them with D tied as an input and no SCC def). A lane mask or symbolic D is refused. + def bitset(self, ops, one): + d = reg_range(ops[0]) + if not d or d[0] != 's' or d[1] != d[2] or d[1] in self.masks: + raise Unsupported('s_bitset%d_b32 destination %s' % (one, ops[0])) + bit = '(1u << (%s & 31))' % self.u(ops[1]) + old = self.S(d[1]) + expr = '%s | %s' % (old, bit) if one else '%s & ~%s' % (old, bit) + a, b = self.is_const(d[1]), self.is_const(reg_range(ops[1])[1]) if reg_range(ops[1]) else None + if b is None and re.fullmatch(r'(0x[0-9a-f]+|\d+)', ops[1]): + b = int(ops[1], 0) + if a is not None and b is not None: # both known: keep the constant (descriptor words are built this way) + value = (a | 1 << (b & 31)) if one else (a & ~(1 << (b & 31))) + self.set_s(d[1], '0x%08xu' % (value & 0xffffffff), ('const', value & 0xffffffff)) + return + self.set_s(d[1], expr) - RDNA 2 ISA 12.2 (SOPK 15, 16): addk sets SCC to the signed overflow of the sum, mulk leaves SCC - alone. LLVM 15 SOPInstructions.td declares Defs = [SCC] for both, so after mulk the SCC proof is - dropped (the emitted scc keeps its value, which is the ISA meaning). - """ - if mods or len(ops) != 2: - raise Unsupported('%s with %d operands' % (base, len(ops))) - dst = reg_range(ops[0]) - if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: - raise Unsupported('%s destination %s' % (base, ops[0])) - if not re.fullmatch(r'0x[0-9a-f]{1,4}', ops[1]): - raise Unsupported('%s immediate %s' % (base, ops[1])) - d = dst[1] - # D is read before it is written: refuse a mask or descriptor source while the old state is intact. - if d in self.masks or self.sym.get(d, ('',))[0] == 'execcopy': - raise Unsupported('%s on a lane mask' % base) - sym = self.sym.get(d) - if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): - raise Unsupported('%s on %s data' % (base, sym[0])) - simm = int(ops[1], 16) - imm = (simm - 0x10000 if simm & 0x8000 else simm) & 0xffffffff - imm_text = '0x%08xu' % imm - old = self.S(d) - add = base == 's_addk_i32' - result = '%s %s %s' % (old, '+' if add else '*', imm_text) - if add: - # signed overflow: the operands share a sign that the sum does not keep - overflow = '((%s ^ (%s)) & ~(%s ^ %s) & 0x80000000u) != 0u' % (old, result, old, imm_text) - if sym and sym[0] == 'const': - total = (sym[1] + imm) & 0xffffffff - overflow = 'true' if ((sym[1] ^ total) & ~(sym[1] ^ imm) & 0x80000000) else 'false' - self.set_scc(overflow) - elif self.tracks_uniformity(): - self.scc_uniform = False - if sym and sym[0] == 'const': - value = (sym[1] + imm if add else sym[1] * imm) & 0xffffffff - self.set_s(d, '0x%08xu' % value, ('const', value)) - else: - self.set_s(d, result) - self.masks.discard(d) - return None + def op_s_bitset0_b32(self, ops, mods): + self.bitset(ops, 0) + + def op_s_bitset1_b32(self, ops, mods): + self.bitset(ops, 1) def op_s_addk_i32(self, ops, mods): - return self.scalar_accumulate('s_addk_i32', ops, mods) + self.sopk_arith(ops, '+') def op_s_mulk_i32(self, ops, mods): - return self.scalar_accumulate('s_mulk_i32', ops, mods) + self.sopk_arith(ops, '*') def op_s_cselect_b32(self, ops, mods): self.scalar_select(ops, False) @@ -3589,22 +3650,19 @@ def scalar_select(self, ops, pair): if pair and 'm0' in low: raise Unsupported('64-bit scalar operand m0') expr = 'scc ? %s : %s' % (self.u(low[1]), self.u(low[2])) - if low[0] == 'm0': - self.sym.pop('m0', None) - self.emit('m0 = %s;' % expr) - return if low[0] in ('exec', 'vcc', 'exec_lo', 'vcc_lo'): - # In wave32, exec_lo and vcc_lo hold the whole lane mask, as the generic scalar path reads them. - mask = 'exec' if low[0].startswith('exec') else 'vcc' - if mask == 'exec': + # wave32: vcc_lo / exec_lo are the whole lane mask, as in the generic scalar path + var = low[0][:4].rstrip('_') if low[0].startswith('exec') else 'vcc' + if var == 'exec': self.exec_known = False - self.emit('%s = (%s) & 1;' % (mask, expr)) + self.emit('%s = (%s) & 1;' % (var, expr)) return - r = reg_range(low[0]) - if not r or r[0] != 's': + if not reg_range(low[0]) or reg_range(low[0])[0] != 's': raise Unsupported('s_cselect into %s' % low[0]) - d = r[1] + d = reg_range(low[0])[1] self.set_s(d, '(%s) & 1' % expr if pair else expr) + if not pair and {low[1], low[2]} <= {'-1', '0'} and hasattr(self, 'splat'): + self.splat.add(d) if pair: self.masks.add(d) self.set_s(d + 1, '0u') @@ -3639,80 +3697,48 @@ def const_soffset(self, tok): return None def op_s_load_dwordx4(self, ops, mods, count=4): - imm = smem_mods(mods) - if len(ops) != 3: - raise Unsupported('s_load with %d operands' % len(ops)) + smem_imm_refuse('s_load', ops, mods) dst, base = reg_range(ops[0]), reg_range(ops[1]) - if not dst or dst[0] != 's' or dst[2] - dst[1] + 1 != count or dst[2] > 105: - raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) - if not base or base[0] != 's' or base[2] - base[1] != 1 or base[2] > 105: - raise Unsupported('s_load base %s' % ops[1]) - # A loaded descriptor or word is not a lane mask; some forms below only record a symbol, not set_s. for n in range(dst[1], dst[2] + 1): - getattr(self, 'masks', set()).discard(n) + getattr(self, 'masks', set()).discard(n) # a loaded descriptor or value is not a lane mask (some paths below skip set_s) p = self.sym.get(base[1]) if not p or p[0] != 'ptr': raise Unsupported('s_load through s%d holding %s' % (base[1], p)) - # 'off' names no offset operand at all, so the byte offset is zero, as for the literal 0. - token = smem_offset(ops[2]) - known = self.const_soffset(token) if p[1] != ('smpheap',) else None - if known is not None: - # A register offset that holds a known constant (s_movk before the load) is that literal byte - # offset; the modifier adds to it. This reaches descriptors in a bindless heap (#1723). - total = known + (imm or 0) - if total > 0xfffff: - raise Unsupported('SMEM register offset %#x' % total) - token, imm = str(total), None - if re.fullmatch(r'-?(?:0[xX][0-9a-fA-F]+|\d+)', token): - off = int(token, 0) - if off < 0 or off > 0xfffff: - raise Unsupported('SMEM immediate offset %s' % ops[2]) - if imm is not None: - raise Unsupported('SMEM literal offset %s with offset:%#x' % (ops[2], imm)) - if p[1][0] == 'root': - buf = self.pipe.resource((p[1], None), 'buf') - for i in range(count): - self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, off + 4 * i)) - return - # The pointer symbol does not record an addend or a rewritten high word, so two loads through such a - # pointer may read different words under the same (source, offset). In a compute or vertex stage (the - # stages that accept a raw descriptor conversion before a store) those loads are told apart by the - # offset of the s_load; loads through the untouched pair keep one identity. - # A 32-bit table pointer carries a high word the program sets to a constant: loads through the same - # untouched low word and the same constant read the same words (tag -1 - constant). - hi = self.sym.get(base[1] + 1) - if getattr(self, 'kind', None) not in ('cs', 'vs') or (p == ('ptr', p[1]) and hi == ('ptrhi', p[1])): - load = () - elif p == ('ptr', p[1]) and hi and hi[0] == 'const' and len(hi) == 2: - load = (-1 - hi[1],) - else: - load = (self.pc,) + if p[1] == ('resheap',) and 'heap' in getattr(self.pipe, 'features', ()) and count in (4, 8) and not mods: + k = len(self.pipe.heapvars) + self.pipe.heapvars.append(None) + self.used_h.add(k) + self.emit('h%d = %s;' % (k, self.u(ops[2]) if reg_range(ops[2]) else '0x%xu' % (int(ops[2], 0) & 0xffffffff))) for i in range(count): - self.sym[dst[1] + i] = ('desc', p[1], off, i) + load + self.sym[dst[1] + i] = ('desc', ('heapdyn', k), 0, i) return - if p[1] == ('smpheap',): - if self.pipe.sampler_heap and count == 4: + try: + # 'off' names no offset operand at all, so the byte offset is zero, as for the literal 0. + off = int(smem_offset(ops[2]), 0) + except ValueError: + if p[1] == ('smpheap',) and self.pipe.sampler_heap and count == 4: # A sampler picked at run time from the sampler heap: keep the byte offset in the # first destination register; image() indexes the heap table with it. d = dst[1] self.used_s.add(d) - expr = self.smem_soffset(token) - if imm: - expr = '%s + %d' % (expr, imm) - self.emit('s%d = %s;' % (d, expr)) + self.emit('s%d = %s;' % (d, self.u(ops[2]))) for i in range(count): self.sym[d + i] = ('smpheap', d, i) return - self.smem_soffset(token, record_use=False) - if count != 4: - raise Unsupported('s_load of %d dwords from %s' % (count, p[1])) - # Shortcut (default unless X2W_SAMPLER_HEAP=1): a fixed default sampler. + if p[1] == ('smpheap',): + # Shortcut (default unless X2W_SAMPLER_HEAP=1): a fixed default sampler. + for i in range(count): + self.sym[dst[1] + i] = ('const', 0) + self.pipe.notes.add('dynamic sampler index replaced by a default sampler') + return + raise Unsupported('s_load with a register offset through %s' % (p[1],)) + if p[1][0] == 'root': + buf = self.pipe.resource((p[1], None), 'buf') for i in range(count): - # Never assigned at run time (the third field says so): a join that reads it refuses (run_time_symbol). - self.sym[dst[1] + i] = ('const', 0, 'unassigned') - self.pipe.notes.add('dynamic sampler index replaced by a default sampler') + self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, off + 4 * i)) return - raise Unsupported('s_load with a register offset through %s' % (p[1],)) + for i in range(count): + self.sym[dst[1] + i] = ('desc', p[1], off, i) def op_s_bfm_b32(self, ops, mods): """Fold constant bitfield masks: titles build inline sampler words with them.""" @@ -3745,91 +3771,36 @@ def op_s_bfm_b32(self, ops, mods): self.set_s(d, '(((1u << (%s & 31)) - 1) << (%s & 31))' % (self.u(ops[1]), self.u(ops[2]))) return None - def scalar_const(self, tok): - """Value of a 32-bit scalar source that is known at translation time, else None.""" - r = reg_range(tok) - if r: - return self.is_const(r[1]) if r[0] == 's' and r[1] == r[2] else None - try: - return int(tok, 0) & 0xffffffff - except ValueError: - return None - - def scalar_wide_op(self, name, ops, mods, wide_src, wide_dst, helper, signed=None): - """SOP2 shifts and bitfield extracts with a 64-bit source and/or result. - - D = f(S0, S1) with S1 a 32-bit word; SCC = (D != 0). Every source is read before any destination - register is written, so an overlapping destination cannot feed a half-written value back.""" - if mods or len(ops) != 3: - raise Unsupported('%s with %d operands and modifiers %s' % (name, len(ops), mods)) - dst = reg_range(ops[0]) - width = 1 + wide_dst - if (not dst or dst[0] != 's' or dst[2] != dst[1] + wide_dst or dst[2] > 105 - or (wide_dst and dst[1] % 2)): - raise Unsupported('%s destination %s' % (name, ops[0])) - s1 = reg_range(ops[2]) - if ('m0' in ops[1:] or any(self.is_lane_mask(t) for t in ops[1:]) - or any(r[0] == 's' and any(w in self.masks for w in range(r[1], r[2] + 1)) - for r in map(reg_range, ops[1:]) if r) or ops[2] in FLOATS or ops[1] in FLOATS - or (s1 and (s1[0] != 's' or s1[1] != s1[2] or s1[1] > 105))): - raise Unsupported('%s source %s' % (name, ', '.join(ops[1:]))) - if wide_src: - r0 = reg_range(ops[1]) - if r0 and r0[0] != 's': - raise Unsupported('%s source %s' % (name, ops[1])) - low, high = self.i64_words(ops[1]) - known = [self.scalar_const('s%d' % r0[1]), self.scalar_const('s%d' % r0[2])] if r0 else [ - int(low[:-1]), int(high[:-1])] - else: - low, high = self.u(ops[1]), None - known = [self.scalar_const(ops[1])] - amount = self.u(ops[2]) - amount_known = self.scalar_const(ops[2]) - d = dst[1] - self.masks.difference_update(range(d, d + width)) - if None not in known and amount_known is not None: - x = known[0] | (known[1] << 32 if wide_src else 0) - value = scalar_wide_fold(helper, x, amount_known, signed) - for i in range(width): - word = (value >> (32 * i)) & 0xffffffff - self.set_s(d + i, '0x%08xu' % word, ('const', word)) - self.set_scc('true' if value else 'false') - return None - uniform = (self.tracks_uniformity() - and self.scalar_expr_uniform('%s %s %s' % (low, high or '', amount))) - sg = '' if signed is None else ', %du' % (1 if signed else 0) - if wide_dst: - call = '%s(%s, %s, %s%s)' % (helper, low, high if wide_src else '0u', amount, sg) - self.emit('{ uint2 t = %s; s%d = t.x; s%d = t.y; scc = (t.x | t.y) != 0u; }' % (call, d, d + 1)) - else: - self.emit('{ uint t = %s(%s, %s%s); s%d = t; scc = t != 0u; }' % (helper, low, amount, sg, d)) - for r in range(d, d + width): - self.sym.pop(r, None) - self.used_s.add(r) - if self.tracks_uniformity(): - (self.varying_s.discard if uniform else self.varying_s.add)(r) - self.scc_effect = 'emitted' - if self.tracks_uniformity(): - self.scc_uniform = uniform + def op_s_bfm_b64(self, ops, mods): + """D[63:0] = ((1 << S0[5:0]) - 1) << S1[5:0]; SCC unchanged. Folded when both counts are constant.""" + d = reg_range(ops[0])[1] + vals = [] + for o in ops[1:3]: + r = reg_range(o) + if r and r[0] == 's': + vals.append(self.is_const(r[1])) + else: + try: + vals.append(int(o, 0)) + except ValueError: + vals.append(None) + if None in vals: + raise Unsupported('s_bfm_b64 with a run-time count') + value = (((1 << (vals[0] & 63)) - 1) << (vals[1] & 63)) & 0xffffffffffffffff + self.masks.discard(d) + self.set_s(d, '0x%08xu' % (value & 0xffffffff), ('const', value & 0xffffffff)) + self.set_s(d + 1, '0x%08xu' % (value >> 32), ('const', value >> 32)) return None - def op_s_lshl_b64(self, ops, mods): - return self.scalar_wide_op('s_lshl_b64', ops, mods, True, True, 'shl64') - - def op_s_lshr_b64(self, ops, mods): - return self.scalar_wide_op('s_lshr_b64', ops, mods, True, True, 'shr64u') + def bitcmp(self, ops, want): + """s_bitcmp{0,1}_b32: SCC = (S0[S1[4:0]] == want); no register is written.""" + self.emit('scc = ((%s >> (%s & 31u)) & 1u) == %du;' % (self.u(ops[0]), self.u(ops[1]), want)) - def op_s_ashr_i64(self, ops, mods): - return self.scalar_wide_op('s_ashr_i64', ops, mods, True, True, 'shr64i') + def op_s_bitcmp0_b32(self, ops, mods): + self.bitcmp(ops, 0) - def op_s_bfe_i32(self, ops, mods): - return self.scalar_wide_op('s_bfe_i32', ops, mods, False, False, 'bfe32', True) - - def op_s_bfe_u64(self, ops, mods): - return self.scalar_wide_op('s_bfe_u64', ops, mods, True, True, 'bfe64', False) - - def op_s_bfe_i64(self, ops, mods): - return self.scalar_wide_op('s_bfe_i64', ops, mods, True, True, 'bfe64', True) + def op_s_bitcmp1_b32(self, ops, mods): + self.bitcmp(ops, 1) def op_s_load_dwordx8(self, ops, mods): self.op_s_load_dwordx4(ops, mods, 8) @@ -3844,35 +3815,31 @@ def op_s_load_dword(self, ops, mods): self.op_s_load_dwordx4(ops, mods, 1) def op_s_buffer_load_dword(self, ops, mods, count=1): - imm = smem_mods(mods) - if len(ops) != 3: - raise Unsupported('s_buffer_load with %d operands' % len(ops)) + smem_imm_refuse('s_buffer_load', ops, mods) dst = reg_range(ops[0]) if not dst or dst[0] != 's' or dst[2] - dst[1] + 1 != count or dst[2] > 105: raise Unsupported('s_buffer_load destination %s for %d dwords' % (ops[0], count)) buf = self.pipe.resource(self.descriptor(ops[1]), 'buf') token = smem_offset(ops[2]) - is_lit = bool(re.fullmatch(r'-?(?:0[xX][0-9a-fA-F]+|\d+)', token)) - if is_lit: - val = int(token, 0) - if val < 0 or val > 0xfffff: - raise Unsupported('SMEM immediate offset %s' % ops[2]) - if imm is not None: - raise Unsupported('SMEM literal offset %s with offset:%#x' % (ops[2], imm)) - offset = self.u(token) - extra = 0 - else: - offset = self.smem_soffset(token) - extra = imm or 0 - sreg = reg_range(token) - if sreg and offset == ('s%d' % sreg[1]) and dst[1] <= sreg[1] < dst[2]: - self.emit('a = %s;' % offset) - offset = 'a' - # All words use the original offset, even when a destination overwrites its register. - uniform = self.tracks_uniformity() and self.uniform_source(token) - for i in range(count): - self.set_s(dst[1] + i, '%s.Load(%s + %d)' % (buf, offset, extra + 4 * i), uniform=uniform) - if is_lit: + offset = self.u(token) + # An SGPR offset can carry an immediate as well (disasm_rdna2 prints "s4 offset:0x10"): the byte offset is + # the sum. glc/dlc are cache policy. Anything else is refused. + extra = 0 + for m in mods: + if m.startswith('offset:'): + extra += int(m[7:], 0) + elif m not in ('glc', 'dlc'): + raise Unsupported('s_buffer_load modifier %s' % m) + # Every word's address uses the offset register as it was before the load, so when the destination range + # holds that register it is written last (s_buffer_load_dwordx2 s[4:5], s[16:19], s4). + order = list(range(count)) + r = reg_range(token) + if r and r[0] == 's' and dst[1] <= r[1] < dst[1] + count: + order.remove(r[1] - dst[1]) + order.append(r[1] - dst[1]) + for i in order: + self.set_s(dst[1] + i, '%s.Load(%s + %d)' % (buf, offset, extra + 4 * i)) + if not mods and re.fullmatch(r'0x[0-9a-f]+|\d+', token): self.sym[dst[1] + i] = ('fixed_buffer_word',) def op_s_buffer_load_dwordx2(self, ops, mods): @@ -3887,59 +3854,57 @@ def op_s_buffer_load_dwordx8(self, ops, mods): def op_s_buffer_load_dwordx16(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 16) - def buffer_address(self, ops, mods): - # MUBUF and MTBUF share the same address calculation: optional index * stride (idxen), - # optional byte VGPR offset (offen), scalar byte offset (soffset) and 12-bit immediate - # offset. Cache-policy flags (glc, slc, dlc) do not change the loaded bytes; lds, tfe - # and any other modifier change the destination or operand layout and are refused first. - offset = 0 - for m in mods: - if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): - offset += int(m[7:], 0) - elif m not in ('idxen', 'offen', 'glc', 'slc', 'dlc'): - raise Unsupported('buffer modifier %s' % m) + @staticmethod + def check_buffer_load_arity(ops, mods): + for modifier in mods: + if modifier in ('lds', 'tfe', 'lwe'): + raise Unsupported('buffer modifier %s' % modifier) if len(ops) != 4: raise Unsupported('buffer load with %d operands, expected 4' % len(ops)) + + def buffer_address(self, ops, mods): + Stage.check_buffer_load_arity(ops, mods) key = self.descriptor(ops[2]) - buf = self.pipe.resource(key, 'buf') - soffset = None - if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): - offset += int(ops[3], 0) + rw = key in getattr(self.pipe, 'rw_keys', ()) or key in getattr(self.pipe, 'uavs', {}) + if rw: + # A buffer this program also stores to: read through its UAV (in place, so the program sees its own + # stores), at the same uavbase-shifted address the stores use. No stride source for a UAV. + if 'idxen' in mods: + raise Unsupported('indexed load through a buffer the program stores to') + buf = self.pipe.uav(key) else: - sreg = reg_range(ops[3]) - if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: - raise Unsupported('buffer soffset %s' % ops[3]) - soffset = self.S(sreg[1]) + buf = self.pipe.resource(key, 'buf') + soff = ops[3] + if re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', soff): + offset, extra = int(soff, 0), '' + else: + offset, extra = 0, '%s + ' % self.u(soff) # an SGPR soffset adds its value + for m in mods: + if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): + offset += int(m[7:], 0) + if rw: + extra = 'ud%d + %s' % (self.pipe.ud(('uavbase', int(buf[1:]))), extra) idxen, offen = 'idxen' in mods, 'offen' in mods + if idxen or offen: + regs = reg_range(ops[1]) + mode = 'idxen offen' if idxen and offen else 'idxen' if idxen else 'offen' + if not regs or regs[0] != 'v' or regs[2] > 255 or regs[2] - regs[1] != int(idxen and offen): + raise Unsupported('buffer vaddr %s for %s' % (ops[1], mode)) + elif ops[1] != 'off': + raise Unsupported('buffer vaddr %s without idxen or offen' % ops[1]) terms = [] - if idxen and offen: - if key in self.pipe.modified: - raise Unsupported('indexed load through a modified descriptor') - r = reg_range(ops[1]) - if not r or r[0] != 'v' or r[2] - r[1] != 1 or r[2] > 255: - raise Unsupported('buffer vaddr %s for idxen offen' % ops[1]) - stride = self.pipe.ud(('stride', self.pipe.resources[key]['index'])) - terms.append('%s * ud%d' % (self.u('v%d' % r[1]), stride)) - terms.append(self.u('v%d' % r[2])) - elif idxen: + if idxen: if key in self.pipe.modified: raise Unsupported('indexed load through a modified descriptor') - r = reg_range(ops[1]) - if not r or r[0] != 'v' or r[1] != r[2] or r[1] > 255: - raise Unsupported('buffer vaddr %s for idxen' % ops[1]) - stride = self.pipe.ud(('stride', self.pipe.resources[key]['index'])) - terms.append('%s * ud%d' % (self.u(ops[1]), stride)) - elif offen: - r = reg_range(ops[1]) - if not r or r[0] != 'v' or r[1] != r[2] or r[1] > 255: - raise Unsupported('buffer vaddr %s for offen' % ops[1]) - terms.append(self.u(ops[1])) - elif ops[1] != 'off': - raise Unsupported('buffer vaddr %s without idxen or offen' % ops[1]) - if soffset is not None: - terms.append(soffset) - terms.append('%d' % offset) - return buf, ' + '.join(terms) + if key[0][0] == 'heapdyn': + stride = 'x2w_vstride(h%d)' % key[0][1] + else: + stride = 'ud%d' % self.pipe.ud(('stride', self.pipe.resources[key]['index'])) + terms.append('%s * %s' % (self.u('v%d' % regs[1]), stride)) + if offen: + terms.append(self.u('v%d' % regs[2])) + address = ' + '.join(terms + [str(offset)]) + return buf, extra + address def op_buffer_load_dword(self, ops, mods, count=1): # ops[0] is read before buffer_address() can refuse a short operand list, so an instruction with no @@ -3962,278 +3927,47 @@ def op_buffer_load_dwordx3(self, ops, mods): def op_buffer_load_dwordx4(self, ops, mods): self.op_buffer_load_dword(ops, mods, 4) - def op_buffer_store_vs(self, ops, mods, count): - # Vertex-stage store in the `off` form: scalar byte offset plus the 12-bit immediate, through a - # descriptor read from a fixed root-table slot, written to a RWByteAddressBuffer (issue #1723). - # The manifest carries the `uav` line the runtime binds; a descriptor may not also be loaded. - if self.kind != 'vs': - raise Unsupported('buffer store in the %s stage' % self.kind) - offset = 0 - for m in mods: - if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): - offset += int(m[7:], 0) - else: - raise Unsupported('buffer store modifier %s' % m) - if len(ops) != 4 or ops[1] != 'off': - raise Unsupported('buffer store without the off address form') - src = reg_range(ops[0]) - if not src or src[0] != 'v' or src[2] - src[1] != count - 1 or src[2] > 255: - raise Unsupported('buffer store data %s' % ops[0]) - key = self.descriptor(ops[2]) - if key[0][0] != 'table' or key[1] is None: - raise Unsupported('buffer store through %s' % (key,)) - if key in self.pipe.modified: - # Only the modifications a compute store accepts: the stride clear or the structured-to-raw conversion. - self.store_descriptor(ops[2], 4, 'buffer store', stride0_ok=True, raw_conversion_ok=True) - if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): - offset += int(ops[3], 0) - soffset = '' - if offset % 4: - raise Unsupported('buffer store at unaligned byte offset %d' % offset) - else: - sreg = reg_range(ops[3]) - if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: - raise Unsupported('buffer soffset %s' % ops[3]) - if offset % 4: - raise Unsupported('buffer store at unaligned immediate offset %d' % offset) - soffset = '%s + ' % self.S(sreg[1]) - uav = self.pipe.uav(key, 'raw') - words = ', '.join(self.u('v%d' % n) for n in range(src[1], src[2] + 1)) - store = '%s.Store%s(a, %s);' % (uav, '' if count == 1 else str(count), 'uint%d(%s)' % (count, words) if count > 1 else words) - # Store* needs a multiple of four: the immediate is checked above; a register offset is rounded down. - self.emit('a = (%s%d) & 0xfffffffcu;' % (soffset, offset) if soffset else 'a = %d;' % offset) - self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) - - def store_descriptor(self, tok, words, what, stride0_ok=False, raw_conversion_ok=False): - """Resource key for a single loaded descriptor or a proven raw transformation of it.""" - rsrc = reg_range(tok) - first = self.sym.get(rsrc[1]) if rsrc and rsrc[0] == 's' and rsrc[2] - rsrc[1] == words - 1 else None - if not first or first[0] != 'desc' or first[1][0] != 'table' or first[2] is None or first[3] % 4: - raise Unsupported('%s through %s holding %s' % (what, tok, first)) - key = desc_key(first) - loaded = tuple(desc_word(first, first[3] + k) for k in range(words)) - actual = tuple(self.sym.get(rsrc[1] + k) for k in range(words)) - valid = names_one_value(first) and actual == loaded - if names_one_value(first) and stride0_ok and words == 4: - cleared = loaded[1] + ('stride0',) - valid = valid or actual == (loaded[0], cleared, *loaded[2:]) - if not valid and raw_conversion_ok: - valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',)) - if (not valid or key in getattr(self.pipe, 'other_modified', ()) - or (key in self.pipe.modified and not stride0_ok)): - raise Unsupported('%s through a modified descriptor' % what) - return key - - def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=False, allow_scalar_address=False, - raw_conversion_ok=False): - """Validate a fixed-table raw UAV descriptor, data range, byte address, and 4-byte alignment.""" - offset = 0 - glc = False - for m in mods: - if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): - offset += int(m[7:], 0) - elif m == 'glc' and allow_glc: - glc = True - elif m != 'offen': - raise Unsupported('%s modifier %s' % (kind_label, m)) - offen = 'offen' in mods - if len(ops) != 4 or (not offen and not (allow_scalar_address and glc and ops[1] == 'off')): - raise Unsupported('%s without the offen address form' % kind_label) - data = reg_range(ops[0]) - if not data or data[0] != 'v' or data[2] - data[1] != data_count - 1 or data[2] > 255: - raise Unsupported('%s data %s' % (kind_label, ops[0])) - if offen: - vaddr = reg_range(ops[1]) - if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: - raise Unsupported('%s vaddr %s for offen' % (kind_label, ops[1])) - key = self.store_descriptor(ops[2], 4, kind_label, stride0_ok=True, raw_conversion_ok=raw_conversion_ok) - terms = [self.u(ops[1])] if offen else [] - if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): - if not offen: - raise Unsupported('%s off requires a scalar register soffset' % kind_label) - offset += int(ops[3], 0) - else: - sreg = reg_range(ops[3]) - if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: - raise Unsupported('buffer soffset %s' % ops[3]) - terms.append(self.S(sreg[1])) - if offset % 4: - raise Unsupported('%s at unaligned immediate offset %d' % (kind_label, offset)) - terms.append(str(offset)) - return data, self.pipe.uav(key), '(%s) & 0xfffffffcu' % ' + '.join(terms), glc - - def op_buffer_store_dword(self, ops, mods, count=1): - # Compute-stage store in the offen form: per-lane byte VGPR plus the scalar offset and the 12-bit immediate, - # through a descriptor read from a fixed root-table slot, to a RWByteAddressBuffer (manifest `uav` line). - # Like the loads, this assumes a raw descriptor (no swizzle or stride). Out-of-range stores: assumes a future - # runtime sizes the view to the descriptor's range so both sides drop them; nothing binds or checks that yet. - if self.kind == 'vs': - return self.op_buffer_store_vs(ops, mods, count) - if self.kind != 'cs': - raise Unsupported('buffer_store_dword' + ('x%d' % count if count > 1 else '')) # the unknown-op refusal - src, uav, address, _ = self.raw_table_uav_store('buffer store', ops, mods, count, raw_conversion_ok=True) - words = [self.u('v%d' % n) for n in range(src[1], src[2] + 1)] - data = words[0] if count == 1 else 'uint%d(%s)' % (count, ', '.join(words)) - # Store* needs a multiple of four. As in #2059, the run-time part (VGPR and register soffset) is rounded down: - # an assumption that a dword access ignores the low two address bits, not a measurement. - self.emit('a = %s;' % address) - store = '%s.Store%s(a, %s);' % (uav, '' if count == 1 else count, data) - self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) - - def buffer_atomic(self, name, ops, mods): - """Lower 32-bit compute MUBUF atomics with optional glc pre-atomic return.""" - if self.kind != 'cs': - raise Unsupported(name) - method, signed, is_sub, data_count = MUBUF_ATOMIC_OPS[name] - data, uav, address, glc = self.raw_table_uav_store( - 'buffer atomic', ops, mods, data_count, allow_glc=True, allow_scalar_address=name == 'buffer_atomic_add') - words = [self.u('v%d' % n) for n in range(data[1], data[2] + 1)] - self.emit('a = %s;' % address) - if not isinstance(getattr(self, 'used_atomic', None), set): - self.used_atomic = set() - if name == 'buffer_atomic_cmpswap': - # RDNA 2 puts replacement in vdata[0] and compare in vdata[1]; HLSL takes compare first. - if glc: - self.used_atomic.add('uint') - call = '%s.InterlockedCompareExchange(a, %s, %s, ao);' % (uav, words[1], words[0]) - else: - call = '%s.InterlockedCompareStore(a, %s, %s);' % (uav, words[1], words[0]) - elif name == 'buffer_atomic_swap': - # HLSL RWByteAddressBuffer.InterlockedExchange always requires an output operand. - self.used_atomic.add('uint') - call = '%s.InterlockedExchange(a, %s, ao);' % (uav, words[0]) - else: - arg = 'asint(%s)' % words[0] if signed else ('(0u - %s)' % words[0] if is_sub else words[0]) - if glc: - out_var = 'ai' if signed else 'ao' - self.used_atomic.add('int' if signed else 'uint') - call = '%s.Interlocked%s(a, %s, %s);' % (uav, method, arg, out_var) - else: - call = '%s.Interlocked%s(a, %s);' % (uav, method, arg) - self.emit(call if self.exec_known else 'if (exec & 1) %s' % call) - if glc: - self.set_v(data[1], 'asuint(ai)' if signed else 'ao') - - def _lds_general_barrier_ok(self): - """True when a compute stage uses dual/atomic LDS ops in straight-line code without legacy exchange ops.""" - ins = getattr(self, 'ins', None) - if not ins: - return False - has_general = False - for i, (_, _, name, _) in enumerate(ins): - op = re.sub(r'_e(32|64)$', '', name) - if op in LEGACY_LDS_EXCHANGE_OPS: - return False - if op in LDS_DUAL_ATOMIC_OPS: - has_general = True - if op.startswith(('s_branch', 's_cbranch', 's_setpc', 's_swappc')) or (op == 's_endpgm' and i + 1 < len(ins)): - return False - return has_general - - def _lds_require_alloc(self, base): - if getattr(self, 'pipe', None) is None: - raise Unsupported('%s needs pipeline metadata' % base) - words = self.pipe.lds_words - if not 0 < words <= 8192: - raise Unsupported('%s needs a nonzero LDS allocation of at most 32 KiB' % base) - self.uses_lds = True - return words * 4 - - def lds_dual(self, name, ops, mods): - """Lower 32-bit dual-offset and stride-64 LDS ops (ds_write2_b32, ds_write2st64_b32, ds_read2st64_b32).""" - if getattr(self, 'kind', None) != 'cs': - raise Unsupported(name) - is_write, stride = LDS_DUAL_OPS[name] - if is_write: - if (len(ops) != 3 or _lds_single(ops[0]) is None - or _lds_single(ops[1]) is None or _lds_single(ops[2]) is None): - raise Unsupported('%s needs three single VGPRs (addr, data0, data1)' % name) - else: - if len(ops) != 2 or _lds_pair(ops[0]) is None or _lds_single(ops[1]) is None: - raise Unsupported('%s needs a 2-VGPR pair and a byte address VGPR' % name) - # Reuse ds_read2_b32 modifier/aliasing validation (offset0/offset1 in 0..255, distinct, no gds/unknown mods). - off0, off1 = lds_byte_offsets('ds_read2_b32', mods) - scale = stride // 4 - off0, off1 = off0 * scale, off1 * scale - lds_bytes = self._lds_require_alloc(name) - exec_prefix = '' if self.exec_known else '(exec & 1) && ' - if is_write: - addr = self.u(ops[0]) - d0, d1 = self.u(ops[1]), self.u(ops[2]) - self.emit('a = %s;' % addr) - for off, val in ((off0, d0), (off1, d1)): - if off < lds_bytes: - self.emit('if (%s((a & 3u) == 0u) && a < %du) lds[(a + %du) >> 2] = %s;' - % (exec_prefix, lds_bytes - off, off, val)) - else: - dst = _lds_pair(ops[0]) - addr = self.u(ops[1]) - self.emit('a = %s;' % addr) - for idx, off in enumerate((off0, off1)): - if off < lds_bytes: - self.emit('w = 0u;') - self.emit('if (%s((a & 3u) == 0u) && a < %du) w = lds[(a + %du) >> 2];' - % (exec_prefix, lds_bytes - off, off)) - self.set_v(dst + idx, 'w') - else: - self.set_v(dst + idx, '0u') - - def lds_atomic(self, name, ops, mods): - """Lower 32-bit unsigned/bitwise compute LDS atomics (non-rtn and _rtn forms) onto groupshared uint lds[N].""" - if getattr(self, 'kind', None) != 'cs': - raise Unsupported(name) - method, has_rtn = LDS_ATOMIC_OPS[name] - if has_rtn: - if (len(ops) != 3 or _lds_single(ops[0]) is None - or _lds_single(ops[1]) is None or _lds_single(ops[2]) is None): - raise Unsupported('%s needs three single VGPRs (dst, addr, data)' % name) - dst, addr_op, data_op = _lds_single(ops[0]), ops[1], ops[2] - else: - if len(ops) != 2 or _lds_single(ops[0]) is None or _lds_single(ops[1]) is None: - raise Unsupported('%s needs two single VGPRs (addr, data)' % name) - dst, addr_op, data_op = None, ops[0], ops[1] - # Reuse ds_write_b32 single-offset validation (optional 16-bit byte offset, no gds/unknown mods). - off, = lds_byte_offsets('ds_write_b32', mods) - if off % 4: - raise Unsupported('%s requires 4-byte aligned immediate offset, got %d' % (name, off)) - lds_bytes = self._lds_require_alloc(name) - addr = self.u(addr_op) - data = self.u(data_op) - self.emit('a = %s;' % addr) - exec_prefix = '' if self.exec_known else '(exec & 1) && ' - if off < lds_bytes: - if has_rtn: - if not isinstance(getattr(self, 'used_atomic', None), set): - self.used_atomic = set() - self.used_atomic.add('uint') - self.emit('ao = 0u;') - self.emit('if (%s((a & 3u) == 0u) && a < %du) Interlocked%s(lds[(a + %du) >> 2], %s, ao);' - % (exec_prefix, lds_bytes - off, method, off, data)) - self.set_v(dst, 'ao') - else: - self.emit('if (%s((a & 3u) == 0u) && a < %du) Interlocked%s(lds[(a + %du) >> 2], %s);' - % (exec_prefix, lds_bytes - off, method, off, data)) - elif has_rtn: - self.set_v(dst, '0u') - - def op_buffer_store_dwordx2(self, ops, mods): - self.op_buffer_store_dword(ops, mods, 2) - - def op_buffer_store_dwordx3(self, ops, mods): - self.op_buffer_store_dword(ops, mods, 3) - - def op_buffer_store_dwordx4(self, ops, mods): - self.op_buffer_store_dword(ops, mods, 4) - def tbuffer(self, ops, mods, count): - if not ops: - raise Unsupported('buffer load with 0 operands, expected 4') dst = reg_range(ops[0]) formats = [m for m in mods if m.startswith('format:')] fmt = formats[0][8:-1] if formats else 'BUF_FMT_8_UNORM' # the disassembler omits the default format buf, address = self.buffer_address(ops, [m for m in mods if not m.startswith('format:')]) + if buf.startswith('u'): + raise Unsupported('typed load through a buffer the program stores to') # ldu() takes a ByteAddressBuffer self.emit('a = %s;' % address) - self.load_format(fmt, buf, dst[1], count) + table = {'BUF_FMT_8_8_8_8_UNORM': ('ldu({0}, a)', ['U((w & 255) / 255.0)', 'U(((w >> 8) & 255) / 255.0)', 'U(((w >> 16) & 255) / 255.0)', 'U((w >> 24) / 255.0)']), + 'BUF_FMT_8_8_UNORM': ('ldu({0}, a)', ['U((w & 255) / 255.0)', 'U(((w >> 8) & 255) / 255.0)', '0u', 'U(1.0)']), + 'BUF_FMT_8_UNORM': ('ldu({0}, a)', ['U((w & 255) / 255.0)', '0u', '0u', 'U(1.0)']), + 'BUF_FMT_8_UINT': ('{0}.Load(a & ~3u) >> ((a & 3u) * 8u)', ['w & 255u', '0u', '0u', '1u']), + # integer fields as unsigned values; a missing component of an integer format reads 1 + 'BUF_FMT_8_8_8_8_UINT': ('ldu({0}, a)', ['w & 255u', '(w >> 8) & 255u', '(w >> 16) & 255u', 'w >> 24']), + 'BUF_FMT_16_16_UINT': ('ldu({0}, a)', ['w & 65535u', 'w >> 16', '0u', '1u']), + # x in bits [9:0], y [19:10], z [29:20], w [31:30] (the R10G10B10A2 layout, x lowest). ASSUMED from + # the GCN data-format naming; not checked against a source or a console readback. + 'BUF_FMT_2_10_10_10_UNORM': ('ldu({0}, a)', ['U((w & 1023) / 1023.0)', 'U(((w >> 10) & 1023) / 1023.0)', + 'U(((w >> 20) & 1023) / 1023.0)', 'U((w >> 30) / 3.0)']), + 'BUF_FMT_16_16_UNORM': ('ldu({0}, a)', ['U((w & 65535) / 65535.0)', 'U((w >> 16) / 65535.0)', '0u', 'U(1.0)']), + # SNORM n: max(c / (2^(n-1) - 1), -1.0), so both -32768 and -32767 read -1.0 (the D3D11.3 functional + # spec's SNORM -> FLOAT rule; that the console's buffer fetch clamps the same way is ASSUMED) + 'BUF_FMT_16_SNORM': ('ldu({0}, a)', ['U(max(float(asint(w << 16) >> 16) / 32767.0, -1.0))', + '0u', '0u', 'U(1.0)']), + 'BUF_FMT_16_16_SNORM': ('ldu({0}, a)', ['U(max(float(asint(w << 16) >> 16) / 32767.0, -1.0))', + 'U(max(float(asint(w) >> 16) / 32767.0, -1.0))', '0u', 'U(1.0)']), + 'BUF_FMT_16_16_FLOAT': ('ldu({0}, a)', ['U(f16tof32(w))', 'U(f16tof32(w >> 16))', '0u', 'U(1.0)']), + # four binary16 values in eight bytes: x, y in the first dword (low half first), z, w in the second + 'BUF_FMT_16_16_16_16_FLOAT': ('ldu({0}, a)', ['U(f16tof32(w))', 'U(f16tof32(w >> 16))', + 'U(f16tof32(ldu({0}, a + 4)))', 'U(f16tof32(ldu({0}, a + 4) >> 16))']), + 'BUF_FMT_32_32_32_32_FLOAT': (None, ['{0}.Load(a)', '{0}.Load(a + 4)', '{0}.Load(a + 8)', '{0}.Load(a + 12)']), + 'BUF_FMT_32_32_32_FLOAT': (None, ['{0}.Load(a)', '{0}.Load(a + 4)', '{0}.Load(a + 8)', 'U(1.0)']), + 'BUF_FMT_32_32_FLOAT': (None, ['{0}.Load(a)', '{0}.Load(a + 4)', '0u', 'U(1.0)']), + 'BUF_FMT_32_FLOAT': (None, ['{0}.Load(a)', '0u', '0u', 'U(1.0)'])} + if fmt not in table: + raise Unsupported('buffer format %s' % fmt) + load, comps = table[fmt] + if load: + self.emit('w = %s;' % load.format(buf)) + for i in range(count): + self.set_v(dst[1] + i, comps[i].format(buf)) def load_format(self, fmt, buf, first, count): if fmt not in FETCH_FORMATS: @@ -4259,6 +3993,18 @@ def op_s_swappc_b64(self, ops, mods): self.load_format(FETCH_DXGI[e['format']][0], buf, e['vgpr'], e['count']) self.fetched = True + def op_tbuffer_load_format_x(self, ops, mods): + self.tbuffer(ops, mods, 1) + + def op_tbuffer_load_format_xy(self, ops, mods): + self.tbuffer(ops, mods, 2) + + def op_tbuffer_load_format_xyz(self, ops, mods): + self.tbuffer(ops, mods, 3) + + def op_tbuffer_load_format_xyzw(self, ops, mods): + self.tbuffer(ops, mods, 4) + @staticmethod def descriptor_scalar_writes(name, ops): regs = set() @@ -4415,131 +4161,295 @@ def mubuf_format(self, ops, mods, count): % (sel, sel, sel, sel, sel)) self.emit('}') - def op_buffer_load_format_x(self, ops, mods): - self.mubuf_format(ops, mods, 1) + def format_load(self, ops, mods, count, name): + """buffer_load_format_*: the format and swizzle are in the descriptor's word 3, known only at draw time. - def op_buffer_load_format_xy(self, ops, mods): - self.mubuf_format(ops, mods, 2) + Behind X2W_DRAW_FEATURES=bufword3: the draw runtime passes srv i's word 3 as an entry constant (manifest + `udsrc bufword3 `: the real word of a title-written descriptor, the synthesized one of a typed + buffer view, 0 for raw-copy, vertex and root sources) and x2w_fmt_load decodes the element. The idxen + stride is `udsrc stride` (element size of a typed view, descriptor stride otherwise; d3d12_draw.inl).""" + if self.kind == 'cs': + return self.mubuf_format(ops, mods, count) + if 'bufword3' not in getattr(self.pipe, 'features', ()): + raise Unsupported(name) + for m in mods: + if not (m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:')): + raise Unsupported('%s modifier %s' % (name, m)) + key = self.descriptor(ops[2]) + if key[0][0] == 'heapdyn' and {'heap', 'heapwords'} <= set(getattr(self.pipe, 'features', ())): + for m in mods: + if not (m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:')): + raise Unsupported('%s modifier %s' % (name, m)) + dst = reg_range(ops[0]) + buf, address = self.buffer_address(ops, mods) + if buf.startswith('u'): + raise Unsupported('%s through a buffer the program stores to' % name) + self.pipe.draw_heapwords = True + self.emit('a = %s;' % address) + for i in range(count): + self.set_v(dst[1] + i, 'x2w_fmt_load(%s, a, x2w_hword(h%d, 3u), %du)' % (buf, key[0][1], i)) + return + if key[0][0] != 'table': + # word 3 reaches the shader only for table entries (root and vertex sources give 0) + raise Unsupported('%s through %s' % (name, key[0][0])) + dst = reg_range(ops[0]) + buf, address = self.buffer_address(ops, mods) + if buf.startswith('u'): + raise Unsupported('%s through a buffer the program stores to' % name) # bufword3 names an srv + w3 = self.pipe.ud(('bufword3', self.pipe.resources[key]['index'])) + self.emit('a = %s;' % address) + for i in range(count): + self.set_v(dst[1] + i, 'x2w_fmt_load(%s, a, ud%d, %du)' % (buf, w3, i)) - def op_buffer_load_format_xyz(self, ops, mods): - self.mubuf_format(ops, mods, 3) + def buffer_store(self, ops, mods, count, name): + """buffer_store_dword{,x2,x3,x4} to a raw buffer UAV, behind X2W_DRAW_FEATURES=uav. - def op_buffer_load_format_xyzw(self, ops, mods): - self.mubuf_format(ops, mods, 4) - - def op_buffer_store_format_d16_x(self, ops, mods): - """Lower compute MUBUF buffer_store_format_d16_x (opcode 0x84) using V# word 3, stride and num_records. - - Writes one converted 16-bit component from the low 16 bits of vdata into a raw UAV buffer: - - BUF_FMT_32_FLOAT (22): binary16 -> binary32, 4-byte aligned Store. - - BUF_FMT_16_FLOAT (13), BUF_FMT_16_UINT (11), BUF_FMT_16_SINT (12): low 16 bits stored at a - 2-byte aligned offset via a lock-free InterlockedCompareExchange CAS loop on the enclosing dword. - - BUF_FMT_16_UNORM (7), BUF_FMT_16_SNORM (8): binary16 -> binary32 -> D3D half-away-from-zero - 16-bit UNORM/SNORM (NaN -> 0), stored via the same 2-byte atomic CAS loop. - Per RDNA 2 ISA §8.1.5 Table 35, OOB_SELECT 0 (structured, stride != 0) checks index < num_records - and (voff + imm_off) + elem_bytes <= stride while soffset adds to the base address; OOB_SELECT 3 - (raw, stride == 0) checks (soffset + voff + imm_off) + elem_bytes <= num_records. OOB_SELECT 1/2, - mismatched stride/OOB_SELECT, nonzero DW1[31:30] swizzle flags (uav_stride carries DW1 >> 16), - unsupported formats/flags, misaligned addresses and out-of-bounds lanes are no-ops. + The descriptor becomes `uav buf table|root ...` (RWByteAddressBuffer u, draw-rt RUNTIME_DONE.md) and the + address adds `udsrc uavbase ` (the bytes between the 16-aligned view start the runtime binds and the + descriptor base; without it a misaligned buffer would get a null UAV). Refused: idxen (no stride line for a + UAV), a descriptor this program also reads as an SRV (D3D12 has no SRV + UAV on one buffer in a draw), and + any modifier other than offen, offset:N and the cache-policy bits. The lane's store runs only where exec holds. """ - name = 'buffer_store_format_d16_x' - if self.kind != 'cs': + if 'uav' not in getattr(getattr(self, 'pipe', None), 'features', ()): raise Unsupported(name) - raw = getattr(self, 'raw_code', b'') - pc = getattr(self, 'pc', None) - if raw and pc is not None and pc + 8 <= len(raw): - w0, w1 = struct.unpack_from(' 0xfff: - raise Unsupported('%s modifier %s' % (name, m)) - imm_offset = val + if not (m in ('offen', 'glc', 'slc', 'dlc') or m.startswith('offset:')): + raise Unsupported('%s modifier %s' % (name, m)) + key = self.descriptor(ops[2]) + if key[0][0] not in ('table', 'root'): + raise Unsupported('%s through %s' % (name, key[0][0])) + if key in self.pipe.modified: + # A raw store uses only the base address (word 0, word 1 [15:0]); the runtime binds the entry's bytes in + # place. Accepted edits: words 2 and 3 (record count, format, OOB select: bounds and typing a raw + # store ignores; assumed in range) and an AND of word 1 that keeps [15:0] (clearing the stride). + for word, op, other in getattr(self.pipe, 'modified_words', {}).get(key, [('?', '?', ())]): + keeps_base = word == 1 and op == 's_and_b32' and len(other) == 1 and \ + re.fullmatch(r'0x[0-9a-f]+', other[0]) and int(other[0], 16) & 0xffff == 0xffff + if word not in (2, 3) and not keeps_base: + raise Unsupported('%s through a modified descriptor' % name) + u = self.pipe.uav(key) + base = self.pipe.ud(('uavbase', int(u[1:]))) + offset = sum(int(m[7:], 0) for m in mods if m.startswith('offset:')) + soff = ops[3] + if re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', soff): + offset += int(soff, 0) + parts = [] + else: + parts = [self.u(soff)] # an SGPR soffset adds its value + if 'offen' in mods: + parts.insert(0, self.u(ops[1])) + address = ' + '.join(['ud%d' % base] + parts + ['%d' % offset]) + data = reg_range(ops[0]) + if data[2] - data[1] + 1 != count: + raise Unsupported('%s data %s' % (name, ops[0])) + values = ', '.join(self.u('v%d' % (data[1] + i)) for i in range(count)) + call = '%s.Store%s(a, %s);' % (u, '' if count == 1 else count, values if count == 1 else 'uint%d(%s)' % (count, values)) + self.emit('a = %s;' % address) + self.emit(call if self.exec_known else 'if (exec & 1) %s' % call) + + def op_v_pack_b32_f16(self, ops, mods): + """D[15:0] = S0.f16, D[31:16] = S1.f16 (AMD RDNA 2 ISA VOP3 V_PACK_B32_F16). op_sel[i] picks the high half of""" + sel = [0, 0, 0] + for m in mods: + if m.startswith('op_sel:[') and m.endswith(']'): + sel = [int(x) for x in m[len('op_sel:['):-1].split(',')] else: + raise Unsupported('v_pack_b32_f16 modifier %s' % m) + if len(sel) != 3 or sel[2] or len(ops) != 3: + raise Unsupported('v_pack_b32_f16 form %s %s' % (', '.join(ops), ' '.join(mods))) + halves = [] + for i, tok in enumerate(ops[1:3]): + neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) + if neg: + tok = tok[1:] + absolute = tok.startswith('|') and tok.endswith('|') + if absolute: + tok = tok[1:-1] + if reg_range(tok) and reg_range(tok)[1] == reg_range(tok)[2]: + half = '(%s >> 16)' % self.u(tok) if sel[i] else '(%s & 0xffffu)' % self.u(tok) + elif sel[i]: + raise Unsupported('v_pack_b32_f16 op_sel on %s' % tok) + else: + half = '(%s & 0xffffu)' % self.h(tok) + if absolute: + half = '(%s & 0x7fffu)' % half + if neg: + half = '(%s ^ 0x8000u)' % half + halves.append(half) + self.set_v(reg_range(ops[0])[1], '%s | (%s << 16)' % (halves[0], halves[1])) + + def format_store(self, ops, mods, count, name): + """buffer_store_format_{x,xy,xyz,xyzw} to a typed buffer UAV, behind X2W_DRAW_FEATURES=uav,uavfmt. + + The format is in the V# word 3 [18:12], known only at draw time: `udsrc uavword3 ` gives it, and + `udsrc uavstride ` the V# stride (word 1 [29:16]) that idxen multiplies the index by (RDNA 2 ISA, + MUBUF addressing: base + soffset + offset + stride * index (+ the offen VGPR)). x2w_fmt_store writes data + component c to format channel c; only formats whose channels are all 32 bits (codes 20-22, 62-64, 72-77: + the bits are stored as given) are written, any other format stores nothing. ASSUMED, not measured: DST_SEL + does not reorder a store (LLVM lowers the store intrinsic with the data in channel order), and the index + is in range (num_records not checked, as for the raw stores). The lane's store runs only where exec holds.""" + if not {'uav', 'uavfmt'} <= set(getattr(self.pipe, 'features', ())): + raise Unsupported(name) + for m in mods: + if not (m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:')): raise Unsupported('%s modifier %s' % (name, m)) - imm_offset = 0 if imm_offset is None else imm_offset - src = reg_range(ops[0]) - if not src or src[0] != 'v' or src[1] != src[2] or src[1] > 255: + key = self.descriptor(ops[2]) + if key[0][0] not in ('table', 'root'): + raise Unsupported('%s through %s' % (name, key[0][0])) + if key in self.pipe.modified: + raise Unsupported('%s through a modified descriptor' % name) + u = self.pipe.uav(key) + index = int(u[1:]) + base, w3 = self.pipe.ud(('uavbase', index)), self.pipe.ud(('uavword3', index)) + offset = sum(int(m[7:], 0) for m in mods if m.startswith('offset:')) + soff = ops[3] + parts = ['ud%d' % base] + if re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', soff): + offset += int(soff, 0) + else: + parts.append(self.u(soff)) + vaddr = reg_range(ops[1]) + if 'idxen' in mods and 'offen' in mods: + if not vaddr or vaddr[2] != vaddr[1] + 1: + raise Unsupported('%s idxen offen address %s' % (name, ops[1])) + parts += ['v%d * ud%d' % (vaddr[1], self.pipe.ud(('uavstride', index))), self.u('v%d' % vaddr[2])] + elif 'idxen' in mods: + parts.append('%s * ud%d' % (self.u(ops[1]), self.pipe.ud(('uavstride', index)))) + elif 'offen' in mods: + parts.append(self.u(ops[1])) + data = reg_range(ops[0]) + if not data or data[2] - data[1] + 1 != count: raise Unsupported('%s data %s' % (name, ops[0])) - if idxen and offen: - vaddr = reg_range(ops[1]) - if not vaddr or vaddr[0] != 'v' or vaddr[2] - vaddr[1] != 1 or vaddr[2] > 255: - raise Unsupported('%s vaddr %s for idxen offen' % (name, ops[1])) - idx_expr, voff_expr = self.u('v%d' % vaddr[1]), self.u('v%d' % vaddr[2]) - elif idxen: - vaddr = reg_range(ops[1]) - if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: - raise Unsupported('%s vaddr %s for idxen' % (name, ops[1])) - idx_expr, voff_expr = self.u(ops[1]), '0u' - elif offen: + values = [self.u('v%d' % (data[1] + i)) for i in range(count)] + ['0u'] * (4 - count) + self.pipe.notes.add('typed UAV store (x2w_fmt_store: 32-bit channel formats only)') + call = 'x2w_fmt_store(%s, a, ud%d, uint4(%s), %du);' % (u, w3, ', '.join(values), count) + self.emit('a = %s;' % ' + '.join(parts + ['%d' % offset])) + self.emit(call if self.exec_known else 'if (exec & 1) %s' % call) + + def op_buffer_store_format_x(self, ops, mods): + self.format_store(ops, mods, 1, 'buffer_store_format_x') + + def op_buffer_store_format_xy(self, ops, mods): + self.format_store(ops, mods, 2, 'buffer_store_format_xy') + + def op_buffer_store_format_xyz(self, ops, mods): + self.format_store(ops, mods, 3, 'buffer_store_format_xyz') + + def op_buffer_store_format_xyzw(self, ops, mods): + self.format_store(ops, mods, 4, 'buffer_store_format_xyzw') + + def store_descriptor(self, tok, words, what, stride0_ok=False, raw_conversion_ok=False): + """Resource key for a single loaded descriptor or a proven raw transformation of it.""" + rsrc = reg_range(tok) + first = self.sym.get(rsrc[1]) if rsrc and rsrc[0] == 's' and rsrc[2] - rsrc[1] == words - 1 else None + if not first or first[0] != 'desc' or first[1][0] != 'table' or first[2] is None or first[3] % 4: + raise Unsupported('%s through %s holding %s' % (what, tok, first)) + key = desc_key(first) + loaded = tuple(desc_word(first, first[3] + k) for k in range(words)) + actual = tuple(self.sym.get(rsrc[1] + k) for k in range(words)) + valid = names_one_value(first) and actual == loaded + if names_one_value(first) and stride0_ok and words == 4: + cleared = loaded[1] + ('stride0',) + valid = valid or actual == (loaded[0], cleared, *loaded[2:]) + if not valid and raw_conversion_ok: + valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',)) + if (not valid or key in getattr(self.pipe, 'other_modified', ()) + or (key in self.pipe.modified and not stride0_ok)): + raise Unsupported('%s through a modified descriptor' % what) + return key + + def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=False, allow_scalar_address=False, + raw_conversion_ok=False): + """Validate a fixed-table raw UAV descriptor, data range, byte address, and 4-byte alignment.""" + offset = 0 + glc = False + for m in mods: + if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): + offset += int(m[7:], 0) + elif m == 'glc' and allow_glc: + glc = True + elif m != 'offen': + raise Unsupported('%s modifier %s' % (kind_label, m)) + offen = 'offen' in mods + if len(ops) != 4 or (not offen and not (allow_scalar_address and glc and ops[1] == 'off')): + raise Unsupported('%s without the offen address form' % kind_label) + data = reg_range(ops[0]) + if not data or data[0] != 'v' or data[2] - data[1] != data_count - 1 or data[2] > 255: + raise Unsupported('%s data %s' % (kind_label, ops[0])) + if offen: vaddr = reg_range(ops[1]) if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: - raise Unsupported('%s vaddr %s for offen' % (name, ops[1])) - idx_expr, voff_expr = '0u', self.u(ops[1]) - else: - if ops[1] != 'off': - raise Unsupported('%s vaddr %s without idxen or offen' % (name, ops[1])) - idx_expr, voff_expr = '0u', '0u' + raise Unsupported('%s vaddr %s for offen' % (kind_label, ops[1])) + key = self.store_descriptor(ops[2], 4, kind_label, stride0_ok=True, raw_conversion_ok=raw_conversion_ok) + terms = [self.u(ops[1])] if offen else [] if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): - soff_imm = int(ops[3], 0) - if soff_imm > 0xffffffff: - raise Unsupported('%s soffset %s' % (name, ops[3])) - soff_expr = '%du' % soff_imm + if not offen: + raise Unsupported('%s off requires a scalar register soffset' % kind_label) + offset += int(ops[3], 0) else: - if self.is_lane_mask(ops[3]): - raise Unsupported('%s soffset %s is a lane mask' % (name, ops[3])) sreg = reg_range(ops[3]) if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: - raise Unsupported('%s soffset %s' % (name, ops[3])) - soff_expr = self.S(sreg[1]) - rsrc = reg_range(ops[2]) - if not rsrc or rsrc[0] != 's' or rsrc[2] - rsrc[1] != 3 or rsrc[2] > 105: - raise Unsupported('%s descriptor %s' % (name, ops[2])) - key = self.store_descriptor(ops[2], 4, name, stride0_ok=False) - first = self.sym.get(rsrc[1]) - if getattr(self, 'past_entry', False) and not self.formatted_descriptor_from_block(rsrc, first): - raise Unsupported('%s requires descriptor words proven in the entry block or a local table load' % name) - uav = self.pipe.uav(key, 'raw') - uav_index = self.pipe.uavs[key]['index'] - word3 = 'ud%d' % self.pipe.ud(('uav_descword3', uav_index)) - stride = 'ud%d' % self.pipe.ud(('uav_stride', uav_index)) - num_records = 'ud%d' % self.pipe.ud(('uav_numrecords', uav_index)) - val_expr = self.u(ops[0], low16_only=True) - self.pipe.uses_store_d16_x = True - call = 'store_format_d16_x(%s, %s, %s, %s, %s, %s, %s, %du, %s);' % ( - uav, word3, stride, num_records, idx_expr, voff_expr, soff_expr, imm_offset, val_expr) - self.emit(call if self.exec_known else 'if (exec & 1) ' + call) + raise Unsupported('buffer soffset %s' % ops[3]) + terms.append(self.S(sreg[1])) + if offset % 4: + raise Unsupported('%s at unaligned immediate offset %d' % (kind_label, offset)) + terms.append(str(offset)) + return data, self.pipe.uav(key), '(%s) & 0xfffffffcu' % ' + '.join(terms), glc - def op_tbuffer_load_format_x(self, ops, mods): - self.tbuffer(ops, mods, 1) + def compute_buffer_store(self, ops, mods, count=1): + # Compute-stage store in the offen form: per-lane byte VGPR plus the scalar offset and the 12-bit immediate, + # through a descriptor read from a fixed root-table slot, to a RWByteAddressBuffer (manifest `uav` line). + # Like the loads, this assumes a raw descriptor (no swizzle or stride). Out-of-range stores: assumes a future + # runtime sizes the view to the descriptor's range so both sides drop them; nothing binds or checks that yet. + if self.kind != 'cs': + raise Unsupported('buffer_store_dword' + ('x%d' % count if count > 1 else '')) # the unknown-op refusal + src, uav, address, _ = self.raw_table_uav_store('buffer store', ops, mods, count, raw_conversion_ok=True) + words = [self.u('v%d' % n) for n in range(src[1], src[2] + 1)] + data = words[0] if count == 1 else 'uint%d(%s)' % (count, ', '.join(words)) + # Store* needs a multiple of four. As in #2059, the run-time part (VGPR and register soffset) is rounded down: + # an assumption that a dword access ignores the low two address bits, not a measurement. + self.emit('a = %s;' % address) + store = '%s.Store%s(a, %s);' % (uav, '' if count == 1 else count, data) + self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) - def op_tbuffer_load_format_xy(self, ops, mods): - self.tbuffer(ops, mods, 2) + def op_buffer_store_dword(self, ops, mods, count=1): + if getattr(self, 'kind', None) == 'cs': + return self.compute_buffer_store(ops, mods, count) + Stage.buffer_store(self, ops, mods, count, 'buffer_store_dword' + ('x%d' % count if count > 1 else '')) - def op_tbuffer_load_format_xyz(self, ops, mods): - self.tbuffer(ops, mods, 3) + def op_buffer_store_dwordx2(self, ops, mods): + if getattr(self, 'kind', None) == 'cs': + return self.compute_buffer_store(ops, mods, 2) + self.buffer_store(ops, mods, 2, 'buffer_store_dwordx2') - def op_tbuffer_load_format_xyzw(self, ops, mods): - self.tbuffer(ops, mods, 4) + def op_buffer_store_dwordx3(self, ops, mods): + if getattr(self, 'kind', None) == 'cs': + return self.compute_buffer_store(ops, mods, 3) + self.buffer_store(ops, mods, 3, 'buffer_store_dwordx3') + + def op_buffer_store_dwordx4(self, ops, mods): + if getattr(self, 'kind', None) == 'cs': + return self.compute_buffer_store(ops, mods, 4) + self.buffer_store(ops, mods, 4, 'buffer_store_dwordx4') + + def op_buffer_load_format_x(self, ops, mods): + self.format_load(ops, mods, 1, 'buffer_load_format_x') + + def op_buffer_load_format_xy(self, ops, mods): + self.format_load(ops, mods, 2, 'buffer_load_format_xy') + + def op_buffer_load_format_xyz(self, ops, mods): + self.format_load(ops, mods, 3, 'buffer_load_format_xyz') + + def op_buffer_load_format_xyzw(self, ops, mods): + self.format_load(ops, mods, 4, 'buffer_load_format_xyzw') def image(self, ops, mods, how): - if getattr(self, 'kind', None) == 'cs' and 'd16' in mods: - raise Unsupported('compute d16 image load requires validated SRV formats') - # Every image form reads vdata, an address and a descriptor, so a shorter operand list would reach - # ops[1] or ops[2] as an index error rather than a refusal. Samplers are checked further down, where - # the form decides whether one is required. + packed_load = how in ('load', 'load_mip') and 'd16' in mods if len(ops) < 3: - raise Unsupported('image instruction with %d operands, expected at least 3' % len(ops)) + raise Unsupported('image instruction requires three operands') + if packed_load and (self.kind == 'cs' or self.round16): + raise Unsupported('d16 image load requires validated SRV formats and round-to-nearest') dst = reg_range(ops[0]) dims = [m for m in mods if m.startswith('dim:')] dmasks = [m for m in mods if m.startswith('dmask:')] @@ -4547,166 +4457,155 @@ def image(self, ops, mods, how): raise Unsupported('image instruction without %s' % ('dim:' if not dims else 'dmask:')) dim = dims[0][4:] dmask = int(dmasks[0][6:], 0) - kinds = {'SQ_RSRC_IMG_1D': 'tex1d', 'SQ_RSRC_IMG_2D': 'tex2d', 'SQ_RSRC_IMG_3D': 'tex3d', 'SQ_RSRC_IMG_2D_ARRAY': 'tex2da'} + kinds = {'SQ_RSRC_IMG_1D': 'tex1d', 'SQ_RSRC_IMG_2D': 'tex2d', 'SQ_RSRC_IMG_3D': 'tex3d', + 'SQ_RSRC_IMG_2D_ARRAY': 'tex2da'} if dim not in kinds: raise Unsupported('image dimension %s' % dim) # A 2D array takes the slice as its third address component, where a volume takes z. Sample and - # Load on a Texture2DArray take it in the same place, so only the declared type differs. - one = dim == 'SQ_RSRC_IMG_1D' - three = dim in ('SQ_RSRC_IMG_3D', 'SQ_RSRC_IMG_2D_ARRAY') + # Load on a Texture2DArray take it in the same place, so only the declared type differs. A 1D image has + # the one coordinate (x for a load, u for a sample), bound as a Texture1D (manifest kind tex1d). + axes = {'SQ_RSRC_IMG_1D': 1, 'SQ_RSRC_IMG_2D': 2}.get(dim, 3) coords = ops[1] if coords.startswith('['): cs = [c.strip() for c in coords[1:-1].split(',')] else: r = reg_range(coords) cs = ['v%d' % n for n in range(r[1], r[2] + 1)] - if one and (how != 'sample' or len(cs) != 1 or not dmask or any(not m.startswith(('dim:', 'dmask:')) for m in mods)): - raise Unsupported('unverified 1D image sample address or modifiers') - lod = bias = None - if how in ('l', 'b'): - # image_sample_l: the address dwords are the coordinates and then the explicit level. image_sample_b: - # the RDNA 2 ISA (section 8.2.5, "{ offset } { bias } { z-compare } { derivative } { body }") puts one - # float bias dword BEFORE the coordinates. Offsets, clamp and derivatives would add dwords or modifiers - # this lowering does not read, so they are refused. Only the cache-policy + # Every form takes only dim, dmask, the cache-policy bits and, for the loads, unorm (a load addresses texels by + # integer coordinates either way) and a16. a16 packs the 16-bit address components two to a dword, the first + # in the low half (LLVM SIISelLowering packImage16bitOpsToDwords): unsigned texel coordinates for a load and + # binary16 coordinates for a sample. d16, tfe, lwe and r128 change the result or resource layout and are + # refused, as is any modifier not named here. + # (image_sample_l and image_load_mip check their own modifier lists below.) + allowed = ('dlc', 'glc', 'slc', 'a16') + (('unorm', 'd16') if how == 'load' else ('d16',) if how in ('sample', 'lz') else ()) + if how == 'get_lod': + allowed = ('dlc', 'glc', 'slc') + for m in mods: + if how in ('sample', 'lz', 'load', 'b', 'd', 'get_lod') and not (m.startswith(('dim:', 'dmask:')) or m in allowed): + raise Unsupported('image_%s modifier %s' % (how, m)) + a16 = 'a16' in mods + bias = None + if how == 'b': + # image_sample_b: the LOD bias is the first address dword, before the coordinates (LLVM + # AMDGPUImageDimIntrinsics sample_b: ExtraAddrArgs [bias]). With a16 it would be a 16-bit value packed + # into its own dword, not modelled here. + if a16 or dmask == 0 or len(cs) != axes + 1: + raise Unsupported('image_sample_b form %s %s' % (', '.join(ops), ' '.join(mods))) + bias, cs = cs[0], cs[1:] + grads = None + if how == 'd': + # image_sample_d: the gradients come first, ddh for each coordinate c (s, t, r) then ddv, and then + # the coordinates and the slice (LLVM IntrinsicsAMDGPU.td AMDGPUDimProps.GradientArgs, AddrArgs order + # ExtraAddrArgs, GradientArgs, CoordSliceArgs). h is the horizontal (x) and v the vertical (y) screen + # direction: SampleGrad's ddx and ddy. A 2D array has 2D gradients. With a16 the gradients would be + # packed too, not modelled here. + n = {'SQ_RSRC_IMG_1D': 1, 'SQ_RSRC_IMG_2D': 2, 'SQ_RSRC_IMG_3D': 3, 'SQ_RSRC_IMG_2D_ARRAY': 2}[dim] + if a16 or dmask == 0 or len(cs) != 2 * n + axes: + raise Unsupported('image_sample_d form %s %s' % (', '.join(ops), ' '.join(mods))) + grads, cs = (cs[:n], cs[n:2 * n]), cs[2 * n:] + if a16: + if len(cs) < (axes + 1) // 2: + raise Unsupported('a16 image address with %d registers' % len(cs)) + # component i is the (i % 2) half of address dword i // 2; unpacked to one 32-bit value each + cs = [('a16', cs[i // 2], i % 2) for i in range(axes)] + lod = None + if how == 'l': + # Address dwords are the coordinates and then the explicit level; offsets, bias, clamp and derivatives + # would add dwords or modifiers this lowering does not read, so they are refused. Only the cache-policy # bits (glc, slc, dlc), which never change the sampled value, are accepted next to dim and dmask; # unorm, r128, tfe, lwe, a16, d16 and reserved bits would each change the address, resource or result # layout and are refused by name. - name = 'image_sample_' + how for m in mods: if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): - raise Unsupported('%s modifier %s' % (name, m)) + raise Unsupported('image_sample_l modifier %s' % m) if dmask == 0: - raise Unsupported('%s with an empty dmask' % name) - if len(cs) != (4 if three else 3): - raise Unsupported('%s with %d address registers' % (name, len(cs))) - if how == 'l': - lod, cs = cs[-1], cs[:-1] - else: - # The bias is added to the LOD derived from the coordinate derivatives of the pixel quad: only a - # pixel stage that still runs with its entry mask has them. Elsewhere the plain sample is lowered - # to level 0, which would drop the bias, so the bias form is refused instead. - if self.kind != 'ps' or not self.exec_known or len(self.blocks) > 0: - raise Unsupported('image_sample_b needs implicit derivatives: pixel stage, entry mask, no branches') - bias, cs = cs[0], cs[1:] - if how == 'get_lod': - # image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp - # (Mesa nir_texop_lod, which ACO emits as image_get_lod; GLSL textureQueryLod x/y). Only the 2D form with - # two address registers and dmask 0x1-0x3 is lowered; the cache-policy bits are the only other modifiers. - for m in mods: - if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): - raise Unsupported('image_get_lod modifier %s' % m) - if self.kind != 'ps' or dim != 'SQ_RSRC_IMG_2D' or not dmask or dmask & ~3 or len(cs) != 2: - raise Unsupported('image_get_lod form %s %s' % (', '.join(ops), ' '.join(mods))) - # Both HLSL calls take implicit derivatives, so the rule of image_sample_b applies. - if not self.exec_known or len(self.blocks) > 0: - raise Unsupported('image_get_lod needs implicit derivatives: pixel stage, entry mask, no branches') + raise Unsupported('image_sample_l with an empty dmask') + if len(cs) != axes + 1: + raise Unsupported('image_sample_l with %d address registers' % len(cs)) + lod, cs = cs[-1], cs[:-1] desc_key = self.descriptor(ops[2]) tex = self.pipe.resource(desc_key, kinds[dim]) + if packed_load: + if desc_key not in self.pipe.resources: + raise Unsupported('d16 load requires a bound SRV') + res = self.pipe.resources[desc_key] + if not dst or dst[0] != 'v' or dst[2] > 255 or dst[2] - dst[1] + 1 != (dmask.bit_count() + 1) // 2: + raise Unsupported('image_%s d16 destination %s for dmask %#x' % (how, ops[0], dmask)) + fmt = self.pipe.srv_formats.get(res['index']) + if fmt is not None and fmt not in D16_EXACT_SRV_FORMATS: + raise Unsupported('image_%s d16 unsupported SRV format %d' % (how, fmt)) + if how in ('load', 'load_mip'): # image_load_mip addresses x, y, [slice or z] and then the mip, so a 2D array is four registers - # and Texture2DArray.Load takes int4(x, y, slice, mip) like a volume's int4(x, y, z, mip). - axes = 3 if three else 2 - packed_2d = how == 'load' and dim == 'SQ_RSRC_IMG_2D' and 'a16' in mods - packed_d16 = how in ('load', 'load_mip') and 'd16' in mods - allowed = ('unorm', 'glc', 'slc', 'dlc') - if packed_2d: - allowed += ('a16',) - if packed_d16: - allowed += ('d16',) - unsupported = any(not m.startswith(('dim:', 'dmask:')) and m not in allowed for m in mods) - expected_addr = 1 if packed_2d else (axes + 1 if how == 'load_mip' else axes) - wrong_address = len(cs) != expected_addr - if unsupported or wrong_address or not dmask: - raise Unsupported('image_%s address or modifiers: %s' % (how, ' '.join(mods))) - if packed_d16: - op_name = 'image_' + how - expected_dst = (bin(dmask).count('1') + 1) // 2 - if not dst or dst[0] != 'v' or dst[2] - dst[1] + 1 != expected_dst or dst[2] > 255: - raise Unsupported('%s d16 destination %s for dmask %#x' % (op_name, ops[0], dmask)) - res = self.pipe.resources[desc_key] - if res['index'] in self.pipe.srv_formats: - fmt = self.pipe.srv_formats[res['index']] - if fmt not in D16_EXACT_SRV_FORMATS: - raise Unsupported('%s d16 unsupported SRV format %d' % (op_name, fmt)) - if packed_2d: - packed = self.u(cs[0]) - address = ['%s & 0xffffu' % packed, '%s >> 16' % packed] - else: - address = [self.u(c) for c in cs[:axes]] - mip = self.u(cs[axes]) if how == 'load_mip' else '0' - call = '%s.Load(int%d(%s))' % (tex, axes + 1, ', '.join(address + [mip])) + # and Texture2DArray.Load takes int4(x, y, slice, mip) like a volume's int4(x, y, z, mip); a Texture1D + # takes int2(x, mip). + mip = '0' + if how == 'load_mip': + unsupported = [m for m in mods if not m.startswith(('dim:', 'dmask:')) + and m not in ('unorm', 'glc', 'slc', 'dlc', 'd16')] + if unsupported or len(cs) != axes + 1 or not dmask: + raise Unsupported('image_load_mip address or modifiers: %s' % ' '.join(mods)) + mip = self.u(cs[axes]) + if len(cs) < axes: + raise Unsupported('image_%s with %d address registers' % (how, len(cs))) + address = [self.a16_u(c) if isinstance(c, tuple) else self.u(c) for c in cs[:axes]] + [mip] + call = '%s.Load(int%d(%s))' % (tex, axes + 1, ', '.join(address)) else: - packed_2d = False - if not one and how in ('sample', 'lz'): - op_name = 'image_sample' if how == 'sample' else 'image_sample_lz' - packed_2d = dim == 'SQ_RSRC_IMG_2D' and 'a16' in mods - allowed = ('dlc', 'glc', 'slc') + (('a16',) if packed_2d else ()) - for m in mods: - if not (m.startswith(('dim:', 'dmask:')) or m in allowed): - raise Unsupported('%s modifier %s' % (op_name, m)) - if not dmask: - raise Unsupported('%s with an empty dmask' % op_name) - expected = 1 if packed_2d else (3 if three else 2) - if len(cs) != expected: - raise Unsupported('%s with %d address registers' % (op_name, len(cs))) heap = self.heap_sampler(ops[3]) words = None if heap else self.const_words(ops[3]) - name = 'image_sample' + ('' if how == 'sample' else '_' + how) - if how == 'b': - # The guest clamps the biased LOD to the sampler's MIN_LOD and MAX_LOD. Only a constant descriptor - # can be read here, and only its limits are carried to the static sampler (line smpl), so a sampler - # from the heap or from a register is refused: its limits and bias cannot be shown to be irrelevant. - words = self.sample_b_sampler(heap, words) - smp = self.pipe.sampler(tuple(words), lod_limits=True) - elif how == 'get_lod': - # The clamped result depends on the sampler's MIN_LOD, MAX_LOD and bias, so the sampler must be a - # constant descriptor under the same validation as image_sample_b, with its limits carried. - if heap or not words or self.default_sampler_words(words): - raise Unsupported('image_get_lod with a sampler that is not constant (LOD limits and bias unknown)') - smp = self.pipe.sampler(tuple(self.lod_sampler_words('image_get_lod', words)), lod_limits=True) - elif how in ('sample', 'l', 'lz') and (heap or (words and self.default_sampler_words(words))): - # A heap sampler, or the fixed default that stands in for one, keeps its unbounded static LOD range: the - # descriptor is read at run time, so its MIN_LOD, MAX_LOD and bias are not validated here (#2221). - self.pipe.lod_unvalidated.add(name) - smp = heap or self.pipe.sampler(tuple(words)) - elif how in ('sample', 'l', 'lz') and words: - # A constant descriptor carries its LOD limits like image_sample_b, under the same bias and range - # validation. A mip filter of 0 (base level only) keeps the ordinary sampler, as before: refusing it - # would drop every pipeline with an all-zero inline sampler, and only the bias form needs it refused. - self.lod_sampler_words(name, words, mip_filter_none_ok=True) - smp = self.pipe.sampler(tuple(words), lod_limits=bool((words[2] >> 26) & 3)) - else: - smp = heap or self.pipe.sampler(tuple(words) if words else self.descriptor(ops[3])) - if packed_2d: - packed = self.u(cs[0]) - uv = 'float2(f16tof32(%s), f16tof32(%s >> 16))' % (packed, packed) - elif one: - uv = self.f(cs[0]) - elif three: - uv = 'float3(%s, %s, %s)' % (self.f(cs[0]), self.f(cs[1]), self.f(cs[2])) - else: - uv = 'float2(%s, %s)' % (self.f(cs[0]), self.f(cs[1])) - if how == 'sample' and self.kind == 'cs': - # A compute lane has no pixel quad to supply derivatives; level 0 would be a guess. - raise Unsupported('image_sample with implicit LOD in a compute program') + smp = heap or self.pipe.sampler(tuple(words) if words else self.descriptor(ops[3])) + if len(cs) < axes: + raise Unsupported('image_%s with %d address registers' % (how, len(cs))) + fs = [self.a16_f(c) if isinstance(c, tuple) else self.f(c) for c in cs[:axes]] + uv = fs[0] if axes == 1 else 'float%d(%s)' % (axes, ', '.join(fs)) if how == 'l': call = '%s.SampleLevel(%s, %s, %s)' % (tex, smp, uv, self.f(lod)) elif how == 'b': - # SampleBias adds the bias to the implicit LOD, like the ISA's _B suffix ("Add this BIAS to the LOD - # computed"). The sampler's LOD limits are carried by the smpl line; its LOD bias is refused in - # sample_b_sampler. + # SampleBias takes implicit derivatives like Sample, so it is lowered only where Sample is (below); + # the level-0 fallback Sample uses elsewhere would ignore the bias. + if self.kind != 'ps': + raise Unsupported('image_sample_b outside straight-line code with every lane active') + if not self.exec_known or len(self.blocks) > 0: + # X2W_PS_QUAD_DIVERGENT=1 (see quad_divergent): taken in forward control flow, not in a loop + if not self.quad_divergent or self.has_loop: + raise Unsupported('image_sample_b outside straight-line code with every lane active') + self.quad_divergent_used.append(self.pc) call = '%s.SampleBias(%s, %s, %s)' % (tex, smp, uv, self.f(bias)) elif how == 'get_lod': - # HLSL CalculateLevelOfDetail (clamped) and CalculateLevelOfDetailUnclamped (SM 4.1+). Which clamps - # each side applies besides the sampler's (the view's mip range) is assumed to agree. + # image_get_lod: [0] the LOD the sample would use, clamped, [1] the computed LOD before the clamp + # (Mesa nir_texop_lod, which ACO emits as image_get_lod and returns as is; GLSL textureQueryLod x/y). + # HLSL CalculateLevelOfDetail / CalculateLevelOfDetailUnclamped (HLSL intrinsics, SM 4.1+). Both use implicit + # derivatives, so the control-flow rule of image_sample_b applies. Which clamps each side applies + # (sampler MIN/MAX_LOD, the view's mip range) is ASSUMED to agree; the runtime carries the sampler's + # LOD fields with X2W_SAMPLER_LOD=1. + if self.kind != 'ps' or dim != 'SQ_RSRC_IMG_2D' or dmask & ~3 or not dmask or len(cs) != 2 or a16: + raise Unsupported('image_get_lod form %s %s' % (', '.join(ops), ' '.join(mods))) + if not self.exec_known or len(self.blocks) > 0: + if not self.quad_divergent or self.has_loop: + raise Unsupported('image_get_lod outside straight-line code with every lane active') + self.quad_divergent_used.append(self.pc) call = 'float4(%s.CalculateLevelOfDetail(%s, %s), %s.CalculateLevelOfDetailUnclamped(%s, %s), 0.0, 0.0)' % ( tex, smp, uv, tex, smp, uv) + elif how == 'd': + # explicit gradients: no implicit derivatives, so any control flow and any exec state + ddx, ddy = (', '.join(self.f(c) for c in g) for g in grads) + if len(grads[0]) > 1: + ddx, ddy = 'float%d(%s)' % (len(grads[0]), ddx), 'float%d(%s)' % (len(grads[0]), ddy) + call = '%s.SampleGrad(%s, %s, %s, %s)' % (tex, smp, uv, ddx, ddy) elif how == 'lz' or not self.exec_known or self.kind != 'ps' or len(self.blocks) > 0: call = '%s.SampleLevel(%s, %s, 0)' % (tex, smp, uv) else: call = '%s.Sample(%s, %s)' % (tex, smp, uv) self.emit('t = %s;' % call) - if how in ('load', 'load_mip') and 'd16' in mods: + # An image read with no implicit derivatives (load, level 0, explicit level) of a bound texture (rN) through a + # fixed sampler (qN), at lane-invariant coordinates, returns the same texel or filtered value in every lane. + if how in ('load', 'load_mip', 'lz', 'l') and hasattr(self, 'lane_s') and re.match(r'r\d+\b', call): + expr = re.sub(r'\bq\d+\b', '0', call) + expr = re.sub(r'\.(Load|SampleLevel)\(', '(', expr) + expr = re.sub(r'\b(int|uint|float)[234]\(', '(', expr) + self.t_invariant = self.lane_invariant(expr) + n = dst[1] + if packed_load: res = self.pipe.resources[desc_key] res['d16_exact'] = True mode_arg = 'ud%d' % self.pipe.ud(('d16unorm16', res['index'])) @@ -4716,12 +4615,33 @@ def image(self, ops, mods, how): odd_tail = i + 1 == len(halves) expr = halves[i] if odd_tail else '%s | (%s << 16)' % (halves[i], halves[i + 1]) self.set_v(dst[1] + i // 2, expr, low16_only=odd_tail) - else: - n = dst[1] - for bit, comp in enumerate('xyzw'): - if dmask & (1 << bit): - self.set_v(n, 'U(t.%s)' % comp) - n += 1 + return + elif 'd16' in mods: + if self.round16: + raise Unsupported('image_%s d16 under s_round_mode f16/f64 toward zero' % how) + # Packed D16 (gfx9+, LLVM GCNSubtarget hasPackedD16VMem; SIISelLowering adjustLoadValueType): each enabled + # channel of the filtered result is converted to binary16 and two go in one VGPR, the first channel in + # the low half; the high half after an odd channel count is written as 0 here (undefined in hardware). + # Only the sampling forms take it: their result is a float whatever the texel format. + comps = ['f32tof16(t.%s)' % c for bit, c in enumerate('xyzw') if dmask & (1 << bit)] + if not comps or dst[2] - dst[1] + 1 != (len(comps) + 1) // 2: + raise Unsupported('image_%s d16 with dmask %#x into %s' % (how, dmask, ops[0])) + for i in range(0, len(comps), 2): + self.set_v(n, comps[i] if i + 1 == len(comps) else '%s | (%s << 16)' % (comps[i], comps[i + 1])) + n += 1 + return + for bit, comp in enumerate('xyzw'): + if dmask & (1 << bit): + self.set_v(n, 'U(t.%s)' % comp) + n += 1 + + def a16_u(self, component): + _, reg, half = component + return '(%s >> 16)' % self.u(reg) if half else '(%s & 0xffffu)' % self.u(reg) + + def a16_f(self, component): + _, reg, half = component + return 'f16tof32(%s)' % ('%s >> 16' % self.u(reg) if half else self.u(reg)) def image_compare(self, ops, mods, how): """image_sample_c and image_sample_c_lz: a 2D or 2D-array depth comparison returning one float. @@ -4766,8 +4686,30 @@ def image_compare(self, ops, mods, how): if words is None: raise Unsupported('%s with a sampler that is not constant' % base) import pixel_aot + checked = list(words) + if how == 'c_lz' and (words[2] >> 28) == 1: + # Word 2 bit 28 is MIP_POINT_PRECLAMP (Mesa gfx10-rsrc.json SQ_IMG_SAMP_WORD2): it changes how a point + # mip filter clamps the LOD before rounding it to a level. c_lz samples level zero with MIN_LOD 0 (the + # decoder refuses any other MIN_LOD), so no LOD reaches the mip selection and the bit cannot change the + + # Mesa (bb59ce45 ac_build_sampler_descriptor) never sets the bit, so no open driver documents more. + checked[2] &= ~(1 << 28) + clamp_xy = (words[0] & 7, words[0] >> 3 & 7) + if 6 in clamp_xy and set(clamp_xy) <= {2, 6}: + # SQ_TEX_CLAMP_BORDER (6, Mesa radv_sampler.c maps VK CLAMP_TO_BORDER to it) in X and/or Y: outside + # [0, 1] the texel is the border colour, BORDER_COLOR_TYPE (word 3 bits 31:30; 0 transparent black, + # 1 opaque black, 2 opaque white, Mesa ac_descriptors.c) and the comparison runs against its red + # channel; D3D12 BORDER with that static colour does the same (Vulkan orders texel replacement before + # the depth compare as well). Type 3 (a border colour table entry, BORDER_COLOR_PTR) is refused. The + # runtime carries the colour with X2W_SAMPLER_LOD=1 (sampler_lod_fields); without it the static + # sampler's border is transparent black, which is exact for type 0 only. The smpc manifest line keeps + # the original words (the runtime's decode_sampler maps 6 to D3D12_TEXTURE_ADDRESS_MODE_BORDER); the + # other fields of the contract (filters, compare, LOD, TRUNC_COORD) are checked with CLAMP_LAST_TEXEL. + if words[3] >> 30 == 3: + raise Unsupported('%s sampler: border colour from the border colour table (BORDER_COLOR_TYPE 3)' % base) + checked[0] = checked[0] & ~0x3f | 2 | 2 << 3 try: - pixel_aot.comparison_sampler_state(tuple(words), level_zero=how == 'c_lz', allow_border=True) + pixel_aot.comparison_sampler_state(tuple(checked)) except ValueError as error: raise Unsupported('%s sampler: %s' % (base, error)) tex = self.pipe.resource(self.descriptor(ops[2]), 'tex2da' if array else 'tex2d') @@ -4785,6 +4727,44 @@ def image_compare(self, ops, mods, how): call = '%s.SampleCmpLevelZero(%s)' % (tex, args) self.set_v(reg_range(ops[0])[1], 'U(%s)' % call) + def op_image_gather4_lz(self, ops, mods): + """image_gather4_lz on a 2D texture: the one channel dmask names, from the 2x2 footprint at level 0. + + The four result dwords are the texels in the order Gather*() returns them, (u0,v1), (u1,v1), (u1,v0), + (u0,v0): gather4 is the D3D Gather operation, and compilers map Gather's four results straight onto the + four destination VGPRs. Gather always reads the most detailed level, which is what _lz names. Offsets + (_o), compare (_c), an explicit or biased level, other dimensions and result-layout modifiers (d16, tfe, + lwe, a16, unorm, r128) would change the address or the result and are refused by name. + """ + for m in mods: + if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): + raise Unsupported('image_gather4_lz modifier %s' % m) + dims = [m[4:] for m in mods if m.startswith('dim:')] + masks = [int(m[6:], 0) for m in mods if m.startswith('dmask:')] + if dims != ['SQ_RSRC_IMG_2D'] or len(masks) != 1: + raise Unsupported('image_gather4_lz on %s' % (dims or 'no dim')) + channel = {1: 'Red', 2: 'Green', 4: 'Blue', 8: 'Alpha'}.get(masks[0]) + if channel is None: + raise Unsupported('image_gather4_lz dmask %#x: gather reads exactly one channel' % masks[0]) + dst = reg_range(ops[0]) + if len(ops) != 4 or not dst or dst[0] != 'v' or dst[2] - dst[1] != 3: + raise Unsupported('image_gather4_lz operands %s' % ', '.join(ops)) + coords = ops[1] + if coords.startswith('['): + cs = [c.strip() for c in coords[1:-1].split(',')] + else: + r = reg_range(coords) + cs = ['v%d' % n for n in range(r[1], r[2] + 1)] + if len(cs) != 2: + raise Unsupported('image_gather4_lz with %d address registers' % len(cs)) + tex = self.pipe.resource(self.descriptor(ops[2]), 'tex2d') + heap = self.heap_sampler(ops[3]) + words = None if heap else self.const_words(ops[3]) + smp = heap or self.pipe.sampler(tuple(words) if words else self.descriptor(ops[3])) + self.emit('t = %s.Gather%s(%s, float2(%s, %s));' % (tex, channel, smp, self.f(cs[0]), self.f(cs[1]))) + for i, comp in enumerate('xyzw'): + self.set_v(dst[1] + i, 'U(t.%s)' % comp) + def op_image_sample_c(self, ops, mods): self.image_compare(ops, mods, 'c') @@ -4797,9 +4777,18 @@ def op_image_sample_c_l(self, ops, mods): def op_image_sample(self, ops, mods): self.image(ops, mods, 'sample') + def op_image_sample_b(self, ops, mods): + self.image(ops, mods, 'b') + + def op_image_sample_d(self, ops, mods): + self.image(ops, mods, 'd') + def op_image_sample_lz(self, ops, mods): self.image(ops, mods, 'lz') + def op_image_get_lod(self, ops, mods): + self.image(ops, mods, 'get_lod') + def op_image_sample_l(self, ops, mods): self.image(ops, mods, 'l') @@ -4838,12 +4827,6 @@ def lod_sampler_words(self, name, words, mip_filter_none_ok=False): % (name, words[1] & 0xfff, (words[1] >> 12) & 0xfff)) return words - def op_image_sample_b(self, ops, mods): - self.image(ops, mods, 'b') - - def op_image_get_lod(self, ops, mods): - self.image(ops, mods, 'get_lod') - def op_image_load(self, ops, mods): self.image(ops, mods, 'load') @@ -4911,77 +4894,11 @@ def op_image_store(self, ops, mods): cs = ['v%d' % n for n in range(r[1], r[2] + 1)] if r and r[0] == 'v' else [] if len(cs) != 2: raise Unsupported('%s with %d address registers: x and y expected' % (name, len(cs))) - words = [self.u('v%d' % n) for n in range(data[1], data[2] + 1)] - if self.kind == 'cs': - if not all(re.fullmatch(r'v\d+', c) and int(c[1:]) <= 255 for c in cs): - raise Unsupported('compute image_store requires full-width VGPR coordinates') - key = self.fixed_table_image(ops[2], name) - else: - key = self.descriptor(ops[2]) - if d16: - # RDNA 2 ISA §8.2.5: RG occupy VDATA, BA occupy VDATA+1, low half first. - rgba = ['f16tof32(%s & 0xffffu), f16tof32(%s >> 16)' % (word, word) for word in words] - value = 'float4(%s)' % ', '.join(rgba) - else: - value = 'asfloat(uint4(%s))' % ', '.join(words) - image = self.pipe.uav(key, 'tex2d') + image = self.pipe.image_uav(self.descriptor(ops[2]), 'tex2d') + value = 'asfloat(uint4(%s))' % ', '.join(self.u('v%d' % n) for n in range(data[1], data[1] + 4)) body = '%s[uint2(%s, %s)] = %s;' % (image, self.u(cs[0]), self.u(cs[1]), value) self.emit(body if self.exec_known else 'if (exec & 1) ' + body) - def gather_2d_setup(self, name, ops, mods, addr_count, addr_label, *, mip_preclamp): - if self.kind not in ('ps', 'cs') or len(ops) != 4: - raise Unsupported('%s requires a pixel or compute stage and four operands' % name) - for modifier in mods: - if not (modifier.startswith(('dim:', 'dmask:')) or modifier in ('dlc', 'glc', 'slc')): - raise Unsupported('%s modifier %s' % (name, modifier)) - if [m for m in mods if m.startswith('dim:')] != ['dim:SQ_RSRC_IMG_2D']: - raise Unsupported('%s requires a 2D texture' % name) - channels = {'dmask:0x1': ('Red', 0), 'dmask:0x2': ('Green', 1), 'dmask:0x4': ('Blue', 2), 'dmask:0x8': ('Alpha', 3)} - masks = [m for m in mods if m.startswith('dmask:')] - if len(masks) != 1 or masks[0] not in channels: - raise Unsupported('%s requires a one-hot dmask' % name) - dst, addr, sampler = (reg_range(ops[i]) for i in (0, 1, 3)) - if not dst or dst[0] != 'v' or dst[2] - dst[1] != 3 or dst[2] > 255: - raise Unsupported('%s requires four destination registers' % name) - if not addr or addr[0] != 'v' or addr[2] - addr[1] + 1 != addr_count or addr[2] > 255: - raise Unsupported('%s requires %s' % (name, addr_label)) - words = self.const_words(ops[3]) if sampler and sampler[0] == 's' and sampler[2] - sampler[1] == 3 else None - if words is None: - raise Unsupported('%s requires a constant sampler' % name) - from pixel_aot import check_gather_sampler - profiled = gather_2d_profile_words(words) - if not mip_preclamp and (words[2] & (1 << 28)): - profiled = (profiled[0], profiled[1], profiled[2] | (1 << 28), profiled[3]) - try: - # _lz reads mip zero of the bound view; _l checks all other sampler fields against - # the 2D gather profile and enforces words[1] MAX_LOD plus view mip bounds in HLSL. - check_gather_sampler(profiled, 1, comparison=False) - except ValueError as error: - raise Unsupported('%s sampler: %s' % (name, error)) from error - key = self.fixed_table_image(ops[2], name) if self.kind == 'cs' else self.descriptor(ops[2]) - tex = self.pipe.resource(key, 'tex2d') - return dst, addr, words, channels[masks[0]], tex - - def op_image_gather4_lz(self, ops, mods): - dst, addr, words, (channel_name, _), tex = self.gather_2d_setup( - 'image_gather4_lz', ops, mods, 2, 'two contiguous address registers', mip_preclamp=True) - smp = self.pipe.sampler(tuple(words)) - u, v = (self.f('v%d' % i) for i in range(addr[1], addr[2] + 1)) - self.emit('t = %s.Gather%s(%s, float2(%s, %s));' % (tex, channel_name, smp, u, v)) - for i, component in enumerate('xyzw', dst[1]): - self.set_v(i, 'U(t.%s)' % component) - - def op_image_gather4_l(self, ops, mods): - """image_gather4_l on a 2D texture with explicit LOD and a validated constant sampler.""" - dst, addr, words, (_, channel_index), tex = self.gather_2d_setup( - 'image_gather4_l', ops, mods, 3, 'three contiguous address registers', mip_preclamp=False) - self.pipe.uses_gather_2d_lod = True - max_lod = ((words[1] >> 12) & 0xfff) / 256.0 - u, v, lod = (self.f('v%d' % i) for i in range(addr[1], addr[2] + 1)) - self.emit('t = gather_2d_lod(%s, float2(%s, %s), %s, %d, %sf);' % (tex, u, v, lod, channel_index, repr(max_lod))) - for i, component in enumerate('xyzw', dst[1]): - self.set_v(i, 'U(t.%s)' % component) - def op_image_gather4_c_lz(self, ops, mods): """image_gather4_c_lz: four red-channel depth comparisons at view mip zero. @@ -5067,17 +4984,90 @@ def op_v_cvt_pk_u8_f32(self, ops, mods): self.set_v(dst[1], '((%s & ~(0xffu << %s)) | (((((%s - 1u) < 0x7f800000u) ? uint(round(min(%s, 255.0))) : 0u) & 0xffu) << %s))' % (rest, shift, bits, value, shift)) - def op_s_ff1_i32_b32(self, ops, mods): - if self.kind != 'cs' or mods or len(ops) != 2 or ops[1] != 'exec_lo': - raise Unsupported('s_ff1_i32_b32 requires compute exec_lo') - dst = reg_range(ops[0]) - if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: - raise Unsupported('s_ff1_i32_b32 requires one SGPR destination') - if self.past_entry or not self.exec_known: - raise Unsupported('s_ff1_i32_b32 requires the compute entry EXEC mask') - # At dispatch entry even the last partial wave starts at lane zero. - # FF1 reports its index and leaves SCC unchanged. - self.set_s(dst[1], '0u', ('const', 0)) + WATERFALL_CROSS_LANE = re.compile(r'_dpp$|permlane|readlane|writelane|readfirstlane|^s_store|^s_buffer_store|' + r'^s_atomic|^s_buffer_atomic|^s_scratch|^s_sendmsg|^s_endpgm|^s_setpc|^s_getpc|' + r'^s_swappc|^s_dcache|^exp|^s_movrel|^v_movrel|^s_setreg|^ds_gws|^s_barrier') + + def waterfall(self, s, v): + """Check that the v_readfirstlane_b32 s, v at self.pc heads a waterfall loop the one-lane model runs""" + index = {off: i for i, (off, _, _, _) in enumerate(self.ins)} + h = index[self.pc] + if h + 1 >= len(self.ins): + raise Unsupported('v_readfirstlane_b32 requires a proven uniform source') + _, _, cname, casm = self.ins[h + 1] + _, cops, cmods = parse(casm) + if (not re.fullmatch(r'v_cmpx_eq_[iu]32_e(32|64)', cname) or cmods or + sorted(cops) != sorted(['s%d' % s, 'v%d' % v])): + raise Unsupported('v_readfirstlane_b32 requires a proven uniform source') + # The loop head is the readfirstlane or a run of waits / nops just above it (LLVM places the wait for the + # index VGPR's load at the head when the load is outstanding). + t = h + while t > 0 and self.ins[t - 1][2] in ('s_waitcnt', 's_nop'): + t -= 1 + heads = {off for off, _, _, _ in self.ins[t:h + 1]} + back = [i for i, (off, _, name, asm) in enumerate(self.ins) + if i > h and name.startswith(('s_cbranch', 's_branch')) + and int(parse(asm)[1][0].split('_')[1], 16) in heads] + if len(back) != 1 or self.ins[back[0]][2] != 's_cbranch_scc1': + raise Unsupported('waterfall loop without one s_cbranch_scc1 back edge') + b = back[0] + t = index[int(parse(self.ins[b][3])[1][0].split('_')[1], 16)] + wname, wasm = self.ins[b - 1][2], self.ins[b - 1][3] + wops = parse(wasm)[1] + wide = wname == 's_andn2_wrexec_b64' + if (wname not in ('s_andn2_wrexec_b32', 's_andn2_wrexec_b64') or len(wops) != 2 or wops[0] != wops[1] or + not reg_range(wops[0]) or reg_range(wops[0])[0] != 's' or + reg_range(wops[0])[2] - reg_range(wops[0])[1] != int(wide)): + raise Unsupported('waterfall loop not closed by s_andn2_wrexec') + pending = set(range(reg_range(wops[0])[1], reg_range(wops[0])[2] + 1)) + inner = {off for off, _, _, _ in self.ins[t + 1:b + 1]} + for off, _, name, asm in self.ins: + if name.startswith(('s_cbranch', 's_branch')): + target = int(parse(asm)[1][0].split('_')[1], 16) + if target in inner or (off in inner and off != self.ins[b][0]): + raise Unsupported('waterfall loop with another branch') + body = self.ins[t:b + 1] + body_writes = set().union(*(sgpr_access(n, a)[1] for _, _, n, a in body)) + written = set() + for off, _, name, asm in body: + if off != self.pc and self.WATERFALL_CROSS_LANE.search(name): + raise Unsupported('waterfall loop body with %s' % name) + reads, writes = sgpr_access(name, asm) + if 124 in reads | writes: + raise Unsupported('waterfall loop body uses m0') + carried = (reads - written) & body_writes + if carried - pending: + raise Unsupported('waterfall loop carries s%d' % min(carried - pending)) + written |= writes + live = written - pending + # Every path from the loop exit: each of these SGPRs is written before any read. + stack, seen = [(b + 1, frozenset(live))], set() + while stack: + i, regs = stack.pop() + while regs and i < len(self.ins) and (i, regs) not in seen: + seen.add((i, regs)) + off, _, name, asm = self.ins[i] + reads, writes = sgpr_access(name, asm) + if reads & regs: + raise Unsupported('s%d read after its waterfall loop' % min(reads & regs)) + regs = regs - writes + if name == 's_endpgm' or name.startswith(('s_setpc', 's_swappc')): + break + if name.startswith(('s_cbranch', 's_branch')): + target = index.get(int(parse(asm)[1][0].split('_')[1], 16)) + if target is None: + raise Unsupported('waterfall exit path leaves the program') + stack.append((target, regs)) + if name == 's_branch': + break + i += 1 + # One pass: the lane's own iteration is the only one in which it is active, and it leaves the loop with its + # exec bit 0, so for this lane the back edge is never taken. Emitting it as a branch would leave a loop + # whose model condition repeats the first pass exactly (the one-lane state is the same each time), so a + # body that does not restore exec would spin until a guard; without the edge it runs once. + if not hasattr(self, 'waterfall_back'): + self.waterfall_back = set() + self.waterfall_back.add(self.ins[b][0]) # ---- slot 57 mesh stage: instructions mesh_skeleton() puts in place of the group-memory exchanges ---- def op_x2w_mesh_lane0(self, ops, mods): @@ -5167,21 +5157,38 @@ def op_v_mbcnt_hi_u32_b32(self, ops, mods): self.op_v_mbcnt_lo_u32_b32(ops, mods, high=True) def op_v_readfirstlane_b32(self, ops, mods): + # D = S0 of the first active lane (AMD RDNA 2 ISA; LLVM selects it for a VGPR-to-SGPR copy of a value the + # divergence analysis found uniform, SIFixSGPRCopies). With a lane-invariant source (see set_v) every + # lane's own value is that value. Branches are allowed: invariance is cleared at every branch target. src, dst = reg_range(ops[1]), reg_range(ops[0]) - past_entry = getattr(self, 'past_entry', True) - # Past the entry block of a branch-free program is only dead code after s_endpgm: nothing to recompute. - if (mods or not self.tracks_uniformity() or not dst or dst[0] != 's' or dst[1] != dst[2] or - not src or src[0] != 'v' or src[1] != src[2] or src[1] not in self.uniform_v or - (src[1] not in getattr(self, 'uniform_expr', {}) or not getattr(self, 'has_branches', False) - if past_entry else not getattr(self, 'exec_known', False))): + offsets = [off for off, _, _, _ in getattr(self, 'ins', ())] + here = getattr(self, 'pc', None) + following = self.ins[offsets.index(here) + 1][2] if here in offsets[:-1] else '' + if (not mods and dst and dst[0] == 's' and dst[1] == dst[2] and src and src[0] == 'v' and src[1] == src[2] + and src[1] not in self.uniform_v and getattr(self, 'partial_uniform', {}).get(src[1]) is None + and following.startswith('v_cmpx_eq_')): + # a waterfall loop head (see waterfall): this lane's own value + self.waterfall(dst[1], src[1]) + # An inactive lane's vM is stale (hardware never uses it: no iteration serves that lane), but the HLSL + # evaluates the body's descriptor reads in every lane, and the heap memory is a root SRV with no bounds + # check; index 0 keeps that read inside the heap. Active lanes read their own vM as hardware does. + self.set_s(dst[1], '((exec & 1) != 0 ? %s : 0u)' % self.u(ops[1])) + return + partial = getattr(self, 'partial_uniform', {}).get(src[1]) if src and src[0] == 'v' else None + if (not mods and dst and dst[0] == 's' and partial is not None and + partial['epoch'] == getattr(self, 'exec_writes', 0)): + # The source was written, in the lanes active then, from a lane-invariant value (or a chain of such + # writes, see partial_shadow), and exec has not been written since: the first active lane holds that + # value. Lanes inactive now kept an older VGPR value, but the SGPR is the wave's, so every lane takes the + # value itself, from shadows assigned in all lanes at the writes. (With no active lane the hardware + # reads lane 0; that case is not modelled.) + self.materialize_shadow(partial) + self.set_s(dst[1], 'xv%d' % src[1]) + return + if (mods or not self.exec_known or not dst or dst[0] != 's' or + not src or src[0] != 'v' or src[1] not in self.uniform_v): raise Unsupported('v_readfirstlane_b32 requires a proven uniform source') - if past_entry: - # The first active lane ran the definition: no join, EXEC write or overwrite of the VGPR and no write - # of a scalar it read lies between them. A lane inactive at the definition kept an older VGPR value, - # so the read recomputes the definition from the scalars instead of reading this lane's copy. - self.set_s(dst[1], self.uniform_expr[src[1]]) - else: - self.set_s(dst[1], self.u(ops[1])) + self.set_s(reg_range(ops[0])[1], self.u(ops[1])) # ---- SGPR spill to VGPR lanes (#2125, item E) -------------------------------------------- # The compiler parks a scalar in one lane of a VGPR: `v_writelane_b32 vN, sM, k` writes sM into lane k @@ -5252,46 +5259,219 @@ def op_v_readlane_b32(self, ops, mods): sym, uniform = slot self.set_s(dst[1], 'sp%d_%d' % (n, lane), sym=sym, uniform=uniform) + def pair(self, tok): + """(low, high) uint expressions of a 64-bit integer operand: a register pair or an inline integer constant + (sign-extended to 64 bits). Unsigned VALU sources zero-extend a 32-bit literal.""" + r = reg_range(tok) + if r: + if r[2] != r[1] + 1: + raise Unsupported('64-bit operand %s' % tok) + if r[0] == 'v': + self.used_v.update((r[1], r[2])) + return 'v%d' % r[1], 'v%d' % r[2] + return self.S(r[1]), self.S(r[2]) + try: + value = int(tok, 0) + except ValueError: + raise Unsupported('64-bit operand %r' % tok) + if tok.startswith('0x') and 0 <= value <= (0xffffffff if unsigned_valu else 0x7fffffff): + # RDNA 2 ISA 6.2.1, Literal Expansion to 64 bits. Both logical shifts read S1.u64 (12.9). + return '0x%08xu' % value, '0x00000000u' + if not -16 <= value <= 64 or tok.startswith('0x'): + raise Unsupported('64-bit literal operand %s' % tok) + value &= 0xffffffffffffffff + return '0x%08xu' % (value & 0xffffffff), '0x%08xu' % (value >> 32) + + def shift64(self, ops, mods, helper): + """v_l{sh,sh}rrev_b64 D, S0, S1: D = S1 shifted by S0[5:0]; the shift count comes first ("rev").""" + if mods: + raise Unsupported('64-bit shift with %s' % mods) + d = reg_range(ops[0]) + if not d or d[0] != 'v' or d[2] != d[1] + 1: + raise Unsupported('64-bit shift destination %s' % ops[0]) + low, high = self.pair(ops[2], unsigned_valu=True) + count = self.u(ops[1]) + self.uses_q = True + # Read both source words into q before either destination word is written: D and S1 may overlap. + self.emit('q = uint2(%s_lo(%s, %s, %s), %s_hi(%s, %s, %s));' % (helper, low, high, count, helper, low, high, count)) + self.set_v(d[1], 'q.x') + self.set_v(d[1] + 1, 'q.y') + + def carry_op(self, ops, mods, kind, carry_in): + """v_{add,sub,subrev}_co[_ci]_u32 D, SDST, S0, S1[, CI]: 32-bit add or subtract with a carry or borrow out. + + AMD RDNA 2 ISA: V_ADD_CO_CI_U32 D = S0 + S1 + CI, carry = the 33rd bit; V_SUB_CO_CI_U32 D = S0 - S1 - CI, + borrow = S1 + CI > S0 (as 33-bit values); SUBREV swaps S0 and S1; the _co forms have no carry-in. LLVM + VOP2Instructions.td defines V_ADD_CO_CI_U32 as gfx10's name for v_addc_u32 (VOP2b, carry-out an SGPR mask). + The carry is the lane's bit of SDST, as v_cmp writes it; CI must be a lane mask (vcc, exec or an SGPR the + translation holds as a mask). Both results go through q, so D or SDST may overlap a source. + """ + if mods: + raise Unsupported('v_%s_co%s_u32 with %s' % (kind, '_ci' if carry_in else '', ' '.join(mods))) + if len(ops) != (5 if carry_in else 4): + raise Unsupported('v_%s_co%s_u32 with %d operands' % (kind, '_ci' if carry_in else '', len(ops))) + d = reg_range(ops[0]) + if not d or d[0] != 'v' or d[1] != d[2]: + raise Unsupported('carry operation destination %s' % ops[0]) + a, b = self.u(ops[2]), self.u(ops[3]) + if kind == 'subrev': + a, b = b, a + c = '0u' + if carry_in: + r = reg_range(ops[4]) + if not (ops[4] in ('vcc', 'vcc_lo', 'exec', 'exec_lo') or (r and r[0] == 's' and r[1] in self.masks)): + raise Unsupported('carry-in %s is not a lane mask' % ops[4]) + c = '(%s & 1u)' % self.u(ops[4] if not r else 's%d' % r[1]) + if kind == 'add': + value, carry = '%s + %s + %s' % (a, b, c), '((%s + %s) < %s || (%s + %s + %s) < (%s + %s))' % ( + a, b, a, a, b, c, a, b) + else: + value, carry = '%s - %s - %s' % (a, b, c), '(%s > %s || (%s - %s) < %s)' % (b, a, a, b, c) + self.uses_q = True + self.emit('q = uint2(%s, %s ? 1u : 0u);' % (value, carry)) + self.set_v(d[1], 'q.x') + sdst = ops[1] + r = reg_range(sdst) + self.write_compare(False, sdst if not r else 's%d' % r[1], 'q.y') + + def op_v_add_co_ci_u32(self, ops, mods): + self.carry_op(ops, mods, 'add', True) + + def op_v_sub_co_ci_u32(self, ops, mods): + self.carry_op(ops, mods, 'sub', True) + + def op_v_subrev_co_ci_u32(self, ops, mods): + self.carry_op(ops, mods, 'subrev', True) + + def op_v_add_co_u32(self, ops, mods): + self.carry_op(ops, mods, 'add', False) + + def op_v_sub_co_u32(self, ops, mods): + self.carry_op(ops, mods, 'sub', False) + + def op_v_subrev_co_u32(self, ops, mods): + self.carry_op(ops, mods, 'subrev', False) + + def op_v_lshrrev_b64(self, ops, mods): + self.shift64(ops, mods, 'x2w_lshr64') + + def op_v_lshlrev_b64(self, ops, mods): + self.shift64(ops, mods, 'x2w_lshl64') + + def half_op(self, ops, mods, fn): + """v_{min,max}_f16: the binary16 result goes to D[15:0]; gfx10 keeps D[31:16] (LLVM + GCNSubtarget::zeroesHigh16BitsOfDest: "On gfx10, all 16-bit instructions preserve the high bits").""" + if mods: + raise Unsupported('f16 operation with %s' % mods) + if any(t.startswith(('-', '|')) and not re.match(r'-[\d.]', t) for t in ops[1:3]): + raise Unsupported('f16 operation with source modifiers') + d = reg_range(ops[0])[1] + self.used_v.add(d) + a, b = ('f16tof32(%s)' % self.h(t) for t in ops[1:3]) + self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(%s(%s, %s))' % (d, fn, a, b)) + + def half_arithmetic(self, ops, mods, form, arity): + if len(ops) != arity + 1 or mods: + raise Unsupported('binary16 arithmetic operands or modifiers: %s %s' % (ops, mods)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[1] != dst[2]: + raise Unsupported('binary16 arithmetic destination %s' % ops[0]) + d = dst[1] + self.used_v.add(d) + args = ['f16tof32(%s)' % self.h(t) for t in ops[1:]] + expr = form.format(*args, dest='f16tof32(v%d)' % d) + self.set_v(d, '(v%d & 0xffff0000u) | %s' % (d, self.to_f16(expr))) + + def op_v_mul_f16(self, ops, mods): + # A finite binary16 product fits exactly in binary32 before rounding. + self.half_arithmetic(ops, mods, '{0} * {1}', 2) + + def op_v_fmac_f16(self, ops, mods): + self.half_arithmetic(ops, mods, 'x2w_half_madd_odd({0}, {1}, {dest})', 2) + + def op_v_rsq_f16(self, ops, mods): + self.half_arithmetic(ops, mods, 'rsqrt({0})', 1) + + def op_v_min_f16(self, ops, mods): + self.half_op(ops, mods, 'min') + + def op_v_max_f16(self, ops, mods): + self.half_op(ops, mods, 'max') + + def packed_half(self, ops, mods, fn): + """v_pk_{min,max}_f16: two binary16 lanes. Result half i reads, from each source, the half picked by + op_sel (low result) or op_sel_hi (high result); the disassembler prints only non-default selections.""" + sel, sel_hi = [0, 0], [1, 1] + for m in mods: + if m.startswith('op_sel:['): + sel = [int(x) for x in m[8:-1].split(',')] + elif m.startswith('op_sel_hi:['): + sel_hi = [int(x) for x in m[11:-1].split(',')] + else: + raise Unsupported('packed f16 operation with %s' % m) + if len(sel) != 2 or len(sel_hi) != 2: + raise Unsupported('packed f16 selection %s' % mods) + words = [] + for index, tok in enumerate(ops[1:3]): + r = reg_range(tok) + if r: + words.append(self.u(tok)) + elif re.fullmatch(r'0x[0-9a-f]+', tok) and not sel[index] and not sel_hi[index]: + words.append(self.u(tok)) # a literal read only through its low half + elif tok == '0': + words.append('0x00000000u') # the inline integer 0: every bit is 0, so each half reads +0.0 + else: + raise Unsupported('packed f16 operand %s with selection %s/%s' % (tok, sel[index], sel_hi[index])) + def half(word, high): + return 'f16tof32(%s >> 16)' % word if high else 'f16tof32(%s)' % word + low = 'f32tof16(%s(%s, %s))' % (fn, half(words[0], sel[0]), half(words[1], sel[1])) + high = 'f32tof16(%s(%s, %s))' % (fn, half(words[0], sel_hi[0]), half(words[1], sel_hi[1])) + self.set_v(reg_range(ops[0])[1], '%s | (%s << 16)' % (low, high)) + + def op_v_pk_min_f16(self, ops, mods): + self.packed_half(ops, mods, 'min') + + def op_v_pk_max_f16(self, ops, mods): + self.packed_half(ops, mods, 'max') + + def op_v_cvt_f16_f32(self, ops, mods): + # gfx10 keeps D[31:16] for 16-bit results (see half_op); the SDWA form keeps its own dst_sel handling. + if mods: + raise Unsupported('v_cvt_f16_f32 with %s' % mods) + if len(ops) != 2: + raise Unsupported('v_cvt_f16_f32 with %d operands, expected 2' % len(ops)) + d = reg_range(ops[0])[1] + self.used_v.add(d) + self.set_v(d, '(v%d & 0xffff0000u) | %s' % (d, self.to_f16('F(%s)' % self.u(ops[1])))) + def op_v_mov_b32(self, ops, mods): if len(ops) != 2: raise Unsupported('v_mov_b32 with %d operands, expected 2' % len(ops)) self.set_v(reg_range(ops[0])[1], self.u(ops[1])) def op_v_swap_b32(self, ops, mods): - # VOP1 only (llvm-mc rejects the e64, DPP and SDWA spellings for gfx1013). Both registers exchange - # their old values, so one is read into a temporary before either is written. The ISA allows no - # input or output modifier and no scalar or constant operand: both operands are plain VGPRs. - if mods: - raise Unsupported('v_swap_b32 with %s' % mods) - if len(ops) != 2: - raise Unsupported('v_swap_b32 with %d operands, expected 2' % len(ops)) - regs = [reg_range(o) for o in ops] - if any(not r or r[0] != 'v' or r[1] != r[2] or r[1] > 255 for r in regs): - raise Unsupported('v_swap_b32 operands %s, %s: expected two single VGPRs' % (ops[0], ops[1])) - dst, src = regs[0][1], regs[1][1] - for reg in (dst, src): - self.note_whole_read(reg) - body = '{ uint t = v%d; v%d = v%d; v%d = t; }' % (dst, dst, src, src) - # Uniformity travels with the value; under an unknown exec mask neither register keeps the proof. - uniform = (dst in self.uniform_v and self.exec_known, src in self.uniform_v and self.exec_known) - for reg, flag in zip((src, dst), uniform): - (self.uniform_v.add if flag else self.uniform_v.discard)(reg) - exprs = getattr(self, 'uniform_expr', {}) - moved = {src: exprs.pop(dst, None), dst: exprs.pop(src, None)} - exprs.update({reg: e for reg, e in moved.items() if e is not None and reg in self.uniform_v}) - self.used_v.update((dst, src)) - self.emit(body if self.exec_known else 'if (exec & 1) ' + body) + # RDNA 2 ISA V_SWAP_B32 (VOP1 0x65, LLVM VOP1Instructions.td: outs $vdst, $vdst1 tied to $src0): + # tmp = D; D = S0; S0 = tmp, in the active lanes. Both operands are single VGPRs; there is no VOP3, + # DPP or SDWA form (the decoder reports those as unsupported). + d, s = reg_range(ops[0]) if ops else None, reg_range(ops[1]) if len(ops) == 2 else None + if mods or len(ops) != 2 or not d or not s or d[0] != 'v' or s[0] != 'v' or d[1] != d[2] or s[1] != s[2]: + raise Unsupported('v_swap_b32 form %s %s' % (ops, mods)) + if d[1] == s[1]: + return # a register swapped with itself keeps its value + self.uses_swap = True + self.lines.append('xswap = %s;' % self.u(ops[0])) # every lane: a temporary read only below + self.set_v(d[1], self.u(ops[1])) + self.set_v(s[1], 'xswap') def op_v_cndmask_b32(self, ops, mods): - # The select takes no output modifier: a clamp or mul on it would change the value, so a - # modifier that reaches here is refused rather than dropped from the emitted text. + # The VOP3 form takes neg/abs on its two data operands; the select moves bits, so they are sign-bit + # operations on the selected word. if mods: raise Unsupported('v_cndmask_b32 with %s' % mods) if len(ops) not in (3, 4): raise Unsupported('v_cndmask_b32 with %d operands, expected 3 or 4' % len(ops)) mask = self.u(ops[3]) if len(ops) > 3 else 'vcc' - self.set_v(reg_range(ops[0])[1], - '(%s & 1) ? %s : %s' % (mask, self.u_src(ops[2]), self.u_src(ops[1]))) + self.set_v(reg_range(ops[0])[1], '(%s & 1) ? %s : %s' % (mask, self.u_mod(ops[2]), self.u_mod(ops[1]))) def op_v_interp_p1_f32(self, ops, mods): if hasattr(self, 'uniform_v'): @@ -5310,180 +5490,43 @@ def op_v_interp_mov_f32(self, ops, mods): attr, comp = self.note_attr(ops[2], 'flat') self.set_v(reg_range(ops[0])[1], 'i.fparam%d.%s' % (attr, comp)) - def interp_f16(self, op, ops, mods, vsrc, n_ops): - """Common checks of v_interp_p1ll_f16 / v_interp_p2_f16: -> (attr, field, high). - - The attribute channel holds two binary16 values; `field` is the interpolated float the pair reads - (`param0.x`, `hparam0_lo.z`). Two vertex exports exist, with different mappings: - - compr (see export()): the pair is split into float channels, so half h of attribute channel c is float - channel 2 * c + h of the parameter: attrN.x = (param.x, param.y), attrN.y = (param.z, param.w). Channels - z and w have no such pair. - - plain (a 32-bit export, e.g. halves packed by v_cvt_pkrtz_f16_f32): half h of channel c is - f16tof32(word_c >> 16 * h), carried by the extra outputs hparamN_lo (h = 0) and hparamN_hi (h = 1), - channel c of each. All four channels exist. - """ - allowed = ('high', INTERP_DST_HIGH) if op == 'v_interp_p2_f16' else ('high',) - extra = [m for m in mods if m not in allowed] - if extra: - raise Unsupported('%s with %s: only the plain form and high are lowered' % (op, ' '.join(extra))) - if len(ops) != n_ops: - raise Unsupported('%s with %d operands, expected %d' % (op, len(ops), n_ops)) - for tok in (ops[0], ops[1]) + tuple(ops[3:]): - if not re.fullmatch(r'v\d+', tok): - raise Unsupported('%s operand %s: only plain VGPRs are lowered' % (op, tok)) - m = re.fullmatch(r'attr(\d+)\.([xyzw])', ops[2]) - if not m: - raise Unsupported('%s interpolant %s: expected attrN.x/.y/.z/.w' % (op, ops[2])) - attr, component = self.note_attr(ops[2], 'f16') - chan, high = 'xyzw'.index(component), int('high' in mods) - vs = getattr(getattr(self, 'pipe', None), 'vs', None) - if vs is not None and attr in vs.plain_params and attr not in vs.compr_params: - self.f16_plain.setdefault(attr, set()).add(chan) - return attr, 'hparam%d_%s.%s' % (attr, ('lo', 'hi')[high], component), high - if chan > 1: - raise Unsupported('%s on channel %s: a compr export fills only the x and y channels' % (op, m.group(2))) - return attr, 'param%d.%s' % (attr, 'xyzw'[2 * chan + high]), high - - def interp_f16_pair(self, op, ops): - """The entry I/J registers: the PERSP_CENTER pair of the pixel inputs, I in the first, J in the second.""" - base = getattr(getattr(self, 'pipe', None), 'persp_center_vgpr', 0) - if base is None: - raise Unsupported('%s: the pixel inputs do not enable the PERSP_CENTER barycentrics' % op) - want = 'v%d' % (base + (0 if op == 'v_interp_p1ll_f16' else 1)) - if ops[1] != want: - raise Unsupported('%s barycentric operand %s: only the PERSP_CENTER entry %s (%s) is lowered' % ( - op, ops[1], 'I' if op == 'v_interp_p1ll_f16' else 'J', want)) - return base - - def interp_f16_scan(self): - """Whole-program proof for the f16 interpolation pair (no fixed-point analysis: any doubt is a refusal). - - The lowering reads the rasterizer's interpolant, so it is only faithful if (1) the entry I/J registers are - never written (they still hold the entry barycentrics wherever the pair reads them), (2) v_interp_p1ll_f16, - which emits nothing, has no consumer but the v_interp_p2_f16 that follows it in the same straight-line run - and nothing reads the destination it leaves stale when p2 writes elsewhere, and (3) nothing reads the - upper 16 bits of a plain p2 destination: whether gfx10 keeps or clears them is not established by a source - (LLVM 15 SIInstrInfo/VOP3Instructions.td model the result as f16 only; the encoding states no - high-half behaviour), so only a plain v_cvt_f32_f16 reading the low half may consume it, until a p2 with - op_sel 0x8 writes the high half of that register (Mesa ACO keeps the other half, see check_encoding). - """ - if self.interp_scanned: - return - pair = None - targets = set() - rows = [] - for off, _, name, asm in self.ins: - n, ops, mods = parse(asm) - n = re.sub(r'_e(32|64)$', '', n) - rows.append((off, n, ops, mods)) - target = getattr(self, 'calculated_pc', {}).get(off) - if n.startswith('s_cbranch') or n == 's_branch': - target = int(ops[0].split('_')[1], 16) - if target is not None: - if target <= off: - raise Unsupported('a backward branch in a program with v_interp_p1ll_f16 / v_interp_p2_f16') - targets.add(target) - - def regs(tok): - r = reg_range(tok) - return set(range(r[1], r[2] + 1)) if r and r[0] == 'v' else set() - - pending, stale, high_undefined = {}, set(), set() - for off, n, ops, mods in rows: - branch_boundary = off in targets or n.startswith('s_cbranch') or n in ('s_branch', 's_setpc_b64') - if branch_boundary and pending: - raise Unsupported('a branch between v_interp_p1ll_f16 %s and its v_interp_p2_f16: p2 could be ' - 'reached without the matching p1ll' % ', '.join('v%d' % r for r in sorted(pending))) - if branch_boundary and (stale or high_undefined): - raise Unsupported('unmodelled v_interp_p2_f16 result across a branch') - store = n == 'exp' or n.startswith(INTERP_STORE_PREFIXES) - # A malformed pair member is refused by its own handler; the scan models only the plain spelling. - interp = (n in ('v_interp_p1ll_f16', 'v_interp_p2_f16') and len(ops) == (3 if n[10] == '1' else 4) and - all(re.fullmatch(r'v\d+', o) for o in ops[:2] + ops[3:])) - if n in ('v_interp_p1ll_f16', 'v_interp_p2_f16') and not interp: - return # its own handler refuses the program; nothing after it is worth proving - written = regs(ops[0]) if ops and not store else set() - if interp: - read = regs(ops[1]) - pair = self.interp_f16_pair(n, ops) - else: - read = set().union(*(regs(o) for o in ops)) if ops else set() - low_reader = (n == 'v_cvt_f32_f16' and not mods and len(ops) == 2 and - all(re.fullmatch(r'v\d+', o) for o in ops)) - for r in sorted(read): - if r in pending: - raise Unsupported('v%d is the v_interp_p1ll_f16 result, which emits nothing: %s reads it before ' - 'the matching v_interp_p2_f16' % (r, n)) - if r in stale: - raise Unsupported('v%d is the v_interp_p1ll_f16 result, which emits nothing: %s reads it after ' - 'a v_interp_p2_f16 that wrote another register' % (r, n)) - if r in high_undefined and not (low_reader and r == int(ops[1][1:])): - raise Unsupported('%s reads the upper 16 bits of the v_interp_p2_f16 result v%d: not modelled' % - (n, r)) - if n == 'v_interp_p1ll_f16' and interp: - pending[int(ops[0][1:])] = (ops[2], 'high' in mods) - elif n == 'v_interp_p2_f16' and interp: - d, out = int(ops[3][1:]), int(ops[0][1:]) - if pending.get(d) != (ops[2], 'high' in mods): - raise Unsupported('v_interp_p2_f16 source %s is not the v_interp_p1ll_f16 result of %s' % - (ops[3], ops[2])) - del pending[d] - if out in pending: - raise Unsupported('v_interp_p2_f16 overwrites the pending v_interp_p1ll_f16 result v%d' % out) - stale.discard(out) - if out != d: - stale.add(d) - if INTERP_DST_HIGH in mods: - # Completes a 16-bit pair: the low half it keeps must be a plain p2 result still waiting for its - # upper half (no other writer is modelled), after which every reader sees defined halves. - if out not in high_undefined: - raise Unsupported('v_interp_p2_f16 op_sel 0x8 into v%d, which holds no v_interp_p2_f16 low ' - 'half: the half it keeps is not modelled' % out) - high_undefined.discard(out) - else: - high_undefined.add(out) - elif low_reader: - high_undefined.discard(int(ops[0][1:])) - stale.discard(int(ops[0][1:])) - # I and J: never written anywhere - base = pair if pair is not None else (getattr(getattr(self, 'pipe', None), 'persp_center_vgpr', 0) or 0) - for off, n, ops, mods in rows: - store = n == 'exp' or n.startswith(INTERP_STORE_PREFIXES) - if ops and not store and regs(ops[0]) & {base, base + 1}: - raise Unsupported('%s writes v%d: the entry barycentric registers must still hold the entry values ' - 'where v_interp_p1ll_f16 / v_interp_p2_f16 read them' % (n, min( - regs(ops[0]) & {base, base + 1}))) - if n == 'v_swap_b32' and len(ops) == 2 and regs(ops[1]) & {base, base + 1}: - raise Unsupported('v_swap_b32 writes the entry barycentric registers') - self.interp_scanned = True + def interp_f16_mods(self, name, mods): + if any(m != 'high' for m in mods): + raise Unsupported('%s with %s' % (name, ' '.join(mods))) + return 'hi' if 'high' in mods else 'lo' def op_v_interp_p1ll_f16(self, ops, mods): - # P0 + I * P10 in f32 from a binary16 attribute. The rasterizer interpolates the float channel, so the - # statement itself emits nothing; p2 reads the interpolated value. The destination is remembered so that - # p2 can be checked to continue this very pass. - attr, field, high = self.interp_f16('v_interp_p1ll_f16', ops, mods, 1, 3) - self.interp_f16_pair('v_interp_p1ll_f16', ops) - self.interp_f16_scan() - if self.interp_p1 is None: - self.interp_p1 = {} - self.interp_p1[int(ops[0][1:])] = (attr, field, high) + # First pass of a binary16 attribute (Mesa ACO emit_interp_instr: p1ll then p2_f16). Like p1_f32 it + # produces no value of its own here: the interpolated half comes from p2. + self.interp_f16_mods('v_interp_p1ll_f16', mods) + if len(ops) != 3: + raise Unsupported('v_interp_p1ll_f16 with %d operands' % len(ops)) + self.note_attr(ops[2], 'half') def op_v_interp_p2_f16(self, ops, mods): - # P1 + J * P20, converted to binary16 into one half of the destination, the other half kept (LLVM: the - # result is f16, the high bit selects the attribute half only). The plain form writes the low half; with - # op_sel 0x8 (ACO's v_interp_p2_hi_f16) the high half. interp_f16_scan refuses every consumer of a half the - # pair has not written, so a half that is never written is never observed. - attr, field, high = self.interp_f16('v_interp_p2_f16', ops, mods, 1, 4) - self.interp_f16_pair('v_interp_p2_f16', ops) - self.interp_f16_scan() - if (self.interp_p1 or {}).get(int(ops[3][1:])) != (attr, field, high): - raise Unsupported('v_interp_p2_f16 source %s is not the v_interp_p1ll_f16 result of %s' % (ops[3], ops[2])) + """The f16 attribute half (`high`: bits 31:16 of the exported word) interpolated, rounded to binary16. + + The vertex/mesh stage exports a second and third interpolated copy of the attribute, each half converted to + f32 (loparamN / hiparamN, see export); the result is f32tof16 of the interpolant. The hardware + interpolates in f32 and rounds once, as this does (LLVM SIInstrInfo / ACO: p1ll is f32 out, p2 f16 out). + A 16-bit write: the other half of the VGPR is kept (Mesa aco_ir.cpp instr_is_16bit lists v_interp_p2_f16 + and v_interp_p2_hi_f16 for GFX9+). op_sel bit 3 (VOP3 word 0 bit 14, which LLVM 15 and the decoder do not + print) writes the high half: Mesa aco_assembler.cpp emits v_interp_p2_hi_f16 as v_interp_p2_f16 with + opsel 0x8. Other op_sel bits are refused.""" + half = self.interp_f16_mods('v_interp_p2_f16', mods) + if len(ops) != 4: + raise Unsupported('v_interp_p2_f16 with %d operands' % len(ops)) + attr, comp = self.note_attr(ops[2], 'half') + opsel = struct.unpack_from('> 11 & 15 + if opsel not in (0, 8): + raise Unsupported('v_interp_p2_f16 with op_sel %#x' % opsel) d = reg_range(ops[0])[1] self.used_v.add(d) - if INTERP_DST_HIGH in mods: - self.set_v(d, '(v%d & 0xffffu) | (f32tof16(i.%s) << 16)' % (d, field)) + value = self.to_f16('i.%sparam%d.%s' % (half, attr, comp)) + if opsel: + self.set_v(d, '(v%d & 0xffffu) | (%s << 16)' % (d, value)) else: - self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(i.%s)' % (d, field)) + self.set_v(d, '(v%d & 0xffff0000u) | %s' % (d, value)) def note_attr(self, tok, how): m = re.fullmatch(r'attr(\d+)\.([xyzw])', tok) @@ -5500,75 +5543,173 @@ def note_attr(self, tok, how): return attr, component def mix(self, ops, mods, dest): - """v_fma_mix_f32 / v_fma_mix{lo,hi}_f16: fma of sources that are binary32 words or binary16 halves. + """v_fma_mix{_f32,lo_f16,hi_f16}: fma of operands that are f32 or f16 halves. - Per source (LLVM 15 SelectVOP3PMadMixModsImpl): op_sel_hi set means the source is binary16, and - op_sel set picks its high half. abs, then neg, apply after widening. dest is 'f32', 'lo' or 'hi'. + LLVM AMDGPUISelDAGToDAG::SelectVOP3PMadMixModsImpl: op_sel_hi[i] makes operand i an f16 converted to f32 + and op_sel[i] then picks its high half; abs and neg act on the converted value (abs first). The result is + f32 (dest 'f32') or rounds to f16 in the low or high half, the other half kept. """ - half, hi, clamp = [0, 0, 0], [0, 0, 0], False + sel, high = [0, 0, 0], [0, 0, 0] for m in mods: - if m.startswith('op_sel_hi:['): - half = [int(x) for x in m[11:-1].split(',')] - elif m.startswith('op_sel:['): - hi = [int(x) for x in m[8:-1].split(',')] - elif m == 'clamp': - clamp = True - else: - raise Unsupported('fma_mix modifier %s' % m) - - def operand(tok, is_half, is_hi): - if not is_half and is_hi: - raise Unsupported('op_sel on a binary32 fma_mix source %s' % tok) - if tok == '-0': - # neg on inline 0 is -0.0 in either format; f() would print +0.0, which changes a -0 product. - return '(-0.0)' + if m.startswith('op_sel_hi:'): + sel = [int(x) for x in m[len('op_sel_hi:['):-1].split(',')] + elif m.startswith('op_sel:'): + high = [int(x) for x in m[len('op_sel:['):-1].split(',')] + elif m != 'clamp': + raise Unsupported('modifier %s on fma_mix' % m) + if len(ops) != 4 or len(sel) != 3 or len(high) != 3: + raise Unsupported('fma_mix form %s %s' % (ops, mods)) + def operand(tok, is_half, is_high): if not is_half: - if tok.startswith('--') and tok[1:] in FLOATS: - # neg on a negative inline float prints as `--0.5`; `(--0.5)` is an HLSL decrement. - return '(-(%s))' % self.f(tok[1:]) - if re.fullmatch(r'-(\d+|0x[0-9a-fA-F]+)', tok): - # The decoder prints neg on inline 1..64 or a literal as a negative integer, which f() - # reads without the sign-bit flip. Refuse until the decoder resolves it from the encoding. - raise Unsupported('negated integer or literal fma_mix source %s' % tok) - return self.f(tok) - neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) - if neg: - tok = tok[1:] - absolute = tok.startswith('|') and tok.endswith('|') + if is_high: + raise Unsupported('op_sel on an f32 fma_mix operand') + if tok.lstrip('-') == '0.15915494': + raise Unsupported('fma_mix inline constant 1/(2*pi)') + # "-0" is the inline 0 with the neg modifier: -0.0 (f() reads it as +0.0) + return '(-0.0)' if tok == '-0' else self.f(tok) + if tok in ('0', '-0'): + return '0.0' if tok == '0' else '(-0.0)' + if tok in FLOATS and not is_high and tok != '0.15915494': + # An inline float constant read as an f16 operand is that constant's binary16 form: 0.5 is 0x3800, + # not the low half of the f32 0x3f000000 (LLVM VOP3PInstructions.td, VOP3P_Mix_Profile: "The inline + # immediate values are really f16 converted to f32"; its fadd pattern passes FP16_ONE with op_sel_hi). + # 1/(2*pi) is refused: its f16 and f32 forms differ and only the f16 one is documented here. + return 'f16tof32(%s)' % self.h(tok) + neg = tok.startswith('-') + body = tok[1:] if neg else tok + absolute = body.startswith('|') and body.endswith('|') if absolute: - tok = tok[1:-1] - r = reg_range(tok) - if tok == '0': - text = '0.0' - elif re.fullmatch(r'0x[0-9a-fA-F]{1,8}', tok): - word = (int(tok, 16) >> (16 if is_hi else 0)) & 0xffff - text = 'f16tof32(0x%04xu)' % word - elif tok == '0.5' and not is_hi: - text = '0.5' - elif r and r[1] == r[2]: - # Only a high-half read needs the upper 16 bits defined. - text = 'f16tof32(%s%s)' % (self.u(tok, low16_only=not is_hi), ' >> 16' if is_hi else '') + body = body[1:-1] + r = reg_range(body) + if re.fullmatch(r'0x[0-9a-f]{1,8}', body): + # A 32-bit literal read as an f16 operand: op_sel picks its half as for a register (LLVM + # SIFoldOperands::tryFoldImmWithOpSel reads VOP3P literal halves as ImmVal >> (OP_SEL_0 ? 16 : 0)). + value = int(body, 16) + text = 'f16tof32(0x%04xu)' % ((value >> 16) if is_high else (value & 0xffff)) + elif not r or r[1] != r[2]: + raise Unsupported('f16 fma_mix operand %s' % tok) else: - raise Unsupported('binary16 fma_mix source %s' % tok) + text = 'f16tof32(%s%s)' % (self.u(body), ' >> 16' if is_high else '') if absolute: text = 'abs(%s)' % text return '(-%s)' % text if neg else text - - # v_fma_mix* is fused, but HLSL may round `a * b` before the add, so binary32 sources with long - # mantissas can differ from the hardware by 1 ULP (same as v_fma_f32 in VEC_F). - expr = '%s * %s + %s' % tuple(operand(*a) for a in zip(ops[1:4], half, hi)) - if clamp: + expr = '%s * %s + %s' % tuple(operand(t, s, h) for t, s, h in zip(ops[1:4], sel, high)) + if 'clamp' in mods: expr = 'saturate(%s)' % expr d = reg_range(ops[0])[1] if dest == 'f32': - self.set_v(d, 'U(%s)' % expr) - return + return self.set_v(d, 'U(%s)' % expr) self.used_v.add(d) if dest == 'hi': - self.set_v(d, '(v%d & 0xffffu) | (f32tof16(%s) << 16)' % (d, expr)) + self.set_v(d, '(v%d & 0xffffu) | (%s << 16)' % (d, self.to_f16(expr))) else: - keep_low16 = d in self.low16_only_v - self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(%s)' % (d, expr), low16_only=keep_low16) + self.set_v(d, '(v%d & 0xffff0000u) | %s' % (d, self.to_f16(expr)), low16_only=d in self.low16_only_v) + + # s_round_mode writes MODE[3:0] from its immediate: bits 1:0 round f32 results, bits 3:2 round f16 and f64 results + # (LLVM SIDefines.h FP_ROUND_MODE_SP / FP_ROUND_MODE_DP; Mesa aco_ir.h struct float_mode, round32 : 2 then + # round16_64 : 2, "matches encoding of the MODE register"), each 0 nearest even, 1 +inf, 2 -inf, 3 toward zero + # (FP_ROUND_ROUND_TO_*, aco fp_round_*). The denorm bits are s_denorm_mode's and stay refused. Taken: f32 to + # nearest even (what the HLSL arithmetic does) with f16/f64 to nearest even or toward zero, in the straight-line + # entry of the program, so the mode at every later instruction is known. Under a nonzero f16/f64 mode the + # instructions that round an f16 result go through to_f16; check_round16 refuses every other f16/f64 one. + ROUND16_EXACT = ('v_cvt_f32_f16', 'v_cmp_', 'v_cmpx_', 'v_interp_p1ll_f16', 'v_fma_mix_f32', 'v_min_f16', + 'v_max_f16', 'v_pk_min_f16', 'v_pk_max_f16', 'v_cvt_pkrtz_f16_f32') + ROUND16_LOWERED = ('v_mul_f16', 'v_fmac_f16', 'v_rsq_f16', 'v_fma_mixlo_f16', 'v_fma_mixhi_f16', 'v_cvt_f16_f32', 'v_interp_p2_f16') + round16 = 0 # the class defaults, for a Stage built without __init__ (the operand-count probe) + uses_round_mode = False + launch_unknown = False # a pixel stage built without its launch FLOAT_MODE (launch_mode) + mode_at = {} # offset -> MODE[3:2] values reaching it (round_mode_flow), for stages with s_round_mode + quad_divergent = has_loop = False + + def op_s_round_mode(self, ops, mods): + value = int(ops[0], 0) if ops and re.fullmatch(r'(0x[0-9a-f]+|\d+)', ops[0]) else None + if value is None or mods: + raise Unsupported('s_round_mode %s' % ' '.join(ops + mods)) + if self.kind not in ('ps', 'ms') or (self.kind == 'ms' and not self.mode_at): + raise Unsupported('s_round_mode in a %s stage' % self.kind) + # After control flow the layout-order value set here can differ from what some path brings to a later + # instruction; round_mode_flow finds the values per instruction and one() refuses a mismatch. + if value & ~0xf or value & 3 or (value >> 2) not in (0, 3): + raise Unsupported('s_round_mode %#x (only f32 nearest even with f16/f64 nearest even or toward zero)' + % value) + self.round16 = value >> 2 + self.launch_unknown = False # MODE[3:2] is known from here on + + # FLOAT_MODE denorm bits [7:4] the lowering matches: f32 denormals flushed ([5:4] = 0), f16/f64 kept ([7:6] = 3). + # D3D flushes f32 denormals in shader arithmetic and keeps f16 ones; the 1,500 measured mesh sets are all 0xc_. + LAUNCH_DENORM = 0xc0 + + def launch_mode(self, mode): + """Start the pixel stage's MODE from its launch FLOAT_MODE (SPI_SHADER_PGM_RSRC1_PS bits 19:12; the layout""" + if mode is None: + self.launch_unknown = True + return + if mode & 0xf0 != self.LAUNCH_DENORM or mode & 3 or (mode >> 2 & 3) not in (0, 3): + raise Unsupported('launch FLOAT_MODE %#04x (only f32 nearest even, f16/f64 nearest even or toward zero, ' + 'denorm %#04x)' % (mode, self.LAUNCH_DENORM)) + self.round16 = mode >> 2 & 3 + + def round_mode_flow(self): + """offset -> the set of MODE[3:2] values (0, 3, or '?' for the unknown launch value, 'x' after an + s_round_mode op_s_round_mode refuses) that reach it on some path from the entry. Paths follow fall-through + and branch targets, loops included; only s_round_mode changes the value (s_setreg of MODE is refused).""" + info = {off: (name, asm) for off, n, name, asm in self.ins} + order = [ins[0] for ins in self.ins] + following = dict(zip(order, order[1:])) + at = {order[0]: {'?' if self.launch_unknown else self.round16}} if order else {} + todo = list(at) + while todo: + off = todo.pop() + name, asm = info[off] + out = at[off] + if name == 's_round_mode': + ops = parse(asm)[1] + value = int(ops[0], 0) if ops and re.fullmatch(r'(0x[0-9a-f]+|\d+)', ops[0]) else -1 + out = {value >> 2} if 0 <= value <= 0xf and not value & 3 and value >> 2 in (0, 3) else {'x'} + if name == 's_endpgm': + continue + nxt = [] if name == 's_branch' else [following[off]] if off in following else [] + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + for t in nxt: + if t in info and not out <= at.get(t, set()): + at[t] = at.get(t, set()) | out + todo.append(t) + return at + + def check_round16(self, name): + """Under f16/f64 round toward zero: refuse an f16/f64 instruction that rounds and is not lowered for it. + + Exact whatever the mode: the f16 -> f32 widening, compares (no result rounding), v_interp_p1ll_f16 and + v_fma_mix_f32 (f32 results, MODE[1:0]), f16 min/max (the result is an operand), v_cvt_pkrtz_f16_f32 (its + rounding is toward zero by definition).""" + if not self.rounds16(name): + return + if re.sub(r'_(e32|e64)$', '', name) in self.ROUND16_LOWERED: + return + raise Unsupported('%s under s_round_mode f16/f64 toward zero (not lowered)' % name) + + def rounds16(self, name): + """An f16/f64 instruction whose result depends on MODE[3:2] (not in ROUND16_EXACT).""" + if not re.search(r'f16|f64', name): + return False + return not re.sub(r'_(e32|e64|sdwa|dpp)$', '', name).startswith(self.ROUND16_EXACT) + + def check_launch_known(self, name): + """A pixel stage whose launch FLOAT_MODE was not passed: refuse an instruction whose result depends on + MODE[3:2] before an s_round_mode sets it. The launch value is not 0 in general (MEASURED: 0xcc, f16 toward + zero, in 262 of 1412 mesh pixel stages and 1015 of 3124 draw requests), so neither rounding can be assumed.""" + if self.rounds16(name): + raise Unsupported('%s: f16/f64 rounding with the launch FLOAT_MODE not passed (.psin third field)' % name) + + def to_f16(self, expr): + """An f32 value rounded to binary16 under the current MODE[3:2] (see op_s_round_mode).""" + # HLSL f32tof16 rounds toward zero on WARP and on an RX 9070 XT (MEASURED, startup_round_mode_check), so + # nearest even (MODE[3:2] = 0) needs its own helper. + return ('x2w_f32tof16_rtz(%s)' if self.round16 == 3 else 'x2w_f32tof16_rne(%s)') % expr + + def op_v_fma_mix_f32(self, ops, mods): + self.mix(ops, mods, 'f32') def op_v_fma_mix_f32(self, ops, mods): self.mix(ops, mods, 'f32') @@ -5579,51 +5720,6 @@ def op_v_fma_mixlo_f16(self, ops, mods): def op_v_fma_mixhi_f16(self, ops, mods): self.mix(ops, mods, 'hi') - def cube(self, kind, ops, mods): - """v_cube{id,sc,tc,ma}_f32: LLVM's ConstantFoldAMDGCNCubeIntrinsic. - - The major axis is z when |z| is at least |x| and |y|, otherwise y when |y| is at - least |x|, otherwise x. A face is negative only for a nonzero, non-NaN negative - coordinate. cubema returns twice the signed major coordinate. - """ - if len(ops) != 4: - raise Unsupported('v_cube%s_f32 with %d operands, expected 4' % (kind, len(ops))) - if any(m != 'clamp' for m in mods): - raise Unsupported('v_cube%s_f32 with %s' % (kind, ', '.join(mods))) - dst = reg_range(ops[0]) - if not dst or dst[0] != 'v' or dst[2] != dst[1] or dst[2] > 255: - raise Unsupported('v_cube%s_f32 destination %s' % (kind, ops[0])) - x, y, z = [self.f(o) for o in ops[1:4]] - temp = 'cube%d' % getattr(self, 'cube_temps', 0) - self.cube_temps = getattr(self, 'cube_temps', 0) + 1 - self.emit('float3 %s = float3(%s, %s, %s);' % (temp, x, y, z)) - c = temp - a = 'abs(%s)' % c - zmajor = '(%s.z >= %s.x && %s.z >= %s.y)' % (a, a, a, a) - ymajor = '(%s.y >= %s.x)' % (a, a) - expression = { - 'id': '(%s ? (%s.z < 0.0f ? 5.0f : 4.0f) : %s ? (%s.y < 0.0f ? 3.0f : 2.0f) ' - ': (%s.x < 0.0f ? 1.0f : 0.0f))' % (zmajor, c, ymajor, c, c), - 'sc': '(%s ? (%s.z < 0.0f ? -%s.x : %s.x) : %s ? %s.x ' - ': (%s.x < 0.0f ? %s.z : -%s.z))' % (zmajor, c, c, c, ymajor, c, c, c, c), - 'tc': '(%s ? -%s.y : %s ? (%s.y < 0.0f ? -%s.z : %s.z) : -%s.y)' % ( - zmajor, c, ymajor, c, c, c, c), - 'ma': '((%s ? %s.z : %s ? %s.y : %s.x) * 2.0f)' % (zmajor, c, ymajor, c, c), - }[kind] - self.set_vf(dst[1], expression, mods) - - def op_v_cubeid_f32(self, ops, mods): - self.cube('id', ops, mods) - - def op_v_cubesc_f32(self, ops, mods): - self.cube('sc', ops, mods) - - def op_v_cubetc_f32(self, ops, mods): - self.cube('tc', ops, mods) - - def op_v_cubema_f32(self, ops, mods): - self.cube('ma', ops, mods) - def i64_words(self, tok): """(low, high) uint expressions of a 64-bit integer source: a VGPR/SGPR pair or an inline int.""" pair = reg_range(tok) @@ -5633,34 +5729,10 @@ def i64_words(self, tok): if pair[0] == 's' and pair[1] % 2 == 0 and pair[2] <= 105: return self.u('s%d' % pair[1]), self.u('s%d' % pair[2]) raise Unsupported('64-bit source %s' % tok) - if re.fullmatch(r'0|-?[1-9]\d*', tok) and -16 <= int(tok) <= 64: - value = int(tok) & 0xffffffffffffffff - return '%du' % (value & 0xffffffff), '%du' % (value >> 32) - raise Unsupported('64-bit source %s' % tok) - - def shift64(self, ops, mods, helper): - if mods: - raise Unsupported('64-bit shift with %s' % mods) - if len(ops) != 3: - raise Unsupported('64-bit shift with %d operands, expected 3' % len(ops)) - dst = reg_range(ops[0]) - if not dst or dst[0] != 'v' or dst[2] != dst[1] + 1 or dst[2] > 255: - raise Unsupported('64-bit shift destination %s' % ops[0]) - sr = reg_range(ops[1]) - if (sr and (sr[1] != sr[2] or (sr[0] == 'v' and sr[1] > 255) or (sr[0] == 's' and sr[1] > 105)) - or ops[1] in ('vcc', 'exec') or ops[1] in FLOATS): - raise Unsupported('64-bit shift amount %s' % ops[1]) - amount = self.u(ops[1]) - low, high = self.i64_words(ops[2]) - body = '{ uint2 t = %s(%s, %s, %s); v%d = t.x; v%d = t.y; }' % ( - helper, low, high, amount, dst[1], dst[2]) - if hasattr(self, 'uniform_v'): - self.uniform_v.discard(dst[1]) - self.uniform_v.discard(dst[2]) - self.clear_low16(dst[1]) - self.clear_low16(dst[2]) - self.used_v.update((dst[1], dst[2])) - self.emit(body if self.exec_known else 'if (exec & 1) ' + body) + if re.fullmatch(r'0|-?[1-9]\d*', tok) and -16 <= int(tok) <= 64: + value = int(tok) & 0xffffffffffffffff + return '%du' % (value & 0xffffffff), '%du' % (value >> 32) + raise Unsupported('64-bit source %s' % tok) def carry_out_op(self, ops, mods, kind): """v_{add,sub,subrev}_co_u32 D, SDST, S0, S1: a 32-bit add or subtract with a carry or borrow out. @@ -5699,138 +5771,55 @@ def carry_out_op(self, ops, mods, kind): self.set_s(sdst[1], predicate, uniform=False) self.masks.add(sdst[1]) - def op_v_add_co_u32(self, ops, mods): - self.carry_out_op(ops, mods, 'add') - - def op_v_sub_co_u32(self, ops, mods): - self.carry_out_op(ops, mods, 'sub') - - def op_v_subrev_co_u32(self, ops, mods): - self.carry_out_op(ops, mods, 'subrev') - - def carry_in_out_op(self, ops, mods, kind): - """v_{add,sub,subrev}_co_ci_u32 D, SDST, S0, S1, S2: 32-bit add/sub with carry or borrow in and out. - - AMD RDNA 2 ISA: V_ADD_CO_CI_U32 D = S0 + S1 + S2[lane] with carry out to SDST[lane]; - V_SUB_CO_CI_U32 D = S0 - S1 - S2[lane] with borrow out to SDST[lane]; V_SUBREV_CO_CI_U32 swaps S0 and S1. - Both VOP2 (_e32, implicit vcc_lo) and VOP3b (_e64) forms arrive with five operands. Results go through - scratch a and w first so D or SDST may overlap any source. - """ - name = 'v_%s_co_ci_u32' % kind - if mods: - raise Unsupported('%s with %s' % (name, ' '.join(mods))) - if len(ops) != 5: - raise Unsupported('%s with %d operands' % (name, len(ops))) - d = reg_range(ops[0]) - if not d or d[0] != 'v' or d[1] != d[2] or d[1] > 255: - raise Unsupported('%s destination %s' % (name, ops[0])) - sdst = reg_range(ops[1]) - if ops[1] not in ('vcc', 'vcc_lo') and not (sdst and sdst[0] == 's' and sdst[1] == sdst[2] and sdst[1] <= 105): - raise Unsupported('%s carry-out destination %s' % (name, ops[1])) - cin_tok = ops[4] - if cin_tok in ('vcc_hi', 'exec_hi'): - raise Unsupported('%s carry-in %s' % (name, cin_tok)) - cin_const = self.const_u32(cin_tok) - if cin_const in (0, 0xffffffff): - ci = '1u' if cin_const else '0u' - elif self.is_lane_mask(cin_tok): - ci = '(%s & 1u)' % self.u(cin_tok) - else: - raise Unsupported('%s carry-in %s' % (name, cin_tok)) - a, b = self.u(ops[2]), self.u(ops[3]) - if kind == 'subrev': - a, b = b, a - if kind == 'add': - self.emit('a = %s + %s;' % (a, b)) - self.emit('w = a < %s ? 1u : 0u;' % a) - self.emit('a = a + %s;' % ci) - self.emit('w = w | (a < %s ? 1u : 0u);' % ci) - else: - self.emit('a = %s - %s;' % (a, b)) - self.emit('w = %s > %s ? 1u : 0u;' % (b, a)) - self.emit('w = w | (%s > a ? 1u : 0u);' % ci) - self.emit('a = a - %s;' % ci) - self.set_v(d[1], 'a') - predicate = 'w' if self.exec_known else '(exec & w)' - if ops[1] in ('vcc', 'vcc_lo'): - self.emit('vcc = %s;' % predicate) - else: - self.set_s(sdst[1], predicate, uniform=False) - self.masks.add(sdst[1]) - - def op_v_add_co_ci_u32(self, ops, mods): - self.carry_in_out_op(ops, mods, 'add') - - def op_v_sub_co_ci_u32(self, ops, mods): - self.carry_in_out_op(ops, mods, 'sub') - - def op_v_subrev_co_ci_u32(self, ops, mods): - self.carry_in_out_op(ops, mods, 'subrev') - - def op_v_lshlrev_b64(self, ops, mods): - self.shift64(ops, mods, 'shl64') - - def op_v_lshrrev_b64(self, ops, mods): - self.shift64(ops, mods, 'shr64u') - def op_v_ashrrev_i64(self, ops, mods): - self.shift64(ops, mods, 'shr64i') + raise Unsupported('v_ashrrev_i64 (local shift64 has no arithmetic 64-bit form)') def op_v_cvt_pkrtz_f16_f32(self, ops, mods): + # Round toward zero whatever MODE says (the "rtz" of the name; LLVM int_amdgcn_cvt_pkrtz; Mesa + # nir_opt_algebraic.py turns pack_half_2x16_split into pack_half_2x16_rtz_split only for backends with + # has_pack_half_2x16_rtz, the rounding being the difference). HLSL f32tof16 does not promise that rounding (MEASURED toward zero + # on WARP, startup_round_mode_check), so both halves go through x2w_f32tof16_rtz. if len(ops) != 3: raise Unsupported('v_cvt_pkrtz_f16_f32 with %d operands, expected 3' % len(ops)) - self.set_v(reg_range(ops[0])[1], 'f32tof16(%s) | (f32tof16(%s) << 16)' % (self.f(ops[1]), self.f(ops[2]))) - - # VOPC with sub-dword addressing (tools/disasm_rdna2.py _decode_vopc_sdwa prints it): each source - # reads its src0_sel/src1_sel field, zero-extended or, under sext(), sign-extended, and the - # compare then reads that 32-bit value as its type. A binary32 class compare reads the whole - # float in SRC0 and selects an integer field in SRC1 for the mask. - # - # An f32 source (#1906) with a DWORD selection reads the register as binary32 with neg/abs as in - # the e64 form. A BYTE or WORD selection is refused: LLVM's SIPeepholeSDWA models it as the field - # zero-extended and read as binary32 bits (the RDNA 2 ISA guide gives SDWAB only its fields), so - # the field is always +0 or a denormal and the result depends on the binary32 denormal mode, which - # this translator does not read (pixel_aot refuses the same forms). sext() is valid for integer - # operands only (LLVM AMDGPUModifierSyntax; LLVM 15 does not decode the bit on a float source). - def compare_sdwa_sources(self, base, typ, ops, mods, *, float_src0=False, float_sources=False): - fields = {} - for m in mods: - key, _, value = m.partition(':') - if key not in ('src0_sel', 'src1_sel') or value not in SDWA_SEL or key in fields: - raise Unsupported('%s with SDWA modifier %s' % (base, m)) - fields[key] = value - sources = [] - for index, token in enumerate(ops): - selection = fields.get('src%d_sel' % index) - if not selection: - raise Unsupported('%s SDWA without src%d_sel' % (base, index)) - sext = token.startswith('sext(') and token.endswith(')') - if float_src0 and index == 0: - if selection != 'DWORD' or sext: - raise Unsupported('%s requires a DWORD float source' % base) - sources.append(self.f(token)) - continue - if float_sources: - if 'sext(' in token: - raise Unsupported('%s: sext() on a float source' % base) - if selection != 'DWORD': - raise Unsupported('%s: f32 SDWA byte/word selection depends on the binary32 denormal mode' - % base) - # The whole word: the same text as the e64 form with the same modifiers. - sources.append(self.f(token)) - continue - if sext: - token = token[len('sext('):-1] - word = sdwa_source(self.u(token, low16_only=selection in ('BYTE_0', 'BYTE_1', 'WORD_0')), selection, sext) - sources.append('int(%s)' % word if typ == 'i32' else word) - return sources + self.set_v(reg_range(ops[0])[1], 'x2w_f32tof16_rtz(%s) | (x2w_f32tof16_rtz(%s) << 16)' + % (self.f(ops[1]), self.f(ops[2]))) - def check_compare_sdwa_destination(self, base, writes_exec, ops): - # v_cmpx_*_sdwa prints just its sources. v_cmp_*_sdwa prints the scalar destination first. - if len(ops) != (2 if writes_exec else 3): - raise Unsupported('%s with %d operands' % (base, len(ops))) - if not writes_exec and ops[0] not in ('vcc', 'vcc_lo', 'exec', 'exec_lo') and not ( - reg_range(ops[0]) and reg_range(ops[0])[0] == 's'): - raise Unsupported('%s into %s' % (base, ops[0])) + def pknorm(self, ops, mods, kind): + # S0 packs into D[15:0] and S1 into D[31:16] (per Mesa ACO selection: pack_[us]norm_2x16 of (x, y) is + # v_cvt_pknorm_[ui]16_f32 x, y); each half is x2w_pknorm_[ui]16, see HELPERS. Source neg/abs apply first. + if mods or len(ops) != 3: + raise Unsupported('v_cvt_pknorm_%s16_f32 with %s' % (kind, mods or ops)) + helper = 'x2w_pknorm_%s16' % kind + self.set_v(reg_range(ops[0])[1], '%s(%s) | (%s(%s) << 16)' % (helper, self.f(ops[1]), helper, self.f(ops[2]))) + + def op_v_cvt_pknorm_u16_f32(self, ops, mods): + self.pknorm(ops, mods, 'u') + + def op_v_cvt_pknorm_i16_f32(self, ops, mods): + self.pknorm(ops, mods, 'i') + + def _low16_source(self, base, tok, signed): + """A source of a 16-bit integer compare: bits 15:0 of the operand, sign- or zero-extended (RDNA 2 VOPC + S0.i16 / S0.u16). A float token is refused: on a 16-bit operand the inline constants 240-248 are binary16 + values (LLVM 15 prints inline 1.0 there as 0x3c00), while u() would give the binary32 word.""" + if tok in FLOATS: + raise Unsupported('%s source %s: inline float constants are binary16 on 16-bit operands' % (base, tok)) + reg = reg_range(tok) + if reg: + if reg[1] != reg[2]: + raise Unsupported('%s source %s' % (base, tok)) + x = self.u(tok, low16_only=True) + return '(asint(%s << 16u) >> 16u)' % x if signed else '(%s & 0xffffu)' % x + try: + value = int(tok, 0) + except ValueError: + # vcc, exec, m0 and modifier spellings: not a source this lowering reads. + raise Unsupported('%s source %s' % (base, tok)) + # The decoder prints inline integers -16..64 in decimal and a literal in hex; LLVM 15 accepts only 16-bit + # literals on these operands. + if not -16 <= value <= 0xffff: + raise Unsupported('%s source %s: wider than 16 bits' % (base, tok)) + low = value & 0xffff + return '%d' % (low - 0x10000 if low & 0x8000 else low) if signed else '0x%04xu' % low def _low16_source(self, base, tok, signed): """A source of a 16-bit integer compare: bits 15:0 of the operand, sign- or zero-extended (RDNA 2 VOPC @@ -5857,88 +5846,111 @@ def _low16_source(self, base, tok, signed): return '%d' % (low - 0x10000 if low & 0x8000 else low) if signed else '0x%04xu' % low def compare(self, base, ops, mods=()): - # A comparison reads its two operands directly, so a modifier that arrives here is one this - # lowering does not model (op_sel selects a packed half, clamp/omod have no place in a compare): - # refuse it rather than emit a predicate computed from the unselected operands. - if mods and not base.endswith('_sdwa'): + m = re.fullmatch(r'v_cmp(x?)_(\w+?)_(f32|u32|i32|f16|u16|i16)(_sdwa)?', base) + if not m or (m.group(4) and m.group(3) not in ('i32', 'u32') and m.group(2) != 'class') \ + or (m.group(3) == 'f16' and m.group(2) not in ('class', 'gt', 'lt')): + if m and m.group(4) and m.group(3) == 'f32': + # The f32 predicates are verified on the plain and e64 forms only (#1920); the SDWA forms + # stay refused until they are verified too. + raise Unsupported('%s: f32 SDWA compares are not lowered' % base) + raise Unsupported(base) + writes_exec, cond, typ = m.group(1) == 'x', m.group(2), m.group(3) + if typ in ('u16', 'i16'): + if m.group(4) or cond not in ('lt', 'eq', 'le', 'gt', 'ne', 'ge'): + raise Unsupported(base) + if mods: + raise Unsupported('%s with %s' % (base, mods)) + if len(ops) == 3: + dst, a, b = ops + elif len(ops) == 2: + dst, (a, b) = ('exec' if writes_exec else 'vcc'), ops + else: + raise Unsupported('%s with %d operands' % (base, len(ops))) + if m.group(4): + # VOPC SDWA on integers: each source is its selected field (zero- or, with sext(), sign-extended) + # compared as a 32-bit value; the result goes to vcc, an SGPR mask or (cmpx) exec as for e32. + fields = dict(mod.partition(':')[::2] for mod in mods) + if set(fields) != {'src0_sel', 'src1_sel'} or any(v not in SDWA_SEL for v in fields.values()): + raise Unsupported('%s with %s' % (base, mods)) + if cond == 'class' and typ == 'f16': + # v_cmp_class_f16 SDWA: S0 is the selected field of a VGPR or SGPR, zero-extended, of which the op + # reads bits [15:0] as the binary16 value (SDWA source selection, AMD RDNA ISA 6.3.3; for WORD_1 that + # is the high half); neg()/abs() act on bit 15 of the selected value. S1 is the integer class mask + # through its own selection, as for f32. A constant S0 is refused: its f16 inline form is not modelled. + # The disassembly spells the modifiers -vN and |vN| on registers (neg(N)/abs(N) on constants). + # -|vN| is abs then neg (SDWA applies abs before neg, as VOP3): bit 15 set. + mm = re.fullmatch(r'(-)?(?:\|(\w+)\||(\w+))', a) + src = (mm.group(2) or mm.group(3)) if mm else a + if src.startswith('sext(') or not reg_range(src): + raise Unsupported('%s with f16 value operand %s' % (base, a)) + value = sdwa_source(self.u(src), fields['src0_sel'], False) + if mm and mm.group(2): + value = '(%s %s)' % (value, '| 0x8000u' if mm.group(1) else '& 0x7fffu') + elif mm and mm.group(1): + value = '(%s ^ 0x8000u)' % value + if b.startswith(('sext(', 'neg(', 'abs(')): + raise Unsupported('%s with a modified class mask %s' % (base, b)) + expr = 'x2w_class_f16(%s, %s)' % (value, sdwa_source(self.u(b), fields['src1_sel'], False)) + return self.write_compare(writes_exec, dst, expr) + if cond == 'class': + # v_cmp_class_f32 SDWA: S0 is the f32 value (whole dword only; neg()/abs() act on its sign bit as + # for the e64 form), S1 the integer class mask read through its selection (a compiler uses + # src1_sel:BYTE_n to test bits of one byte against constant classes such as -0.0). + if fields['src0_sel'] != 'DWORD': + raise Unsupported('%s with a sub-dword f32 value' % base) + mm = re.fullmatch(r'(neg|abs)\((.*)\)', a) + value = self.u(mm.group(2) if mm else a) + if mm: + value = '(%s %s)' % (value, '^ 0x80000000u' if mm.group(1) == 'neg' else '& 0x7fffffffu') + if b.startswith(('sext(', 'neg(', 'abs(')): + raise Unsupported('%s with a modified class mask %s' % (base, b)) + expr = 'x2w_class_f32(%s, %s)' % (value, sdwa_source(self.u(b), fields['src1_sel'], False)) + return self.write_compare(writes_exec, dst, expr) + words = [] + for token, key in ((a, 'src0_sel'), (b, 'src1_sel')): + sext = token.startswith('sext(') and token.endswith(')') + words.append(sdwa_source(self.u(token[5:-1] if sext else token), fields[key], sext)) + x, y = words if typ == 'u32' else ['int(%s)' % w for w in words] + return self.compare_result(base, cond, writes_exec, dst, x, y) + elif mods: raise Unsupported('%s with %s' % (base, mods)) - # v_cmp_class_f32 / v_cmpx_class_f32 test the binary32 class of the value in SRC0 against the - # class-bit mask in SRC1 (the ISA order: the float operand first, the integer mask second). - name = base.removesuffix('_sdwa') - if name in ('v_cmp_class_f32', 'v_cmpx_class_f32', 'v_cmp_class_f16', 'v_cmpx_class_f16'): - # The half form (issue #1855) takes the raw binary16 pattern in the low half of the operand - # word: its classes follow the half layout (exponent 5 bits, mantissa 10, quiet bit 0x0200) - # and abs/neg act on bit 15, so the value is never converted to float here. - f16 = name.endswith('_f16') - writes_exec = name in ('v_cmpx_class_f32', 'v_cmpx_class_f16') - sdwa = name != base - if f16 and sdwa: - raise Unsupported('SDWA form of %s' % name) - if sdwa: - self.check_compare_sdwa_destination(base, writes_exec, ops) - if len(ops) == 3: - dst, value, mask = ops - elif writes_exec and len(ops) == 2: - # The e32 and SDWA spellings write EXEC implicitly and print no destination. - dst, (value, mask) = 'exec', ops - else: - raise Unsupported('%s with %d operands' % (base, len(ops))) - if sdwa: - value, mask = self.compare_sdwa_sources(base, 'u32', [value, mask], mods, float_src0=True) - elif f16: - # abs() and - apply to bit 15 of the half, before the class test. - # The decoder prints an absolute source as |v4| and a negated one as -v4, so both - # spellings are accepted here as well as abs(...). - token = value - if re.fullmatch(r'-[1-9]\d*', token): - raise Unsupported('%s source %s: ambiguous signed inline half' % (base, value)) - negative = token.startswith('-') - if negative: - token = token[1:] - absolute = (token.startswith('|') and token.endswith('|')) or ( - token.startswith('abs(') and token.endswith(')')) - if absolute: - token = token[4:-1] if token.startswith('abs(') else token[1:-1] - if token in FLOATS or re.fullmatch(r'-[1-9]\d*', token): - # A float-printed operand would otherwise be lowered as its binary32 bit pattern. - raise Unsupported('%s source %s: f16 class compares need the raw half' % (base, value)) - bits = self.u(token, low16_only=True) - if absolute: - bits = '(%s & 0x7fffu)' % bits - if negative: - bits = '(%s ^ 0x8000u)' % bits - if mask in FLOATS: - raise Unsupported('%s mask %s: expected an integer class mask' % (base, mask)) - value, mask = bits, self.u(mask) + if cond == 'class': + # v_cmp_class: S0 is the value, S1 the class mask (llvm.amdgcn.class(x, mask)); neg/abs on S0 act on + # its sign bit, and an f16 value sits in the low half with inline float constants in half form. + if typ == 'f16': + value = self.u_mod(a, 0x8000) if reg_range(a.strip('-|')) else self.h(a) + expr = 'x2w_class_f16(%s, %s)' % (value, self.u(b)) else: - value, mask = self.f(value), self.u(mask) - cond = '(%s(%s) & %s) != 0u' % ('class16' if f16 else 'class32', value, mask) - predicate = '((%s) ? 1u : 0u)' % cond - # A narrowed EXEC must stay narrowed: intersect with it, as the generic compare path does. - if not self.exec_known: - predicate = '(exec & %s)' % predicate - if writes_exec or dst in ('exec', 'exec_lo'): - self.exec_known = False - self.emit('exec = %s;' % predicate) - elif dst in ('vcc', 'vcc_lo'): - self.emit('vcc = %s;' % predicate) - else: - reg = reg_range(dst) - if not reg or reg[0] != 's': - raise Unsupported('%s into %s' % (base, dst)) - d = reg[1] - self.set_s(d, predicate) - self.masks.add(d) - return None + expr = 'x2w_class_f32(%s, %s)' % (self.u_mod(a), self.u(b)) + return self.write_compare(writes_exec, dst, expr) + if typ == 'f16': + words = [self.u_mod(t, 0x8000) if reg_range(t.strip('-|')) else self.h(t) for t in (a, b)] + op = '>' if cond == 'gt' else '<' + expr = '((%s & 0x7fffu) <= 0x7c00u && (%s & 0x7fffu) <= 0x7c00u && f16tof32(%s) %s f16tof32(%s))' + return self.write_compare(writes_exec, dst, expr % (words[0], words[1], words[0], op, words[1])) + if typ == 'f32': + x, y = self.f(a), self.f(b) + elif typ in ('i16', 'u16'): + if not writes_exec and dst not in ('vcc', 'vcc_lo') and not re.fullmatch(r's[0-9]+', dst): + raise Unsupported('%s into %s' % (base, dst)) + x, y = (self._low16_source(base, t, typ == 'i16') for t in (a, b)) + elif typ == 'i32': + x, y = 'int(%s)' % self.u(a), 'int(%s)' % self.u(b) + else: + x, y = self.u(a), self.u(b) + ordered = '' + if typ == 'f32': + def word(tok): + # A float source's word before its neg/abs modifiers, as f() reads them; they keep a NaN a NaN. + if tok.startswith('-') and not re.match(r'-[\d.]', tok): + tok = tok[1:] + if tok.startswith('|') and tok.endswith('|'): + tok = tok[1:-1] + return self.u(tok) + ordered = ' && '.join('(%s & 0x7fffffffu) <= 0x7f800000u' % word(t) for t in (a, b)) + return self.compare_result(base, cond, writes_exec, dst, x, y, ordered) - m = re.fullmatch(r'v_cmp(x?)_(\w+?)_(f32|u32|i32|i16|u16)(_sdwa)?', base) - if not m: - raise Unsupported(base) - writes_exec, cond, typ, sdwa = m.group(1) == 'x', m.group(2), m.group(3), bool(m.group(4)) - # The 16-bit integer compares have the six relations only (gfx10 has no 16-bit f or t). Their SDWA forms - # are not lowered here (tools/pixel_aot.py has its own lowering of them). - if typ in ('i16', 'u16') and (sdwa or cond not in ('lt', 'eq', 'le', 'gt', 'ne', 'ge')): - raise Unsupported(base) + def compare_result(self, base, cond, writes_exec, dst, x, y, ordered=''): # f32 lg is ordered and not equal (false when either source is NaN) and nlg its negation (#1920). # HLSL != is unordered, so lg reads as less or greater, behind {2}: both source words not NaN, # tested on their bits. DXC marks float compares fast unless -Gis, and a driver may then fold @@ -5952,36 +5964,15 @@ def compare(self, base, ops, mods=()): 'nle': '!({2} && {0} <= {1})', 'ngt': '!({2} && {0} > {1})', 'nge': '!({2} && {0} >= {1})', 'nlg': '!({2} && ({0} < {1} || {0} > {1}))', 'o': '({2})', 'u': '!({2})', 't': 'true', 'f': 'false'} - # Conditions outside the table or dedicated lowering stay refused in both forms. if cond not in table: raise Unsupported(base) - if sdwa: - self.check_compare_sdwa_destination(base, writes_exec, ops) - if len(ops) == 3: - dst, a, b = ops - else: - dst, (a, b) = ('exec' if writes_exec else 'vcc'), ops - if sdwa: - # f32 sources: DWORD selections only, read as in the e64 form, so {2} tests the registers. - x, y = self.compare_sdwa_sources(base, typ, [a, b], mods, float_sources=typ == 'f32') - elif typ == 'f32': - x, y = self.f(a), self.f(b) - elif typ == 'i32': - x, y = 'int(%s)' % self.u(a), 'int(%s)' % self.u(b) - elif typ in ('i16', 'u16'): - x, y = (self._low16_source(base, t, typ == 'i16') for t in (a, b)) - else: - x, y = self.u(a), self.u(b) - def word(tok): - # A float source's word before its neg/abs modifiers, as f() reads them; they keep a NaN a NaN. - tok = self.split_neg(tok)[1] - if tok.startswith('|') and tok.endswith('|'): - tok = tok[1:-1] - return self.u(tok) - ordered = '' - if '{2}' in table[cond]: - ordered = ' && '.join('(%s & 0x7fffffffu) <= 0x7f800000u' % word(t) for t in (a, b)) - expr = '((%s) ? 1u : 0u)' % table[cond].format(x, y, ordered) + if '{2}' in table[cond] and not ordered: + # Only the plain and e64 f32 forms supply the source words the ordered test needs. + raise Unsupported('%s: no f32 source words for the ordered test' % base) + return self.write_compare(writes_exec, dst, '((%s) ? 1u : 0u)' % table[cond].format(x, y, ordered)) + + def write_compare(self, writes_exec, dst, expr): + """Store a 0/1 compare result as the lane's bit of exec, vcc or an SGPR mask.""" if not self.exec_known: expr = '(exec & %s)' % expr if writes_exec or dst in ('exec', 'exec_lo'): @@ -5990,20 +5981,18 @@ def word(tok): elif dst in ('vcc', 'vcc_lo'): self.emit('vcc = %s;' % expr) else: - # vcc_hi, exec_hi, m0 or a literal are not an SGPR the one-lane model holds a mask in; reg_range - # returned None for them and the index raised TypeError, which ended the whole translation. - reg = reg_range(dst) - if not reg or reg[0] != 's': - raise Unsupported('%s into %s' % (base, dst)) - d = reg[1] + r = reg_range(dst) + if not r or r[0] != 's': + # e.g. vcc_hi or exec_hi as a carry-out / compare destination: not an SGPR the one-lane model holds + raise Unsupported('compare or carry destination %s' % dst) + d = r[1] self.set_s(d, expr) self.masks.add(d) def export(self, asm): - # disasm_rdna2 prints a compressed EN that is not a whole channel pair (0x0, 0x3, 0xC or 0xF) as - # an explicit en:0x.. flag. As in pixel_aot, such a mask is refused rather than guessed. - m = re.fullmatch(r'exp (\w+) (.*?)((?: done| compr| vm| en:0x[0-9a-f]+)*)', asm) + m = re.fullmatch(r'exp (\w+) (.*?)((?: done| compr| vm)*)', asm) if not m: + # e.g. a compressed export with an unpaired enable mask, which the disassembler prints as en: raise Unsupported('export form %r' % asm) target, vals, flags = m.group(1), [v.strip() for v in m.group(2).split(',')], m.group(3).split() if getattr(self, 'kind', None) == 'ms' and not getattr(self, 'in_mesh_export', False): @@ -6013,13 +6002,28 @@ def export(self, asm): % next(f for f in flags if f.startswith('en:'))[3:]) if 'vm' in flags and not self.exec_known: self.emit('if (!(exec & 1)) discard;') + if target == 'null': + # The null target carries no data; titles use it to end a pixel stage (done, vm) that exports nothing + # else, so only the valid-mask discard above applies. + if any(v != 'off' for v in vals) or self.kind != 'ps': + raise Unsupported('null export with data: %s' % asm) + return None if target == 'mrtz': - if (self.kind != 'ps' or self.has_branches or self.blocks or not self.exec_known or 'depth' in self.exports - or 'compr' in flags or len(vals) != 4 or not re.fullmatch(r'v\d+', vals[0]) - or vals[1:] != ['off', 'off', 'off']): - raise Unsupported('MRTZ requires one uncompressed depth export in a straight-line pixel shader with entry EXEC') + # Z export: x is depth, y stencil, z the sample mask, w alpha for alpha-to-coverage. Only a depth-only + # export (SPI_SHADER_32_R) has an HLSL output, SV_Depth; the others are refused by channel. + if self.kind != 'ps' or 'compr' in flags or vals[0] == 'off' or any(v != 'off' for v in vals[1:]): + raise Unsupported('mrtz export other than depth alone: %s' % asm) self.exports['depth'] = True - self.emit('o.depth = %s;' % self.f(vals[0])) + self.emit('o.depth = F(%s);' % self.u(vals[0])) + return None + if target == 'pos1' and self.kind == 'vs' and getattr(self.pipe, 'vs_out_cntl', None) is not None \ + and 'compr' not in flags: + # With VS_OUT_MISC_VEC_ENA clear and VS_OUT_CCDIST0_VEC_ENA set, the export after pos0 is the first + # clip/cull distance vector (see clip_vector_width); D3D: SV_ClipDistance0. + n = clip_vector_width(self.pipe.vs_out_cntl, vals) + self.exports['clip'] = n + parts = ', '.join('F(%s)' % self.u(v) for v in vals[:n]) + self.emit('o.clip0 = %s;' % (parts if n == 1 else 'float%d(%s)' % (n, parts))) return None name = {'pos0': 'pos'}.get(target, target) if not re.fullmatch(r'pos|param\d+|mrt[0-7]', name): @@ -6032,20 +6036,21 @@ def export(self, asm): mask = sum(1 << c for c, v in enumerate(vals) if v != 'off') if 'compr' in flags: if name.startswith('param'): - self.compr_params.add(int(name[5:])) + self.__dict__.setdefault('compr_params', set()).add(int(name[5:])) if kind in ('uint', 'int'): raise Unsupported('packed integer export %s' % name) - # Two binary16 channels per register: the low pair (0, 1) from the first, the high pair - # (2, 3) from the second, each printed twice or as 'off', 'off'. - if vals[1] != vals[0] or vals[3] != vals[2]: + # A compressed export takes x, y from the two halves of its first register and z, w from the second. + # The enable mask is per pair (0x3 and 0xc), and the disassembler prints each enabled register twice + # and a disabled pair as "off, off"; a disabled pair reads 0 like an "off" channel of a plain export. + if vals[0] != vals[1] or vals[2] != vals[3]: raise Unsupported('compressed export operands %s' % ', '.join(vals)) - if mask != 0xF and not name.startswith('mrt'): - raise Unsupported('partial compressed export to %s' % name) - pairs = [] + exprs = [] for v in (vals[0], vals[2]): - r = self.u(v) if v != 'off' else None - pairs += ['f16tof32(%s)' % r, 'f16tof32(%s >> 16)' % r] if r else ['0.0', '0.0'] - exprs = pairs + if v == 'off': + exprs += ['0.0', '0.0'] + else: + word = self.u(v) + exprs += ['f16tof32(%s)' % word, 'f16tof32(%s >> 16)' % word] words = ['0u' if e == '0.0' else 'U(%s)' % e for e in exprs] elif kind in ('uint', 'int'): exprs = ['0u' if v == 'off' else self.u(v) for v in vals] @@ -6058,13 +6063,13 @@ def export(self, asm): exprs = ['0.0' if v == 'off' else 'F(%s)' % self.u(v) for v in vals] words = ['0u' if v == 'off' else self.u(v) for v in vals] if name.startswith('param'): - self.plain_params[int(name[5:])] = {c for c, v in enumerate(vals) if v == 'off'} + self.__dict__.setdefault('plain_params', {})[int(name[5:])] = {c for c, v in enumerate(vals) if v == 'off'} if name.startswith('mrt'): # One pipeline write mask per target: an export of no channel, or two exports of one target # with different channels, cannot be represented and is refused. if not mask: raise Unsupported('export to %s writes no channel' % name) - known = self.write_masks.setdefault(name, mask) + known = self.__dict__.setdefault('write_masks', {}).setdefault(name, mask) if known != mask: raise Unsupported('exports to %s write channel masks 0x%x and 0x%x' % (name, known, mask)) self.exports[name] = True @@ -6076,21 +6081,27 @@ def export(self, asm): # denormals (#1259). hlsl_vs() drops the line for attributes the pixel stage reads only # interpolated. self.emit('o.f%s = uint4(%s);' % (name, ', '.join(words))) - if 'compr' not in flags and kind not in ('uint', 'int', 'bits'): - # The binary16 halves of each word for v_interp_p1ll_f16 / v_interp_p2_f16 (see interp_f16); - # interpolated like param, and dropped by hlsl_vs() unless the pixel stage reads them. - for half, shift in (('lo', ''), ('hi', ' >> 16')): - self.emit('o.h%s_%s = float4(%s);' % (name, half, ', '.join( - '0.0' if v == 'off' else 'f16tof32(%s%s)' % (self.u(v), shift) for v in vals))) + if 'compr' in flags: + # The words of a compressed export are not the registers' halves (each half went to its own + # channel), so a binary16 read of this attribute is refused (Pipeline.check_half_reads). + self.__dict__.setdefault('compr_params', set()).add(int(name[5:])) + return None + # The binary16 halves of each word as f32, interpolated for v_interp_p2_f16 (the hardware interpolates + # each half of the parameter word). Dropped like the flat copy when the pixel stage does not read them. + self.emit('o.lo%s = float4(%s);' % (name, ', '.join( + '0.0' if w == '0u' else 'f16tof32(%s)' % w for w in words))) + self.emit('o.hi%s = float4(%s);' % (name, ', '.join( + '0.0' if w == '0u' else 'f16tof32((%s) >> 16)' % w for w in words))) return None # ---- output ------------------------------------------------------------------------------ + LOOP_PASSES = 64 + def body(self): """Statements of the whole program as structured HLSL.""" out = [] offsets = [b[0] for b in self.blocks] index = {off: i for i, off in enumerate(offsets)} - loops = any(t and t[0] in ('jump', 'branch') and t[-1] <= b[0] for b in self.blocks for t in [b[2]]) if len(self.blocks) == 1: return [' ' + line for line in self.blocks[0][1]] @@ -6099,26 +6110,52 @@ def goto(off): raise Unsupported('branch into the middle of a block (+0x%x)' % off) return index[off] out.append(' uint pc = 0;') - if loops: - out.append(' [loop] for (uint guard = 0; guard < 65536 && pc != 0xffffu; ++guard) {') - for i, (off, lines, term) in enumerate(self.blocks): - if off == getattr(self, 'mesh_allocation_block', None): - out.append(' {') + # Only the blocks between a loop head and its back edge run inside a dispatch loop: the intervals + # [head, source] of the back edges, merged where they overlap. A branch out of a region goes forward (a + # backward one would be a back edge inside the region), so the blocks outside the regions, tested in offset + # order, run each at most once like the loop-free form. Same execution as one loop over all blocks; FXC + # takes minutes on a large dispatch loop, so the loop is kept as small as the control flow allows. + regions = [] + for j, (_, _, term) in enumerate(self.blocks): + if term and term[0] in ('jump', 'branch') and goto(term[-1]) <= j: + regions.append([goto(term[-1]), j]) + regions.sort() + merged = [] + for lo, hi in regions: + if merged and lo <= merged[-1][1]: + merged[-1][1] = max(merged[-1][1], hi) else: - out.append(' %sif (pc == %d) {' % ('else ' if loops and i else '', i)) - out += [' ' + line for line in lines] + merged.append([lo, hi]) + starts = {lo: hi for lo, hi in merged} + inside = None + for i, (off, lines, term) in enumerate(self.blocks): + if i in starts: + inside = starts[i] + # A hard bound so that a wrong lowering costs a wrong pixel, never a GPU timeout: LOOP_PASSES + # passes through the region (one block visit per guard step). ASSUMED enough for the title's loops. + out.append(' [loop] for (uint guard = 0; guard < %du && pc >= %d && pc <= %d; ++guard) {' + % (self.LOOP_PASSES * (inside - i + 1), i, inside)) + indent = ' ' if inside is not None else '' + first = inside is not None and i in starts + out.append(' %s%sif (pc == %d) {' % (indent, 'else ' if inside is not None and not first else '', i)) + for line in lines: + if line in getattr(self, 'uniform_dpp', ()): + out.extend([' }', ' ' + line, ' if (pc == %d) {' % i]) + else: + out.append(' ' + indent + line) nxt = i + 1 if i + 1 < len(self.blocks) else 0xffff if not term: - out.append(' pc = %d;' % nxt) + out.append(' %spc = %d;' % (indent, nxt)) elif term[0] == 'end': - out.append(' pc = 0xffffu;') + out.append(' %spc = 0xffffu;' % indent) elif term[0] == 'jump': - out.append(' pc = %d;' % goto(term[1])) + out.append(' %spc = %d;' % (indent, goto(term[1]))) else: - out.append(' pc = (%s) ? %d : %d;' % (term[1], goto(term[2]), nxt)) - out.append(' }') - if loops: - out.append(' }') + out.append(' %spc = (%s) ? %d : %d;' % (indent, term[1], goto(term[2]), nxt)) + out.append(' %s}' % indent) + if inside is not None and i == inside: + out.append(' }') + inside = None return out def declarations(self): @@ -6127,89 +6164,63 @@ def declarations(self): lines.append(' uint %s;' % ', '.join('s%d = 0' % n for n in sorted(self.used_s))) if self.used_v: lines.append(' uint %s;' % ', '.join('v%d = 0' % n for n in sorted(self.used_v))) - packed = self.pipe.packed_position_vgpr - if self.kind == 'ps' and packed in self.used_v: + if getattr(self, 'shadow_v', None): + lines.append(' uint %s;' % ', '.join('xv%d = 0' % n for n in sorted(self.shadow_v))) + packed = getattr(self.pipe, 'packed_position_vgpr', None) # the tests' bare pipelines have none + if self.kind == 'ps' and packed is not None and packed in self.used_v: lines.append(' v%d = (uint(i.pos.x) & 0xffffu) | ((uint(i.pos.y) & 0xffffu) << 16);' % packed) + if self.kind == 'ps': + for reg, bit in sorted(getattr(self.pipe, 'ps_input_vgprs', {}).items()): + lines.append(' v%d = %s; // SPI input %s' % (reg, PS_INPUT_HLSL[bit], PS_INPUTS[bit][0])) if getattr(self, 'spill_slots', None): lines.append(' uint %s;' % ', '.join('sp%d_%d = 0' % k for k in sorted(self.spill_slots))) lines.append(' uint vcc = 0, exec = 1, m0 = 0, a = 0, w = 0; bool scc = false; float4 t = 0;') - if getattr(self, 'used_atomic', None): - if 'uint' in self.used_atomic: - lines.append(' uint ao = 0;') - if 'int' in self.used_atomic: - lines.append(' int ai = 0;') - lines += [' s%d = %s;' % kv for kv in sorted(getattr(self, 'materialized', {}).items())] + if self.used_h: + lines.append(' uint %s;' % ', '.join('h%d = 0' % k for k in sorted(self.used_h))) + if self.uses_q: + lines.append(' uint2 q = 0;') + if self.uses_swap: + lines.append(' uint xswap = 0;') + if self.uses_xsave: + lines.append(' uint xsave = 0;') return lines -# 32-bit raw MUBUF atomics: opcode_name -> (RWByteAddressBuffer method suffix, signed, is_sub, data_vgprs) -MUBUF_ATOMIC_OPS = { - 'buffer_atomic_swap': ('Exchange', False, False, 1), - 'buffer_atomic_cmpswap': ('CompareExchange', False, False, 2), - 'buffer_atomic_add': ('Add', False, False, 1), - 'buffer_atomic_sub': ('Add', False, True, 1), - 'buffer_atomic_smin': ('Min', True, False, 1), - 'buffer_atomic_umin': ('Min', False, False, 1), - 'buffer_atomic_smax': ('Max', True, False, 1), - 'buffer_atomic_umax': ('Max', False, False, 1), - 'buffer_atomic_and': ('And', False, False, 1), - 'buffer_atomic_or': ('Or', False, False, 1), - 'buffer_atomic_xor': ('Xor', False, False, 1), -} - -# Legacy straight-line LDS exchange ops checked by check_lds_exchange(). -LEGACY_LDS_EXCHANGE_OPS = frozenset(( - 'ds_write_b32', 'ds_read_b32', 'ds_read2_b32', 'ds_write_b64', 'ds_read_b64', 'ds_write_b128', 'ds_read_b128', -)) - -# Dual-offset & stride-64 32-bit LDS ops: name -> (is_write, offset_stride_bytes) -LDS_DUAL_OPS = { - 'ds_write2_b32': (True, 4), - 'ds_write2st64_b32': (True, 256), - 'ds_read2st64_b32': (False, 256), -} - -# 32-bit unsigned/bitwise LDS atomics: name -> (HLSL Interlocked* suffix, has_rtn) -LDS_ATOMIC_OPS = { - 'ds_add_u32': ('Add', False), - 'ds_min_u32': ('Min', False), - 'ds_max_u32': ('Max', False), - 'ds_and_b32': ('And', False), - 'ds_or_b32': ('Or', False), - 'ds_add_rtn_u32': ('Add', True), - 'ds_min_rtn_u32': ('Min', True), - 'ds_max_rtn_u32': ('Max', True), - 'ds_and_rtn_b32': ('And', True), - 'ds_or_rtn_b32': ('Or', True), - 'ds_wrxchg_rtn_b32': ('Exchange', True), -} - -LDS_DUAL_ATOMIC_OPS = frozenset((*LDS_DUAL_OPS, *LDS_ATOMIC_OPS)) - -# Unused w1 register field masks in RDNA 2 DS encoding (must be zero): -# w1[7:0]=ADDR, w1[15:8]=DATA0, w1[23:16]=DATA1, w1[31:24]=VDST. -LDS_UNUSED_W1_MASK = { - 'ds_write2_b32': 0xff000000, - 'ds_write2st64_b32': 0xff000000, - 'ds_read2st64_b32': 0x00ffff00, - **{op: (0x00ff0000 if has_rtn else 0xffff0000) for op, (_, has_rtn) in LDS_ATOMIC_OPS.items()}, -} - +# Identifiers Stage.lane_invariant accepts in an expression besides registers: pure HLSL functions and the +# translation's own pure helpers (x2w_* are accepted by prefix), the buffer Load method and literals. +LANE_INVARIANT_NAMES = frozenset(( + 'F', 'U', 'asuint', 'asfloat', 'asint', 'uint', 'int', 'float', 'uint2', 'float2', 'float3', 'float4', + 'min', 'max', 'abs', 'saturate', 'sqrt', 'rsqrt', 'exp2', 'log2', 'floor', 'ceil', 'trunc', 'frac', 'round', + 'sin', 'cos', 'countbits', 'firstbitlow', 'firstbithigh', 'reversebits', 'f16tof32', 'f32tof16', + 'mul_legacy', 'med3', 'clamp', 'Load', 'true', 'false')) +# The multiply-add rule for draw stages, X2W_DRAW_FMA: exact (default) = fused ops through fma in binary64 then one +# rounding (the binary32 product is exact in binary64, so this is the fused result except in rare double-rounding +# cases; needs DoublePrecisionFloatShaderOps), unfused ops as a `precise` multiply then add; precise = both through +# the precise multiply-add (deterministic, not the console's fused value); legacy = `a * b + c` as before (the +# compiler may fuse or not). Names differ from mesh2hlsl's x2w_fma/x2w_madp (same bodies) so a mesh pipeline, which +# emits its own, never gets two definitions. +FMA_FUSED = ('v_fma_f32', 'v_fmac_f32', 'v_fmamk_f32', 'v_fmaak_f32') +FMA_UNFUSED = ('v_mad_f32', 'v_mac_f32', 'v_madmk_f32', 'v_madak_f32') +DRAW_FMA = os.environ.get('X2W_DRAW_FMA', 'exact') +if DRAW_FMA not in ('exact', 'precise', 'legacy'): + raise SystemExit('X2W_DRAW_FMA: exact, precise or legacy, not %r' % DRAW_FMA) # name -> (source operand count, expression); operands are floats VEC_F = { 'v_add_f32': (2, '{0} + {1}'), 'v_sub_f32': (2, '{0} - {1}'), 'v_subrev_f32': (2, '{1} - {0}'), 'v_mul_f32': (2, '{0} * {1}'), 'v_mul_legacy_f32': (2, 'mul_legacy({0}, {1})'), 'v_min_f32': (2, 'min({0}, {1})'), 'v_max_f32': (2, 'max({0}, {1})'), - 'v_fmac_f32': (2, '{0} * {1} + {2}'), 'v_mac_f32': (2, 'mad32({0}, {1}, {2}, false)'), - 'v_fma_f32': (3, '{0} * {1} + {2}'), 'v_mad_f32': (3, 'mad32({0}, {1}, {2}, false)'), - 'v_mad_legacy_f32': (3, 'mad32({0}, {1}, {2}, true)'), + 'v_fmac_f32': (2, '{0} * {1} + {2}'), 'v_mac_f32': (2, '{0} * {1} + {2}'), + 'v_fma_f32': (3, '{0} * {1} + {2}'), 'v_mad_f32': (3, '{0} * {1} + {2}'), 'v_mad_legacy_f32': (3, 'mul_legacy({0}, {1}) + {2}'), 'v_fmamk_f32': (3, '{0} * {1} + {2}'), 'v_fmaak_f32': (3, '{0} * {1} + {2}'), - 'v_madmk_f32': (3, 'mad32({0}, {1}, {2}, false)'), 'v_madak_f32': (3, 'mad32({0}, {1}, {2}, false)'), + 'v_madmk_f32': (3, '{0} * {1} + {2}'), 'v_madak_f32': (3, '{0} * {1} + {2}'), 'v_rcp_f32': (1, '1.0 / {0}'), 'v_rcp_iflag_f32': (1, '1.0 / {0}'), 'v_rsq_f32': (1, 'rsqrt({0})'), 'v_sqrt_f32': (1, 'sqrt({0})'), 'v_exp_f32': (1, 'exp2({0})'), 'v_log_f32': (1, 'log2({0})'), 'v_floor_f32': (1, 'floor({0})'), 'v_ceil_f32': (1, 'ceil({0})'), 'v_trunc_f32': (1, 'trunc({0})'), 'v_fract_f32': (1, 'fract32({0})'), 'v_rndne_f32': (1, 'round({0})'), 'v_sin_f32': (1, 'sin({0} * 6.283185307)'), 'v_cos_f32': (1, 'cos({0} * 6.283185307)'), - 'v_med3_f32': (3, 'med3_32({0}, {1}, {2})'), 'v_min3_f32': (3, 'min({0}, min({1}, {2}))'), 'v_max3_f32': (3, 'max({0}, max({1}, {2}))'), + 'v_med3_f32': (3, 'med3({0}, {1}, {2})'), 'v_min3_f32': (3, 'min({0}, min({1}, {2}))'), 'v_max3_f32': (3, 'max({0}, max({1}, {2}))'), + # Cube-map face selection; x2w_cube() returns (face id, sc, tc, 2 * major axis), see HELPERS. + 'v_cubeid_f32': (3, 'x2w_cube({0}, {1}, {2}).x'), 'v_cubesc_f32': (3, 'x2w_cube({0}, {1}, {2}).y'), + 'v_cubetc_f32': (3, 'x2w_cube({0}, {1}, {2}).z'), 'v_cubema_f32': (3, 'x2w_cube({0}, {1}, {2}).w'), } # Conversions whose result is binary32. The expression is the float value, so an output modifier # (clamp, mul:2, mul:4, div:2) can wrap it the way it wraps any other float result. The uint-result @@ -6228,20 +6239,23 @@ def declarations(self): 'v_not_b32': (1, '~{0}'), 'v_lshlrev_b32': (2, '{1} << ({0} & 31)'), 'v_lshrrev_b32': (2, '{1} >> ({0} & 31)'), 'v_ashrrev_i32': (2, 'uint(int({1}) >> ({0} & 31))'), 'v_min_u32': (2, 'min({0}, {1})'), 'v_max_u32': (2, 'max({0}, {1})'), 'v_min_i32': (2, 'uint(min(int({0}), int({1})))'), 'v_max_i32': (2, 'uint(max(int({0}), int({1})))'), - 'v_min3_u32': (3, 'min(min({0}, {1}), {2})'), - 'v_max3_u32': (3, 'max(max({0}, {1}), {2})'), + # Three-operand integer forms (RDNA2 ISA: V_MIN3/V_MAX3/V_MED3 _I32/_U32; median = max(min(a, b), min(max(a, b), c)), + # the identity the f32 med3 helper uses). + 'v_min3_u32': (3, 'min({0}, min({1}, {2}))'), 'v_max3_u32': (3, 'max({0}, max({1}, {2}))'), + 'v_min3_i32': (3, 'uint(min(int({0}), min(int({1}), int({2}))))'), + 'v_max3_i32': (3, 'uint(max(int({0}), max(int({1}), int({2}))))'), 'v_med3_u32': (3, 'max(min({0}, {1}), min(max({0}, {1}), {2}))'), - 'v_min3_i32': (3, 'uint(min(min(int({0}), int({1})), int({2})))'), - 'v_max3_i32': (3, 'uint(max(max(int({0}), int({1})), int({2})))'), 'v_med3_i32': (3, 'uint(max(min(int({0}), int({1})), min(max(int({0}), int({1})), int({2}))))'), 'v_cvt_u32_f32': (1, 'uint(max(F({0}), 0.0))'), - 'v_cvt_f16_f32': (1, 'f32tof16(F({0}))'), + 'v_cvt_f16_f32': (1, 'x2w_f32tof16_rne(F({0}))'), # nearest even (MODE 0; check_round16 refuses other modes) 'v_bfe_u32': (3, '({0} >> ({1} & 31)) & ((1u << ({2} & 31)) - 1)'), 'v_mad_u32_u24': (3, '({0} & 0xffffffu) * ({1} & 0xffffffu) + {2}'), 'v_mad_i32_i24': (3, 'asuint(asint({0} << 8) >> 8) * asuint(asint({1} << 8) >> 8) + {2}'), 'v_lshl_add_u32': (3, '({0} << ({1} & 31)) + {2}'), 'v_add_lshl_u32': (3, '({0} + {1}) << ({2} & 31)'), 'v_add3_u32': (3, '{0} + {1} + {2}'), - 'v_or3_b32': (3, '{0} | {1} | {2}'), 'v_xor3_b32': (3, '{0} ^ {1} ^ {2}'), 'v_and_or_b32': (3, '({0} & {1}) | {2}'), 'v_lshl_or_b32': (3, '({0} << ({1} & 31)) | {2}'), + 'v_or3_b32': (3, '{0} | {1} | {2}'), 'v_xor3_b32': (3, '{0} ^ {1} ^ {2}'),'v_and_or_b32': (3, '({0} & {1}) | {2}'), 'v_lshl_or_b32': (3, '({0} << ({1} & 31)) | {2}'), 'v_xad_u32': (3, '({0} ^ {1}) + {2}'), 'v_bfi_b32': (3, '({0} & {1}) | (~{0} & {2})'), 'v_mul_u32_u24': (2, '({0} & 0xffffffu) * ({1} & 0xffffffu)'), + # v_bfm_b32: a mask of S0[4:0] ones shifted left by S1[4:0] (RDNA 2 ISA VOP3; same formula as s_bfm_b32). + 'v_bfm_b32': (2, '(((1u << ({0} & 31)) - 1) << ({1} & 31))'), 'v_mul_i32_i24': (2, 'asuint(asint({0} << 8) >> 8) * asuint(asint({1} << 8) >> 8)'), # Per-lane bit operations (AMD RDNA 2 ISA reference). The bitscan results count from the most significant # bit for the "h" forms and read 0xffffffff when no bit qualifies; firstbitlow(0) is already 0xffffffff. @@ -6253,6 +6267,10 @@ def declarations(self): 'v_ffbh_u32': (1, '({0} == 0u ? 0xffffffffu : 31u - firstbithigh({0}))'), 'v_ffbh_i32': (1, '({0} == 0u || {0} == 0xffffffffu ? 0xffffffffu : 31u - firstbithigh(asint({0}) < 0 ? ~{0} : {0}))'), 'v_bfrev_b32': (1, 'reversebits({0})'), + # The high word of the unsigned 64-bit product; shader model 5.1 has no 64-bit integers (see HELPERS). + 'v_mul_hi_u32': (2, 'x2w_mul_hi_u32({0}, {1})'), + # D = S0[15:0] * S1[15:0] + S2 (op_sel, which picks other halves, arrives as a modifier and is refused). + 'v_mad_u32_u16': (3, '({0} & 0xffffu) * ({1} & 0xffffu) + {2}'), 'v_sad_u8': (3, 'sad_u8({0}, {1}, {2})'), 'v_sad_u16': (3, 'sad_u16({0}, {1}, {2})'), 'v_sad_u32': (3, 'sad_u32({0}, {1}, {2})'), @@ -6261,8 +6279,222 @@ def declarations(self): 'v_cvt_pk_u16_u32': (2, 'min({0}, 0xffffu) | (min({1}, 0xffffu) << 16u)'), 'v_cvt_pk_i16_i32': (2, '(asuint(clamp(asint({0}), -32768, 32767)) & 0xffffu) | ' '(asuint(clamp(asint({1}), -32768, 32767)) << 16u)'), + 'v_cvt_pk_u16_u32': (2, 'min({0}, 0xffffu) | (min({1}, 0xffffu) << 16u)'), + 'v_cvt_pk_i16_i32': (2, '(asuint(clamp(asint({0}), -32768, 32767)) & 0xffffu) | ' + '(asuint(clamp(asint({1}), -32768, 32767)) << 16u)'), } VOP3_ONLY_VEC_U = frozenset(('v_cvt_pk_u16_u32', 'v_cvt_pk_i16_i32')) +# HLSL helpers, each emitted only by pipelines whose code calls it. The integer helpers are single expressions so +# tests/startup_gfx2hlsl_coverage_check.py can evaluate their text against plain integer references. +# x2w_mul_hi_u32: bits 63:32 of the unsigned product, from four 16-bit partial products; the carry into bit 32 +# comes from the high half of the low product plus the low halves of the two cross products (each sum < 2^18). +MUL_HI_U32 = ('(a >> 16) * (b >> 16) + (((a & 0xffffu) * (b >> 16)) >> 16) + (((a >> 16) * (b & 0xffffu)) >> 16) + ' + '(((((a & 0xffffu) * (b & 0xffffu)) >> 16) + (((a & 0xffffu) * (b >> 16)) & 0xffffu) + ' + '(((a >> 16) * (b & 0xffffu)) & 0xffffu)) >> 16)') +# v_cmp_class: the bit index of the IEEE class of x in the S1 mask (LLVM SIDefines.h ClassFlags): 0 signaling NaN, +# 1 quiet NaN, 2 -inf, 3 -normal, 4 -subnormal, 5 -0, 6 +0, 7 +subnormal, 8 +normal, 9 +inf. Classified on the bits, +# so no float compare or denormal flush can change the answer. +CLASS_F32 = ('(((x >> 23) & 255u) == 255u ? ((x & 0x7fffffu) != 0u ? ((x >> 22) & 1u) : ((x >> 31) != 0u ? 2u : 9u)) : ' + '((x >> 23) & 255u) != 0u ? ((x >> 31) != 0u ? 3u : 8u) : ' + '(x & 0x7fffffu) != 0u ? ((x >> 31) != 0u ? 4u : 7u) : ((x >> 31) != 0u ? 5u : 6u))') +CLASS_F16 = ('(((x >> 10) & 31u) == 31u ? ((x & 0x3ffu) != 0u ? ((x >> 9) & 1u) : (((x >> 15) & 1u) != 0u ? 2u : 9u)) : ' + '((x >> 10) & 31u) != 0u ? (((x >> 15) & 1u) != 0u ? 3u : 8u) : ' + '(x & 0x3ffu) != 0u ? (((x >> 15) & 1u) != 0u ? 4u : 7u) : (((x >> 15) & 1u) != 0u ? 5u : 6u))') +LSHR64_LO = ('((n & 63u) == 0u ? l : (n & 63u) < 32u ? (l >> (n & 63u)) | (h << (32u - (n & 63u))) : ' + 'h >> ((n & 63u) - 32u))') +LSHR64_HI = '((n & 63u) < 32u ? h >> (n & 63u) : 0u)' +LSHL64_LO = '((n & 63u) < 32u ? l << (n & 63u) : 0u)' +LSHL64_HI = ('((n & 63u) == 0u ? h : (n & 63u) < 32u ? (h << (n & 63u)) | (l >> (32u - (n & 63u))) : ' + 'l << ((n & 63u) - 32u))') +# SCA operations folded when every operand is a known constant (Stage.scalar), as their SCA texts compute them +# (AMD RDNA ISA: S_BREV_B32 D.u[31:0] = S0.u[0:31], no SCC write). s_bfm_b32 has its own folding handler. +SCALAR_CONST_FOLD = { + 's_brev_b32': lambda a: int('{:032b}'.format(a)[::-1], 2), +} + +HELPERS = { + # The product of binary16 inputs is exact in f32. Use FastTwoSum for the addition + # residual, then round to odd at f32 precision. The final conversion to f16 can + # decide ties and directed rounding without double rounding. + 'x2w_half_madd_odd': '''float x2w_half_madd_odd(float a, float b, float c) { + precise float p = a * b; + precise float sum = p + c; + if (!isfinite(sum)) return sum; + precise float hi = abs(p) >= abs(c) ? p : c; + precise float lo = abs(p) >= abs(c) ? c : p; + precise float tail = lo - (sum - hi); + uint u = asuint(sum); + if (tail == 0.0 || (u & 1u)) return sum; + return asfloat((tail > 0.0) == (sum > 0.0) ? u + 1u : u - 1u); + }''', + 'x2w_mul_hi_u32': 'uint x2w_mul_hi_u32(uint a, uint b) { return %s; }' % MUL_HI_U32, + 'x2w_class_f32': 'uint x2w_class_f32(uint x, uint mask) { return (mask >> %s) & 1u; }' % CLASS_F32, + # binary16 rounding toward zero (MODE[3:2] = 3, see Stage.op_s_round_mode): f32tof16, then one step toward zero + # when that rounded away from zero. Exact if f32tof16 rounds to nearest or toward zero: overflow to inf steps + # back to 0x7bff; a NaN or an exactly representable value stays (the compare is false). + 'x2w_f32tof16_rtz': ('uint x2w_f32tof16_rtz(float x) { uint h = f32tof16(x); ' + 'return abs(f16tof32(h)) > abs(x) ? h - 1u : h; }'), + # binary16 rounding to nearest even (MODE[3:2] = 0): t = the toward-zero result (as x2w_f32tof16_rtz, inlined so + # the helper stands alone), u = the next value away from zero (0x7c00 counts as 65536, the first value past the + # range, so 65520 and above round to inf); the nearer wins, a tie goes to the even one. The two distances are + # exact in f32 (Sterbenz: |x| lies within [lo, 2 lo] of the f16 neighbours, or lo is 0). inf and NaN stay. + 'x2w_f32tof16_rne': ('uint x2w_f32tof16_rne(float x) { uint t = f32tof16(x); float a = abs(x); ' + 'if (abs(f16tof32(t)) > a) t -= 1u; if ((t & 0x7c00u) == 0x7c00u) return t; ' + 'float lo = abs(f16tof32(t)); if (a == lo) return t; uint u = t + 1u; ' + 'float hi = (u & 0x7fffu) == 0x7c00u ? 65536.0 : abs(f16tof32(u)); ' + 'float dl = a - lo, dh = hi - a; return (dh < dl || (dh == dl && (t & 1u) != 0u)) ? u : t; }'), + 'x2w_class_f16':'uint x2w_class_f16(uint x, uint mask) { return (mask >> %s) & 1u; }' % CLASS_F16, + # The words of a 64-bit shift of (l, h) by n[5:0]. HLSL masks shift counts to five bits, so a count of 0 + # (where 32 - n would wrap to a shift by 0) and counts of 32..63 are separate cases. + 'x2w_lshr64_lo': 'uint x2w_lshr64_lo(uint l, uint h, uint n) { return %s; }' % LSHR64_LO, + 'x2w_lshr64_hi': 'uint x2w_lshr64_hi(uint l, uint h, uint n) { return %s; }' % LSHR64_HI, + 'x2w_lshl64_lo': 'uint x2w_lshl64_lo(uint l, uint h, uint n) { return %s; }' % LSHL64_LO, + 'x2w_lshl64_hi': 'uint x2w_lshl64_hi(uint l, uint h, uint n) { return %s; }' % LSHL64_HI, + # v_cube{id,sc,tc,ma}_f32 as LLVM's constant folder defines them (ConstantFoldAMDGCNCubeIntrinsic): the + # major axis is z when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|, else x; a negative major axis is one + # that is below zero (not -0, not NaN). ma is twice the major-axis component. + 'x2w_cube': ('float4 x2w_cube(float a, float b, float c) { ' + 'if (abs(c) >= abs(a) && abs(c) >= abs(b)) return float4(c < 0.0 ? 5.0 : 4.0, c < 0.0 ? -a : a, -b, c + c); ' + 'if (abs(b) >= abs(a)) return float4(b < 0.0 ? 3.0 : 2.0, a, b < 0.0 ? -c : c, b + b); ' + 'return float4(a < 0.0 ? 1.0 : 0.0, a < 0.0 ? c : -c, -b, a + a); }'), + # One 16-bit half of v_cvt_pknorm_{u16,i16}_f32, per Mesa ACO selection (Mesa main 13ebbc00, + # src/amd/compiler/instruction_selection/aco_select_nir_alu.cpp selects nir pack_[us]norm_2x16 to these + # opcodes) with the NIR definition (src/compiler/nir/nir_constant_expressions.py pack_[us]norm_1x16): + # (uint16_t)(int)roundeven(CLAMP(x, lo, 1) * 65535 or 32767). Mesa's CLAMP (src/util/macros.h) is + # "X > MIN ? (X > MAX ? MAX : X) : MIN", so NaN gives MIN: unorm 0, snorm -32767 (0x8001). The NaN case is + # decided on the bits so no compiler min/max rewrite can change it; HLSL round() rounds half to even. + 'x2w_pknorm_u16': ('uint x2w_pknorm_u16(float x) { if ((asuint(x) & 0x7fffffffu) > 0x7f800000u) return 0u; ' + 'return uint(round(clamp(x, 0.0, 1.0) * 65535.0)); }'), + 'x2w_pknorm_i16': ('uint x2w_pknorm_i16(float x) { if ((asuint(x) & 0x7fffffffu) > 0x7f800000u) return 0x8001u; ' + 'return uint(int(round(clamp(x, -1.0, 1.0) * 32767.0))) & 0xffffu; }'), +} + +# gfx10 buffer FORMAT codes (V# word 3 [18:12]) the draw runtime can synthesize for a typed buffer view +# (gfx10_view_words.h gfx10_buffer_words; raw and structured views get 22, 32_FLOAT) and their channels, x first +# from bit 0: (bit widths, numeric kind). Mixed widths list x, y, z, w as the bits rise: 10_11_11_FLOAT is x 11, y +# 11, z 10; 2_10_10_10 is x 10, y 10, z 10, w 2. Codes from Mesa's gfx10 format table, as in gfx10_view_words.h. +BUF_FORMATS = { + 1: ((8,), 'unorm'), 2: ((8,), 'snorm'), 5: ((8,), 'uint'), 6: ((8,), 'sint'), + 7: ((16,), 'unorm'), 8: ((16,), 'snorm'), 11: ((16,), 'uint'), 12: ((16,), 'sint'), 13: ((16,), 'float'), + 14: ((8, 8), 'unorm'), 15: ((8, 8), 'snorm'), 18: ((8, 8), 'uint'), 19: ((8, 8), 'sint'), + 20: ((32,), 'uint'), 21: ((32,), 'sint'), 22: ((32,), 'float'), + 23: ((16, 16), 'unorm'), 24: ((16, 16), 'snorm'), 27: ((16, 16), 'uint'), 28: ((16, 16), 'sint'), + 29: ((16, 16), 'float'), + 36: ((11, 11, 10), 'float'), + 50: ((10, 10, 10, 2), 'unorm'), 54: ((10, 10, 10, 2), 'uint'), + 56: ((8, 8, 8, 8), 'unorm'), 57: ((8, 8, 8, 8), 'snorm'), 60: ((8, 8, 8, 8), 'uint'), 61: ((8, 8, 8, 8), 'sint'), + 62: ((32, 32), 'uint'), 63: ((32, 32), 'sint'), 64: ((32, 32), 'float'), + 65: ((16,) * 4, 'unorm'), 66: ((16,) * 4, 'snorm'), 69: ((16,) * 4, 'uint'), 70: ((16,) * 4, 'sint'), + 71: ((16,) * 4, 'float'), + 72: ((32,) * 3, 'uint'), 73: ((32,) * 3, 'sint'), 74: ((32,) * 3, 'float'), + 75: ((32,) * 4, 'uint'), 76: ((32,) * 4, 'sint'), 77: ((32,) * 4, 'float'), +} + + +def buf_format_channel(widths, kind, k): + """HLSL for channel k (a Python int) of an element at byte address a of ByteAddressBuffer b, as a uint.""" + pos, n = sum(widths[:k]), widths[k] + field = 'b.Load(a + %du)' % (pos // 8) if n == 32 else \ + '((ldu(b, a + %du) >> %du) & 0x%xu)' % (4 * (pos // 32), pos % 32, (1 << n) - 1) + if kind == 'uint' or (kind == 'float' and n == 32): + return field + if kind == 'sint': + return field if n == 32 else 'uint(int(%s << %du) >> %du)' % (field, 32 - n, 32 - n) + if kind == 'unorm': + return 'U(float(%s) / %d.0)' % (field, (1 << n) - 1) + if kind == 'snorm': + return 'U(max(float(int(%s << %du) >> %du) / %d.0, -1.0))' % (field, 32 - n, 32 - n, (1 << (n - 1)) - 1) + # binary16, and the unsigned 11-bit (5-bit exponent, 6-bit mantissa) and 10-bit (5, 5) floats, which are the + # upper bits of a binary16 without its sign + return 'U(f16tof32(%s))' % (field if n == 16 else '(%s << %du)' % (field, 15 - n)) + + +def buf_format_helper(): + """x2w_fmt_load(b, a, w3, c): channel c of a buffer_load_format_* result, from V# word 3 w3 (udsrc bufword3). + + DST_SEL_X/Y/Z/W ([2:0] [5:3] [8:6] [11:9]): 0 -> 0, 1 -> 1 (1.0 for a float format, 1 for an integer one), + 4..7 -> element channel x..w. A channel the format lacks reads 0 (w reads 1, as the fill 0001); a FORMAT code + not in BUF_FORMATS (0 = invalid, which the runtime gives for raw-copy, vertex and root sources) reads 0 in + every channel, as do selectors 2 and 3. These fills are assumptions, not measured.""" + lines = ['uint x2w_fmt_chan(ByteAddressBuffer b, uint a, uint f, uint k, uint one) {'] + for code, (widths, kind) in sorted(BUF_FORMATS.items()): + chans = ' '.join('if (k == %du) return %s;' % (k, buf_format_channel(widths, kind, k)) for k in range(len(widths))) + lines.append(' if (f == %du) { %s return k == 3u ? one : 0u; }' % (code, chans)) + lines.append(' return 0u; }') + known = ' || '.join('f == %du' % c for c in sorted(BUF_FORMATS)) + ints = ' || '.join('f == %du' % c for c, (_, kind) in sorted(BUF_FORMATS.items()) if kind in ('uint', 'sint')) + lines.append('uint x2w_fmt_load(ByteAddressBuffer b, uint a, uint w3, uint c) {') + lines.append(' uint f = (w3 >> 12) & 127u, s = (w3 >> (3u * c)) & 7u;') + lines.append(' if (!(%s) || s == 0u || s == 2u || s == 3u) return 0u;' % known) + lines.append(' uint one = (%s) ? 1u : 0x3f800000u;' % ints) + lines.append(' return s == 1u ? one : x2w_fmt_chan(b, a, f, s - 4u, one); }') + return '\n'.join(lines) + + +FMT_KIND = {'uint': 0, 'sint': 1, 'unorm': 2, 'snorm': 3, 'float': 4} + + +def buf_format_word(code): + """x2w_fmt_tab entry: channel widths x, y, z, w in 6-bit fields [5:0] [11:6] [17:12] [23:18] (0 = absent), kind + in [26:24] (FMT_KIND); 0 for a code not in BUF_FORMATS.""" + if code not in BUF_FORMATS: + return 0 + widths, kind = BUF_FORMATS[code] + word = FMT_KIND[kind] << 24 + for k, n in enumerate(widths): + word |= n << (6 * k) + return word + + +def buf_format_helper_table(): + """The same x2w_fmt_load as buf_format_helper, written once for every format: the format code indexes a constant + table of channel widths and kind, and one channel decoder serves all formats. Values are the same as the per-format + chain's (same field, sign extension, UNORM/SNORM divisor, binary16 widening), except that the UNORM/SNORM divisor + is a run-time value here rather than a literal, so the compiler cannot replace the division by a multiply.""" + size = max(BUF_FORMATS) + 1 + table = ', '.join('0x%08xu' % buf_format_word(c) for c in range(size)) + return '\n'.join([ + 'static const uint x2w_fmt_tab[%d] = { %s };' % (size, table), + 'uint x2w_fmt_chan(ByteAddressBuffer b, uint a, uint d, uint k, uint one) {', + ' uint n = (d >> (6u * k)) & 63u;', + ' if (n == 0u) return k == 3u ? one : 0u;', + ' uint pos = (k > 0u ? (d & 63u) : 0u) + (k > 1u ? ((d >> 6) & 63u) : 0u) + (k > 2u ? ((d >> 12) & 63u) : 0u);', + ' uint kind = (d >> 24) & 7u, sh = 32u - n;', + ' uint raw = n == 32u ? b.Load(a + pos / 8u) : ((ldu(b, a + 4u * (pos / 32u)) >> (pos % 32u)) & ((1u << n) - 1u));', + ' int sv = int(raw << sh) >> sh;', + ' if (kind == 0u || (kind == 4u && n == 32u)) return raw;', + ' if (kind == 1u) return uint(sv);', + ' if (kind == 2u) return U(float(raw) / float((1u << n) - 1u));', + ' if (kind == 3u) return U(max(float(sv) / float((1u << (n - 1u)) - 1u), -1.0));', + ' return U(f16tof32(n == 16u ? raw : raw << (15u - n))); }', + 'uint x2w_fmt_load(ByteAddressBuffer b, uint a, uint w3, uint c) {', + ' uint f = (w3 >> 12) & 127u, s = (w3 >> (3u * c)) & 7u;', + ' uint d = f < %du ? x2w_fmt_tab[f] : 0u;' % size, + ' if (d == 0u || s == 0u || s == 2u || s == 3u) return 0u;', + ' uint one = ((d >> 24) & 7u) <= 1u ? 1u : 0x3f800000u;', + ' return s == 1u ? one : x2w_fmt_chan(b, a, d, s - 4u, one); }']) + + +# The table form: fxc 10.0.26100 took 432.6 s for a vertex stage with two calls of the per-format chain and 0.6 s with +# this one (translator_work NOTES round 5). buf_format_helper stays as the reference the check compares against. +HELPERS['x2w_fmt_load'] = buf_format_helper_table() +HELPERS['x2w_fmt_store'] = '\n'.join([ + 'void x2w_fmt_store(RWByteAddressBuffer b, uint a, uint w3, uint4 v, uint m) {', + ' uint f = (w3 >> 12) & 127u;', + ' uint n = (f >= 20u && f <= 22u) ? 1u : (f >= 62u && f <= 64u) ? 2u : (f >= 72u && f <= 74u) ? 3u :', + ' (f >= 75u && f <= 77u) ? 4u : 0u;', + ' n = min(n, m);', + ' if (n > 0u) b.Store(a, v.x);', + ' if (n > 1u) b.Store(a + 4u, v.y);', + ' if (n > 2u) b.Store(a + 8u, v.z);', + ' if (n > 3u) b.Store(a + 12u, v.w); }']) +HELPERS['x2w_fma_exact'] = ('float x2w_fma_exact(float a, float b, float c) ' + '{ return (float)fma((double)a, (double)b, (double)c); }') +HELPERS['x2w_mad_precise'] = ('float x2w_mad_precise(float a, float b, float c) ' + '{ precise float p = a * b; precise float r = p + c; return r; }') +# VEC_U conversions whose result is a binary32 value, so the VOP3 output modifiers apply to it. +FLOAT_RESULT_U = frozenset(('v_cvt_f32_u32', 'v_cvt_f32_i32', 'v_cvt_f32_ubyte0', 'v_cvt_f32_ubyte1', + 'v_cvt_f32_ubyte2', 'v_cvt_f32_ubyte3', 'v_cvt_f32_f16')) # scalar ops: (expression over uint sources, SCC rule with $ for the result or None) # Scalar ops that write SCC on the hardware (carry, overflow, or which source was selected) but have # no SCC template here: the emitted scc keeps its previous value, so the uniformity proof stops @@ -6284,32 +6516,47 @@ def declarations(self): 's_add_i32': ('{0} + {1}', None), 's_add_u32': ('{0} + {1}', None), 's_sub_i32': ('{0} - {1}', None), 's_sub_u32': ('{0} - {1}', None), 's_mul_i32': ('{0} * {1}', None), 's_min_u32': ('min({0}, {1})', None), 's_max_u32': ('max({0}, {1})', None), 's_min_i32': ('uint(min(int({0}), int({1})))', None), 's_max_i32': ('uint(max(int({0}), int({1})))', None), - 's_bfe_u32': ('({0} >> ({1} & 31)) & ((({1} >> 16) & 127) >= 32 ? 0xffffffffu : ((1u << (({1} >> 16) & 31)) - 1))', '$ != 0'), + 's_bfe_u32': ('({0} >> ({1} & 31)) & ((1u << (({1} >> 16) & 127)) - 1)', '$ != 0'), 's_brev_b32': ('reversebits({0})', None), - # s_mul_hi_u32: high 32 bits of the unsigned 64-bit product; SCC unchanged. - 's_mul_hi_u32': ('mul_hi_u32({0}, {1})', None), + # s_bcnt0/1_i32_b32: the count of zero / one bits of S0; SCC = (D != 0) (AMD RDNA 2 ISA SOP1, LLVM + # SOPInstructions.td: Defs = [SCC]). + 's_bcnt1_i32_b32': ('countbits({0})', '$ != 0'), 's_bcnt0_i32_b32': ('32u - countbits({0})', '$ != 0'), + # s_ff1/s_ff0_i32_b32: the index of the lowest one / zero bit of S0, -1 when there is none; SCC unchanged (AMD + # RDNA 2 ISA SOP1; LLVM SOPInstructions.td has no SCC def; it selects AMDGPUffbl_b32 = cttz_zero_undef with + # the -1 result). HLSL firstbitlow returns 0xffffffff for 0 as well. + 's_ff1_i32_b32': ('firstbitlow({0})', None), 's_ff0_i32_b32': ('firstbitlow(~{0})', None), # s_sext_i32_iN: sign-extend the low N bits of S0; SCC unchanged. 's_sext_i32_i8': ('uint(int({0} << 24) >> 24)', None), 's_sext_i32_i16': ('uint(int({0} << 16) >> 16)', None), - # s_pack_*_b32_b16: two halfwords of the sources into one word; SCC unchanged. - 's_pack_ll_b32_b16': ('({0} & 0xffffu) | ({1} << 16)', None), 's_pack_lh_b32_b16': ('({0} & 0xffffu) | ({1} & 0xffff0000u)', None), - 's_pack_hh_b32_b16': ('({0} >> 16) | ({1} & 0xffff0000u)', None), - # s_absdiff_i32: D = S0 - S1 wrapped to 32 bits, negated if negative (INT_MIN stays); SCC = result != 0. - 's_absdiff_i32': ('asuint(abs(asint({0} - {1})))', '$ != 0'), # s_bfm_b32: a mask of S0[4:0] ones shifted left by S1[4:0]; SCC unchanged. 's_bfm_b32': ('(((1u << ({0} & 31)) - 1) << ({1} & 31))', None), - # s_lshlN_add_u32: low 32 bits of (S0 << N) + S1. SHIFT_ADD also supplies SCC for wide overflow. + # s_absdiff_i32: D = |S0 - S1| with the 32-bit wrapping difference (|INT_MIN| stays INT_MIN); SCC = (D != 0) + # (RDNA 2 ISA SOP2; LLVM SOPInstructions.td Defs = [SCC]). + 's_absdiff_i32': ('uint(abs(int({0} - {1})))', '$ != 0'), + 's_mul_hi_u32': ('x2w_mul_hi_u32({0}, {1})', None), + # LLVM SOPInstructions.td: s_lshlN_add_u32 selects shlN_add, (S0 << N) + S1; it defines SCC, not modelled. 's_lshl1_add_u32': ('({0} << 1) + {1}', None), 's_lshl2_add_u32': ('({0} << 2) + {1}', None), 's_lshl3_add_u32': ('({0} << 3) + {1}', None), 's_lshl4_add_u32': ('({0} << 4) + {1}', None), + # s_abs_i32 is what LLVM selects for smax(x, -x) (so abs(INT_MIN) stays INT_MIN); it defines SCC, not modelled. + 's_abs_i32': ('uint(max(int({0}), -int({0})))', None), + 's_pack_ll_b32_b16': ('({0} & 0xffffu) | ({1} << 16)', None), + 's_pack_hh_b32_b16': ('({0} >> 16) | ({1} & 0xffff0000u)', None), + # LLVM SOPInstructions.td S_SEXT_I32_I8 / S_SEXT_I32_I16: sext_inreg of S0 to i8 / i16; no SCC def. + 's_sext_i32_i8': ('uint(int({0} << 24) >> 24)', None), 's_sext_i32_i16': ('uint(int({0} << 16) >> 16)', None), } -# SCA operations folded when every operand is a known constant (Stage.scalar), computing what their SCA text -# computes (AMD RDNA 2 ISA: S_BREV_B32 D.u[31:0] = S0.u[0:31], no SCC write). s_bfm_b32 has its own handler. -SCALAR_CONST_FOLD = { - 's_brev_b32': lambda a: int('{:032b}'.format(a)[::-1], 2), -} -# shift amount of the scalar shift-and-add forms; their SCC is a carry from the sources, not a rule over the result -SHIFT_ADD = {'s_lshl1_add_u32': 1, 's_lshl2_add_u32': 2, 's_lshl3_add_u32': 3, 's_lshl4_add_u32': 4} +# Scalar ops whose SCC result the translation does not compute (LLVM SOPInstructions.td lists SCC in their Defs). +# Stage.check_scc refuses a program only when that SCC can reach a reader. +SCC_UNMODELLED = frozenset(('s_add_u32', 's_add_i32', 's_sub_u32', 's_sub_i32', 's_min_u32', 's_max_u32', 's_min_i32', + 's_max_i32', 's_abs_i32', 's_addk_i32', 's_lshl1_add_u32', 's_lshl2_add_u32', + 's_lshl3_add_u32', 's_lshl4_add_u32', 's_lshl_b64', 's_lshr_b64', 's_ashr_i64')) +SCC_READERS = ('s_cbranch_scc0', 's_cbranch_scc1', 's_cselect_b32', 's_cselect_b64', 's_cmov_b32', 's_cmov_b64', + 's_cmovk_i32', 's_addc_u32', 's_subb_u32') + + +def reads_scc(name, asm): + return re.sub(r'_e(32|64)$', '', name) in SCC_READERS or 'src_scc' in parse(asm)[1] + for _name, _op in (('eq', '=='), ('lg', '!='), ('gt', '>'), ('ge', '>='), ('lt', '<'), ('le', '<=')): for _typ, _cast in (('i32', 'int({0}) %s int({1})'), ('u32', '{0} %s {1}')): def _make(op=_op, cast=_cast, name='s_cmp_%s_%s' % (_name, _typ)): @@ -6321,27 +6568,45 @@ def handler(self, ops, mods): self.set_scc((cast % op).format(self.u(ops[0]), self.u(ops[1]))) return handler setattr(Stage, 'op_s_cmp_%s_%s' % (_name, _typ), _make()) - for _typ, _cast in (('i32', 'int({0}) %s int({1})'), ('u32', '{0} %s {1}')): - def _make_cmpk(op=_op, cast=_cast, signed=_typ == 'i32', name='s_cmpk_%s_%s' % (_name, _typ)): + + def _make_k(op=_op, cast=_cast, signed=_typ == 'i32', name='s_cmpk_%s_%s' % (_name, _typ)): + # s_cmpk_*_i32 compares with signext(SIMM16), s_cmpk_*_u32 with SIMM16 zero-extended (LLVM s16imm / + # u16imm); the disassembler prints the field unsigned either way. def handler(self, ops, mods): + # A wrong operand count is refused by count, like s_cmp_* (upstream handler arity check). if len(ops) != 2: raise Unsupported('%s with %d operands, expected 2' % (name, len(ops))) if mods: - raise Unsupported('%s with modifiers' % name) - self.set_scc((cast % op).format(self.u(ops[0]), '0x%08xu' % sopk_imm(ops[1], signed))) + raise Unsupported('s_cmpk with %s %s' % (ops, mods)) + imm = sopk_simm(ops[1]) if signed else ops[1] + self.emit('scc = %s;' % (cast % op).format(self.u(ops[0]), self.u(imm))) return handler - setattr(Stage, 'op_s_cmpk_%s_%s' % (_name, _typ), _make_cmpk()) -# s_bitcmp1_b32 / s_bitcmp0_b32: SCC = S0[S1[4:0]] == 1 / == 0. -for _bit in (0, 1): - def _make_bitcmp(bit=_bit): - def handler(self, ops, mods): - if len(ops) != 2 or mods: - raise Unsupported('scalar bit test requires two unmodified operands') - if any(self.is_lane_mask(tok) for tok in ops): - raise Unsupported('scalar bit test on a lane mask') - self.set_scc('((%s >> (%s & 31)) & 1u) == %du' % (self.u(ops[0]), self.u(ops[1]), bit)) - return handler - setattr(Stage, 'op_s_bitcmp%d_b32' % _bit, _make_bitcmp()) + setattr(Stage, 'op_s_cmpk_%s_%s' % (_name, _typ), _make_k()) + + +def _cmp_u64(equal): + # s_cmp_eq_u64 / s_cmp_lg_u64: SCC = (S0 == S1) / (S0 != S1) on 64-bit values (RDNA 2 ISA, SOPC). Lowered on + # data pairs only (a 64-bit pointer or constant read from memory, an inline constant): a lane mask compared + # with anything is a question about the whole wave, which this one-lane model holds as this lane's bit only, + # so exec, vcc and any pair holding a lane mask (or a copy of exec) are refused. + def handler(self, ops, mods): + if len(ops) != 2 or mods: + raise Unsupported('s_cmp_%s_u64 form %s %s' % ('eq' if equal else 'lg', ops, mods)) + for tok in ops: + r = reg_range(tok) + if r and r[0] == 's' and any(n in getattr(self, 'masks', ()) or (self.sym.get(n) or ('',))[0] == 'execcopy' + for n in (r[1], r[2])): + raise Unsupported('s_cmp_%s_u64 on a lane mask' % ('eq' if equal else 'lg')) + (a0, a1), (b0, b1) = self.pair(ops[0]), self.pair(ops[1]) + if equal: + self.emit('scc = %s == %s && %s == %s;' % (a0, b0, a1, b1)) + else: + self.emit('scc = %s != %s || %s != %s;' % (a0, b0, a1, b1)) + return handler + + +Stage.op_s_cmp_eq_u64 = _cmp_u64(True) +Stage.op_s_cmp_lg_u64 = _cmp_u64(False) def scalar_wide_fold(helper, x, amount, signed): @@ -6404,6 +6669,33 @@ def read(fmt, data, offset): SAMPLER_HEAP_FALLBACK = SAMPLER_HEAP_SIZE - 1 +# Draw lowerings that need the draw runtime to parse a manifest line, named in X2W_DRAW_FEATURES (comma list): +# heap (`heap 1`), bufword3 (`udsrc bufword3 ` for buffer_load_format_*), uav (`uav buf table ...` +# with `udsrc uavbase ` for buffer stores), heapwords (`heapwords 1`: a resource-heap view's synthesized +# descriptor words from vdesc, for buffer_load_format_* through a heap descriptor; needs heap and bufword3). +# Off by default until a build with the runtime side is announced. +KNOWN_DRAW_FEATURES = frozenset(('heap', 'bufword3', 'uav', 'heapwords', 'uavfmt')) + + +def draw_features(): + named = frozenset(f for f in os.environ.get('X2W_DRAW_FEATURES', '').replace(' ', '').split(',') if f) + unknown = named - KNOWN_DRAW_FEATURES + if unknown: + raise SystemExit('X2W_DRAW_FEATURES: unknown %s' % ', '.join(sorted(unknown))) + return named + + +# Resource-heap views of a draw (manifest `heap 1`, layout agreed with draw-rt): the title heap memory heapmem +# (t0 space1, a view token per 32-byte slot: HEAP_TOKEN then the view id), vinfo (t1 space1, 16 bytes per view id, +# dword 0 the buffer stride), and one array per kind over the view-id region, index 8 + 8 * id + kind for ids below +# HEAP_IDS and kind alone (an empty view) otherwise. Bounded arrays, so FXC needs no unbounded-table flag. +HEAP_TOKEN = 0x56573258 +HEAP_IDS = 90000 +HEAP_KINDS = {'tex2d': ('heaptex2d', 0, 'Texture2D'), 'tex2da': ('heaptex2da', 1, 'Texture2DArray'), + 'tex3d': ('heaptex3d', 2, 'Texture3D'), 'tex1d': ('heaptex1d', 3, 'Texture1D'), + 'buf': ('heapbuf', 4, 'ByteAddressBuffer')} + + # DXGI_FORMAT values for integer RTVs and the binary32 float targets. UINT_RTVS = frozenset((3, 7, 12, 17, 25, 30, 36, 42, 50, 57, 62)) SINT_RTVS = frozenset((4, 8, 14, 18, 32, 38, 43, 52, 59, 64)) @@ -6420,6 +6712,51 @@ def read(fmt, data, offset): VERIFIED_SINT_RTVS = frozenset((4, 14, 18, 32, 38, 43, 52, 59, 64)) +# SPI pixel-stage inputs in SPI_PS_INPUT_ENA/ADDR bit order and the VGPRs each takes (Mesa +# src/amd/common/ac_shader_util.c ac_get_fs_input_vgpr_cnt): the IJ pairs, the pull model's three, then +# one VGPR each for line stipple, POS_X/Y/Z/W_FLOAT, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT. +PS_INPUTS = (('persp_sample', 2), ('persp_center', 2), ('persp_centroid', 2), ('persp_pull_model', 3), + ('linear_sample', 2), ('linear_center', 2), ('linear_centroid', 2), ('line_stipple', 1), + ('pos_x_float', 1), ('pos_y_float', 1), ('pos_z_float', 1), ('pos_w_float', 1), + ('front_face', 1), ('ancillary', 1), ('sample_coverage', 1), ('pos_fixed_pt', 1)) +POS_FIXED_PT = 15 +# SPI inputs lowered besides POS_FIXED_PT (bit -> HLSL uint expression over PSIn i). Mesa +# ac_nir_lower_intrinsics_to_args.c reads frag_coord x/y/z from POS_X/Y/Z_FLOAT and frag_coord_w_rcp from +# POS_W_FLOAT; nir_builder.c nir_build_frag_coord makes gl_FragCoord.w = frcp(frag_coord_w_rcp), and D3D +# SV_Position.w is 1 / gl_FragCoord.w (vkd3d-shader spirv.c frag_coord_fixup), so POS_W_FLOAT is SV_Position.w. +PS_INPUT_HLSL = {8: 'U(i.pos.x)', 9: 'U(i.pos.y)', 10: 'U(i.pos.z)', 11: 'U(i.pos.w)', + # FRONT_FACE is the float +1.0 (front) or -1.0 (back): Mesa nir_intrinsics.py front_face_fsign + # "front_face ? 1.0 : -1.0", which ac_nir_lower_intrinsics_to_args.c loads as the front_face argument + # itself (and load_front_face as fgt(arg, 0)). SV_IsFrontFace follows the PSO's FrontCounterClockwise, + # which the runtime sets from the cull register (pipeline_state_decode.h); the manifest says + # `frontface 1` so these keys can be found if that convention changes (X2W_DRAW_STATE_CULL_FLIP). + 12: 'U(i.ff ? 1.0 : -1.0)'} +FRONT_FACE = 12 +# The SPI position inputs, which a per-sample stage would read at the sample (see PS_SAMPLE_RATE). +PS_POSITION_INPUTS = (8, 9, 10, 11) +# The *_sample barycentrics: the stage runs per sample and the position inputs are at the sample, which a plain +# SV_Position input is not. +PS_SAMPLE_RATE = (1 << 0) | (1 << 4) + + +def ps_input_layout(ena, addr): + """VGPR -> SPI input bit for the given SPI_PS_INPUT_ENA/ADDR, or Unsupported. + + The VGPRs follow ADDR, the inputs the code was compiled for; ENA names the ones the hardware initializes + and must lie inside ADDR (Mesa ac_print_spi_ps_input_vgpr_list walks the ADDR bits to number v0, v1, ... and + marks an input "initialized" only when its ENA bit is also set). Both are 16-bit masks. + """ + if not 0 <= ena <= 0xffff or not 0 <= addr <= 0xffff or ena & ~addr: + raise Unsupported('unverified pixel input enable/address combination %#x/%#x' % (ena, addr)) + layout, vgpr = {}, 0 + for bit, (_, width) in enumerate(PS_INPUTS): + if addr >> bit & 1: + for _ in range(width): + layout[vgpr] = bit + vgpr += 1 + return layout + + class Pipeline: vertex_kind = 'vs' uses_pack16_rne = False @@ -6427,27 +6764,29 @@ class Pipeline: uses_store_d16_x = False uses_sad = () srv_formats = () - uavs = None # key -> dict(index, kind): images a pixel stage stores to (u registers); None until the first store - - def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), ps_hw_inputs=None, vs_fetch=None, - refusals=None, decoded=None, ps_attr_map=None, srv_formats=()): + f16_plain = () + + def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), ps_hw_inputs=None, + features=None, vs_out_cntl=None, rw_keys=(), vs_fetch=None, refusals=None, decoded=None, + ps_attr_map=None, srv_formats=(), pk_u8_s0_contract=False): + # pk_u8_s0_contract: the caller guarantees that every v_cvt_pk_u8_f32 S0 register not proven in domain + # holds +0.0 or an integer in 1..255 (fixtures only; ordinary translation never selects it). + self.pk_u8_s0_contract = pk_u8_s0_contract self.root = parse_root(root_blob) + self.rw_keys = frozenset(rw_keys) # buffers the program stores to and reads: every access through the UAV + # PA_CL_VS_OUT_CNTL of the vertex stage (request .vsout), or None: says what a pos1 export carries. + self.vs_out_cntl = vs_out_cntl + self.features = draw_features() if features is None else frozenset(features) + self.heapvars = [] # heap descriptor k -> resource kind it is used as (None until used) + self.fma_rule = None # set by the first multiply-add lowered (manifest `fma exact|precise`) + self.draw_heapwords = False # x2w_hword read (X2W_DRAW_FEATURES heapwords, manifest `heapwords 1`) + self.spi_inputs(ps_hw_inputs) self.ps_attr_map = ps_attr_map # stream_interface(): pixel attribute -> (vertex parameter, component mask); None pairs by number self.vs_fetch = vs_fetch # stream_fetch(): the loads the vertex stage's entry call stands for - self.packed_position_vgpr = None + # (packed_position_vgpr is set by spi_inputs above.) # First VGPR of the PERSP_CENTER I/J entry pair (SPI_PS_INPUT_ADDR bit 1, after the PERSP_SAMPLE pair when that # one is enabled). Without hardware inputs the model assumes the center pair alone: v0, v1. self.persp_center_vgpr = 0 - if ps_hw_inputs is not None: - ena, addr = ps_hw_inputs - if ena != addr or not 0 <= ena <= 0xffff: - raise Unsupported('unverified pixel input enable/address combination') - self.persp_center_vgpr = (2 if addr & 1 else 0) if addr & 2 else None - if ena & (1 << 15): - # SPI PS inputs 0..6 supply IJ pairs (the pull model supplies three); - # line stipple through sample coverage each occupy one VGPR. - widths = (2, 2, 2, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1) - self.packed_position_vgpr = sum(w for bit, w in enumerate(widths) if addr & (1 << bit)) self.rtv_formats = rtv_formats self.srv_formats = dict(srv_formats) if isinstance(srv_formats, dict) else dict(enumerate(srv_formats)) self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap @@ -6461,7 +6800,8 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.uds = [] # entry-constant sources self.notes = set() # shortcuts taken (written to the manifest as comments) self.lod_unvalidated = set() # image_sample forms read through a heap sampler (LOD fields unchecked, #2221) - self.modified, self.other_modified = set(), set() # other: unproved descriptor writes + self.modified = set() + self.helper_text = None # both stage bodies, read once by common() to pick the HELPERS to emit self.rect = self.ud(('rect',)) if refusals is None: self.vs = Stage(self, self.vertex_kind, vs_code) @@ -6471,12 +6811,16 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.vs = Stage(self, self.vertex_kind, vs_code, refusals=refusals, decoded=decoded.get('vs')) self.ps = Stage(self, 'ps', ps_code, refusals=refusals, decoded=decoded.get('ps')) if ps_code is not None else None if self.ps is None: - self.params, self.flat, self.f16_plain = [], [], [] + self.params, self.flat, self.half, self.f16_plain = [], [], [], [] + self.ps_entry_reads = {} if 'pos' not in self.vs.exports: raise Unsupported('vertex stage exports no position') return + self.spi_reads() self.params = sorted(int(k[5:]) for k in self.vs.exports if k.startswith('param')) self.flat = sorted(a for a, how in self.ps.attrs.items() if 'flat' in how) + self.half = sorted(a for a, how in self.ps.attrs.items() if 'half' in how) + self.check_half_reads() for a, how in self.ps.attrs.items(): if 'f16' not in how: continue @@ -6496,16 +6840,86 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( if 'pos' not in self.vs.exports: raise Unsupported('vertex stage exports no position') + def spi_inputs(self, ps_hw_inputs): + """Before the pixel stage is built: the SPI input layout from its SPI_PS_INPUT_ENA/ADDR, or none. + + Shared by the draw and mesh pipelines. With (ENA, ADDR), entry VGPRs map to SPI inputs. Only POS_FIXED_PT + is lowered: the integer pixel X in [15:0] and Y in [31:16] (Mesa nir_intrinsics.py pixel_coord, "16-bit + integer vec2 of the pixel X/Y in the framebuffer", which ac_nir_lower_intrinsics_to_args.c builds as + unpack_32_2x16 of the pos_fixed_pt argument). D3D SV_Position.xy is the pixel centre, so its integer part + is that pixel.""" + self.packed_position_vgpr = None + self.ps_input_layout = None + # The pixel stage's launch FLOAT_MODE (SPI_SHADER_PGM_RSRC1_PS bits 19:12), the third .psin field, or None + # when the request does not carry it (then f16 rounding before s_round_mode is refused; Stage.launch_mode). + # (None, None, mode) passes the mode without an SPI input layout. + self.ps_float_mode = ps_hw_inputs[2] if ps_hw_inputs is not None and len(ps_hw_inputs) > 2 else None + if ps_hw_inputs is not None and ps_hw_inputs[0] is None: + ps_hw_inputs = None + if ps_hw_inputs is not None: + ena, addr = ps_hw_inputs[:2] + self.ps_input_layout = layout = ps_input_layout(ena, addr) + self.ps_input_ena = ena + if ena >> POS_FIXED_PT & 1: + self.packed_position_vgpr = [v for v, bit in layout.items() if bit == POS_FIXED_PT][0] + + def spi_reads(self): + """After the pixel stage is built: check its entry-VGPR reads against the SPI input layout. + + A pixel stage starts with its SPI inputs in the VGPRs (barycentrics, position, face, ancillary data). The + interpolation instructions name them without reading them (they take the attribute); any other read before + a write sees 0 in the HLSL instead of the hardware input. Without the layout this is reported, not refused + (existing fixtures read entry VGPRs as zero): ps_entry_reads, VGPR -> offset of the first read; the + translate_to callers refuse a pipeline that has any. With the layout, a read of an input that is not + lowered is kept in ps_input_refusal and raised by hlsl_ps(), so a pipeline can still be built to ask for its + layout (packed_position_vgpr), but no pixel HLSL is ever written for it.""" + self.ps_entry_reads = dict(self.ps.entry_reads) + self.ps_input_refusal = None + self.ps_input_vgprs = {} # entry VGPR -> PS_INPUT_HLSL bit, initialized by Stage.declarations() + if self.ps_input_layout is None: + return + for reg, off in sorted(self.ps_entry_reads.items(), key=lambda item: item[1]): + bit = self.ps_input_layout.get(reg) + if bit is None: + self.ps_input_refusal = ('pixel stage reads entry VGPR v%d at %#x, past the SPI inputs (ADDR allocates %d)' + % (reg, off, len(self.ps_input_layout))) + elif not self.ps_input_ena >> bit & 1: + self.ps_input_refusal = ('pixel stage reads SPI input %s (v%d) at %#x, allocated but not enabled' + % (PS_INPUTS[bit][0], reg, off)) + elif bit in PS_POSITION_INPUTS and self.ps_input_ena & PS_SAMPLE_RATE: + self.ps_input_refusal = ('pixel stage reads SPI input %s (v%d) at %#x with per-sample barycentrics ' + 'enabled (%#x)' % (PS_INPUTS[bit][0], reg, off, self.ps_input_ena)) + elif bit in PS_INPUT_HLSL: + self.ps_input_vgprs[reg] = bit + elif bit != POS_FIXED_PT: + self.ps_input_refusal = ('pixel stage reads SPI input %s (v%d) at %#x: not lowered' + % (PS_INPUTS[bit][0], reg, off)) + if self.ps_input_refusal: + break + self.ps_entry_reads = {} # every entry read is a lowered input (or refused above) + + def check_half_reads(self): + """Refuse a binary16 read (v_interp_p2_f16) of an attribute the vertex/mesh stage exports with compr: its + loparam/hiparam copies are not written (Stage.export).""" + compr = sorted(set(self.half) & set(getattr(self.vs, 'compr_params', ()))) + if compr: + raise Unsupported('binary16 interpolation of attribute %s exported with compr' % compr) + def mrt_kind(self, slot): if slot >= len(self.rtv_formats): return 'float' fmt = self.rtv_formats[slot] + # R32_UINT / R32_SINT (42 / 43) are verified by a draw (tests/startup_mrt_check.py). The other formats with + # 32 bits per channel (R32G32B32A32 3 / 4, R32G32B32 7 / 8, R32G32 17 / 18) take the same uncompressed + # export words unconverted, only with more channels (D3D drops the components a format lacks, as the + # colour buffer does): ASSUMED equal, not drawn. Narrower integer targets convert in the colour buffer + # (clamp or wrap, not checked) and stay refused. if fmt in UINT_RTVS: - if fmt not in VERIFIED_UINT_RTVS: + if fmt not in (3, 7, 17, 42): raise Unsupported('unverified UINT RTV format %d' % fmt) return 'uint' if fmt in SINT_RTVS: - if fmt not in VERIFIED_SINT_RTVS: + if fmt not in (4, 8, 18, 43): raise Unsupported('unverified SINT RTV format %d' % fmt) return 'int' return 'bits' if fmt in FLOAT32_RTVS else 'float' @@ -6516,22 +6930,50 @@ def ud(self, source): return self.uds.index(source) def resource(self, key, kind): - if key in self.stored_images(): + if key[0][0] == 'heapdyn': + k = key[0][1] + if key[1] not in (0, None): + raise Unsupported('heap descriptor at word offset %s' % key[1]) + if self.heapvars[k] not in (None, kind): + raise Unsupported('heap descriptor used as %s and %s' % (self.heapvars[k], kind)) + if kind not in HEAP_KINDS: + raise Unsupported('heap %s' % kind) + self.heapvars[k] = kind + return '%s[NonUniformResourceIndex(x2w_hix(h%d, %du))]' % (HEAP_KINDS[kind][0], k, HEAP_KINDS[kind][1]) + if key in getattr(self, 'uavs', {}) or key in getattr(self, 'rw_keys', ()): + raise Unsupported('descriptor %s read as an SRV and stored to as a UAV' % (key,)) + if key in Pipeline.stored_images(self): raise Unsupported('resource %s is both read and stored to' % (key,)) r = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) if r['kind'] != kind: raise Unsupported('resource %s used as %s and %s' % (key, r['kind'], kind)) return 'r%d' % r['index'] + def uav(self, key): + """u for a raw buffer UAV (manifest `uav buf ...`); indices count from 0 apart from the SRVs.""" + if key in self.resources: + # translate_to builds the pipeline again with the key in rw_keys, so its vector loads go through the UAV + raise StoredSrv(key, 'descriptor %s read as an SRV and stored to as a UAV' % (key,)) + if getattr(self, 'image_uavs', None): + raise Unsupported('buffer UAV %s in a program with stored images (u registers are shared)' % (key,)) + uavs = self.__dict__.setdefault('uavs', {}) + if key not in uavs: + if len(uavs) == 8: + raise Unsupported('more than 8 UAVs') + uavs[key] = len(uavs) + return 'u%d' % uavs[key] + def stored_images(self): - return self.uavs or {} + return getattr(self, 'image_uavs', None) or {} - def uav(self, key, kind): + def image_uav(self, key, kind): if key in self.resources: raise Unsupported('resource %s is both read and stored to' % (key,)) - if self.uavs is None: - self.uavs = {} - r = self.uavs.setdefault(key, dict(index=len(self.uavs), kind=kind)) + if getattr(self, 'uavs', None): + raise Unsupported('stored image %s in a program with buffer UAVs (u registers are shared)' % (key,)) + if getattr(self, 'image_uavs', None) is None: + self.image_uavs = {} + r = self.image_uavs.setdefault(key, dict(index=len(self.image_uavs), kind=kind)) if r['kind'] != kind: raise Unsupported('stored image %s used as %s and %s' % (key, r['kind'], kind)) return ('u%d' if kind == 'raw' else 'w%d') % r['index'] @@ -6556,37 +6998,7 @@ def sampler_lines(self): def common(self): out = ['#define F(x) asfloat(x)', '#define U(x) asuint(x)', 'float mul_legacy(float a, float b) { return (a == 0.0 || b == 0.0) ? 0.0 : a * b; }', - # Match pixel_aot: round the product before adding and flush denormals to signed zero. - 'float ftz32(float value) {', - ' uint bits = asuint(value);', - # Select the mask as an integer so FXC preserves the sign of a flushed zero. - ' uint mask = (bits & 0x7fffffffu) < 0x00800000u ? 0x80000000u : 0xffffffffu;', - ' return asfloat(bits & mask);', - '}', - 'float mad32(float a, float b, float c, bool legacy) {', - ' a = ftz32(a);', - ' b = ftz32(b);', - ' precise float product = ftz32(legacy ? mul_legacy(a, b) : a * b);', - ' precise float sum = product + ftz32(c);', - ' return ftz32(sum);', - '}', - # Match pixel_aot: x - floor(x) capped at 0x3f7fffff, so a tiny negative input cannot round up to - # 1.0. The cap is a comparison, not min: min returns its other operand for a NaN. - # The comparison is on the bits because FXC folds `frac(value) >= 1.0f` to false and emits a bare - # frc for it, which loses the cap on an adapter whose frac returns 1.0. frac can only reach the cap - # by rounding to exactly +1.0, so the equality covers the same case, and a NaN misses it and passes. - 'float fract32(float value) {', - ' float f = frac(value);', - ' return asuint(f) == 0x3f800000u ? asfloat(0x3f7fffffu) : f;', - '}', - # v_med3_f32 with a NaN source is the minimum of the three (ISA "343 V_MED3_F32"), so the test is - # on the encoding: a float isnan() may be folded away by the compiler. D3D min() returns the - # other operand, so min(min(a, b), c) over a NaN source is the smallest of the non-NaN ones. - # Same body as med3_32 in tools/pixel_aot.py. - 'float med3_32(float a, float b, float c) {', - ' uint top = max(max(asuint(a) & 0x7fffffffu, asuint(b) & 0x7fffffffu), asuint(c) & 0x7fffffffu);', - ' return top > 0x7f800000u ? min(min(a, b), c) : max(min(a, b), min(max(a, b), c));', - '}', + 'float med3(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); }', # High half of an unsigned 32x32 product, by halfword products so it fits 32-bit HLSL. 'uint mul_hi_u32(uint a, uint b) { uint la = a & 0xffffu, lb = b & 0xffffu;' ' uint middle = (a >> 16) * lb + ((la * lb) >> 16);' @@ -6628,19 +7040,39 @@ def common(self): ' uint e = (x >> (s1 & 31u)) & (w >= 32u ? 0xffffffffu : ((1u << (w & 31u)) - 1u));' ' uint sh = (32u - w) & 31u; return sg != 0u ? asuint(asint(e << sh) >> sh) : e; }', 'uint ldu(ByteAddressBuffer b, uint a) { uint k = (a & 3) * 8, lo = b.Load(a & ~3u); if (k == 0) return lo; ' - 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }', - 'cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))] + 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }'] + if getattr(self, 'helper_text', None) is None: # upstream unit probes build a Pipeline without __init__ + # The draw stages, or the compute stage of upstream's ComputePipeline (slot 67). + stages = [getattr(self, k) for k in ('vs', 'ps', 'cs') if getattr(self, k, None) is not None] + self.helper_text = '\n'.join(line for s in stages for line in s.body()) + out += [text for name, text in HELPERS.items() if re.search(r'\b%s\(' % name, self.helper_text)] + out += ['cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))] for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D'}[r['kind']], r['index'], r['index'])) - for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): - out.append('%s %s%d : register(u%d);' % ({'tex2d': 'RWTexture2D', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) + for key, i in getattr(self, 'uavs', {}).items(): + out.append('RWByteAddressBuffer u%d : register(u%d);' % (i, i)) + for key, r in sorted(Pipeline.stored_images(self).items(), key=lambda kv: kv[1]['index']): + out.append('%s w%d : register(u%d);' % ({'tex2d': 'RWTexture2D'}[r['kind']], r['index'], r['index'])) for key, i in self.samplers.items(): out.append('%s q%d : register(s%d);' % ('SamplerComparisonState' if key[0] == 'cmp' else 'SamplerState', i, i)) + if any(getattr(self, 'heapvars', ())): # tests build bare pipelines without __init__ + out += ['ByteAddressBuffer heapmem : register(t0, space1);', 'ByteAddressBuffer vinfo : register(t1, space1);', + 'uint x2w_vid(uint h) { return heapmem.Load(h) == 0x%08xu ? heapmem.Load(h + 4) : 0xffffffffu; }' + % HEAP_TOKEN, + 'uint x2w_hix(uint h, uint k) { uint i = x2w_vid(h); return i < %du ? 8u + 8u * i + k : k; }' % HEAP_IDS, + 'uint x2w_vstride(uint h) { uint i = x2w_vid(h); return i < %du ? vinfo.Load(i * 16u) : 0u; }' % HEAP_IDS] + for kind in sorted(set(k for k in self.heapvars if k), key=lambda k: HEAP_KINDS[k][1]): + name, slot, hlsl_type = HEAP_KINDS[kind] + out.append('%s %s[%d] : register(t0, space%d);' % (hlsl_type, name, 8 + 8 * HEAP_IDS, 2 + slot)) + if getattr(self, 'draw_heapwords', False): + out += ['ByteAddressBuffer x2w_vdesc : register(t2, space1);', + 'uint x2w_hword(uint h, uint i) { uint id = x2w_vid(h); return id < %du ? ' + 'x2w_vdesc.Load(id * 32u + 4u * i) : 0u; }' % HEAP_IDS] if self.uses_sampler_heap: out.append('SamplerState qh[%d] : register(s0, space%d);' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE)) out.append('uint x2w_sampler_entry(uint offset) { return (offset & 15u) != 0 || offset >= %du ? %du : offset >> 4; }' % (16 * SAMPLER_HEAP_FALLBACK, SAMPLER_HEAP_FALLBACK)) - if self.uses_pack16_rne: + if getattr(self, 'uses_pack16_rne', False): # IEEE binary32 to binary16 round-to-nearest-even (quieting NaN while preserving its sign, # matching RDNA 2 hardware on binary32 inputs), plus exact UNORM16 ratio-to-half conversion # (avoiding binary32 double-rounding at 0xffaf -> 0x3bfd and 0xffef -> 0x3bff). @@ -6801,20 +7233,31 @@ def interface(self, for_pixel): # Attributes read without interpolation get a second, flat copy of the vertex output. for p in self.flat: fields.append(' nointerpolation uint4 fparam%d : FPARAM%d;' % (p, p)) + # Attributes read as binary16 halves (v_interp_p2_f16) get the two halves as interpolated f32 copies. + for p in getattr(self, 'half', ()): + fields.append(' float4 loparam%d : LOPARAM%d;' % (p, p)) + fields.append(' float4 hiparam%d : HIPARAM%d;' % (p, p)) for p in self.f16_plain: fields.append(' float4 hparam%d_lo : HPARAML%d;' % (p, p)) fields.append(' float4 hparam%d_hi : HPARAMH%d;' % (p, p)) fields.append(' float4 pos : SV_Position;') + if for_pixel and FRONT_FACE in getattr(self, 'ps_input_vgprs', {}).values(): + fields.append(' bool ff : SV_IsFrontFace;') # system-generated: pixel input only + clip = self.vs.exports.get('clip') + if clip: + fields.append(' float%s clip0 : SV_ClipDistance0;' % ('' if clip == 1 else clip)) return fields def hlsl_vs(self): s = self.vs out = self.common() + ['struct VSOut {'] + self.interface(False) + ['};', 'VSOut body(uint vid) {', ' VSOut o = (VSOut)0;'] s.used_v.add(0) - flat = re.compile(r'\s*o\.fparam(\d+) = ') - half = re.compile(r'\s*o\.hparam(\d+)_(?:lo|hi) = ') - body = [line for line in s.body() if not (flat.match(line) and int(flat.match(line).group(1)) not in self.flat) - and not (half.match(line) and int(half.match(line).group(1)) not in self.f16_plain)] + flat = re.compile(r'\s*o\.(f|lo|hi)param(\d+) = ') + + def unread(line): + m = flat.match(line) + return m and int(m.group(2)) not in (self.flat if m.group(1) == 'f' else getattr(self, 'half', ())) + body = [line for line in s.body() if not unread(line)] if s.fetched: # Behind a fetch call a register read as 0 by default would hide a missing input, so every read must be # of a register defined on all paths. Proven here only for the entry block (straight-line code from the @@ -6843,6 +7286,10 @@ def hlsl_vs(self): for p in range(max(self.params) + 1 if self.params else 0): out.append(' o.param%d = p.param%d + r.param%d - q.param%d;' % (p, p, p, p)) out += [' o.fparam%d = p.fparam%d;' % (p, p) for p in self.flat] + for p in getattr(self, 'half', ()): + out += [' o.%sparam%d = p.%sparam%d + r.%sparam%d - q.%sparam%d;' % ((h, p) * 4) for h in ('lo', 'hi')] + if self.vs.exports.get('clip'): + out.append(' o.clip0 = p.clip0 + r.clip0 - q.clip0;') # linear in the corner, like the params for p in self.f16_plain: out += [' o.hparam%d_%s = p.hparam%d_%s + r.hparam%d_%s - q.hparam%d_%s;' % (p, h, p, h, p, h, p, h) for h in ('lo', 'hi')] @@ -6854,26 +7301,29 @@ def ps_profile(self): return 'ps_6_0' if self.ps.needs_sm6 else 'ps_5_1' def hlsl_ps(self): + refusal = getattr(self, 'ps_input_refusal', None) # the tests' bare pipelines have none + if refusal: + raise Unsupported(refusal) s = self.ps targets = sorted(int(k[3:]) for k in s.exports if k.startswith('mrt')) - depth = 'depth' in s.exports out = self.common() + ['struct PSIn {'] + self.interface(True) + ['};'] - if not targets and not depth: + depth = 'depth' in s.exports + if not targets and not depth: # depth-only: no output struct, so the pipeline declares no SV_Target out += ['void main(PSIn i) {'] + s.declarations() + s.body() + ['}'] return '\n'.join(out) + '\n' out.append('struct PSOut {') - if depth: - out.append(' float depth : SV_Depth;') for t in targets: kind = self.mrt_kind(t) out.append(' %s mrt%d : SV_Target%d;' % ({'int': 'int4', 'uint': 'uint4'}.get(kind, 'float4'), t, t)) + if depth: + out.append(' float depth : SV_Depth;') out += ['};', 'PSOut main(PSIn i) {', ' PSOut o = (PSOut)0;'] out += s.declarations() + s.body() + [' return o;', '}'] return '\n'.join(out) + '\n' def manifest(self): # A manifest that names a writable view is version 2, so a runtime that reads only version 1 lines can tell. - lines = ['x2w-manifest %d' % (2 if self.stored_images() else 1), 'ud %d' % len(self.uds)] + lines = ['x2w-manifest %d' % (2 if Pipeline.stored_images(self) else 1), 'ud %d' % len(self.uds)] for i, source in enumerate(self.uds): lines.append('udsrc %d %s' % (i, ' '.join(str(x) for x in source))) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): @@ -6885,7 +7335,18 @@ def manifest(self): lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) if r.get('d16_exact'): lines.append('d16srv %d exact' % r['index']) - for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): + for (source, off), i in sorted(getattr(self, 'uavs', {}).items(), key=lambda kv: kv[1]): + if source[0] == 'table': + lines.append('uav %d buf table %d %d' % (i, source[1] if len(source) > 1 else 0, off or 0)) + elif source[0] == 'root' and not off: + lines.append('uav %d buf root %d 0' % (i, source[1] if len(source) > 1 else 0)) + else: + raise Unsupported('uav through %s at %s' % (source, off)) + if any(getattr(self, 'heapvars', ())): + lines.append('heap 1') + if getattr(self, 'draw_heapwords', False): + lines.append('heapwords 1') + for key, r in sorted(Pipeline.stored_images(self).items(), key=lambda kv: kv[1]['index']): source, off = key if source[0] != 'table': raise Unsupported('stored image through %s' % (source,)) @@ -6893,6 +7354,13 @@ def manifest(self): lines += self.sampler_lines() if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) + if getattr(self, 'fma_rule', None) and self.fma_rule != 'legacy': + lines.append('fma %s' % self.fma_rule) + if getattr(self.ps, 'quad_divergent_used', None): + # X2W_PS_QUAD_DIVERGENT lowered a quad read or image_sample_b a lane may skip (Stage.translate) + lines.append('quaddivergent 1') + if FRONT_FACE in getattr(self, 'ps_input_vgprs', {}).values(): + lines.append('frontface 1') # reads SV_IsFrontFace: depends on the PSO winding (see PS_INPUT_HLSL) lines.append('params %d' % (max(self.params) + 1 if self.params else 0)) if self.ps is None: lines.append('ps none') @@ -6900,7 +7368,7 @@ def manifest(self): lines.append('targets %s' % ' '.join(k[3:] for k in sorted(self.ps.exports) if k.startswith('mrt'))) # 'wmask ': the export leaves the channels outside the mask unwritten, so the # runtime keeps them out of that target's RenderTargetWriteMask. Full masks are not written. - for name, mask in sorted(self.ps.write_masks.items(), key=lambda kv: int(kv[0][3:])): + for name, mask in sorted(getattr(self.ps, 'write_masks', {}).items(), key=lambda kv: int(kv[0][3:])): if mask != 0xF: lines.append('wmask %d 0x%x' % (int(name[3:]), mask)) return '\n'.join(lines) + '\n' @@ -6940,17 +7408,10 @@ def resource(self, key, kind): def uav(self, key, kind='raw'): if key in self.resources: raise Unsupported('descriptor %s used for a load and a store' % (key,)) - return super().uav(key, kind) - - def stored_images(self): - return {key: r for key, r in self.uavs.items() if r['kind'] != 'raw'} + return super().uav(key) if kind == 'raw' else self.image_uav(key, kind) def common(self): - out = [line for line in super().common() if self.uds or not line.startswith('cbuffer entry')] - for r in self.uavs.values(): - if r['kind'] == 'raw': - out.append('RWByteAddressBuffer u{0} : register(u{0});'.format(r['index'])) - return out + return [line for line in super().common() if self.uds or not line.startswith('cbuffer entry')] def hlsl_cs(self): s = self.cs @@ -6974,12 +7435,10 @@ def manifest(self): else: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) - for (source, off), r in self.uavs.items(): - where = 'table %d %d' % (source[1], off) - if r['kind'] == 'raw': - lines.append('uav %d %s' % (r['index'], where)) - else: - lines.append('uav %d tex2d float %s channels 4' % (r['index'], where)) + for (source, off), index in self.uavs.items(): + lines.append('uav %d table %d %d' % (index, source[1], off)) + for (source, off), r in self.stored_images().items(): + lines.append('uav %d tex2d float table %d %d channels 4' % (r['index'], source[1], off)) lines += self.sampler_lines() if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) @@ -6989,10 +7448,15 @@ def manifest(self): class MeshPipeline(Pipeline): """A slot 57 mesh pipeline with an optional pixel stage. The mesh stage is self.vs.""" vertex_kind = 'ms' + uses_mesh_skeleton = True def hlsl_ms(self): s = self.vs - lines = [re.sub(r' o\.fparam(\d+) = [^;]*;', lambda m: m[0] if int(m[1]) in self.flat else '', + outputs = {'f': self.flat, 'lo': self.half, 'hi': self.half} + def linked_output(match): + return match[0] if int(match[2]) in outputs[match[1]] else '' + + lines = [re.sub(r' o\.(f|lo|hi)param(\d+) = [^;]*;', linked_output, re.sub(r' o\.hparam(\d+)_(?:lo|hi) = [^;]*;', lambda m: m[0] if int(m[1]) in self.f16_plain else '', line)) for line in s.body()] @@ -7017,7 +7481,7 @@ def fnv(data, h=1469598103934665603): def pipeline_key(vs_code, ps_code, root_blob, layout=b''): """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-17')))) + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-3')))) return fnv(layout, key) if layout else key @@ -7026,7 +7490,7 @@ def compute_key(cs_code, data, root_blob, desc, state_a=b'', state_b=b''): graphics revision followed by "cs", then each part preceded by its length as a little-endian u64: the code, the words 7-8 blob, the root signature, the 12 description words with their pointers zeroed and the two state blocks.""" - key = fnv(b'x2w-startup-shader-17cs') + key = fnv(b'x2w-startup-shader-3cs') for part in (cs_code, data, root_blob, desc, state_a, state_b): key = fnv(part, fnv(struct.pack('.vs.hlsl, .ps.hlsl and .txt (last), or .fail with the reason. With check, the pair is compiled to .vs.cso and .ps.cso first and a missing fxc is a failure. check=False, or X2W_FXC set to the empty string, publishes the manifest without bytecode.""" name = os.path.join(out_dir, '%016x' % key) try: - pipe = Pipeline(vs_code, ps_code, root_blob, rtv_formats=rtv_formats, vs_fetch=vs_fetch, ps_attr_map=ps_attr_map) + rw_keys = set() + while True: + try: + pipe = Pipeline(vs_code, ps_code, root_blob, rtv_formats=rtv_formats, ps_hw_inputs=ps_hw_inputs, + vs_out_cntl=vs_out_cntl, rw_keys=rw_keys, + vs_fetch=vs_fetch, ps_attr_map=ps_attr_map) + break + except StoredSrv as conflict: + # read before the first store: build again with every access to that buffer through its UAV + if conflict.key in rw_keys or len(rw_keys) == 8: + raise + rw_keys.add(conflict.key) + if pipe.ps_entry_reads: + # A request does not carry the SPI input layout, so the HLSL would read that input as 0 (for example + # the packed pixel position a dither or a full-screen copy addresses with). Not written as a result. + reg, off = min(pipe.ps_entry_reads.items(), key=lambda item: item[1]) + raise Unsupported('pixel stage reads entry VGPR v%d (an SPI input; layout not in the request) at %#x' + % (reg, off)) vs, ps, manifest = pipe.hlsl_vs(), pipe.hlsl_ps(), pipe.manifest() if rtv_request: manifest += rtv_request + '\n' @@ -7246,46 +7727,67 @@ def translate_to(out_dir, key, vs_code, ps_code, root_blob, check=True, rtv_form compiler, profiles = fxc, (('vs', 'vs_5_1'), ('ps', 'ps_5_1')) if fxc: import subprocess - # An existing manifest can already point at these paths. Publish only bytecode from a successful pair. - with tempfile.TemporaryDirectory(prefix='.fxc-', dir=out_dir) as staging: + # X2W_FXC_FLAGS: extra fxc options, for example /Od for a stage the default optimiser takes minutes on + # (the bytecode then runs unoptimised; the HLSL and so the result are the same). Default: none. + extra = os.environ.get('X2W_FXC_FLAGS', '').split() + if any(not re.fullmatch(r'/(Od|O[0-3]|Gfp)', flag) for flag in extra): + # (options that change results or layouts, /Gis /Gpp /Zpr /Zpc, are not taken) + raise SystemExit('X2W_FXC_FLAGS: only /Od, /O0-/O3 and /Gfp') + if not sm6: for stage, profile in profiles: - bytecode = os.path.join(staging, stage + '.cso') - if sm6: - command = [compiler, '-Gis', '-T', profile, '-E', 'main', '-Fo', bytecode, name + '.%s.hlsl' % stage] - else: - command = [compiler, '/nologo', '/T', profile, '/E', 'main', '/Fo', bytecode, name + '.%s.hlsl' % stage] - r = subprocess.run(command, capture_output=True, text=True) - if r.returncode or not has_bytecode(bytecode): - detail = r.stderr.strip() or ('?' if r.returncode else 'no bytecode produced') - open(name + '.fail', 'w').write('fxc %s: %s\n' % (stage, detail[-2000:])) - return 'fxc %s failed: %s' % (stage, detail.splitlines()[-1]) - with suppress(FileNotFoundError, UnicodeError): - with open(manifest_path) as existing: - write_manifest = existing.read() != manifest - # If the bindings changed, withdraw the old manifest before publishing new bytecode. - if write_manifest: + r = subprocess.run([fxc, '/nologo', '/T', profile, '/E', 'main'] + extra + + ['/Fo', name + '.%s.cso' % stage, name + '.%s.hlsl' % stage], + capture_output=True, text=True) + if r.returncode: + open(name + '.fail', 'w').write('fxc %s: %s\n' % (stage, r.stderr[-2000:])) + return 'fxc %s failed: %s' % (stage, r.stderr.strip().splitlines()[-1] if r.stderr.strip() else '?') + else: # upstream: a shader model 6.0 pair (dxc), staged and published together + # An existing manifest can already point at these paths. Publish only bytecode from a successful pair. + with tempfile.TemporaryDirectory(prefix='.fxc-', dir=out_dir) as staging: + for stage, profile in profiles: + bytecode = os.path.join(staging, stage + '.cso') + if sm6: + command = [compiler, '-Gis', '-T', profile, '-E', 'main', '-Fo', bytecode, name + '.%s.hlsl' % stage] + else: + command = [compiler, '/nologo', '/T', profile, '/E', 'main', '/Fo', bytecode, name + '.%s.hlsl' % stage] + r = subprocess.run(command, capture_output=True, text=True) + if r.returncode or not has_bytecode(bytecode): + detail = r.stderr.strip() or ('?' if r.returncode else 'no bytecode produced') + open(name + '.fail', 'w').write('fxc %s: %s\n' % (stage, detail[-2000:])) + return 'fxc %s failed: %s' % (stage, detail.splitlines()[-1]) + with suppress(FileNotFoundError, UnicodeError): + with open(manifest_path) as existing: + write_manifest = existing.read() != manifest + # If the bindings changed, withdraw the old manifest before publishing new bytecode. + if write_manifest: + with suppress(FileNotFoundError): + os.remove(manifest_path) + for stage in ('vs', 'ps'): + os.replace(os.path.join(staging, stage + '.cso'), name + '.%s.cso' % stage) + if not sm6: + temporary = '%s.txt.%d.tmp' % (name, os.getpid()) + with open(temporary, 'w') as result: + result.write(manifest) + os.replace(temporary, name + '.txt') + else: + if write_manifest: + temporary = '%s.%d.tmp' % (manifest_path, os.getpid()) + try: + with open(temporary, 'w') as result: + result.write(manifest) + os.replace(temporary, manifest_path) + finally: with suppress(FileNotFoundError): - os.remove(manifest_path) - for stage in ('vs', 'ps'): - os.replace(os.path.join(staging, stage + '.cso'), name + '.%s.cso' % stage) - if write_manifest: - temporary = '%s.%d.tmp' % (manifest_path, os.getpid()) - try: - with open(temporary, 'w') as result: - result.write(manifest) - os.replace(temporary, manifest_path) - finally: + os.remove(temporary) + if fxc: with suppress(FileNotFoundError): - os.remove(temporary) - if fxc: - with suppress(FileNotFoundError): - os.remove(name + '.fail') + os.remove(name + '.fail') return 'ok' def classify_decoded(ins): text = ' '.join(x[3] for x in ins if x[2] == 'exp') - return 'vs' if 'pos' in text else 'ps' if 'mrt' in text or not text else 'other' # no export: a depth-only pixel shader + return 'vs' if 'pos' in text else 'ps' if 'mrt' in text or 'null' in text or not text else 'other' def classify(blob): @@ -7350,7 +7852,7 @@ def classify_stage(blob): def mesh57_key(ms, ps, root): - value = fnv(b'x2w-startup-mesh-57-2') + value = fnv(b'x2w-startup-mesh-57-1') for part in (ms, ps, root): value = fnv(part, fnv(struct.pack(' 0xffffffffffffffff or any(fmt > 0xffffffff for fmt in formats): + raise Unsupported('invalid RTV variant values') + name = os.path.join(out_dir, 'req_%016x' % base) + a, b, root = (open(name + ext, 'rb').read() for ext in ('.a', '.b', '.root')) + # Upstream: a stream pipeline's input layout (.ia) is part of its key (pipeline_key, draw.inl). + layout = open(name + '.ia', 'rb').read() if os.path.isfile(name + '.ia') else b'' + if request and pipeline_key(a, b, root, layout) != base: + raise Unsupported('RTV variant source key mismatch') + fetch = attr_map = None + ps_hw_inputs = read_ps_inputs(name + '.psin') + vs_out_cntl = read_vs_out(name + '.vsout') + dumped = dumped_state(name) if ps_hw_inputs is None or vs_out_cntl is None else (None, None) + if ps_hw_inputs is None and dumped[0] is not None: + ps_hw_inputs = (dumped[0], dumped[0]) # ADDR assumed equal to ENA (no ADDR field located) + if ps_hw_inputs is None or len(ps_hw_inputs) == 2: + mode = dumped_float_mode(name) # the launch FLOAT_MODE, when the .psin does not carry it + if mode is not None: + ps_hw_inputs = tuple(ps_hw_inputs or (None, None)) + (mode,) + if vs_out_cntl is None: + vs_out_cntl = dumped[1] + if a.startswith(b'DXBC') or b.startswith(b'DXBC'): + # Slot 86 records complete containers in canonical (VS, PS) order. + # Keep the container bytes in the cache key; translate only the bounded native code. + import zlib + from pixel_aot import container_code + from resource_inventory import parts + try: + container, ps_container = a, b + a, b = (container_code(parts(blob)[b'DXIL'], stage=stage) + for blob, stage in ((a, 1), (b, 0))) + # Upstream: the stream's attribute pairing and the loads its vertex fetch call stands for. + attr_map = stream_interface(container, ps_container) + if starts_with_fetch_call(a): + fetch = stream_fetch(container, layout.decode('ascii') if layout else None) + except (KeyError, ValueError, IndexError, struct.error, zlib.error) as error: + raise Unsupported('invalid stream shader: %s' % error) from error + if classify(a) != 'vs' or classify(b) != 'ps': + raise Unsupported('stream stage and shader export disagree') + kinds = {'vs': a, 'ps': b} + else: + kinds = {classify(a): a, classify(b): b} except (Unsupported, OSError, UnicodeError) as reason: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason if set(kinds) != {'vs', 'ps'}: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write('stages %s\n' % sorted(kinds)) return 'stages %s' % sorted(kinds) - return translate_to(out_dir, key, kinds['vs'], kinds['ps'], root, rtv_formats=formats, rtv_request=request, vs_fetch=fetch, - ps_attr_map=attr_map) + return translate_to(out_dir, key, kinds['vs'], kinds['ps'], root, rtv_formats=formats, rtv_request=request, + ps_hw_inputs=ps_hw_inputs, vs_out_cntl=vs_out_cntl, vs_fetch=fetch, ps_attr_map=attr_map) + + +VSREGS_PS_INPUT_ENA = 0x58 +VSREGS_VS_OUT_CNTL = 0x98 + + +def dumped_state(name): + """(ENA or None, PA_CL_VS_OUT_CNTL or None) from .vsregs, else from the per-state dumps + .<8 hex>.vsregs when they all agree. (None, None) when nothing is dumped.""" + paths = [name + '.vsregs'] if os.path.isfile(name + '.vsregs') else [] + if not paths: + folder, base = os.path.split(name) + try: + paths = [os.path.join(folder, n) for n in os.listdir(folder or '.') + if re.fullmatch(re.escape(os.path.basename(base)) + r'\.[0-9a-f]{8}\.vsregs', n)] + except OSError: + paths = [] + enas, cntls = set(), set() + for path in paths: + with open(path, 'rb') as file: + blob = file.read(0x400) + enas.add(struct.unpack_from('= VSREGS_PS_INPUT_ENA + 2 else None) + cntls.add(struct.unpack_from('= VSREGS_VS_OUT_CNTL + 4 else None) + return (enas.pop() if len(enas) == 1 else None), (cntls.pop() if len(cntls) == 1 else None) + + +VSREGS_PS_RSRC1 = 0x4c + + +def dumped_float_mode(name): + """The pixel stage's launch FLOAT_MODE from .vsregs (or the agreeing per-state dumps), else None.""" + paths = [name + '.vsregs'] if os.path.isfile(name + '.vsregs') else [] + if not paths: + folder, base = os.path.split(name) + try: + paths = [os.path.join(folder, n) for n in os.listdir(folder or '.') + if re.fullmatch(re.escape(os.path.basename(base)) + r'\.[0-9a-f]{8}\.vsregs', n)] + except OSError: + paths = [] + modes = set() + for path in paths: + with open(path, 'rb') as file: + blob = file.read(0x400) + modes.add(struct.unpack_from('> 12 & 0xff if len(blob) >= VSREGS_PS_RSRC1 + 4 + else None) + return modes.pop() if len(modes) == 1 else None + + +def read_vs_out(path): + """PA_CL_VS_OUT_CNTL from a request's optional .vsout file, 'pa_cl_vs_out_cntl 1 ', or None.""" + if not os.path.isfile(path): + return None + with open(path, encoding='ascii') as file: + text = file.read(64) + m = re.fullmatch(r'pa_cl_vs_out_cntl 1 ([0-9a-f]{8})\n', text) + if not m: + raise Unsupported('invalid vertex output control file') + return int(m.group(1), 16) + + +# PA_CL_VS_OUT_CNTL fields (Mesa src/amd/registers/gfx10.json): CLIP_DIST_ENA_0..7 [7:0], CULL_DIST_ENA_0..7 [15:8], +# USE_VTX_POINT_SIZE 16, _EDGE_FLAG 17, _RENDER_TARGET_INDX 18, _VIEWPORT_INDX 19, _KILL_FLAG 20, +# VS_OUT_MISC_VEC_ENA 21, VS_OUT_CCDIST0_VEC_ENA 22, VS_OUT_CCDIST1_VEC_ENA 23, VS_OUT_MISC_SIDE_BUS_ENA 24, +# USE_VTX_GS_CUT_FLAG 25, USE_VTX_SHD_OBJPRIM_ID 26, USE_VTX_LINE_WIDTH 27. +VS_OUT_CCDIST0 = 1 << 22 +VS_OUT_SIDE_BUS = 1 << 24 + + +def clip_vector_width(cntl, vals): + """Channels of a pos1 export that are clip distances 0..n-1; refuses every other PA_CL_VS_OUT_CNTL use. + + Accepted only when pos1 is the first clip/cull distance vector (no misc vector, CCDIST0 on, CCDIST1 off, + no per-vertex misc values), the written channels are x.. contiguously, each is a clip distance, and the + cull enables are either none or the same channels. A distance that is both clip and cull distance is + lowered as SV_ClipDistance alone: the cull removes a primitive only when every vertex is below 0, which the + clip at 0 removes already. VS_OUT_MISC_SIDE_BUS_ENA (a transport choice) is allowed. + """ + written = [i for i, v in enumerate(vals) if v != 'off'] + n = len(written) + clip, cull = cntl & 0xff, cntl >> 8 & 0xff + if (cntl & ~(0xffff | VS_OUT_CCDIST0 | VS_OUT_SIDE_BUS) or not cntl & VS_OUT_CCDIST0 or not n + or written != list(range(n)) or clip != (1 << n) - 1 or cull not in (0, clip)): + raise Unsupported('pos1 export with PA_CL_VS_OUT_CNTL %#010x (channels %s)' % (cntl, written)) + return n + + +def read_ps_inputs(path): + """(ENA, ADDR[, FLOAT_MODE]) from a request's optional .psin file, + 'spi_ps_input 1 [ ]', or None. FLOAT_MODE is the pixel stage's launch + MODE[7:0] (SPI_SHADER_PGM_RSRC1_PS bits 19:12; for a mesh pipeline u32 at state block A + 0x04c, bits 19:12); + without it MODE 0 rounding is assumed (Stage.launch_mode). + + The runtime writes it beside the request (it is not part of the key); without one the pixel stage's SPI + input layout is unknown and a read of an input VGPR is refused. + """ + if not os.path.isfile(path): + return None + with open(path, encoding='ascii') as file: + text = file.read(256) + m = re.fullmatch(r'spi_ps_input 1 ([0-9a-f]{8}) ([0-9a-f]{8})( [0-9a-f]{8})?\n(?:vs_input 1 [0-3] [0-9a-f]{8}\n)?', + text) + if not m: + raise Unsupported('invalid SPI input file') + if m.group(3) is None: + return int(m.group(1), 16), int(m.group(2), 16) + # optional third field: the pixel stage's launch FLOAT_MODE (SPI_SHADER_PGM_RSRC1_PS bits 19:12), 8 hex digits + mode = int(m.group(3), 16) + if mode > 0xff: + raise Unsupported('invalid SPI input file') + return int(m.group(1), 16), int(m.group(2), 16), mode REFUSALS_CAVEAT = ('Counts after the first refusal are approximate. Skipped instructions leave later state ' diff --git a/tools/startup/gpu_slab_pool.py b/tools/startup/gpu_slab_pool.py new file mode 100644 index 0000000000..9cece44d1d --- /dev/null +++ b/tools/startup/gpu_slab_pool.py @@ -0,0 +1,120 @@ +"""Hold shared pagefile sections used by the XMem GPU pool. Run with ensure, hold or quit.""" +import ctypes +import os +import subprocess +import sys +import time +from ctypes import wintypes as wt + +PREFIX = "Local\\x2w-gpu-slab-" +READY = "Local\\x2w-gpu-slab-pool-ready" +QUIT = "Local\\x2w-gpu-slab-pool-quit" +k32 = ctypes.WinDLL("kernel32", use_last_error=True) +k32.CreateFileMappingW.restype = wt.HANDLE +k32.CreateFileMappingW.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.DWORD, wt.LPCWSTR] +k32.OpenEventW.restype = wt.HANDLE +k32.OpenEventW.argtypes = [wt.DWORD, wt.BOOL, wt.LPCWSTR] +k32.CreateEventW.restype = wt.HANDLE +k32.CreateEventW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.BOOL, wt.LPCWSTR] +k32.OpenFileMappingW.restype = wt.HANDLE +k32.OpenFileMappingW.argtypes = [wt.DWORD, wt.BOOL, wt.LPCWSTR] +PAGE_READWRITE, SEC_COMMIT, SYNCHRONIZE, EVENT_MODIFY_STATE, FILE_MAP_READ = 0x04, 0x8000000, 0x100000, 0x2, 0x4 + + +def opt(name, default): + return int(sys.argv[sys.argv.index(name) + 1]) if name in sys.argv else default + + +def running(): + h = k32.OpenEventW(SYNCHRONIZE, False, READY) + if not h: + return False + k32.CloseHandle(h) + return True + + +def hold(count, mib): + quit_event = k32.CreateEventW(None, True, False, QUIT) + handles = [] + size = mib << 20 + for i in range(count): + h = k32.CreateFileMappingW(wt.HANDLE(-1), None, PAGE_READWRITE | SEC_COMMIT, size >> 32, size & 0xFFFFFFFF, PREFIX + str(i)) + if not h: + print(f"section {i} failed: {ctypes.get_last_error()}", flush=True) + break + handles.append(h) # an existing section (a second holder growing the pool) is just held once more + ready = k32.CreateEventW(None, True, True, READY) + print(f"holding {len(handles)} x {mib} MiB sections ({PREFIX}0..{len(handles) - 1})", flush=True) + k32.WaitForSingleObject(wt.HANDLE(quit_event), 0xFFFFFFFF) + for h in handles: + k32.CloseHandle(wt.HANDLE(h)) + k32.CloseHandle(wt.HANDLE(ready)) + return 0 + + +def reachable(): + """How many pool sections can be opened by name now.""" + n = 0 + while True: + h = k32.OpenFileMappingW(FILE_MAP_READ, False, PREFIX + str(n)) + if not h: + return n + k32.CloseHandle(wt.HANDLE(h)) + n += 1 + + +def ensure(count, mib=256): + """Starts the holder unless it runs with at least count sections; returns the number of pool sections reachable + (0 if it failed). A holder with fewer sections is not ended (its used sections stay charged anyway): a second + holder is started that opens the existing sections and creates the missing ones; quit ends both.""" + have = reachable() if running() else 0 + if have >= count: + return have + # Detached, outside any job of the caller, no console: it must outlive the run that started it. + flags = 0x00000008 | 0x00000200 | 0x01000000 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB + out_dir = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "out")) + os.makedirs(out_dir, exist_ok=True) + args = [sys.executable, "-B", os.path.abspath(__file__), "hold", "--count", str(count), "--mib", str(mib)] + # Neutral working directory: the holder must not keep the caller's (e.g. the title's data drive) in use. + cwd = os.environ.get("SystemRoot", out_dir) + with open(os.path.join(out_dir, "gpu_slab_pool.log"), "a") as log: + try: + subprocess.Popen(args, creationflags=flags, stdout=log, stderr=log, stdin=subprocess.DEVNULL, close_fds=True, + cwd=cwd) + except OSError: # the caller's job may refuse breakaway: start without it + print("gpu_slab_pool: the holder could not leave the caller's job and ends with it; the pool then " + "only helps within that job's lifetime", flush=True) + subprocess.Popen(args, creationflags=flags & ~0x01000000, stdout=log, stderr=log, stdin=subprocess.DEVNULL, + close_fds=True, cwd=cwd) + for _ in range(100): + if running() and reachable() >= count: + return reachable() + time.sleep(0.1) + return reachable() if running() else 0 + + +def main(): + what = sys.argv[1] if len(sys.argv) > 1 else "status" + count, mib = opt("--count", 12), opt("--mib", 256) + if what == "hold": + return hold(count, mib) + if what == "status": + print(f"holder {'running' if running() else 'not running'}; {reachable()} pool section(s) reachable") + return 0 + if what == "quit": + h = k32.OpenEventW(EVENT_MODIFY_STATE, False, QUIT) + if h: + k32.SetEvent(wt.HANDLE(h)) + k32.CloseHandle(wt.HANDLE(h)) + print("quit signalled" if h else "holder not running") + return 0 + if what == "ensure": + n = ensure(count, mib) + print(f"{n} pool section(s) reachable" if n else "holder did not report ready within 10 s") + return 0 if n else 1 + print(__doc__) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/startup/mesh2hlsl.py b/tools/startup/mesh2hlsl.py new file mode 100644 index 0000000000..946e3abd67 --- /dev/null +++ b/tools/startup/mesh2hlsl.py @@ -0,0 +1,3684 @@ +"""gfx1013 NGG mesh-stage machine code -> HLSL mesh shader (SM 6.5) for a mesh + pixel pipeline (startup tools). + +The console compiles a mesh shader to an NGG primitive shader (wave64, 128 threads, one thread per output vertex and +one per output primitive). This module translates that program with the pipeline translator's one-lane model +(gfx2hlsl.Stage: registers are uint variables, exec/vcc/masks hold the lane's bit) and wraps it in an HLSL mesh +shader: + + * one HLSL thread per console lane: SV_GroupIndex = the console's thread index in the group + (wave id from merged_wave_info bits 27:24 times 64, plus v_mbcnt lane); + * s_sendmsg 0x9 (GS_ALLOC_REQ) records m0 = vertices | primitives << 12 (Mesa ac_nir_prerast_utils.c + ac_nir_ngg_alloc_vertices_and_primitives) in groupshared memory; after the program a barrier publishes it and + SetMeshOutputCounts runs once, in uniform control flow; + * `exp pos0` / `exp paramN` from thread t define output vertex t, `exp prim` (target 20) primitive t, with the + gfx10 primitive export word: index i in bits [10*i+8 : 10*i], bit 31 = null primitive (Mesa ac_nir_lower_ngg.c + "nir_ubfe_imm(..., 10 * v, 9)" and the "1u << 31" null export). A null or out-of-range primitive is emitted + with SV_CullPrimitive; + * the workgroup index: the console reads v5 (first ES input VGPR, the vertex id in a fast-launch NGG + dispatch) of its first lane and shifts it right by 7. This translation sets v5 = SV_GroupID.x * 128 + + SV_GroupIndex (INFERRED: consistent with every one of the 9282 archive shaders reading v5 >> 7 in each wave + without LDS; a register dump of a mesh pipeline's GE/SPI state would settle it). + +Cross-lane facts the one-lane model cannot see are checked and refused (Unsupported), never guessed: + * v_readfirstlane_b32 needs a source that is the same in every lane (taint analysis over the emitted HLSL); + * a per-lane branch (execz/execnz/vccz/vccnz) is taken per lane; that equals the wave-level branch only when + no scalar register written in the skipped range is read after it, and, for vcc, when vcc is uniform over the + active lanes (`exec & uniform`); + * a branch on an SCC that depends on lane masks (the hardware sets SCC from the whole 64-bit result) is taken + per lane only when that SCC is the same in every active lane and every running thread is an active lane; + otherwise the wave's SCC is published through groupshared memory and a group barrier (MeshStage.lane_scc), + or the program is refused where a barrier cannot be placed (X2W_MESH_LANE_SCC=0 refuses all of them). +LDS, DPP and permlane are not lowered (refused by the base translator); v_writelane / v_readlane only as the SGPR +spill idiom (per-wave scalar slots, MeshStage.lower_spills). +""" +import copy +import os +import re +import struct +import subprocess +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 +from gfx2hlsl import Unsupported, reg_range, parse # noqa: E402 + +GROUP = 128 # PSV0 numthreads (128, 1, 1) in all 9282 archive mesh records +MAX_VERTICES = 128 # PSV0 MaxOutputVertices +MAX_PRIMITIVES = 128 # PSV0 MaxOutputPrimitives +ALL_LANES = (1 << 64) - 1 +# User SGPRs of the mesh stage start at s16 (MEASURED: in all 4045 distinct run programs the SGPRs read before any +# write lie in s16..s24, and the real root signatures (regblob g57_*.root) give 9 = 3 tables + 1 root SRV + 2 +# constants + resource heap + sampler heap; s8..s15 are written first. Pixel and vertex stages start at s8.) +MESH_USER_SGPR = 16 +FUSED = ('v_fma_f32', 'v_fmac_f32', 'v_fmamk_f32', 'v_fmaak_f32') +UNFUSED = ('v_mad_f32', 'v_mac_f32', 'v_madmk_f32', 'v_madak_f32') +FMA_MODE = os.environ.get('X2W_MESH_FMA', 'exact') +if os.environ.get('X2W_MESH_EXACT_FMA') == '0': + FMA_MODE = 'precise' # the round-1 switch, kept +if FMA_MODE not in ('exact', 'precise'): + raise SystemExit('X2W_MESH_FMA: exact or precise, not %r' % FMA_MODE) +EXACT_FMA = FMA_MODE == 'exact' +LDS_DWORDS = 1024 # groupshared x2w_lds (4 KB of the 28 KB a D3D12 mesh shader may use); addresses are clamped +TOKEN = re.compile(r'\b(v\d+|s\d+|exec|vcc|m0|scc|a|w|t|q|tid|lane)\b') +SIMPLE = re.compile(r'^\s*(?:if \(exec & 1\) )?(v\d+|s\d+|exec|vcc|m0|scc|a|w|t|q)\s*=\s*(.*)$') + +MESH_HELPERS = { + # v_perm_b32 D, S0, S1, S2: byte i of D = selector byte i of S2 over the eight bytes {S0 (bytes 4-7), S1 (0-3)}; + # 8..11 replicate the sign bit of S1[15], S1[31], S0[15], S0[31]; 12 gives 0x00, 13..15 give 0xff + # (RDNA 2 ISA, V_PERM_B32). + 'x2w_perm': ('uint x2w_perm_byte(uint s0, uint s1, uint sel) { if (sel < 4u) return (s1 >> (8u * sel)) & 255u; ' + 'if (sel < 8u) return (s0 >> (8u * (sel - 4u))) & 255u; if (sel == 8u) return ((s1 >> 15) & 1u) * 255u; ' + 'if (sel == 9u) return ((s1 >> 31) & 1u) * 255u; if (sel == 10u) return ((s0 >> 15) & 1u) * 255u; ' + 'if (sel == 11u) return ((s0 >> 31) & 1u) * 255u; if (sel == 12u) return 0u; return 255u; }\n' + 'uint x2w_perm(uint s0, uint s1, uint s2) { uint r = 0; [unroll] for (uint i = 0; i < 4u; ++i) ' + 'r |= x2w_perm_byte(s0, s1, (s2 >> (8u * i)) & 255u) << (8u * i); return r; }'), + # v_mbcnt_{lo,hi}_u32_b32 D, S0, S1 in a 64-lane wave: S1 + the number of set S0 bits below this lane in the + # low (lanes 0-31) or high (lanes 32-63) half of the wave mask. + 'x2w_fclass': ('uint x2w_fclass(uint u) { uint e = (u >> 23) & 255u, m = u & 0x7fffffu, s = u >> 31; ' + 'if (e == 255u) return m != 0u ? ((m >> 22) != 0u ? 1u : 0u) : (s != 0u ? 2u : 9u); ' + 'if (e == 0u) return m == 0u ? (s != 0u ? 5u : 6u) : (s != 0u ? 4u : 7u); ' + 'return s != 0u ? 3u : 8u; }'), + 'x2w_fma':'float x2w_fma(float a, float b, float c) { return (float)fma((double)a, (double)b, (double)c); }', + 'x2w_madp': 'float x2w_madp(float a, float b, float c) { precise float p = a * b; precise float r = p + c; return r; }', + 'x2w_mbcnt_lo':'uint x2w_mbcnt_lo(uint m, uint lane) { return countbits(m & (lane >= 32u ? 0xffffffffu : ((1u << lane) - 1u))); }', + 'x2w_mbcnt_hi': 'uint x2w_mbcnt_hi(uint m, uint lane) { return lane < 32u ? 0u : countbits(m & ((1u << (lane - 32u)) - 1u)); }', + 'x2w_hword': ('ByteAddressBuffer x2w_vdesc : register(t2, space1);\n' + 'uint x2w_hword(uint h, uint i) { uint id = x2w_vid(h); return id < %du ? x2w_vdesc.Load(id * 32u + 4u * i) : 0u; }' + % getattr(G, 'HEAP_IDS', 90000)), +} +# Mesh-only lowerings whose manifest lines need runtime support not in the draw path yet (comma list): +# heapwords = numeric reads of resource-heap descriptor words (x2w_hword, manifest `heapwords 1`). +# Exec-off conflicts (MeshStage.merge_exec_off): on by default; X2W_MESH_EXECOFF=0 restores the earlier refusals. +EXEC_OFF = os.environ.get('X2W_MESH_EXECOFF', '1') != '0' +# X2W_MESH_EXEC_COPIES=0: per-lane skipped ranges accept only exec copies taken inside the range (the f37ad9f8 rule); +# default on: also a pair proven equal to exec at the branch, and copies of copies (MeshStage.exec_copies_at). +EXEC_COPIES = os.environ.get('X2W_MESH_EXEC_COPIES', '1') != '0' +# X2W_MESH_BARRIER_RANGES=0: a group-uniform execz range is skipped when no lane of the group is active even when it +# holds a phase barrier (the f37ad9f8 form; barrier_count then refuses "paths cross different numbers of barriers"). +BARRIER_RANGES = os.environ.get('X2W_MESH_BARRIER_RANGES', '1') != '0' +# X2W_MESH_RESTORED_SCALARS=0: a scalar written in a per-lane skipped range counts as live after it even when every +# exit of the range gives it back its value from before, and liveness reads VALU lane masks by their low SGPR only +# (the f37ad9f8 rule). +RESTORED_SCALARS = os.environ.get('X2W_MESH_RESTORED_SCALARS', '1') != '0' +# X2W_MESH_SPILLS=0: v_writelane_b32 / v_readlane_b32 stay refused (the 9eacac67 behaviour); default on: the SGPR +# spill idiom is lowered to per-wave scalar slots (MeshStage.lower_spills). +SPILLS = os.environ.get('X2W_MESH_SPILLS', '1') != '0' +# X2W_MESH_VCC_DATA=0: vcc stays the one-lane mask variable everywhere (32-bit data in vcc_lo is cut to bit 0, vcc_hi +# is refused); default on: vcc holding no lane mask is the SGPR pair s[106:107] (MeshStage.lower_vcc_data). +VCC_DATA = os.environ.get('X2W_MESH_VCC_DATA', '1') != '0' +# X2W_MESH_DATA_PAIRS=0: every s_mov_b64 between SGPR pairs is a lane-mask move (the base: bit 0 of the low word); +# default on: a pair that holds no lane mask is copied as its two 32-bit registers (MeshStage.scalar_inner). +DATA_PAIRS = os.environ.get('X2W_MESH_DATA_PAIRS', '1') != '0' +SLOT_BASE = 1000 # spill slot (i-th spill VGPR, lane k) = pseudo-SGPR s +# X2W_MESH_RFL_FIRST=0: v_readfirstlane_b32 of a lane-dependent value under a partial exec is refused (as before); +# default on: the wave's first ACTIVE lane is found through groupshared memory and a group barrier +# (MeshStage.first_active_broadcast), and an execz range holding such a read is run by the whole group. +RFL_FIRST = os.environ.get('X2W_MESH_RFL_FIRST', '1') != '0' +RFL_FIRST_SLOTS = 8 # first-active-lane reads per program (each: 2 x 128 groupshared words) +MESH_FEATURES = frozenset(f for f in os.environ.get('X2W_MESH_FEATURES', '').replace(' ', '').split(',') if f) +# descword (MeshStage.dw_*): a word of a TABLE descriptor read as a number becomes the runtime's entry value +# `udsrc descword ` (d3d12_draw.inl, needs X2W_MESH_DESCWORD=1 there), computed lazily: only words +# some numeric use reaches get an entry value; arithmetic nobody reads stays dead (0u). +if MESH_FEATURES - {'heapwords', 'descword'}: + raise SystemExit('X2W_MESH_FEATURES: unknown %s' % ', '.join(sorted(MESH_FEATURES - {'heapwords', 'descword'}))) +# Lane-mask SCC (wave "any lane" value through groupshared memory, MeshStage.lane_scc): on unless +# X2W_MESH_LANE_SCC=0. X2W_MESH_TEST_DROP=publish|restore (TESTS ONLY, negative controls) leaves out the wave +# publish of such an SCC / the restore of hit scalars after a group-uniform execz range: both give wrong results. +LANE_SCC = os.environ.get('X2W_MESH_LANE_SCC', '1') != '0' +TEST_DROP = frozenset(os.environ.get('X2W_MESH_TEST_DROP', '').replace(' ', '').split(',')) - {''} +# Lane taint merged at joins of forward edges (MeshStage.merge): on unless X2W_MESH_JOIN_TAINT=0 (the linear scan). +JOIN_TAINT = os.environ.get('X2W_MESH_JOIN_TAINT', '1') != '0' +# The per-lane shortcut for an active-uniform lane-mask SCC with lanes off needs a mask result confined to the +# active lanes (MeshStage.one_body): on unless X2W_MESH_CONFINED_SCC=0 (tests only: the unrestricted shortcut). +CONFINED_SCC = os.environ.get('X2W_MESH_CONFINED_SCC', '1') != '0' +# A group-uniform execz skip may jump over every barrier the translation added (readfirstlane broadcasts, inner +# group-branch publishes, lane-mask SCC publishes), never over the program's s_barrier: on unless +# X2W_MESH_SKIP_ADDED=0 (then only lane-mask SCC publishes may be skipped, as at 135ee723). +SKIP_ADDED = os.environ.get('X2W_MESH_SKIP_ADDED', '1') != '0' +# Exec lineage (MeshStage.emit, lineage_ok): a value written from uniform values while exec was E stays the same in +# every active lane wherever exec is E or a narrowing of E (also after a restore to a saved copy of E or of a +# narrowing of it), not only until the next exec widening. OFF unless X2W_MESH_EXEC_LINEAGE=1: it moves no request key +# to ok yet (the keys it unblocks stop at a numeric descriptor word next) and no difftest covers a program needing it. +EXEC_LINEAGE = os.environ.get('X2W_MESH_EXEC_LINEAGE', '0') == '1' + + +class LaneScc(Unsupported): + """A branch on an SCC computed from lane masks; `origins` = offsets of the SALU mask instructions it comes from + (MeshPipeline translates again with those publishing the wave's value).""" + + def __init__(self, text, origins): + super().__init__(text) + self.origins = origins + + +class NeedGroupRange(Unsupported): + """A lane-dependent v_readfirstlane_b32 inside the per-lane execz range at `off`: MeshPipeline translates again + with that range run by the whole group (MeshStage.group_branches), so the read can use a group barrier.""" + + def __init__(self, off, text): + super().__init__(text) + self.off = off + +# Loop heads take the join of their entry and back edges, iterated until it settles (MeshStage.loop_one). +# X2W_MESH_LOOP_JOIN=0 restores the linear state at loop heads (the old behaviour: wrong for loop-carried values). +LOOP_JOIN = os.environ.get('X2W_MESH_LOOP_JOIN', '1') != '0' +LOOP_PASSES = 8 +BOTTOM = 'x2w_bottom' # key in a symbolic state: no path reaches this code in the current loop pass +# Waterfall loops (MeshStage.waterfalls): one pass per lane with the lane's own value. X2W_MESH_WATERFALL=0 refuses +# them as before (v_readfirstlane of a lane-dependent value with lanes off). +WATERFALL = os.environ.get('X2W_MESH_WATERFALL', '1') != '0' +# Instructions a waterfall body may not contain: cross-lane, wave-level, exec, memory ordering across lanes. +# Per-lane loops (MeshStage.perlane_loop): a back edge on "some lane still loops" becomes each thread's own loop. +# X2W_MESH_PERLANE_LOOPS=0 refuses them as before (branch on an SCC that depends on lane masks). +PERLANE_LOOPS = os.environ.get('X2W_MESH_PERLANE_LOOPS', '1') != '0' +PERLANE_BODY_REFUSED = re.compile(r'(v_readlane|v_writelane|v_permlane|ds_|s_barrier|s_sendmsg|exp$|s_setreg|s_store|' + r's_atomic|s_buffer_store|s_buffer_atomic|.*_dpp$|s_endpgm)') +WATERFALL_BODY_REFUSED = re.compile(r'(v_readlane|v_readfirstlane|v_writelane|v_permlane|ds_|s_barrier|s_sendmsg|exp$|' + r's_setreg|s_cbranch|s_branch|s_endpgm|.*_dpp$|.*_saveexec|.*_wrexec|v_cmpx)') + + +class LoopRetry(Exception): + """A loop head's state was not the join of its edges; carries the back-edge states for the next pass.""" + + def __init__(self, backs): + super().__init__('loop state not settled') + self.backs = backs + + +def scalar_regs(text): + """SGPR numbers named in an operand string (s7, s[4:7]).""" + out = set() + for m in re.finditer(r'\bs\[(\d+):(\d+)\]|\bs(\d+)\b', text): + if m.group(3): + out.add(int(m.group(3))) + else: + out.update(range(int(m.group(1)), int(m.group(2)) + 1)) + return out + + +CARRY = re.compile(r'v_(add|sub|subrev)_co(_ci)?_u32') + +NO_DEST = ('s_cmp', 's_bitcmp', 's_cbranch', 's_branch', 's_waitcnt', 's_sendmsg', 's_barrier', 's_nop', 's_setreg', + 's_inst_prefetch', 's_endpgm', 's_clause', 's_setprio', 's_code_end', 's_sopp') + + +def reads_writes(name, asm): + """(scalar registers read, scalar registers written, writes vcc, reads vcc) of one instruction (approximate: + writes are only what the destination operand names).""" + _, ops, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', name) + writes, reads = set(), set() + wvcc = rvcc = False + if base.startswith('s_') and not base.startswith(NO_DEST) and ops: + writes = scalar_regs(ops[0]) + wvcc = ops[0].startswith('vcc') + rest = ops[1:] + if base.startswith(('s_load', 's_buffer_load')): + rest = ops[1:] + elif (base.startswith('v_cmp') and len(ops) == 3) or base == 'v_readfirstlane_b32' or base == 'v_readlane_b32': + writes = scalar_regs(ops[0]) + wvcc = ops[0].startswith('vcc') + rest = ops[1:] + elif CARRY.fullmatch(base) and len(ops) >= 4: + # VOP2/VOP3b carry-out: the disassembler names one SGPR (or vcc_lo); in wave64 the mask is the pair + writes = scalar_regs(ops[1]) + writes |= {n + 1 for n in writes} + wvcc = ops[1].startswith('vcc') + rest = ops[2:] + else: + rest = ops + if base.startswith('v_cmp') and len(ops) == 2: + wvcc = not base.startswith('v_cmpx') + for o in rest: + reads |= scalar_regs(o) + rvcc |= o.startswith('vcc') + if base in ('v_cndmask_b32', 'v_addc_co_u32') and len(ops) == 3: + rvcc = True + if base in ('s_cbranch_vccz', 's_cbranch_vccnz'): + rvcc = True + return reads, writes, wvcc, rvcc + + +class MeshStage(G.Stage): + """One NGG mesh stage. kind 'ms'.""" + + def __init__(self, pipe, code): + self.tainted = {'tid', 'lane', 'v5'} + self.au, self.epoch = {}, 0 + # exec lineage: exec states form a tree (a narrowing is a child of the state it narrows); xs = the current + # state, au_xs[reg] = (state, write serial) of an active-uniform value, xs_copy[sgpr] = the state it copies + self.xs, self.xs_parent, self.au_xs, self.xs_copy, self.xs_serial = 0, {0: None}, {}, {}, 0 + self._xs_exec_seen = False + self.au_scalars = {} + self.broadcasts = 0 + self.literal_tables = {} + self.first_slots = 0 # first-active-lane reads (x2w_rfv / x2w_rfe slots) + self.divergent_until = -1 + self.exported_vertex = False + self.exported_prim = False + self.alloc_seen = False + self.wave = 64 + self.exec_static = ALL_LANES # exec as a known 64-bit lane mask (the same in every wave), else None + self.static_copies = {} # SGPR -> the static exec mask it holds + self._static_set = False + self.shadow = {} # VGPR -> (unguarded variable, exec mask at the write); straight-line code only + self.shadow_vars = [] + self.pending = [] # statements that start the next block (after a broadcast barrier) + self.scc_from = {} # register -> offsets of lane-mask SCC definitions its value derives from + self.scc_any = [] # lane-mask SCCs published per wave (offsets): x2w_sany[k][wave] + self.join_from = {} # branch target -> scc_from union over the branches to it + self.fell_off = False # the previous instruction does not fall through (jump, end) + self.running_active = False # inside a per-lane execz range, no exec write since: running threads = active lanes + self.scc_confined = set() # lane-mask SCC offsets whose mask result is inside the active lanes (`x & exec`) + self.lds_used = False + self.lds_written_in_phase = False + self.exec_off = set() # conflict SGPRs whose conflicting paths all came with this lane's exec bit 0 + self._execz_edge = False + self._execz_snaps = [] # snapshots of taken s_cbranch_execz edges (compared by identity) + super().__init__(pipe, 'ms', code) + if not self.alloc_seen: + raise Unsupported('no GS_ALLOC_REQ (s_sendmsg 0x9): not an NGG mesh stage') + self.barriers = self.barrier_count() + + def translate(self): + # The program ends at the s_code_end padding; the words after it are data, not code. + for i, x in enumerate(self.ins): + if x[2] == 's_code_end': + self.ins = self.ins[:i] + break + self.vcc_renamed = self.lower_vcc_data() + self.spill_vgprs, self.spill_slots = self.lower_spills() + self.swap_scc = self.lower_pair_swaps() + self.has_lds = any(x[2].startswith('ds_') for x in self.ins) + self.wave_any = [] # group-uniform execz branches (offsets): x2w_any[k][wave] = some lane active + self.group_restore = {} # range end -> statements restoring hit scalars in a wave that had no lane on + self.group_checks = {} # range end -> (register, symbolic value before the range, branch offset) + self.uniform_skips = set() # offsets of the inserted group-uniform skip blocks + if LOOP_JOIN and self.loop_heads(): + self.loop_prepare() + self.one = self.loop_one # instance attribute: the base's scan calls it for every instruction + result = super().translate() + if LOOP_JOIN and self.loop_heads(): + self.loop_settled() + for n in sorted(self.spill_vgprs): + if n in self.used_v or n in self.written_v: + raise Unsupported('v%d holds spilled scalars (v_writelane) and is also used as a VGPR' % n) + # A group-uniform branch block ends in a barrier (the lanes publish their exec bit); the block after it + # skips the range when no lane of the group was active (group_branch). + # A range with a phase barrier inside (a console s_barrier, a broadcast or a nested group branch) is never + # skipped: the skip is group-uniform, but a block after the range would then start in two different phases + # (body() gives each block one). Running it with every lane off is what skipping does: vector writes, + # exports, LDS writes and stores stay guarded by exec, and the restore gives each wave with no active lane + # its scalars from before the range back. + # (lane-mask SCC publish barriers are left out: 28020dea lets the uniform skip jump over those) + barrier_at = [b[0] for b in self.blocks if b[2] and b[2][0] == 'barrier' and b[2][1:2] != ('lane-scc',)] + blocks = [] + for b in self.blocks: + if b[2] and b[2][0] == 'barrier' and len(b[2]) > 1 and b[2][1] == 'wave-branch': + k = b[2][2] + blocks.append((b[0], self.group_restore.get(b[0], []) + b[1], ('barrier',))) + if not (BARRIER_RANGES and any(b[0] < o < b[2][3] for o in barrier_at)): + blocks.append((b[0] + 0.5, [], ('branch', '(x2w_any[%d][0] | x2w_any[%d][1]) == 0u' % (k, k), b[2][3]))) + self.uniform_skips.add(b[0] + 0.5) + elif b[0] in self.group_restore: + blocks.append((b[0], self.group_restore[b[0]] + b[1], b[2])) + else: + blocks.append(b) + missing = set(self.group_restore) - {b[0] for b in self.blocks} + if missing: + raise Unsupported('execz range end %#x is not a block start' % min(missing)) + self.blocks = blocks + return result + + def lower_pair_swaps(self): + """A ^= B; B ^= A; A ^= B swaps two disjoint SGPR pairs, including descriptors. + Keep the original offsets for branches. No edge may enter the middle. The final + XOR's wave-wide SCC must be dead because the three replacement moves leave it alone. + """ + targets = {int(parse(asm)[1][0].split('_')[1], 16) for _, _, name, asm in self.ins + if name == 's_branch' or name.startswith('s_cbranch')} + scc = set() + for i, first in enumerate(self.ins): + _, _, xor, _ = first + if xor not in ('s_xor_b32', 's_xor_b64'): + continue + first_ops = parse(first[3])[1] + if len(first_ops) != 3: + continue + touched = set().union(*(scalar_regs(o) for o in first_ops)) + sites = [i] + for j in range(i + 1, min(i + 16, len(self.ins))): + off, _, name, asm = self.ins[j] + if off in targets: + break + if name == xor: + sites.append(j) + if len(sites) == 3: + break + else: + if not (name in ('s_mov_b32', 's_mov_b64') or + re.fullmatch(r'v_(?:add_f32|sub_f32|mul_f32|mov_b32)_e(?:32|64)', name)): + break + regs = set().union(*G.sgpr_access(name, asm)) + if regs & touched or 'src_scc' in parse(asm)[1]: + break + if len(sites) != 3: + continue + operands = [parse(self.ins[j][3])[1] for j in sites] + if any(len(o) != 3 for o in operands): + continue + a, b = operands[0][0], operands[1][0] + ra, rb = reg_range(a), reg_range(b) + width = 2 if xor.endswith('64') else 1 + if not all(r and r[0] == 's' and r[2] == r[1] + width - 1 and r[2] < 128 for r in (ra, rb)): + continue + if abs(ra[1] - rb[1]) < width or operands[2][0] != a or any(set(o[1:]) != {a, b} for o in operands): + continue + # The architectural SGPRs are below 128; private lane spill slots start at SLOT_BASE. + tmp = 's[%d:%d]' % (SLOT_BASE-2, SLOT_BASE-1) if width == 2 else 's%d' % (SLOT_BASE-2) + move = 's_mov_b64' if width == 2 else 's_mov_b32' + for j, (dst, src) in zip(sites, ((tmp, a), (a, b), (b, tmp))): + off, n, _, _ = self.ins[j] + self.ins[j] = (off, n, move, '%s %s, %s' % (move, dst, src)) + scc.add(self.ins[sites[-1]][0]) + return scc + + def check_scc(self, written, unknown): + return super().check_scc(written, unknown | self.swap_scc) + + # ---- SGPR spills to VGPR lanes -------------------------------------------------------------- + # v_writelane_b32 vN, S, k writes the scalar S into lane k of vN and keeps the other lanes; v_readlane_b32 sD, vN, k + # copies lane k of vN into sD. Neither reads exec (LLVM VOP2Instructions.td: "These are special and do not read + # the exec mask", Uses = []; V_WRITELANE_B32 ties $vdst = $vdst_in). LLVM SIRegisterInfo::spillSGPR / + # restoreSGPR and Mesa ACO spill a scalar register to one lane per 32-bit part with an immediate lane index, so + # the 64 lanes of such a VGPR are 64 wave scalars: lane k is written and read only as a whole-wave value. In the + # one-lane model that is a scalar register like any other; lower_spills renames it to the pseudo-SGPR + # s and the instructions to scalar moves, so liveness, the per-lane skipped-range rules, + # group-uniform branches, lane masks, symbolic descriptors and exec copies treat a slot exactly as an SGPR. + @staticmethod + def _half(tok): + """(pair name for s_mov_b64, 0 = low / 1 = high half) of a 32-bit operand that is half of a 64-bit pair.""" + if tok in ('vcc_lo', 'vcc_hi'): + return 'vcc', int(tok == 'vcc_hi') + if tok in ('exec_lo', 'exec_hi'): + return 'exec', int(tok == 'exec_hi') + r = reg_range(tok) + if r and r[0] == 's' and r[1] == r[2] and r[1] < SLOT_BASE: + low = r[1] & ~1 # 64-bit SGPR operands are even-aligned + return 's[%d:%d]' % (low, low + 1), r[1] & 1 + return None + + # ---- vcc as two 32-bit scalar registers ---------------------------------------------------------- + # VCC_LO / VCC_HI are SGPRs 106 / 107 (RDNA 2 ISA, scalar operand encoding); in wave64 the compiler uses them as + # an ordinary SGPR pair when no lane mask needs them (32-bit loads, moves, float operands, spills). The one-lane + # model keeps a lane MASK in the variable `vcc` (the lane's bit), so a 32-bit value there is cut to bit 0. + @staticmethod + def vcc_roles(name, asm): + """[(operand index or None, halves, is_def, kind)] for each vcc operand; kind 'mask' (the wave64 lane mask + the one-lane model keeps in `vcc`), 'data' (a 32-bit value) or 'any' (a 64-bit scalar move or logic op, + a spill of a half: right either way).""" + _, ops, mods = parse(asm) + base = re.sub(r'_(e32|e64|sdwa|dpp)$', '', name) + out = [] + if base in ('s_cbranch_vccz', 's_cbranch_vccnz'): + return [(None, (0, 1), False, 'mask')] + if base in ('v_div_fmas_f32', 'v_div_fmas_f64', 'v_div_scale_f32', 'v_div_scale_f64'): + out.append((None, (0, 1), base.startswith('v_div_scale'), 'mask')) # implicit vcc + carry = re.fullmatch(r'v_(add|sub|subrev)_co(_ci)?_u32|v_(add|sub|subrev)c_co_u32', base) + for i, tok in enumerate(ops): + t = tok.lstrip('-|').rstrip('|') + r = reg_range(t) + if r and r[0] == 's' and r[1] <= 107 and r[2] >= 106: + # the disassembler names vcc by number inside a register range (s_buffer_load_dwordx2 s[106:107]) + halves = tuple(h for h in (0, 1) if r[1] <= 106 + h <= r[2]) + elif t not in ('vcc', 'vcc_lo', 'vcc_hi'): + continue + else: + halves = (0, 1) if t == 'vcc' else ((1,) if t == 'vcc_hi' else (0,)) + if base.startswith('s_'): + is_def = i == 0 and not base.startswith(NO_DEST) + kind = 'any' if (base.endswith('_b64') or 'saveexec' in base) else 'data' + elif base.startswith('v_cmp') and not base.startswith('v_cmpx') and i == 0: + is_def, kind, halves = True, 'mask', (0, 1) # wave64 SDST: the disassembler names vcc_lo + elif base == 'v_cndmask_b32' and i == len(ops) - 1: + is_def, kind, halves = False, 'mask', (0, 1) + elif carry and i == 1 and len(ops) >= 4: + is_def, kind, halves = True, 'mask', (0, 1) + elif carry and i == len(ops) - 1 and len(ops) >= 5: + is_def, kind, halves = False, 'mask', (0, 1) + elif base in ('v_writelane_b32', 'v_readlane_b32'): + is_def, kind = base == 'v_readlane_b32' and i == 0, 'any' + elif base in ('v_readfirstlane_b32',) and i == 0: + is_def, kind = True, 'data' + else: + is_def, kind = False, 'data' + out.append((i, halves, is_def, kind)) + # forms whose vcc the disassembler might leave implicit (VOPC / VOP2 carry / cndmask e32 without a vcc + # operand): the lane mask + if not any(j is not None for j, _, _, _ in out) and name.endswith('_e32'): + if base.startswith('v_cmp') and not base.startswith('v_cmpx'): + out.append((None, (0, 1), True, 'mask')) + elif base == 'v_cndmask_b32' or (carry and '_ci' in base) or re.fullmatch(r'v_(add|sub|subrev)c_co_u32', base): + out.append((None, (0, 1), False, 'mask')) + if carry: + out.append((None, (0, 1), True, 'mask')) + return out + + def lower_vcc_data(self): + """Rename vcc to the SGPR pair s[106:107] where it does not hold a lane mask. Webs of definitions and uses of + each half (reaching definitions over the branch graph) are classified by their instructions: a web with a + lane-mask use or definition keeps `vcc`; any other web (32-bit data, or only 64-bit moves) is renamed, which + is exact (an SGPR pair takes every scalar form, including a lane mask moved through it). A web that is + both a lane mask and 32-bit data is refused, unless its only 32-bit uses are scalar reads whose results + nothing reads (dead_use; the web then keeps `vcc`, as before the rename). Returns the number of renamed + operands.""" + if not VCC_DATA: + return 0 + roles = {i: self.vcc_roles(x[2], x[3]) for i, x in enumerate(self.ins)} + roles = {i: r for i, r in roles.items() if r} + if not any(k == 'data' or (j is not None and k == 'any') for r in roles.values() for (j, h, d, k) in r): + return 0 + parent = {} + + def find(a): + parent.setdefault(a, a) + while parent[a] != a: + parent[a] = parent[parent[a]] + a = parent[a] + return a + + def union(a, b): + parent[find(a)] = find(b) + kind_of = {} + for i, r in roles.items(): + for n, (j, halves, is_def, kind) in enumerate(r): + nodes = [(i, n, h) for h in halves] + for a in nodes: + kind_of[a] = kind + find(a) + for a in nodes[1:]: + union(nodes[0], a) + offs = [x[0] for x in self.ins] + at = {x[0]: i for i, x in enumerate(self.ins)} + # Reaching definitions, with each path marked "exec is zero" after the taken edge of s_cbranch_execz (the + # fall-through of execnz) until an exec write that can turn lanes on. A vector instruction does nothing in a + # lane whose exec bit is off (in the one-lane model: its writes are guarded), so a definition that reaches a + # vector data use only along such paths does not join that use's value. + entry = (('entry', 0), ('entry', 1)) + for a in entry: + kind_of[a] = 'any' + find(a) + + def zero_edges(i): + """(successor, path becomes exec-zero) pairs.""" + name, asm = self.ins[i][2], self.ins[i][3] + out = [] + t = int(parse(asm)[1][0].split('_')[1], 16) if (name.startswith('s_cbranch') or name == 's_branch') else None + if name not in ('s_endpgm', 's_branch') and i + 1 < len(self.ins): + out.append((i + 1, name == 's_cbranch_execnz')) + if t is not None and t in at: + out.append((at[t], name == 's_cbranch_execz')) + return out + + def narrows(name, asm): + ops = parse(asm)[1] + if name.startswith('v_cmpx') or name == 's_and_saveexec_b64': + return True + return bool(re.match(r's_(and|andn2)_b64$', name) and ops and ops[0] == 'exec' and 'exec' in ops[1:2] + or re.match(r's_and_b64$', name) and ops and ops[0] == 'exec' and 'exec' in ops[1:]) + # facts: (frozenset of path flags reaching, defs of half 0, defs of half 1); a def is (node, exec-zero flag) + reach = {0: (frozenset([False]), frozenset([(entry[0], False)]), frozenset([(entry[1], False)]))} if self.ins else {} + work = [0] if self.ins else [] + while work: + i = work.pop() + flags, d0, d1 = reach[i] + facts = [d0, d1] + name, asm = self.ins[i][2], self.ins[i][3] + for n, (j, halves, is_def, kind) in enumerate(roles.get(i, ())): + if not is_def: + vector_data = kind == 'data' and name.startswith('v_') + for h in halves: + for d, z in facts[h]: + if not (z and vector_data): + union((i, n, h), d) + for n, (j, halves, is_def, kind) in enumerate(roles.get(i, ())): + if is_def: + for h in halves: + facts[h] = frozenset(((i, n, h), z) for z in flags) + if self.exec_written(name, parse(asm)[1]) and not narrows(name, asm): + flags = frozenset([False]) + facts = [frozenset((d, False) for d, z in f) for f in facts] + for s, zero in zero_edges(i): + if zero: + out = (frozenset([True]),) + tuple(frozenset((d, True) for d, z in f) for f in facts) + else: + out = (flags, facts[0], facts[1]) + old = reach.get(s) + new = out if old is None else tuple(a | b for a, b in zip(old, out)) + if new != old: + reach[s] = new + work.append(s) + webs = {} + for a, k in kind_of.items(): + webs.setdefault(find(a), set()).add((k, a)) + all_reads = set() + for x in self.ins: + all_reads |= set(reads_writes(x[2], x[3])[0]) + + def dead_use(i): + """A scalar instruction reading vcc as data whose results nothing reads: its destination SGPRs are read + by no instruction of the program, it writes no vcc / exec / m0, and its SCC (assumed written) is not + read on any path before an s_cmp / s_bitcmp sets SCC again.""" + name, asm = self.ins[i][2], self.ins[i][3] + if not name.startswith('s_') or name.startswith(('s_cbranch', 's_branch', 's_setpc', 's_swappc')): + return False + rd, wr, wv, rv = reads_writes(name, asm) + ops = parse(asm)[1] + if wv or (ops and ops[0].startswith(('exec', 'm0'))) or set(wr) & all_reads: + return False + seen, work = set(), [s for s, _ in zero_edges(i)] + while work: + k = work.pop() + if k in seen: + continue + seen.add(k) + kn, ka = self.ins[k][2], self.ins[k][3] + if G.reads_scc(kn, ka): + return False + if kn.startswith(('s_cmp', 's_bitcmp')): + continue + work += [s for s, _ in zero_edges(k)] + return True + rename = set() + for root, members in webs.items(): + kinds = {k for k, _ in members} + if 'mask' in kinds and 'data' in kinds: + data = [a for k, a in members if k == 'data' and a[0] != 'entry'] + if all(not roles[a[0]][a[1]][2] and dead_use(a[0]) for a in data): + continue # only dead 32-bit reads of a lane mask: nothing observes the cut value + m = next(offs[a[0]] for k, a in members if k == 'mask' and a[0] != 'entry') + d = next(offs[a[0]] for k, a in members if k == 'data' and a[0] != 'entry') + raise Unsupported('vcc used as a lane mask (%#x) and as 32-bit data (%#x) in one value' % (m, d)) + if 'mask' not in kinds: + rename |= {(a[0], a[1]) for k, a in members if a[0] != 'entry'} + count = 0 + for i, n in sorted(rename): + j = roles[i][n][0] + if j is None: + continue + off, size, name, asm = self.ins[i] + _, ops, mods = parse(asm) + tok = ops[j] + t = tok.lstrip('-|').rstrip('|') + if t not in ('vcc', 'vcc_lo', 'vcc_hi'): + continue # already named s106 / s107 by number + ops[j] = tok.replace(t, {'vcc': 's[106:107]', 'vcc_lo': 's106', 'vcc_hi': 's107'}[t]) + text = '%s %s' % (asm.split(' ', 1)[0], ', '.join(ops)) + if mods: + text += ' ' + ' '.join(mods) + self.ins[i] = (off, size, name, text) + count += 1 + return count + + def lower_spills(self): + """Rewrite the spill idiom in self.ins (before the translation and every analysis reads it) into scalar + moves to pseudo-SGPR slots; refuse whatever is not that idiom. Returns (spill VGPR numbers, slot numbers). + + * v_writelane_b32 vN, S, k -> s_mov_b32 slot(N, k), S; v_readlane_b32 sD, vN, k -> s_mov_b32 sD, slot(N, k). + * The two halves of a 64-bit pair (sX/sX+1, vcc_lo/hi, exec_lo/hi) spilled to lanes k, k+1, or reloaded from + them, in one basic block with nothing in between reading or writing the registers or slots involved, + become one s_mov_b64 at the later instruction (the earlier is a no-op): the value moved is the same, and + the lane-mask and exec-copy rules see the pair. A half of vcc or exec on its own is refused (the one-lane + model keeps only the lane's bit of a mask; vcc as 32-bit data is not modelled). + * Refused: a lane select that is not a constant 0..63, a spill VGPR named by any other instruction (also + checked against the translation's VGPR use afterwards), a slot read on some path before any write.""" + idx = [i for i, x in enumerate(self.ins) if x[2] in ('v_writelane_b32', 'v_readlane_b32')] + if not idx or not SPILLS: + return set(), set() + info = {} + vgprs = set() + for i in idx: + off, n, name, asm = self.ins[i] + _, ops, mods = parse(asm) + if mods or len(ops) != 3: + raise Unsupported('%s form %s at %#x' % (name, asm, off)) + vtok = ops[0] if name == 'v_writelane_b32' else ops[1] + v = reg_range(vtok) + if not v or v[0] != 'v' or v[1] != v[2]: + raise Unsupported('%s on %s at %#x' % (name, vtok, off)) + if not re.fullmatch(r'0x[0-9a-f]+|\d+', ops[2]) or int(ops[2], 0) > 63: + raise Unsupported('%s lane select %s is not a constant lane at %#x' % (name, ops[2], off)) + info[i] = (name, v[1], int(ops[2], 0), ops[1] if name == 'v_writelane_b32' else ops[0]) + vgprs.add(v[1]) + order = sorted(vgprs) + slot = {(v, k): SLOT_BASE + 64 * j + k for j, v in enumerate(order) for k in range(64)} + # any other instruction naming a spill VGPR (single or in a range) uses it as per-lane data + for i, (off, n, name, asm) in enumerate(self.ins): + if i in info: + continue + for m in re.finditer(r'\bv(\d+)\b|\bv\[(\d+):(\d+)\]', asm): + lo, hi = (int(m.group(1)),) * 2 if m.group(1) else (int(m.group(2)), int(m.group(3))) + hit = [v for v in order if lo <= v <= hi] + if hit: + raise Unsupported('v%d holds spilled scalars (v_writelane) and is also used by %s at %#x' + % (hit[0], name, off)) + targets = self.branch_targets() + + def regs_of(name, asm): + """(scalar registers read, written) with vcc = -1 and exec = -2.""" + r, w, wv, rv = reads_writes(name, asm) + r, w = set(r), set(self.pair_writes(name, asm)) + ops = parse(asm)[1] + if wv: + w.add(-1) + if rv: + r.add(-1) + if self.exec_written(name, ops): + w.add(-2) + if not name.startswith('s_') or any(t.startswith('exec') for t in ops[1:]) or 'saveexec' in name: + r.add(-2) # every vector instruction reads exec + return r, w + + def tok_regs(tok): + if tok.startswith('vcc'): + return {-1} + if tok.startswith('exec'): + return {-2} + r = reg_range(tok) + return set(range(r[1], r[2] + 1)) if r and r[0] == 's' else set() + + def partner(i): + """Index of the other half's instruction that may be fused with i, or None.""" + name, v, k, tok = info[i] + half = self._half(tok) + if not half: + return None + pair, h = half + want_k = k + 1 if h == 0 else k - 1 + regs = tok_regs(tok) | tok_regs(pair) + slots = {slot[(v, k)], slot.get((v, want_k), -9)} + for j in range(i + 1, len(self.ins)): + off, n, nm, asm = self.ins[j] + if off in targets: + return None + if j in info and info[j][0] == name and info[j][1] == v and info[j][2] == want_k: + other = self._half(info[j][3]) + return j if other == (pair, 1 - h) else None + if j in info: + jn, jv, jk, jt = info[j] + if slot[(jv, jk)] in slots: + return None + r, w = (tok_regs(jt), set()) if jn == 'v_writelane_b32' else (set(), tok_regs(jt)) + else: + r, w = regs_of(nm, asm) + if w & regs or (name == 'v_readlane_b32' and r & regs): + return None + if nm.startswith('s_cbranch') or nm in ('s_branch', 's_endpgm', 's_setpc_b64'): + return None + return None + + new = list(self.ins) + done = set() + for i in idx: + if i in done: + continue + name, v, k, tok = info[i] + off, n = self.ins[i][0], self.ins[i][1] + j = partner(i) + if j is not None: + pair, h = self._half(tok) + lo_k = k if h == 0 else k - 1 + spair = 's[%d:%d]' % (slot[(v, lo_k)], slot[(v, lo_k)] + 1) + asm = 's_mov_b64 %s, %s' % ((spair, pair) if name == 'v_writelane_b32' else (pair, spair)) + new[i] = (off, n, 's_nop', 's_nop 0') + new[j] = (self.ins[j][0], self.ins[j][1], 's_mov_b64', asm) + done |= {i, j} + continue + s = 's%d' % slot[(v, k)] + if name == 'v_writelane_b32': + if tok.startswith(('vcc', 'exec')) or (reg_range(tok) and reg_range(tok)[0] != 's'): + raise Unsupported('v_writelane_b32 of %s alone at %#x (half of a 64-bit pair)' % (tok, off)) + new[i] = (off, n, 's_mov_b32', 's_mov_b32 %s, %s' % (s, tok)) + else: + r = reg_range(tok) + if not r or r[0] != 's': + raise Unsupported('v_readlane_b32 into %s alone at %#x (half of a 64-bit pair)' % (tok, off)) + new[i] = (off, n, 's_mov_b32', 's_mov_b32 %s, %s' % (tok, s)) + done.add(i) + self.ins = new + slots = {s for (v, k), s in slot.items()} + entry = self.liveness().get(self.ins[0][0], frozenset()) if self.ins else frozenset() + unset = sorted(r for r in entry if isinstance(r, int) and r >= SLOT_BASE) + if unset: + j, k = divmod(unset[0] - SLOT_BASE, 64) + raise Unsupported('v_readlane_b32 of v%d lane %d, which no v_writelane_b32 writes on some path to it' + % (order[j], k)) + return set(vgprs), slots + # ---- loops: the state at a loop head is the join of every edge into it ----------------------------------- + # The base scan is linear and keeps, at a loop head, the state of the instruction above it: the back edges are + # never seen (a constant before the loop was folded into the loop body: `s0 = 0; loop: s0 += 1` became + # `s0 = 0u + 1u` on every iteration), and after an s_branch that state belongs to no path at all. Here the + # stage is translated again until the state used at each loop head equals the join of its entry edges and + # its back edges from the pass before (MeshPipeline retries on LoopRetry). A head no entry reaches in a pass + # (entered through a forward branch into the body) is `bottom`: what is translated from it is not used and + # its edges are left out of joins, and the next pass seeds it with the back edges. + def loop_prepare(self): + heads = self.loop_heads() + self._loop_edges = {} # head -> offsets of the branches to it + targets = set() + for off, _, name, asm in self.ins: + if name.startswith('s_cbranch') or name == 's_branch': + t = int(parse(asm)[1][0].split('_')[1], 16) + targets.add(t) + if t in heads: + self._loop_edges.setdefault(t, []).append(off) + # Unreachable alignment NOPs after a jump do not introduce another + # entry edge into the following loop head. + self._loop_fallthrough = set() + falls_through = False + for off, _, name, _ in self.ins: + if falls_through and off in heads: + self._loop_fallthrough.add(off) + reachable = falls_through or off in targets or off == self.ins[0][0] + falls_through = reachable and name not in ('s_branch', 's_endpgm') + self._loop_branch = {o for v in self._loop_edges.values() for o in v} + self._loop_after = {} # branch offset -> loop state after it (this pass) + self._loop_entry = {} # head -> loop states of its entries (forward edges, fall-through), this pass + self._loop_used = {} # head -> the joined state used at the head, this pass + self._loop_bottom = False + + def loop_state(self): + return (self.snapshot(), frozenset(self.tainted), dict(self.au_scalars)) + + def loop_join(self, states): + """Sets the stage to the join of loop states (snapshot, tainted, au_scalars).""" + self.merge([s[0] for s in states]) + self.tainted = set().union(*(s[1] for s in states)) + # values known uniform only over the active lanes are not followed around a loop: lane-dependent + self.au = {} + self.lineage_reset() + stale = {r for s in states for r in s[2]} + current = states[0][2] + self.au_scalars = {r: (current[r] if all(s[2].get(r) == current.get(r) for s in states) else -1) + for r in stale} + self.lane_s = set(range(128)) # the base marks every SGPR suspect at a loop head; keep it so + + @staticmethod + def loop_key(state): + snap, tainted, au_scalars = state + return (snap[0], snap[1], snap[2], tainted, tuple(sorted(au_scalars.items()))) + + def loop_one(self, name, asm): + head = self.pc if self.pc in self._loop_edges else None + if head is not None: + entries = [self._loop_after[o] for o in self._loop_edges[head] if o < head and o in self._loop_after] + if head in self._loop_fallthrough and BOTTOM not in self.sym: + entries.append(self.loop_state()) + entries = [s for s in entries if BOTTOM not in s[0][0]] + self._loop_entry[head] = entries + seeds = [s for s in self.pipe.loop_seed.get(head, []) if BOTTOM not in s[0][0]] + if entries or seeds: + self.loop_join(entries + seeds) + else: + self.sym[BOTTOM] = True + self._loop_bottom = True + self._loop_used[head] = self.loop_state() + if BOTTOM in self.sym: + # not reached by any path in this pass: translated only to carry on the scan + try: + term = MeshStage.one(self, name, asm) + except Unsupported: + term = None + else: + term = MeshStage.one(self, name, asm) + if self.pc in self._loop_branch: + self._loop_after[self.pc] = self.loop_state() + return term + + def loop_settled(self): + """Raises LoopRetry with the back edges of this pass when some loop head's state was not the join.""" + backs = {h: [self._loop_after[o] for o in srcs if o >= h and o in self._loop_after] + for h, srcs in self._loop_edges.items()} + saved = self.loop_state() + settled = not self._loop_bottom + for head, used in self._loop_used.items(): + states = [s for s in self._loop_entry.get(head, []) + backs[head] if BOTTOM not in s[0][0]] + if not states: + settled = False + continue + self.loop_join(states) + if self.loop_key(self.loop_state()) != self.loop_key(used): + settled = False + self.loop_join([saved]) + if not settled: + raise LoopRetry(backs) + + def next_offset(self): + for off, n, _, _ in self.ins: + if off == self.pc: + return off + n + return None + + def loop_heads(self): + if getattr(self, '_heads', None) is None: + self._heads = set() + for off, _, name, asm in self.ins: + if name.startswith('s_cbranch') or name == 's_branch': + t = int(parse(asm)[1][0].split('_')[1], 16) + if t <= off: + self._heads.add(t) + # a waterfall is translated as one pass per lane (no loop): its head takes no loop join + self._heads -= {h for h, info in self.waterfalls().items() if not info['refuse']} + return self._heads + + # ---- waterfall loops: one pass per lane with the lane's own value ---------------------------------------- + # The compiler's idiom for a resource index that differs between lanes (LLVM AMDGPU SIInstrInfo + # loadMBUFScalarOperandsFromVGPR / emitLoadScalarOpsFromVGPRLoop, "waterfall loop"): + # s_mov_b64 s[a], exec; s_mov_b64 s[m], exec (copies of exec before the loop) + # H: v_readfirstlane_b32 sX, vY (the first remaining lane's value) + # v_cmpx_eq_u32/i32 sX, vY (exec = the remaining lanes holding that value) + # ... body using sX as a uniform value ... + # s_andn2_wrexec_b64 s[m], s[m] (m &= ~exec; exec = m; SCC = m != 0) + # s_cbranch_scc1 H (again while lanes remain) + # s_mov_b64 exec, s[a] (restore) + # Each lane that is active at H runs the body exactly once, with exec holding it (and the other lanes of its + # value), and sX equal to its own vY. In the one-lane model that is: sX = vY, the body under the lane's entry + # exec bit, then on: s[m] = 0, SCC = 0, exec back to s[a] (RDNA 2 ISA S_ANDN2_WREXEC_B64, V_CMPX_EQ_U32, + # V_READFIRSTLANE_B32). The hardware leaves sX, the body's scalar results and vcc with the LAST pass's values; + # here every lane holds its own, so such a register must not be read after the loop (refused). + def waterfalls(self): + """head -> {role offset: role} plus 'refuse' (a reason) for each loop that has the waterfall's shape.""" + if getattr(self, '_wf', None) is not None: + return self._wf + self._wf = {} + if not WATERFALL: + return self._wf + ins = self.ins + index = {x[0]: i for i, x in enumerate(ins)} + sources = {} + for off, _, name, asm in ins: + if name.startswith('s_cbranch') or name == 's_branch': + sources.setdefault(int(parse(asm)[1][0].split('_')[1], 16), []).append(off) + skip = ('s_nop', 's_waitcnt', 's_waitcnt_vmcnt', 's_waitcnt_lgkmcnt', 's_waitcnt_depctr') + for i, (off, _, name, asm) in enumerate(ins): + if name != 's_cbranch_scc1': + continue + head = int(parse(asm)[1][0].split('_')[1], 16) + if head > off or head not in index or sources.get(head) != [off]: + continue + j = index[head] + k = j + while k < i and ins[k][2] in skip: + k += 1 + if k + 2 >= i - 1 or ins[k][2] != 'v_readfirstlane_b32': + continue + rops = parse(ins[k][3])[1] + cname, cops = ins[k + 1][2], parse(ins[k + 1][3])[1] + wname, wops = ins[i - 1][2], parse(ins[i - 1][3])[1] + sx, vy = reg_range(rops[0]), reg_range(rops[1]) + if not (sx and sx[0] == 's' and vy and vy[0] == 'v' and sx[2] == sx[1] and vy[2] == vy[1]): + continue + if not (re.fullmatch(r'v_cmpx_eq_[ui]32_e32', cname) and sorted(cops) == sorted(rops)): + continue + mr = reg_range(wops[0]) if wops else None + if not (wname == 's_andn2_wrexec_b64' and len(wops) == 2 and wops[0] == wops[1] and mr and mr[0] == 's'): + continue + m = mr[1] + info = {'head': head, 'rfl': ins[k][0], 'cmpx': ins[k + 1][0], 'wrexec': ins[i - 1][0], 'branch': off, + 's': sx[1], 'v': vy[1], 'm': m} + self._wf[head] = info + info['refuse'] = self.waterfall_check(info, ins, index, sources, i, j, k) + return self._wf + + def waterfall_check(self, info, ins, index, sources, i, j, k): + """None when the matched loop is translatable as one pass per lane, else the reason.""" + m, vy = info['m'], info['v'] + body = ins[k + 2:i - 1] + for off, _, name, asm in body: + if WATERFALL_BODY_REFUSED.match(name) or self.exec_written(name, parse(asm)[1]): + return '%s at %#x' % (name, off) + if any(t in ('exec', 'exec_lo', 'exec_hi') for t in parse(asm)[1]): + return 'exec read at %#x (the pass\'s lanes, not one lane)' % off + if off in sources: + return 'branch target %#x inside it' % off + _, w, _, _ = reads_writes(name, asm) + if w & {m, m + 1}: + return 'the remaining-lanes mask s%d written at %#x' % (m, off) + ops = parse(asm)[1] + if name.startswith(('v_', 'buffer_', 'image_', 'global_', 'flat_', 'scratch_')) and ops: + d = reg_range(ops[0]) + if d and d[0] == 'v' and d[1] <= vy <= d[2]: + return 'v%d (the index) written at %#x' % (vy, off) + # before the head: s[m] = exec, and a copy s[a] = exec that the instruction after the loop restores, with + # no exec write and no other way in between + nxt = i + 1 + while nxt < len(ins) and ins[nxt][2] in ('s_nop',): + nxt += 1 + if nxt >= len(ins): + return 'no exec restore after it' + rname, rops = ins[nxt][2], parse(ins[nxt][3])[1] + ar = reg_range(rops[1]) if rname == 's_mov_b64' and len(rops) == 2 and rops[0] == 'exec' else None + if not (ar and ar[0] == 's'): + return 'no s_mov_b64 exec restore after it (%s)' % ins[nxt][3] + a = ar[1] + found = set() + p = j - 1 + while p >= 0 and found != {'m', 'a'}: + off, _, name, asm = ins[p] + ops = parse(asm)[1] + if ins[p + 1][0] in sources and ins[p + 1][0] != info['head']: + return 'branch target %#x between the exec copies and the head' % ins[p + 1][0] + if name == 's_mov_b64' and len(ops) == 2 and ops[1] == 'exec': + r = reg_range(ops[0]) + if r and r[1] == m: + found.add('m') + elif r and r[1] == a: + found.add('a') + p -= 1 + continue + if self.exec_written(name, ops) or name.startswith(('s_cbranch', 's_branch', 's_endpgm')): + return 'exec written or a branch at %#x before the head' % off + _, w, _, _ = reads_writes(name, asm) + if w & {m, m + 1, a, a + 1}: + return 'an exec copy overwritten at %#x' % off + p -= 1 + if found != {'m', 'a'}: + return 'no exec copies before the head' + for off, _, name, asm in ins[j:nxt]: + _, w, _, _ = reads_writes(name, asm) + if w & {a, a + 1}: + return 'the restored copy s%d written at %#x' % (a, off) + # what the body leaves in scalar registers (each lane's own here, the last pass's on the hardware) + written = set() + for off, _, name, asm in ins[k:i - 1]: + _, w, wv, _ = reads_writes(name, asm) + written |= w | ({-1} if wv else set()) + live = self.liveness()[ins[nxt][0]] - {m, m + 1} + hit = written & live + if hit: + return '%s written in it is live after it' % ('vcc' if min(hit) == -1 else 's%d' % min(hit)) + info['restore'] = ins[nxt][0] + return None + + def waterfall_role(self): + """(info, role) of the instruction at self.pc in a waterfall loop, else None.""" + if getattr(self, '_wf_roles', None) is None: + self._wf_roles = {} + for info in self.waterfalls().values(): + for role in ('rfl', 'cmpx', 'wrexec', 'branch'): + self._wf_roles[info[role]] = (info, role) + return self._wf_roles.get(self.pc) + + def waterfall_step(self, info, role, ops): + """The translation of a waterfall instruction; NotImplemented: translate it as any other instruction (a + refused waterfall stays a loop, as before, unless its index is lane-dependent: then the reason is given).""" + if info['refuse']: + if role == 'rfl' and self.lane_dependent('v%d' % info['v']): + raise Unsupported('waterfall loop %#x-%#x: %s' % (info['head'], info['branch'], info['refuse'])) + return NotImplemented + if role == 'rfl': + # this lane's pass: the value is its own (threads with exec 0 compute it too; their body is guarded) + self.set_s(info['s'], self.u(ops[1])) + self.au_scalars.pop(info['s'], None) + return None + if role == 'cmpx': + return None # sX == vY in this lane: exec keeps its bit + if role == 'wrexec': + # the lane's pass is over: s[m] holds no lane any more (all passes done), SCC = 0 + self.set_s(info['m'], '0u', sym=('const', 0)) + self.set_s(info['m'] + 1, '0u', sym=('const', 0)) + self.emit('scc = false;') + self.scc_from.pop('scc', None) + return None + return None # the back edge: no further pass for this lane + + def perlane_loop(self, head, off): + """None when the loop head..off (an scc1 back edge on a lane-mask SCC) is translatable per lane, else the + reason.""" + cache = self.__dict__.setdefault('_perlane', {}) + if off in cache: + return cache[off] + ins = self.ins + index = {x[0]: i for i, x in enumerate(ins)} + i, j = index[off], index.get(head) + why = None + prev = parse(ins[i - 1][3])[1] if i else [] + pname = ins[i - 1][2] if i else '' + if ins[i][2] != 's_cbranch_scc1': + why = '%s back edge' % ins[i][2] + elif not ((pname == 's_andn2_b64' and len(prev) == 3 and prev[0] == prev[1] and prev[2] == 'exec') or + (pname == 's_andn2_wrexec_b64' and len(prev) == 2 and prev[0] == prev[1])): + why = 'SCC not from the remaining-lanes mask (%s)' % ins[i - 1][3] + mr = reg_range(prev[0]) if prev else None + if why is None and not (mr and mr[0] == 's'): + why = 'mask %s' % (prev[0] if prev else '?') + if why is None: + m = mr[1] + written = set() + for o, _, name, asm in ins[j:i + 1]: + ops = parse(asm)[1] + if PERLANE_BODY_REFUSED.match(name): + why = '%s at %#x' % (name, o) + break + # the first active lane differs between a thread's iteration and the wave's: only a translated + # waterfall (each lane's own value) may read one + if name == 'v_readfirstlane_b32' and not any( + info['rfl'] == o and not info['refuse'] for info in self.waterfalls().values()): + why = 'v_readfirstlane_b32 at %#x' % o + break + if name.startswith('s_cbranch') or name == 's_branch': + t = int(ops[0].split('_')[1], 16) + if not head <= t <= off + 4: + why = 'a branch out of the loop at %#x' % o + break + _, w, wv, _ = reads_writes(name, asm) + written |= w | ({-1} if wv else set()) + nxt = i + 1 + while why is None and nxt < len(ins) and ins[nxt][2] == 's_nop': + nxt += 1 + if why is None: + rops = parse(ins[nxt][3])[1] if nxt < len(ins) else [] + ar = reg_range(rops[1]) if (nxt < len(ins) and ins[nxt][2] == 's_mov_b64' and len(rops) == 2 + and rops[0] == 'exec') else None + if not (ar and ar[0] == 's'): + why = 'no s_mov_b64 exec restore after it' + elif written & {ar[1], ar[1] + 1}: + why = 'the restored exec copy s%d written in it' % ar[1] + if why is None: + hit = written & (self.liveness()[ins[nxt][0]] - {m, m + 1}) + if hit: + why = '%s written in it is live after it' % ('vcc' if min(hit) == -1 else 's%d' % min(hit)) + cache[off] = why + return why + + def branch_targets(self): + if getattr(self, '_targets', None) is None: + self._targets = {int(parse(asm)[1][0].split('_')[1], 16) for _, _, name, asm in self.ins + if name.startswith('s_cbranch') or name == 's_branch'} + return self._targets + + def body(self): + """With barriers: the program runs as barriers + 1 phases, written out one after the other with a group + barrier between them in straight-line code (no barrier inside a loop). barrier_count() put every block in + exactly one phase; within a phase a thread runs its blocks until it reaches a barrier (pc gets + 0x10000 | the block after it) or the end (0x20000). Each console barrier is thus the phase boundary every + wave of the group reaches.""" + if not any(b[2] and b[2][0] == 'barrier' for b in self.blocks): + return super().body() + index = {b[0]: i for i, b in enumerate(self.blocks)} + + def goto(off): + if off not in index: + raise Unsupported('branch into the middle of a block (+0x%x)' % off) + return index[off] + out = [' uint pc = 0;'] + for phase in range(self.barriers + 1): + members = [i for i in range(len(self.blocks)) if self.phase_of.get(i) == phase] + loop = any(t and t[0] in ('jump', 'branch') and goto(t[-1]) <= i + for i in members for t in [self.blocks[i][2]]) + out.append(' // phase %d' % phase) + ind = ' ' + if loop: + out.append(' [loop] for (uint guard = 0; guard < 65536 && pc < 0x10000u; ++guard) {') + ind = ' ' + for k, i in enumerate(members): + off, lines, term = self.blocks[i] + if loop and term and term[0] in ('jump', 'branch') and self.phase_of.get(goto(term[-1])) != phase: + # (a group-uniform skip into a later phase: the loop would spin on that pc until its guard) + raise Unsupported('jump from a looping phase into another phase at %#x' % int(off)) + out.append('%s%sif (pc == %d) {' % (ind, 'else ' if loop and k else '', i)) + out += [ind + ' ' + line for line in lines] + last = i + 1 >= len(self.blocks) + nxt = '0x20000u' if last else '%d' % (i + 1) + if not term: + out.append('%s pc = %s;' % (ind, nxt)) + elif term[0] == 'end': + out.append('%s pc = 0x20000u;' % ind) + elif term[0] == 'barrier': + out.append('%s pc = %s;' % (ind, '0x20000u' if last else '0x10000u | %d' % (i + 1))) + elif term[0] == 'jump': + out.append('%s pc = %d;' % (ind, goto(term[1]))) + else: + out.append('%s pc = (%s) ? %d : %s;' % (ind, term[1], goto(term[2]), nxt)) + out.append('%s}' % ind) + if loop: + out.append(' }') + if phase < self.barriers: + out += [' GroupMemoryBarrierWithGroupSync();', + ' if (pc < 0x20000u) pc &= 0xffffu;'] + return out + + def barrier_count(self): + """Every path from the entry to s_endpgm must cross the same number of barriers (the hardware needs every + wave to arrive at each barrier). Returns that number; the body runs as that many + 1 phases.""" + blocks = self.blocks + index = {b[0]: i for i, b in enumerate(blocks)} + memo = {} + cmemo = {} + + def console(i, depth=0): + """Sorted counts of console barriers (not lane-mask SCC publishes) from block i to the end.""" + if i in cmemo: + return cmemo[i] + if depth > 10000: + raise Unsupported('block graph too deep') + cmemo[i] = () + off, lines, term = blocks[i] + # only the program's s_barrier: the translation's own barriers (lane-mask SCC publish, readfirstlane + # broadcast, group-branch publish) are reached or skipped by the whole group together + here = 1 if term and term[0] == 'barrier' and term[1:2] == ('console',) and SKIP_ADDED else 0 + if term and term[0] == 'barrier' and not SKIP_ADDED and term[1:2] != ('lane-scc',): + here = 1 + nxt = [i + 1] if (term is None or term[0] in ('barrier', 'branch')) and i + 1 < len(blocks) else [] + if term and term[0] in ('jump', 'branch'): + if term[0] == 'jump': + nxt = [] + if term[-1] > off: + nxt.append(index[term[-1]]) + got = sorted({here + c for k in nxt for c in console(k, depth + 1)}) if nxt else [here] + cmemo[i] = tuple(got) + return cmemo[i] + + def counts(i, depth=0): + if i in memo: + return memo[i] + if depth > 10000: + raise Unsupported('block graph too deep') + off, lines, term = blocks[i] + here = 1 if term and term[0] == 'barrier' else 0 + if off in self.uniform_skips: + # group-uniform skip of an execz range (group_branch): every thread of the group goes the same + # way, so the skip may jump over barriers inside the range (body() runs the target in its later + # phase; the threads still pass every phase barrier in between, doing nothing) + through, skip = counts(i + 1, depth + 1), counts(index[term[-1]], depth + 1) + if len(through) != 1 or len(skip) != 1 or min(skip) > min(through): + raise Unsupported('group-uniform execz range at %#x: barrier counts %s / %s' + % (int(off), sorted(through), sorted(skip))) + # only barriers this translation added (lane-mask SCC publishes) may be skipped: a console + # s_barrier inside the range would be skipped by a wave without active lanes on the hardware + if console(i + 1) != console(index[term[-1]]): + raise Unsupported('s_barrier inside a group-uniform execz range at %#x (console barriers ahead %s ' + 'through, %s skipping)' % (int(off), list(console(i + 1)), + list(console(index[term[-1]])))) + memo[i] = through + return through + nxt = [] + if term is None or term[0] in ('barrier', 'branch'): + if i + 1 < len(blocks): + nxt.append(i + 1) + if term and term[0] in ('jump', 'branch'): + if term[-1] <= off: + if any(blocks[k][2] and blocks[k][2][0] == 'barrier' for k in range(index[term[-1]], i + 1)): + raise Unsupported('barrier inside a loop') + nxt = [k for k in nxt if k != index[term[-1]]] # loop back edge: counted once + else: + nxt.append(index[term[-1]]) + result = set() + for k in nxt: + result |= {here + c for c in counts(k, depth + 1)} + if not nxt: + result = {here} + memo[i] = result + return result + found = counts(0) + if len(found) != 1: + raise Unsupported('paths cross different numbers of barriers: %s' % sorted(found)) + total = min(found) + # Every reachable block then has one count of barriers still ahead (two would give two totals), so it runs + # in exactly one phase: total - that count. + self.phase_of = {} + for i, c in memo.items(): + if len(c) != 1: + raise Unsupported('block %#x reaches the end across different numbers of barriers' % blocks[i][0]) + self.phase_of[i] = total - min(c) + return total + + # ---- entry --------------------------------------------------------------------------------- + def setup_entry(self): + root = self.pipe.root + reg = self.pipe.user_sgpr + for index, p in enumerate(root['params']): + if p['type'] == 0: + self.sym[reg] = ('ptr', ('table', index)) + reg += 1 + elif p['type'] == 1: + for i in range(p['count']): + self.sym[reg] = ('ud', self.pipe.ud(('rootconst', index, i))) + reg += 1 + else: + self.sym[reg] = ('ptr', ('root', index)) + self.sym[reg + 1] = ('ptrhi', ('root', index)) + reg += 2 + if root['flags'] & 0x400: + self.sym[reg] = ('ptr', ('resheap',)) + reg += 1 + if root['flags'] & 0x800: + self.sym[reg] = ('ptr', ('smpheap',)) + reg += 1 + self.user_end = reg + # s3: merged_wave_info (bits 27:24 = wave index in the group, Mesa radv_shader_args.c / ac_unpack_param). + self.sym[3] = ('waveinfo',) + + # ---- taint (lane dependence) --------------------------------------------------------------- + # Three levels per register: uniform (not in `tainted`: the same in every lane of the wave), active-uniform + # (in `tainted` and au[reg] == epoch: the same in every lane active since the last widening of exec; e.g. a + # value computed from uniform values under a partial exec, or `exec & uniform`), and lane-dependent. + # `epoch` counts exec writes that can turn lanes back on (restores); narrowing writes (v_cmpx, `exec & x`, any + # write while every lane was active) keep active-uniform values valid. + def emit(self, text): + self.lines.append(text) + for stmt in text.split(';'): + m = SIMPLE.match(stmt) + if not m: + continue + target, expr = m.group(1), m.group(2) + deps = set(TOKEN.findall(expr)) + if stmt.strip().startswith('if (exec & 1)'): + deps.add('exec') + origins = frozenset().union(*(self.scc_from.get(d, ()) for d in deps)) + if stmt.strip().startswith('if '): + origins |= self.scc_from.get(target, frozenset()) # a guarded write keeps the old value elsewhere + if origins: + self.scc_from[target] = origins + else: + self.scc_from.pop(target, None) + if target == 'exec': + narrow = expr.startswith('(exec & ') or getattr(self, '_known_at_start', True) + if not narrow: + self.epoch += 1 + self.xs = self.lineage_exec(expr) + self._xs_exec_seen = True + elif self.LINEAGE_COPY.match(expr.strip()) and not stmt.strip().startswith('if '): + self.xs_copy[target] = self.xs + else: + self.xs_copy.pop(target, None) + # (a scalar computed inside a per-lane region from uniform values is what the wave computes there: the + # lanes that skip the region never see it, and check_skipped_scalars refuses it being live after) + if not deps & self.tainted: + self.tainted.discard(target) + self.au.pop(target, None) + self.au_xs.pop(target, None) + continue + # (the sources as they were before this statement: `s12 = scc ? s12 : s24` reads the old, untainted s12) + lane = {d for d in deps & self.tainted + if d != 'exec' and self.au.get(d) != self.epoch and not self.lineage_ok(d)} + self.tainted.add(target) + if lane or target == 'exec': + self.au.pop(target, None) + self.au_xs.pop(target, None) + else: + self.au[target] = self.epoch + self.xs_serial += 1 + self.au_xs[target] = (self.xs, self.xs_serial) + + def is_tainted(self, expr): + return bool(set(TOKEN.findall(expr)) & self.tainted) + + def lane_dependent(self, name): + """Neither uniform nor uniform over the active lanes.""" + return name in self.tainted and self.au.get(name) != self.epoch and not self.lineage_ok(name) + + # ---- exec lineage ------------------------------------------------------------------------------ + # The epoch rule above forgets every active-uniform value at the first exec write that may widen exec. The + # compiler's usual shape restores a SAVED exec instead: `s[26:27] = exec ... exec = s26 & x (narrow) ... exec = + # s26 (restore) ... exec = s26 & y`. A value written from uniform values under E is the same in every lane of E; + # every later exec that is E or a subset of E (a narrowing of E or of a restore of E) has only such lanes active. + # States: 0 at entry (all lanes), a child per narrowing, the saved state per restore of an unchanged copy, a + # fresh root for any other exec write, at loop heads, and where joined paths have no common ancestor. + def lineage_new(self, parent): + n = len(self.xs_parent) + self.xs_parent[n] = parent + return n + + def lineage_reset(self): + self.xs = self.lineage_new(None) + self.au_xs, self.xs_copy = {}, {} + + def lineage_chain(self, x): + out = [] + while x is not None: + out.append(x) + x = self.xs_parent.get(x) # (a loop seed's state from an earlier pass: loop_join resets after it) + return out + + def lineage_ok(self, name): + """name's active-uniform value was written under the current exec state or an ancestor of it.""" + got = self.au_xs.get(name) if EXEC_LINEAGE else None + return got is not None and got[0] in self.lineage_chain(self.xs) + + LINEAGE_COPY = re.compile(r'^\(?exec\)?(?: & 1)?$') + LINEAGE_INNER = re.compile(r'^\((.+)\) & 1$') + + def lineage_exec(self, expr): + """The exec state after `exec = expr` (the one-lane forms: `(s26) & 1`, `(s18 & exec) & 1`, + `(exec & xsave) & 1`, `(s18 & ~exec) & 1`).""" + e = expr.strip() + m = self.LINEAGE_INNER.match(e) + terms = [t.strip() for t in m.group(1).split(' & ')] if m else [e] + if len(terms) == 1 and terms[0] in self.xs_copy: + return self.xs_copy[terms[0]] # a restore of an unchanged copy + if len(terms) >= 2 and all(re.fullmatch(r'~?\w+', t) for t in terms): + if 'exec' in terms: + return self.lineage_new(self.xs) # exec & x: a narrowing of the current state + for t in terms: + if t in self.xs_copy: + return self.lineage_new(self.xs_copy[t]) # copy & x (x may be ~exec): inside the copy's lanes + return self.lineage_new(None) + + def lineage_merge(self, states): + """Join of the lineage fields (xs, au_xs, xs_copy) of the incoming paths.""" + chains = [self.lineage_chain(s[0]) for s in states] + common = [x for x in chains[0] if all(x in c for c in chains[1:])] + self.xs = common[0] if common else self.lineage_new(None) + first = states[0] + self.xs_copy = {r: v for r, v in first[2].items() if all(s[2].get(r) == v for s in states)} + self.au_xs = {r: v for r, v in first[1].items() if all(s[1].get(r) == v for s in states)} + + # ---- instructions -------------------------------------------------------------------------- + def one(self, name, asm): + """one_body, plus the lane-mask SCC provenance (scc_from) carried along branch edges: the scan is linear, + so a branch target gets the union of the states at the branches to it (and at its fall-through when the + previous instruction falls through). Backward edges are not followed (a missed origin only refuses).""" + if self.pc in self.join_from: + saved = self.join_from.pop(self.pc) + if self.fell_off: + self.scc_from = dict(saved) + else: + for k, v in saved.items(): + self.scc_from[k] = self.scc_from.get(k, frozenset()) | v + self._xs_exec_seen = False + self._dw_keep = set() + before = len(self.lines) + term = self.one_body(name, asm) + if 'descword' in MESH_FEATURES: + # an SGPR this instruction wrote other than by an in-place descriptor edit (dw_mark_edit) holds a new value + for r in G.sgpr_access(name, asm)[1] - self._dw_keep: + self.sym.pop(self.dw_edit_key(r), None) + if not self._xs_exec_seen and (self.exec_written(name, parse(asm)[1]) or + any(re.search(r'exec = ', l) for l in self.lines[before:])): + self.xs = self.lineage_new(None) # an exec write emit() did not see: no lineage across it + self.fell_off = bool(term) and term[0] in ('jump', 'end') + target = None + if term and term[0] in ('jump', 'branch'): + target = term[-1] + elif term and term[0] == 'barrier' and len(term) > 3: + target = term[3] # group-uniform execz: the skip edge + if target is not None and target > self.pc: + into = self.join_from.setdefault(target, {}) + for k, v in self.scc_from.items(): + into[k] = into.get(k, frozenset()) | v + return term + + def one_body(self, name, asm): + _, ops, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', name) + if self.pending: + self.lines.extend(self.pending) + self.pending = [] + if base == 's_cbranch_execz': + self._execz_edge = True # the snapshot of this branch's taken edge (base translate) is an execz edge + if self.pc in self.loop_heads(): + self.exec_off = set() + for r, before, at in self.group_checks.get(self.pc, ()): + # A merge that left ('conflict',) is refused by any later use (exec_off_use: an exec-masked mask op + # excepted), so only another change is refused here. + if self.sym.get(r) != before and not (EXEC_OFF and self.sym.get(r) == ('conflict',)): + raise Unsupported('execz range %#x-%#x changes s%d from %s to %s' % (at, self.pc, r, before[0], self.sym.get(r))) + if self.pc in self.branch_targets(): + self.shadow.clear() # another path may arrive here without the shadow assignments + if self.pc >= self.divergent_until or self.pc in self.loop_heads(): + self.running_active = False + if self.pc in self.loop_heads(): + # the linear scan reaches a loop head with the state from before the loop; a later iteration can + # arrive with any exec + self.exec_static = None + self.static_copies.clear() + self.lineage_reset() # a back edge may arrive with any exec + # the base marks s0..s127 lane-suspect at a loop head; spill slots are scalars too + self.lane_s |= self.spill_slots + if base in ('s_waitcnt_depctr',): + return None + if base.startswith('s_cbranch_exec') and self.exec_static is not None: + # exec is a known mask (the same in every wave): the wave-level branch is decided here + taken = (self.exec_static == 0) == (base == 's_cbranch_execz') + return ('jump', int(ops[0].split('_')[1], 16)) if taken else None + if base.startswith('ds_'): + return self.lds(base, ops, mods) + if base in FUSED or base in UNFUSED: + # the multiply-add rule at FMA_MODE: fused ops exact (x2w_fma) or precise; unfused ops always precise + arity, _ = G.VEC_F[base] + args = [self.f(o) for o in ops[1:1 + arity]] + if base in ('v_fmac_f32', 'v_mac_f32'): + args.append(self.f(ops[0])) + helper = 'x2w_fma' if base in FUSED and EXACT_FMA else 'x2w_madp' + return self.set_vf(reg_range(ops[0])[1], '%s(%s, %s, %s)' % ((helper,) + tuple(args)), mods) + if base == 's_sendmsg': + if ops != ['0x9']: + raise Unsupported('s_sendmsg %s' % ops) + self.alloc_seen = True + if self.au_scalars.get('m0', self.epoch) != self.epoch: + raise Unsupported('m0 (from v_readfirstlane under a partial exec) sent after exec was widened') + # Wave-level message: the wave sends it when it reaches it. Lanes active here all hold the same m0. + self.emit('if (exec & 1) x2w_alloc = m0;') + self.alloc_guarded = True + return None + if base == 's_barrier': + if not self.has_lds: + # A barrier orders LDS (and memory) traffic between the waves; a program without LDS instructions + # writes nothing another wave reads here (the archive form's barriers sit in per-lane regions + # around the allocation, which the one-lane model could not place anyway) + return None + # s_barrier runs whatever exec is; a lane that skipped it per lane would arrive at a different one + if self.pc < self.divergent_until: + raise Unsupported('s_barrier inside a per-lane skipped range at %#x' % self.pc) + self.lds_written_in_phase = False + return ('barrier', 'console') # the program's own barrier (others are added by the translation) + if base in ('s_waitcnt_vmcnt', 's_waitcnt_lgkmcnt', 's_waitcnt_expcnt', 's_waitcnt_vscnt'): + return None + # Every scalar destination stops being a lane mask unless the handler marks it again (the base + # translator only updates the mask set in its ALU paths, so a load into a former mask register kept + # the mark and a later s_or of it was cut to bit 0). + reads, writes, _, _ = reads_writes(name, asm) + masks_before = set(self.masks) + for r in writes: + if isinstance(r, int): + # a copy is named by its low SGPR: a write to either half ends it (a copy this instruction makes is + # entered again by emit) + self.xs_copy.pop('s%d' % r, None) + self.xs_copy.pop('s%d' % (r - 1), None) + self.masks -= writes + if base == 's_sendmsg' or 'm0' in ops[1:]: + reads = reads | {'m0'} + if ops and ops[0] == 'm0': + writes = writes | {'m0'} + # A scalar read from the first active lane while some lanes were off holds, in the one-lane model, each + # lane's own value: right in the lanes that were active, stale in the others. Once exec has been widened + # those other lanes run again, so such a register must not be read any more. + stale = [r for r in reads if r in self.au_scalars and self.au_scalars[r] != self.epoch] + if stale: + raise Unsupported('%s (from v_readfirstlane under a partial exec) read after exec was widened at %#x' + % (stale[0], self.pc)) + derived = any(r in self.au_scalars for r in reads) + for r in writes: + if derived and base.startswith('s_'): + self.au_scalars[r] = self.epoch # computed from such a value: the same caveat + else: + self.au_scalars.pop(r, None) + self._known_at_start = self.exec_known + self._static_set = False + for r in writes: + self.static_copies.pop(r, None) + if isinstance(r, int): + self.static_copies.pop(r - 1, None) # the high half of a 64-bit copy + role = self.waterfall_role() + if role is not None: + term = self.waterfall_step(role[0], role[1], ops) + if term is not NotImplemented: + return term + before = len(self.lines) + term = super().one(name, asm) + if self.exec_written(name, ops) or any(re.search(r'\bexec = ', l) for l in self.lines[before:]): + self.exec_off = set() # lanes may have been turned on: an exec-off register is plain conflict again + if not self._static_set and (self.exec_written(name, ops) or + any(re.search(r'\bexec = ', l) for l in self.lines[before:])): + self.exec_static = None # exec changed in a way not modelled as a constant mask + if self.exec_written(name, ops) or any(re.search(r'\bexec = ', l) for l in self.lines[before:]): + self.running_active = False # threads with exec 0 may run on from here + mask_read = any(t in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or (reg_range(t) and reg_range(t)[0] == 's' and + reg_range(t)[1] in masks_before) + for t in ops[1:]) + if self.mask_scc(base, ops, masks_before, self.lines[before:]): + self.scc_from['scc'] = frozenset([self.pc]) + if re.match(r's_and_b(32|64)$', base) and ('exec' in ops[1:] or 'exec_lo' in ops[1:]): + self.scc_confined.add(self.pc) # result inside the active lanes (see the per-lane shortcut below) + if self.pc in getattr(self.pipe, 'scc_publish', ()): + if term is not None: + raise Unsupported('lane-mask SCC at %#x ends a block' % self.pc) + return self.lane_scc() + elif (base.startswith('s_') and mask_read and 'scc' in self.tainted + and any(re.search(r'\bscc = ', l) for l in self.lines[before:])): + # SCC of a non-mask SALU op on a lane mask (e.g. s_lshl_b32 of vcc_lo): the one-lane bit has no + # per-wave rule here (an OR of the threads' results is not the op on the 64-bit mask): origin -(pc+1) + self.scc_from['scc'] = frozenset([-(self.pc + 1)]) + if term and term[0] == 'branch': + cond = term[1] + off = self.pc + target = term[2] + per_lane = base[10:] in ('execz', 'execnz', 'vccz', 'vccnz') + lane_cond = self.is_tainted(cond) + if base[10:] in ('scc0', 'scc1') and lane_cond: + tokens = TOKEN.findall(cond) + origins = frozenset().union(*(self.scc_from.get(d, ()) for d in tokens)) + # with lanes off, a lane-mask SCC is the active lanes' value only when its mask result was confined + # to them (`x & exec`): `saved & ~exec` has 0 in every active lane and the wave's SCC is 1 + confined = self.exec_known or origins <= self.scc_confined or not CONFINED_SCC + if (LANE_SCC and not any(self.lane_dependent(t) for t in tokens) + and (self.exec_known or self.running_active) and confined): + # SCC the same in every active lane (e.g. `vcc & exec` with vcc from a uniform compare), and + # every thread that runs here is an active lane (all lanes on, or right inside a per-lane + # skipped range with no exec write since): each thread's SCC is the wave's, so the per-lane + # branch is the wave's branch + return term + if target <= off and PERLANE_LOOPS: + why = self.perlane_loop(target, off) + if why is None: + return term # per-lane loop: each thread iterates until its own lane leaves + raise Unsupported('per-lane loop %#x-%#x: %s' % (target, off, why)) + raise LaneScc('branch on an SCC that depends on lane masks at %#x' % off, origins) + if per_lane and lane_cond: + if target <= off: + raise Unsupported('per-lane loop branch %s at %#x' % (base, off)) + # vcc must be the same in every active lane (vcc = exec & uniform): inactive lanes then read 0 and + # take the branch the way execz would, which the skipped-range check below covers + if base[10:] in ('vccz', 'vccnz') and self.lane_dependent('vcc'): + raise Unsupported('%s on a lane-dependent vcc at %#x' % (base, off)) + if base == 's_cbranch_execz' and off in self.group_branches(): + return self.group_branch(off, target) + self.check_skipped_scalars(off, target) + self.divergent_until = max(self.divergent_until, target) + if base == 's_cbranch_execz': + self.running_active = True # the threads that go on are exactly the active lanes + elif base[10:] in ('execnz', 'vccnz'): + self.running_active = False # the threads that go on may be inactive lanes + return term + + def group_branch(self, off, target): + """s_cbranch_execz over a range that writes a scalar live at its end (or encloses such a range). + + Per lane, the lanes that skip would keep the old scalar where the wave computed a new one. Instead every + lane publishes its exec bit (x2w_any[k][wave]), a group barrier follows, and the range is skipped only when + no lane of the GROUP is active; otherwise all 128 threads run it, the inactive lanes with exec 0 (vector + writes, exports, LDS and buffer stores stay guarded by exec; inner per-lane branches still skip per lane). + A whole wave with no active lane (which the hardware skips) then gets back, at the end of the range, the + values the hit scalars had before it. Because every thread of the group runs the range, barriers inside + it are allowed. Refused: exec writes the per-lane model cannot follow (as before), the branch inside a + per-lane range, a hit scalar holding a descriptor before the range, and other ways into the target.""" + if off < self.divergent_until or self.exec_known or self.pending: + raise Unsupported('group-uniform execz at %#x inside a per-lane range' % off) + hits = self.skipped_scalars(off, target) + restore = [] + # the end may also be reached by other branches: only a lane that came through this branch restores + # (x2w_u = 1 here, cleared at the end) + seen = 'x2w_u%d' % len(self.shadow_vars) + self.shadow_vars.append(seen) + k = len(self.wave_any) + self.wave_any.append(off) + for r in sorted(hits): + reg = 'vcc' if r == -1 else 's%d' % r + if r != -1 and r not in self.sym and r not in self.used_s: + continue # no value before the range: a wave that skips it reads an undefined register + before = self.sym.get(r) if r != -1 else None + if before is not None and before[0] not in ('const', 'fixed_buffer_word'): + # a symbolic value (descriptor, pointer): no run-time copy exists. Right only when the range leaves + # the same symbolic value (a reload of the same descriptor): checked at the target. + self.group_checks.setdefault(target, []).append((r, before, off)) + continue + try: + value = self.u(reg) + except Unsupported: + raise Unsupported('execz range %#x-%#x writes %s, which holds %s before it' % (off, target, reg, before)) + var = 'x2w_u%d' % len(self.shadow_vars) + self.shadow_vars.append(var) + self.emit('%s = %s;' % (var, value)) + if r != -1: + self.used_s.add(r) + restore.append('if (%s != 0u && x2w_any[%d][wave] == 0u) %s = %s;' % (seen, k, reg, var)) + if restore: + self.emit('%s = 1u;' % seen) + restore.append('%s = 0u;' % seen) + self.emit('if (exec & 1) x2w_any[%d][wave] = 1u;' % k) + if 'restore' not in TEST_DROP: + self.group_restore.setdefault(target, []).extend(restore) + return ('barrier', 'wave-branch', k, target) + + MASK_OPS = ('and', 'or', 'xor', 'andn2', 'orn2', 'nand', 'nor', 'xnor', 'not') + + def mask_scc(self, base, ops, masks_before, lines): + """The SALU instruction just translated set SCC from a lane mask, lane-dependently: SCC = (64-bit result + != 0) is one bit for the whole wave (RDNA 2 ISA: S_AND_B64 etc. "SCC = (D != 0)"; S_*_SAVEEXEC_B64 + "SCC = (EXEC != 0)"), while the one-lane model computed it from this lane's bit only.""" + if not base.startswith('s_') or not any(re.search(r'\bscc = ', l) for l in lines): + return False + if 'scc' not in self.tainted: + return False + if 'saveexec' in base or 'wrexec' in base: + return True + if base.split('_')[1] not in self.MASK_OPS: + return False + for t in ops[1:]: + r = reg_range(t) + if t in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or (r and r[0] == 's' and r[1] in masks_before): + return True + return False + + def lane_scc(self): + """Publish the wave's SCC of a lane-mask instruction: every thread whose bit of the result is set marks + x2w_sany[k][wave], a group barrier follows (a phase boundary, as the readfirstlane broadcast), and the next + block starts with scc = the wave's value, which is then the same in every lane of the wave (not tainted). + Inactive lanes take part with their own bits: in a group-uniform execz range they run with exec 0, so a + result masked with exec has 0 there, as on the hardware. Every thread of the group must reach the barrier: + refused inside a per-lane skipped range, before a branch target, and (barrier_count) inside loops or on one + side of a branch only.""" + if self.pc < self.divergent_until: + raise Unsupported('lane-mask SCC at %#x inside a per-lane skipped range' % self.pc) + if self.pending: + raise Unsupported('lane-mask SCC at %#x right after a broadcast' % self.pc) + if self.next_offset() in self.branch_targets(): + raise Unsupported('lane-mask SCC at %#x followed by a branch target' % self.pc) + self.scc_from.pop('scc', None) + self.tainted.discard('scc') + self.au.pop('scc', None) + self.au_xs.pop('scc', None) + if 'publish' in TEST_DROP: + return None # negative control: the lane's own bit is taken as the wave's SCC + k = len(self.scc_any) + if 2 * (k + 1) > GROUP: + raise Unsupported('more than %d lane-mask SCCs (the slots are cleared by one thread each)' % (GROUP // 2)) + self.scc_any.append(self.pc) + self.lines.append('if (scc) x2w_sany[%d][wave] = 1u;' % k) + self.pending.append('scc = x2w_sany[%d][wave] != 0u;' % k) + self.lds_written_in_phase = False + return ('barrier', 'lane-scc') + + @staticmethod + def exec_written(name, ops): + base = re.sub(r'_e(32|64)$', '', name) + return ('saveexec' in base or 'wrexec' in base or base.startswith('v_cmpx') or + (base.startswith('s_') and ops and ops[0] in ('exec', 'exec_lo'))) + + def exec_mask_expr(self, mask): + """This lane's bit of a constant 64-bit exec mask.""" + lo, hi = mask & 0xffffffff, mask >> 32 + if hi == 0 and lo == 1: + return '(lane == 0u ? 1u : 0u)' + return '((lane < 32u ? (0x%08xu >> lane) : (0x%08xu >> (lane - 32u))) & 1u)' % (lo, hi) + + def set_v(self, n, expr, *, low16_only=False): + # Shadow: under a constant partial exec, a value computed only from wave-uniform inputs is also kept in an + # unguarded variable, so a later v_readfirstlane can read it although the HLSL thread's lane was off + # (the hardware reads the first active lane, which held that same value if it was active at the write). + sub = expr + if self.exec_static is not None and not self.exec_known: + for v in set(re.findall(r'\bv(\d+)\b', expr)): + if int(v) in self.shadow: + sub = re.sub(r'\bv%s\b' % v, self.shadow[int(v)][0], sub) + super().set_v(n, expr, low16_only=low16_only) + self.shadow.pop(n, None) + if self.exec_static is None or self.exec_known or self.exec_static == 0: + return + if set(TOKEN.findall(sub)) & (self.tainted | {'exec', 'lane', 'tid'}): + return + var = 'x2w_u%d' % len(self.shadow_vars) + self.shadow_vars.append(var) + self.lines.append('%s = %s;' % (var, sub)) + self.shadow[n] = (var, self.exec_static) + + def declarations(self): + lines = super().declarations() + for (offset, size), name in self.literal_tables.items(): + words = struct.unpack_from('<%dI' % (size // 4), self.raw, offset) + values = ', '.join('0x%08xu' % word for word in words) + lines.append(' static const uint %s[%d] = {%s};' % (name, len(words), values)) + if self.shadow_vars: + lines.append(' uint %s;' % ', '.join('%s = 0' % v for v in self.shadow_vars)) + return lines + + def snapshot(self): + snap = super().snapshot() + ((self.xs, dict(self.au_xs), dict(self.xs_copy)), + self.exec_static, dict(self.static_copies)) + if JOIN_TAINT: + snap += (frozenset(self.tainted), dict(self.au), self.epoch) + if self._execz_edge: + self._execz_edge = False + self._execz_snaps.append(snap) + return snap + + def merge(self, states): + # edges from code no path reaches in this loop pass (loop_one) do not count, unless all are + states = [s for s in states if BOTTOM not in s[0]] or states + dw_join = {} + if 'descword' in MESH_FEATURES: + # a value computed from table descriptor words on some path, where the paths disagree: when every path + # holds a run-time number there (None / RUNTIME_BACKED), the join is a run-time number that may depend on + # those words: ('dwnum', union), marked used only by a later numeric read. Otherwise (a conflict, which an + # exec-off read may still take as its variable) the words are needed now (conservative). + for reg in set().union(*(s[0] for s in states)): + values = [s[0].get(reg) for s in states] + if all(v == values[0] for v in values) or not any(v and v[0] == 'dwnum' for v in values): + continue + deps = frozenset().union(*(v[1] for v in values if v and v[0] == 'dwnum')) + if all(v is None or v[0] in self.RUNTIME_BACKED for v in values): + dw_join[reg] = ('dwnum', deps) + else: + self.dw_use(deps) + n_base = len(G.Stage.snapshot(self)) + super().merge(states) + self.sym.update(dw_join) + self.lineage_merge([s[n_base] for s in states]) # right after the base fields + # the mesh fields are the last ones of the snapshot, whatever the base snapshot holds before them + n = 5 if JOIN_TAINT else 2 + statics = [s[-n] for s in states] + self.exec_static = statics[0] if all(x == statics[0] for x in statics) else None + copies = [s[-n + 1] for s in states] + self.static_copies = {r: m for r, m in copies[0].items() if all(c.get(r) == m for c in copies)} + if JOIN_TAINT: + # Taint at a join of forward edges (the base merges only its own fields; the linear scan otherwise kept + # the state of the instruction above, which after an unconditional jump is no incoming path at all): + # tainted on any incoming path; active-uniform only where every path that taints the register has it + # active-uniform at the current epoch (no exec widening the linear scan saw since that branch). + self.tainted = set().union(*(s[-3] for s in states)) + au = {} + for r in self.tainted: + if all(r not in s[-3] or (s[-2].get(r) == s[-1] == self.epoch) for s in states): + au[r] = self.epoch + self.au = au + self.merge_exec_off(states) + + def merge_exec_off(self, states): + """Registers that the merge made ('conflict',) only because of taken s_cbranch_execz edges. + + A lane takes an execz edge only with its exec bit 0 (per lane: `(exec & 1) == 0`; group-uniform: no lane of + the group active), so on those paths the lane's bit is 0 at the join; every other path assigned the + register at run time. The run programs use this for a lane mask merged after a divergent if (v_cmp_e64 + into a reused SGPR inside the range, then `s_nand_b64 / s_orn2_b64 sX, sX, exec` after it; INFERRED to be the + compiler's i1 phi, whose skipped side is undefined). Until exec is written again + (exec_off_use), a mask op whose lane bit does not depend on the register when exec is 0 may read its HLSL + variable.""" + self.exec_off = set() + if not EXEC_OFF: + return + backed = self.RUNTIME_BACKED + for reg, value in self.sym.items(): + if value != ('conflict',): + continue + bad = [s for s in states if s[0].get(reg) is not None and s[0].get(reg)[0] not in backed] + if bad and len(bad) < len(states) and all(any(s is e for e in self._execz_snaps) for s in bad): + self.exec_off.add(reg) + + def exec_off_use(self, base, ops): + """Exec-off conflict registers (merge_exec_off) a 64-bit mask op may read: the op takes exec as the other + operand and its lane bit is the same for both values of the register's bit when the lane's exec bit is 0 + (s_and X, exec = 0; s_nand = 1; s_andn2 exec, X = 0; s_orn2 X, exec = 1). Empty when it does not apply.""" + if not self.exec_off or base not in G.SCA or len(ops) != 3 or not base.endswith('_b64'): + return set() + srcs = ops[1:] + if 'exec' not in srcs: + return set() + k = 1 - srcs.index('exec') + r = reg_range(srcs[k]) + if not r or r[0] != 's' or r[1] not in self.exec_off or self.sym.get(r[1]) != ('conflict',): + return set() + text = G.SCA[base][0] + if '{2}' in text or not re.fullmatch(r'[~(){}01&|^ ]+', text): + return set() + bits = set() + for x in (0, 1): + args = ['0', '0'] + args[k] = str(x) + bits.add(eval(text.format(*args)) & 1) # noqa: S307 (a fixed SCA formula over two constant bits) + return {r[1]} if len(bits) == 1 else set() + + def format_load(self, ops, mods, count, name): + """buffer_load_format_* through a resource-heap descriptor (X2W_DRAW_FEATURES heap + bufword3): the format + and swizzle come from the view's word 3 (x2w_hword, X2W_MESH_FEATURES=heapwords); table descriptors take + the base path.""" + key = self.descriptor(ops[2]) + if key[0][0] != 'heapdyn': + return super().format_load(ops, mods, count, name) + if not {'heap', 'bufword3'} <= set(getattr(self.pipe, 'features', ())) or 'heapwords' not in MESH_FEATURES: + raise Unsupported('%s through heapdyn' % name) + self.pipe.heapwords = True + for m in mods: + if not (m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:')): + raise Unsupported('%s modifier %s' % (name, m)) + dst = reg_range(ops[0]) + buf, address = self.buffer_address(ops, mods) + self.emit('a = %s;' % address) + for i in range(count): + self.set_v(dst[1] + i, 'x2w_fmt_load(%s, a, x2w_hword(h%d, 3u), %du)' % (buf, key[0][1], i)) + + # ---- table descriptor words read as numbers (X2W_MESH_FEATURES=descword) --------------------------------------- + # A word of a descriptor loaded from a root descriptor TABLE (('desc', ('table', p), off, w)) is known only at draw + # time: the runtime passes it as entry value `udsrc descword

` (d3d12_draw.inl draw_descword_value: + # the title's dword, or the synthesized T# / V# word of a view token, as compute's descword). Scalar arithmetic over + # such words is emitted with a placeholder X2W_DW per word and the result register holds ('dwnum', {k, ...}) + # (a run-time number). Only a numeric use (S(), or a join where paths disagree) marks its words used; build() + # then makes used placeholders entry values and the others 0u (their arithmetic is dead code, as before: a V# + # NUM_RECORDS x STRIDE bounds computation nobody reads adds no entry value). + RUNTIME_BACKED = G.Stage.RUNTIME_BACKED + ('dwnum',) + + @staticmethod + def dw_edit_key(n): + return 'x2w_dwedit_%d' % n # key in the symbolic state (snapshotted and merged with it), as BOTTOM + + def dw_mark_edit(self, n): + """s holding a descriptor word was edited in place (the base keeps its symbol): marked until an instruction + writes s otherwise (one(): a fresh load of the same entry is the table's word again).""" + self.sym[self.dw_edit_key(n)] = ('dwedit',) + self._dw_keep = getattr(self, '_dw_keep', set()) | {n} + + def dw_word(self, s, n): + """Placeholder index for symbol s of s when it is a table descriptor word the runtime can pass, else None.""" + if 'descword' not in MESH_FEATURES or not s or s[0] != 'desc' or not isinstance(s[1], tuple): + return None + if s[1][0] != 'table' or s[2] is None or not isinstance(s[2], int) or not isinstance(s[3], int): + return None + if self.sym.get(self.dw_edit_key(n)): + # edited in place since it was loaded (or on some path into a join): the table's word is not its value + raise Unsupported('numeric use of an edited descriptor word (s%d: table %d +%d word %d)' % (n, s[1][1], s[2], s[3])) + src = ('descword', s[1][1], s[2] + 4 * s[3]) + if src not in self.pipe.dw_src: + self.pipe.dw_src.append(src) + return self.pipe.dw_src.index(src) + + def dw_scalar(self, base, ops): + """A 32-bit scalar op over table descriptor words (and numbers): emitted with placeholders, result ('dwnum', + deps). None when the op is not one (the caller goes on as before).""" + if 'descword' not in MESH_FEATURES or base not in G.SCA or base.endswith('_b64') or len(ops) < 2: + return None + d = reg_range(ops[0]) + if not d or d[0] != 's' or d[1] != d[2]: + return None + syms = [] + for t in ops[1:]: + r = reg_range(t) + if r and r[0] == 's' and r[1] != r[2]: + return None + syms.append(self.sym.get(r[1]) if r and r[0] == 's' else None) + kinds = [s[0] if s else None for s in syms] + if not any(k in ('desc', 'dwnum') for k in kinds): + return None + if base == 's_mov_b32' and kinds[0] == 'desc': + # a descriptor word moved: it keeps its descriptor meaning (a resource operand, as before), and its edit mark + if self.sym.get(self.dw_edit_key(reg_range(ops[1])[1])): + self.dw_mark_edit(d[1]) + return None + if any(k not in (None, 'const', 'ud', 'fixed_buffer_word', 'desc', 'dwnum') for k in kinds): + return None + own = self.sym.get(d[1]) + if own and own[0] == 'desc' and own in syms: + # an in-place edit of a descriptor word: the base records it (and keeps the symbol); noted for dw_word + self.dw_mark_edit(d[1]) + return None + if base == 's_movk_i32': + return None + regs = [reg_range(t) for t in ops[1:]] + if any(k == 'desc' and self.dw_word(s, r[1]) is None for k, s, r in zip(kinds, syms, regs)): + return None + deps, values = set(), [] + for t, s in zip(ops[1:], syms): + r = reg_range(t) + if s and s[0] == 'desc': + k = self.dw_word(s, r[1]) + deps.add(k) + values.append('X2W_DW%d' % k) + elif s and s[0] == 'dwnum': + deps |= s[1] + self.used_s.add(r[1]) + values.append('s%d' % r[1]) + else: + values.append(self.u(t)) + text, scc = G.SCA[base] + self.set_s(d[1], text.format(*values)) + self.sym[d[1]] = ('dwnum', frozenset(deps)) + if scc: + self.emit('scc = %s;' % scc.replace('$', 's%d' % d[1])) + return True + + def dw_use(self, deps): + self.pipe.dw_used |= set(deps) + + def S(self, n): + """A word of a resource-heap descriptor read as a number (an image's width bits, a null test): the + runtime's synthesized word (x2w_hword), with X2W_MESH_FEATURES=heapwords; a table descriptor word or a + value computed from such words (X2W_MESH_FEATURES=descword): its entry value / variable, marked used; + otherwise as the base.""" + s = self.sym.get(n) + if s and s[0] == 'hword': + return 'x2w_hword(h%d, %du)' % (s[1], s[2]) + if s and s[0] == 'dwnum': + self.dw_use(s[1]) + self.used_s.add(n) + return 's%d' % n + k = self.dw_word(s, n) + if k is not None: + self.dw_use({k}) + return 'X2W_DW%d' % k + if (s and s[0] == 'desc' and isinstance(s[1], tuple) and s[1][0] == 'heapdyn' and s[2] == 0 + and 'heapwords' in MESH_FEATURES and 'heap' in getattr(self.pipe, 'features', ())): + self.pipe.heapwords = True + return 'x2w_hword(h%d, %du)' % (s[1][1], s[3]) + return super().S(n) + + def heap_sampler(self, tok): + # run-time offset (base) or a constant entry of the sampler heap (const_heap_sampler) + return super().heap_sampler(tok) or const_heap_sampler(self, tok) + + def set_exec_static(self, mask): + """exec = a constant lane mask (s_mov_b64 exec, or a copy of one).""" + mask &= ALL_LANES + self._static_set = True + self.exec_static = mask + if mask == ALL_LANES: + self.emit('exec = 1;') + self.exec_known = True + else: + self.emit('exec = %s;' % self.exec_mask_expr(mask)) + self.exec_known = False + + def op_s_cselect_b32(self, ops, mods): + # the base handles register / exec / vcc destinations; the run form also selects into m0 + if ops[0] == 'm0': + low = [('s%d' % reg_range(t)[1]) if reg_range(t) and reg_range(t)[0] == 's' else t for t in ops[1:3]] + self.emit('m0 = scc ? %s : %s;' % (self.u(low[0]), self.u(low[1]))) + return None + if not reg_range(ops[0]) and ops[0] not in ('exec', 'exec_lo', 'vcc', 'vcc_lo'): + raise Unsupported('s_cselect_b32 to %s' % ops[0]) + return super().op_s_cselect_b32(ops, mods) + + def op_s_and_b32(self, ops, mods): + # merged_wave_info & mask: the wave index field (bits 27:24) is the only part this translation models + for i, j in ((1, 2), (2, 1)): + src = reg_range(ops[i]) + if src and src[0] == 's' and self.sym.get(src[1]) == ('waveinfo',): + if not re.fullmatch(r'0x[0-9a-f]+|\d+', ops[j]) or int(ops[j], 0) & ~0x0f000000: + raise Unsupported('merged_wave_info & %s' % ops[j]) + d = reg_range(ops[0]) + if not d or d[0] != 's': + raise Unsupported('s_and_b32 of merged_wave_info to %s' % ops[0]) + self.masks.discard(d[1]) + self.set_s(d[1], '((wave << 24) & 0x%08xu)' % int(ops[j], 0), scc='$ != 0u') + return None + return self.scalar('s_and_b32', ops) + + def lds(self, base, ops, mods): + """ds_read_b32 / ds_write_b32 / _b64 with offset:N as groupshared uint x2w_lds[] (byte address / 4). + Lanes of one wave run independently between barriers here, so an LDS read after an LDS write in the same + barrier phase (lane-to-lane traffic inside a wave) is refused.""" + size = {'ds_read_b32': 1, 'ds_write_b32': 1, 'ds_read_b64': 2, 'ds_write_b64': 2}.get(base) + if size is None: + raise Unsupported(base) + off = 0 + for m in mods: + if m.startswith('offset:'): + off = int(m[7:], 0) + else: + raise Unsupported('%s with %s' % (base, m)) + if off + 4 * size > 4 * LDS_DWORDS: + raise Unsupported('%s offset %d beyond the modelled LDS' % (base, off)) + self.lds_used = True + if base.startswith('ds_write'): + addr, data = ops[0], reg_range(ops[1]) + # Several lanes storing to one address are ordered on the console (the highest lane wins) but race in + # HLSL: a uniform address is only taken under a constant single-lane exec. + single = self.exec_static is not None and bin(self.exec_static).count('1') == 1 + ar = reg_range(addr) + if not single and not (ar and ar[0] == 'v' and self.lane_dependent('v%d' % ar[1])): + raise Unsupported('%s to a wave-uniform address with more than one lane active at %#x' % (base, self.pc)) + self.emit('a = (%s + %du) >> 2;' % (self.u(addr), off)) + for i in range(size): + self.emit('if (exec & 1) x2w_lds[min(a + %du, %du)] = v%d;' % (i, LDS_DWORDS - 1, data[1] + i)) + self.used_v.add(data[1] + i) + self.lds_written_in_phase = True + return None + if self.lds_written_in_phase: + raise Unsupported('LDS read after an LDS write without a barrier at %#x' % self.pc) + dst, addr = reg_range(ops[0]), ops[1] + ar = reg_range(addr) + if ar and ar[0] == 'v' and dst[1] <= ar[1] < dst[1] + size - 1: # a later word would read the new value + raise Unsupported('%s overwrites its address register' % base) + for i in range(size): + # the address expression is repeated (no temporary), so a shadow (see set_v) can substitute into it + self.set_v(dst[1] + i, 'x2w_lds[min(((%s + %du) >> 2) + %du, %du)]' % (self.u(addr), off, i, LDS_DWORDS - 1)) + return None + + def liveness(self): + """Scalar registers (numbers; -1 = vcc) live on entry to each instruction offset (backward dataflow over + fall-through and branch edges).""" + if getattr(self, '_live', None) is not None: + return self._live + order = [x[0] for x in self.ins] + info = {x[0]: (x[2], x[3]) for x in self.ins} + following = dict(zip(order, order[1:])) + rw = {} + succ = {} + for off in order: + name, asm = info[off] + r, w, wv, rv = reads_writes(name, asm) + if RESTORED_SCALARS: + # wave64 lane masks that a VALU op names by their low SGPR: a v_cmp SDST writes the pair; a + # v_cndmask / carry-in mask operand reads it (AMD RDNA 2 ISA, VOP3 SDST / SSRC2 in wave64) + w = self.pair_writes(name, asm) + base = re.sub(r'_e(32|64)$', '', name) + last = parse(asm)[1][-1:] if base.startswith('v_cndmask') or (CARRY.fullmatch(base) and '_ci' in base) else [] + if last and re.fullmatch(r's\d+', last[0]): + r = set(r) | {int(last[0][1:]) + 1} + rw[off] = (frozenset(r | ({-1} if rv else set())), frozenset(w | ({-1} if wv else set()))) + nxt = [] if name in ('s_endpgm', 's_branch') else ([following[off]] if off in following else []) + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + succ[off] = [o for o in nxt if o in info] + live = {off: frozenset() for off in order} + changed = True + while changed: + changed = False + for off in reversed(order): + out = frozenset().union(*(live[s] for s in succ[off])) if succ[off] else frozenset() + r, w = rw[off] + new = r | (out - w) + if new != live[off]: + live[off], changed = new, True + self._live = live + return live + + def check_skipped_scalars(self, off, target): + """Refuse when a scalar register written in (off, target) is live at target (some path reads it before a + write): lanes that skip the range would see the old value where the wave saw the new one.""" + hit = self.skipped_scalars(off, target) + if hit: + raise Unsupported('scalar %s written in the per-lane skipped range %#x-%#x is live at its end' + % ('vcc' if min(hit) == -1 else 's%d' % min(hit), off, target)) + + def range_successors(self): + if getattr(self, '_succ', None) is None: + order = [x[0] for x in self.ins] + info = {x[0]: (x[2], x[3]) for x in self.ins} + following = dict(zip(order, order[1:])) + self._succ = {} + for o in order: + name, asm = info[o] + nxt = [] if name in ('s_endpgm', 's_branch') else ([following[o]] if o in following else []) + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + self._succ[o] = [x for x in nxt if x in info] + return self._succ + + def restored_scalars(self, off, target, hits): + """Of the SGPRs in `hits` (written in the range (off, target)), those that hold their value from before the + range again on every exit of the range: the register-allocator shuffle `s_mov_b32 sT, sR; ... sR = ...; + ... s_mov_b32 sR, sT`. Forward copy tracking over the range's own paths (state: register -> the register + whose entry value it holds, None = unknown; a register not in the state holds its own entry value), + intersected at joins; s_mov_b32 / s_mov_b64 copy, any other write ends what the destination held.""" + if not RESTORED_SCALARS: + return set() + succ = self.range_successors() + info = {x[0]: (x[2], x[3]) for x in self.ins} + inside = [o for o, _, _, _ in self.ins if off < o < target] + if not inside: + return set() + state = {inside[0]: {}} + exits = [] + work = [inside[0]] + seen_edges = 0 + while work: + seen_edges += 1 + if seen_edges > 100000: + return set() + o = work.pop() + st = dict(state[o]) + name, asm = info[o] + ops = parse(asm)[1] + w = self.pair_writes(name, asm) + d = reg_range(ops[0]) if ops else None + s = reg_range(ops[1]) if len(ops) == 2 else None + if name in ('s_mov_b32', 's_mov_b64') and d and d[0] == 's' and s and s[0] == 's': + n = 2 if name == 's_mov_b64' else 1 + vals = [st.get(s[1] + i, s[1] + i) for i in range(n)] + for i in range(n): + st[d[1] + i] = vals[i] + else: + for r in w: + if isinstance(r, int): + st[r] = None + for nx in succ[o]: + if not off < nx < target: + if nx <= off: + return set() # a loop back above the branch: not modelled + exits.append(st) + continue + if nx not in state: + state[nx] = st + work.append(nx) + else: + merged = {r: v for r, v in state[nx].items()} + for r in set(merged) | set(st): + a, b = merged.get(r, r), st.get(r, r) + merged[r] = a if a == b else None + if merged != state[nx]: + state[nx] = merged + work.append(nx) + return {r for r in hits if isinstance(r, int) and r >= 0 and exits and all(e.get(r, r) == r for e in exits)} + + def group_branches(self): + """execz branches (offsets) translated as group-uniform branches: those whose range writes a scalar that + is live at its end or holds a published lane-mask SCC (pipe.scc_publish), and every execz range enclosing + one of them (the inner barrier needs every thread of the group to reach it). Exec-write refusals are left + to the translation.""" + if getattr(self, '_group', None) is None: + ranges = [] + for o, n, name, asm in self.ins: + if name == 's_cbranch_execz': + t = int(parse(asm)[1][0].split('_')[1], 16) + if t > o: + ranges.append((o, t)) + # ranges that hold a lane-dependent v_readfirstlane_b32 (NeedGroupRange, set by MeshPipeline) + need = set(o for o, t in ranges if o in getattr(self.pipe, 'force_group', ())) + for o, t in ranges: + try: + if self.skipped_scalars(o, t): + need.add(o) + except Unsupported: + pass + # a lane-mask SCC published inside the range: the publish barrier needs every thread of the group, and + # the wave's SCC is then the OR over all 64 lanes' bits (the SALU op reads every bit, whatever exec is; + # the inactive lanes run the range with exec 0, their compare bits 0, as VOPC writes them) + publish = getattr(self.pipe, 'scc_publish', ()) if LANE_SCC else () + for o, t in ranges: + if any(o < p < t for p in publish): + need.add(o) + for o, t in ranges: + if any(o < o2 < t for o2 in need): + need.add(o) + self._group = {o: t for o, t in ranges if o in need} + return self._group + + @staticmethod + def pair_writes(name, asm): + """SGPRs an instruction writes, with the high half of a wave64 lane mask that a compare names by its low + register only (v_cmp / v_cmp_class SDST: the disassembler prints one SGPR; carry-outs are already pairs in + reads_writes; readlane / readfirstlane write one SGPR).""" + w = set(reads_writes(name, asm)[1]) + if name.startswith('v_cmp'): + w |= {x + 1 for x in w} + return w + + def exec_copies_at(self): + """Offset -> SGPR pairs (low register numbers) that hold exactly the wave's exec on entry to that + instruction on EVERY path from the entry: `s_mov_b64 sX, exec`, `s_mov_b64 exec, sX` and moves of such a + pair. Forward dataflow over fall-through and branch edges (loops included), intersected at joins; any other + exec write, or a write to the pair, ends the fact. Static (no translation state), so the pre-pass of + group_branches sees the same facts as the translation.""" + if not EXEC_COPIES: + return {} + if getattr(self, '_exec_copies', None) is None: + order = [x[0] for x in self.ins] + info = {x[0]: (x[2], x[3]) for x in self.ins} + following = dict(zip(order, order[1:])) + succ = {} + for off in order: + name, asm = info[off] + nxt = [] if name in ('s_endpgm', 's_branch') else ([following[off]] if off in following else []) + if name.startswith('s_cbranch') or name == 's_branch': + nxt.append(int(parse(asm)[1][0].split('_')[1], 16)) + succ[off] = [o for o in nxt if o in info] + + def transfer(off, eq): + # eq: 32-bit halves (register, 0 = exec_lo / 1 = exec_hi) holding that half of the current exec + name, asm = info[off] + ops = parse(asm)[1] + w = self.pair_writes(name, asm) + hv = [self.mask_halves(t) for t in ops[:2]] + if ops and ops[0] in ('exec', 'exec_lo', 'exec_hi') or self.exec_written(name, ops): + if name == 's_mov_b64' and ops[0] == 'exec' and isinstance(hv[1], list) and len(hv[1]) == 2: + return frozenset(hv[1]) + return frozenset() + add = set() + d = hv[0] if hv and isinstance(hv[0], list) else None + if d and len(ops) == 2 and name in ('s_mov_b64', 's_mov_b32'): + s = hv[1] + if name == 's_mov_b64' and len(d) == 2: + if s == 'exec': + add = set(d) + elif isinstance(s, list) and len(s) == 2: + add = {(d[i][0], s[i][1]) for i in range(2) if s[i] in eq} + elif name == 's_mov_b32' and len(d) == 1: + if isinstance(s, tuple): + add = {(d[0][0], s[1])} + elif isinstance(s, list) and len(s) == 1: + add = {(d[0][0], h) for (rr, h) in eq if rr == s[0][0]} + return frozenset({x for x in eq if x[0] not in w} | add) + facts = {order[0]: frozenset()} if order else {} # None (absent) = not reached yet + work = list(order[:1]) + while work: + off = work.pop() + out = transfer(off, facts[off]) + for s in succ[off]: + new = out if s not in facts else facts[s] & out + if facts.get(s) != new: + facts[s] = new + work.append(s) + self._exec_copies = {o: frozenset(r for (r, h) in eq if h == 0 and (r + 1, 1) in eq) for o, eq in facts.items()} + return self._exec_copies + + def skipped_scalars(self, off, target): + """Scalar registers (-1 = vcc) written in (off, target) and live at target; Unsupported for exec writes + the per-lane model cannot follow.""" + if EXEC_COPIES: + written = self.exec_walk(off, target) + hits = written & self.liveness().get(target, frozenset()) + return hits - self.restored_scalars(off, target, hits) if hits else hits + written = set() + copies = set() # registers holding exec as it was inside the range (nested if/else masks) + for o, n, name, asm in self.ins: + if off < o < target: + r, w, wv, _ = reads_writes(name, asm) + written |= w | ({-1} if wv else set()) + ops = parse(asm)[1] + low = [reg_range(t)[1] if reg_range(t) and reg_range(t)[0] == 's' else t for t in ops] + if name.startswith('s_') and 'saveexec' in name: + copies.add(low[0]) + continue + if name in ('s_mov_b64', 's_mov_b32') and len(ops) == 2 and ops[1] in ('exec', 'exec_lo'): + copies.add(low[0]) + continue + if (re.match(r's_(and|andn2)_b(32|64)$', name) and len(ops) == 3 and ops[0] not in ('exec', 'exec_lo') + and low[1] in copies): + copies.add(low[0]) # a subset of a copy taken in the range (`copy & ~exec`: the else lanes) + continue + if name.startswith('s_') and ops and ops[0] in ('exec', 'exec_lo'): + # A wave-level exec write can turn on lanes the per-lane model left behind, unless it only + # narrows exec (and / andn2 with exec) or restores / complements a copy taken in the range. + srcs = low[1:] + if re.match(r's_(and|andn2)_b(32|64)$', name) and 'exec' in ops[1:]: + pass + elif name in ('s_mov_b64', 's_mov_b32') and srcs[0] in copies: + pass + elif re.match(r's_andn2_b(32|64)$', name) and srcs[0] in copies: + pass # else branch: copy & ~exec is inside the copy + else: + raise Unsupported('exec written by %s inside the per-lane skipped range %#x-%#x' + % (name, off, target)) + for t in w: + copies.discard(t) + return written & self.liveness().get(target, frozenset()) + + @staticmethod + def mask_halves(tok): + """A scalar operand as 32-bit halves of a wave64 mask: 's[30:31]' -> [(30, 0), (31, 1)], 's30' -> [(30, None)] + (a 32-bit move keeps whichever half it holds), 'exec' -> 'exec', 'exec_lo' / 'exec_hi' -> ('exec', h).""" + if tok == 'exec': + return 'exec' + if tok in ('exec_lo', 'exec_hi'): + return ('exec', 0 if tok == 'exec_lo' else 1) + r = reg_range(tok) + if not r or r[0] != 's': + return None + if r[2] == r[1] + 1: + return [(r[1], 0), (r[1] + 1, 1)] + if r[2] == r[1]: + return [(r[1], None)] + return None + + def xor_swaps(self): + """XOR swaps of two SGPRs or two disjoint SGPR pairs: `s_xor_b32 sA, sA, sB; s_xor_b32 sB, sA, sB; + s_xor_b32 sA, sA, sB` (or the s_xor_b64 form; sources in either order) inside one basic block, where the + instructions between them touch neither A nor B. Afterwards A holds B's old value and B holds A's + (x ^ y ^ y = x). Returns ({offset of the first: {register: register it moves to}}, {offsets of the other + two}): exec_walk exchanges the facts of A and B at the first and leaves them alone at the others.""" + if getattr(self, '_xor_swaps', None) is None: + swaps, rest = {}, set() + targets = self.branch_targets() + + def form(x): + """(width, destination base, {source bases}) of an s_xor_b32 / s_xor_b64 on SGPRs.""" + ops = parse(x[3])[1] + width = {'s_xor_b32': 1, 's_xor_b64': 2}.get(x[2]) + if not width or len(ops) != 3: + return None + # vcc is s[106:107] on the console (the register allocator swaps through it as a data pair) + r = [('s', 106, 107) if t == 'vcc' else reg_range(t) for t in ops] + if not all(rr and rr[0] == 's' and rr[2] - rr[1] + 1 == width for rr in r): + return None + return width, r[0][1], {r[1][1], r[2][1]} + for i in range(len(self.ins) - 2): + f0 = form(self.ins[i]) + if not f0 or len(f0[2]) != 2 or f0[1] not in f0[2]: + continue + width, a = f0[0], f0[1] + b = (f0[2] - {a}).pop() + if abs(a - b) < width: + continue # overlapping pairs are no swap + regs = set(range(a, a + width)) | set(range(b, b + width)) + # the next two instructions that touch sA or sB must be the other two xors; instructions between + # them touch neither, and none of them is a branch or a branch target (one basic block) + found = [] + for x in self.ins[i + 1:i + 17]: + if x[0] in targets or x[2].startswith(('s_branch', 's_cbranch', 's_setpc', 's_endpgm')): + break + rd, wr, wv, rv = reads_writes(x[2], x[3]) + touched = set(rd) | set(wr) | ({106, 107} if wv or rv else set()) + if not (regs & touched): + continue + want = (width, b, {a, b}) if not found else (width, a, {a, b}) + if form(x) != want: + break + found.append(x[0]) + if len(found) == 2: + swaps[self.ins[i][0]] = {a + k: b + k for k in range(width)} | \ + {b + k: a + k for k in range(width)} + rest |= set(found) + break + self._xor_swaps = (swaps, rest) + return self._xor_swaps + + def exec_walk(self, off, target): + """The exec rule of skipped_scalars as a forward dataflow over the paths inside (off, target): returns the + scalar registers (-1 = vcc) written there, or raises Unsupported for an exec write that could turn on a lane + that was off at the branch (the one-lane model left that lane at the target). + + State: the 32-bit halves (register, 0 = lanes 0-31 / 1 = lanes 32-63) that hold part of a lane mask inside + the lanes active at the branch ("in-range masks"). Exec itself always is one (every accepted exec write keeps + it inside). Seeded with the pairs equal to exec at the branch (exec_copies_at); saveexec destinations, + copies of exec, moves (64- and 32-bit: register shuffles and SGPR spill slots), `and` with an in-range mask, + `andn2` of one and `or` of two are in-range masks; any other write ends what the register held. Intersected + at joins (a register is an in-range mask only if it is one on every path). Accepted exec writes: v_cmpx + (narrows), s_and with exec or an in-range mask, s_andn2 / andn2_saveexec / andn2_wrexec of an in-range mask + (an else mask), s_or / or_saveexec of in-range masks, and moves of an in-range pair or half.""" + info = {x[0]: (x[2], x[3]) for x in self.ins} + succ = self.range_successors() + inside = [o for o, _, _, _ in self.ins if off < o < target] + written = set() + if not inside: + return written + seed = set() + for x in self.exec_copies_at().get(off, ()): + seed |= {(x, 0), (x + 1, 1)} + state = {inside[0]: frozenset(seed)} + work = [inside[0]] + steps = 0 + swaps, swap_rest = self.xor_swaps() + + def refuse(name): + raise Unsupported('exec written by %s inside the per-lane skipped range %#x-%#x (at %#x)' + % (name, off, target, o)) + while work: + steps += 1 + if steps > 200000: + raise Unsupported('exec dataflow of the per-lane range %#x-%#x does not settle' % (off, target)) + o = work.pop() + st = set(state[o]) + name, asm = info[o] + ops = parse(asm)[1] + halves = [self.mask_halves(t) for t in ops] + + def inrange(h): + """Operand h (from mask_halves) is an in-range 64-bit mask.""" + return h == 'exec' or (isinstance(h, list) and len(h) == 2 and all(x in st for x in h)) + add = set() + base = name + if base.startswith('s_') and ops and ops[0] in ('exec', 'exec_lo', 'exec_hi'): + src = halves[1:] + if base in ('s_mov_b64',) and inrange(src[0]): + pass + elif base == 's_mov_b32' and isinstance(src[0], list) and src[0][0][1] is None and \ + any((src[0][0][0], h) in st for h in (0, 1)) and \ + (src[0][0][0], 0 if ops[0] == 'exec_lo' else 1) in st: + pass # a half restored into its own half of exec + elif base == 's_and_b64' and (inrange(src[0]) or inrange(src[1])): + pass + elif base == 's_andn2_b64' and inrange(src[0]): + pass # else mask: an in-range mask & ~exec + elif base == 's_or_b64' and inrange(src[0]) and inrange(src[1]): + pass + else: + refuse(name) + elif base.startswith('s_') and ('saveexec' in base or 'wrexec' in base): + src = halves[1] + if not (base.startswith('s_and_') or inrange(src)): + refuse(name) # or / andn2 forms take lanes from the source + d = halves[0] + if isinstance(d, list) and len(d) == 2: + add = set(d) # the old exec (saveexec) or the new one (wrexec): inside the branch's lanes + elif base.startswith('s_') and len(ops) >= 2 and isinstance(halves[0], list): + d = halves[0] + if base == 's_mov_b64' and len(d) == 2: + s = halves[1] + if s == 'exec': + add = set(d) + elif isinstance(s, list) and len(s) == 2: + add = {(d[i][0], s[i][1]) for i in range(2) if s[i] in st} + elif base == 's_mov_b32' and len(d) == 1: + s = halves[1] + if isinstance(s, tuple): + add = {(d[0][0], s[1])} # exec_lo / exec_hi + elif isinstance(s, list) and len(s) == 1: + add = {(d[0][0], h) for (rr, h) in st if rr == s[0][0]} + elif base == 's_and_b64' and len(d) == 2 and (inrange(halves[1]) or inrange(halves[2])): + add = set(d) + elif base == 's_andn2_b64' and len(d) == 2 and inrange(halves[1]): + add = set(d) + elif base == 's_or_b64' and len(d) == 2 and inrange(halves[1]) and inrange(halves[2]): + add = set(d) + if o in swaps: + # the register allocator's XOR swap (three s_xor): A and B exchange their values + st = {(swaps[o].get(r, r), h) for (r, h) in st} + elif o not in swap_rest: + pw = self.pair_writes(name, asm) + st = {x for x in st if x[0] not in pw} | add + out = frozenset(st) + for nx in succ[o]: + if not off < nx < target: + continue + new = out if nx not in state else state[nx] & out + if state.get(nx) != new: + state[nx] = new + work.append(nx) + for o in inside: + name, asm = info[o] + _, w, wv, _ = reads_writes(name, asm) + written |= w | ({-1} if wv else set()) + ops = parse(asm)[1] + # an instruction the walk did not reach from the branch (entered from elsewhere): no exec write there + if o not in state and name.startswith('s_') and (ops and ops[0] in ('exec', 'exec_lo', 'exec_hi') or + 'saveexec' in name or 'wrexec' in name): + refuse(name) + return written + + def scalar(self, base, ops): + """With X2W_MESH_FEATURES=heapwords, words of a resource-heap descriptor that a scalar op reads as numbers + (not an in-place edit of the descriptor) are the runtime's synthesized words (x2w_hword): they are + swapped for a numeric symbol for this instruction, so the base computes the result at run time + instead of keeping a symbolic `descnum`.""" + swapped = {} + off_regs = self.exec_off_use(base, ops) + for n in off_regs: + # (merge_exec_off) the register's run-time variable: right on the paths that assigned it, and the + # result does not depend on it in a lane that came with exec 0 + self.sym.pop(n) + if 'heapwords' in MESH_FEATURES and 'heap' in getattr(self.pipe, 'features', ()): + d = reg_range(ops[0]) + own = self.sym.get(d[1]) if d and d[0] == 's' else None + for t in ops[1:]: + r = reg_range(t) + if not r or r[0] != 's': + continue + for n in range(r[1], r[2] + 1): + s = self.sym.get(n) + if (s and s[0] == 'desc' and isinstance(s[1], tuple) and s[1][0] == 'heapdyn' and s[2] == 0 + and s != own): + swapped[n] = s + self.sym[n] = ('hword', s[1][1], s[3]) + if swapped: + self.pipe.heapwords = True + edits = sum(len(v) for v in getattr(self.pipe, 'modified_words', {}).values()) + try: + term = self.scalar_inner(base, ops) + if 'descword' in MESH_FEATURES and sum(len(v) for v in getattr(self.pipe, 'modified_words', {}).values()) > edits: + # the base recorded an in-place edit of a descriptor word (whatever the other operands): s keeps the + # symbol but not the table's value (dw_word refuses its numeric use until it is written otherwise) + d = reg_range(ops[0]) + if d and d[0] == 's': + for n in range(d[1], d[2] + 1): + self.dw_mark_edit(n) + return term + finally: + for n, s in swapped.items(): + if self.sym.get(n) == ('hword', s[1][1], s[3]): + self.sym[n] = s + for n in off_regs: + if n not in scalar_regs(ops[0]): + self.sym[n] = ('conflict',) + + def scalar_inner(self, base, ops): + dst = reg_range(ops[0]) + src = reg_range(ops[1]) if len(ops) >= 2 else None + if (base == 's_mov_b32' and len(ops) == 2 and dst and src and dst[0] == src[0] == 's' + and dst[1] == dst[2] and src[1] == src[2] and self.sym.get(src[1]) == ('conflict',)): + # Also used for either dword of an SGPR pair. Copy its numeric backing where it + # exists, retaining the conflict so numeric users still need a proof on every path. + masked = src[1] in self.masks + self.used_s.add(src[1]) + self.set_s(dst[1], 's%d' % src[1]) + self.sym[dst[1]] = ('conflict',) + self.exec_off.discard(dst[1]) + getattr(self, 'execzero', {}).pop(dst[1], None) + if masked: + self.masks.add(dst[1]) + return None + symbol = self.sym.get(src[1]) if src and src[0] == 's' else None + if dst and dst[0] == 's' and symbol and symbol[0] in ('code_lo', 'code_hi'): + if base == 's_mov_b32': + self.set_s(dst[1], None, symbol) + return + if base == 's_add_u32' and symbol[0] == 'code_lo' and re.fullmatch(r'0x[0-9a-f]+|\d+', ops[2]): + self.set_s(dst[1], None, ('code_lo', symbol[1] + int(ops[2], 0))) + return + if base == 's_bcnt1_i32_b32' and len(ops) == 2 and self.is_tainted(ops[1]): + # a scalar that depends on lane masks holds this lane's share of a wave value: its count is not the wave's + raise Unsupported('s_bcnt1_i32_b32 of a value that depends on lane masks') + dname = ops[0] + r0 = reg_range(dname) + if dname == 'm0': + text, _ = G.SCA[base] + srcs = [('s%d' % reg_range(t)[1]) if reg_range(t) and reg_range(t)[0] == 's' else t for t in ops[1:]] + self.emit('m0 = %s;' % text.format(*[self.u(t) for t in srcs])) + return None + # restoring exec from a copy taken while every lane was active makes every lane active again; + # s_mov_b64 exec, -1 (the program's first instruction) activates all 64 lanes, which all exist + # (128 threads = two full waves) + if dname == 'exec' and base == 's_mov_b64': + if re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', ops[1]): + self.set_exec_static(int(ops[1], 0)) + return None + src = reg_range(ops[1]) + if src and src[0] == 's' and src[1] in self.static_copies: + self.set_exec_static(self.static_copies[src[1]]) + return None + if src and src[0] == 's' and self.sym.get(src[1]) == ('execcopy',): + self.set_exec_static(ALL_LANES) + return None + if base == 's_mov_b64' and len(ops) == 2 and ops[1] == 'exec' and self.exec_static is not None: + d = reg_range(dname) + if d and d[0] == 's': + mask = self.exec_static + term = super().scalar(base, ops) + self.static_copies[d[1]] = mask + return term + if r0 and r0[0] == 's': + for t in ops[1:]: + rr = reg_range(t) + if rr and rr[0] == 's' and self.sym.get(rr[1]) == ('waveinfo',): + raise Unsupported('merged_wave_info used by %s' % base) + if dname == 'null': + # the null destination discards the result; only SCC would change, and the moves seen write none + if base not in ('s_mov_b32', 's_mov_b64'): + raise Unsupported('%s to null' % base) + return None + if not r0 and dname not in ('exec', 'exec_lo', 'vcc', 'vcc_lo'): + raise Unsupported('%s to %s' % (base, dname)) + if self.dw_scalar(base, ops): + return None + if DATA_PAIRS and base == 's_mov_b64' and r0 and r0[0] == 's' and len(ops) == 2: + src = reg_range(ops[1]) + if (src and src[0] == 's' and src[2] == src[1] + 1 and r0[2] == r0[1] + 1 + and (src[1] not in self.masks or self.sym.get(src[2]) == ('conflict',))): + # Copy both halves. A modeled lane mask keeps its lane bit in the low register; + # an unresolved upper half remains unreadable as numeric data after the move. + # If the ranges overlap, read the shared source before overwriting it. + order = (1, 0) if r0[1] == src[2] else (0, 1) + for offset in order: + self.scalar_inner('s_mov_b32', ['s%d' % (r0[1] + offset), 's%d' % (src[1] + offset)]) + return None + return super().scalar(base, ops) + + def op_s_getpc_b64(self, ops, mods): + # Keep the two address halves symbolic. Numeric uses remain unsupported, + # since the guest code's original GPU virtual address is unknown. + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[2] != dst[1] + 1: + raise Unsupported('getpc destination is not a scalar register pair') + self.set_s(dst[1], None, ('code_lo', self.pc + 4)) + self.set_s(dst[2], None, ('code_hi',)) + + def copied_constant(self, reg): + """Follow SGPR copies over every predecessor to the load. Every reaching + definition must agree on a literal. An entry input or other definition is unknown. + """ + if self.is_const(reg) is not None: + return self.is_const(reg) + if not hasattr(self, '_literal_predecessors'): + if any(name.startswith(('s_call', 's_setpc', 's_swappc', 's_rfe', 's_movrel')) + for _, _, name, _ in self.ins): + return None + self._literal_index = {off: i for i, (off, _, _, _) in enumerate(self.ins)} + self._literal_predecessors = {off: [] for off in self._literal_index} + self._literal_predecessors[self.ins[0][0]].append(None) + for off, targets in self.range_successors().items(): + for target in targets: + self._literal_predecessors[target].append(off) + todo = [(off, reg) for off in self._literal_predecessors[self.pc]] + seen, values = set(), set() + while todo: + off, source = todo.pop() + if off is None: + return None + if (off, source) in seen: + continue + seen.add((off, source)) + _, _, name, asm = self.ins[self._literal_index[off]] + if source in (106, 107) and reads_writes(name, asm)[2]: + return None + if source in self.pair_writes(name, asm): + ops = parse(asm)[1] + if name not in ('s_mov_b32', 's_mov_b64', 's_movk_i32') or len(ops) != 2: + return None + dst, src = map(reg_range, ops) + if not dst or not dst[1] <= source <= dst[2]: + return None + if src and src[0] == 's' and src[2] - src[1] == dst[2] - dst[1]: + source = src[1] + source - dst[1] + elif name != 's_mov_b64' and re.fullmatch(r'0x[0-9a-f]+|-?[0-9]+', ops[1]): + literal = G.sopk_simm(ops[1]) if name == 's_movk_i32' else ops[1] + values.add(int(literal, 0) & 0xffffffff) + if len(values) > 1: + return None + continue + else: + return None + todo.extend((previous, source) for previous in self._literal_predecessors[off]) + return next(iter(values)) if len(values) == 1 else None + + def scalar_literal_index_bits(self, index): + """Accept a contiguous BFE, LSHL-by-two, DWORD-load sequence with no + intervening index writes or branches into the sequence after the BFE. + """ + targets = self.branch_targets() + i = next(i for i, ins in enumerate(self.ins) if ins[0] == self.pc) + if self.pc in targets: + return None + i -= 1 + while i >= 0 and self.ins[i][2] == 's_buffer_load_dword': + off, _, _, asm = self.ins[i] + if off in targets or index == parse(asm)[1][0]: + return None + i -= 1 + if i < 1: + return None + off, _, shift, asm = self.ins[i] + if off in targets or shift != 's_lshl_b32' or parse(asm)[1] != [index, index, '2']: + return None + _, _, extract, asm = self.ins[i - 1] + ops = parse(asm)[1] + if extract != 's_bfe_u32' or ops[0] != index or not re.fullmatch(r'0x[0-9a-f]+', ops[2]): + return None + return (int(ops[2], 0) >> 16) & 0x7f + + def scalar_literal_load(self, ops, mods, count, desc, base): + register = desc[1] + size = self.copied_constant(register + 2) + if (count != 1 or desc[2] != register + 3 or self.sym.get(register + 1) != ('code_hi',) + or self.copied_constant(register + 3) != 0x31016fac or not size or size % 4 + or base < 0 or base % 4 or base + size > len(self.raw)): + raise Unsupported('incomplete scalar PC-relative raw buffer descriptor at %#x' % self.pc) + if len(mods) > 1 or any(not re.fullmatch(r'offset:0x[0-9a-f]+', m) for m in mods): + raise Unsupported('unsupported scalar literal table modifiers') + extra = int(mods[0][7:], 0) if mods else 0 + bits = self.scalar_literal_index_bits(ops[2]) + if bits is None or bits > 30 or extra % 4 or extra + (1 << bits) * 4 > size: + raise Unsupported('scalar literal table index unproven or outside descriptor at %#x' % self.pc) + table = self.literal_tables.setdefault((base, size), 'x2w_literals_%x_%x' % (base, size)) + self.set_s(reg_range(ops[0])[1], '%s[(%s >> 2u) + %du]' % (table, self.u(ops[2]), extra // 4)) + + def op_buffer_load_dword(self, ops, mods, count=1): + desc = reg_range(ops[2]) + low = self.sym.get(desc[1]) if desc else None + if not low or low[0] != 'code_lo': + return super().op_buffer_load_dword(ops, mods, count) + reg = desc[1] + size = self.is_const(reg + 2) + if (self.sym.get(reg + 1) != ('code_hi',) or self.is_const(reg + 3) != 0x31016fac + or not size or size % 4 or low[1] % 4 or low[1] < 0 or low[1] + size > len(self.raw)): + raise Unsupported('incomplete PC-relative raw buffer descriptor at %#x' % self.pc) + offsets = [int(m[7:], 0) for m in mods if m.startswith('offset:')] + if (count != 1 or ops[3] != '0' or 'offen' not in mods + or any(m != 'offen' and not m.startswith('offset:') for m in mods)): + raise Unsupported('PC-relative buffer load uses unsupported addressing') + key = (low[1], size) + table = self.literal_tables.setdefault(key, 'x2w_literals_%x_%x' % key) + offset = sum(offsets) + if offset % 4: + raise Unsupported('unaligned literal table instruction offset') + # RDNA2 raw DWORD addressing ignores the low two address bits. + # Compare before adding the immediate so a large VGPR cannot wrap. + self.emit('a = %s >> 2u;' % self.u(ops[1])) + value = '0u' if offset >= size else '(a < %du ? %s[min(a, %du) + %du] : 0u)' % ( + (size - offset) // 4, table, (size - offset) // 4 - 1, offset // 4) + self.set_v(reg_range(ops[0])[1], value) + + def op_s_bfe_u32(self, ops, mods): + src = reg_range(ops[1]) + if src and src[0] == 's' and self.sym.get(src[1]) == ('waveinfo',): + if ops[2] != '0x40018': + raise Unsupported('merged_wave_info field %s' % ops[2]) + self.set_s(reg_range(ops[0])[1], 'wave') + return None + return self.scalar('s_bfe_u32', ops) + + def op_s_bfe_i32(self, ops, mods): + # D = sext(S0 >> S1[4:0]) of width S1[22:16]; a width of 0 gives 0 (RDNA 2 ISA, S_BFE_I32). + a, b = self.u(ops[1]), self.u(ops[2]) + expr = ('((({1} >> 16) & 127u) == 0u ? 0u : asuint(asint({0} << (32u - min(({1} & 31u) + (({1} >> 16) & 127u), 32u))) ' + '>> (32u - min(({1} & 31u) + (({1} >> 16) & 127u), 32u) + ({1} & 31u))))').format(a, b) + self.set_s(reg_range(ops[0])[1], expr, scc='$ != 0') + + def op_s_bitset1_b32(self, ops, mods): + d = reg_range(ops[0])[1] + own = self.sym.get(d) + if own and own[0] in ('ptrhi', 'descnum'): + # a descriptor word built from a root pointer (stride / swizzle bits): keeps its descriptor meaning + self.sym[d] = ('descnum',) if own[0] == 'descnum' else own + return None + self.set_s(d, '%s | (1u << (%s & 31u))' % (self.S(d), self.u(ops[1]))) + + def op_s_bitset0_b32(self, ops, mods): + # RDNA 2 ISA S_BITSET0_B32: D.u[S0.u[4:0]] = 0 (no SCC); a descriptor word is refused (no rule for it) + d = reg_range(ops[0])[1] + own = self.sym.get(d) + if own and own[0] not in ('const', 'fixed_buffer_word'): + raise Unsupported('s_bitset0_b32 on s%d holding %s' % (d, own[0])) + self.set_s(d, '%s & ~(1u << (%s & 31u))' % (self.S(d), self.u(ops[1]))) + + # s_pack_{lh,hl,hh}_b32_b16: D = low half from S0 (l = bits 15:0, h = bits 31:16), high half from S1 + # (RDNA 2 ISA, S_PACK_*). s_pack_ll is in the base table. + def pack(self, ops, text): + d = reg_range(ops[0]) + if not d or d[0] != 's': + raise Unsupported('s_pack to %s' % ops[0]) + self.masks.discard(d[1]) + self.set_s(d[1], text.format(self.u(ops[1]), self.u(ops[2]))) + + def op_s_pack_lh_b32_b16(self, ops, mods): + self.pack(ops, '(({0} & 0xffffu) | ({1} & 0xffff0000u))') + + def op_s_pack_hl_b32_b16(self, ops, mods): + self.pack(ops, '(({0} >> 16) | ({1} << 16))') + + def op_s_pack_hh_b32_b16(self, ops, mods): + self.pack(ops, '(({0} >> 16) | ({1} & 0xffff0000u))') + + # v_min3 / v_max3 / v_med3 on integers (RDNA 2 ISA): three-way min, max, median + def three(self, ops, fn, signed): + a, b, c = [self.u(o) for o in ops[1:4]] + if signed: + a, b, c = ['asint(%s)' % x for x in (a, b, c)] + expr = {'min': 'min(min({0}, {1}), {2})', 'max': 'max(max({0}, {1}), {2})', + 'med': 'max(min({0}, {1}), min(max({0}, {1}), {2}))'}[fn].format(a, b, c) + self.set_v(reg_range(ops[0])[1], 'asuint(%s)' % expr if signed else expr) + + def op_v_min3_u32(self, ops, mods): + self.three(ops, 'min', False) + + def op_v_max3_u32(self, ops, mods): + self.three(ops, 'max', False) + + def op_v_med3_u32(self, ops, mods): + self.three(ops, 'med', False) + + def op_v_min3_i32(self, ops, mods): + self.three(ops, 'min', True) + + def op_v_max3_i32(self, ops, mods): + self.three(ops, 'max', True) + + def op_v_med3_i32(self, ops, mods): + self.three(ops, 'med', True) + + SEL = {'BYTE_0': (0, 8), 'BYTE_1': (8, 8), 'BYTE_2': (16, 8), 'BYTE_3': (24, 8), 'WORD_0': (0, 16), + 'WORD_1': (16, 16), 'DWORD': (0, 32)} + + def sdwa_src(self, tok, sel): + sx = tok.startswith('sext(') and tok.endswith(')') + u = self.u(tok[5:-1] if sx else tok) + sh, w = self.SEL[sel] + if w == 32: + return u + if sx: + return 'asuint(asint(%s << %du) >> %du)' % (u, 32 - sh - w, 32 - w) + return '((%s >> %du) & 0x%xu)' % (u, sh, (1 << w) - 1) + + def op_v_mov_b32_sdwa(self, ops, mods): + """D = the selected field of S0 placed at dst_sel; other bits zero (UNUSED_PAD) or kept (UNUSED_PRESERVE) + (RDNA 2 ISA, SDWA).""" + f = dict(m.partition(':')[::2] for m in mods) + if set(f) - {'dst_sel', 'dst_unused', 'src0_sel'} or len(ops) != 2: + raise Unsupported('v_mov_b32_sdwa with %s' % mods) + d = reg_range(ops[0])[1] + sh, w = self.SEL[f.get('dst_sel', 'DWORD')] + val = '((%s & 0x%xu) << %du)' % (self.sdwa_src(ops[1], f.get('src0_sel', 'DWORD')), (1 << w) - 1 if w < 32 else 0xffffffff, sh) + unused = f.get('dst_unused', 'UNUSED_PAD') + if unused == 'UNUSED_PRESERVE': + keep = 0xffffffff & ~((((1 << w) - 1) << sh)) + val = '(%s | (v%d & 0x%08xu))' % (val, d, keep) + self.used_v.add(d) + elif unused != 'UNUSED_PAD': + raise Unsupported('v_mov_b32_sdwa %s' % unused) + self.set_v(d, val) + + def op_v_cmp_class_f32_sdwa(self, ops, mods): + """V_CMP_CLASS_F32 (SDWA, VOPC into an SGPR mask): bit class(S0) of the selected S1 field; class bits 0 sNaN, + 1 qNaN, 2 -inf, 3 -normal, 4 -denormal, 5 -0, 6 +0, 7 +denormal, 8 +normal, 9 +inf (RDNA 2 ISA).""" + f = dict(m.partition(':')[::2] for m in mods) + if set(f) - {'src0_sel', 'src1_sel'} or f.get('src0_sel', 'DWORD') != 'DWORD' or len(ops) != 3: + raise Unsupported('v_cmp_class_f32_sdwa with %s %s' % (ops, mods)) + x = self.u(ops[1]) + mask = self.sdwa_src(ops[2], f.get('src1_sel', 'DWORD')) + return self.write_compare(False, ops[0], '((%s >> x2w_fclass(%s)) & 1u)' % (mask, x)) + + def op_v_cmp_class_f16_sdwa(self, ops, mods): + """V_CMP_CLASS_F16 (SDWA, VOPC into an SGPR mask): the selected 16-bit field of S0 with its abs/neg applied + to bit 15 (as the e64 form, base x2w_class_f16), S1 the class mask (DWORD).""" + f = dict(m.partition(':')[::2] for m in mods) + if set(f) - {'src0_sel', 'src1_sel'} or f.get('src1_sel', 'DWORD') != 'DWORD' or len(ops) != 3: + raise Unsupported('v_cmp_class_f16_sdwa with %s %s' % (ops, mods)) + tok = ops[1] + neg, ab = tok.startswith('-'), '|' in tok + reg = tok.strip('-|') + if not reg_range(reg) or f.get('src0_sel', 'DWORD') not in ('WORD_0', 'WORD_1', 'DWORD'): + raise Unsupported('v_cmp_class_f16_sdwa source %s %s' % (tok, mods)) + x = '(%s & 0xffffu)' % self.sdwa_src(reg, f.get('src0_sel', 'DWORD')) + if ab: + x = '(%s & 0x7fffu)' % x + if neg: + x = '(%s ^ 0x8000u)' % x + return self.write_compare(False, ops[0], 'x2w_class_f16(%s, %s)' % (x, self.u(ops[2]))) + + def compare(self, base, ops, mods=()): + """16-bit integer compares (v_cmp[x]__{i16,u16}, e32/e64 without modifiers): the low halves, + sign- or zero-extended, compared as 32-bit integers; everything else as the base translator.""" + m = re.fullmatch(r'v_cmp(x?)_(\w+?)_(i16|u16)', base) + if not m: + return super().compare(base, ops, mods) + if mods or any(t.startswith(('-', '|')) for t in ops): + raise Unsupported('%s with modifiers %s' % (base, mods)) + writes_exec, cond, typ = m.group(1) == 'x', m.group(2), m.group(3) + if len(ops) == 3: + dst, a, b = ops + elif len(ops) == 2: + dst, (a, b) = ('exec' if writes_exec else 'vcc'), ops + else: + raise Unsupported('%s with %d operands' % (base, len(ops))) + if typ == 'i16': + x, y = ('(asint(%s << 16u) >> 16)' % self.u(t) for t in (a, b)) + else: + x, y = ('(%s & 0xffffu)' % self.u(t) for t in (a, b)) + return self.compare_result(base.replace(typ, 'i32' if typ == 'i16' else 'u32'), cond, writes_exec, dst, x, y) + + def image(self, ops, mods, how): + """d16 image results: the channels the base computes as binary32 are packed two per VGPR as binary16, + the first in the low half, the unused half of an odd last register 0 (gfx10 packed D16). Only for the + float views the base binds (Texture*); the base refuses the other result modifiers.""" + if 'd16' not in mods: + return super().image(ops, mods, how) + dmask = int([m for m in mods if m.startswith('dmask:')][0][6:], 0) + n = bin(dmask & 15).count('1') + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[2] - dst[1] + 1 != (n + 1) // 2: + raise Unsupported('d16 image result %s for dmask %#x' % (ops[0], dmask)) + tmp = 1000 # HLSL-only scratch VGPRs (the console has 256) + super().image([('v[%d:%d]' % (tmp, tmp + n - 1)) if n > 1 else 'v%d' % tmp] + list(ops[1:]), [m for m in mods if m != 'd16'], how) + for j in range((n + 1) // 2): + lo = 'f32tof16(asfloat(v%d))' % (tmp + 2 * j) + hi = '(f32tof16(asfloat(v%d)) << 16)' % (tmp + 2 * j + 1) if 2 * j + 1 < n else '0u' + self.set_v(dst[1] + j, '(%s | %s)' % (lo, hi)) + + def op_v_bfm_b32(self, ops, mods): + """V_BFM_B32: D = ((1 << S0[4:0]) - 1) << S1[4:0] (RDNA 2 ISA).""" + if mods or len(ops) != 3: + raise Unsupported('v_bfm_b32 form %s %s' % (ops, mods)) + self.set_v(reg_range(ops[0])[1], '(((1u << (%s & 31u)) - 1u) << (%s & 31u))' % (self.u(ops[1]), self.u(ops[2]))) + + def carry_op(self, base, ops, mods): + """v_add_co_u32 / v_sub_co_u32 / v_subrev_co_u32 and the _ci forms: D, carry-out mask, S0, S1[, carry-in mask]. + Add: sum = S0 + S1 + cin (mod 2^32), carry = cin ? sum <= S0 : sum < S0. Sub: d = S0 - S1 - bin, borrow = + bin ? d >= S0 : d > S0 (subrev swaps the sources). Both read only S0, the result and the carry-in, so the + carry-in may be the destination mask. The carry is the lane's bit of the destination mask.""" + m = CARRY.fullmatch(base) + if mods or len(ops) != (5 if m.group(2) else 4): + raise Unsupported('%s form %s %s' % (base, ops, mods)) + x, y = self.u(ops[2]), self.u(ops[3]) + if m.group(1) == 'subrev': + x, y = y, x + cin = '(%s & 1u)' % self.u(ops[4]) if m.group(2) else '0u' + if m.group(1) == 'add': + self.emit('a = %s; w = a + %s + %s;' % (x, y, cin)) + carry = '((%s != 0u ? w <= a : w < a) ? 1u : 0u)' % cin + else: + self.emit('a = %s; w = a - %s - %s;' % (x, y, cin)) + carry = '((%s != 0u ? w >= a : w > a) ? 1u : 0u)' % cin + dst = ops[1] + if dst.startswith('vcc'): + dst = 'vcc' + else: + r = reg_range(dst) + if not r or r[0] != 's': + raise Unsupported('%s carry to %s' % (base, dst)) + dst = 's%d' % r[1] + self.write_compare(False, dst, carry) + self.set_v(reg_range(ops[0])[1], 'w') + + def op_v_mbcnt_lo_u32_b32(self, ops, mods): + self.set_v(reg_range(ops[0])[1], 'x2w_mbcnt_lo(%s, lane) + %s' % (self.u(ops[1]), self.u(ops[2]))) + + def op_v_mbcnt_hi_u32_b32(self, ops, mods): + self.set_v(reg_range(ops[0])[1], 'x2w_mbcnt_hi(%s, lane) + %s' % (self.u(ops[1]), self.u(ops[2]))) + + def op_v_perm_b32(self, ops, mods): + if mods: + raise Unsupported('v_perm_b32 with %s' % mods) + self.set_v(reg_range(ops[0])[1], 'x2w_perm(%s, %s, %s)' % (self.u(ops[1]), self.u(ops[2]), self.u(ops[3]))) + + def op_v_pack_b32_f16(self, ops, mods): + sel = [0, 0, 0] + for m in mods: + if m.startswith('op_sel:['): + sel = [int(x) for x in m[8:-1].split(',')] + else: + raise Unsupported('v_pack_b32_f16 with %s' % m) + if any(t.startswith(('-', '|')) for t in ops[1:3]): + raise Unsupported('v_pack_b32_f16 with source modifiers') + lo = '(%s >> 16)' % self.h(ops[1]) if sel[0] else self.h(ops[1]) + hi = '(%s >> 16)' % self.h(ops[2]) if sel[1] else self.h(ops[2]) + self.set_v(reg_range(ops[0])[1], '(%s & 0xffffu) | ((%s & 0xffffu) << 16)' % (lo, hi)) + + def op_v_readfirstlane_b32(self, ops, mods): + src, dst = reg_range(ops[1]), reg_range(ops[0]) + if mods or not dst or dst[0] != 's' or not src or src[0] != 'v': + raise Unsupported('v_readfirstlane_b32 form %s' % ops) + self.masks.discard(dst[1]) # a number now, not a lane mask (s_or of it must not be masked to bit 0) + if src[1] == 5 and 5 not in self.written_v: + # v5 = group * 128 + thread (inferred fast-launch vertex id); the wave's first lane is its thread & ~63 + # (`wbase` = the wave's first thread: the same in every lane of a wave, so not lane-tainted) + self.set_s(dst[1], '(gid * %du + wbase)' % GROUP) + return None + shadow = self.shadow.get(src[1]) + read_mask = ALL_LANES if self.exec_known else self.exec_static + if shadow and read_mask: + first = (read_mask & -read_mask).bit_length() - 1 + if (shadow[1] >> first) & 1: + # the first active lane wrote this wave-uniform value: every thread takes it from the shadow + self.set_s(dst[1], shadow[0]) + return None + # A source that is the same in every active lane: each active lane's own value is the first active lane's + # (the result is then active-uniform itself, through emit). + if self.lane_dependent('v%d' % src[1]): + # Lane-dependent source: the console wave reads its first active lane. With every lane active and + # no per-lane region open (so every thread of the group reaches this statement, a group barrier is + # legal), that lane is the wave's first thread: broadcast through groupshared memory. + if not self.exec_known or self.pc < self.divergent_until: + text = 'v_readfirstlane_b32 of a lane-dependent v%d with lanes off at %#x (%s)' % ( + src[1], self.pc, 'in a per-lane range' if self.pc < self.divergent_until else 'partial exec') + if not RFL_FIRST: + raise Unsupported(text) + if any(t <= self.pc < o for o, t in self.backward_branches()): + # inside a loop: the trip count may differ between the waves of a group, so a group barrier + # there is not reached by every thread the same number of times (a waterfall loop over a + # per-lane index is mesh4's lowering, without a barrier) + raise Unsupported(text.replace('lanes off at', 'lanes off inside a loop at')) + if self.pc < self.divergent_until: + # not every thread reaches the read: ask for the innermost execz range around it to be run by + # the whole group (once; a range already run so, or a per-lane range of another kind, refuses) + around = [o for o, t in self.execz_ranges() if o < self.pc < t] + if around and max(around) not in self.group_branches(): + raise NeedGroupRange(max(around), text) + raise Unsupported(text) + return self.first_active_broadcast(src, dst, ops) + # The group barrier is a phase boundary of the body (see body()): the read starts the next block, so + # that block must not also be entered by a branch. + nxt = self.next_offset() + if nxt in self.branch_targets(): + raise Unsupported('v_readfirstlane_b32 broadcast followed by a branch target at %#x' % self.pc) + slot = self.broadcasts + self.broadcasts += 1 + self.emit('if (lane == 0u) x2w_rfl[%d][wave] = %s;' % (slot, self.u(ops[1]))) + self.sym.pop(dst[1], None) + self.used_s.add(dst[1]) + self.pending.append('s%d = x2w_rfl[%d][wave];' % (dst[1], slot)) + self.tainted.discard('s%d' % dst[1]) + self.au.pop('s%d' % dst[1], None) + self.au_xs.pop('s%d' % dst[1], None) + self.lds_written_in_phase = False + return ('barrier',) + self.set_s(dst[1], self.u(ops[1])) + if self.is_tainted('v%d' % src[1]): + self.au_scalars[dst[1]] = self.epoch + + def backward_branches(self): + """(branch offset, target) of every branch whose target is not after it (the loops of the program).""" + out = [] + for o, n, name, asm in self.ins: + if name.startswith(('s_branch', 's_cbranch_')): + args = parse(asm)[1] + if args and args[0].startswith('label_'): + t = int(args[0].split('_')[1], 16) + if t <= o: + out.append((o, t)) + return out + + def execz_ranges(self): + """(branch offset, target) of the forward s_cbranch_execz ranges of the program.""" + out = [] + for o, n, name, asm in self.ins: + if name == 's_cbranch_execz': + t = int(parse(asm)[1][0].split('_')[1], 16) + if t > o: + out.append((o, t)) + return out + + def first_active_broadcast(self, src, dst, ops): + """v_readfirstlane_b32 sD, vS of a lane-dependent vS under a partial exec, reached by every thread of the + group (no per-lane range open). The console wave reads the lane with the lowest index whose EXEC bit is set + (RDNA 2 ISA V_READFIRSTLANE_B32; with EXEC = 0 it reads lane 0 [ASSUMED from the ISA text, not measured]). + Every thread stores its vS (an inactive lane's VGPR keeps its old value, as here) and its exec bit in + groupshared memory, a group barrier follows, and the next block reads the first set bit's value of the + thread's own wave (x2w_rfirst). Refused: more than RFL_FIRST_SLOTS such reads, and a branch target right + after the read (the barrier is a phase boundary of the body, as for the lane-0 broadcast).""" + nxt = self.next_offset() + if nxt in self.branch_targets(): + raise Unsupported('v_readfirstlane_b32 broadcast followed by a branch target at %#x' % self.pc) + if self.first_slots >= RFL_FIRST_SLOTS: + raise Unsupported('more than %d first-active-lane v_readfirstlane_b32 reads' % RFL_FIRST_SLOTS) + k = self.first_slots + self.first_slots += 1 + self.emit('x2w_rfv[%d][tid] = %s;' % (k, self.u(ops[1]))) + self.emit('x2w_rfe[%d][tid] = exec & 1u;' % k) + self.sym.pop(dst[1], None) + self.used_s.add(dst[1]) + self.pending.append('s%d = x2w_rfirst(%du, wbase);' % (dst[1], k)) + self.tainted.discard('s%d' % dst[1]) + self.au.pop('s%d' % dst[1], None) + self.au_xs.pop('s%d' % dst[1], None) + self.lds_written_in_phase = False + return ('barrier',) + + def op_s_buffer_load_dword(self, ops, mods, count=1): + """As the pipeline translator, plus: the offset is read once before the destination is written (the + title's `s_buffer_load_dwordx2 s[4:5], s[16:19], s4` overwrote s4 before the second word), the + instruction's offset:N is added, and the address is dword aligned (the hardware ignores bits 1:0).""" + G.smem_imm_refuse('s_buffer_load', ops, mods) + desc = reg_range(ops[1]) + origin = self.sym.get(desc[1]) if desc else None + if origin and origin[0] == 'code_lo': + return self.scalar_literal_load(ops, mods, count, desc, origin[1]) + extra = 0 + for m in mods: + if m.startswith('offset:'): + extra += int(m[7:], 0) + else: + raise Unsupported('s_buffer_load with %s' % m) + dst = reg_range(ops[0]) + buf = self.pipe.resource(self.descriptor(ops[1]), 'buf') + fixed = re.fullmatch(r'0x[0-9a-f]+|\d+', ops[2]) + if fixed: + base = '%du' % ((int(ops[2], 0) + extra) & ~3) + else: + self.emit('a = (%s + %du) & ~3u;' % (self.u(ops[2]), extra)) + base = 'a' + for i in range(count): + self.set_s(dst[1] + i, '%s.Load(%s + %d)' % (buf, base, 4 * i)) + if fixed: + self.sym[dst[1] + i] = ('fixed_buffer_word',) + + # Typed buffer formats the pipeline translator's table lacks. SNORM: max(x / (2^(n-1) - 1), -1) (RDNA 2 ISA + # data-format conversion). 2_10_10_10 lists fields from the most significant: x is bits 9:0 and w bits 31:30 + # (Mesa gfx10_format_table.py maps R10G10B10A2 to 2_10_10_10). + MESH_FORMATS = { + 'BUF_FMT_16_16_SNORM': ('ldu({0}, a)', ['U(max(float(asint(w << 16) >> 16) / 32767.0, -1.0))', + 'U(max(float(asint(w) >> 16) / 32767.0, -1.0))', '0u', 'U(1.0)']), + 'BUF_FMT_16_16_16_16_SNORM': ('ldu({0}, a)', ['U(max(float(asint(w << 16) >> 16) / 32767.0, -1.0))', + 'U(max(float(asint(w) >> 16) / 32767.0, -1.0))', + 'U(max(float(asint(ldu({0}, a + 4) << 16) >> 16) / 32767.0, -1.0))', + 'U(max(float(asint(ldu({0}, a + 4)) >> 16) / 32767.0, -1.0))']), + 'BUF_FMT_16_16_16_16_UNORM': ('ldu({0}, a)', ['U((w & 65535) / 65535.0)', 'U((w >> 16) / 65535.0)', + 'U((ldu({0}, a + 4) & 65535) / 65535.0)', + 'U((ldu({0}, a + 4) >> 16) / 65535.0)']), + 'BUF_FMT_8_8_8_8_SNORM': ('ldu({0}, a)', ['U(max(float(asint(w << 24) >> 24) / 127.0, -1.0))', + 'U(max(float(asint(w << 16) >> 24) / 127.0, -1.0))', + 'U(max(float(asint(w << 8) >> 24) / 127.0, -1.0))', + 'U(max(float(asint(w) >> 24) / 127.0, -1.0))']), + 'BUF_FMT_2_10_10_10_UNORM': ('ldu({0}, a)', ['U((w & 1023) / 1023.0)', 'U(((w >> 10) & 1023) / 1023.0)', + 'U(((w >> 20) & 1023) / 1023.0)', 'U((w >> 30) / 3.0)']), + # integer formats: the register gets the integer; missing components read 0, w reads 1 (as the float + # formats' 1.0) + 'BUF_FMT_8_8_8_8_UINT': ('ldu({0}, a)', ['w & 255u', '(w >> 8) & 255u', '(w >> 16) & 255u', 'w >> 24']), + 'BUF_FMT_8_8_UINT': ('ldu({0}, a)', ['w & 255u', '(w >> 8) & 255u', '0u', '1u']), + 'BUF_FMT_16_16_UINT': ('ldu({0}, a)', ['w & 65535u', 'w >> 16', '0u', '1u']), + 'BUF_FMT_16_UINT': ('ldu({0}, a)', ['w & 65535u', '0u', '0u', '1u']), + 'BUF_FMT_16_16_16_16_UINT': ('ldu({0}, a)', ['w & 65535u', 'w >> 16', 'ldu({0}, a + 4) & 65535u', + 'ldu({0}, a + 4) >> 16']), + 'BUF_FMT_32_UINT': ('ldu({0}, a)', ['w', '0u', '0u', '1u']), + 'BUF_FMT_32_32_UINT': ('ldu({0}, a)', ['w', 'ldu({0}, a + 4)', '0u', '1u']), + 'BUF_FMT_32_32_32_32_UINT': ('ldu({0}, a)', ['w', 'ldu({0}, a + 4)', 'ldu({0}, a + 8)', 'ldu({0}, a + 12)']), + } + + def tbuffer(self, ops, mods, count): + formats = [m for m in mods if m.startswith('format:')] + fmt = formats[0][8:-1] if formats else None + if fmt not in self.MESH_FORMATS: + return super().tbuffer(ops, mods, count) + dst = reg_range(ops[0]) + buf, address = self.buffer_address(ops, [m for m in mods if not m.startswith('format:')]) + self.emit('a = %s;' % address) + load, comps = self.MESH_FORMATS[fmt] + self.emit('w = %s;' % load.format(buf)) + for i in range(count): + self.set_v(dst[1] + i, comps[i].format(buf)) + + def export(self, asm): + m = re.fullmatch(r'exp (\w+) (.*?)((?: done| compr| vm)*)', asm) + if not m: + raise Unsupported('export form %r' % asm) + target, vals = m.group(1), [v.strip() for v in m.group(2).split(',')] + if target in ('prim', 'target_20'): + if vals[0] == 'off' or any(v != 'off' for v in vals[1:]) or 'compr' in m.group(3): + raise Unsupported('primitive export form %r' % asm) + self.exported_prim = True + self.emit('if (exec & 1) { x2w_prim = %s; }' % self.u(vals[0])) + return None + if target == 'pos1' and self.pipe.vs_out_cntl is None: + # what pos1 carries (misc vector or clip/cull distances, and which channels) is pipeline state + raise Unsupported('mesh export target pos1 without PA_CL_VS_OUT_CNTL (request .vsout)') + if target not in ('pos0', 'pos1') and not target.startswith('param'): + raise Unsupported('mesh export target %s' % target) + before = len(self.lines) + self.kind = 'vs' # the base export only accepts pos/param outside a pixel stage + try: + super().export(asm) + finally: + self.kind = 'ms' + body = self.lines[before:] + del self.lines[before:] + self.lines.append('if (exec & 1) { %s }' % ' '.join(body)) + self.exported_vertex = True + return None + + +for _op in ('add', 'sub', 'subrev'): + for _ci in ('', '_ci'): + _name = 'v_%s_co%s_u32' % (_op, _ci) + setattr(MeshStage, 'op_' + _name, lambda self, ops, mods, _n=_name: self.carry_op(_n, ops, mods)) + + +def const_heap_sampler(stage, tok): + """'qh[]' for a sampler operand whose four words are one sampler-heap entry loaded at a constant byte + offset (`s_load_dwordx4 s[..], s[], 0x410`: a fixed entry of the title's bound sampler heap, as + the run programs read it), else None. + + The same table and manifest contract as the run-time offset form (gfx2hlsl heap_sampler; `smpheap 2048 1 + fallback 2047`: entry n = the title's heap entry at byte 16 * n, an unaligned or out-of-range offset takes the + fallback entry), so the stand-in binds it as for a draw. Opt-in with X2W_SAMPLER_HEAP=1 as that form is. + Refused: words edited in place after the load, or words from different loads.""" + r = reg_range(tok) + if not r or r[0] != 's' or r[2] - r[1] != 3: + return None + first = stage.sym.get(r[1]) + if not first or first[0] != 'desc' or first[1] != ('smpheap',) or first[2] is None: + return None + if not stage.pipe.sampler_heap: + raise Unsupported('sampler from the sampler heap at constant offset %#x (X2W_SAMPLER_HEAP=1 binds the heap)' + % (first[2] + 4 * first[3])) + if any(stage.sym.get(r[1] + i) != ('desc', first[1], first[2], first[3] + i) for i in range(4)): + raise Unsupported('sampler operand %s mixes sampler heap words' % tok) + if (first[1], first[2]) in stage.pipe.modified: + raise Unsupported('sampler heap entry at %#x edited in the shader' % (first[2] + 4 * first[3])) + offset = first[2] + 4 * first[3] + entry = offset >> 4 if offset % 16 == 0 and offset < 16 * G.SAMPLER_HEAP_FALLBACK else G.SAMPLER_HEAP_FALLBACK + stage.pipe.uses_sampler_heap = True + return 'qh[%du]' % entry + + +class MeshPixelStage(G.Stage): + """The pixel stage of a mesh pipeline: the base pixel stage plus constant sampler-heap entries.""" + + def heap_sampler(self, tok): + return super().heap_sampler(tok) or const_heap_sampler(self, tok) + + +class MeshPipeline(G.Pipeline): + """Mesh + pixel pipeline. ps_code None: the mesh stage alone (coverage runs; params = what it exports).""" + + def __init__(self, ms_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), user_sgpr=MESH_USER_SGPR, + ps_hw_inputs=None, vs_out_cntl=None): + self.root = G.parse_root(root_blob) + # First user SGPR: s16 for the run programs (measured, real roots). Archive programs (offline, synthesized + # root) may start at s8: callers pass entry_sgpr(code) together with synth_root(code). + self.user_sgpr = user_sgpr + # PA_CL_VS_OUT_CNTL of the pipeline (request .vsout; regblob .vsregs u32 at +0x98, +0x54 in mesh blocks), + # or None: what a pos1 export carries (G.clip_vector_width). None refuses pos1. + self.vs_out_cntl = vs_out_cntl + # Lane-mask SCCs to publish per wave: found by translating, refusing at the branch with the offsets of the + # mask instructions the SCC comes from (LaneScc), and translating again with those published. + self.scc_publish = frozenset() + for _ in range(8): + try: + self.build(ms_code, ps_code, sampler_heap, rtv_formats, ps_hw_inputs) + return + except LaneScc as refusal: + if not LANE_SCC or not refusal.origins or refusal.origins <= self.scc_publish: + raise Unsupported(str(refusal)) + if min(refusal.origins) < 0: + raise Unsupported('%s (through a non-mask op on a lane mask at %#x)' + % (refusal, -min(refusal.origins) - 1)) + self.scc_publish |= refusal.origins + raise Unsupported('lane-mask SCC: no fixed point after 8 translations') + + def build(self, ms_code, ps_code, sampler_heap, rtv_formats, ps_hw_inputs=None): + # Fields of G.Pipeline.__init__ (which this does not call: it builds a vertex stage) that newer base + # translators read. The draw lowerings (manifest `heap 1`, `udsrc bufword3`, `uav`) are named in + # X2W_DRAW_FEATURES as for draws (pstrans gfx2hlsl.draw_features); a base without them keeps refusing. + self.features = G.draw_features() if hasattr(G, 'draw_features') else frozenset() + self.heapvars = [] + self.heapwords = False # x2w_hword used (manifest `heapwords 1`) + self.rw_keys = frozenset() + # the pixel stage's SPI inputs (SPI_PS_INPUT_ENA/ADDR, request .psin), as for draws + self.spi_inputs(ps_hw_inputs) + self.quad_ops = True # the pixel stage compiles with dxc ps_6_0: DPP quad reads (gfx2hlsl Stage.quad_dpp) + self.rtv_formats = rtv_formats + self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap + self.uses_sampler_heap = False + self.resources, self.samplers, self.uds = {}, {}, [] + self.notes = set() + self.modified = set() + self.helper_text = None + self.rect = self.ud(('rect',)) + self.dw_src, self.dw_used, self.dw_text = [], set(), {} # descword placeholders (MeshStage.dw_word) + # A lane-dependent v_readfirstlane_b32 inside a per-lane execz range asks for that range to be run by the + # whole group (NeedGroupRange): translate again from the same state with it added (bounded: each range once). + self.force_group = frozenset() + fresh = copy.deepcopy(self.__dict__) + while True: + try: + self.vs = self.mesh_stage(ms_code) + break + except NeedGroupRange as e: + if e.off in self.force_group: + raise Unsupported(str(e)) + force = self.force_group | {e.off} + self.__dict__.clear() + self.__dict__.update(copy.deepcopy(fresh)) + self.force_group = force + # descword placeholders: a word some numeric use reached is an entry value (`udsrc descword

`), + # any other is dead arithmetic and reads 0u + self.dw_text = {k: ('ud%d' % self.ud(src) if k in self.dw_used else '0u') for k, src in enumerate(self.dw_src)} + self.ps = MeshPixelStage(self, 'ps', ps_code) if ps_code is not None else None + self.params = sorted(int(k[5:]) for k in self.vs.exports if k.startswith('param')) + if self.ps is not None: + self.spi_reads() + self.flat = sorted(a for a, how in self.ps.attrs.items() if 'flat' in how) + self.half = sorted(a for a, how in self.ps.attrs.items() if 'half' in how) + self.check_half_reads() + missing = [a for a in self.ps.attrs if a not in self.params] + if missing: + raise Unsupported('pixel stage reads attributes %s the mesh stage does not export' % missing) + else: + self.ps_entry_reads, self.flat, self.half = {}, [], [] + if 'pos' not in self.vs.exports: + raise Unsupported('mesh stage exports no position') + if not self.vs.exported_prim: + raise Unsupported('mesh stage exports no primitive') + + def mesh_stage(self, ms_code): + """The mesh stage, translated again (from the same pipeline state) until every loop head's state is the + join of its edges (MeshStage.loop_settled); refused when that does not settle within LOOP_PASSES.""" + self.loop_seed = {} + before = copy.deepcopy(self.__dict__) + for _ in range(LOOP_PASSES): + try: + return MeshStage(self, ms_code) + except LoopRetry as retry: + seeds = retry.backs + self.__dict__.clear() + self.__dict__.update(copy.deepcopy(before)) + self.loop_seed = seeds + raise Unsupported('loop state does not settle in %d passes' % LOOP_PASSES) + + def dw_sub(self, lines): + """The mesh stage's lines with the descword placeholders replaced (build()).""" + dw = getattr(self, 'dw_text', {}) + if not dw: + return lines + out = [re.sub(r'\bX2W_DW(\d+)\b', lambda m: dw[int(m.group(1))], line) for line in lines] + if any('X2W_DW' in line for line in out): + raise Unsupported('descword placeholder left in the mesh stage') + return out + + def common(self): + if self.helper_text is None: + self.helper_text = '\n'.join(self.dw_sub(self.vs.body()) + (self.ps.body() if self.ps else [])) + return super().common() + + def hlsl_ms(self, dump=False): + """The mesh shader. dump=True (tests only): also store each thread's outputs and the group's allocation + word in RWByteAddressBuffer u0 (per group: 16 bytes header [alloc], then per thread pos, param0..N-1, + primitive word, then the clip distances when pos1 is exported) and give each primitive SV_PrimitiveID = + group * 128 + index.""" + s = self.vs + nparams = max(self.params) + 1 if self.params else 0 + nclip = s.exports.get('clip') or 0 + stride = 4 * (4 + 4 * nparams + 1 + nclip) + out = self.common() + body_text = self.helper_text + if self.heapwords and not any(self.heapvars): + # descriptor words read, but no heap view used as a resource: the base emitted no heap declarations + out += ['ByteAddressBuffer heapmem : register(t0, space1);', + 'uint x2w_vid(uint h) { return heapmem.Load(h) == 0x%08xu ? heapmem.Load(h + 4) : 0xffffffffu; }' + % G.HEAP_TOKEN] + out += [text for name, text in MESH_HELPERS.items() if re.search(r'\b%s\(' % name, body_text)] + out += ['struct MSOut {'] + self.interface(False) + ['};', + 'struct MSPrim { bool cull : SV_CullPrimitive;%s };' % (' uint pid : SV_PrimitiveID;' if dump else '')] + ( + ['RWByteAddressBuffer x2w_dump : register(u0);'] if dump else []) + [ + 'groupshared uint x2w_alloc;'] + ( + ['groupshared uint x2w_rfl[%d][2]; // v_readfirstlane broadcasts, one slot per instruction' % s.broadcasts] + if s.broadcasts else []) + ( + ['groupshared uint x2w_rfv[%d][%d]; // first-active-lane reads: each thread\'s value' % (s.first_slots, GROUP), + 'groupshared uint x2w_rfe[%d][%d]; // ... and its exec bit' % (s.first_slots, GROUP), + '// v_readfirstlane_b32 under a partial exec: the lowest lane of the wave (first thread w0) with its', + '// exec bit set, lane 0 when none is (MeshStage.first_active_broadcast)', + 'uint x2w_rfirst(uint k, uint w0) {', + ' for (uint i = 0u; i < 64u; i++) { if (x2w_rfe[k][w0 + i] != 0u) return x2w_rfv[k][w0 + i]; }', + ' return x2w_rfv[k][w0];', + '}'] if s.first_slots else []) + ( + ['groupshared uint x2w_lds[%d]; // LDS (ds_read / ds_write), dword addressed' % LDS_DWORDS] + if s.lds_used else []) + ( + ['groupshared uint x2w_any[%d][2]; // wave-level execz branches: some lane of the wave active' + % len(s.wave_any)] if s.wave_any else []) + ( + ['groupshared uint x2w_sany[%d][2]; // lane-mask SCCs: some lane of the wave has its result bit set' + % len(s.scc_any)] if s.scc_any else []) + [ + '[outputtopology("triangle")]', + '[numthreads(%d, 1, 1)]' % GROUP, + 'void main(uint tid : SV_GroupIndex, uint3 group : SV_GroupID,', + ' out vertices MSOut verts[%d], out indices uint3 tris[%d], out primitives MSPrim prims[%d]) {' + % (MAX_VERTICES, MAX_PRIMITIVES, MAX_PRIMITIVES), + ' uint gid = group.x, lane = tid & 63u, wave = tid >> 6, wbase = tid & ~63u;', + ' if (tid == 0) x2w_alloc = 0;'] + ( + [' if (tid < %du) x2w_any[tid >> 1][tid & 1u] = 0u;' % (2 * len(s.wave_any))] if s.wave_any else []) + ( + [' if (tid < %du) x2w_sany[tid >> 1][tid & 1u] = 0u;' % (2 * len(s.scc_any))] if s.scc_any else []) + [ + ' GroupMemoryBarrierWithGroupSync();', + ' MSOut o = (MSOut)0;', + ' uint x2w_prim = 0x80000000u;'] + s.used_v.add(5) + flat = re.compile(r'.*o\.fparam(\d+) = ') + body = [] + for line in self.dw_sub(s.body()): + # attributes the pixel stage reads only interpolated: drop the flat copy (as hlsl_vs), and the + # binary16 half copies unless it reads them (v_interp_p2_f16) + line = re.sub(r'o\.(f|lo|hi)param(\d+) = [^;]*;', lambda mm: mm.group(0) if int(mm.group(2)) in ( + self.flat if mm.group(1) == 'f' else self.half) else '', line) + body.append(line) + if dump: + # progress markers (tests only): header word 1 = 1 at entry, word 2 = phases completed + marked, phase = [], 0 + for line in body: + marked.append(line) + if line.strip() == 'GroupMemoryBarrierWithGroupSync();' and line.startswith(' G'): + phase += 1 + marked.append(' if (tid == 0) x2w_dump.Store(gid * %du + 8u, %du);' % (16 + GROUP * stride, phase)) + body = [' if (tid == 0) x2w_dump.Store(gid * %du + 4u, 1u);' % (16 + GROUP * stride)] + marked + out += s.declarations() + [' v5 = gid * %du + tid; // inferred fast-launch vertex id' % GROUP] + body + out += [' GroupMemoryBarrierWithGroupSync();', + ' uint nv = min(x2w_alloc & 0x7ffu, %du), np = min((x2w_alloc >> 12) & 0x7ffu, %du);' % (MAX_VERTICES, MAX_PRIMITIVES), + ' SetMeshOutputCounts(nv, np);', + ' if (tid < nv) verts[tid] = o;', + ' if (tid < np) {', + ' uint3 t = uint3(x2w_prim & 0x1ffu, (x2w_prim >> 10) & 0x1ffu, (x2w_prim >> 20) & 0x1ffu);', + ' bool cull = (x2w_prim >> 31) != 0u || t.x >= nv || t.y >= nv || t.z >= nv;', + ' tris[tid] = cull ? uint3(0, 0, 0) : t;', + ' prims[tid].cull = cull;'] + ( + [' prims[tid].pid = gid * %du + tid;' % GROUP] if dump else []) + [ + ' }'] + if dump: + out += [' uint db = gid * %du, tb = db + 16u + tid * %du;' % (16 + GROUP * stride, stride), + ' if (tid == 0) x2w_dump.Store(db, x2w_alloc);', + ' x2w_dump.Store4(tb, asuint(o.pos));'] + out += [' x2w_dump.Store4(tb + %du, asuint(o.param%d));' % (16 + 16 * p, p) for p in range(nparams)] + out += [' x2w_dump.Store(tb + %du, x2w_prim);' % (16 + 16 * nparams)] + if nclip: + out += [' x2w_dump.Store%s(tb + %du, asuint(o.clip0));' % (nclip if nclip > 1 else '', 20 + 16 * nparams)] + out += ['}'] + return '\n'.join(out) + '\n' + + def manifest(self): + text = super().manifest() if self.ps else self.manifest_ms_only() + if self.heapwords: + if not re.search(r'^heap 1$', text, re.M): + text += 'heap 1\n' + text += 'heapwords 1\n' + text += 'fma %s\n' % ('exact' if EXACT_FMA else 'precise') + return text + 'stage mesh\nms %d %d %d\n' % (GROUP, MAX_VERTICES, MAX_PRIMITIVES) + + def manifest_ms_only(self): + class _P: # base manifest() reads self.ps.exports for the targets line + exports = {} + saved, self.ps = self.ps, _P() + try: + return G.Pipeline.manifest(self) + finally: + self.ps = saved + + +DXC = os.environ.get('X2W_DXC', r'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\dxc.exe') + + +def compile_hlsl(path, profile, out): + r = subprocess.run([DXC, '-nologo', '-T', profile, '-E', 'main', '-Fo', out, path], capture_output=True, text=True) + return r.returncode, r.stderr + + +def translate_to(out_dir, key, ms_code, ps_code, root_blob, check=True, rtv_formats=(), rtv_request='', + user_sgpr=MESH_USER_SGPR, ps_hw_inputs=None, vs_out_cntl=None): + """Writes .ms.hlsl, .ps.hlsl, the .cso files and .txt (last), or .fail. + ps_hw_inputs: the pixel stage's (SPI_PS_INPUT_ENA, SPI_PS_INPUT_ADDR[, launch FLOAT_MODE]), or None (entry-VGPR + reads refused). The FLOAT_MODE (SPI_SHADER_PGM_RSRC1_PS bits 19:12) is the optional third .psin field. + vs_out_cntl: the pipeline's PA_CL_VS_OUT_CNTL (what a pos1 export carries), or None (pos1 refused).""" + name = os.path.join(out_dir, '%016x' % key) + try: + pipe = MeshPipeline(ms_code, ps_code, root_blob, rtv_formats=rtv_formats, user_sgpr=user_sgpr, + ps_hw_inputs=ps_hw_inputs if ps_code is not None else None, vs_out_cntl=vs_out_cntl) + if pipe.ps_entry_reads: + reg, off = min(pipe.ps_entry_reads.items(), key=lambda item: item[1]) + raise Unsupported('pixel stage reads entry VGPR v%d (an SPI input; layout not in the request) at %#x' % (reg, off)) + ms = pipe.hlsl_ms() + ps = pipe.hlsl_ps() if ps_code is not None else None + manifest = pipe.manifest() + (rtv_request + '\n' if rtv_request else '') + except Unsupported as reason: + open(name + '.fail', 'w').write(str(reason) + '\n') + return 'unsupported: %s' % reason + open(name + '.ms.hlsl', 'w').write(ms) + if ps is not None: + open(name + '.ps.hlsl', 'w').write(ps) + if check: + # The pixel stage is compiled with dxc too: a pipeline with a DXIL mesh stage takes DXIL stages only. + for stage, profile, present in (('ms', 'ms_6_5', True), ('ps', 'ps_6_0', ps is not None)): + if not present: + continue + code, err = compile_hlsl(name + '.%s.hlsl' % stage, profile, name + '.%s.cso' % stage) + if code: + open(name + '.fail', 'w').write('dxc %s: %s\n' % (stage, err[-2000:])) + return 'dxc %s failed: %s' % (stage, err.strip().splitlines()[0] if err.strip() else '?') + temporary = '%s.txt.%d.tmp' % (name, os.getpid()) + with open(temporary, 'w') as result: + result.write(manifest) + os.replace(temporary, name + '.txt') + return 'ok' + + +def is_mesh(code): + """NGG mesh stage: it sends GS_ALLOC_REQ and exports a primitive.""" + text = [x[3] for x in G.decode(G.strip_header(code))] + return any(t == 's_sendmsg 0x9' for t in text) and any(re.match(r'exp (prim|target_20)', t) for t in text) + + +def translate_request(out_dir, key): + """A mesh pipeline request req_.{a,b,root}: whichever blob is the mesh stage, the other the pixel stage. + + An RTV variant (the draw path's contract, gfx2hlsl.translate_request; the mesh runtime publishes it when a bound + target is integer or 32-bit float, d3d12_mesh.inl): req_.rtv holds `rtv1 ` with + key = fnv(that text); the blobs are the base request's, checked against the base key; the pixel exports take + the target formats (Pipeline.mrt_kind) and the manifest carries the rtv1 line. A variant of a depth-only + pipeline is refused (the runtime takes the base translation for any target there).""" + base = os.path.join(out_dir, 'req_%016x' % key) + request, formats, base_key = '', (), key + if os.path.isfile(base + '.rtv'): + try: + with open(base + '.rtv', encoding='ascii') as file: + request = file.read(256) + except (OSError, UnicodeError) as error: + return 'unreadable: %s' % error + if not re.fullmatch(r'rtv1 [0-9]{1,20}(?: [0-9]{1,10}){1,8}', request) or G.fnv(request.encode('ascii')) != key: + return 'unsupported: invalid RTV variant request' + base_key, *formats = map(int, request.split()[1:]) + if base_key > 0xffffffffffffffff or any(fmt > 0xffffffff for fmt in formats): + return 'unsupported: invalid RTV variant values' + formats = tuple(formats) + base = os.path.join(out_dir, 'req_%016x' % base_key) + try: + a, b, root = (open(base + ext, 'rb').read() for ext in ('.a', '.b', '.root')) + except OSError as error: + return 'unreadable: %s' % error + if request: + if G.pipeline_key(a, b, root) != base_key: + return 'unsupported: RTV variant source key mismatch' + if not (a and b): + return 'unsupported: RTV variant of a mesh pipeline without a pixel stage' + rtv = {'rtv_formats': formats, 'rtv_request': request} if request else {} + # optional req_.vsout `pa_cl_vs_out_cntl 1 ` (not part of the key): what a pos1 export carries + try: + cntl = G.read_vs_out(base + '.vsout') + except Unsupported as reason: + return 'unsupported: %s' % reason + if not a and b and is_mesh(b): + return translate_to(out_dir, key, b, None, root, vs_out_cntl=cntl) # depth-only mesh pipeline (no pixel stage) + try: + # the pixel stage's SPI inputs: req_.psin (gfx2hlsl.read_ps_inputs format), else none + ps_hw_inputs = G.read_ps_inputs(base + '.psin') + except Unsupported as reason: + return 'unsupported: %s' % reason + if a and b and is_mesh(b) and not is_mesh(a): + return translate_to(out_dir, key, b, a, root, ps_hw_inputs=ps_hw_inputs, vs_out_cntl=cntl, **rtv) + if a and b and is_mesh(a) and not is_mesh(b): + return translate_to(out_dir, key, a, b, root, ps_hw_inputs=ps_hw_inputs, vs_out_cntl=cntl, **rtv) + return 'not a mesh pipeline' + + +# ---- root signature synthesis for coverage runs over the archive (no real root blob there) ---------------------- +def synth_root(*codes): + """A root signature blob whose SGPR layout from s16 (MESH_USER_SGPR) matches how the programs (the stages of one pipeline, which + share the layout) use their entry SGPRs: a register read as a 32-bit table pointer (with a zero high word) + becomes a descriptor table, a pair used as a 64-bit base a root SRV, everything else 32-bit constants. + COVERAGE ONLY: the title's real root signature comes with the request.""" + tables, pairs, used = set(), set(), set() + for code in codes: + if code: + synth_scan(code, tables, pairs, used) + return synth_layout(tables, pairs, used, min(entry_sgpr(c) for c in codes if c)) + + +def entry_sgpr(code): + """First user SGPR for a program without a real root: 8 if it reads any of s8..s15 before writing it (the + archive programs), else MESH_USER_SGPR (16, the run programs: s8..s15 are written first). Straight-line scan + up to the first branch; COVERAGE ONLY.""" + written = set() + for off, n, name, asm in G.decode(G.strip_header(code)): + _, ops, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', name) + for t in ops[1:]: + if any(8 <= r < MESH_USER_SGPR and r not in written for r in scalar_regs(t)): + return 8 + if base.startswith(('s_branch', 's_cbranch', 's_endpgm')): + break + dst = reg_range(ops[0]) if ops else None + if dst and dst[0] == 's' and not base.startswith(NO_DEST): + written.update(range(dst[1], dst[2] + 1)) + return MESH_USER_SGPR + + +def synth_scan(code, tables, pairs, used): + ins = G.decode(G.strip_header(code)) + origin = {} # current register -> entry register it holds + zero = set() + for r in range(8, 64): + origin[r] = r + for off, n, name, asm in ins: + _, ops, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', name) + for t in ops[1:]: + for r in scalar_regs(t): + if r in origin: + used.add(origin[r]) + if base.startswith(('s_load', 's_buffer_load', 'buffer_', 'tbuffer_', 'image_')): + sb = ops[1] if base.startswith(('s_load', 's_buffer_load')) else (ops[2] if len(ops) > 2 else '') + rr = reg_range(sb) + if rr and rr[0] == 's': + lo = origin.get(rr[1]) + if lo is not None and (rr[1] + 1) in zero and base.startswith('s_load'): + tables.add(lo) + elif lo is not None and origin.get(rr[1] + 1) == lo + 1: + pairs.add(lo) + dst = reg_range(ops[0]) if ops else None + if dst and dst[0] == 's' and base.startswith('s_') and not base.startswith(NO_DEST): + src = reg_range(ops[1]) if len(ops) > 1 else None + if base == 's_bitset1_b32': + continue # sets one bit in place (descriptor word 1 from a pointer's high word): same origin + for r in range(dst[1], dst[2] + 1): + origin.pop(r, None) + zero.discard(r) + if base == 's_mov_b32' and src and src[0] == 's' and src[1] in origin: + origin[dst[1]] = origin[src[1]] + elif base in ('s_or_b32', 's_bitset1_b32') and src and src[0] == 's' and src[1] in origin: + origin[dst[1]] = origin[src[1]] # descriptor word 1 built from a pointer's high word + elif base == 's_mov_b32' and ops[1] == '0': + zero.add(dst[1]) + + +def synth_layout(tables, pairs, used, start=MESH_USER_SGPR): + params, r = [], start + used = {u for u in used if u >= start} + if start == MESH_USER_SGPR and used & {23, 24}: + # s23/s24 are the resource and sampler heaps after the dominant real layout (sampled real roots: 3 tables, + # a root SRV, 2 constants, heap flags 0xc00 in ~87%); such a program cannot be expressed by the scan below + return root_blob([(0, None), (0, None), (0, None), (3, None), (1, 2)], 0xc00) + top = max(used | {start - 1}) + 1 + while r < top: + if r in tables: + params.append((0, None)) + r += 1 + elif r in pairs: + params.append((3, None)) + r += 2 + else: + n = 1 + while r + n < top and r + n not in tables and r + n not in pairs: + n += 1 + params.append((1, n)) + r += n + return root_blob(params) + + +def root_blob(params, flags=0): + """DXBC container with an RTS0 part (version 2) for params [(type, count)]: type 0 table (no ranges), 1 constants, + 3 root SRV.""" + head = 24 + body = bytearray() + extra = bytearray() + poff = head + eoff = head + 12 * len(params) + for i, (t, count) in enumerate(params): + if t == 1: + body += struct.pack('<3I', t, 0, eoff + len(extra)) + extra += struct.pack('<3I', i, 0, count) + elif t == 0: + body += struct.pack('<3I', t, 0, eoff + len(extra)) + extra += struct.pack('<2I', 0, eoff + len(extra) + 8) + else: + body += struct.pack('<3I', t, 0, eoff + len(extra)) + extra += struct.pack('<3I', i, 0, 0) + rts = struct.pack('<6I', 2, len(params), poff, 0, eoff + len(extra), flags) + bytes(body) + bytes(extra) + part = b'RTS0' + struct.pack('= 3 and sys.argv[1] == '--requests': + out_dir = sys.argv[2] + for name in sorted(os.listdir(out_dir)): + m = re.fullmatch(r'req_([0-9a-f]{16})\.a', name) + if not m or os.path.exists(os.path.join(out_dir, '%s.txt' % m.group(1))): + continue + result = translate_request(out_dir, int(m.group(1), 16)) + if result != 'not a mesh pipeline': + print('%s: %s' % (m.group(1), result)) + return + if len(sys.argv) >= 4 and sys.argv[1] == '--ms-only': + # --ms-only [...]: the mesh stage alone with a synthesized root (coverage) + out_dir = sys.argv[2] + os.makedirs(out_dir, exist_ok=True) + for i, path in enumerate(sys.argv[3:]): + code = open(path, 'rb').read() + print('%s: %s' % (os.path.basename(path), translate_to(out_dir, i, code, None, synth_root(code), + user_sgpr=entry_sgpr(code)))) + return + print(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/mesh_harness.cpp b/tools/startup/mesh_harness.cpp new file mode 100644 index 0000000000..f0524321da --- /dev/null +++ b/tools/startup/mesh_harness.cpp @@ -0,0 +1,536 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(x) \ + do { \ + HRESULT hr_ = (x); \ + if (FAILED(hr_)) { \ + std::fprintf(stderr, "%s failed: 0x%08lx (line %d)\n", #x, hr_, __LINE__); \ + dump_messages(); \ + return 1; \ + } \ + } while (0) + +template struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T** operator&() { return &p; } + T* operator->() const { return p; } + operator T*() const { return p; } +}; + +static ID3D12InfoQueue* g_info = nullptr; + +static void dump_messages() { + if (!g_info) return; + UINT64 n = g_info->GetNumStoredMessages(); + for (UINT64 i = 0; i < n; ++i) { + SIZE_T size = 0; + g_info->GetMessage(i, nullptr, &size); + std::vector buf(size); + auto* m = reinterpret_cast(buf.data()); + g_info->GetMessage(i, m, &size); + std::printf("debug-layer: severity %d id %d: %.*s\n", (int)m->Severity, (int)m->ID, + (int)m->DescriptionByteLength, m->pDescription); + } + std::printf("debug-layer messages: %llu\n", (unsigned long long)n); +} + +static std::vector read_file(const std::string& path) { + std::ifstream f(path, std::ios::binary); + return std::vector((std::istreambuf_iterator(f)), std::istreambuf_iterator()); +} + +template struct alignas(void*) Sub { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = T; + D data{}; +}; + +struct MeshStream { + Sub root; + Sub ms; + Sub ps; + Sub blend; + Sub raster; + Sub depth; + Sub rtv; + Sub sample; + Sub mask; +}; + +static D3D12_RESOURCE_DESC buffer_desc(UINT64 size, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = size < 16 ? 16 : (size + 15) & ~15ull; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + return d; +} + +static D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3D12_RESOURCE_STATES b) { + D3D12_RESOURCE_BARRIER x{}; + x.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + x.Transition.pResource = r; + x.Transition.StateBefore = a; + x.Transition.StateAfter = b; + x.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + return x; +} + +typedef LONG(WINAPI* RtlGetVersionFn)(OSVERSIONINFOW*); + +int main(int argc, char** argv) { + if (argc < 2) { + std::fprintf(stderr, "usage: mesh_harness [--hw] [--debug]\n"); + return 2; + } + bool hw = false, debug = false; + for (int i = 2; i < argc; ++i) { + hw |= std::string(argv[i]) == "--hw"; + debug |= std::string(argv[i]) == "--debug"; + } + std::string ms_path, ps_path, out; + UINT groups = 1; + std::vector consts; + std::vector srvs; + UINT64 dump_bytes = 16, hits_bytes = 16; + std::string heap_files[3], blob_path; // heapmem, vinfo, vdesc + struct HeapView { + UINT id = 0, kind = 4; // gfx2hlsl HEAP_KINDS slot: 0 tex2d, 3 tex1d, 4 buf + UINT dxgi = 0, width = 0, height = 1; + UINT64 offset = 0, bytes = 0; + }; + std::vector hviews; + { + std::ifstream cfg(argv[1]); + std::string line; + while (std::getline(cfg, line)) { + std::istringstream s(line); + std::string key; + s >> key; + if (key == "ms") std::getline(s >> std::ws, ms_path); + else if (key == "ps") std::getline(s >> std::ws, ps_path); + else if (key == "groups") s >> groups; + else if (key == "consts") { UINT n; s >> n; consts.resize(n); for (auto& c : consts) s >> c; } + else if (key == "srv") { std::string p; std::getline(s >> std::ws, p); srvs.push_back(p); } + else if (key == "dump") s >> dump_bytes; + else if (key == "hits") s >> hits_bytes; + else if (key == "out") std::getline(s >> std::ws, out); + else if (key == "heapmem") std::getline(s >> std::ws, heap_files[0]); + else if (key == "vinfo") std::getline(s >> std::ws, heap_files[1]); + else if (key == "vdesc") std::getline(s >> std::ws, heap_files[2]); + else if (key == "blob") std::getline(s >> std::ws, blob_path); + else if (key == "hbuf") { HeapView v; s >> v.id >> v.offset >> v.bytes; hviews.push_back(v); } + else if (key == "htex1d") { HeapView v; v.kind = 3; s >> v.id >> v.dxgi >> v.width >> v.offset; hviews.push_back(v); } + else if (key == "htex2d") { HeapView v; v.kind = 0; s >> v.id >> v.dxgi >> v.width >> v.height >> v.offset; hviews.push_back(v); } + else if (!key.empty() && key[0] != '#') { std::fprintf(stderr, "cfg: unknown line '%s'\n", line.c_str()); return 2; } + } + } + const bool heap = !heap_files[0].empty(); + if (heap && (heap_files[1].empty() || heap_files[2].empty())) { std::fprintf(stderr, "cfg: heapmem needs vinfo and vdesc\n"); return 2; } + constexpr UINT heap_ids = 90000, region_size = 8 + 8 * heap_ids; // gfx2hlsl HEAP_IDS, array size 8 + 8 * HEAP_IDS + for (const auto& v : hviews) + if (v.id >= heap_ids || (v.kind == 4 && (v.offset & 15))) { std::fprintf(stderr, "cfg: bad view id %u / offset %llu\n", v.id, v.offset); return 2; } + if (consts.empty()) consts.push_back(0); + + OSVERSIONINFOW os{sizeof(os)}; + if (auto fn = (RtlGetVersionFn)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion")) fn(&os); + std::printf("windows %lu.%lu.%lu\n", os.dwMajorVersion, os.dwMinorVersion, os.dwBuildNumber); + + if (debug) { + Ref dbg; + if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&dbg)))) dbg->EnableDebugLayer(); + } + std::printf("debug layer: %s\n", debug ? "on" : "off"); + Ref factory; + CHECK(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory))); + Ref adapter; + if (hw) CHECK(factory->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&adapter))); + else CHECK(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))); + DXGI_ADAPTER_DESC1 ad{}; + adapter->GetDesc1(&ad); + LARGE_INTEGER umd{}; + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &umd); + std::printf("adapter: %ls (vendor %04x device %04x) driver %u.%u.%u.%u\n", ad.Description, ad.VendorId, ad.DeviceId, + HIWORD(umd.HighPart), LOWORD(umd.HighPart), HIWORD(umd.LowPart), LOWORD(umd.LowPart)); + Ref device; + CHECK(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device))); + if (debug && SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&g_info)))) g_info->SetMuteDebugOutput(FALSE); + D3D12_FEATURE_DATA_D3D12_OPTIONS7 o7{}; + device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &o7, sizeof(o7)); + D3D12_FEATURE_DATA_SHADER_MODEL sm{D3D_SHADER_MODEL_6_5}; + device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &sm, sizeof(sm)); + std::printf("mesh shader tier %d, shader model 0x%x\n", (int)o7.MeshShaderTier, (unsigned)sm.HighestShaderModel); + if (o7.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED || sm.HighestShaderModel < D3D_SHADER_MODEL_6_5) { + std::printf("capability skip: no mesh shaders\n"); + return 77; + } + D3D12_FEATURE_DATA_D3D12_OPTIONS9 o9{}; + bool stats_ok = SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS9, &o9, sizeof(o9))) && + o9.MeshShaderPipelineStatsSupported; + + // root signature: b0 constants, t0..tN-1 as ONE descriptor table of raw buffer views (bounded: a load past + // the end reads 0, as the console's V# range check; root SRVs have no bounds check and an out-of-range load + // there is undefined, which hung a GPU), u0 dump, u1 hits + std::vector params; + D3D12_ROOT_PARAMETER1 p{}; + p.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + p.Constants.Num32BitValues = (UINT)consts.size(); + params.push_back(p); + D3D12_DESCRIPTOR_RANGE1 srv_range{}; + srv_range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + srv_range.NumDescriptors = (UINT)srvs.size(); + srv_range.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC; + if (!srvs.empty()) { + D3D12_ROOT_PARAMETER1 q{}; + q.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + q.DescriptorTable.NumDescriptorRanges = 1; + q.DescriptorTable.pDescriptorRanges = &srv_range; + params.push_back(q); + } + // heap: t0..t2 space1 (bounded raw views) and the view-id region (spaces 2..6, overlaid at offset 0) + D3D12_DESCRIPTOR_RANGE1 space1_range{}; + space1_range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + space1_range.NumDescriptors = 3; + space1_range.RegisterSpace = 1; + space1_range.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC; + D3D12_DESCRIPTOR_RANGE1 region_ranges[5]{}; + for (UINT k = 0; k < 5; ++k) { + region_ranges[k].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + region_ranges[k].NumDescriptors = region_size; + region_ranges[k].RegisterSpace = 2 + k; + region_ranges[k].OffsetInDescriptorsFromTableStart = 0; + region_ranges[k].Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE; + } + UINT heap_param = 0; + if (heap) { + heap_param = (UINT)params.size(); + D3D12_ROOT_PARAMETER1 q{}; + q.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + q.DescriptorTable.NumDescriptorRanges = 1; + q.DescriptorTable.pDescriptorRanges = &space1_range; + params.push_back(q); + q.DescriptorTable.NumDescriptorRanges = 5; + q.DescriptorTable.pDescriptorRanges = region_ranges; + params.push_back(q); + } + const UINT uav_param = (UINT)params.size(); + for (UINT i = 0; i < 2; ++i) { + D3D12_ROOT_PARAMETER1 q{}; + q.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + q.Descriptor.ShaderRegister = i; + params.push_back(q); + } + D3D12_VERSIONED_ROOT_SIGNATURE_DESC rsd{}; + rsd.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + rsd.Desc_1_1.NumParameters = (UINT)params.size(); + rsd.Desc_1_1.pParameters = params.data(); + Ref rs_blob, rs_err; + if (FAILED(D3D12SerializeVersionedRootSignature(&rsd, &rs_blob, &rs_err))) { + std::fprintf(stderr, "root signature: %s\n", rs_err ? (const char*)rs_err->GetBufferPointer() : "?"); + return 1; + } + Ref root; + CHECK(device->CreateRootSignature(0, rs_blob->GetBufferPointer(), rs_blob->GetBufferSize(), IID_PPV_ARGS(&root))); + + auto ms = read_file(ms_path), ps = read_file(ps_path); + if (ms.empty() || ps.empty()) { std::fprintf(stderr, "missing shader file\n"); return 1; } + MeshStream st{}; + st.root.data = root; + st.ms.data = {ms.data(), ms.size()}; + st.ps.data = {ps.data(), ps.size()}; + st.blend.data.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + st.raster.data.FillMode = D3D12_FILL_MODE_SOLID; + st.raster.data.CullMode = D3D12_CULL_MODE_NONE; + st.raster.data.DepthClipEnable = TRUE; + st.depth.data.DepthEnable = FALSE; + st.rtv.data.NumRenderTargets = 1; + st.rtv.data.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + st.sample.data.Count = 1; + st.mask.data = 0xffffffff; + D3D12_PIPELINE_STATE_STREAM_DESC sd{sizeof(st), &st}; + Ref pso; + CHECK(device->CreatePipelineState(&sd, IID_PPV_ARGS(&pso))); + + D3D12_HEAP_PROPERTIES up{D3D12_HEAP_TYPE_UPLOAD}, def{D3D12_HEAP_TYPE_DEFAULT}, rb{D3D12_HEAP_TYPE_READBACK}; + std::vector> srv_res(srvs.size()); + for (size_t i = 0; i < srvs.size(); ++i) { + auto data = read_file(srvs[i]); + auto d = buffer_desc(data.size()); + CHECK(device->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&srv_res[i]))); + void* m = nullptr; + CHECK(srv_res[i]->Map(0, nullptr, &m)); + std::memset(m, 0, (size_t)d.Width); + std::memcpy(m, data.data(), data.size()); + srv_res[i]->Unmap(0, nullptr); + } + // one shader-visible heap: [0, n) the srv table, then (heap) 3 space1 views, then the view-id region + const UINT n_srv = (UINT)srvs.size(), space1_at = n_srv, region_at = n_srv + 3; + const UINT heap_size = heap ? region_at + region_size : (n_srv ? n_srv : 1u); + Ref srv_heap; + D3D12_DESCRIPTOR_HEAP_DESC shd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, heap_size, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + CHECK(device->CreateDescriptorHeap(&shd, IID_PPV_ARGS(&srv_heap))); + UINT srv_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + auto cpu_at = [&](UINT i) { + D3D12_CPU_DESCRIPTOR_HANDLE h = srv_heap->GetCPUDescriptorHandleForHeapStart(); + h.ptr += SIZE_T{i} * srv_step; + return h; + }; + auto upload = [&](const std::vector& data, UINT64 at_least, Ref& res) -> HRESULT { + auto d = buffer_desc(data.size() > at_least ? data.size() : at_least); + HRESULT hr = device->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&res)); + if (FAILED(hr)) return hr; + void* m = nullptr; + if (FAILED(hr = res->Map(0, nullptr, &m))) return hr; + std::memset(m, 0, (size_t)d.Width); + if (!data.empty()) std::memcpy(m, data.data(), data.size()); + res->Unmap(0, nullptr); + return S_OK; + }; + auto raw_view = [&](ID3D12Resource* res, UINT64 offset, UINT64 bytes, D3D12_CPU_DESCRIPTOR_HANDLE h) { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Buffer.FirstElement = offset / 4; + v.Buffer.NumElements = (UINT)(bytes / 4); + v.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(v.Buffer.NumElements ? res : nullptr, &v, h); + }; + auto null_view = [&](UINT kind, D3D12_CPU_DESCRIPTOR_HANDLE h) { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + switch (kind) { + case 0: v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; v.Texture2D.MipLevels = 1; break; + case 1: v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; v.Texture2DArray.MipLevels = 1; v.Texture2DArray.ArraySize = 1; break; + case 2: v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; v.Texture3D.MipLevels = 1; break; + case 3: v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; v.Texture1D.MipLevels = 1; break; + default: raw_view(nullptr, 0, 0, h); return; + } + device->CreateShaderResourceView(nullptr, &v, h); + }; + Ref heap_res[3], blob_res; + std::vector> tex_res(hviews.size()), tex_up(hviews.size()); + std::vector tex_fp(hviews.size()); + if (heap) { + // space1: exact sizes, so a load past the end reads 0 (heapmem: the title heap; vinfo 16 and vdesc 32 bytes per id) + const UINT64 min_bytes[3] = {16, 16ull * heap_ids, 32ull * heap_ids}; + for (int i = 0; i < 3; ++i) { + auto data = read_file(heap_files[i]); + if (data.empty() && i == 0) { std::fprintf(stderr, "missing %s\n", heap_files[i].c_str()); return 1; } + CHECK(upload(data, min_bytes[i], heap_res[i])); + raw_view(heap_res[i], 0, data.size() > min_bytes[i] ? data.size() : min_bytes[i], cpu_at(space1_at + i)); + } + auto blob = read_file(blob_path); + CHECK(upload(blob, 16, blob_res)); + for (UINT k = 0; k < 8; ++k) null_view(k, cpu_at(region_at + k)); + for (const auto& v : hviews) + for (UINT k = 0; k < 5; ++k) null_view(k, cpu_at(region_at + 8 + 8 * v.id + k)); + UINT counts[5] = {}; + for (size_t i = 0; i < hviews.size(); ++i) { + const auto& v = hviews[i]; + const D3D12_CPU_DESCRIPTOR_HANDLE h = cpu_at(region_at + 8 + 8 * v.id + v.kind); + ++counts[v.kind]; + if (v.kind == 4) { + if (v.offset + v.bytes > blob.size()) { std::fprintf(stderr, "hbuf %u past the blob\n", v.id); return 1; } + raw_view(blob_res, v.offset, v.bytes, h); + continue; + } + D3D12_RESOURCE_DESC td{}; + td.Dimension = v.kind == 3 ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = v.width; + td.Height = v.kind == 3 ? 1 : v.height; + td.DepthOrArraySize = 1; + td.MipLevels = 1; + td.Format = (DXGI_FORMAT)v.dxgi; + td.SampleDesc.Count = 1; + CHECK(device->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&tex_res[i]))); + UINT rows = 0; + UINT64 row_bytes = 0, total = 0; + device->GetCopyableFootprints(&td, 0, 1, 0, &tex_fp[i], &rows, &row_bytes, &total); + if (v.offset + row_bytes * rows > blob.size()) { std::fprintf(stderr, "htex %u past the blob\n", v.id); return 1; } + std::vector staged((size_t)total); + for (UINT r = 0; r < rows; ++r) + std::memcpy(staged.data() + tex_fp[i].Offset + (size_t)r * tex_fp[i].Footprint.RowPitch, blob.data() + v.offset + r * row_bytes, (size_t)row_bytes); + CHECK(upload(staged, total, tex_up[i])); + D3D12_SHADER_RESOURCE_VIEW_DESC sv{}; + sv.Format = td.Format; + sv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (v.kind == 3) { sv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; sv.Texture1D.MipLevels = 1; } + else { sv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; sv.Texture2D.MipLevels = 1; } + device->CreateShaderResourceView(tex_res[i], &sv, h); + } + std::printf("heap: heapmem %zu bytes, region %u descriptors at %u, views tex2d %u tex1d %u buf %u\n", + read_file(heap_files[0]).size(), region_size, region_at, counts[0], counts[3], counts[4]); + } + for (size_t i = 0; i < srvs.size(); ++i) { + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Buffer.NumElements = (UINT)(read_file(srvs[i]).size() / 4); + v.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + D3D12_CPU_DESCRIPTOR_HANDLE h = srv_heap->GetCPUDescriptorHandleForHeapStart(); + h.ptr += i * srv_step; + device->CreateShaderResourceView(srv_res[i], &v, h); + } + Ref uav[2], back[2], zero; + UINT64 sizes[2] = {dump_bytes, hits_bytes}; + UINT64 zmax = dump_bytes > hits_bytes ? dump_bytes : hits_bytes; + { + auto d = buffer_desc(zmax); + CHECK(device->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&zero))); + void* m = nullptr; + CHECK(zero->Map(0, nullptr, &m)); + std::memset(m, 0, (size_t)d.Width); + zero->Unmap(0, nullptr); + } + for (int i = 0; i < 2; ++i) { + auto d = buffer_desc(sizes[i], D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + CHECK(device->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&uav[i]))); + auto r = buffer_desc(sizes[i]); + CHECK(device->CreateCommittedResource(&rb, D3D12_HEAP_FLAG_NONE, &r, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&back[i]))); + } + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = 256; + td.Height = 256; + td.DepthOrArraySize = 1; + td.MipLevels = 1; + td.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + td.SampleDesc.Count = 1; + td.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + D3D12_CLEAR_VALUE cv{DXGI_FORMAT_R8G8B8A8_UNORM, {0, 0, 0, 0}}; + Ref rt; + CHECK(device->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_RENDER_TARGET, &cv, + IID_PPV_ARGS(&rt))); + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + Ref rtv_heap; + CHECK(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtv_heap))); + auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(rt, nullptr, rtv); + + Ref qheap; + Ref qback; + if (stats_ok) { + D3D12_QUERY_HEAP_DESC qd{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS1, 1}; + if (FAILED(device->CreateQueryHeap(&qd, IID_PPV_ARGS(&qheap)))) stats_ok = false; + auto r = buffer_desc(sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS1)); + CHECK(device->CreateCommittedResource(&rb, D3D12_HEAP_FLAG_NONE, &r, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&qback))); + } + + D3D12_COMMAND_QUEUE_DESC qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + Ref queue; + CHECK(device->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&queue))); + Ref alloc; + CHECK(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc))); + Ref list; + CHECK(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc, nullptr, IID_PPV_ARGS(&list))); + + D3D12_RESOURCE_BARRIER b[2]; + for (int i = 0; i < 2; ++i) b[i] = transition(uav[i], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->ResourceBarrier(2, b); + for (int i = 0; i < 2; ++i) list->CopyBufferRegion(uav[i], 0, zero, 0, buffer_desc(sizes[i]).Width); + for (int i = 0; i < 2; ++i) b[i] = transition(uav[i], D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->ResourceBarrier(2, b); + for (size_t i = 0; i < hviews.size(); ++i) { + if (!tex_res[i]) continue; + D3D12_TEXTURE_COPY_LOCATION dst{tex_res[i], D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}, src{tex_up[i], D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.SubresourceIndex = 0; + src.PlacedFootprint = tex_fp[i]; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + D3D12_RESOURCE_BARRIER t = transition(tex_res[i], D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list->ResourceBarrier(1, &t); + } + const float clear[4] = {0, 0, 0, 0}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + D3D12_VIEWPORT vp{0, 0, 256, 256, 0, 1}; + D3D12_RECT sc{0, 0, 256, 256}; + list->RSSetViewports(1, &vp); + list->RSSetScissorRects(1, &sc); + list->SetGraphicsRootSignature(root); + list->SetPipelineState(pso); + list->SetGraphicsRoot32BitConstants(0, (UINT)consts.size(), consts.data(), 0); + ID3D12DescriptorHeap* heaps[] = {srv_heap}; + list->SetDescriptorHeaps(1, heaps); + if (!srvs.empty()) list->SetGraphicsRootDescriptorTable(1, srv_heap->GetGPUDescriptorHandleForHeapStart()); + if (heap) { + D3D12_GPU_DESCRIPTOR_HANDLE g = srv_heap->GetGPUDescriptorHandleForHeapStart(); + g.ptr += UINT64{space1_at} * srv_step; + list->SetGraphicsRootDescriptorTable(heap_param, g); + g.ptr += UINT64{3} * srv_step; + list->SetGraphicsRootDescriptorTable(heap_param + 1, g); + } + for (UINT i = 0; i < 2; ++i) list->SetGraphicsRootUnorderedAccessView(uav_param + i, uav[i]->GetGPUVirtualAddress()); + if (stats_ok) list->BeginQuery(qheap, D3D12_QUERY_TYPE_PIPELINE_STATISTICS1, 0); + list->DispatchMesh(groups, 1, 1); + if (stats_ok) { + list->EndQuery(qheap, D3D12_QUERY_TYPE_PIPELINE_STATISTICS1, 0); + list->ResolveQueryData(qheap, D3D12_QUERY_TYPE_PIPELINE_STATISTICS1, 0, 1, qback, 0); + } + for (int i = 0; i < 2; ++i) b[i] = transition(uav[i], D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(2, b); + for (int i = 0; i < 2; ++i) list->CopyBufferRegion(back[i], 0, uav[i], 0, buffer_desc(sizes[i]).Width); + CHECK(list->Close()); + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + Ref fence; + CHECK(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); + CHECK(queue->Signal(fence, 1)); + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + CHECK(fence->SetEventOnCompletion(1, ev)); + DWORD t0 = GetTickCount(); + DWORD waited = WaitForSingleObject(ev, 60000); + printf("gpu wait: %s after %lu ms, fence %llu\n", waited == WAIT_OBJECT_0 ? "done" : "TIMEOUT", + (unsigned long)(GetTickCount() - t0), (unsigned long long)fence->GetCompletedValue()); + CHECK(device->GetDeviceRemovedReason()); + if (waited != WAIT_OBJECT_0) { + fprintf(stderr, "the GPU did not finish within 60 s\n"); + return 3; + } + + const char* ext[2] = {".dump", ".hits"}; + for (int i = 0; i < 2; ++i) { + void* m = nullptr; + D3D12_RANGE r{0, (SIZE_T)sizes[i]}; + CHECK(back[i]->Map(0, &r, &m)); + std::ofstream f(out + ext[i], std::ios::binary); + f.write((const char*)m, (std::streamsize)sizes[i]); + back[i]->Unmap(0, nullptr); + } + if (stats_ok) { + void* m = nullptr; + CHECK(qback->Map(0, nullptr, &m)); + auto* q = (D3D12_QUERY_DATA_PIPELINE_STATISTICS1*)m; + std::printf("stats: MSInvocations %llu MSPrimitives %llu CInvocations %llu CPrimitives %llu PSInvocations %llu\n", + q->MSInvocations, q->MSPrimitives, q->CInvocations, q->CPrimitives, q->PSInvocations); + qback->Unmap(0, nullptr); + } else { + std::printf("stats: mesh pipeline statistics not supported\n"); + } + dump_messages(); + std::printf("ok\n"); + return 0; +} diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index 8132b595e2..de9d71a93e 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -56,6 +56,7 @@ if ($HostCpu) { $env:X2W_HOST_CPU = "1" } if ($TraceApi) { $env:X2W_TRACE_API = "1" } if ($StartupBelow40) { $env:X2W_XMEM_STARTUP_BELOW_40 = "1" } if ($Render) { + if (-not (Test-Path Env:X2W_PRESENT_IN_TITLE_WINDOW)) { $env:X2W_PRESENT_IN_TITLE_WINDOW = "1" } 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 diff --git a/tools/startup/window_status.py b/tools/startup/window_status.py new file mode 100644 index 0000000000..fac8f85e9d --- /dev/null +++ b/tools/startup/window_status.py @@ -0,0 +1,96 @@ +"""Keep the launched executable's own window at its requested initial size and update its caption.""" +import ctypes +from ctypes import wintypes as wt +import os +import re +import threading + + +def follow_window(pid, trap_log): + user = ctypes.WinDLL('user32', use_last_error=True) + kernel = ctypes.WinDLL('kernel32', use_last_error=True) + user.SetThreadDpiAwarenessContext.argtypes = [wt.HANDLE] + user.SetThreadDpiAwarenessContext(wt.HANDLE(-4)) + user.SendMessageTimeoutW.argtypes = (wt.HWND, wt.UINT, wt.WPARAM, wt.LPCWSTR, wt.UINT, wt.UINT, + ctypes.POINTER(ctypes.c_size_t)) + user.GetWindow.argtypes = (wt.HWND, wt.UINT) + user.GetWindow.restype = wt.HWND + user.GetMenu.argtypes = [wt.HWND] + user.GetMenu.restype = wt.HMENU + kernel.OpenProcess.restype = wt.HANDLE + process = kernel.OpenProcess(0x100000, False, pid) # SYNCHRONIZE + if not process: + return + window = None + caption = '' + position = 0 + remainder = b'' + previous = None + status = 'Xbox2Windows' + displayed = None + + @ctypes.WINFUNCTYPE(wt.BOOL, wt.HWND, wt.LPARAM) + def candidate(hwnd, unused): + nonlocal window + owner = wt.DWORD() + user.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + if owner.value != pid or not user.IsWindowVisible(hwnd) or user.GetWindow(hwnd, 4): + return True + name = ctypes.create_unicode_buffer(256) + user.GetClassNameW(hwnd, name, len(name)) + if name.value in ('#32770', 'X2WOutputWindow') or user.GetWindowLongW(hwnd, -20) & 0x80: + return True + window = hwnd + return False + + try: + while kernel.WaitForSingleObject(wt.HANDLE(process), 300) == 258: + if not window or not user.IsWindow(window): + window = None + user.EnumWindows(candidate, 0) + if not window: + continue + title = ctypes.create_unicode_buffer(512) + user.GetWindowTextW(window, title, len(title)) + caption = title.value + displayed = None + rect = wt.RECT(0, 0, 1280, 720) + if user.IsZoomed(window): + user.ShowWindowAsync(window, 9) + if user.AdjustWindowRectExForDpi(ctypes.byref(rect), user.GetWindowLongW(window, -16), + bool(user.GetMenu(window)), user.GetWindowLongW(window, -20), + user.GetDpiForWindow(window)): + # Size once, keep position, z-order and activation, let the owner process the request. + user.SetWindowPos(window, None, 0, 0, rect.right - rect.left, rect.bottom - rect.top, 0x4016) + try: + with open(trap_log, 'rb') as log: + size = os.fstat(log.fileno()).st_size + if position > size or size - position > 2**21: + position = max(0, size - 2**21) + remainder = b'' + log.seek(position) + chunk = log.read(2**21) + position = log.tell() + except OSError: + chunk = b'' + if chunk: + lines = (remainder + chunk).split(b'\n') + remainder = lines.pop()[-4096:] + for line in lines: + match = re.search(rb'heartbeat: (\d+) frames presented in ([\d.]+) s', line) + if match: + frame, seconds = int(match[1]), float(match[2]) + if previous and seconds > previous[1]: + fps = (frame - previous[0]) / (seconds - previous[1]) + status = f'Xbox2Windows | Frame {frame} | {fps:.1f} FPS' + previous = frame, seconds + if displayed != status: + text = f'{caption} | {status}' if caption else status + if user.SendMessageTimeoutW(window, 12, 0, text, 2, 150, ctypes.byref(ctypes.c_size_t())): + displayed = status + finally: + kernel.CloseHandle(wt.HANDLE(process)) + + +def start(pid, trap_log): + threading.Thread(target=follow_window, args=(pid, trap_log), name='title-window-status', daemon=True).start()