From 1be42301d443b3f2e09025bedc12566c00d4de50 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 00:37:22 +0530 Subject: [PATCH 001/269] perf(agc): GPU descriptor heap on VK_EXT_descriptor_heap (APS5_GPU_HEAP) Co-authored-by: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> --- 3rdparty/Vulkan-Headers | 2 +- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 75 +- .../include/Driver/Dispatch/DispatchCache.hpp | 4 + .../include/Driver/Draw/DrawCache.hpp | 5 + .../include/Driver/Draw/DrawPipeline.hpp | 2 + .../include/Driver/Draw/HeapStages.hpp | 57 ++ .../Execution/include/Driver/Driver.hpp | 2 +- .../include/Driver/Shaders/ShaderRegistry.hpp | 1 + .../Execution/include/VulkanDevice.hpp | 2 + .../src/Driver/Dispatch/Dispatch.cpp | 13 + .../src/Driver/Dispatch/VariantValidation.cpp | 1 + .../Execution/src/Driver/Draw/Draw.cpp | 188 +++-- .../Execution/src/Driver/Draw/DrawCapture.cpp | 142 +++- .../Execution/src/Driver/Draw/DrawLookup.cpp | 5 +- .../src/Driver/Draw/DrawPipeline.cpp | 19 + .../src/Driver/Draw/DrawRelocate.cpp | 2 +- .../Execution/src/Driver/Draw/HeapStages.cpp | 431 ++++++++++ .../src/Driver/Memory/WrittenBuffers.cpp | 25 +- .../src/Driver/Shaders/ShaderRegistry.cpp | 119 ++- .../Execution/src/PresentationPass.cpp | 3 +- .../Execution/src/VulkanDevice.cpp | 147 +++- .../Graphics/include/BindlessHeap.hpp | 151 ++++ .../Graphics/include/BufferPool.hpp | 2 + .../Graphics/include/Context.hpp | 6 + .../include/DescriptorHeapObjects.hpp | 32 + .../Graphics/include/GuestBufferMemory.hpp | 5 + .../Graphics/include/Pipeline.hpp | 2 + .../Graphics/include/PipelineLibrary.hpp | 1 + .../Graphics/include/Recorder.hpp | 1 + .../Graphics/include/Sampler.hpp | 7 + .../Graphics/include/ShaderResources.hpp | 73 +- .../Graphics/include/Shaders.hpp | 17 +- .../Graphics/include/Texture.hpp | 5 + .../Graphics/src/BdaResources.cpp | 1 + .../Graphics/src/BindlessHeap.cpp | 697 ++++++++++++++++ .../Graphics/src/BufferPool.cpp | 15 + .../Graphics/src/DescriptorHeapObjects.cpp | 164 ++++ .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 63 +- .../Graphics/src/GpuColorTransfer.cpp | 3 +- .../Graphics/src/GuestBufferMemory.cpp | 114 +++ .../libSceAgcDriver/Graphics/src/Pipeline.cpp | 56 +- .../Graphics/src/PipelineLibrary.cpp | 51 +- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 20 + .../Graphics/src/Resources.cpp | 15 +- .../libSceAgcDriver/Graphics/src/Sampler.cpp | 1 + .../Graphics/src/ShaderAddressResources.cpp | 114 +-- .../Graphics/src/ShaderResources.cpp | 757 +++++++++++++++--- .../Graphics/src/ShaderValidation.cpp | 48 +- .../libSceAgcDriver/Graphics/src/Texture.cpp | 1 + .../Graphics/src/TextureDetiler.cpp | 9 +- .../Graphics/src/UnitShadow.cpp | 5 + .../libSceAgcDriver/tests/BdaContracts.cpp | 118 --- .../libSceAgcDriver/tests/BdaResources.cpp | 1 + .../tests/BindlessHeapSlots.cpp | 158 ++++ core/libs/prx/libSceAgcDriver/tests/Mesh.cpp | 7 +- .../libSceAgcDriver/tests/ShaderMemory.cpp | 23 + .../tests/execution/AddressPasses.cpp | 6 +- .../tests/execution/BindlessImages.cpp | 8 +- .../tests/execution/BufferAtomics.cpp | 4 +- .../tests/execution/BufferFormat.cpp | 4 +- .../tests/execution/BufferLoadStore.cpp | 6 +- .../tests/execution/HeapComputeSample.cpp | 190 +++++ .../tests/execution/HeapDrawSample.cpp | 263 ++++++ .../tests/execution/ImageAtomics.cpp | 4 +- .../tests/execution/ImageAtomics64.cpp | 4 +- .../tests/execution/ImageAtomicsBitwise.cpp | 4 +- .../tests/execution/ImageAtomicsFloat.cpp | 4 +- .../tests/execution/ImageTableCacheBounds.cpp | 6 + .../tests/execution/MeshDrawRelocation.cpp | 3 + .../tests/execution/MultisampleRetirement.cpp | 4 +- .../tests/execution/PipelineJournal.cpp | 66 ++ .../execution/PixelBarycentricEmulation.cpp | 3 + .../tests/execution/PreparedGraphics.cpp | 26 +- .../tests/execution/PreparedShaders.cpp | 10 +- .../tests/execution/Tessellation.cpp | 6 +- .../tests/execution/TessellationSubmit.cpp | 212 +++++ core/shader/recompiler/CMakeLists.txt | 5 + core/shader/recompiler/CacheKey.hpp | 6 + .../IrMetadata/DescriptorBinding.hpp | 28 +- .../include/Optimization/BindingAllocator.hpp | 2 +- .../Optimization/DescriptorBindingBuilder.hpp | 3 + .../include/Optimization/ResourceProgram.hpp | 8 +- .../Optimization/src/BindingAllocator.cpp | 23 +- .../src/DescriptorBindingBuilder.cpp | 32 +- core/shader/recompiler/Recompiler.cpp | 275 ++++++- core/shader/recompiler/Recompiler.hpp | 21 + core/shader/recompiler/RuntimeAbi.hpp | 26 + core/shader/recompiler/ShaderDiskCache.cpp | 50 +- .../include/SpirvBackend/SpirvEmitter.hpp | 2 + .../SpirvBackend/SpirvEmitterHelpers.hpp | 2 + .../SpirvBackend/SpirvEmitterState.hpp | 9 + .../SpirvMemory/SpirvBufferAccess.hpp | 9 + .../SpirvBackend/src/SpirvBdaFault.cpp | 9 +- .../SpirvBackend/src/SpirvBdaLookup.cpp | 6 +- .../SpirvBackend/src/SpirvEmitter.cpp | 2 + .../SpirvBackend/src/SpirvFlowEmitter.cpp | 3 +- .../SpirvBackend/src/SpirvImageEmitter.cpp | 9 +- .../src/SpirvMemory/SpirvBufferAccess.cpp | 123 ++- .../src/SpirvMemory/SpirvDescriptors.cpp | 93 ++- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 85 +- .../SpirvMemory/SpirvMemoryInstructions.cpp | 17 +- .../src/SpirvMemory/SpirvTypes.cpp | 4 + .../SpirvBackend/src/SpirvModuleEmitter.cpp | 5 +- .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 24 +- docs/dev/ARCHITECTURE.md | 1 + docs/dev/ENVIRONMENT.md | 3 + docs/dev/debt/libSceAgcDriver.md | 1 + docs/user/USAGE.md | 4 + 108 files changed, 5043 insertions(+), 668 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp create mode 100644 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp create mode 100644 core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp create mode 100644 core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp create mode 100644 core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp create mode 100644 core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp diff --git a/3rdparty/Vulkan-Headers b/3rdparty/Vulkan-Headers index 2fa203425eb4..5d94bb4dcc96 160000 --- a/3rdparty/Vulkan-Headers +++ b/3rdparty/Vulkan-Headers @@ -1 +1 @@ -Subproject commit 2fa203425eb4af9dfc6b03f97ef72b0b5bcb8350 +Subproject commit 5d94bb4dcc968cccce1f601324fcaf3eda92a52b diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 613780e64718..a8292e61c990 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -260,6 +260,7 @@ set(agcDriverSources ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/DrawCache.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/DrawCacheStatistics.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/DrawCapture.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/HeapStages.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/DrawDecode.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/DrawLookup.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Draw/DrawPipeline.cpp @@ -328,6 +329,7 @@ set(agcDriverSources ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/PipelineJournal.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/Resources.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/PlaceholderImages.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/DescriptorHeapObjects.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/Recorder.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/ParallelCompare.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/ShaderInputState.cpp @@ -355,6 +357,7 @@ set(agcDriverSources ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/UnitShadow.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/Sampler.cpp ${agcSampleOrderShaderHeaders} + ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/BindlessHeap.cpp ${agcTextureDetileShaderHeader} ${agcReadbackHeaders} ${agcMultisampleUploadHeader} @@ -1489,6 +1492,25 @@ target_link_libraries(agc_driver_cmask_fast_clear_tests PRIVATE set_target_properties(agc_driver_cmask_fast_clear_tests PROPERTIES CXX_EXTENSIONS OFF) configure_windows_unwind(agc_driver_cmask_fast_clear_tests) +add_test_executable(agc_driver_heap_slots_tests EXCLUDE_FROM_ALL + tests/BindlessHeapSlots.cpp +) + +target_include_directories(agc_driver_heap_slots_tests PRIVATE + ${LIBS_INCLUDE_DIR} + ${CMAKE_SOURCE_DIR}/core/shader/recompiler + ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} +) + +target_link_libraries(agc_driver_heap_slots_tests PRIVATE + libSceAgcDriver + SDL2-static + libc +) + +set_target_properties(agc_driver_heap_slots_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_driver_heap_slots_tests) + set(agcBufferUpdateSource ${CMAKE_CURRENT_SOURCE_DIR}/tests/shaders/BufferUpdate.comp) set(agcBufferUpdateSpv ${agcTestShaderGeneratedRoot}/BufferUpdate.spv) set(agcBufferUpdateHeader ${agcTestShaderGeneratedRoot}/BufferUpdate_spv.h) @@ -2501,7 +2523,7 @@ if(BUILD_TESTING) if(WIN32) set_tests_properties(agc_shader_bindless agc_shader_selected_records_image_limit agc_shader_selected_records_pair_limit agc_shader_selected_records_direct_image_limit agc_shader_selected_records_direct_pair_limit agc_shader_srt_read_patching agc_shader_type_zero_image_materialization agc_shader_frontend_pair agc_shader_frontend_pair_off agc_shader_layout_pair agc_shader_layout_pair_off agc_shader_entry_lane_proof_budget PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() - foreach(agcTest IN ITEMS agc_vertex_input_tests agc_mesh_output_budget_tests agc_shared_write_tests agc_locks_tests agc_driver_tests agc_shader_memory_tests agc_structurizer_tests agc_spirv_module_tests agc_dpp_write_tests agc_masked_select_tests agc_ir_reclaim_tests agc_vector_window_tests agc_constant_bit_test_tests agc_integer_narrowing_tests agc_scalar_select_mask_tests agc_vertex_input_validation_tests agc_vop1_control_decode_tests agc_validate_program_tests agc_pass_hazards_tests agc_barrier_batch_tests agc_shader_disk_cache_tests agc_screenshot_tests agc_shader_device_profile_tests agc_placeholder_images_tests agc_shader_control_flow_tests agc_driver_flip_tests agc_driver_pm4_tests agc_driver_graphics_tests agc_driver_bda_device_tests agc_driver_mesh_tests agc_driver_cmask_fast_clear_tests agc_formatted_buffer_once_tests agc_formatted_buffer_byte_stores_tests ${agcExecutionTests} agc_fma_mix_once_tests agc_f16_single_convert_tests) + foreach(agcTest IN ITEMS agc_vertex_input_tests agc_mesh_output_budget_tests agc_shared_write_tests agc_locks_tests agc_driver_tests agc_shader_memory_tests agc_structurizer_tests agc_spirv_module_tests agc_dpp_write_tests agc_masked_select_tests agc_ir_reclaim_tests agc_vector_window_tests agc_constant_bit_test_tests agc_integer_narrowing_tests agc_scalar_select_mask_tests agc_vertex_input_validation_tests agc_vop1_control_decode_tests agc_validate_program_tests agc_pass_hazards_tests agc_barrier_batch_tests agc_shader_disk_cache_tests agc_screenshot_tests agc_shader_device_profile_tests agc_placeholder_images_tests agc_shader_control_flow_tests agc_driver_flip_tests agc_driver_pm4_tests agc_driver_graphics_tests agc_driver_bda_device_tests agc_driver_mesh_tests agc_driver_cmask_fast_clear_tests agc_formatted_buffer_once_tests agc_formatted_buffer_byte_stores_tests ${agcExecutionTests} agc_fma_mix_once_tests agc_f16_single_convert_tests agc_driver_heap_slots_tests) if(agcTest STREQUAL "agc_driver_constant_store_tests" OR agcTest STREQUAL "agc_driver_flat_apertures_tests" OR agcTest STREQUAL "agc_driver_pipeline_optimized_readback_tests" OR agcTest STREQUAL "agc_driver_rcp_hardware_tests") continue() endif() @@ -2602,6 +2624,14 @@ if(BUILD_TESTING) set_tests_properties(${agcTestName}_draw_pipeline PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endforeach() + set(agcGpuHeapTests ${agcDrawPipelineTests} agc_driver_rect_list_indirect agc_driver_provoking_vertex agc_driver_pixel_barycentric_emulation agc_driver_bindless_images agc_driver_image_sample_shared_sampler agc_driver_image_sample_border_color agc_driver_image_sample_lod_clamp agc_driver_image_sample_derivatives agc_driver_image_gather_one_dimensional agc_driver_image_load_packed agc_driver_sampled_cache_budget agc_driver_image_atomics agc_driver_image_atomics64 agc_driver_image_atomics_bitwise agc_driver_image_atomics_float agc_driver_gpu_indirect_arguments_misaligned_writer_ahead agc_driver_gpu_indirect_arguments_written_ahead agc_driver_indirect_arguments_written_ahead agc_driver_indirect_patched_stage agc_driver_compute_table_calls agc_driver_buffer_atomics agc_driver_buffer_format agc_driver_mesh agc_driver_tessellation agc_driver_mesh_draw_relocation agc_driver_mesh_index_cache agc_driver_mesh_provoking_vertex agc_driver_tessellation_submit agc_driver_fragment_user_data_tail agc_driver_image_table_cache_bounds agc_driver_lds_beyond_device_limit agc_driver_address_passes) + foreach(agcTestName IN LISTS agcGpuHeapTests) + add_test(NAME ${agcTestName}_gpu_heap COMMAND ${agcTestName}_tests) + set_tests_properties(${agcTestName}_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(${agcTestName}_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() + endforeach() add_test(NAME agc_driver_partially_resident_pending_stores COMMAND agc_driver_partially_resident_snapshot_tests --pending-stores) set_tests_properties(agc_driver_multisample_readback PROPERTIES TIMEOUT 20) foreach(agcReadbackCase IN ITEMS uint8 uint16 uint64 uint128 depth upload retile depth_retile) @@ -3038,6 +3068,47 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() add_test(NAME agc_driver_draw_cache_reuse_off COMMAND agc_driver_draw_cache_reuse_tests) + if(TARGET agc_driver_heap_draw_sample_tests) + add_test(NAME agc_driver_heap_draw_sample_heap COMMAND agc_driver_heap_draw_sample_tests) + set_tests_properties(agc_driver_heap_draw_sample_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + endif() + add_test(NAME agc_driver_heap_slots_comes_back COMMAND agc_driver_heap_slots_tests comes-back) + set_tests_properties(agc_driver_heap_slots_comes_back PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_heap_slots_comes_back PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() + if(TARGET agc_driver_heap_draw_sample_tests) + add_test(NAME agc_driver_heap_draw_sample_full_heap COMMAND agc_driver_heap_draw_sample_tests) + set_tests_properties(agc_driver_heap_draw_sample_full_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_HEAP_SLOT_CAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + add_test(NAME agc_driver_heap_draw_sample_full_heap_pipelined COMMAND agc_driver_heap_draw_sample_tests) + set_tests_properties(agc_driver_heap_draw_sample_full_heap_pipelined PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_HEAP_SLOT_CAP=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + endif() + if(TARGET agc_driver_heap_draw_sample_tests) + add_test(NAME agc_driver_heap_draw_sample_nogpl COMMAND agc_driver_heap_draw_sample_tests) + set_tests_properties(agc_driver_heap_draw_sample_nogpl PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_GPL=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + add_test(NAME agc_driver_heap_draw_sample_nogpl_heap COMMAND agc_driver_heap_draw_sample_tests) + set_tests_properties(agc_driver_heap_draw_sample_nogpl_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_GPL=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + endif() + if(TARGET agc_driver_heap_compute_sample_tests) + add_test(NAME agc_driver_heap_compute_sample_heap_pipelined COMMAND agc_driver_heap_compute_sample_tests) + set_tests_properties(agc_driver_heap_compute_sample_heap_pipelined PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_PIPELINE_DISPATCH=1;APS5_PIPELINED_DRAWS=32" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + endif() + if(TARGET agc_driver_heap_compute_sample_tests) + add_test(NAME agc_driver_heap_compute_sample_heap COMMAND agc_driver_heap_compute_sample_tests) + set_tests_properties(agc_driver_heap_compute_sample_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + endif() + if(TARGET agc_driver_pipeline_journal_tests) + add_test(NAME agc_driver_pipeline_journal_gpu_heap COMMAND agc_driver_pipeline_journal_tests --gpu-heap) + set_tests_properties(agc_driver_pipeline_journal_gpu_heap PROPERTIES ENVIRONMENT "APS5_GPU_HEAP=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + endif() + if(TARGET agc_driver_dispatch_move_tests) + add_test(NAME agc_driver_dispatch_move_gpu_heap COMMAND agc_driver_dispatch_move_tests) + set_tests_properties(agc_driver_dispatch_move_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + endif() + if(TARGET agc_driver_bindless_images_tests) + add_test(NAME agc_driver_bindless_images_heap COMMAND agc_driver_bindless_images_tests) + set_tests_properties(agc_driver_bindless_images_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1" SKIP_RETURN_CODE 77) + endif() set_tests_properties(agc_driver_draw_cache_reuse_off PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_GPL=1" SKIP_RETURN_CODE 77) add_test(NAME agc_driver_draw_cache_reuse_verify COMMAND agc_driver_draw_cache_reuse_tests) set_tests_properties(agc_driver_draw_cache_reuse_verify PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_VERIFY_DRAW_DATA_HITS=1" SKIP_RETURN_CODE 77) @@ -3956,6 +4027,6 @@ endif() if(BUILD_TESTING) get_directory_property(agcRegisteredTests TESTS) - list(FILTER agcRegisteredTests EXCLUDE REGEX "^(agc_pipeline_journal(_long_paths|_extended_paths)?|agc_driver_pipeline_journal)$") + list(FILTER agcRegisteredTests EXCLUDE REGEX "^(agc_pipeline_journal(_long_paths|_extended_paths)?|agc_driver_pipeline_journal|agc_driver_pipeline_journal_gpu_heap)$") set_property(TEST ${agcRegisteredTests} APPEND PROPERTY ENVIRONMENT "APS5_NO_PIPELINE_JOURNAL=1") endif() diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp index 5f3df6c538af..397d0b283c2c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp @@ -47,6 +47,10 @@ struct DispatchVariant { std::vector> shaderDataPatches; std::uint64_t userDataMask = ~std::uint64_t{0}; std::shared_ptr vertexInfo; + bool ring = false; + std::shared_ptr> ringAttributes; + std::shared_ptr> ringFlat; + std::shared_ptr>> ringBindings; std::shared_ptr memory; std::vector captured; diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp index d3f3da21fa21..62a950402dc1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp @@ -58,6 +58,7 @@ struct PreparedGraphicsStage { ShaderRecompiler::ShaderStage stage = ShaderRecompiler::ShaderStage::Vertex; std::uint32_t pushOffset = 0; std::shared_ptr registration; + bool heapVariant = false; }; std::vector PrepareGraphicsStages(const DrawDecode& decoded, const ShaderRecompiler::SpirvTarget& target, bool deferUnprepared = false); @@ -130,6 +131,10 @@ struct StageCapture { std::uint32_t pushOffset = 0; ShaderRecompiler::SrtUserDataUse userDataUse; std::uint64_t userDataMask = ~std::uint64_t{0}; + bool direct = false; + bool ring = false; + std::shared_ptr heapWords; + std::shared_ptr> heapReadWords; }; struct RelocatableUserWord { diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp index 50844922e83f..2580db29d7b9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp @@ -60,6 +60,7 @@ class DrawPipeline { static bool MetadataPassesPipelined(); static void CountPipelinedMetadataPass(); static std::uint64_t PipelinedMetadataPasses(); + void QueuedWrites(std::vector& out); private: struct Item { Commit commit; @@ -125,6 +126,7 @@ class DrawFinisher { LabelLookup PendingLabel(std::uint64_t address, std::size_t bytes, std::uint64_t& value); bool PendingOverlapsAny(std::span ranges); bool PendingKey(std::uint64_t key, std::uint64_t shape); + void PendingWrites(std::vector& out); enum class DrainSite : std::uint32_t { Lookup, Reads, Packet, Kept, Count }; static void NoteDrain(DrainSite site, bool drained); static std::string DrainText(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp new file mode 100644 index 000000000000..151abcd55cb3 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -0,0 +1,57 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_HEAPSTAGES_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_HEAPSTAGES_HPP + +#include "Optimization/ResourceProgram.hpp" +#include "UserDataUse.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::DriverDetail { + +bool HeapFragmentsEnabled(); +bool HeapRefused(); +bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage); +bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex); +std::optional HeapFragmentKnown(const void* snapshot, std::size_t codeOffset); +void NoteHeapFragment(const void* snapshot, std::size_t codeOffset, bool eligible); +bool HeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress = false); +bool HeapPairRefused(std::uint64_t pair); +void RefuseHeapPair(std::uint64_t pair); + +class HeapDrawOff { +public: + HeapDrawOff(); + ~HeapDrawOff(); + HeapDrawOff(const HeapDrawOff&) = delete; + HeapDrawOff& operator=(const HeapDrawOff&) = delete; + +private: + bool previous; +}; + +bool SampleHeapStageVerify(); + +struct HeapStageReads { + std::vector> ranges; + std::vector values; + ShaderRecompiler::SrtUserDataUse userDataUse; + std::shared_ptr capture; + bool complete = false; +}; + +std::shared_ptr MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase, ShaderRecompiler::HeapStageWords* words = nullptr, std::shared_ptr* sharedWords = nullptr, HeapStageReads* stageReads = nullptr); +void NoteHeapDirect(); +void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const ShaderRecompiler::RecompileResult& expected, const ShaderRecompiler::ResourceCapture* expectedCapture = nullptr); +std::uint64_t HeapStagesTaken(); +std::shared_ptr PatchedHeapResult(const ShaderRecompiler::RecompileResult& shared, const ShaderRecompiler::HeapStageWords& words); +void VerifyHeapAccessor(const Graphics::CompiledShader& stage); +void VerifyRingWords(const ShaderRecompiler::RecompileResult& kept, const ShaderRecompiler::HeapStageWords& ring, const ShaderRecompiler::RecompileResult& fresh, const ShaderRecompiler::HeapStageWords* freshWords); + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp index 18303f9f7b54..a177047eae7a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp @@ -191,7 +191,7 @@ class Driver { std::shared_ptr decodeDraw(const QueueState& queue, const Submission& submission, const Graphics::Context& context); void resolveDrawDecode(const QueueState& queue, const Submission& submission, const Graphics::Context& context, std::shared_ptr& decode, bool registerKey, std::uint64_t drawKey, bool profile); void lookupDraw(const Submission& submission, const std::shared_ptr& localDevice, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector& programs, const std::vector& roles, const std::vector>& vertexInfos, bool useDrawEntries, bool registerKey, bool profile, std::uint64_t& drawKey, std::shared_ptr& entry, std::vector>& matched, std::vector>& matchedRegions, bool& drawHit, bool& verifyHit, DrawPhaseTiming& phaseTiming, std::array& phaseMs, const std::shared_ptr& dataEntry, DrawDataCandidates& dataCandidates, std::vector& stageData); - std::shared_ptr materializeDrawStage(std::size_t i, std::uint32_t pushOffset, const QueueState& queue, const Submission& submission, std::size_t packetOffset, std::uint64_t traceToken, const std::vector& programs, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector>& vertexInfos, std::vector& memory, const std::vector& linked, const Pm4::DrawParameters& drawParameters, const std::shared_ptr& localDevice, ShaderMemory& shaderMemory, std::vector& stageCaptures, std::vector& recompiled, bool drawHit, const std::vector>& matched, const std::vector>& matchedRegions, bool profile, std::uint64_t dumpTarget, std::uint64_t dumpSlot1, std::uint64_t& captures, DrawPhaseTiming& phaseTiming, std::array& phaseMs, std::string& rejected, const std::optional& meshBarycentrics); + std::shared_ptr materializeDrawStage(std::size_t i, std::uint32_t pushOffset, const QueueState& queue, const Submission& submission, std::size_t packetOffset, std::uint64_t traceToken, const std::vector& programs, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector>& vertexInfos, std::vector& memory, const std::vector& linked, const Pm4::DrawParameters& drawParameters, const std::shared_ptr& localDevice, ShaderMemory& shaderMemory, std::vector& stageCaptures, std::vector& recompiled, bool drawHit, const std::vector>& matched, const std::vector>& matchedRegions, bool profile, std::uint64_t dumpTarget, std::uint64_t dumpSlot1, std::uint64_t& captures, DrawPhaseTiming& phaseTiming, std::array& phaseMs, std::string& rejected, const std::optional& meshBarycentrics, bool heapPartners = true); static void recordStageDataPositions(DispatchVariant& variant, const ShaderRecompiler::ResourceCapture& capture, const std::vector& decodeReads); void cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawParameters& drawParameters, const std::optional& indirectCpu, const std::vector& programs, const std::vector& stageCaptures, const std::vector>& vertexInfos, const std::vector>& decodeReads, bool verifyHit, const std::vector>& matched, const std::vector& stageData, std::vector>& fresh, std::uint64_t drawKey, bool registerKey, const std::shared_ptr& decode, DrawPhaseTiming& phaseTiming, const std::vector& reused, const std::shared_ptr& entry, std::uint64_t shapeKey, bool shapeNeedsEntry = false); static bool drawPrecheck(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp index b1907257c40a..1daa2e4ff657 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp @@ -236,6 +236,7 @@ ShaderRecompiler::RectListShaders DrawRectangle(const ShaderSnapshot& front, con std::shared_ptr SourceHandleFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request); ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request); std::shared_ptr CaptureInvocation(ShaderMemory& memory, const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request, ShaderRecompiler::PreparedShaderInvocation& invocation); +bool PreparedHeapStage(const ShaderSnapshot& snapshot, std::size_t codeOffset); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp index 8dbf80c316ec..74ff3b91688e 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp @@ -64,6 +64,7 @@ class VulkanDevice { void SavePipelineCache(); // Compute pipelines this device built, by dispatches and by the journal replay (tests). std::uint64_t ComputePipelinesCreated() const; + std::uint64_t DescriptorHeapComputePipelines() const; ~VulkanDevice(); VulkanDevice(const VulkanDevice&) = delete; VulkanDevice& operator=(const VulkanDevice&) = delete; @@ -355,6 +356,7 @@ class VulkanDevice { IndirectDrawSupport DrawIndirectSupport() const; void EnqueueDraw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots = {}); bool PrebuildGraphicsLibraries(const Graphics::ShaderStages& stages, std::span shaders); + Graphics::Context GraphicsContext() const { return graphicsContext(); } public: // The device's Graphics::Context: a copy of the one built at setup (its instance functions diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index 8110338e839c..d7fac001535a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -2,6 +2,7 @@ #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DrawWriteRanges.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/BufferCopy.hpp" @@ -168,6 +169,9 @@ void Driver::dispatch(QueueState& queue, std::span packet, localDevice->ComputeTarget((packet[4] & 0x8000u) != 0 ? 32u : 64u), {0, 0, 0, threadGroup != std::array{} ? 0u : 128u} }; + constexpr std::size_t computeHeapKey = std::size_t{1} << 61u; + if (request.target.gpuResolvedImages && HeapFragmentKnown(&snapshot, codeOffset | computeHeapKey) == std::optional(false)) request.target.gpuResolvedImages = false; + if (threadGroup != std::array{}) request.target.gpuResolvedImages = false; static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; static double captureMs = 0, keyMs = 0, recompileMs = 0, deviceMs = 0; static std::uint64_t cacheHits = 0; @@ -367,6 +371,15 @@ void Driver::dispatch(QueueState& queue, std::span packet, timing.Mark("capture_resources"); compiledResult = invocation.Materialize(*capture); + if (compiledResult->gpuResolvedImages && !HeapStageMappable(*compiledResult, compiledResult->workgroupMemoryDwords != 0)) { + NoteHeapFragment(&snapshot, codeOffset | computeHeapKey, false); + request.target.gpuResolvedImages = false; + invocation = InvocationFor(snapshot, codeOffset, request); + capture = shaderMemory->Capture(invocation); + captured = shaderMemory->Regions(); + request.context.memory = captured; + compiledResult = invocation.Materialize(*capture); + } timing.Mark("materialize"); if (compiledResult->cacheHit) ++cacheHits; const auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - started).count(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp index 99c7b3542621..87495ad34df0 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp @@ -21,6 +21,7 @@ void Driver::appendEntryRegions(const DispatchVariant& variant, std::vector Driver::patchDataWords(const DispatchVariant& variant, const std::vector& words) { + if (variant.ringFlat != nullptr) return variant.compiled; auto patched = std::make_shared(*variant.compiled); auto& descriptor = patched->bindings[variant.flatBinding].guestDescriptor; for (std::size_t k = 0; k < variant.dataPositions.size(); ++k) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 477c943f721e..d7ab7abf638e 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -6,6 +6,8 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DrawWriteRanges.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawProgramTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DrawWriteRanges.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" @@ -223,7 +225,7 @@ void noteHeld(HeldReason reason) { std::optional writesBeyondTargets(const ShaderRecompiler::RecompileResult& compiled) { using Role = ShaderRecompiler::DescriptorRole; for (const auto& binding : compiled.bindings) { - if (binding.role == Role::BdaPagetable && Graphics::ShaderStoresThroughAddresses(compiled.spirv)) return HeldReason::Bda; + if (binding.role == Role::BdaPagetable && compiled.bdaStores) return HeldReason::Bda; if (binding.role == Role::GuestBuffers) { for (std::uint32_t element = 0; element < binding.count; ++element) { if (element >= binding.bufferWritten.size() || binding.bufferWritten[element]) return HeldReason::Buffer; @@ -872,11 +874,48 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { std::memcpy(words.data() + offset, region.bytes.data(), count * sizeof(std::uint32_t)); } }; + const auto buildRingWords = [&](std::size_t i, const DispatchVariant& variant) { + auto words = std::make_shared(); + const auto& user = programs[i].userData; + for (const auto index : variant.compiled->heapUserWords) { + require(index < user.size(), "a ring vertex template reads a user word the draw does not have"); + words->userData.push_back(user[index]); + } + if (variant.ringAttributes != nullptr) words->vertexAttributes = *variant.ringAttributes; + if (variant.ringFlat != nullptr) { + words->flattenedSrt = *variant.ringFlat; + if (&variant == matched[i].get() && stageData[i].compiled != nullptr) { + for (std::size_t k = 0; k < variant.dataPositions.size(); ++k) { + if (variant.dataSlots[k] < words->flattenedSrt.size()) words->flattenedSrt[variant.dataSlots[k]] = stageData[i].words[variant.dataPositions[k]]; + } + } + } + if (variant.ringBindings != nullptr) { + words->bindings = *variant.ringBindings; + require(words->bindings.size() == variant.compiled->bindings.size(), "a ring vertex hit's bindings differ in number from its template"); + for (std::size_t index = 0; index < words->bindings.size(); ++index) { + const auto role = variant.compiled->bindings[index].role; + if (role == ShaderRecompiler::DescriptorRole::ShaderData || role == ShaderRecompiler::DescriptorRole::FlattenedSrt) words->bindings[index].clear(); + } + } + ShaderRecompiler::CompleteHeapDataWords(*variant.compiled, *words); + if (words->vertexAttributes.empty()) return words; + decodeVertexInfo(i); + require(vertexInfos[i].has_value(), "a ring vertex hit has no vertex stage info"); + const auto& vertex = *vertexInfos[i]; + for (auto& attribute : words->vertexAttributes) { + require(attribute.location < vertex.resourcesNum && attribute.location < vertex.resources.size(), "a ring vertex attribute lies outside the draw's vertex resources"); + attribute.resource = vertex.resources[attribute.location]; + if (vertex.fetchEmbedded) attribute.fetchIndex = vertex.resourcesDst[attribute.location].fetchIndex; + } + return words; + }; const auto verifyDataStage = [&](std::size_t i, const DispatchVariant& kept) { std::vector> runs; std::vector words; freshRuns(i, runs, words); const auto& compiled = *stageCaptures[i].compiled; + if (kept.ring) VerifyRingWords(*kept.compiled, *buildRingWords(i, kept), *stageCaptures[i].compiled, stageCaptures[i].heapWords.get()); const char* what = runs != kept.runs ? "runs" : words != kept.words ? "words" : vertexInfos[i].has_value() != (kept.vertexInfo != nullptr) || (vertexInfos[i] && !sameVertexInfo(*vertexInfos[i], *kept.vertexInfo)) ? "vertex stage info" : compiled.variantId != kept.compiled->variantId ? "variant" : compiled.pushConstants != kept.compiled->pushConstants ? "push constants" : nullptr; ++dataVerified; if (what == nullptr) return; @@ -900,62 +939,117 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { std::snprintf(message, sizeof(message), "APS5_VERIFY_DRAW_DATA_HITS: stage %zu (program 0x%llx) of a stage data hit differs from its full build in its %s (%zu data positions refreshed)", i, static_cast(programs[i].binary.codeAddress), what, kept.dataPositions.size()); throw std::runtime_error(message); }; + const auto ringWords = [&](std::size_t i) { + if (!matched[i]->ring) return; + stageCaptures[i].heapWords = buildRingWords(i, *matched[i]); + stageCaptures[i].direct = true; + stageCaptures[i].ring = true; + }; std::optional indirectCpu; std::size_t completedSubdraws = 0; std::vector pushOffsets(programs.size(), 0); std::optional meshBarycentrics; std::vector resultIndex(programs.size(), 0); - for (std::size_t i = 0; i < programs.size(); ++i) { - if (roles[i] == Role::GeometryBack) continue; - const auto& program = programs[i]; - pushCursorBytes = Graphics::StagePushOffset(pushCursorBytes, program.binary.stage, localDevice->GraphicsPipelineLibraries()); - pushOffsets[i] = pushCursorBytes; - if (drawHit) { + const bool heapCheck = !drawHit && Graphics::DescriptorHeapEnabled(); + std::uint64_t heapPair = 0xcbf29ce484222325ull; + for (const auto& program : programs) heapPair = (heapPair ^ reinterpret_cast(program.snapshot.get()) ^ (static_cast(program.codeOffset) << 1u)) * 0x100000001b3ull; + const bool heapPairRefused = heapCheck && HeapPairRefused(heapPair); + const auto runStages = [&]() -> std::optional { + for (std::size_t i = 0; i < programs.size(); ++i) { + if (roles[i] == Role::GeometryBack) continue; + const auto& program = programs[i]; + pushCursorBytes = Graphics::StagePushOffset(pushCursorBytes, program.binary.stage, localDevice->GraphicsPipelineLibraries()); + pushOffsets[i] = pushCursorBytes; + if (drawHit) { - programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); - memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); - } else { - const auto candidate = std::find_if(dataCandidates[i].begin(), dataCandidates[i].end(), [&](const auto& kept) { return kept.first->pushOffset == pushCursorBytes; }); - if (candidate != dataCandidates[i].end() && !verifyDrawDataHits()) { - matched[i] = candidate->first; - matchedRegions[i] = std::move(candidate->second); - reused[i] = true; programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); + ringWords(i); } else { - if (!dataCandidates[i].empty() && !verifyDrawDataHits()) decodeVertexInfo(i); - if (program.binary.stage == ShaderRecompiler::ShaderStage::Fragment) { - for (auto previous = i; previous-- > 0;) { - if (programResults[previous] == nullptr) continue; - pixel = Graphics::DefaultUnexportedInputs(decode->pixel, programResults[previous]->parameterExports); - break; + const bool afterHeap = std::any_of(programResults.begin(), programResults.begin() + static_cast(i), [](const ShaderRecompiler::RecompileResult* earlier) { return earlier != nullptr && earlier->gpuResolvedImages; }); + if (reused[i] && afterHeap && !matched[i]->compiled->gpuResolvedImages) { + reused[i] = false; + matched[i] = nullptr; + matchedRegions[i].clear(); + } + const auto candidate = reused[i] ? dataCandidates[i].end() : std::find_if(dataCandidates[i].begin(), dataCandidates[i].end(), [&](const auto& kept) { return kept.first->pushOffset == pushCursorBytes && (!afterHeap || kept.first->compiled->gpuResolvedImages); }); + if (reused[i]) { + programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); + memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); + ringWords(i); + } else if (candidate != dataCandidates[i].end() && !verifyDrawDataHits()) { + matched[i] = candidate->first; + matchedRegions[i] = std::move(candidate->second); + reused[i] = true; + programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); + memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); + ringWords(i); + } else { + if (!dataCandidates[i].empty() && !verifyDrawDataHits()) decodeVertexInfo(i); + if (program.binary.stage == ShaderRecompiler::ShaderStage::Fragment) { + for (auto previous = i; previous-- > 0;) { + if (programResults[previous] == nullptr) continue; + pixel = Graphics::DefaultUnexportedInputs(decode->pixel, programResults[previous]->parameterExports); + break; + } } + compiledStages.push_back(materializeDrawStage(i, pushCursorBytes, queue, submission, packetOffset, trace.token, programs, graphics, pixel, vertexInfos, memory, linked, drawParameters, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics, !heapPairRefused)); + if (!rejected.empty()) return DrawVerdict::Rejected; + programResults[i] = compiledStages.back().get(); + if (verifyHit && matched[i] != nullptr && matched[i]->ring) VerifyRingWords(*matched[i]->compiled, *buildRingWords(i, *matched[i]), *programResults[i], stageCaptures[i].heapWords.get()); + if (candidate != dataCandidates[i].end()) verifyDataStage(i, *candidate->first); + if (stageData[i].compiled != nullptr && verifyDrawDataHits()) verifyStageData(i); } - compiledStages.push_back(materializeDrawStage(i, pushCursorBytes, queue, submission, packetOffset, trace.token, programs, graphics, pixel, vertexInfos, memory, linked, drawParameters, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics)); - if (!rejected.empty()) return DrawVerdict::Rejected; - programResults[i] = compiledStages.back().get(); - if (candidate != dataCandidates[i].end()) verifyDataStage(i, *candidate->first); - if (stageData[i].compiled != nullptr && verifyDrawDataHits()) verifyStageData(i); + if (dataEntry != nullptr && reused[i]) ++dataStagesReused; + else if (dataEntry != nullptr) ++dataStagesCompiled; } - if (dataEntry != nullptr && reused[i]) ++dataStagesReused; - else if (dataEntry != nullptr) ++dataStagesCompiled; - } - const auto& result = *programResults[i]; - if (i == 0 && drawParameters.indirect) { - indirectCpu = ClassifyIndirectDraw(result, graphics, programs.front(), localDevice, drawParameters, traceIndirect); - if (EmptyIndirectSkip()) CpuIndirectPrograms()[programs.front().binary.codeAddress] = indirectCpu.has_value(); - } else if (i == 0) { - fold(result, drawParameters); + const auto& result = *programResults[i]; + if (i == 0 && drawParameters.indirect) { + indirectCpu = ClassifyIndirectDraw(result, graphics, programs.front(), localDevice, drawParameters, traceIndirect); + if (EmptyIndirectSkip()) CpuIndirectPrograms()[programs.front().binary.codeAddress] = indirectCpu.has_value(); + } else if (i == 0) { + fold(result, drawParameters); + } + try { + const auto slotEnd = (pushCursorBytes / Graphics::PipelinePushSlotBytes + 1u) * Graphics::PipelinePushSlotBytes; + require(result.pushConstants.size() <= slotEnd - pushCursorBytes, "stage push constants exceed the pipeline push constant block"); + stages.push_back({program.binary.stage, &result, result.pushConstants.empty() ? 0u : pushCursorBytes, stageCaptures[i].heapWords.get()}); + pushCursorBytes += static_cast(result.pushConstants.size()); + } catch (...) { + TraceMaterializationFailure(trace.token, submission, packetOffset, "push-constant-validation", completedSubdraws, std::current_exception()); + throw; + } + if (stages.back().heap != nullptr && SampleHeapStageVerify()) VerifyHeapAccessor(stages.back()); } - try { - const auto slotEnd = (pushCursorBytes / Graphics::PipelinePushSlotBytes + 1u) * Graphics::PipelinePushSlotBytes; - require(result.pushConstants.size() <= slotEnd - pushCursorBytes, "stage push constants exceed the pipeline push constant block"); - stages.push_back({program.binary.stage, &result, result.pushConstants.empty() ? 0u : pushCursorBytes}); - pushCursorBytes += static_cast(result.pushConstants.size()); - } catch (...) { - TraceMaterializationFailure(trace.token, submission, packetOffset, "push-constant-validation", completedSubdraws, std::current_exception()); - throw; + return std::nullopt; + }; + const auto mixedHeap = [&] { + const auto guest = [&](const Graphics::CompiledShader& stage) { return std::ranges::find(programResults, stage.program) != programResults.end(); }; + return std::ranges::any_of(stages, [](const Graphics::CompiledShader& stage) { return stage.program->gpuResolvedImages; }) && std::ranges::any_of(stages, [&](const Graphics::CompiledShader& stage) { return guest(stage) && !stage.program->gpuResolvedImages; }); + }; + const auto stagesBefore = stages.size(); + const auto compiledBefore = compiledStages.size(); + const auto pushBefore = pushCursorBytes; + const auto parametersBefore = heapCheck ? std::optional(drawParameters) : std::nullopt; + const auto pixelBefore = heapCheck ? std::optional(pixel) : std::nullopt; + if (const auto verdict = runStages()) return *verdict; + for (std::uint32_t retry = 0; heapCheck && mixedHeap(); ++retry) { + require(retry < 2u, "a draw mixes GPU-mode and per-draw stages after taking the per-draw path"); + if (retry == 1u) RefuseHeapPair(heapPair); + stages.resize(stagesBefore); + compiledStages.resize(compiledBefore); + pushCursorBytes = pushBefore; + drawParameters = *parametersBefore; + pixel = *pixelBefore; + std::fill(programResults.begin(), programResults.end(), nullptr); + for (std::size_t i = 0; i < programs.size(); ++i) { + if (!reused[i]) stageCaptures[i] = {}; } + dataStagesReused = dataStagesCompiled = dataVerified = stageDataVerified = 0; + indirectCpu.reset(); + std::optional heapOff; + if (retry == 1u) heapOff.emplace(); + if (const auto verdict = runStages()) return *verdict; } if (stageDataVerified != 0) { @@ -977,7 +1071,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { }; for (std::size_t i = 0; i < programs.size(); ++i) { const auto& capture = stageCaptures[i]; - if (reused[i] || capture.compiled == nullptr || !CacheableResult(*capture.compiled)) continue; + if (reused[i] || capture.compiled == nullptr || (capture.direct && !capture.ring) || !CacheableResult(*capture.compiled)) continue; stored = true; const auto& words = programs[i].userData; for (std::size_t w = 0; w < words.size(); ++w) { @@ -1035,10 +1129,11 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { if (programResults[0]->meshBarycentrics != meshBarycentrics) { const auto pushBytes = programResults[0]->pushConstants.size(); const auto exports = programResults[0]->parameterExports; - compiledStages.push_back(materializeDrawStage(0, pushOffsets[0], queue, submission, packetOffset, traceToken, programs, graphics, pixel, vertexInfos, memory, linked, drawParameters, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics)); + compiledStages.push_back(materializeDrawStage(0, pushOffsets[0], queue, submission, packetOffset, traceToken, programs, graphics, pixel, vertexInfos, memory, linked, drawParameters, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics, !heapPairRefused)); if (!rejected.empty()) return DrawVerdict::Rejected; programResults[0] = compiledStages.back().get(); stages[0].program = programResults[0]; + stages[0].heap = stageCaptures[0].heapWords.get(); require(programResults[0]->pushConstants.size() == pushBytes && programResults[0]->parameterExports == exports, "pairing the mesh program with its pixel shader changed the push constants or the parameter exports the pixel shader was built for"); } require(programResults[0]->meshBarycentrics == meshBarycentrics, "the mesh program was compiled for a different barycentric layout than its pixel shader"); @@ -1157,6 +1252,9 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { result = *materializeDrawStage(programIndex, pushOffsets[programIndex], queue, submission, packetOffset, trace.token, programs, graphics, pixel, vertexInfos, memory, linked, programs[programIndex].binary.stage == Stage::TessellationControl || programs[programIndex].binary.stage == Stage::TessellationEvaluation ? direct : drawParameters, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics); if (!rejected.empty()) return DrawVerdict::Rejected; require(result.pushConstants.size() == pushBytes, "patched program changed its push constant layout"); + for (auto& stage : stages) { + if (stage.program == &result) stage.heap = stageCaptures[programIndex].heapWords.get(); + } } fold(*programResults[0], direct); if (graphics.rectList && patched.contains(0)) buildRectList(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index a6f6b5ebd968..7d920f1bdb35 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -1,3 +1,14 @@ +#include +#include +#include +#include +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include +#include +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" @@ -60,11 +71,17 @@ void TraceShaderRequestFailure(std::uint64_t token, const Submission& submission } -std::shared_ptr Driver::materializeDrawStage(std::size_t i, std::uint32_t pushOffset, const QueueState& queue, const Submission& submission, std::size_t packetOffset, std::uint64_t traceToken, const std::vector& programs, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector>& vertexInfos, std::vector& memory, const std::vector& linked, const Pm4::DrawParameters& drawParameters, const std::shared_ptr& localDevice, ShaderMemory& shaderMemory, std::vector& stageCaptures, std::vector& recompiled, bool drawHit, const std::vector>& matched, const std::vector>& matchedRegions, bool profile, std::uint64_t dumpTarget, std::uint64_t dumpSlot1, std::uint64_t& captures, DrawPhaseTiming& phaseTiming, std::array& phaseMs, std::string& rejected, const std::optional& meshBarycentrics) try { +std::shared_ptr Driver::materializeDrawStage(std::size_t i, std::uint32_t pushOffset, const QueueState& queue, const Submission& submission, std::size_t packetOffset, std::uint64_t traceToken, const std::vector& programs, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector>& vertexInfos, std::vector& memory, const std::vector& linked, const Pm4::DrawParameters& drawParameters, const std::shared_ptr& localDevice, ShaderMemory& shaderMemory, std::vector& stageCaptures, std::vector& recompiled, bool drawHit, const std::vector>& matched, const std::vector>& matchedRegions, bool profile, std::uint64_t dumpTarget, std::uint64_t dumpSlot1, std::uint64_t& captures, DrawPhaseTiming& phaseTiming, std::array& phaseMs, std::string& rejected, const std::optional& meshBarycentrics, bool heapPartners) try { PerformanceTimer timing("Shader.DrawStage"); using Stage = ShaderRecompiler::ShaderStage; phaseTiming.Phase(DrawRowVectors); const auto& program = programs[i]; + const auto tailMask = [&]() -> std::uint64_t { + const auto& tail = program.snapshot->userDataTailRegister; + if (!tail || *tail < program.firstUserSgpr) return 0; + const auto index = *tail - program.firstUserSgpr; + return index + 1u < 64u ? std::uint64_t{3} << index : ~std::uint64_t{0}; + }; const auto waveSize = program.binary.stage == Stage::Fragment ? graphics.stages.fragmentWaveSize : graphics.stages.vertexWaveSize; ShaderRecompiler::RecompileRequest request{ program.binary, @@ -74,16 +91,45 @@ std::shared_ptr Driver::materializeDraw ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, linked, graphics.stages.mesh, graphics.stages.tessellation, {drawParameters.indexAddress, drawParameters.indexCount, drawParameters.indexSize, drawParameters.instanceCount}, program.binary.stage == Stage::Mesh ? meshBarycentrics : std::nullopt} }; const auto waitedBefore = traceCapSync() || profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0; - auto invocation = [&] { + const bool heapCandidate = heapPartners && (program.binary.stage == Stage::Fragment || HeapPreRasterStage(program.binary.stage)) && HeapFragmentsEnabled(); + const auto fragmentOnHeap = [&] { + const auto fragment = std::find_if(programs.begin(), programs.end(), [](const DrawProgram& candidate) { return candidate.binary.stage == Stage::Fragment; }); + if (fragment == programs.end()) return true; + const auto known = HeapFragmentKnown(fragment->snapshot.get(), fragment->codeOffset); + return known.has_value() ? *known : PreparedHeapStage(*fragment->snapshot, fragment->codeOffset); + }; + const bool heapVertex = request.target.descriptorMemory && HeapPreRasterStage(program.binary.stage) && fragmentOnHeap(); + const auto heapKey = program.codeOffset | (heapVertex ? std::size_t{1} << 62u : std::size_t{0}); + const auto heapKnown = heapCandidate ? HeapFragmentKnown(program.snapshot.get(), heapKey) : std::nullopt; + if (heapKnown.value_or(false)) request.target.gpuResolvedImages = true; + const auto invocationFor = [&] { try { return InvocationFor(*program.snapshot, program.codeOffset, request); } catch (...) { TraceShaderRequestFailure(traceToken, submission, packetOffset, program, std::current_exception()); throw; } - }(); + }; + auto invocation = invocationFor(); + const auto heapEligible = [&](const std::shared_ptr& plan) { return HeapStageEligible(program.binary.stage, plan.get(), heapVertex); }; + if (heapKnown.value_or(false) && !heapEligible(invocation.Plan())) { + NoteHeapFragment(program.snapshot.get(), heapKey, false); + request.target.gpuResolvedImages = false; + invocation = invocationFor(); + } else if (heapCandidate && !heapKnown.has_value()) { + const bool eligible = heapEligible(invocation.Plan()); + NoteHeapFragment(program.snapshot.get(), heapKey, eligible); + if (eligible) { + request.target.gpuResolvedImages = true; + invocation = invocationFor(); + } + } timing.Mark("prepared_invocation"); auto& stageCapture = stageCaptures[i]; + stageCapture.direct = false; + stageCapture.ring = false; + stageCapture.heapReadWords.reset(); + stageCapture.capture.reset(); stageCapture.forgetSerial = GuestMemory::ForgetSerial(); stageCapture.pushOffset = pushOffset; const auto named = [&](const std::exception& error, std::span regions) { @@ -102,6 +148,58 @@ std::shared_ptr Driver::materializeDraw where << ": "; return std::runtime_error(where.str() + error.what()); }; + const auto unmapped = [&] { + NoteHeapFragment(program.snapshot.get(), heapKey, false); + return materializeDrawStage(i, pushOffset, queue, submission, packetOffset, traceToken, programs, graphics, pixel, vertexInfos, memory, linked, drawParameters, localDevice, shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics, heapPartners); + }; + if (request.target.gpuResolvedImages) { + auto words = std::make_shared(); + std::shared_ptr reusedWords; + HeapStageReads reads; + decltype(MaterializeHeapStage(invocation, program.userData, program.binary.codeAddress, words.get(), &reusedWords, &reads)) direct; + try { + direct = MaterializeHeapStage(invocation, program.userData, program.binary.codeAddress, words.get(), &reusedWords, &reads); + } catch (const std::exception& error) { + throw named(error, request.context.memory); + } + if (direct == nullptr) goto heapCapture; + if (!HeapStageMappable(*direct)) return unmapped(); + NoteHeapDirect(); + stageCapture.compiled = std::move(direct); + if (reusedWords != nullptr) words = std::const_pointer_cast(std::move(reusedWords)); + stageCapture.heapWords = stageCapture.compiled->heapTemplateId != 0 ? std::move(words) : nullptr; + if (SampleHeapStageVerify()) { + const auto fullCapture = shaderMemory.Capture(invocation); + const auto expected = invocation.Materialize(*fullCapture); + static_cast(shaderMemory.TakeRecentRegions()); + NoteHeapDirectVerify(stageCapture.heapWords != nullptr ? *PatchedHeapResult(*stageCapture.compiled, *stageCapture.heapWords) : *stageCapture.compiled, *expected, fullCapture.get()); + } + stageCapture.regions.clear(); + stageCapture.direct = true; + if (reads.complete) { + auto owned = std::make_shared>(std::move(reads.values)); + std::size_t cursor = 0; + for (const auto& [begin, end] : reads.ranges) { + const auto count = static_cast((end - begin) / sizeof(std::uint32_t)); + stageCapture.regions.push_back({begin, std::as_bytes(std::span(owned->data() + cursor, count))}); + cursor += count; + } + stageCapture.heapReadWords = std::move(owned); + stageCapture.userDataUse = reads.userDataUse; + stageCapture.capture = std::move(reads.capture); + auto mask = reads.userDataUse.asValue | reads.userDataUse.asBase | stageCapture.compiled->userDataRegisterReads | tailMask(); + if (vertexInfos[i]) { + for (const auto reg : {static_cast(vertexInfos[i]->fetchAttribReg), static_cast(vertexInfos[i]->fetchBufferReg)}) mask |= reg + 1u < 64u ? std::uint64_t{3} << reg : ~std::uint64_t{0}; + } + stageCapture.userDataMask = mask; + stageCapture.ring = true; + } + recompiled[i] = true; + timing.Mark("heap_direct"); + phaseTiming.Phase(DrawRowRecompile); + return stageCapture.compiled; + } +heapCapture: const auto capture = [&] { const SampledReadScope sampling(evidenceReads); try { @@ -152,16 +250,30 @@ std::shared_ptr Driver::materializeDraw phaseTiming.Phase(DrawRowCapture); timing.Mark("capture_resources"); - try { - stageCapture.compiled = invocation.Materialize(*capture); - stageCapture.capture = capture; - } catch (const std::exception& error) { - TraceMaterializationFailure(traceToken, submission, packetOffset, i, "capture-or-materialize", std::current_exception()); - throw named(error, request.context.memory); + stageCapture.heapWords.reset(); + if (request.target.gpuResolvedImages) { + auto words = std::make_shared(); + if (auto shared = invocation.MaterializeHeap(*capture, *words)) { + stageCapture.compiled = std::move(shared); + stageCapture.heapWords = std::move(words); + stageCapture.direct = true; + stageCapture.ring = true; + if (SampleHeapStageVerify()) NoteHeapDirectVerify(*PatchedHeapResult(*stageCapture.compiled, *stageCapture.heapWords), *invocation.Materialize(*capture)); + } + } + if (stageCapture.heapWords == nullptr) { + try { + stageCapture.compiled = invocation.Materialize(*capture); + } catch (const std::exception& error) { + TraceMaterializationFailure(traceToken, submission, packetOffset, i, "capture-or-materialize", std::current_exception()); + throw named(error, request.context.memory); + } } + if (stageCapture.compiled->gpuResolvedImages && !HeapStageMappable(*stageCapture.compiled)) return unmapped(); + stageCapture.capture = capture; timing.Mark("materialize"); const auto walked = capture->userDataUse.asValue | capture->userDataUse.asBase; - auto mask = walked == 0 ? ~std::uint64_t{0} : walked | stageCapture.compiled->userDataRegisterReads; + auto mask = walked == 0 ? ~std::uint64_t{0} : walked | stageCapture.compiled->userDataRegisterReads | tailMask(); if (vertexInfos[i]) { for (const auto reg : {static_cast(vertexInfos[i]->fetchAttribReg), static_cast(vertexInfos[i]->fetchBufferReg)}) { mask |= reg + 1u < 64u ? std::uint64_t{3} << reg : ~std::uint64_t{0}; @@ -180,7 +292,7 @@ void Driver::recordStageDataPositions(DispatchVariant& variant, const ShaderReco for (std::size_t b = 0; b < compiled.bindings.size(); ++b) { if (compiled.bindings[b].role != ShaderRecompiler::DescriptorRole::FlattenedSrt) continue; variant.flatBinding = static_cast(b); - static_cast(DataWordPositions(variant.runs, capture.readTrace.leaves, capture.readTrace.otherReads, variant.words, compiled.bindings[b].guestDescriptor, variant.dataPositions, variant.dataSlots)); + static_cast(DataWordPositions(variant.runs, capture.readTrace.leaves, capture.readTrace.otherReads, variant.words, variant.ringFlat != nullptr ? *variant.ringFlat : compiled.bindings[b].guestDescriptor, variant.dataPositions, variant.dataSlots)); break; } if (variant.dataPositions.empty() || decodeReads.empty()) return; @@ -219,7 +331,7 @@ void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawP fresh[i] = matched[i]; continue; } - if (stageCapture.compiled == nullptr || !CacheableResult(*stageCapture.compiled)) continue; + if (stageCapture.compiled == nullptr || (stageCapture.direct && !stageCapture.ring) || !CacheableResult(*stageCapture.compiled)) continue; auto variant = std::make_shared(); variant->compiled = stageCapture.compiled; if (programs[i].binary.stage == ShaderRecompiler::ShaderStage::Mesh) { @@ -229,6 +341,12 @@ void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawP variant->forgetSerial = stageCapture.forgetSerial; variant->pushOffset = stageCapture.pushOffset; variant->userDataMask = stageCapture.userDataMask; + if (stageCapture.ring && stageCapture.heapWords != nullptr) { + variant->ring = true; + variant->ringAttributes = std::make_shared>(stageCapture.heapWords->vertexAttributes); + if (!stageCapture.heapWords->flattenedSrt.empty()) variant->ringFlat = std::make_shared>(stageCapture.heapWords->flattenedSrt); + if (!stageCapture.heapWords->bindings.empty()) variant->ringBindings = std::make_shared>>(stageCapture.heapWords->bindings); + } if (vertexInfos[i]) variant->vertexInfo = std::make_shared(*vertexInfos[i]); std::vector regions(stageCapture.regions.begin(), stageCapture.regions.end()); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp index ec65e9734eaf..5cee762df110 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include #include @@ -8,6 +9,7 @@ namespace AgcDriver::DriverDetail { void Driver::lookupDraw(const Submission& submission, const std::shared_ptr& localDevice, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector& programs, const std::vector& roles, const std::vector>& vertexInfos, bool useDrawEntries, bool registerKey, bool profile, std::uint64_t& drawKey, std::shared_ptr& entry, std::vector>& matched, std::vector>& matchedRegions, bool& drawHit, bool& verifyHit, DrawPhaseTiming& phaseTiming, std::array& phaseMs, const std::shared_ptr& dataEntry, DrawDataCandidates& dataCandidates, std::vector& stageData) { using Role = ShaderRecompiler::ProgramRole; + const bool heapRefused = HeapRefused(); if (useDrawEntries) { if (!registerKey) { drawKey = 0xcbf29ce484222325ull; @@ -124,7 +126,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptrpushOffset != cursor) continue; + if (variant->pushOffset != cursor || (heapRefused && variant->compiled->gpuResolvedImages)) continue; if (programs[i].binary.stage == ShaderRecompiler::ShaderStage::Mesh && !std::equal(variant->meshIndexDescriptor.begin(), variant->meshIndexDescriptor.end(), programs[i].userData.begin() + ShaderRecompiler::MeshIndexBufferUserWord)) { if (!anyLayout) outcome = EntryOutcome::Differing; anyLayout = true; @@ -232,6 +234,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptrdecode->programs[i].userData; auto& candidates = dataCandidates[i]; for (const auto& variant : dataEntry->stages[i]) { + if (heapRefused && variant->compiled->gpuResolvedImages) continue; bool usedEqual = true; for (std::size_t w = 0; w < now.size() && usedEqual; ++w) { if (now[w] != was[w] && (w >= 64u || ((variant->userDataMask >> w) & 1u) != 0)) usedEqual = false; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp index a1a5ebaab141..6865d419e2c4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp @@ -5,6 +5,7 @@ #include "prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/WorkerSampler.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libc/include/HostThreadLocal.hpp" #include #include @@ -116,6 +117,15 @@ bool DrawFinisher::PendingKey(std::uint64_t key, std::uint64_t shape) { return std::any_of(pending.begin(), pending.end(), [&](const Pending& held) { return held.key == key || (shape != 0 && held.shape == shape); }); } +void DrawFinisher::PendingWrites(std::vector& out) { + if (!Busy() || !finisherProducer) return; + std::lock_guard lock(mutex); + for (const auto& held : pending) { + if (held.unknown) out.emplace_back(0, std::numeric_limits::max()); + else out.insert(out.end(), held.writes.begin(), held.writes.end()); + } +} + namespace { std::array, static_cast(DrawFinisher::DrainSite::Count)> finisherDrains{}, finisherSkips{}; } @@ -508,6 +518,15 @@ std::optional DrawPipeline::PendingLabel(std::uint64_t address, s return std::nullopt; } +void DrawPipeline::QueuedWrites(std::vector& out) { + if (DrawFinisher::Overlap()) DrawFinisher::Get().PendingWrites(out); + std::lock_guard lock(mutex); + for (const auto& item : items) { + out.insert(out.end(), item.writes.begin(), item.writes.end()); + if (item.labelAddress != 0 && !item.labelBytes.empty()) out.emplace_back(item.labelAddress, item.labelAddress + item.labelBytes.size()); + } +} + void DrawPipeline::countWrites(const std::vector& writes, bool added) { for (const auto& range : writes) { const auto found = std::find_if(queuedWrites.begin(), queuedWrites.end(), [&](const auto& entry) { return entry.first == range; }); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp index c03e05baea00..ef4c9d3aeb6e 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp @@ -261,7 +261,7 @@ void Driver::applyShaderDataPatches(DispatchVariant& variant) { auto rebased = std::make_shared(*variant.compiled); for (const auto& [slot, value] : variant.shaderDataPatches) { const auto at = static_cast(slot) * sizeof(std::uint32_t); - if (at + sizeof(std::uint32_t) <= rebased->pushConstants.size()) std::memcpy(rebased->pushConstants.data() + at, &value, sizeof(value)); + if (!rebased->dataAddressPush && at + sizeof(std::uint32_t) <= rebased->pushConstants.size()) std::memcpy(rebased->pushConstants.data() + at, &value, sizeof(value)); for (auto& binding : rebased->bindings) { if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData && slot < binding.guestDescriptor.size()) binding.guestDescriptor[slot] = value; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp new file mode 100644 index 000000000000..2a4535836d42 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -0,0 +1,431 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" +#include "prx/libc/include/HostThreadLocal.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::DriverDetail { + +namespace { + +std::atomic& heapStages() { + static std::atomic count{0}; + return count; +} + +const char* resultDifference(const ShaderRecompiler::RecompileResult& left, const ShaderRecompiler::RecompileResult& right, std::size_t& index) { + index = 0; + if (left.PipelineVariantId() != right.PipelineVariantId()) return "variant"; + if (left.pushConstants != right.pushConstants) return "push constants"; + if (left.bindings.size() != right.bindings.size()) return "binding count"; + if (left.specialization.size() != right.specialization.size()) return "specialization count"; + for (index = 0; index < left.bindings.size(); ++index) { + const auto& a = left.bindings[index]; + const auto& b = right.bindings[index]; + if (a.role != b.role || a.kind != b.kind || a.binding != b.binding || a.count != b.count) return "binding layout"; + if (a.guestDescriptor != b.guestDescriptor) return "binding words"; + } + for (index = 0; index < left.specialization.size(); ++index) { + if (left.specialization[index].id != right.specialization[index].id || left.specialization[index].value != right.specialization[index].value) return "specialization"; + } + index = 0; + if (left.vertexAttributes.size() != right.vertexAttributes.size()) return "attribute count"; + for (index = 0; index < left.vertexAttributes.size(); ++index) { + const auto& a = left.vertexAttributes[index]; + const auto& b = right.vertexAttributes[index]; + if (a.location != b.location || a.components != b.components || a.resource.fields != b.resource.fields || a.fetchIndex != b.fetchIndex || a.formatComponents != b.formatComponents) return "attribute"; + } + return nullptr; +} + +bool sameResult(const ShaderRecompiler::RecompileResult& left, const ShaderRecompiler::RecompileResult& right) { + std::size_t index = 0; + return resultDifference(left, right, index) == nullptr; +} + +void reportHeapMismatch(const char* check, const char* what, const ShaderRecompiler::RecompileResult& result, std::size_t index) { + static std::atomic printed{0}; + if (printed.fetch_add(1, std::memory_order_relaxed) >= 64u) return; + const int role = index < result.bindings.size() ? static_cast(result.bindings[index].role) : -1; + const int kind = index < result.bindings.size() ? static_cast(result.bindings[index].kind) : -1; + std::fprintf(stderr, "[heap-verify] %s: %s differ at %zu (role %d kind %d, template %llu, variant 0x%llx)\n", check, what, index, role, kind, static_cast(result.heapTemplateId), static_cast(result.PipelineVariantId())); + std::fflush(stderr); +} + +struct VerifyCounts { + std::atomic verified{0}, differ{0}, notComparable{0}, accessor{0}, accessorDiffer{0}, ring{0}, ringDiffer{0}; +}; + +VerifyCounts& verifyCounts() { + static VerifyCounts counts; + static std::once_flag registered; + std::call_once(registered, [] { + std::atexit([] { + auto& c = verifyCounts(); + if (c.verified.load() != 0u || c.notComparable.load() != 0u) std::fprintf(stderr, "[heap-verify] %llu heap stages compared with a full capture, %llu differed, %llu not comparable (the full capture could not read every descriptor)\n", static_cast(c.verified.load()), static_cast(c.differ.load()), static_cast(c.notComparable.load())); + if (c.accessor.load() != 0u || c.ring.load() != 0u) std::fprintf(stderr, "[heap-verify] %llu accessor checks, %llu differed; %llu ring hits checked, %llu differed\n", static_cast(c.accessor.load()), static_cast(c.accessorDiffer.load()), static_cast(c.ring.load()), static_cast(c.ringDiffer.load())); + }); + }); + return counts; +} + +} + +bool HeapRefused() { + return Graphics::BindlessHeap::NearlyFull(); +} + +namespace { + +bool& heapDrawOff() { + struct DrawOffStorage {}; + return HostThreadLocal(); +} + +} + +HeapDrawOff::HeapDrawOff() : previous(heapDrawOff()) { + heapDrawOff() = true; +} + +HeapDrawOff::~HeapDrawOff() { + heapDrawOff() = previous; +} + +bool HeapFragmentsEnabled() { + return Graphics::DescriptorHeapEnabled() && !HeapRefused() && !heapDrawOff(); +} + +bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage) { + using Stage = ShaderRecompiler::ShaderStage; + return stage == Stage::Vertex || stage == Stage::Local || stage == Stage::TessellationControl || stage == Stage::TessellationEvaluation || stage == Stage::Mesh; +} + +bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex) { + if (plan == nullptr || (stage != ShaderRecompiler::ShaderStage::Fragment && !HeapPreRasterStage(stage))) return false; + return (stage == ShaderRecompiler::ShaderStage::Fragment || heapVertex) && ShaderRecompiler::HeapFragmentEligible(*plan) && std::none_of(plan->info.images.begin(), plan->info.images.end(), [](const ShaderRecompiler::ImageResource& image) { return image.table != ShaderRecompiler::NoTable && (image.atomic || image.atomic64); }); +} + +namespace { + +std::unordered_set& refusedPairs() { + struct PairsStorage {}; + return HostThreadLocal, PairsStorage>(); +} + +} + +bool HeapPairRefused(std::uint64_t pair) { + return refusedPairs().contains(pair); +} + +void RefuseHeapPair(std::uint64_t pair) { + auto& refused = refusedPairs(); + if (refused.size() >= 65536u) refused.clear(); + refused.insert(pair); +} + +bool HeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { + struct MappableStorage {}; + auto& known = HostThreadLocal, MappableStorage>(); + const auto key = result.variantId * 2u + (workgroupAddress ? 1u : 0u); + if (const auto found = known.find(key); found != known.end()) return found->second; + if (known.size() >= 65536u) known.clear(); + const bool mappable = Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), workgroupAddress, result.dataAddressPush); + known.emplace(key, mappable); + return mappable; +} + +namespace { + +struct HeapFragmentKey { + const void* snapshot; + std::size_t codeOffset; + bool operator==(const HeapFragmentKey&) const = default; +}; + +struct HeapFragmentKeyHash { + std::size_t operator()(const HeapFragmentKey& key) const { return std::hash{}(key.snapshot) ^ (key.codeOffset * 0x9e3779b97f4a7c15ull); } +}; + +std::unordered_map& heapFragments() { + struct FragmentsStorage {}; + auto& value = HostThreadLocal, FragmentsStorage>(); + return value; +} + +} + +std::optional HeapFragmentKnown(const void* snapshot, std::size_t codeOffset) { + const auto& known = heapFragments(); + const auto found = known.find({snapshot, codeOffset}); + return found == known.end() ? std::nullopt : std::optional(found->second); +} + +void NoteHeapFragment(const void* snapshot, std::size_t codeOffset, bool eligible) { + heapFragments()[{snapshot, codeOffset}] = eligible; +} + +bool SampleHeapStageVerify() { + static const std::uint64_t every = [] { + const char* text = std::getenv("APS5_VERIFY_GPU_HEAP"); + if (text == nullptr) return std::uint64_t{0}; + const auto value = std::strtoull(text, nullptr, 10); + return value == 0 ? std::uint64_t{1} : static_cast(value); + }(); + if (every == 0) return false; + thread_local std::uint64_t calls = 0; + return calls++ % every == 0; +} + +namespace { + +struct HeapWalkEntry { + std::uint64_t variant = 0; + std::uint64_t shaderBase = 0; + std::uint32_t pushOffset = 0; + std::vector userData; + std::vector> ranges; + std::vector values; + std::vector> accessible; + ShaderRecompiler::SrtUserDataUse userDataUse; + std::shared_ptr capture; + std::shared_ptr result; + std::shared_ptr words; +}; + +constexpr std::size_t HeapWalkWays = 4; + +std::unordered_map>& heapWalkMemo() { + struct WalkMemoStorage {}; + auto& memo = HostThreadLocal>, WalkMemoStorage>(); + return memo; +} + +} + +std::shared_ptr MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase, ShaderRecompiler::HeapStageWords* words, std::shared_ptr* sharedWords, HeapStageReads* stageReads) { + const auto finish = [&](const std::shared_ptr& capture) { + if (words != nullptr) { + if (auto shared = invocation.MaterializeHeap(*capture, *words)) return shared; + } + return invocation.Materialize(*capture); + }; + { + struct Reads { + std::vector words; + std::uint64_t page = ~std::uint64_t{0}; + std::vector> accessible; + bool failed = false; + }; + struct ReadsStorage {}; + struct RangesStorage {}; + auto& reads = HostThreadLocal(); + auto& ranges = HostThreadLocal>, RangesStorage>(); + reads.words.clear(); + reads.accessible.clear(); + reads.failed = false; + reads.page = ~std::uint64_t{0}; + const auto before = Graphics::Recorder::PendingWriteSnapshot(); + const auto generation = GuestMemory::TrackerGeneration(); + const bool memoOn = words != nullptr && !invocation.Request().context.vertex.has_value(); + std::uint64_t memoKey = 0; + if (memoOn) { + memoKey = (invocation.VariantId() * 0x9e3779b97f4a7c15ull ^ shaderBase) + invocation.Request().layout.pushConstantOffsetBytes; + for (const auto word : userData) memoKey = (memoKey ^ word) * 0x100000001b3ull; + auto& memo = heapWalkMemo(); + const auto found = memo.find(memoKey); + for (std::size_t way = 0; found != memo.end() && way < found->second.size(); ++way) { + const auto& entry = found->second[way]; + bool equal = entry.variant == invocation.VariantId() && entry.shaderBase == shaderBase && entry.pushOffset == invocation.Request().layout.pushConstantOffsetBytes && std::equal(entry.userData.begin(), entry.userData.end(), userData.begin(), userData.end()); + if (!equal) continue; + std::size_t cursor = 0; + for (std::size_t r = 0; equal && r < entry.ranges.size(); ++r) { + const auto [begin, end] = entry.ranges[r]; + const auto count = static_cast((end - begin) / 4u); + equal = GuestMemory::CompareMapped(begin, std::as_bytes(std::span(entry.values.data() + cursor, count))) == GuestMemory::Compare::Equal; + cursor += count; + } + for (std::size_t a = 0; equal && a < entry.accessible.size(); ++a) equal = GuestMemory::Accessible(reinterpret_cast(entry.accessible[a].first), static_cast(entry.accessible[a].second)); + if (!equal) { + continue; + } + bool settled = !(DrawPipeline::Active() && DrawPipeline::Queue0().Busy() && DrawPipeline::Queue0().OverlapsAny(entry.ranges)) && Graphics::Recorder::ReadsSettled(entry.ranges, before.get()); + for (std::size_t r = 0; settled && r < entry.ranges.size(); ++r) settled = GuestMemory::NewestStamp(entry.ranges[r].first, static_cast(entry.ranges[r].second - entry.ranges[r].first)) <= generation; + if (!settled) { + break; + } + for (const auto& [begin, end] : entry.ranges) GuestMemory::GuardRead(begin, static_cast(end - begin)); + if (sharedWords != nullptr) *sharedWords = entry.words; + else *words = *entry.words; + if (stageReads != nullptr) *stageReads = {entry.ranges, entry.values, entry.userDataUse, entry.capture, true}; + auto result = entry.result; + if (way != 0) std::rotate(found->second.begin(), found->second.begin() + static_cast(way), found->second.begin() + static_cast(way) + 1); + return result; + } + } + ShaderRecompiler::SrtRuntime plain; + plain.userData = userData; + plain.shaderBase = shaderBase; + plain.userContext = &reads; + plain.readMemory = [](void* context, std::uint64_t address, std::uint32_t* value) { + auto& self = *static_cast(context); + const auto page = address & ~std::uint64_t{0xfff}; + if (page != self.page || (address & 0xfffu) > 0x1000u - sizeof(*value)) { + if (GuestMemory::Accessible(reinterpret_cast(page), 0x1000u)) self.page = page; + else if (!GuestMemory::Accessible(reinterpret_cast(address), sizeof(*value))) { + self.failed = true; + return false; + } + } + std::memcpy(value, reinterpret_cast(address), sizeof(*value)); + self.words.push_back(address); + return true; + }; + plain.accessible = [](void* context, std::uint64_t address, std::uint64_t bytes) { + auto& self = *static_cast(context); + const bool accessible = GuestMemory::Accessible(reinterpret_cast(address), static_cast(bytes)); + if (accessible) self.accessible.emplace_back(address, bytes); + else self.failed = true; + return accessible; + }; + auto capture = invocation.Capture(plain); + std::sort(reads.words.begin(), reads.words.end()); + ranges.clear(); + for (const auto address : reads.words) { + if (!ranges.empty() && address <= ranges.back().second) { + ranges.back().second = std::max(ranges.back().second, address + 4u); + continue; + } + ranges.emplace_back(address, address + 4u); + } + struct ValuesStorage {}; + auto& values = HostThreadLocal, ValuesStorage>(); + if ((memoOn || stageReads != nullptr) && !reads.failed) { + values.clear(); + for (const auto& [begin, end] : ranges) { + const auto offset = values.size(); + values.resize(offset + static_cast((end - begin) / 4u)); + std::memcpy(values.data() + offset, reinterpret_cast(begin), static_cast(end - begin)); + } + } + bool settled = !(DrawPipeline::Active() && DrawPipeline::Queue0().Busy() && DrawPipeline::Queue0().OverlapsAny(ranges)) && Graphics::Recorder::ReadsSettled(ranges, before.get()); + for (std::size_t i = 0; settled && i < ranges.size(); ++i) settled = GuestMemory::NewestStamp(ranges[i].first, static_cast(ranges[i].second - ranges[i].first)) <= generation; + if (settled) { + for (const auto& [begin, end] : ranges) GuestMemory::GuardRead(begin, static_cast(end - begin)); + auto result = finish(capture); + if (stageReads != nullptr && !reads.failed && result != nullptr) *stageReads = {ranges, values, capture->userDataUse, capture, true}; + if (memoOn && !reads.failed && result != nullptr) { + auto& memo = heapWalkMemo(); + if (memo.size() >= 16384) memo.clear(); + auto& ways = memo[memoKey]; + if (ways.size() >= HeapWalkWays) ways.pop_back(); + ways.emplace(ways.begin()); + auto& entry = ways.front(); + entry.variant = invocation.VariantId(); + entry.pushOffset = invocation.Request().layout.pushConstantOffsetBytes; + entry.shaderBase = shaderBase; + entry.userData.assign(userData.begin(), userData.end()); + entry.ranges = ranges; + entry.values = values; + entry.accessible = reads.accessible; + entry.userDataUse = capture->userDataUse; + entry.capture = capture; + entry.result = result; + entry.words = std::make_shared(*words); + } + return result; + } + } + return nullptr; +} + +std::uint64_t HeapStagesTaken() { + return heapStages().load(); +} + +std::shared_ptr PatchedHeapResult(const ShaderRecompiler::RecompileResult& shared, const ShaderRecompiler::HeapStageWords& words) { + auto result = std::make_shared(shared); + for (auto& binding : result->bindings) { + if (binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt && !words.flattenedSrt.empty()) binding.guestDescriptor = words.flattenedSrt; + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) std::copy_n(words.userData.begin(), std::min(words.userData.size(), binding.guestDescriptor.size()), binding.guestDescriptor.begin()); + } + if (!words.bindings.empty()) { + if (words.bindings.size() != result->bindings.size()) throw std::runtime_error("a heap stage's per-draw bindings differ in number from its template"); + for (std::size_t index = 0; index < words.bindings.size(); ++index) { + if (words.bindings[index].empty()) continue; + if (result->bindings[index].role != ShaderRecompiler::DescriptorRole::FlattenedSrt && words.bindings[index].size() != result->bindings[index].guestDescriptor.size()) throw std::runtime_error("a heap stage's per-draw descriptor words differ in size from its template"); + result->bindings[index].guestDescriptor = words.bindings[index]; + } + } + if (!words.vertexAttributes.empty()) result->vertexAttributes = words.vertexAttributes; + return result; +} + +void NoteHeapDirect() { + heapStages().fetch_add(1, std::memory_order_relaxed); +} + +void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const ShaderRecompiler::RecompileResult& expected, const ShaderRecompiler::ResourceCapture* expectedCapture) { + auto& counts = verifyCounts(); + if (expectedCapture != nullptr) { + const auto partial = [](const std::vector& values) { + return std::ranges::any_of(values, [](const ShaderRecompiler::DescriptorValue& value) { return value.availableDwordMask != static_cast((1u << value.dwordCount) - 1u); }); + }; + const auto& snapshot = expectedCapture->snapshot; + if (partial(snapshot.buffers) || partial(snapshot.images) || partial(snapshot.samplers)) { + counts.notComparable.fetch_add(1, std::memory_order_relaxed); + return; + } + } + counts.verified.fetch_add(1, std::memory_order_relaxed); + std::size_t index = 0; + if (const auto* what = resultDifference(direct, expected, index)) { + counts.differ.fetch_add(1, std::memory_order_relaxed); + reportHeapMismatch("heap stage vs full capture", what, expected, index); + } +} + +void VerifyHeapAccessor(const Graphics::CompiledShader& stage) { + if (stage.heap == nullptr || stage.program == nullptr) return; + const auto patched = PatchedHeapResult(*stage.program, *stage.heap); + auto& counts = verifyCounts(); + counts.accessor.fetch_add(1, std::memory_order_relaxed); + for (std::size_t index = 0; index < stage.program->bindings.size(); ++index) { + if (Graphics::DrawGuestWords(stage, stage.program->bindings[index]) == patched->bindings[index].guestDescriptor) continue; + counts.accessorDiffer.fetch_add(1, std::memory_order_relaxed); + reportHeapMismatch("accessor vs patched result", "binding words", *patched, index); + } + const auto& attributes = Graphics::DrawVertexAttributes(stage); + bool sameAttributes = attributes.size() == patched->vertexAttributes.size(); + for (std::size_t index = 0; sameAttributes && index < attributes.size(); ++index) sameAttributes = attributes[index].resource.fields == patched->vertexAttributes[index].resource.fields && attributes[index].fetchIndex == patched->vertexAttributes[index].fetchIndex; + if (!sameAttributes) { + counts.accessorDiffer.fetch_add(1, std::memory_order_relaxed); + reportHeapMismatch("accessor vs patched result", "vertex attributes", *patched, 0); + } +} + +void VerifyRingWords(const ShaderRecompiler::RecompileResult& kept, const ShaderRecompiler::HeapStageWords& ring, const ShaderRecompiler::RecompileResult& fresh, const ShaderRecompiler::HeapStageWords* freshWords) { + const auto reused = PatchedHeapResult(kept, ring); + const auto expected = freshWords != nullptr ? PatchedHeapResult(fresh, *freshWords) : std::make_shared(fresh); + auto& counts = verifyCounts(); + counts.ring.fetch_add(1, std::memory_order_relaxed); + std::size_t index = 0; + if (const auto* what = resultDifference(*reused, *expected, index)) { + counts.ringDiffer.fetch_add(1, std::memory_order_relaxed); + reportHeapMismatch("ring hit vs fresh build", what, *expected, index); + } +} + +} diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp index 58fa8648a33b..9343f2abe410 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DrawWriteRanges.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" @@ -17,13 +18,14 @@ namespace AgcDriver::DriverDetail { namespace { template -void visitWrittenBuffers(const ShaderRecompiler::RecompileResult& compiled, TVisit&& visit) { +void visitWrittenBuffers(const ShaderRecompiler::RecompileResult& compiled, TVisit&& visit, const ShaderRecompiler::HeapStageWords* heap = nullptr) { for (const auto& binding : compiled.bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; for (std::uint32_t element = 0; element < binding.count; ++element) { + const auto& guestWords = Graphics::DrawGuestWords(compiled, heap, binding); const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; - if (!written || binding.guestDescriptor.size() < (static_cast(element) + 1) * 4) continue; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 4, 4); + if (!written || guestWords.size() < (static_cast(element) + 1) * 4) continue; + const auto words = std::span(guestWords).subspan(static_cast(element) * 4, 4); const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; const auto base = descriptor.Base48(); const auto size = descriptor.GetSize(); @@ -88,7 +90,7 @@ void Driver::noteForeignWriter(std::uint64_t begin, std::uint64_t end, std::uint void Driver::noteDrawWriters(std::span stages, std::uint32_t queue) { for (const auto& stage : stages) { - forEachWrittenBuffer(*stage.program, [&](std::uint32_t, std::uint64_t begin, std::uint64_t end, bool) { noteForeignWriter(begin, end, queue); }); + visitWrittenBuffers(*stage.program, [&](std::uint32_t, std::uint64_t begin, std::uint64_t end, bool) { noteForeignWriter(begin, end, queue); }, stage.heap); } } @@ -106,13 +108,14 @@ std::vector> DrawWriteRanges(const Graph }; for (const auto& stage : stages) { if (stage.program == nullptr) continue; - visitWrittenBuffers(*stage.program, [&](std::uint32_t, std::uint64_t begin, std::uint64_t end, bool) { ranges.emplace_back(begin, end); }); + visitWrittenBuffers(*stage.program, [&](std::uint32_t, std::uint64_t begin, std::uint64_t end, bool) { ranges.emplace_back(begin, end); }, stage.heap); for (const auto& binding : stage.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages || binding.kind != ShaderRecompiler::DescriptorKind::StorageImage) continue; for (std::uint32_t element = 0; element < binding.count; ++element) { const bool written = element >= binding.imageWritten.size() || binding.imageWritten[element]; - if (!written || binding.guestDescriptor.size() < (static_cast(element) + 1) * 8) continue; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8, 8); + const auto& guestWords = Graphics::DrawGuestWords(stage, binding); + if (!written || guestWords.size() < (static_cast(element) + 1) * 8) continue; + const auto words = std::span(guestWords).subspan(static_cast(element) * 8, 8); if (words[0] == 0u && (words[1] & 0xffu) == 0u) continue; const auto resource = Graphics::DecodeTextureResource(words); if (resource.baseAddress == 0) continue; @@ -171,16 +174,18 @@ std::vector> QueuedDrawReadRanges(const for (const auto& stage : stages) { if (stage.program == nullptr) continue; for (const auto& binding : stage.program->bindings) { - if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers || binding.guestDescriptor.size() < static_cast(binding.count) * 4u) continue; + if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; + const auto& guest = Graphics::DrawGuestWords(stage, binding); + if (guest.size() < static_cast(binding.count) * 4u) continue; for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto* words = binding.guestDescriptor.data() + static_cast(element) * 4u; + const auto* words = guest.data() + static_cast(element) * 4u; const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; add(descriptor.Base48(), descriptor.GetSize()); } } } if (stages.empty() || stages.front().program == nullptr) return ranges; - for (const auto& attribute : stages.front().program->vertexAttributes) { + for (const auto& attribute : Graphics::DrawVertexAttributes(stages.front())) { if (Graphics::NullVertexDescriptor(attribute)) continue; const auto address = attribute.resource.fields[0] | (static_cast(attribute.resource.fields[1] & 0xffffu) << 32u); std::uint64_t bytes = 0; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp index cccf175abf69..f3b8ecfc3464 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp @@ -6,6 +6,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" #include "prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "CacheKey.hpp" @@ -1060,6 +1061,12 @@ ShaderRecompiler::LinkedCalls LinkUserDataCallees(const ShaderRecompiler::Recomp } +bool PreparedHeapStage(const ShaderSnapshot& snapshot, std::size_t codeOffset) { + if (snapshot.prepared == nullptr) return false; + std::lock_guard lock(snapshot.prepared->mutex); + return std::ranges::any_of(snapshot.prepared->entries, [&](const auto& entry) { return entry.codeOffset == codeOffset && entry.handle != nullptr && entry.handle->artifact != nullptr && ShaderRecompiler::GetPreparedArtifact(*entry.handle).gpuResolvedImages; }); +} + ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request) { require(codeOffset < snapshot.code.size(), "prepared shader code offset is outside the snapshot"); const auto code = std::span(snapshot.code).subspan(codeOffset); @@ -1084,7 +1091,7 @@ ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& s if (entry.codeOffset != codeOffset) continue; invocationRequest.shader.code = ShaderRecompiler::GetPreparedCode(*entry.handle); if (!linked.code.empty() && !std::ranges::equal(invocationRequest.shader.code, linked.code)) continue; - if (auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(invocationRequest, entry.handle, key)) { + if (auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(std::move(invocationRequest), entry.handle, key)) { NoteMatchedEntry(entry, preparedAtUse); return std::move(*invocation); } @@ -1094,7 +1101,7 @@ ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& s auto handle = PrepareShaderWithDiagnostics(source); invocationRequest = source; invocationRequest.shader.code = ShaderRecompiler::GetPreparedCode(*handle); - auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(invocationRequest, handle, key); + auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(std::move(invocationRequest), handle, key); if (!invocation.has_value()) throw std::runtime_error("AGC driver: an artifact prepared at use does not match its invocation"); snapshot.prepared->entries.push_back({codeOffset, std::move(handle)}); return std::move(*invocation); @@ -1330,6 +1337,7 @@ bool LibraryPrebuildDisabled() { void PrebuildStageLibrary(const std::shared_ptr& device, const Graphics::ShaderStages& stages, ShaderRecompiler::ShaderStage stage, std::shared_ptr result, std::uint32_t pushOffset) { if (LibraryPrebuildDisabled() || result == nullptr || (stage != ShaderRecompiler::ShaderStage::Vertex && stage != ShaderRecompiler::ShaderStage::Fragment)) return; + if (result->gpuResolvedImages && !HeapStageMappable(*result)) return; SubmitLibraryPrebuild([device, stages, stage, result = std::move(result), pushOffset] { const std::array shaders{{{stage, result.get(), pushOffset}}}; try { @@ -1349,13 +1357,30 @@ std::vector PrepareRegistered(RegisteredPreparation& pla entries.push_back({plan.codeOffset, PrepareShaderWithDiagnostics(request, &preparation)}); }; append(); - if (plan.prebuildDevice != nullptr && request.target.registrationModules && request.shader.stage == ShaderRecompiler::ShaderStage::Fragment && !LibraryPrebuildDisabled()) { + const bool fragment = request.shader.stage == ShaderRecompiler::ShaderStage::Fragment; + const bool heapVertex = HeapPreRasterStage(request.shader.stage) && request.target.descriptorMemory; + const bool vertex = request.shader.stage == ShaderRecompiler::ShaderStage::Vertex; + const auto prebuild = [&](const ShaderRecompiler::RecompileRequest& stageRequest, const ShaderRecompiler::SourceHandle& handle) { + if (plan.prebuildDevice == nullptr || !stageRequest.target.registrationModules || !(fragment || (vertex && heapVertex && stageRequest.target.gpuResolvedImages)) || LibraryPrebuildDisabled()) return; try { - PrebuildStageLibrary(plan.prebuildDevice, {Graphics::ShaderPath::Vertex, 0u, 32u, request.context.waveSize, {}, {}}, request.shader.stage, ShaderRecompiler::RegistrationResult(request, *entries.front().handle), request.layout.pushConstantOffsetBytes); + PrebuildStageLibrary(plan.prebuildDevice, {Graphics::ShaderPath::Vertex, 0u, 32u, stageRequest.context.waveSize, {}, {}}, stageRequest.shader.stage, ShaderRecompiler::RegistrationResult(stageRequest, handle), stageRequest.layout.pushConstantOffsetBytes); } catch (const std::exception& error) { APS5_LOG_OUT("shader library prebuild skipped: %s", error.what()); } + }; + bool heapPrebuilt = false; + if ((fragment || heapVertex) && HeapFragmentsEnabled()) { + const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, entries.front().handle); + if (invocation && HeapStageEligible(request.shader.stage, invocation->Plan().get(), heapVertex)) { + auto heapRequest = request; + heapRequest.target.gpuResolvedImages = true; + PerformanceTimer timing("Shader.PrepareArtifact"); + entries.push_back({plan.codeOffset, PrepareShaderWithDiagnostics(heapRequest, &preparation)}); + prebuild(heapRequest, *entries.back().handle); + heapPrebuilt = request.target.descriptorMemory; + } } + if (!heapPrebuilt) prebuild(request, *entries.front().handle); if (request.context.compute) { request.context.compute->partialThreads = {1, 1, 1}; append(); @@ -1752,6 +1777,24 @@ unsigned RegistrationPreparationThreads() { std::vector PrepareGraphicsStages(const DrawDecode& decoded, const ShaderRecompiler::SpirvTarget& target, bool deferUnprepared) { ShaderPreparationTransaction transaction; + const auto preparedHandle = [&](const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request) { + std::vector key; + ShaderRecompiler::BuildPreparedShaderKey(request, key); + for (const auto& entry : transaction.Read(snapshot).entries) { + if (entry.codeOffset == codeOffset && ShaderRecompiler::MatchesPreparedShader(request, *entry.handle, key)) return entry.handle; + } + PerformanceTimer timing("Shader.PrepareArtifact"); + return PrepareShaderWithDiagnostics(request); + }; + const auto registrationFor = [&](const ShaderRecompiler::RecompileRequest& request, const ShaderRecompiler::SourceHandle& handle) -> std::shared_ptr { + if (!target.registrationModules || LibraryPrebuildDisabled()) return nullptr; + try { + return ShaderRecompiler::RegistrationResult(request, handle); + } catch (const std::exception& error) { + APS5_LOG_OUT("shader library prebuild skipped: %s", error.what()); + return nullptr; + } + }; require(decoded.programs.size() == decoded.roles.size(), "graphics ABI program roles are incomplete"); for (const auto& program : decoded.programs) require(program.snapshot != nullptr, "graphics ABI has no registered shader snapshot"); std::vector expected; @@ -1775,6 +1818,7 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod linked.push_back({decoded.roles[index], program.binary, program.userDataBase, program.firstUserSgpr, program.userData}); } std::vector prepared; + std::vector> requests; std::uint32_t pushOffset = 0; const bool fixedSlots = target.fixedPushSlots; const auto capacity = decoded.state.stages.mesh ? ShaderRecompiler::MeshDrawPushOffsetBytes : decoded.state.stages.tessellation ? ShaderRecompiler::TessellationLevelPushOffsetBytes : decoded.state.depthRemap.mode != 0u ? ShaderRecompiler::DepthRemapPushOffsetBytes : Graphics::PipelinePushSlotBytes; @@ -1788,6 +1832,7 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod const auto room = (fixedSlots && fragment ? Graphics::PipelinePushSlotBytes : capacity) - pushOffset % Graphics::PipelinePushSlotBytes; if (deferUnprepared && DeferFailedRegistration(*program.snapshot)) { prepared.push_back({program.snapshot, {program.codeOffset, nullptr}, program.binary.stage, offset, nullptr}); + requests.emplace_back(); continue; } std::optional vertex; @@ -1797,6 +1842,7 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod if (!deferUnprepared) throw; DeferPipelineStage(transaction.Edit(*program.snapshot), *program.snapshot, error.what()); prepared.push_back({program.snapshot, {program.codeOffset, nullptr}, program.binary.stage, offset, nullptr}); + requests.emplace_back(); continue; } if (vertex) { @@ -1804,39 +1850,44 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod Graphics::ApplyPointSize(decoded.state, *vertex); } ShaderRecompiler::RecompileRequest request{program.binary, {wave, program.firstUserSgpr, program.userData, {}, fragment ? std::optional(decoded.pixel) : std::nullopt, vertex, memory, RegisteredFloatMode(*program.snapshot)}, target, {0, 0, offset, room}, ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, linked, decoded.state.stages.mesh, decoded.state.stages.tessellation, {}}}; - std::vector key; - ShaderRecompiler::BuildPreparedShaderKey(request, key); std::shared_ptr handle; - for (const auto& entry : transaction.Read(*program.snapshot).entries) { - if (entry.codeOffset == program.codeOffset && ShaderRecompiler::MatchesPreparedShader(request, *entry.handle, key)) { - handle = entry.handle; - break; - } - } - if (handle == nullptr) { - PerformanceTimer timing("Shader.PrepareArtifact"); - try { - handle = PrepareShaderWithDiagnostics(request); - } catch (const std::exception& error) { - if (!deferUnprepared) throw; - DeferPipelineStage(transaction.Edit(*program.snapshot), *program.snapshot, error.what()); - prepared.push_back({program.snapshot, {program.codeOffset, nullptr}, program.binary.stage, offset, nullptr}); - continue; - } + try { + handle = preparedHandle(*program.snapshot, program.codeOffset, request); + } catch (const std::exception& error) { + if (!deferUnprepared) throw; + DeferPipelineStage(transaction.Edit(*program.snapshot), *program.snapshot, error.what()); + prepared.push_back({program.snapshot, {program.codeOffset, nullptr}, program.binary.stage, offset, nullptr}); + requests.emplace_back(); + continue; } const auto bytes = handle->artifact->bindings.pushConstantSizeBytes; require(bytes <= room, "prepared graphics stages exceed the push constant block"); - std::shared_ptr registration; - if (target.registrationModules && !LibraryPrebuildDisabled()) { - try { - registration = ShaderRecompiler::RegistrationResult(request, *handle); - } catch (const std::exception& error) { - APS5_LOG_OUT("shader library prebuild skipped: %s", error.what()); - } - } - prepared.push_back({program.snapshot, {program.codeOffset, handle}, program.binary.stage, offset, std::move(registration)}); + prepared.push_back({program.snapshot, {program.codeOffset, handle}, program.binary.stage, offset, registrationFor(request, *handle)}); + requests.push_back(std::move(request)); pushOffset += bytes; } + if (HeapFragmentsEnabled()) { + std::vector heap; + const auto addHeap = [&](std::size_t index, bool heapVertex) { + const auto& stage = prepared[index]; + if (stage.entry.handle == nullptr || !requests[index]) return false; + const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(*requests[index], stage.entry.handle); + if (!invocation || !HeapStageEligible(stage.stage, invocation->Plan().get(), heapVertex)) return false; + auto request = *requests[index]; + request.target.gpuResolvedImages = true; + const auto handle = preparedHandle(*stage.snapshot, stage.entry.codeOffset, request); + heap.push_back({stage.snapshot, {stage.entry.codeOffset, handle}, stage.stage, stage.pushOffset, registrationFor(request, *handle), true}); + return true; + }; + bool fragmentOnHeap = true; + for (std::size_t index = 0; index < prepared.size(); ++index) { + if (prepared[index].stage == ShaderRecompiler::ShaderStage::Fragment) fragmentOnHeap = addHeap(index, false); + } + for (std::size_t index = 0; index < prepared.size(); ++index) { + if (HeapPreRasterStage(prepared[index].stage)) static_cast(addHeap(index, target.descriptorMemory && fragmentOnHeap)); + } + prepared.insert(prepared.begin(), std::make_move_iterator(heap.begin()), std::make_move_iterator(heap.end())); + } transaction.Commit(); return prepared; } @@ -1934,7 +1985,7 @@ void Driver::ResolveGraphicsStagesAbi(std::span stages, std if (!duplicate) transaction.Edit(*stage.snapshot).entries.push_back(std::move(stage.entry)); } for (const auto& stage : prepared) { - if (stage.snapshot->type == 1) continue; + if (stage.snapshot->type == 1 || stage.heapVariant) continue; ResolvePreparedGraphics(*stage.snapshot, {}, primitiveType == state.userConfig.end() ? 0u : primitiveType->second, localDevice->Target(), true); } if (decoded.state.stages.path == Graphics::ShaderPath::Vertex) { @@ -1943,7 +1994,9 @@ void Driver::ResolveGraphicsStagesAbi(std::span stages, std } } PreparedShaderState::GraphicsAbi abi{key, registry, {}}; - for (const auto& stage : prepared) abi.stages.push_back(stage.snapshot); + for (const auto& stage : prepared) { + if (!stage.heapVariant) abi.stages.push_back(stage.snapshot); + } auto& graphicsAbis = transaction.Edit(*owner).graphicsAbis; std::erase_if(graphicsAbis, [](const auto& entry) { return entry.registry.expired(); }); graphicsAbis.push_back(std::move(abi)); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp index e42e4e2b0378..210daab380e4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/PresentationPass.hpp" #include "prx/libSceAgcDriver/Execution/include/AspectFit.hpp" #include "prx/libSceAgcDriver/Execution/include/DisplayFormat.hpp" @@ -273,7 +274,7 @@ void PresentationPass::draw(VkCommandBuffer commands, const Slot& slot, const Ta const VkRect2D scissor{{0, 0}, extent}; context.Function("vkCmdSetViewport")(commands, 0, 1, &viewport); context.Function("vkCmdSetScissor")(commands, 0, 1, &scissor); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &slot.set, 0, nullptr); + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &slot.set); context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), parameters); context.Function("vkCmdDraw")(commands, 3, 1, 0, 0); context.Function("vkCmdEndRenderPass")(commands); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 70fdef29e3b2..74129acbb352 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -10,6 +10,7 @@ #include "prx/libSceAgcDriver/Graphics/include/PipelineJournal.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Execution/include/FloatFlushProbe.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" @@ -175,6 +176,28 @@ const wchar_t* ComputePipelineDumpDirectory() { return _wgetenv(L"APS5_DUMP_COMP const char* ComputePipelineDumpDirectory() { return std::getenv("APS5_DUMP_COMPUTE_PIPELINES"); } #endif +void CreateComputeHeapPipeline(VkDevice device, PFN_vkCreateComputePipelines create, VkPipelineCache cache, VkShaderModule module, VkPipelineCreateFlags flags, VkPipelineShaderStageCreateFlags stageFlags, const VkSpecializationInfo* specialization, std::uint32_t subgroupSize, std::span mappings, VkPipeline* pipeline, Graphics::PipelineCacheSynchronization* synchronization) { + VkPipelineCreateFlags2CreateInfoKHR flags2{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR}; + flags2.flags = static_cast(flags) | VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT; + VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, &flags2}; + info.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + info.stage.flags = stageFlags; + info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + info.stage.module = module; + info.stage.pName = "main"; + info.stage.pSpecializationInfo = specialization; + VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; + mappingInfo.mappingCount = static_cast(mappings.size()); + mappingInfo.pMappings = mappings.data(); + VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT subgroup{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO_EXT}; + subgroup.requiredSubgroupSize = subgroupSize; + info.stage.pNext = &mappingInfo; + if (subgroupSize != 0) mappingInfo.pNext = &subgroup; + info.layout = VK_NULL_HANDLE; + auto cacheLock = synchronization != nullptr ? synchronization->LockForPipelineUse() : Graphics::PipelineCacheSynchronization::PipelineUseLock{}; + check(create(device, cache, 1, &info, nullptr, pipeline), "vkCreateComputePipelines (descriptor heap)"); +} + bool CaptureComputePipeline(std::size_t words) { const char* minimum = std::getenv("APS5_DUMP_COMPUTE_MIN_WORDS"); if (minimum == nullptr) return true; @@ -286,6 +309,7 @@ struct ComputePipelineObjects { VkDescriptorSetLayout resourcesLayout = VK_NULL_HANDLE; std::mutex splitMutex; std::map, VkPipeline> splitPipelines; + bool descriptorHeap = false; ~ComputePipelineObjects() { for (const auto& [base, split] : splitPipelines) destroyPipeline(device, split, nullptr); if (pipeline != VK_NULL_HANDLE) destroyPipeline(device, pipeline, nullptr); @@ -312,6 +336,7 @@ struct WorkgroupMemory { std::unique_ptr buffer; VkDescriptorPool pool = VK_NULL_HANDLE; VkDescriptorSet set = VK_NULL_HANDLE; + VkDeviceAddress address = 0; ~WorkgroupMemory() { buffer.reset(); if (pool != VK_NULL_HANDLE) destroyPool(device, pool, nullptr); @@ -471,6 +496,8 @@ struct VulkanDevice::State { Graphics::Context context; bool contextReady = false; std::unique_ptr detiler; + bool descriptorHeap = false; + VkPhysicalDeviceDescriptorHeapPropertiesEXT descriptorHeapProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_PROPERTIES_EXT}; std::unique_ptr recorder; // Device-local buffers of a repeated 16-byte fill pattern (FillBuffer), most recently used // last; each is filled once by a doubling chain in device memory. @@ -487,6 +514,7 @@ struct VulkanDevice::State { std::shared_ptr journalReplay; std::atomic journalReplayPending{false}; std::atomic computePipelinesCreated{0}; + std::atomic descriptorHeapComputePipelines{0}; std::unique_ptr colorTransfer; std::shared_ptr bufferPool; std::unique_ptr emptyBuffer; @@ -612,7 +640,7 @@ struct VulkanDevice::State { auto memory = std::make_shared(); memory->device = device; memory->destroyPool = DeviceFunction("vkDestroyDescriptorPool"); - memory->buffer = std::make_unique(context, static_cast(size), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + memory->buffer = std::make_unique(context, static_cast(size), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (context.descriptorHeap ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u)); const VkDescriptorPoolSize poolSize{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; poolInfo.maxSets = 1; @@ -632,6 +660,10 @@ struct VulkanDevice::State { write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &described; DeviceFunction("vkUpdateDescriptorSets")(device, 1, &write, 0, nullptr); + if (context.descriptorHeap) { + const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, memory->buffer->Handle()}; + memory->address = DeviceFunction("vkGetBufferDeviceAddressKHR")(device, &addressInfo); + } workgroupMemory = std::move(memory); return workgroupMemory; } @@ -888,6 +920,7 @@ struct VulkanDevice::State { resourceCache.Clear(); Graphics::ClearCachedTextures(device); Graphics::ClearSnapshotCopies(device); + Graphics::BindlessHeap::Release(device); Graphics::ClearImageMirrors(device); Graphics::ClearHostImports(device); patternBuffers.clear(); @@ -1831,6 +1864,24 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : state->InstanceFunction("vkGetPhysicalDeviceProperties2")(selected, &properties); } } + VkPhysicalDeviceDescriptorHeapFeaturesEXT descriptorHeapFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_FEATURES_EXT}; + if (Graphics::GpuHeapEnabled() && hasExtension(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME) && hasExtension(VK_KHR_MAINTENANCE_5_EXTENSION_NAME) && hasExtension(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) && hasExtension(VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME) && hasExtension(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME)) { + VkPhysicalDeviceMaintenance5FeaturesKHR heapMaintenance5{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR, &descriptorHeapFeatures}; + VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &heapMaintenance5}; + state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &features); + if (descriptorHeapFeatures.descriptorHeap == VK_TRUE && heapMaintenance5.maintenance5 == VK_TRUE) { + state->descriptorHeap = true; + state->maintenance5 = true; + VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &state->descriptorHeapProperties}; + state->InstanceFunction("vkGetPhysicalDeviceProperties2")(selected, &properties); + deviceExtensions.push_back(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME); + for (const char* required : {VK_KHR_MAINTENANCE_5_EXTENSION_NAME, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME}) { + if (std::find_if(deviceExtensions.begin(), deviceExtensions.end(), [&](const char* name) { return std::strcmp(name, required) == 0; }) == deviceExtensions.end()) deviceExtensions.push_back(required); + } + } + descriptorHeapFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_FEATURES_EXT}; + descriptorHeapFeatures.descriptorHeap = state->descriptorHeap ? VK_TRUE : VK_FALSE; + } descriptorIndexingFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT}; if (state->descriptorIndexing || state->storageBufferUpdateAfterBind || state->sampledImageUpdateAfterBind || state->descriptorBindingPartiallyBound || state->descriptorBindingVariableDescriptorCount || state->runtimeDescriptorArray) deviceExtensions.push_back(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME); if (state->descriptorIndexing) { @@ -1861,6 +1912,10 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : meshFeatures.pNext = const_cast(deviceInfo.pNext); deviceInfo.pNext = &meshFeatures; } + if (state->descriptorHeap) { + descriptorHeapFeatures.pNext = const_cast(deviceInfo.pNext); + deviceInfo.pNext = &descriptorHeapFeatures; + } if (state->depthClipControl) { depthClipFeatures.pNext = const_cast(deviceInfo.pNext); deviceInfo.pNext = &depthClipFeatures; @@ -2140,8 +2195,11 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : state->functionsReady = true; } Graphics::PrepareImportWatch(graphicsContext()); + Graphics::SetDescriptorHeapDevice(state->descriptorHeap && state->descriptorHeapProperties.maxPushDataSize >= Graphics::PipelinePushConstantBytes); + Graphics::BufferPool::SetForceAddresses(Graphics::DescriptorHeapEnabled()); state->bufferPool = std::make_shared(graphicsContext()); state->emptyBuffer = std::make_unique(graphicsContext(), Graphics::EmptyBufferBytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + if (state->descriptorHeap && Graphics::DescriptorHeapEnabled()) APS5_LOG_OUT("Vulkan descriptor heap: %s", "GPU-mode draws and dispatches bind from VK_EXT_descriptor_heap"); state->pipelineCache = std::make_unique(graphicsContext(), state->properties, window != nullptr || compileOnly); state->detiler = std::make_unique(graphicsContext()); state->textureCache = std::make_unique(graphicsContext()); @@ -2281,6 +2339,10 @@ std::uint64_t VulkanDevice::ComputePipelinesCreated() const { return state->computePipelinesCreated.load(std::memory_order_relaxed); } +std::uint64_t VulkanDevice::DescriptorHeapComputePipelines() const { + return state->descriptorHeapComputePipelines.load(std::memory_order_relaxed); +} + bool VulkanDevice::ReplayComputePipeline(const ShaderRecompiler::RecompileResult& shader, bool pushConstants) { ShaderRecompiler::RuntimeAbi::RequireVersion(shader.runtimeAbiVersion); const auto key = ComputePipelineKey::Of(shader, pushConstants); @@ -3521,10 +3583,12 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu check(state->DeviceFunction("vkResetCommandBuffer")(commands, 0), "vkResetCommandBuffer"); VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + Graphics::NoteCommandBufferBegun(commands); check(state->DeviceFunction("vkBeginCommandBuffer")(commands, &begin), "vkBeginCommandBuffer"); APS5_LOG_OUT_DEBUG("Presentation command buffer begin commands=%p image=%p", reinterpret_cast(commands), reinterpret_cast(state->images[index])); using CommandClass = Graphics::Recorder::CommandClass; Graphics::Recorder::CountPresent(); + if (Graphics::GpuHeapEnabled()) Graphics::BindlessHeap::SweepIfDue(); if (Graphics::Recorder::GpuTimingEnabled()) { if (slot.queries == VK_NULL_HANDLE) { VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; @@ -3790,6 +3854,7 @@ void VulkanDevice::QueuePresent() { ShaderRecompiler::SpirvTarget VulkanDevice::ComputeTarget(std::uint32_t waveSize) const { auto target = Target(); if (waveSize == 32u && state->computeWave32) target.subgroupSize = 32u; + target.gpuResolvedImages = Graphics::HeapComputeEnabled(); return target; } @@ -3845,6 +3910,7 @@ ShaderRecompiler::SpirvTarget VulkanDevice::Target() const { target.float32FlushToZero = state->float32FlushToZero; target.fusedExactArithmetic = state->fusedExactArithmetic; target.float32DenormPreserve = state->float32DenormPreserve; + target.descriptorMemory = Graphics::DescriptorHeapEnabled(); return target; } @@ -3968,6 +4034,8 @@ Graphics::Context VulkanDevice::buildContext() const { context.settleFamily = state->settleFamily; context.settleQueueMutex = &state->settleQueueMutex; context.recorder = state->recorder.get(); + context.descriptorHeap = state->descriptorHeap; + context.descriptorHeapProperties = state->descriptorHeapProperties; context.descriptorCache = state->descriptorCache.get(); context.vertexInputs = state->vertexInputs.get(); context.samplerCache = state->samplerCache.get(); @@ -4043,7 +4111,9 @@ VulkanDevice::IndirectDrawSupport VulkanDevice::DrawIndirectSupport() const { } std::optional VulkanDevice::KnownDrawRejection(const Graphics::State& graphics, std::span shaders) const { - return Graphics::KnownValidationFailure(graphicsContext(), shaders, graphics); + static const bool noCache = std::getenv("APS5_NO_CONTEXT_CACHE") != nullptr; + if (state->contextReady && !noCache) return Graphics::KnownValidationFailure(state->context, shaders, graphics); + return Graphics::KnownValidationFailure(buildContext(), shaders, graphics); } void VulkanDevice::ColorMetadataPass(const Graphics::ColorMetadataPass& pass) { @@ -4804,7 +4874,7 @@ std::shared_ptr VulkanDevice::PrepareDispatch(const ShaderReco if (built.Layout() != VK_NULL_HANDLE) { const auto layouts = built.SetLayouts(); prepared->objects = computePipeline(context, shader, layouts.main, layouts.mainKey, pushStages, programAddress); - } else if (context.descriptorCache != nullptr) { + } else if (context.descriptorCache != nullptr && !shader.gpuResolvedImages) { const auto described = Graphics::DescribeSetLayouts(context, shaders); prepared->describedLayoutKey = described.mainKey; prepared->objects = computePipeline(context, shader, described.layouts.main, described.mainKey, pushStages, programAddress); @@ -4987,6 +5057,10 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { for (const auto& snapshot : record.bindings->snapshots) recorder.KeepBytes(snapshot.buffer.get(), snapshot.buffer->Bytes().size()); } recordStep(PhaseRecordKeeps); + if (resources.HeapStage()) { + resources.RefreshHeapStage(std::span(record.shader, 1)); + if (record.bindings != nullptr) resources.RefreshMovedAddresses(*record.bindings); + } if (record.dataRefresh != RecordedDispatch::DataRefresh::None) { // The template's data buffers take this dispatch's words: a transfer write the pre-dispatch // barrier makes visible (so it is recorded whatever the previous command covered), ordered @@ -5067,16 +5141,40 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { } } context.Resolved(&Graphics::DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->pipeline); - if (record.bindings != nullptr) Graphics::Require(record.bindings->allocation.set != VK_NULL_HANDLE, "dispatch overlay has no descriptor set"); - if (record.bindings != nullptr) context.Resolved(&Graphics::DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, 0, 1, &record.bindings->allocation.set, 0, nullptr); - else resources.Bind(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout); + if (record.objects->descriptorHeap) { + Graphics::BindlessHeap::For(context).BindDescriptorHeaps(commands); + } else if (record.bindings != nullptr) { + Graphics::Require(record.bindings->allocation.set != VK_NULL_HANDLE && !resources.HeapStage(), "dispatch overlay has no descriptor set"); + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, 0, 1, &record.bindings->allocation.set); + } else { + Graphics::Require(!resources.HeapStage(), "a GPU-mode dispatch needs a VK_EXT_descriptor_heap pipeline"); + resources.Bind(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout); + } + VkDeviceAddress workgroupAddress = 0; if (const auto dwords = record.shader->program->workgroupMemoryDwords; dwords != 0) { auto memory = state->WorkgroupMemoryFor(context, record.x, record.y, record.z, dwords); - context.Resolved(&Graphics::DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, ShaderRecompiler::WorkgroupMemoryDescriptorSet, 1, &memory->set, 0, nullptr); + const auto workgroupSet = record.shader->program->gpuResolvedImages ? ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet : ShaderRecompiler::WorkgroupMemoryDescriptorSet; + if (record.objects->descriptorHeap) { + workgroupAddress = memory->address; + if (record.pushStages == 0) { + const VkPushDataInfoEXT push{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, Graphics::ComputePushConstantBytes, {&memory->address, sizeof(memory->address)}}; + context.Function("vkCmdPushDataEXT")(commands, &push); + } + } else { + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, workgroupSet, 1, &memory->set); + } recorder.Keep(std::move(memory)); } if (record.pushStages != 0) { - context.Resolved(&Graphics::DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, record.objects->layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, Graphics::ComputePushConstantBytes, record.pushBytes->data()); + auto pushed = *record.pushBytes; + resources.PatchDataAddresses(pushed, std::span(record.shader, 1), record.bindings.get()); + if (record.objects->descriptorHeap) { + std::memcpy(pushed.data() + Graphics::ComputePushConstantBytes, &workgroupAddress, sizeof(workgroupAddress)); + const VkPushDataInfoEXT push{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {pushed.data(), pushed.size()}}; + context.Function("vkCmdPushDataEXT")(commands, &push); + } else { + context.Resolved(&Graphics::DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, record.objects->layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, Graphics::ComputePushConstantBytes, pushed.data()); + } } const auto gpuTiming = recorder.BeginGpuTiming(record.programAddress != 0 ? record.programAddress : record.shader->program->variantId); if (state->checkpointMarker != nullptr) state->checkpointMarker(commands, reinterpret_cast(static_cast(record.programAddress))); @@ -5154,9 +5252,6 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { recordStep(PhaseRecordCompletion); } -// The module, pipeline layout and pipeline of a compute result over `setLayout` (the set layout -// its bindings describe): what a dispatch or its preparation builds at the first use of a module, -// and what the journal replay builds on its own threads before that use. std::shared_ptr VulkanDevice::createComputePipeline(const Graphics::Context& context, const ShaderRecompiler::RecompileResult& shader, VkDescriptorSetLayout setLayout, std::span layoutKey, VkShaderStageFlags pushStages, std::uint64_t programAddress) { PerformanceTimer timing("Vulkan.ComputePipeline"); static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; @@ -5168,14 +5263,17 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons objects->destroyPipeline = state->DeviceFunction("vkDestroyPipeline"); objects->module = Graphics::CreateShaderModule(state->DeviceFunction("vkCreateShaderModule"), state->device, state->graphicsPipelineLibrary, shader.spirv.data(), shader.spirv.size() * sizeof(std::uint32_t), "vkCreateShaderModule"); objects->resourcesLayout = setLayout; - const std::array setLayouts{setLayout, shader.workgroupMemoryDwords != 0 ? state->workgroupMemoryLayout : VK_NULL_HANDLE}; + const bool gpuMode = shader.gpuResolvedImages; const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, Graphics::ComputePushConstantBytes}; - VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layoutInfo.setLayoutCount = shader.workgroupMemoryDwords != 0 ? ShaderRecompiler::WorkgroupMemoryDescriptorSet + 1 : 1; - layoutInfo.pSetLayouts = setLayouts.data(); - layoutInfo.pushConstantRangeCount = pushStages != 0 ? 1 : 0; - layoutInfo.pPushConstantRanges = pushStages != 0 ? &push : nullptr; - check(state->DeviceFunction("vkCreatePipelineLayout")(state->device, &layoutInfo, nullptr, &objects->layout), "vkCreatePipelineLayout"); + if (!gpuMode) { + const std::array setLayouts{setLayout, state->workgroupMemoryLayout}; + VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layoutInfo.setLayoutCount = shader.workgroupMemoryDwords != 0 ? ShaderRecompiler::WorkgroupMemoryDescriptorSet + 1 : 1u; + layoutInfo.pSetLayouts = setLayouts.data(); + layoutInfo.pushConstantRangeCount = pushStages != 0 ? 1 : 0; + layoutInfo.pPushConstantRanges = pushStages != 0 ? &push : nullptr; + check(state->DeviceFunction("vkCreatePipelineLayout")(state->device, &layoutInfo, nullptr, &objects->layout), "vkCreatePipelineLayout"); + } const VkPipelineCreateFlags pipelineFlags = computePipelineFlags(); const Graphics::PipelineSpecialization specialization(shader); const auto subgroupSize = computeSubgroupSize(shader); @@ -5207,12 +5305,18 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons if (!path.empty()) std::fprintf(stderr, "[compute-capture] %s\n", path.string().c_str()); } if (profile && shader.spirv.size() > 100000) std::fprintf(stderr, "[dispatch] creating a pipeline for %zu SPIR-V words (program 0x%llx)\n", shader.spirv.size(), static_cast(programAddress)); - CreateComputePipeline(state->device, state->DeviceFunction("vkCreateComputePipelines"), context.pipelineCache, objects->module, objects->layout, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, &objects->pipeline, context.pipelineCacheSynchronization); + std::vector heapMappings; + const bool workgroupAddress = shader.workgroupMemoryDwords != 0; + objects->descriptorHeap = gpuMode && context.descriptorHeap && Graphics::DescriptorHeapEnabled() && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(std::span(shader.spirv.data(), shader.spirv.size()), heapMappings, workgroupAddress ? Graphics::ComputePushConstantBytes : ~0u, shader.dataAddressPush); + require(!gpuMode || objects->descriptorHeap, "a GPU-mode compute stage does not map onto VK_EXT_descriptor_heap"); + if (objects->descriptorHeap) CreateComputeHeapPipeline(state->device, state->DeviceFunction("vkCreateComputePipelines"), context.pipelineCache, objects->module, computePipelineFlags(), stageFlags, specialization.Info(), subgroupSize, heapMappings, &objects->pipeline, context.pipelineCacheSynchronization); + else CreateComputePipeline(state->device, state->DeviceFunction("vkCreateComputePipelines"), context.pipelineCache, objects->module, objects->layout, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, &objects->pipeline, context.pipelineCacheSynchronization); objects->destroyModule(objects->device, objects->module, nullptr); objects->module = VK_NULL_HANDLE; if (!state->probingFloatControls) { computePipelinesCreated.fetch_add(1, std::memory_order_relaxed); state->computePipelinesCreated.fetch_add(1, std::memory_order_relaxed); + if (objects->descriptorHeap) state->descriptorHeapComputePipelines.fetch_add(1, std::memory_order_relaxed); if (GuestMemory::GpuMutex().HeldByThisThread()) computePipelinesCreatedLocked.fetch_add(1, std::memory_order_relaxed); } Graphics::LogPipelineStatistics_nid_no_patch(context, objects->pipeline); @@ -5432,7 +5536,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec } if (moved.has_value() && !moved->empty()) { overlay = cached->PrepareDrawBindings(*state->recorder, *moved, true); - if (overlay != nullptr && overlay->allocation.set == VK_NULL_HANDLE) overlay.reset(); + if (overlay != nullptr && overlay->allocation.set == VK_NULL_HANDLE && !cached->HeapStage()) overlay.reset(); if (overlay == nullptr) { proof.refusal = Graphics::ShaderResources::MoveRefusal::Bindings; moved.reset(); @@ -5518,7 +5622,8 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec if (objects == nullptr) { if (verifySetLayouts && context.descriptorCache != nullptr) { const auto described = Graphics::DescribeSetLayouts(context, shaders); - require(described.layouts.main == resources->Layout() && !described.layouts.split, "the set layout described from the compute shader differs from the dispatch's"); + const auto live = resources->SetLayouts(); + require(described.layouts.main == resources->Layout() && described.layouts.split == live.split && described.layouts.fragment == live.fragment, "the set layout described from the compute shader differs from the dispatch's"); } const auto layouts = resources->SetLayouts(); objects = computePipeline(context, shader, layouts.main, layouts.mainKey, pushStages, programAddress); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp new file mode 100644 index 000000000000..98bf412f3c33 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -0,0 +1,151 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_BINDLESSHEAP_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_BINDLESSHEAP_HPP + +#include "prx/libSceAgcDriver/Graphics/include/Context.hpp" +#include "RuntimeAbi.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +class Buffer; +class Recorder; +class Sampler; +class Texture; + +class BindlessHeap { +public: + explicit BindlessHeap(const Context& context); + ~BindlessHeap(); + BindlessHeap(const BindlessHeap&) = delete; + BindlessHeap& operator=(const BindlessHeap&) = delete; + + static BindlessHeap& For(const Context& context); + static BindlessHeap* Existing(const Context& context); + static void Release(VkDevice device); + + bool DescriptorHeapMode() const { return resourceHeap != nullptr; } + VkDeviceSize ImageHeapOffset(std::uint32_t kind) const; + VkDeviceSize ImageHeapStride() const { return imageHeapStride; } + VkDeviceSize SamplerHeapStride() const { return samplerHeapStride; } + void BindDescriptorHeaps(VkCommandBuffer commands) const; + bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset = ~0u, bool rootGds = false, bool rootFault = false) const; + VkDeviceAddress RingAddress() const; + + std::optional TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, VkImageLayout layout); + std::optional StorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view); + std::uint32_t SlotGeneration(std::uint32_t kind, std::uint32_t slot) const; + const Texture* SlotTexture(std::uint32_t kind, std::uint32_t slot) const; + std::optional SamplerSlot(const std::shared_ptr& sampler); + std::uint32_t SamplerGeneration(std::uint32_t slot) const; + std::uint64_t SlotSerial() const { return slotSerial.load(std::memory_order_acquire); } + bool GenerationsCurrent(std::span> slots, std::span slotGenerations, std::span samplerSlots, std::span samplerGenerations) const; + std::uint32_t AbsentSlot(std::uint32_t kind, VkImageView view); + static bool NearlyFull(); + static void NoteSweepDue(); + static void SweepIfDue(); + + struct DataSpan { + std::uint32_t offset = 0; + std::span words; + }; + DataSpan Allocate(std::size_t words); + + static constexpr std::uint32_t SamplerKind = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Samplers); + void Submitted(Recorder& recorder, std::uint64_t serial); + + struct Counts { + std::uint64_t textures = 0, samplers = 0, full = 0, ringWraps = 0; + std::uint64_t slotsFreed = 0, slotsReused = 0, sweeps = 0, chunkWaits = 0; + }; + Counts Statistics() const; + + static constexpr std::size_t RingBytes = 64u << 20u; + +private: + Context context; + std::unique_ptr ring; + std::unique_ptr resourceHeap; + std::unique_ptr samplerHeap; + VkDeviceSize imageHeapStride = 0; + VkDeviceSize samplerHeapStride = 0; + VkDeviceSize resourceHeapUsed = 0; + VkDeviceSize samplerHeapUsed = 0; + void writeDescriptorHeap(const VkWriteDescriptorSet& write); + static constexpr std::size_t RingChunkBytes = 4u << 20u; + struct Chunk { + Recorder* recorder = nullptr; + std::uint64_t serial = 0; + bool open = false; + }; + std::vector ringChunks; + std::size_t ringChunk = ~std::size_t{0}; + void enterChunk(std::vector& chunks, std::size_t index, std::size_t& current, const char* what); + std::size_t ringCursor = 0; + std::uint32_t ringAlignment = 256; + mutable std::mutex mutex; + std::atomic slotSerial{1}; + struct TextureKey { + std::uint32_t kind; + const void* texture; + VkImageView view; + VkImageLayout layout; + bool operator==(const TextureKey&) const = default; + }; + struct TextureKeyHash { + std::size_t operator()(const TextureKey& key) const { return std::hash{}(key.texture) ^ std::hash{}(reinterpret_cast(key.view)) ^ (static_cast(key.kind) << 48u) ^ (static_cast(key.layout) << 40u); } + }; + std::unordered_map textureSlots; + std::vector nextTextureSlot; + struct SlotOwner { + std::shared_ptr texture; + std::shared_ptr storage; + TextureKey key{}; + std::uint32_t generation = 0; + }; + std::vector> owners; + std::vector> freeSlots; + std::uint32_t slotCap = 0; + std::uint64_t slotRequests = 0; + void sweepLocked(std::vector>& dropped); + std::optional takeSlotLocked(std::uint32_t kind); + std::unordered_map samplerSlots; + std::unordered_map absentSlots; + std::vector> heldSamplers; + std::vector samplerGenerations; + std::vector freeSamplerSlots; + void sweepSamplersLocked(std::vector>& dropped); + void noteTakenLocked(std::uint32_t kind, std::vector>& dropped); + void noteSamplerTakenLocked(std::vector>& dropped); + std::uint32_t imageMargin() const; + std::size_t unusedLocked(std::uint32_t kind) const; + bool roomLocked() const; + Counts counts; +}; + +bool GpuHeapEnabled(); +void SetDescriptorHeapDevice(bool available); +bool DescriptorHeapEnabled(); +bool HeapComputeEnabled(); +bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress); +void NoteHeapComputeStage(); +std::uint64_t HeapComputeStages(); +void NoteImageTableBuild(); +std::uint64_t ImageTableBuilds(); +void NoteDataAddressPush(); +void NoteEmptyResourceSet(); +std::uint64_t EmptyResourceSets(); +std::uint64_t DataAddressPushes(); +void NoteCommandBufferBegun(VkCommandBuffer commands); +void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets); +std::uint64_t DescriptorHeapBinds(); + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp index 01a9c0419165..ceda9722a88b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp @@ -66,6 +66,8 @@ class BufferPool { // The size a buffer for `bytes` is created with: its size class, or `bytes` itself when large. static std::size_t Capacity(std::size_t bytes, VkMemoryPropertyFlags properties); static VkBufferUsageFlags Usage(VkBufferUsageFlags usage, VkMemoryPropertyFlags properties); + static bool ForceAddresses(); + static void SetForceAddresses(bool force); VkDeviceMemory AllocateMemory(const VkMemoryAllocateInfo& allocation, const char* operation, std::optional hostType = std::nullopt, std::uint32_t* allocatedType = nullptr, bool newImage = false); static VkDeviceSize ImageBudget(VkDeviceSize deviceBudget); VkDeviceMemory TakeImageMemory(const VkMemoryAllocateInfo& allocation, const char* operation, std::optional hostType = std::nullopt, std::uint32_t* allocatedType = nullptr, bool newImage = false); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index 7e0e07d07b55..153fac4efb96 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -7,6 +7,7 @@ #include #include #include +#include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" #include #include #include @@ -200,6 +201,8 @@ struct Context { GraphicsPipelineCache* graphicsPipelines = nullptr; // Batches GPU work across guest commands (see Recorder); null before the device finished setup. Recorder* recorder = nullptr; + bool descriptorHeap = false; + VkPhysicalDeviceDescriptorHeapPropertiesEXT descriptorHeapProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_PROPERTIES_EXT}; // Per-device caches of the immutable descriptor objects a ShaderResources build needs (set // layouts, descriptor pools, samplers); null (tests) means every build makes and destroys its own. DescriptorCache* descriptorCache = nullptr; @@ -284,6 +287,9 @@ struct Context { TFunction Function(const char* name) const { Require(deviceProc != nullptr, "missing Vulkan device function resolver"); ++DeviceProcLookups(); + if (descriptorHeap) { + if (const auto hooked = DescriptorHeapObjectFunction(device, deviceProc, name); hooked != nullptr) return reinterpret_cast(hooked); + } const auto function = reinterpret_cast(deviceProc(device, name)); if (function == nullptr) throw std::runtime_error(std::string("AGC graphics: missing Vulkan function: ") + name); return function; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp new file mode 100644 index 000000000000..bbe25790d619 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp @@ -0,0 +1,32 @@ +#ifndef AGC_GRAPHICS_DESCRIPTOR_HEAP_OBJECTS_HPP +#define AGC_GRAPHICS_DESCRIPTOR_HEAP_OBJECTS_HPP + +#include + +#include + +namespace AgcDriver::Graphics { + +struct ImageViewRecord { + VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + VkImageViewUsageCreateInfo usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; + VkImageViewMinLodCreateInfoEXT minLod{VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT}; + bool hasUsage = false; + bool hasMinLod = false; + const VkImageViewCreateInfo* Chain(); +}; + +struct SamplerRecord { + VkSamplerCreateInfo info{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; + VkSamplerReductionModeCreateInfo reduction{VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO}; + bool hasReduction = false; + const VkSamplerCreateInfo* Chain(); +}; + +PFN_vkVoidFunction DescriptorHeapObjectFunction(VkDevice device, PFN_vkGetDeviceProcAddr deviceProc, const char* name); +std::optional FindImageView(VkImageView view); +std::optional FindSampler(VkSampler sampler); + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index 9fe4caae0616..87cf67ac9a95 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -346,6 +346,10 @@ class GuestBufferMemory { // Whether registered allocations are pinned until write-back (address-based shaders): by this // build's own lease, or by the cached address space it holds. bool HoldsLease() const { return !lease.empty() || space != nullptr; } + bool SpaceOnly() const; + std::shared_ptr ReleaseSpace(); + bool RetakeSpace(); + bool SnapshotsServedInPlace(std::span snapshots) const; std::size_t CopiedBytes() const { std::size_t bytes = 0; for (const auto& region : regions) if (region.buffer != nullptr) bytes += static_cast((region.bufferEnd != 0 ? region.bufferEnd : region.end) - region.begin); @@ -489,6 +493,7 @@ class GuestBufferMemory { // The cached address space this build maps through (its lease pins the ranges); `regions` then // holds only the regions outside it (V#s, snapshots, ranges copied per build). std::shared_ptr space; + std::weak_ptr releasedSpace; mutable std::uint64_t tableSerial = 0; mutable std::shared_ptr> tableRanges; // Import registry epoch when `direct` pointers were taken at acquire time; they are reused while diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Pipeline.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Pipeline.hpp index abfb3226a68c..b0b014b70928 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Pipeline.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Pipeline.hpp @@ -47,6 +47,7 @@ class Pipeline { Pipeline(const Pipeline&) = delete; Pipeline& operator=(const Pipeline&) = delete; VkPipelineLayout Layout() const; + bool DescriptorHeap() const { return descriptorHeap; } std::shared_ptr AcquireFramebuffer(std::span targets, std::span> owners, VkExtent2D extent, std::uint32_t layers = 1); // Begins the render pass on the framebuffer, binds the pipeline and sets its dynamic state. void Begin(VkCommandBuffer commands, const Framebuffer& framebuffer, VkExtent2D extent, const State& state) const; @@ -94,6 +95,7 @@ class Pipeline { bool libraries = false; std::shared_ptr optimized; bool dynamicRendering = false; + bool descriptorHeap = false; VkFormat depthFormat = VK_FORMAT_UNDEFINED; VkImageLayout attachmentLayout = VK_IMAGE_LAYOUT_UNDEFINED; std::vector colorSlots; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp index fcd61045697d..c398c01818e8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp @@ -42,6 +42,7 @@ struct OptimizedPipeline { void Schedule(); }; +bool DescriptorHeapPipelineInfo(const VkGraphicsPipelineCreateInfo& info); VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPipelineCreateInfo& info, const VkPipelineRenderingCreateInfoKHR& rendering, const VkPipelineLayoutCreateInfo& layout, const PipelineLibraryKeys& keys, std::shared_ptr* optimized = nullptr, bool partsOnly = false, std::span modules = {}); void WaitForOptimizedPipelines(VkDevice device); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index 8f1c131eba0b..81a89e117d69 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -372,6 +372,7 @@ class Recorder { // validation instead of one per run, and every test sees the same snapshot (design13 R1's p0). using WriteRanges = std::vector>; static std::shared_ptr PendingWriteSnapshot(); + static bool ReadsSettled(std::span> ranges, const WriteRanges* before); static bool SnapshotOverlaps(const WriteRanges* snapshot, std::uint64_t address, std::size_t bytes); // A label behind pending completions (CPU write-backs the label must not precede): stored to // guest memory by a completion action appended to the open batch, or to the newest in-flight diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp index 7212fb40c6da..f494ce1a422f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp @@ -27,6 +27,11 @@ class Sampler { bool RequiresNonSeamlessCube() const; static void Validate(const Context& context, const GuestSamplerResource& descriptor); static bool ReadsOpaqueBlackBorder(const GuestSamplerResource& descriptor); + const std::array* CacheKey() const { return keyed ? &cacheKey : nullptr; } + void SetCacheKey(const std::array& key) { + cacheKey = key; + keyed = true; + } private: void release() noexcept; @@ -37,6 +42,8 @@ class Sampler { bool requiresFilterMinmax = false; bool opaqueBlackBorder = false; bool requiresNonSeamlessCube = false; + std::array cacheKey{}; + bool keyed = false; }; // One VkSampler per distinct S# (its 4 words plus the shader's depth-compare use and the diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index b3d8776df4c7..36fec5502f29 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -26,6 +26,7 @@ namespace AgcDriver { class VulkanDevice; } namespace AgcDriver::Graphics { + class Recorder; void FlushCachedTextures(VkDevice device); @@ -52,8 +53,6 @@ std::shared_ptr CachedSampledTexture(const Context& context, std::span< bool SampledTexturesShareEntry(std::span first, std::span second); bool AnyPendingCpuWrites(const Context& context); bool CompletePendingCpuWrites(const Context& context, std::uint64_t address, std::size_t bytes); -bool SpirvStoresThroughAddresses(std::span words); -bool ShaderStoresThroughAddresses(const ShaderRecompiler::SharedSpirv& spirv); void LastRecordIndices(std::span logged, std::span objects, std::vector& indices); // The cached storage image of a surface (render targets use it as their resident image); brought up @@ -69,6 +68,16 @@ bool StorageImageServesKeys(const StorageTexture& image, std::uint64_t dccAddres // a storage image other than `except` has results pending in [address, address + bytes). bool PendingStorageOverlaps(std::uint64_t address, std::size_t bytes, const StorageTexture* except); +inline std::size_t HeapStageIndex(ShaderRecompiler::ShaderStage stage) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + switch (stage) { + case ShaderRecompiler::ShaderStage::Fragment: return static_cast(Abi::Stage::Fragment); + case ShaderRecompiler::ShaderStage::TessellationControl: return static_cast(Abi::Stage::TessellationControl); + case ShaderRecompiler::ShaderStage::TessellationEvaluation: return static_cast(Abi::Stage::TessellationEvaluation); + default: return static_cast(Abi::Stage::Main); + } +} + struct PipelineSetLayouts { VkDescriptorSetLayout main = VK_NULL_HANDLE; VkDescriptorSetLayout fragment = VK_NULL_HANDLE; @@ -183,7 +192,9 @@ class ShaderResources { std::span LayoutBindingFlags() const { return layoutBindingFlags; } VkDescriptorSetLayout FragmentLayout() const { return fragment.layout; } bool SplitSets() const { return splitSets; } - PipelineSetLayouts SetLayouts() const { return {_layout, fragment.layout, splitSets, layoutKey, fragmentLayoutKey}; } + PipelineSetLayouts SetLayouts() const; + bool HeapStage() const { return heapStage; } + void RefreshHeapStage(std::span shaders); void Bind(VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout) const; struct DrawBindings { DrawBindings() = default; @@ -202,8 +213,12 @@ class ShaderResources { DescriptorCache::SetAllocation fragmentAllocation; DescriptorCache::SetAllocation allocation; std::vector snapshots; + bool addressOffsets = false; + std::array heapOffsets{}; + std::vector addressOverrides; ~DrawBindings(); }; + void RefreshMovedAddresses(DrawBindings& rewritten) const; struct MovedBuffer { std::size_t allocation; std::uint64_t address; @@ -233,7 +248,12 @@ class ShaderResources { // Whether a written buffer was copied (its results reach guest memory by the CPU write-back). bool HasCopiedWrites() const { return guestMemory.HasCopiedWrites(); } bool HoldsLease() const { return guestMemory.HoldsLease(); } + bool SpaceReuse() const { return spaceReuse; } + static bool SpaceReuseDisabled(); bool BdaReadOnly() const { return usesBda && bdaReadOnly; } + bool RetakeSpace() { return guestMemory.RetakeSpace(); } + bool SnapshotsServedInPlace(std::span snapshots) const { return guestMemory.SnapshotsServedInPlace(snapshots); } + std::shared_ptr ReleaseSpace() { return guestMemory.ReleaseSpace(); } bool UsesAddressTable() const { return usesBda; } std::size_t CopiedBytes() const { return guestMemory.CopiedBytes(); } bool WritesOverlap(std::uint64_t address, std::size_t bytes) const { return guestMemory.WritesOverlap(address, bytes); } @@ -313,6 +333,7 @@ class ShaderResources { void PatchPushConstants(std::span bytes) const { for (const auto& [position, adjustment] : pushPatches) bytes[position] = static_cast(adjustment); } + void PatchDataAddresses(std::span bytes, std::span shaders, const DrawBindings* rewritten) const; // Whether RefreshData would record anything for `shader` (the per-word compare; verification). bool DataWordsDiffer(const CompiledShader& shader) const; // Why the fast proof of a Revalidate left the object to the full walk (the [rescache] @@ -390,12 +411,18 @@ class ShaderResources { std::vector imageAllocations; VkDescriptorBindingFlags flags = 0; std::int32_t set = -1; + bool heap = false; + bool addressed = false; + std::uint32_t dataStage = 0; + std::uint32_t addressDword = 0; + ShaderRecompiler::DescriptorRole role = ShaderRecompiler::DescriptorRole::GuestBuffers; }; struct TableStage { ShaderRecompiler::ShaderStage stage = ShaderRecompiler::ShaderStage::Compute; const ShaderRecompiler::RecompileResult* program = nullptr; const ShaderRecompiler::DescriptorBinding* images = nullptr; + std::span imageWords; std::size_t mapAllocation = std::numeric_limits::max(); std::vector map; std::vector poison; @@ -408,15 +435,18 @@ class ShaderResources { bool storage = false; std::vector elementTextures; std::vector> samplerRejections; + bool heap = false; + std::vector elementStorage; + std::vector tableSamplers; }; std::vector tableStages; std::array tableBindings{std::numeric_limits::max(), std::numeric_limits::max()}; std::array tableElements{}; std::array storageTableBindings{std::numeric_limits::max(), std::numeric_limits::max()}; TableStage& tableStage(const CompiledShader& shader); - static const ShaderRecompiler::DescriptorBinding* tableImages(std::span shaders, ShaderRecompiler::ShaderStage stage); + static const ShaderRecompiler::DescriptorBinding* tableImages(std::span shaders, ShaderRecompiler::ShaderStage stage, std::span& words); std::uint32_t rejectTableElement(TableStage& table, std::span words, const std::string& message); - void addSamplerTable(const ShaderRecompiler::DescriptorBinding& binding, VkShaderStageFlags flags, TableStage& table); + void addSamplerTable(const ShaderRecompiler::DescriptorBinding& binding, std::span guest, VkShaderStageFlags flags, TableStage& table); void resolveImageTables(); void finishImageTables(); @@ -448,7 +478,7 @@ class ShaderResources { std::size_t addDataBuffer(std::span words); // Stage A: the layout entry of an image binding (samplers are taken at once, the sampler cache // locks itself); stage B looks the sampled textures and storage images up (resolveImageBinding). - void addImageBinding(const ShaderRecompiler::DescriptorBinding& binding, VkShaderStageFlags flags); + void addImageBinding(const ShaderRecompiler::DescriptorBinding& binding, std::span guest, VkShaderStageFlags flags); // Stage A: one record per planned image element (ImageRecord), in plan order: the decoded // descriptor and its surface size (computed once for the build), the write watch walked so stage // B's collects are memo hits (APS5_NO_PRECOLLECT=1 skips the pass entirely), and for a sampled @@ -490,7 +520,7 @@ class ShaderResources { // Stage B: the record's texture when the fastRevalidate predicate proves it current under the // lock and the cache still holds it; null sends the element to cachedTexture. std::shared_ptr fastTexture(const ImageRecord& record); - void resolveImageBinding(const ShaderRecompiler::DescriptorBinding& binding, Binding& item, std::span> shaderSamplers); + void resolveImageBinding(const ShaderRecompiler::DescriptorBinding& binding, std::span guest, Binding& item, std::span> shaderSamplers); void applyAnisoOverride(); void forgetDeferredInputs(); void release() noexcept; @@ -560,6 +590,7 @@ class ShaderResources { std::vector srtGuardFaults; bool usesBda = false; bool bdaReadOnly = true; + bool spaceReuse = false; std::vector multisampleSources; bool usesFaultBuffer = false; bool faultChecks = false; @@ -578,6 +609,23 @@ class ShaderResources { DescriptorCache::SetAllocation cacheAllocation; }; bool splitSets = false; + bool heapStage = false; + std::array heapOffsets{}; + void writeHeapStage(const CompiledShader& shader); + struct HeapStageState { + std::vector key; + std::array, static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)> slots; + std::vector slotGenerations; + std::vector samplerSlots; + std::vector samplerGenerations; + std::uint64_t slotSerial = 0; + std::vector> dataPatches; + }; + std::array heapStages; + static constexpr std::int64_t HeapRingDataFirst = -2; + static constexpr std::int64_t HeapRingData(std::size_t stage) { return HeapRingDataFirst - static_cast(stage); } + static constexpr bool IsHeapRingData(std::int64_t allocation) { return allocation <= HeapRingDataFirst && allocation > HeapRingDataFirst - static_cast(ShaderRecompiler::RuntimeAbi::StageCount); } + static constexpr std::size_t HeapRingStage(std::int64_t allocation) { return static_cast(HeapRingDataFirst - allocation); } std::vector fragmentLayoutKey; SetObjects fragment; struct TableWrites { @@ -602,6 +650,16 @@ class ShaderResources { std::shared_ptr buffer; }; mutable std::vector movedWordBuffers; + bool addressedBuffers = false; + std::size_t gdsAllocation = std::numeric_limits::max(); + std::array, ShaderRecompiler::RuntimeAbi::StageCount> stageDataWords; + std::array stageDataIndex{}; + std::array heapSrtDwords{}; + std::array heapTableMaps{}; + std::array heapTableMapSet{}; + void writeHeapTableMap(const CompiledShader& shader, std::size_t stageIndex); + void writeBufferAddresses(std::span words, std::uint32_t dataStage, const std::vector* overrides) const; + std::array addressedOffsets(const std::vector* overrides) const; mutable std::size_t movedWordBufferNext = 0; mutable std::vector drawPoolSizes; // Guest buffer elements bound read-only: each use of this object skips that many pending-write @@ -663,6 +721,7 @@ class ShaderResources { std::vector refreshResourceKey; struct DeferredImages { const ShaderRecompiler::DescriptorBinding* binding; + std::span words; std::size_t index; std::size_t firstSampler = 0; std::size_t samplerCount = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp index 2ddac45e80b1..d575cd5c21a6 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp @@ -37,8 +37,23 @@ struct CompiledShader { ShaderRecompiler::ShaderStage stage; const ShaderRecompiler::RecompileResult* program; std::uint32_t pushConstantOffset; + const ShaderRecompiler::HeapStageWords* heap = nullptr; }; +inline const std::vector& DrawGuestWords(const ShaderRecompiler::RecompileResult& program, const ShaderRecompiler::HeapStageWords* heap, const ShaderRecompiler::DescriptorBinding& binding) { + if (heap == nullptr || heap->bindings.empty()) return binding.guestDescriptor; + const auto index = static_cast(&binding - program.bindings.data()); + return index < heap->bindings.size() && !heap->bindings[index].empty() ? heap->bindings[index] : binding.guestDescriptor; +} + +inline const std::vector& DrawGuestWords(const CompiledShader& shader, const ShaderRecompiler::DescriptorBinding& binding) { + return DrawGuestWords(*shader.program, shader.heap, binding); +} + +inline const std::vector& DrawVertexAttributes(const CompiledShader& shader) { + return shader.heap != nullptr && !shader.heap->vertexAttributes.empty() ? shader.heap->vertexAttributes : shader.program->vertexAttributes; +} + inline VkShaderStageFlagBits VulkanStage(ShaderRecompiler::ShaderStage stage) { switch (stage) { case ShaderRecompiler::ShaderStage::Vertex: @@ -73,7 +88,7 @@ inline VkShaderStageFlags PushConstantStages(std::span sha VkShaderStageFlags result = 0; for (const auto& shader : shaders) { Require(shader.program != nullptr, "missing compiled shader"); - if (!shader.program->pushConstants.empty() || shader.program->readsDepthRemapPush || shader.stage == ShaderRecompiler::ShaderStage::Mesh || shader.stage == ShaderRecompiler::ShaderStage::TessellationControl) result |= VulkanStage(shader.stage); + if (!shader.program->pushConstants.empty() || shader.program->readsDepthRemapPush || shader.program->dataAddressPush || shader.stage == ShaderRecompiler::ShaderStage::Mesh || shader.stage == ShaderRecompiler::ShaderStage::TessellationControl) result |= VulkanStage(shader.stage); } return result; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp index 0c6aec2abf01..d2bd289371a2 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp @@ -103,6 +103,7 @@ class Texture { ViewRange SampledViewRange(bool firstLayer) const { return firstLayer ? firstLayerRange : viewRange; } // The layout the image is kept in while sampled. VkImageLayout Layout() const { return layout; } + VkImage Image() const { return image; } VkDeviceSize AllocationBytes() const { return allocationBytes; } VkFormat ViewFormat() const { return viewFormat; } // Whether this texture is a view of a storage image (no snapshot of its own). @@ -119,8 +120,12 @@ class Texture { void MarkRefreshedPerUse() { perUseCopy = PerUseCopy::RemadePerUse; } bool Released() const { return released.load(std::memory_order_acquire); } void MarkReleased() { released.store(true, std::memory_order_release); } + std::uint32_t HeapHolds() const { return heapHolds.load(std::memory_order_relaxed); } + void AddHeapHold() { heapHolds.fetch_add(1, std::memory_order_relaxed); } + void DropHeapHold() { heapHolds.fetch_sub(1, std::memory_order_relaxed); } private: + std::atomic heapHolds{0}; void release() noexcept; bool refreshBlockCopy(); bool refreshSrgbExpand(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp index aa267a27f692..7fb92d097249 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp @@ -4,6 +4,7 @@ #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include #include +#include #include #include #include diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp new file mode 100644 index 000000000000..330ac1f42919 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -0,0 +1,697 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" + +#include +#include +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "RuntimeAbi.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +namespace { + +namespace Abi = ShaderRecompiler::RuntimeAbi; + +void check(VkResult result, const char* what) { + if (result != VK_SUCCESS) throw std::runtime_error(std::string("AGC bindless heap: ") + what + " failed: " + std::to_string(static_cast(result))); +} + +std::uint32_t fragmentBinding(std::uint32_t kind) { + return Abi::BindingNumber(Abi::Stage::Fragment, static_cast(kind)); +} + +} + +bool GpuHeapEnabled() { + static const bool enabled = std::getenv("APS5_GPU_HEAP") != nullptr; + return enabled; +} + +namespace { +std::atomic heapComputeStages{0}; +std::atomic descriptorHeapDevice{false}; +std::atomic imageTableBuilds{0}; +std::atomic dataAddressPushes{0}; +std::atomic emptyResourceSets{0}; +} + +void NoteImageTableBuild() { + imageTableBuilds.fetch_add(1, std::memory_order_relaxed); +} + +std::uint64_t ImageTableBuilds() { + return imageTableBuilds.load(std::memory_order_relaxed); +} + +void NoteDataAddressPush() { + dataAddressPushes.fetch_add(1, std::memory_order_relaxed); +} + +std::uint64_t DataAddressPushes() { + return dataAddressPushes.load(std::memory_order_relaxed); +} + +void NoteEmptyResourceSet() { + emptyResourceSets.fetch_add(1, std::memory_order_relaxed); +} + +std::uint64_t EmptyResourceSets() { + return emptyResourceSets.load(std::memory_order_relaxed); +} + +void NoteHeapComputeStage() { + heapComputeStages.fetch_add(1, std::memory_order_relaxed); +} + +std::uint64_t HeapComputeStages() { + return heapComputeStages.load(std::memory_order_relaxed); +} + +void SetDescriptorHeapDevice(bool available) { + descriptorHeapDevice.store(available, std::memory_order_relaxed); +} + +bool DescriptorHeapEnabled() { + return GpuHeapEnabled() && descriptorHeapDevice.load(std::memory_order_relaxed); +} + +bool HeapComputeEnabled() { + return DescriptorHeapEnabled(); +} + +BindlessHeap::BindlessHeap(const Context& context) : context(context) { + Require(context.descriptorHeap, "the GPU heap needs VK_EXT_descriptor_heap"); + const auto& heapProperties = context.descriptorHeapProperties; + const auto align = [](VkDeviceSize value, VkDeviceSize alignment) { return alignment == 0 ? value : (value + alignment - 1) / alignment * alignment; }; + imageHeapStride = align(heapProperties.imageDescriptorSize, heapProperties.imageDescriptorAlignment); + samplerHeapStride = align(heapProperties.samplerDescriptorSize, heapProperties.samplerDescriptorAlignment); + resourceHeapUsed = align(static_cast(static_cast(Abi::Binding::Samplers)) * Abi::GpuImageHeapSlots * imageHeapStride, heapProperties.resourceHeapAlignment); + samplerHeapUsed = align(static_cast(Abi::GpuSamplerHeapSlots) * samplerHeapStride, heapProperties.samplerHeapAlignment); + Require(resourceHeapUsed + heapProperties.minResourceHeapReservedRange <= heapProperties.maxResourceHeapSize, "the GPU heap's image slots exceed the device's resource heap size"); + Require(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded <= heapProperties.maxSamplerHeapSize, "the GPU heap's sampler slots exceed the device's sampler heap size"); + constexpr VkBufferUsageFlags heapUsage = VK_BUFFER_USAGE_DESCRIPTOR_HEAP_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + resourceHeap = std::make_unique(context, static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange), heapUsage); + samplerHeap = std::make_unique(context, static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage); + std::fill(resourceHeap->Bytes().begin(), resourceHeap->Bytes().end(), std::byte{0}); + std::fill(samplerHeap->Bytes().begin(), samplerHeap->Bytes().end(), std::byte{0}); + constexpr VkBufferUsageFlags ringUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + try { + ring = std::make_unique(context, RingBytes, ringUsage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + } catch (const std::exception&) { + ring = std::make_unique(context, RingBytes, ringUsage); + } + ringAlignment = static_cast(std::max(context.limits.minStorageBufferOffsetAlignment, 16)); + nextTextureSlot.assign(static_cast(Abi::Binding::Samplers), 0u); + ringChunks.resize(RingBytes / RingChunkBytes); + owners.resize(static_cast(Abi::Binding::Samplers)); + freeSlots.resize(static_cast(Abi::Binding::Samplers)); + const char* cap = std::getenv("APS5_HEAP_SLOT_CAP"); + slotCap = cap != nullptr ? std::min(static_cast(std::strtoul(cap, nullptr, 10)), Abi::GpuImageHeapSlots) : Abi::GpuImageHeapSlots; + if (slotCap == 0u) slotCap = Abi::GpuImageHeapSlots; +} + +BindlessHeap::~BindlessHeap() = default; + +namespace { + +std::mutex& heapsMutex() { + static std::mutex mutex; + return mutex; +} + +std::unordered_map>& heaps() { + static auto& map = *new std::unordered_map>(); + return map; +} + +} + +namespace { +std::atomic heapsEpoch{0}; +} + +BindlessHeap& BindlessHeap::For(const Context& context) { + struct Cached { + VkDevice device = VK_NULL_HANDLE; + BindlessHeap* heap = nullptr; + std::uint64_t epoch = ~std::uint64_t{0}; + }; + thread_local Cached cached; + const bool trims = CommitTrims(); + if (trims && cached.heap != nullptr && cached.device == context.device && cached.epoch == heapsEpoch.load(std::memory_order_acquire)) { + return *cached.heap; + } + std::lock_guard lock(heapsMutex()); + auto& heap = heaps()[context.device]; + if (heap == nullptr) { + heap = std::make_unique(context); + heapsEpoch.fetch_add(1, std::memory_order_acq_rel); + } + if (trims) cached = {context.device, heap.get(), heapsEpoch.load(std::memory_order_acquire)}; + return *heap; +} + +void BindlessHeap::Release(VkDevice device) { + std::unique_ptr released; + { + std::lock_guard lock(heapsMutex()); + const auto found = heaps().find(device); + if (found == heaps().end()) return; + released = std::move(found->second); + heaps().erase(found); + heapsEpoch.fetch_add(1, std::memory_order_acq_rel); + } +} + +BindlessHeap* BindlessHeap::Existing(const Context& context) { + std::lock_guard lock(heapsMutex()); + const auto found = heaps().find(context.device); + return found == heaps().end() ? nullptr : found->second.get(); +} + +std::optional BindlessHeap::TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, VkImageLayout layout) { + if (kind < Abi::FirstImageBinding || kind >= Abi::FirstStorageImageBinding || texture == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid texture slot request"); + std::vector> dropped; + std::lock_guard lock(mutex); + const TextureKey key{kind, texture.get(), view, layout}; + if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; + if (++slotRequests % 1024u == 0u) NoteSweepDue(); + auto slot = takeSlotLocked(kind); + if (!slot) { + sweepLocked(dropped); + slot = takeSlotLocked(kind); + } + if (!slot) { + ++counts.full; + return std::nullopt; + } + const VkDescriptorImageInfo image{VK_NULL_HANDLE, view, layout}; + const VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, VK_NULL_HANDLE, fragmentBinding(kind), *slot, 1, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, &image, nullptr, nullptr}; + writeDescriptorHeap(write); + textureSlots.emplace(key, *slot); + auto& kindOwners = owners[kind]; + if (kindOwners.size() <= *slot) kindOwners.resize(*slot + 1u); + kindOwners[*slot].texture = texture; + kindOwners[*slot].key = key; + texture->AddHeapHold(); + ++counts.textures; + noteTakenLocked(kind, dropped); + return slot; +} + +std::optional BindlessHeap::StorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view) { + if (!Abi::GpuHeapStorageKind(kind) || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid storage slot request"); + std::vector> dropped; + std::lock_guard lock(mutex); + const TextureKey key{kind, owner.get(), view, VK_IMAGE_LAYOUT_GENERAL}; + if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; + if (++slotRequests % 1024u == 0u) NoteSweepDue(); + auto slot = takeSlotLocked(kind); + if (!slot) { + sweepLocked(dropped); + slot = takeSlotLocked(kind); + } + if (!slot) { + ++counts.full; + return std::nullopt; + } + const VkDescriptorImageInfo image{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; + const VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, VK_NULL_HANDLE, fragmentBinding(kind), *slot, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &image, nullptr, nullptr}; + writeDescriptorHeap(write); + textureSlots.emplace(key, *slot); + auto& kindOwners = owners[kind]; + if (kindOwners.size() <= *slot) kindOwners.resize(*slot + 1u); + kindOwners[*slot].storage = std::move(owner); + kindOwners[*slot].key = key; + ++counts.textures; + return slot; +} + +std::optional BindlessHeap::takeSlotLocked(std::uint32_t kind) { + auto& free = freeSlots[kind]; + if (!free.empty()) { + const auto slot = free.back(); + free.pop_back(); + ++counts.slotsReused; + return slot; + } + auto& next = nextTextureSlot[kind]; + if (next >= slotCap) return std::nullopt; + return next++; +} + +void BindlessHeap::sweepLocked(std::vector>& dropped) { + ++counts.sweeps; + const auto firstDropped = dropped.size(); + for (std::uint32_t kind = 0; kind < owners.size(); ++kind) { + auto& kindOwners = owners[kind]; + for (std::uint32_t slot = 0; slot < kindOwners.size(); ++slot) { + auto& owner = kindOwners[slot]; + if (owner.storage != nullptr) { + if (owner.storage.use_count() > 1) continue; + textureSlots.erase(owner.key); + owner.storage.reset(); + owner.key = {}; + ++owner.generation; + slotSerial.fetch_add(1, std::memory_order_release); + freeSlots[kind].push_back(slot); + ++counts.slotsFreed; + continue; + } + if (owner.texture == nullptr || owner.texture.use_count() > static_cast(owner.texture->HeapHolds())) continue; + textureSlots.erase(owner.key); + dropped.push_back(std::move(owner.texture)); + owner.key = {}; + ++owner.generation; + slotSerial.fetch_add(1, std::memory_order_release); + freeSlots[kind].push_back(slot); + ++counts.slotsFreed; + } + } + for (auto index = firstDropped; index < dropped.size(); ++index) dropped[index]->DropHeapHold(); +} + +void BindlessHeap::sweepSamplersLocked(std::vector>& dropped) { + for (std::uint32_t slot = 0; slot < heldSamplers.size(); ++slot) { + auto& held = heldSamplers[slot]; + if (held == nullptr || held.use_count() != 1) continue; + samplerSlots.erase(held.get()); + dropped.push_back(std::move(held)); + ++samplerGenerations[slot]; + slotSerial.fetch_add(1, std::memory_order_release); + freeSamplerSlots.push_back(slot); + ++counts.slotsFreed; + } +} + +namespace { + +constexpr std::uint32_t ImageSlotMargin = 1024u; +constexpr std::uint32_t SamplerSlotMargin = Abi::GpuSamplerHeapSlots / 4u; +std::atomic nearlyFull{false}; + +void noteNearlyFull(const char* what, std::uint32_t margin) { + if (!nearlyFull.exchange(true, std::memory_order_relaxed)) std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; draws take the per-draw path from now on\n", margin, what); +} + +} + +bool BindlessHeap::NearlyFull() { + return nearlyFull.load(std::memory_order_relaxed); +} + +namespace { + +std::atomic sweepDue{false}; + +} + +void BindlessHeap::NoteSweepDue() { + sweepDue.store(true, std::memory_order_relaxed); +} + +void BindlessHeap::SweepIfDue() { + if (!sweepDue.load(std::memory_order_relaxed) || !sweepDue.exchange(false, std::memory_order_relaxed)) return; + std::vector> dropped; + std::vector> droppedSamplers; + std::lock_guard heapsLock(heapsMutex()); + bool room = true; + for (auto& [device, heap] : heaps()) { + if (heap == nullptr) continue; + std::lock_guard lock(heap->mutex); + heap->sweepLocked(dropped); + heap->sweepSamplersLocked(droppedSamplers); + room = room && heap->roomLocked(); + } + if (room && nearlyFull.exchange(false, std::memory_order_relaxed)) std::fprintf(stderr, "[gpu-heap] a sweep left twice the margin of slots free; draws take the heap again\n"); +} + +std::uint32_t BindlessHeap::imageMargin() const { + return std::max(1u, std::min(ImageSlotMargin, slotCap / 4u)); +} + +std::size_t BindlessHeap::unusedLocked(std::uint32_t kind) const { + const auto next = nextTextureSlot[kind]; + return (next < slotCap ? slotCap - next : 0u) + freeSlots[kind].size(); +} + +bool BindlessHeap::roomLocked() const { + for (std::uint32_t kind = Abi::FirstImageBinding; kind < Abi::FirstStorageImageBinding; ++kind) { + if (unusedLocked(kind) < 2u * static_cast(imageMargin())) return false; + } + return Abi::GpuSamplerHeapSlots - heldSamplers.size() + freeSamplerSlots.size() >= 2u * SamplerSlotMargin; +} + +void BindlessHeap::noteTakenLocked(std::uint32_t kind, std::vector>& dropped) { + if (nearlyFull.load(std::memory_order_relaxed)) return; + const auto margin = imageMargin(); + if (unusedLocked(kind) >= margin) return; + sweepLocked(dropped); + if (unusedLocked(kind) < margin) noteNearlyFull("image", margin); +} + +void BindlessHeap::noteSamplerTakenLocked(std::vector>& dropped) { + if (nearlyFull.load(std::memory_order_relaxed)) return; + const auto unused = [&] { return Abi::GpuSamplerHeapSlots - heldSamplers.size() + freeSamplerSlots.size(); }; + if (unused() >= SamplerSlotMargin) return; + sweepSamplersLocked(dropped); + if (unused() < SamplerSlotMargin) noteNearlyFull("sampler", SamplerSlotMargin); +} + +std::uint32_t BindlessHeap::SamplerGeneration(std::uint32_t slot) const { + std::lock_guard lock(mutex); + return slot < samplerGenerations.size() ? samplerGenerations[slot] : 0u; +} + +bool BindlessHeap::GenerationsCurrent(std::span> slots, std::span slotGenerations, std::span samplerSlots, std::span samplerGenerations) const { + std::lock_guard lock(mutex); + std::size_t generation = 0; + for (std::uint32_t kind = 0; kind < slots.size(); ++kind) { + for (const auto slot : slots[kind]) { + const auto current = kind < owners.size() && slot < owners[kind].size() ? owners[kind][slot].generation : 0u; + if (generation >= slotGenerations.size() || current != slotGenerations[generation++]) return false; + } + } + for (std::size_t i = 0; i < samplerSlots.size(); ++i) { + if (i >= samplerGenerations.size() || (samplerSlots[i] < this->samplerGenerations.size() ? this->samplerGenerations[samplerSlots[i]] : 0u) != samplerGenerations[i]) return false; + } + return true; +} + +std::uint32_t BindlessHeap::SlotGeneration(std::uint32_t kind, std::uint32_t slot) const { + std::lock_guard lock(mutex); + return kind < owners.size() && slot < owners[kind].size() ? owners[kind][slot].generation : 0u; +} + +const Texture* BindlessHeap::SlotTexture(std::uint32_t kind, std::uint32_t slot) const { + std::lock_guard lock(mutex); + return kind < owners.size() && slot < owners[kind].size() ? owners[kind][slot].texture.get() : nullptr; +} + +std::uint32_t BindlessHeap::AbsentSlot(std::uint32_t kind, VkImageView view) { + if (kind < Abi::FirstImageBinding || kind >= static_cast(Abi::Binding::Samplers)) throw std::runtime_error("AGC bindless heap: invalid absent slot request"); + std::lock_guard lock(mutex); + if (const auto found = absentSlots.find(kind); found != absentSlots.end()) return found->second; + const auto taken = takeSlotLocked(kind); + if (!taken) throw std::runtime_error("AGC bindless heap: the image heap is full"); + const auto slot = *taken; + const VkDescriptorImageInfo image{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; + const VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, VK_NULL_HANDLE, fragmentBinding(kind), slot, 1, Abi::GpuHeapStorageKind(kind) ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, &image, nullptr, nullptr}; + writeDescriptorHeap(write); + absentSlots.emplace(kind, slot); + return slot; +} + +std::optional BindlessHeap::SamplerSlot(const std::shared_ptr& sampler) { + if (sampler == nullptr) throw std::runtime_error("AGC bindless heap: invalid sampler slot request"); + std::vector> dropped; + std::lock_guard lock(mutex); + if (const auto found = samplerSlots.find(sampler.get()); found != samplerSlots.end()) return found->second; + if (freeSamplerSlots.empty()) sweepSamplersLocked(dropped); + std::uint32_t slot = 0; + if (!freeSamplerSlots.empty()) { + slot = freeSamplerSlots.back(); + freeSamplerSlots.pop_back(); + ++counts.slotsReused; + } else if (heldSamplers.size() < Abi::GpuSamplerHeapSlots) { + slot = static_cast(heldSamplers.size()); + heldSamplers.emplace_back(); + samplerGenerations.push_back(0u); + } else { + ++counts.full; + return std::nullopt; + } + const VkDescriptorImageInfo info{sampler->Handle(), VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; + const VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, VK_NULL_HANDLE, fragmentBinding(static_cast(Abi::Binding::Samplers)), slot, 1, VK_DESCRIPTOR_TYPE_SAMPLER, &info, nullptr, nullptr}; + writeDescriptorHeap(write); + samplerSlots.emplace(sampler.get(), slot); + heldSamplers[slot] = sampler; + ++counts.samplers; + noteSamplerTakenLocked(dropped); + return slot; +} + +BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words) { + const auto bytes = words * sizeof(std::uint32_t); + if (bytes > RingChunkBytes) throw std::runtime_error("AGC bindless heap: per-draw data exceeds a ring chunk"); + std::lock_guard lock(mutex); + auto offset = (ringCursor + ringAlignment - 1) / ringAlignment * ringAlignment; + if (offset + bytes > RingBytes) { + offset = 0; + ++counts.ringWraps; + } + ringCursor = offset + bytes; + for (auto chunk = offset / RingChunkBytes; chunk <= (offset + std::max(bytes, 1u) - 1u) / RingChunkBytes; ++chunk) enterChunk(ringChunks, chunk, ringChunk, "shader data"); + auto* base = reinterpret_cast(ring->Bytes().data() + offset); + return {static_cast(offset), std::span(base, words)}; +} + +void BindlessHeap::enterChunk(std::vector& chunks, std::size_t index, std::size_t& current, const char* what) { + if (index == current) return; + current = index; + auto& chunk = chunks[index]; + if (chunk.open) throw std::runtime_error(std::string("AGC bindless heap: one batch's ") + what + " exceeds its ring"); + if (chunk.serial != 0u) { + ++counts.chunkWaits; + if (!chunk.recorder->HasTimeline()) throw std::runtime_error(std::string("AGC bindless heap: the ") + what + " ring needs the recorder timeline to wait for a batch"); + chunk.recorder->WaitSerial(chunk.serial); + chunk.serial = 0u; + } + chunk.open = true; +} + +VkDeviceSize BindlessHeap::ImageHeapOffset(std::uint32_t kind) const { + return static_cast(kind) * Abi::GpuImageHeapSlots * imageHeapStride; +} + +void BindlessHeap::writeDescriptorHeap(const VkWriteDescriptorSet& write) { + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + const auto kind = write.dstBinding % bindingCount; + if (write.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { + const auto writeSamplers = context.Function("vkWriteSamplerDescriptorsEXT"); + for (std::uint32_t element = 0; element < write.descriptorCount; ++element) { + auto record = FindSampler(write.pImageInfo[element].sampler); + Require(record.has_value(), "a GPU heap sampler has no recorded create info"); + const auto offset = static_cast(write.dstArrayElement + element) * samplerHeapStride; + Require(offset + samplerHeapStride <= samplerHeapUsed, "a GPU heap sampler slot lies outside the sampler heap"); + const VkHostAddressRangeEXT target{samplerHeap->Bytes().data() + offset, static_cast(samplerHeapStride)}; + check(writeSamplers(context.device, 1, record->Chain(), &target), "vkWriteSamplerDescriptorsEXT"); + } + return; + } + Require(write.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE || write.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, "the GPU heap writes only images and samplers into the descriptor heap"); + const auto writeResources = context.Function("vkWriteResourceDescriptorsEXT"); + for (std::uint32_t element = 0; element < write.descriptorCount; ++element) { + const auto& image = write.pImageInfo[element]; + const auto offset = ImageHeapOffset(kind) + static_cast(write.dstArrayElement + element) * imageHeapStride; + Require(offset + imageHeapStride <= resourceHeapUsed, "a GPU heap image slot lies outside the resource heap"); + auto* target = resourceHeap->Bytes().data() + offset; + if (image.imageView == VK_NULL_HANDLE) { + std::memset(target, 0, static_cast(imageHeapStride)); + continue; + } + auto record = FindImageView(image.imageView); + Require(record.has_value(), "a GPU heap image view has no recorded create info"); + const VkImageDescriptorInfoEXT imageInfo{VK_STRUCTURE_TYPE_IMAGE_DESCRIPTOR_INFO_EXT, nullptr, record->Chain(), image.imageLayout}; + VkResourceDescriptorInfoEXT resource{VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT}; + resource.type = write.descriptorType; + resource.data.pImage = &imageInfo; + const VkHostAddressRangeEXT range{target, static_cast(imageHeapStride)}; + check(writeResources(context.device, 1, &resource, &range), "vkWriteResourceDescriptorsEXT"); + } +} + +namespace { + +const std::uint32_t GeneratedFaultBinding = Abi::BindingNumber(Abi::Stage::TessellationControl, Abi::Binding::FaultBuffer); + +bool heapBindings(std::span spirv, bool workgroupAddress, bool gdsAddress, bool faultAddress, std::vector& bindings, bool& workgroupMemory, std::uint32_t& gdsBinding, bool& faultMemory) { + bindings.clear(); + workgroupMemory = false; + gdsBinding = ~0u; + faultMemory = false; + if (spirv.size() < 5u) return false; + constexpr std::uint32_t opDecorate = 71u; + constexpr std::uint32_t decorationBinding = 33u; + constexpr std::uint32_t decorationSet = 34u; + std::unordered_map> decorated; + for (std::size_t at = 5; at < spirv.size();) { + const auto count = spirv[at] >> 16u; + if (count == 0u || at + count > spirv.size()) return false; + if ((spirv[at] & 0xffffu) == opDecorate && count >= 4u) { + auto& entry = decorated.try_emplace(spirv[at + 1u], std::pair{~0u, ~0u}).first->second; + if (spirv[at + 2u] == decorationSet) entry.first = spirv[at + 3u]; + if (spirv[at + 2u] == decorationBinding) entry.second = spirv[at + 3u]; + } + at += count; + } + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + constexpr auto samplerBinding = static_cast(Abi::Binding::Samplers); + for (const auto& [id, entry] : decorated) { + if (entry.first == ~0u && entry.second == ~0u) continue; + if (workgroupAddress && entry.first == ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet && entry.second == 0u) { + workgroupMemory = true; + continue; + } + if (gdsAddress && entry.first == Abi::GpuGdsSet && gdsBinding == ~0u) { + gdsBinding = entry.second; + continue; + } + if (faultAddress && entry.first == Abi::DescriptorSet && entry.second == GeneratedFaultBinding) { + faultMemory = true; + continue; + } + if (entry.first != Abi::FragmentDescriptorSet || entry.second < bindingCount + Abi::FirstImageBinding || entry.second > bindingCount + samplerBinding) return false; + if (std::find(bindings.begin(), bindings.end(), entry.second) == bindings.end()) bindings.push_back(entry.second); + } + return (!workgroupAddress || workgroupMemory) && (!faultAddress || faultMemory); +} + +} + +bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress) { + std::vector bindings; + bool workgroupMemory = false; + std::uint32_t gdsBinding = ~0u; + bool faultMemory = false; + return heapBindings(spirv, workgroupAddress, gdsAddress, false, bindings, workgroupMemory, gdsBinding, faultMemory); +} + +bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset, bool rootGds, bool rootFault) const { + mappings.clear(); + std::vector bindings; + bool workgroupMemory = false; + std::uint32_t gdsBinding = ~0u; + bool faultMemory = false; + if (resourceHeap == nullptr || !heapBindings(spirv, workgroupAddressOffset != ~0u, rootGds, rootFault, bindings, workgroupMemory, gdsBinding, faultMemory)) return false; + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + constexpr auto samplerBinding = static_cast(Abi::Binding::Samplers); + std::sort(bindings.begin(), bindings.end()); + for (const auto binding : bindings) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = Abi::FragmentDescriptorSet; + mapping.firstBinding = binding; + mapping.bindingCount = 1; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT; + const auto kind = binding - bindingCount; + if (kind == samplerBinding) { + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT; + mapping.sourceData.constantOffset.heapOffset = 0; + mapping.sourceData.constantOffset.heapArrayStride = static_cast(samplerHeapStride); + } else { + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_IMAGE_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; + mapping.sourceData.constantOffset.heapOffset = static_cast(ImageHeapOffset(kind)); + mapping.sourceData.constantOffset.heapArrayStride = static_cast(imageHeapStride); + } + mappings.push_back(mapping); + } + if (workgroupMemory) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet; + mapping.firstBinding = 0; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; + mapping.sourceData.pushAddressOffset = workgroupAddressOffset; + mappings.push_back(mapping); + } + if (gdsBinding != ~0u) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = Abi::GpuGdsSet; + mapping.firstBinding = gdsBinding; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; + mapping.sourceData.pushAddressOffset = (Abi::RootDword + Abi::RootGdsAddress) * sizeof(std::uint32_t); + mappings.push_back(mapping); + } + if (faultMemory) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = Abi::DescriptorSet; + mapping.firstBinding = GeneratedFaultBinding; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; + mapping.sourceData.pushAddressOffset = (Abi::RootDword + Abi::RootFaultAddress) * sizeof(std::uint32_t); + mappings.push_back(mapping); + } + return true; +} + +namespace { + +std::mutex boundHeapsMutex; +std::unordered_set boundHeaps; +std::atomic heapBinds{0}; + +void forgetHeapBinding(VkCommandBuffer commands) { + if (!DescriptorHeapEnabled()) return; + std::lock_guard lock(boundHeapsMutex); + boundHeaps.erase(commands); +} + +} + +void NoteCommandBufferBegun(VkCommandBuffer commands) { + forgetHeapBinding(commands); +} + +void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets) { + context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, bindPoint, layout, firstSet, setCount, sets, 0, nullptr); + forgetHeapBinding(commands); +} + +std::uint64_t DescriptorHeapBinds() { + return heapBinds.load(std::memory_order_relaxed); +} + +void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { + if (resourceHeap == nullptr) return; + { + std::lock_guard lock(boundHeapsMutex); + if (!boundHeaps.insert(commands).second) return; + } + heapBinds.fetch_add(1, std::memory_order_relaxed); + VkBindHeapInfoEXT info{VK_STRUCTURE_TYPE_BIND_HEAP_INFO_EXT}; + info.heapRange = {resourceHeap->DeviceAddress(), resourceHeapUsed + context.descriptorHeapProperties.minResourceHeapReservedRange}; + info.reservedRangeOffset = resourceHeapUsed; + info.reservedRangeSize = context.descriptorHeapProperties.minResourceHeapReservedRange; + context.Function("vkCmdBindResourceHeapEXT")(commands, &info); + info.heapRange = {samplerHeap->DeviceAddress(), samplerHeapUsed + context.descriptorHeapProperties.minSamplerHeapReservedRangeWithEmbedded}; + info.reservedRangeOffset = samplerHeapUsed; + info.reservedRangeSize = context.descriptorHeapProperties.minSamplerHeapReservedRangeWithEmbedded; + context.Function("vkCmdBindSamplerHeapEXT")(commands, &info); +} + +VkDeviceAddress BindlessHeap::RingAddress() const { + return ring->DeviceAddress(); +} + +void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { + std::lock_guard lock(mutex); + for (std::size_t index = 0; index < ringChunks.size(); ++index) { + if (ringChunks[index].open || index == ringChunk) ringChunks[index] = {&recorder, serial, index == ringChunk}; + } +} + +BindlessHeap::Counts BindlessHeap::Statistics() const { + std::lock_guard lock(mutex); + return counts; +} + +} diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp index 9b22e6a5b54b..1a3941008133 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp @@ -381,7 +381,22 @@ std::size_t BufferPool::NextCapacity(std::size_t capacity) { return capacity < classLimit ? capacity * 2 : capacity + (std::bit_floor(capacity) >> deviceClassBits); } +namespace { + +std::atomic forceAddresses{false}; + +} + +bool BufferPool::ForceAddresses() { + return forceAddresses.load(std::memory_order_relaxed); +} + +void BufferPool::SetForceAddresses(bool force) { + forceAddresses.store(force, std::memory_order_relaxed); +} + VkBufferUsageFlags BufferPool::Usage(VkBufferUsageFlags usage, VkMemoryPropertyFlags properties) { + if (ForceAddresses() && (usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) != 0) usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; return DeviceTiered(properties) ? usage | deviceUsage : usage; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp new file mode 100644 index 000000000000..66005bfc1289 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp @@ -0,0 +1,164 @@ +#include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" + +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +namespace { + +std::atomic realCreateImageView{nullptr}; +std::atomic realDestroyImageView{nullptr}; +std::atomic realCreateSampler{nullptr}; +std::atomic realDestroySampler{nullptr}; + +std::mutex& recordsMutex() { + static auto& mutex = *new std::mutex(); + return mutex; +} + +std::unordered_map& views() { + static auto& map = *new std::unordered_map(); + return map; +} + +std::unordered_map& samplers() { + static auto& map = *new std::unordered_map(); + return map; +} + +ImageViewRecord recordOf(const VkImageViewCreateInfo& info) { + ImageViewRecord record; + record.info = info; + record.info.pNext = nullptr; + for (auto* next = static_cast(info.pNext); next != nullptr; next = next->pNext) { + if (next->sType == VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO) { + record.usage = *reinterpret_cast(next); + record.hasUsage = true; + } else if (next->sType == VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT) { + record.minLod = *reinterpret_cast(next); + record.hasMinLod = true; + } + } + return record; +} + +SamplerRecord recordOf(const VkSamplerCreateInfo& info) { + SamplerRecord record; + record.info = info; + record.info.pNext = nullptr; + for (auto* next = static_cast(info.pNext); next != nullptr; next = next->pNext) { + if (next->sType == VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO) { + record.reduction = *reinterpret_cast(next); + record.hasReduction = true; + } + } + return record; +} + +VKAPI_ATTR VkResult VKAPI_CALL createImageView(VkDevice device, const VkImageViewCreateInfo* info, const VkAllocationCallbacks* allocator, VkImageView* view) { + const auto result = realCreateImageView.load(std::memory_order_acquire)(device, info, allocator, view); + if (result == VK_SUCCESS) { + auto record = recordOf(*info); + std::lock_guard lock(recordsMutex()); + views()[*view] = std::move(record); + } + return result; +} + +VKAPI_ATTR void VKAPI_CALL destroyImageView(VkDevice device, VkImageView view, const VkAllocationCallbacks* allocator) { + { + std::lock_guard lock(recordsMutex()); + views().erase(view); + } + realDestroyImageView.load(std::memory_order_acquire)(device, view, allocator); +} + +VKAPI_ATTR VkResult VKAPI_CALL createSampler(VkDevice device, const VkSamplerCreateInfo* info, const VkAllocationCallbacks* allocator, VkSampler* sampler) { + const auto result = realCreateSampler.load(std::memory_order_acquire)(device, info, allocator, sampler); + if (result == VK_SUCCESS) { + auto record = recordOf(*info); + std::lock_guard lock(recordsMutex()); + samplers()[*sampler] = std::move(record); + } + return result; +} + +VKAPI_ATTR void VKAPI_CALL destroySampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks* allocator) { + { + std::lock_guard lock(recordsMutex()); + samplers().erase(sampler); + } + realDestroySampler.load(std::memory_order_acquire)(device, sampler, allocator); +} + +template +bool resolve(std::atomic& real, VkDevice device, PFN_vkGetDeviceProcAddr deviceProc, const char* name) { + const auto function = reinterpret_cast(deviceProc(device, name)); + if (function == nullptr) return false; + real.store(function, std::memory_order_release); + return true; +} + +} + +const VkImageViewCreateInfo* ImageViewRecord::Chain() { + info.pNext = nullptr; + usage.pNext = nullptr; + minLod.pNext = nullptr; + if (hasMinLod) { + minLod.pNext = info.pNext; + info.pNext = &minLod; + } + if (hasUsage) { + usage.pNext = info.pNext; + info.pNext = &usage; + } + return &info; +} + +const VkSamplerCreateInfo* SamplerRecord::Chain() { + info.pNext = nullptr; + reduction.pNext = nullptr; + if (hasReduction) info.pNext = &reduction; + return &info; +} + +PFN_vkVoidFunction DescriptorHeapObjectFunction(VkDevice device, PFN_vkGetDeviceProcAddr deviceProc, const char* name) { + if (device == VK_NULL_HANDLE) return nullptr; + if (std::strcmp(name, "vkCreateImageView") == 0) { + if (!resolve(realCreateImageView, device, deviceProc, name)) return nullptr; + return reinterpret_cast(&createImageView); + } + if (std::strcmp(name, "vkDestroyImageView") == 0) { + if (!resolve(realDestroyImageView, device, deviceProc, name)) return nullptr; + return reinterpret_cast(&destroyImageView); + } + if (std::strcmp(name, "vkCreateSampler") == 0) { + if (!resolve(realCreateSampler, device, deviceProc, name)) return nullptr; + return reinterpret_cast(&createSampler); + } + if (std::strcmp(name, "vkDestroySampler") == 0) { + if (!resolve(realDestroySampler, device, deviceProc, name)) return nullptr; + return reinterpret_cast(&destroySampler); + } + return nullptr; +} + +std::optional FindImageView(VkImageView view) { + std::lock_guard lock(recordsMutex()); + const auto found = views().find(view); + if (found == views().end()) return std::nullopt; + return found->second; +} + +std::optional FindSampler(VkSampler sampler) { + std::lock_guard lock(recordsMutex()); + const auto found = samplers().find(sampler); + if (found == samplers().end()) return std::nullopt; + return found->second; +} + +} diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index a91fc9d2ffe3..552d002c92e7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1,3 +1,5 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetTransfer.hpp" @@ -847,8 +849,9 @@ bool ValidationKey(const Context& context, std::span shade add(shader.pushConstantOffset); add(program.pushConstants.size()); add(program.bdaAbiVersion); - add(program.vertexAttributes.size()); - for (const auto& attribute : program.vertexAttributes) { + const auto& attributes = DrawVertexAttributes(shader); + add(attributes.size()); + for (const auto& attribute : attributes) { add(attribute.location); add(attribute.components); add(attribute.fetchIndex); @@ -1004,11 +1007,11 @@ ResourceCache::Key DrawResourceKey(const Context& context, std::spandrawKeyMemo.words; - if (auto words = memo.load(std::memory_order_acquire); words != nullptr) { + if (auto words = memo.load(std::memory_order_acquire); words != nullptr && shader.heap == nullptr) { key.insert(key.end(), words->begin(), words->end()); } else { ShaderResources::AppendContentKey(shader, true, MovableBuffers(), key); - memo.store(std::make_shared>(key.begin() + static_cast(sizeAt + 1u), key.end()), std::memory_order_release); + if (shader.heap == nullptr) memo.store(std::make_shared>(key.begin() + static_cast(sizeAt + 1u), key.end()), std::memory_order_release); } key[sizeAt] = static_cast(key.size() - sizeAt - 1u); } @@ -1031,7 +1034,7 @@ void CheckBufferAliases(std::span shaders, const ColorTarg for (const auto& shader : shaders) { for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; - const auto& words = binding.guestDescriptor; + const auto& words = DrawGuestWords(shader, binding); for (std::size_t offset = 0; offset + 4 <= words.size(); offset += 4) { const ShaderRecompiler::ShaderBufferResource descriptor{{words[offset], words[offset + 1], words[offset + 2], words[offset + 3]}}; const auto address = descriptor.Base48(); @@ -1487,7 +1490,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P return inputs; } constexpr std::uint32_t ZeroFetchSlack = 0x10000u; - if (const auto zeroFrom = state.stages.mesh ? std::nullopt : ZeroFetchVertex(shaders.front().program->vertexAttributes)) { + if (const auto zeroFrom = state.stages.mesh ? std::nullopt : ZeroFetchVertex(DrawVertexAttributes(shaders.front()))) { const auto limit = *zeroFrom > draw.firstVertex ? *zeroFrom - draw.firstVertex : 0u; if (*highest >= limit && *highest - limit >= ZeroFetchSlack) { GuestMemory::FlushGpuWrites(draw.indexAddress, static_cast(indexBytes)); @@ -1521,7 +1524,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P } } APS5_LOG_CHARS_OUT_DEBUG("Index validation OK"); - const auto& attributes = shaders.front().program->vertexAttributes; + const auto& attributes = DrawVertexAttributes(shaders.front()); // Validates the vertex descriptors; the layout also keys and builds the pipeline. if (recipe != nullptr) { inputs.vertexInput = recipe->vertexInput; @@ -1688,7 +1691,12 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat if (resolved.cacheable) { resolved.contentKey = DrawResourceKey(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, indexBytes, !trimKey); if (auto cached = SharedResourceCache().Find(resolved.contentKey)) { - const bool valid = cached->Revalidate(shaders); + bool spaceHeld = !cached->SpaceReuse(); + if (!spaceHeld && cached->RetakeSpace()) { + spaceHeld = cached->SnapshotsServedInPlace(snapshots); + if (!spaceHeld) static_cast(cached->ReleaseSpace()); + } + const bool valid = spaceHeld && cached->Revalidate(shaders); auto* recorder = Recorder::Active(); std::optional> moved; if (valid && recorder != nullptr) moved = cached->MovedReadOnlyBuffers(shaders, *recorder); @@ -1696,11 +1704,15 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat if (trimKey) CheckBufferAliases(shaders, state.color, draw.indexAddress, indexBytes); resolved.resources = std::move(cached); resolved.moved = std::move(*moved); + if (resolved.resources->HeapStage()) resolved.resources->RefreshHeapStage(shaders); + outcome.addressBased = resolved.resources->HoldsLease(); outcome.kind = KindTemplateHit; countCache(&DrawProfile::cacheHits); } else if (valid) { + if (cached->SpaceReuse()) static_cast(cached->ReleaseSpace()); countCache(&DrawProfile::cacheMisses); } else { + if (cached->SpaceReuse()) static_cast(cached->ReleaseSpace()); SharedResourceCache().Remove(resolved.contentKey); countCache(&DrawProfile::cacheInvalidated); } @@ -1944,6 +1956,7 @@ void keepRecordedDraw(Recorder& recorder, const std::shared_ptr if (resources->HoldsLease()) CountLeaseOutcome(outcome.waited, outcome.waited ? 0 : recorder.Submissions() + 1); // Every use of a (possibly shared) resources object registers its GPU writes anew. resources->MarkGpuWrites(recorder); + if (resources->SpaceReuse()) recorder.Keep(std::const_pointer_cast(resources->ReleaseSpace())); // The write-back (fault check, copied buffers) runs when the batch completed; a fault is // reported by the recorder ("deferred write-back failed") instead of thrown out of the draw. if (listed && resources->HasCopiedWrites()) { @@ -2009,7 +2022,7 @@ void patchDepthRemapPush(std::array& block std::memcpy(block.data() + ShaderRecompiler::DepthRemapPushOffsetBytes, words.data(), sizeof(words)); } -void recordStencilReplay(const Context& context, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, std::span>> replay, std::span shaders, const ShaderResources& resources, const std::array* bytes = nullptr, VkShaderStageFlags stages = 0) { +void recordStencilReplay(const Context& context, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, std::span>> replay, std::span shaders, const ShaderResources& resources, const std::array* bytes = nullptr, VkShaderStageFlags stages = 0, const ShaderResources::DrawBindings* drawBindings = nullptr) { State selected = state; auto block = bytes != nullptr ? *bytes : AssemblePushConstants(shaders); if (bytes == nullptr) { @@ -2017,9 +2030,10 @@ void recordStencilReplay(const Context& context, VkCommandBuffer commands, const stages = PushConstantStages(shaders); } patchDepthRemapPush(block, state); + resources.PatchDataAddresses(block, shaders, drawBindings); const auto fragment = std::ranges::find_if(shaders, [](const CompiledShader& shader) { return shader.stage == ShaderRecompiler::ShaderStage::Fragment && !shader.program->stencilReferences.empty(); }); Require(fragment != shaders.end(), "stencil replay fragment stage is missing"); - const auto referenceOffset = fragment->pushConstantOffset + fragment->program->stencilReferenceDword * sizeof(std::uint32_t); + const auto referenceOffset = (fragment->program->dataAddressPush ? 0u : fragment->pushConstantOffset) + fragment->program->stencilReferenceDword * sizeof(std::uint32_t); Require(referenceOffset <= block.size() - sizeof(std::uint32_t), "stencil replay reference exceeds the push block"); const auto run = [&](const Pm4::DrawParameters& piece, std::uint32_t firstIndex) { std::uint32_t unusedSubdraw = 0; @@ -2049,13 +2063,14 @@ void recordStencilReplay(const Context& context, VkCommandBuffer commands, const } } -void pushDrawConstants(const Pipeline& pipeline, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, std::span shaders, const ShaderResources& resources, const std::array* bytes, VkShaderStageFlags stages, VkDeviceAddress meshArguments = 0, bool restartTable = false) { +void pushDrawConstants(const Pipeline& pipeline, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, std::span shaders, const ShaderResources& resources, const std::array* bytes, VkShaderStageFlags stages, VkDeviceAddress meshArguments = 0, bool restartTable = false, const ShaderResources::DrawBindings* drawBindings = nullptr) { auto block = bytes != nullptr ? *bytes : AssemblePushConstants(shaders); if (bytes == nullptr) { resources.PatchPushConstants(block); stages = PushConstantStages(shaders); } patchDepthRemapPush(block, state); + resources.PatchDataAddresses(block, shaders, drawBindings); if (state.stages.tessellation) { for (const auto& shader : shaders) Require(shader.program->pushConstants.empty() || shader.pushConstantOffset >= PipelinePushSlotBytes || shader.pushConstantOffset + shader.program->pushConstants.size() <= ShaderRecompiler::TessellationLevelPushOffsetBytes, "a stage's push constants overlap the tessellation levels"); const std::array levels{state.stages.minTessellationLevel, state.stages.maxTessellationLevel}; @@ -2311,21 +2326,26 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam record.pipeline->Begin(commands, *record.framebuffer, state.renderExtent, state); } APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); - if (drawBindings != nullptr) { + if (record.pipeline->DescriptorHeap()) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + NoteEmptyResourceSet(); + } else if (drawBindings != nullptr) { + Require(!resources.HeapStage(), "a GPU-mode draw needs a VK_EXT_descriptor_heap pipeline"); const auto set = drawBindings->allocation.set; const auto fragmentSet = drawBindings->fragmentAllocation.set; - if (set != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), 0, 1, &set, 0, nullptr); - if (fragmentSet != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet, 0, nullptr); + if (set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), 0, 1, &set); + if (fragmentSet != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet); } else { + Require(!resources.HeapStage(), "a GPU-mode draw needs a VK_EXT_descriptor_heap pipeline"); resources.Bind(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout()); } if (std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; })) BindPixelFunctionLds(context, commands, record.pipeline->Layout()); APS5_LOG_CHARS_OUT_DEBUG("Resources bound"); - pushDrawConstants(*record.pipeline, commands, state, draw, shaders, resources, record.pushBytes, record.pushStages, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty()); + pushDrawConstants(*record.pipeline, commands, state, draw, shaders, resources, record.pushBytes, record.pushStages, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty(), drawBindings.get()); APS5_LOG_CHARS_OUT_DEBUG("Push constants recorded"); if (record.stencilReplay.empty()) recordDrawCommands(context, commands, state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw); else { - recordStencilReplay(context, commands, state, draw, inputs, record.stencilReplay, shaders, resources, record.pushBytes, record.pushStages); + recordStencilReplay(context, commands, state, draw, inputs, record.stencilReplay, shaders, resources, record.pushBytes, record.pushStages, drawBindings.get()); for (const auto& [reference, pipeline] : record.stencilReplay) recorder->Keep(pipeline); } if (record.pipeline->SplitsFaces()) { @@ -2509,6 +2529,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara } if (state.quadList || StripPatches(state, shaders)) recipeOut = nullptr; if (context.recorder != nullptr) context.recorder->BoundKeptBytes(); + if (std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->gpuResolvedImages; })) recipeOut = nullptr; auto& timing = prepared.timing.emplace("Graphics.Draw"); // APS5_PROFILE_DRAW prints the time of each phase of the draw (microseconds) and the [draws] totals. static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; @@ -2661,8 +2682,9 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara for (const auto& shader : shaders) { for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages && binding.role != ShaderRecompiler::DescriptorRole::ImageTable) continue; - for (std::size_t offset = 0; offset + 8u <= binding.guestDescriptor.size(); offset += 8u) { - const auto words = std::span(binding.guestDescriptor).subspan(offset, 8u); + const auto& guestWords = DrawGuestWords(shader, binding); + for (std::size_t offset = 0; offset + 8u <= guestWords.size(); offset += 8u) { + const auto words = std::span(guestWords).subspan(offset, 8u); if (words[0] == 0u && (words[1] & 0xffu) == 0u) continue; const auto texture = DecodeTextureResource(words); Require(!DepthSurfaceAt(context, words, texture), "stencil replay refuses sampled depth-surface feedback"); @@ -3052,7 +3074,10 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D APS5_LOG_OUT_DEBUG("Beginning pipeline renderExtent=%ux%u", state.renderExtent.width, state.renderExtent.height); pipeline->Begin(commands, *framebuffer, state.renderExtent, state); APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); - resources->Bind(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->Layout()); + if (pipeline->DescriptorHeap()) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + NoteEmptyResourceSet(); + } else resources->Bind(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->Layout()); if (pixelLdsSubgroup != 0u) BindPixelFunctionLds(context, commands, pipeline->Layout()); APS5_LOG_CHARS_OUT_DEBUG("Resources bound"); pushDrawConstants(*pipeline, commands, state, draw, shaders, *resources, nullptr, 0, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty()); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp index 9881ba24732f..920370bf89d6 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/ColorTransfer_spv.h" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -147,7 +148,7 @@ void GpuColorTransfer::dispatch(VkCommandBuffer commands, bool toTiled, bool swa barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr); const std::array push{width, height, (width + 127u) / 128u, (toTiled ? 1u : 0u) | (swapRedBlue ? 2u : 0u) | (tiledSource ? 4u : 0u) | (tenBit ? 8u : 0u) | (halfFloat ? 16u : 0u) | (pqWhiteNits ? 32u : 0u), std::bit_cast(pqWhiteNits.value_or(0.0f))}; context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &descriptorSet, 0, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &descriptorSet); context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); context.Function("vkCmdDispatch")(commands, (width + 7u) / 8u, (height + 7u) / 8u, 1); VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 12939ea058b4..365107c5160f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -1,6 +1,8 @@ #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" #include "ThreadOwned.hpp" #include "prx/libSceAgcDriver/Graphics/include/SnapshotCopies.hpp" @@ -37,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -119,6 +122,8 @@ struct GuestBufferMemory::AddressSpace { std::vector heapRuns; std::vector sparseMirrors; std::unique_ptr[]> verified; + mutable std::atomic refreshedEpoch{0}; + mutable std::atomic refreshedProof{0}; std::vector copied; // The BDA table entries of `base`, in its order. std::vector ranges; @@ -942,6 +947,7 @@ const char* settleImport(const Context& context, HostImports& state, const HostI if ((result = context.Function("vkResetCommandBuffer")(settle.settleCommands, 0)) != VK_SUCCESS) return "vkResetCommandBuffer (settle)"; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + NoteCommandBufferBegun(settle.settleCommands); if ((result = context.Function("vkBeginCommandBuffer")(settle.settleCommands, &begin)) != VK_SUCCESS) return "vkBeginCommandBuffer (settle)"; const VkBufferCopy region{0, 0, 4}; context.Function("vkCmdCopyBuffer")(settle.settleCommands, source, settle.settleTarget, 1, ®ion); @@ -1036,6 +1042,7 @@ void submitSettleBatch(const Context& context, HostImports& state) { if ((result = context.Function("vkResetCommandBuffer")(batch.commands, 0)) != VK_SUCCESS) return fail("vkResetCommandBuffer (settle batch)"); VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + NoteCommandBufferBegun(batch.commands); if ((result = context.Function("vkBeginCommandBuffer")(batch.commands, &begin)) != VK_SUCCESS) return fail("vkBeginCommandBuffer (settle batch)"); const auto copy = context.Resolved(&DeviceFunctions::cmdCopyBuffer, "vkCmdCopyBuffer"); RecordMemoryBarrier(context, batch.commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); @@ -3383,11 +3390,13 @@ void runImportProbe(const Context& context, std::uint64_t base, std::uint64_t by allocate.commandBufferCount = 2; if ((probe.result = context.Function("vkAllocateCommandBuffers")(context.device, &allocate, commands)) != VK_SUCCESS) return "vkAllocateCommandBuffers"; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + NoteCommandBufferBegun(commands[0]); if ((probe.result = context.Function("vkBeginCommandBuffer")(commands[0], &begin)) != VK_SUCCESS) return "vkBeginCommandBuffer"; const VkBufferCopy region{0, 0, bytes}; context.Function("vkCmdCopyBuffer")(commands[0], import.buffer, destination, 1, ®ion); if ((probe.result = context.Function("vkEndCommandBuffer")(commands[0])) != VK_SUCCESS) return "vkEndCommandBuffer"; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + NoteCommandBufferBegun(commands[1]); if ((probe.result = context.Function("vkBeginCommandBuffer")(commands[1], &begin)) != VK_SUCCESS) return "vkBeginCommandBuffer"; context.Function("vkCmdFillBuffer")(commands[1], import.buffer, 0, bytes, 0x02020202u); if ((probe.result = context.Function("vkEndCommandBuffer")(commands[1])) != VK_SUCCESS) return "vkEndCommandBuffer"; @@ -4319,6 +4328,111 @@ void GuestBufferMemory::AddReadable(std::uint64_t address, std::size_t bytes) { addDescriptorRegion(address, bytes, false, false, true); } +bool GuestBufferMemory::SpaceOnly() const { + return space != nullptr && lease.empty() && regions.empty() && space->sparseMirrors.empty() && space->copied.empty(); +} + +std::shared_ptr GuestBufferMemory::ReleaseSpace() { + releasedSpace = space; + return std::move(space); +} + +namespace { + +bool epochMirrors() { + return DrawPipelineEnabled(); +} + +void noteEpochMirrors(bool reused, const GuestBufferMemory::AddressSpace& space) { + static std::atomic reuses{0}, refreshes{0}, compared{0}, differing{0}; + static const bool verify = std::getenv("APS5_VERIFY_DRAW_PIPELINE") != nullptr; + if (reused && verify && reuses.load(std::memory_order_relaxed) % 64u == 0u) { + for (const auto index : space.writableMirrors) { + const auto& region = space.base[index]; + const auto& mirror = *region.mirror; + if (!mirror.writable || mirror.heap || mirror.shadow.empty()) continue; + constexpr std::uint64_t block = 65536; + for (auto at = region.begin; at < region.end;) { + const auto next = std::min(region.end, (at / block + 1) * block); + const auto offset = static_cast(at - mirror.base); + compared.fetch_add(1, std::memory_order_relaxed); + if (std::memcmp(mirror.shadow.data() + offset, reinterpret_cast(at), static_cast(next - at)) != 0) differing.fetch_add(1, std::memory_order_relaxed); + at = next; + } + } + } + const auto count = (reused ? reuses : refreshes).fetch_add(1, std::memory_order_relaxed) + 1u; + static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; + if (!verify && !profile) return; + if (count % 65536u == 0u || (count & (count - 1u)) == 0u) std::fprintf(stderr, "[epoch-mirrors] address space uses: %llu reused the epoch's refresh, %llu refreshed; verify: %llu blocks compared, %llu differ\n", static_cast(reuses.load()), static_cast(refreshes.load()), static_cast(compared.load()), static_cast(differing.load())); +} + +} + +bool GuestBufferMemory::RetakeSpace() { + if (space != nullptr) return true; + auto kept = releasedSpace.lock(); + if (kept == nullptr) return false; + auto& spaces = Spaces(); + auto current = spaces.current.load(); + if (current != kept) return false; + const auto generation = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); + { + auto& state = Imports(); + std::lock_guard lock(state.mutex); + if (current->device != context.device || current->generation != generation || current->importsEpoch != state.epoch) return false; + importFloor = state.useCounter + 1; + const auto stamp = ++state.useCounter; + for (const auto& region : current->base) { + if (region.direct != nullptr) region.direct->lastUse = stamp; + } + } + spaces.hits.fetch_add(1, std::memory_order_relaxed); + space = std::move(current); + std::vector blocks; + const auto epoch = GuestMemory::CollectEpoch(); + const auto proof = GuestMemory::ProofSerial(); + const bool reuse = epochMirrors() && epoch != 0 && space->refreshedEpoch.load(std::memory_order_relaxed) == epoch && space->refreshedProof.load(std::memory_order_relaxed) == proof; + if (reuse) { + noteEpochMirrors(true, *space); + } else { + for (const auto index : space->writableMirrors) { + const auto& region = space->base[index]; + if (prepareRefresh(*region.mirror, region.begin, region.end - region.begin)) appendBlocks(blocks, *region.mirror, region.begin, region.end - region.begin); + } + if (epochMirrors()) noteEpochMirrors(false, *space); + } + const auto checked = refreshHeapRuns(*space, blocks); + compareBlocks(blocks); + for (const auto& [run, collected] : checked) space->verified[run].store(collected, std::memory_order_relaxed); + if (!reuse && epoch != 0) { + space->refreshedEpoch.store(epoch, std::memory_order_relaxed); + space->refreshedProof.store(proof, std::memory_order_relaxed); + } + { + auto& state = Imports(); + std::lock_guard lock(state.mutex); + if (space->importsEpoch != state.epoch) { + releasedSpace = space; + space.reset(); + return false; + } + } + return true; +} + +bool GuestBufferMemory::SnapshotsServedInPlace(std::span snapshots) const { + if (space == nullptr) return false; + for (const auto& snapshot : snapshots) { + const Region* owner = nullptr; + if (baseOverlap(snapshot.address, snapshot.address + snapshot.bytes.size(), &owner) != BaseOverlap::Inside || owner == nullptr) return false; + if (!(owner->writable || owner->hostBacked || owner->mirror != nullptr)) return false; + if (AnyShadowedOverlaps(snapshot.address, snapshot.bytes.size())) return false; + if (std::memcmp(reinterpret_cast(snapshot.address), snapshot.bytes.data(), snapshot.bytes.size()) != 0) return false; + } + return true; +} + void GuestBufferMemory::AddSnapshot(const GuestMemorySnapshot& snapshot) { validate(snapshot.address, snapshot.bytes.size()); const auto end = snapshot.address + snapshot.bytes.size(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index fcad4ff7bfc1..fa6f4bf2cf7c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -3,6 +3,7 @@ #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp" #include "prx/libSceAgcDriver/Graphics/include/PipelineJournal.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" @@ -333,12 +334,23 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& appendKey(key, shader.pushConstantOffset); if (resources.split) { auto& sets = shader.stage == Stage::Fragment ? keys.fragmentSets : keys.preRasterizationSets; - for (const auto& binding : shader.program->bindings) { - Require(binding.descriptorSet < 2u, "split pipeline library descriptor set exceeds two slots"); - sets |= 1u << binding.descriptorSet; + if (shader.program->gpuResolvedImages) { + sets |= 2u; + for (const auto& binding : shader.program->bindings) { + if (binding.descriptorSet == 0u) sets |= 1u; + } + } else { + for (const auto& binding : shader.program->bindings) { + Require(binding.descriptorSet < 2u, "split pipeline library descriptor set exceeds two slots"); + sets |= 1u << binding.descriptorSet; + } } } } + if (resources.split && std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program->gpuResolvedImages; })) { + keys.preRasterizationSets |= 2u; + keys.fragmentSets |= 2u; + } if (resources.split) { const auto unused = 3u & ~(keys.preRasterizationSets | keys.fragmentSets); keys.preRasterizationSets |= unused & 1u; @@ -427,6 +439,7 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& appendKey(key, resources.fragmentKey.size()); for (const auto word : resources.fragmentKey) appendKey(key, word); } + if ((sets & 4u) != 0u) appendKey(key, 0x44415441u); }; splitKey(keys.layout, 3u); splitKey(keys.preRasterizationLayout, keys.preRasterizationSets); @@ -491,6 +504,18 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput std::vector stages(shaders.size()); std::vector specializations; specializations.reserve(shaders.size()); + std::vector> heapMappings(shaders.size()); + std::vector heapMappingInfos(shaders.size(), VkShaderDescriptorSetAndBindingMappingInfoEXT{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}); + if (context.descriptorHeap && DescriptorHeapEnabled() && std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program->gpuResolvedImages; })) { + auto& heap = BindlessHeap::For(context); + const bool rooted = std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program->dataAddressPush; }); + descriptorHeap = std::all_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { + const auto index = static_cast(&shader - shaders.data()); + const bool generatedFault = !shader.program->gpuResolvedImages && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const auto& binding) { return binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer; }); + return heap.DescriptorHeapMappings(std::span(shader.program->spirv.data(), shader.program->spirv.size()), heapMappings[index], ~0u, shader.program->dataAddressPush, generatedFault && rooted); + }); + } + Require(descriptorHeap || std::none_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program->gpuResolvedImages; }), "a pipeline with GPU-mode stages does not map onto VK_EXT_descriptor_heap"); const VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT meshSubgroup{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO_EXT, nullptr, 32u}; for (std::uint32_t i = 0; i < shaders.size(); ++i) { const auto& shader = *shaders[i].program; @@ -501,13 +526,19 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput stages[i].module = _modules[i]; stages[i].pName = "main"; if (shaders[i].stage == ShaderRecompiler::ShaderStage::Mesh && context.meshWave32 && shader.hostSubgroupSize == 32u) stages[i].pNext = &meshSubgroup; + if (descriptorHeap) { + heapMappingInfos[i].mappingCount = static_cast(heapMappings[i].size()); + heapMappingInfos[i].pMappings = heapMappings[i].data(); + heapMappingInfos[i].pNext = stages[i].pNext; + stages[i].pNext = &heapMappingInfos[i]; + } specializations.emplace_back(shader); stages[i].pSpecializationInfo = specializations.back().Info(); } if (std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && !shader.program->stencilReferences.empty(); })) { for (std::size_t i = 0; i < shaders.size(); ++i) { if (shaders[i].stage != ShaderRecompiler::ShaderStage::Vertex) continue; - Require(stages[i].flags == 0u && stages[i].pNext == nullptr, "stencil replay vertex stage allows varying subgroup size"); + Require(stages[i].flags == 0u && (stages[i].pNext == nullptr || stages[i].pNext == &heapMappingInfos[i]), "stencil replay vertex stage allows varying subgroup size"); } } // A descriptor set layout with the same bindings as this one is compatible with the pipeline @@ -518,12 +549,12 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput const VkPushConstantRange push{pushStages, 0, PipelinePushSlotBytes}; const std::array slots{{{pushStagesOf(context), 0, PipelinePushSlotBytes}, {VK_SHADER_STAGE_FRAGMENT_BIT, PipelinePushSlotBytes, PipelinePushSlotBytes}}}; VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layoutInfo.flags = pixelLds || !resources.split ? 0 : VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT; + layoutInfo.flags = !pixelLds && resources.split && context.graphicsPipelineLibrary ? VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT : 0; layoutInfo.setLayoutCount = pixelLds ? 3u : resources.split ? 2u : 1u; layoutInfo.pSetLayouts = setLayouts.data(); layoutInfo.pushConstantRangeCount = dynamicRendering ? static_cast(slots.size()) : pushStages != 0 ? 1 : 0; layoutInfo.pPushConstantRanges = dynamicRendering ? slots.data() : pushStages != 0 ? &push : nullptr; - Check(context.Function("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &layout), "vkCreatePipelineLayout graphics"); + if (!descriptorHeap) Check(context.Function("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &layout), "vkCreatePipelineLayout graphics"); std::vector colors; std::vector references(state.blends.size(), VkAttachmentReference{VK_ATTACHMENT_UNUSED, attachmentLayout}); for (std::uint32_t index = 0; index < state.colors.size(); ++index) { @@ -710,6 +741,14 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput pipelineInfo.layout = layout; pipelineInfo.renderPass = renderPass; if (dynamicRendering) pipelineInfo.pNext = &rendering; + VkPipelineCreateFlags2CreateInfoKHR heapFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR}; + if (descriptorHeap) { + heapFlags.flags = static_cast(pipelineInfo.flags) | VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT; + heapFlags.pNext = pipelineInfo.pNext; + pipelineInfo.pNext = &heapFlags; + pipelineInfo.flags = 0; + pipelineInfo.layout = VK_NULL_HANDLE; + } timing.Mark("modules_and_state"); if (prebuilding && !libraries) { for (const auto module : _modules) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); @@ -958,6 +997,11 @@ void Pipeline::ContinueBackFaces(VkCommandBuffer commands, const State& state) c void Pipeline::PushConstants(VkCommandBuffer commands, VkShaderStageFlags stages, std::span bytes) const { if (stages == 0) return; + if (descriptorHeap) { + const VkPushDataInfoEXT push{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {bytes.data(), bytes.size()}}; + context.Function("vkCmdPushDataEXT")(commands, &push); + return; + } if (dynamicRendering) { context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, pushStagesOf(context), 0, PipelinePushSlotBytes, bytes.data()); context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, VK_SHADER_STAGE_FRAGMENT_BIT, PipelinePushSlotBytes, PipelinePushSlotBytes, bytes.data() + PipelinePushSlotBytes); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineLibrary.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineLibrary.cpp index 77119254d59e..13c5b20f7c32 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineLibrary.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineLibrary.cpp @@ -112,10 +112,17 @@ std::span PipelineLibraryDynamicStates() { return dynamicStates; } +bool DescriptorHeapPipelineInfo(const VkGraphicsPipelineCreateInfo& info) { + for (auto* next = static_cast(info.pNext); next != nullptr; next = next->pNext) { + if (next->sType == VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR) return (reinterpret_cast(next)->flags & VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT) != 0; + } + return false; +} + VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPipelineCreateInfo& info, const VkPipelineRenderingCreateInfoKHR& rendering, const VkPipelineLayoutCreateInfo& layout, const PipelineLibraryKeys& keys, std::shared_ptr* optimized, bool partsOnly, std::span modules) { Require(info.renderPass == VK_NULL_HANDLE && info.pDynamicState != nullptr, "pipeline library parts need dynamic rendering and the library dynamic states"); const bool split = (layout.flags & VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT) != 0; - Require(!split || (layout.setLayoutCount == 2u && layout.pSetLayouts != nullptr && ((keys.preRasterizationSets | keys.fragmentSets) & ~3u) == 0u), "split pipeline library layout requires two descriptor set slots and a valid mask"); + Require(!split || ((layout.setLayoutCount == 2u || layout.setLayoutCount == 3u) && layout.pSetLayouts != nullptr && ((keys.preRasterizationSets | keys.fragmentSets) & ~((1u << layout.setLayoutCount) - 1u)) == 0u), "split pipeline library layout requires two or three descriptor set slots and a valid mask"); auto& store = Libraries(); std::unique_lock lock(store.mutex); ++store.activeBuilds[context.device]; @@ -138,9 +145,9 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip auto found = device.layouts.find(key); if (found != device.layouts.end()) return found->second; auto info = layout; - std::array sets{VK_NULL_HANDLE, VK_NULL_HANDLE}; + std::array sets{VK_NULL_HANDLE, VK_NULL_HANDLE, VK_NULL_HANDLE}; if (mask.has_value()) { - for (std::uint32_t set = 0; set < sets.size(); ++set) { + for (std::uint32_t set = 0; set < layout.setLayoutCount; ++set) { if ((*mask & (1u << set)) != 0u) sets[set] = layout.pSetLayouts[set]; } info.pSetLayouts = sets.data(); @@ -149,8 +156,11 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip Check(context.Function("vkCreatePipelineLayout")(context.device, &info, nullptr, &handle), "vkCreatePipelineLayout library"); return device.layouts.emplace(key, handle).first->second; }; - const auto fullLayout = layoutFor(keys.layout, std::nullopt); - const std::array partLayouts{VK_NULL_HANDLE, split ? layoutFor(keys.preRasterizationLayout, keys.preRasterizationSets) : fullLayout, split ? layoutFor(keys.fragmentLayout, keys.fragmentSets) : fullLayout, VK_NULL_HANDLE}; + const bool descriptorHeap = DescriptorHeapPipelineInfo(info); + const std::array memoryMarker{std::byte{descriptorHeap ? std::uint8_t{2} : std::uint8_t{0}}}; + const Key memoryKey(memoryMarker.begin(), memoryMarker.end()); + const auto fullLayout = descriptorHeap ? VkPipelineLayout{VK_NULL_HANDLE} : layoutFor(Combined(keys.layout, memoryKey), std::nullopt); + const std::array partLayouts{VK_NULL_HANDLE, split && !descriptorHeap ? layoutFor(Combined(keys.preRasterizationLayout, memoryKey), keys.preRasterizationSets) : fullLayout, split && !descriptorHeap ? layoutFor(Combined(keys.fragmentLayout, memoryKey), keys.fragmentSets) : fullLayout, VK_NULL_HANDLE}; std::vector preRasterization; const VkPipelineShaderStageCreateInfo* fragment = nullptr; bool mesh = false; @@ -167,7 +177,8 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_SHADER_BIT_EXT, VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_OUTPUT_INTERFACE_BIT_EXT, }; - const std::array partKeys{&keys.vertexInput, &keys.preRasterization, &keys.fragmentShader, &keys.fragmentOutput}; + std::array markedParts{Combined(keys.vertexInput, memoryKey), Combined(keys.preRasterization, memoryKey), Combined(keys.fragmentShader, memoryKey), Combined(keys.fragmentOutput, memoryKey)}; + const std::array partKeys{&markedParts[0], &markedParts[1], &markedParts[2], &markedParts[3]}; const Key none; VkPipelineRenderingCreateInfoKHR shaderRendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR}; shaderRendering.viewMask = rendering.viewMask; @@ -196,6 +207,7 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip library.flags = flags[part]; VkGraphicsPipelineCreateInfo create{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &library}; create.flags = VK_PIPELINE_CREATE_LIBRARY_BIT_KHR | VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT; + VkPipelineCreateFlags2CreateInfoKHR partFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR, &library, static_cast(VK_PIPELINE_CREATE_LIBRARY_BIT_KHR | VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT) | VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT}; create.pDynamicState = info.pDynamicState; create.layout = partLayouts[part]; switch (flags[part]) { @@ -223,6 +235,11 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip create.layout = VK_NULL_HANDLE; break; } + if (descriptorHeap) { + create.pNext = &partFlags; + create.flags = 0; + create.layout = VK_NULL_HANDLE; + } VkPipeline handle = VK_NULL_HANDLE; // Built without the store's mutex: a draw whose parts are resident is not held behind // another thread's build, and builds from several threads (the registration prebuild, the @@ -269,11 +286,18 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip linked.libraryCount = static_cast(libraries.size()); linked.pLibraries = libraries.data(); VkGraphicsPipelineCreateInfo create{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &linked}; + create.flags = 0; + create.layout = info.layout; + VkPipelineCreateFlags2CreateInfoKHR linkFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR, &linked, VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT}; + if (descriptorHeap) { + create.pNext = &linkFlags; + create.flags = 0; + create.layout = VK_NULL_HANDLE; + } if (sampleCounts) { linkedSamples.pNext = create.pNext; create.pNext = &linkedSamples; } - create.layout = info.layout; VkPipeline pipeline = VK_NULL_HANDLE; lock.unlock(); { @@ -290,20 +314,25 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip const auto createPipelines = context.Function("vkCreateGraphicsPipelines"); const auto cache = context.pipelineCache; const auto cacheSynchronization = context.pipelineCacheSynchronization; - const auto libraryLayout = fullLayout; - std::function relink = [slot, createPipelines, cache, cacheSynchronization, libraryLayout, libraries, sampleCounts, attachmentSamples, &store, devicePointer = &device] { + const auto libraryLayout = descriptorHeap ? VkPipelineLayout{VK_NULL_HANDLE} : fullLayout; + std::function relink = [slot, createPipelines, cache, cacheSynchronization, libraryLayout, libraries, sampleCounts, attachmentSamples, &store, devicePointer = &device, descriptorHeap] { if (slot->released.load()) return; auto linkedSamples = sampleCounts ? attachmentSamples(*sampleCounts) : VkAttachmentSampleCountInfoNV{}; VkPipelineLibraryCreateInfoKHR linked{VK_STRUCTURE_TYPE_PIPELINE_LIBRARY_CREATE_INFO_KHR}; linked.libraryCount = static_cast(libraries.size()); linked.pLibraries = libraries.data(); VkGraphicsPipelineCreateInfo create{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &linked}; + create.flags = VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT; + create.layout = libraryLayout; + VkPipelineCreateFlags2CreateInfoKHR relinkFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR, &linked, static_cast(VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT) | VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT}; + if (descriptorHeap) { + create.pNext = &relinkFlags; + create.flags = 0; + } if (sampleCounts) { linkedSamples.pNext = create.pNext; create.pNext = &linkedSamples; } - create.flags = VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT; - create.layout = libraryLayout; VkPipeline result = VK_NULL_HANDLE; const auto pipelineCreationResult = [&] { auto pipelineCacheLock = cacheSynchronization != nullptr ? cacheSynchronization->LockForPipelineUse() : PipelineCacheSynchronization::PipelineUseLock{}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 80eb8c355d14..c75c62e7e686 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -5,9 +5,11 @@ #include "prx/libc/include/HostThreadLocal.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libkernel/Time/include/SleepWake.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/ParallelCompare.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libSceAgcDriver/Graphics/include/UnitShadow.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/MeshArguments_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/SampleCounter_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/SampleDumps_spv.h" @@ -665,6 +667,22 @@ bool SnapshotOverlaps(std::uint64_t address, std::size_t bytes) { return SnapshotOverlaps(snapshot.get(), address, bytes); } +} + +bool Recorder::ReadsSettled(std::span> ranges, const WriteRanges* before) { + if (!HookSnapshotEnabled()) return false; + const bool labels = !QueuedLabelRanges().empty(); + const auto now = pendingWrites.load(std::memory_order_acquire); + for (const auto& [begin, end] : ranges) { + const auto bytes = static_cast(end - begin); + if (labels && QueuedLabelOverlaps(begin, bytes)) return false; + if (AgcDriver::Graphics::SnapshotOverlaps(before, begin, bytes) || AgcDriver::Graphics::SnapshotOverlaps(now.get(), begin, bytes)) return false; + } + return !StorageTexture::AnyPendingOverlaps(ranges) && !AnyShadowedOverlaps(ranges); +} + +namespace { + // Whether one merged range of the snapshot contains [address, end) entirely. bool SnapshotCovers(const WriteRanges* snapshot, std::uint64_t address, std::uint64_t end) { if (snapshot == nullptr || snapshot->empty()) return false; @@ -1590,6 +1608,7 @@ void Recorder::ensureOpen() { } VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + NoteCommandBufferBegun(batch->commands); Check(function(beginCommandBuffer, "vkBeginCommandBuffer")(batch->commands, &begin), "vkBeginCommandBuffer recorder"); } catch (...) { release(*batch); @@ -3632,6 +3651,7 @@ void Recorder::Submit() { VkSubmitInfo submission{VK_STRUCTURE_TYPE_SUBMIT_INFO}; submission.commandBufferCount = 1; submission.pCommandBuffers = &batch->commands; + if (auto* heap = DescriptorHeapEnabled() ? BindlessHeap::Existing(context) : nullptr; heap != nullptr) heap->Submitted(*this, submissions + 1); // The timeline reaches this batch's serial when it completes (see WaitSerial). const std::uint64_t serial = submissions + 1; std::string tokensStr = "["; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp index 4f30207defe0..b43442fdc207 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp @@ -1,9 +1,11 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include +#include #include namespace AgcDriver::Graphics { @@ -39,7 +41,8 @@ VkBuffer BindExactBuffer(const Context& context, std::size_t size, VkBufferUsage Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties) : context(context), size(size), capacity(BufferPool::Capacity(size, properties)), usage(BufferPool::Usage(usage, properties)), properties(properties) { Require(size != 0, "zero-sized GPU buffer"); - const bool addressable = (usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0; + if (!context.bufferDeviceAddress && (usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) == 0) this->usage &= ~static_cast(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); + const bool addressable = (this->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0; Require(!addressable || context.bufferDeviceAddress, "buffer device address is not enabled"); cache = GetBufferPool(context); if (const auto allocation = cache->Take(size, this->usage, properties)) { @@ -57,7 +60,7 @@ Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usag deviceAddress = 0; try { buffer = BindExactBuffer(context, size, this->usage, memory, offset, allocationBytes); - initializeAddress(usage); + initializeAddress(this->usage); } catch (...) { release(); throw; @@ -90,14 +93,14 @@ Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usag slab = true; allocationBytes = capacity; Check(context.Function("vkBindBufferMemory")(context.device, buffer, memory, offset), "vkBindBufferMemory slab"); - initializeAddress(usage); + initializeAddress(this->usage); mapping = slot.mapping; ready = true; return; } memory = cache->AllocateMemory(allocation, "vkAllocateMemory buffer"); Check(context.Function("vkBindBufferMemory")(context.device, buffer, memory, 0), "vkBindBufferMemory"); - initializeAddress(usage); + initializeAddress(this->usage); if ((properties & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) Check(context.Function("vkMapMemory")(context.device, memory, 0, VK_WHOLE_SIZE, 0, &mapping), "vkMapMemory"); ready = true; } catch (...) { @@ -145,6 +148,7 @@ void Buffer::Invalidate() { DeviceBuffer::DeviceBuffer(const Context& context, std::size_t size, VkBufferUsageFlags usage) : context(context), size(size), capacity(BufferPool::Capacity(size, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)), usage(BufferPool::Usage(usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { Require(size != 0, "zero-sized device buffer"); + if (!context.bufferDeviceAddress && (usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) == 0) this->usage &= ~static_cast(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); cache = GetBufferPool(context); if (const auto allocation = cache->Take(size, this->usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { buffer = allocation->buffer; @@ -178,6 +182,8 @@ DeviceBuffer::DeviceBuffer(const Context& context, std::size_t size, VkBufferUsa allocation.allocationSize = ClassAllocationBytes(requirements, capacity); allocationBytes = allocation.allocationSize; allocation.memoryTypeIndex = context.DeviceMemoryType(requirements.memoryTypeBits, allocation.allocationSize, "device buffer"); + const VkMemoryAllocateFlagsInfo addressFlags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, nullptr, VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, 0}; + if ((this->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0) allocation.pNext = &addressFlags; const auto deviceType = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); std::uint32_t allocatedType = allocation.memoryTypeIndex; memory = cache->AllocateMemory(allocation, "vkAllocateMemory device buffer", context.RefusedDeviceMemoryFallback(requirements.memoryTypeBits, allocation.memoryTypeIndex), &allocatedType); @@ -341,6 +347,7 @@ CommandBatch::CommandBatch(const Context& context) : context(context) { fence = created; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + NoteCommandBufferBegun(commands); Check(context.Function("vkBeginCommandBuffer")(commands, &begin), "vkBeginCommandBuffer"); // Work recorded so far goes first in queue order, so this batch sees its results. if (auto* recorder = Recorder::Active(); recorder != nullptr && recorder->Recording()) recorder->Submit(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp index d7b1fb0056f7..3b0160e00544 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp @@ -92,6 +92,7 @@ namespace AgcDriver::Graphics { auto resource = DecodeSamplerResource(words, unnormalizedProven, forceDegammaPaired, integerBorder); resource.compareEnable = compareEnable; auto sampler = std::make_shared(context, resource); + sampler->SetCacheKey(key); // The cap keeps live samplers well below the device's limit (NVIDIA: ~4000); a set in flight // still holds the evicted sampler through its own shared_ptr. while (entries.size() >= capacity) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp index 5bfb9d604eb1..5946c28cc79d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp @@ -1,123 +1,11 @@ #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" -#include #include #include #include -#include -#include -#include #include namespace AgcDriver::Graphics { -namespace { - -std::uint32_t pointerOperandStored(std::uint32_t opcode, std::span instruction) { - switch (static_cast(opcode)) { - case spv::OpStore: - case spv::OpCopyMemory: - case spv::OpCopyMemorySized: - case spv::OpAtomicStore: - case spv::OpAtomicFlagClear: - case spv::OpCooperativeMatrixStoreKHR: - case spv::OpCooperativeMatrixStoreNV: - case spv::OpCooperativeMatrixStoreTensorNV: - return instruction.size() > 1 ? instruction[1] : 0u; - case spv::OpAtomicExchange: - case spv::OpAtomicCompareExchange: - case spv::OpAtomicCompareExchangeWeak: - case spv::OpAtomicIIncrement: - case spv::OpAtomicIDecrement: - case spv::OpAtomicIAdd: - case spv::OpAtomicISub: - case spv::OpAtomicSMin: - case spv::OpAtomicUMin: - case spv::OpAtomicSMax: - case spv::OpAtomicUMax: - case spv::OpAtomicAnd: - case spv::OpAtomicOr: - case spv::OpAtomicXor: - case spv::OpAtomicFlagTestAndSet: - case spv::OpAtomicFMinEXT: - case spv::OpAtomicFMaxEXT: - case spv::OpAtomicFAddEXT: - return instruction.size() > 3 ? instruction[3] : 0u; - default: - return 0u; - } -} - -bool definesNoPointerValue(std::uint32_t opcode) { - switch (static_cast(opcode)) { - case spv::OpTypePointer: - case spv::OpTypeUntypedPointerKHR: - case spv::OpTypeForwardPointer: - case spv::OpName: - case spv::OpMemberName: - case spv::OpDecorate: - case spv::OpMemberDecorate: - case spv::OpDecorateId: - case spv::OpDecorateString: - case spv::OpMemberDecorateString: - return true; - default: - return false; - } -} - -template -bool forEachInstruction(std::span words, const TVisit& visit) { - for (std::size_t at = 5; at < words.size();) { - const auto count = words[at] >> 16u; - if (count == 0 || at + count > words.size()) return false; - visit(words[at] & 0xffffu, words.subspan(at, count)); - at += count; - } - return true; -} - -bool storesThroughAddressesCached(const ShaderRecompiler::SharedSpirv& spirv) { - static std::mutex mutex; - static std::map, bool> known; - const auto hash = spirv.ContentHash(); - const std::pair key{hash.low, hash.high}; - { - std::lock_guard lock(mutex); - if (const auto found = known.find(key); found != known.end()) return found->second; - } - const bool stores = SpirvStoresThroughAddresses(spirv.Words()); - std::lock_guard lock(mutex); - known.emplace(key, stores); - return stores; -} - -} - -bool ShaderStoresThroughAddresses(const ShaderRecompiler::SharedSpirv& spirv) { - return storesThroughAddressesCached(spirv); -} - -bool SpirvStoresThroughAddresses(std::span words) { - if (words.size() < 5 || words[0] != spv::MagicNumber) return true; - std::unordered_set pointerTypes; - const bool readable = forEachInstruction(words, [&](std::uint32_t opcode, std::span instruction) { - if ((opcode == spv::OpTypePointer || opcode == spv::OpTypeUntypedPointerKHR) && instruction.size() > 2 && instruction[2] == spv::StorageClassPhysicalStorageBuffer) pointerTypes.insert(instruction[1]); - }); - if (!readable) return true; - if (pointerTypes.empty()) return false; - std::unordered_set pointers; - forEachInstruction(words, [&](std::uint32_t opcode, std::span instruction) { - if (instruction.size() > 2 && !definesNoPointerValue(opcode) && pointerTypes.contains(instruction[1])) pointers.insert(instruction[2]); - }); - bool stores = false; - forEachInstruction(words, [&](std::uint32_t opcode, std::span instruction) { - const auto pointer = pointerOperandStored(opcode, instruction); - const bool extendedWithPointer = opcode == spv::OpExtInst && std::any_of(instruction.begin() + static_cast(std::min(5u, instruction.size())), instruction.end(), [&](std::uint32_t operand) { return pointers.contains(operand); }); - stores = stores || extendedWithPointer || (pointer != 0 && pointers.contains(pointer)); - }); - return stores; -} - void ShaderResources::prepareAddressBindings(std::span shaders, std::span snapshots) { static const bool loopGuarded = std::getenv("APS5_LOOP_GUARD") != nullptr; for (const auto& shader : shaders) { @@ -135,7 +23,7 @@ void ShaderResources::prepareAddressBindings(std::span sha Require(shader.program->bdaAbiVersion == (faults == 0 ? 0u : ShaderRecompiler::BdaAbi::Version), "incompatible BDA ABI version"); // Rect-list validation needs a fault buffer, but never accesses guest addresses. usesBda = usesBda || tables != 0; - if (tables != 0 && storesThroughAddressesCached(shader.program->spirv)) bdaReadOnly = false; + if (tables != 0 && shader.program->bdaStores) bdaReadOnly = false; usesFaultBuffer = usesFaultBuffer || faults != 0; const bool tableFaultsOnly = std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap; }); faultChecks = faultChecks || tables != 0 || (faults != 0 && (!tableFaultsOnly || shader.program->imageTableFaults != 0 || shader.program->poisonedSrtReads != 0 || shader.program->windowLaneGuards != 0 || loopGuarded)); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 84bc841971d5..5411b3d534a1 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -9,6 +9,7 @@ #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/PlaceholderImages.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" @@ -226,6 +227,7 @@ std::list::iterator findTexture(TextureCache& cache, const Textur } void eraseTexture(TextureCache& cache, std::list::iterator it) { + if (it->texture != nullptr && it->texture->HeapHolds() != 0u) BindlessHeap::NoteSweepDue(); cache.bytes -= it->accounted; if (it->source != nullptr) { for (auto [view, last] = cache.views.equal_range(it->source.get()); view != last; ++view) { @@ -318,7 +320,8 @@ bool admitTexture(TextureCache& cache, const TextureKey& key, std::uint64_t inco ++cache.counts.uncached; return false; } - const bool keep = back->accounted == 0 || (!over && back->texture.use_count() > 1); + const auto heapHolds = back->texture != nullptr ? back->texture->HeapHolds() : 0u; + const bool keep = back->accounted == 0 || (!over && back->texture.use_count() > 1 + static_cast(heapHolds)); if (keep && cache.passed < cache.entries.size()) { cache.entries.splice(cache.entries.begin(), cache.entries, back); ++cache.passed; @@ -1578,9 +1581,9 @@ bool StorageDedupeEnabled() { } // Whether storage element `element` of `binding` repeats the previous element's eight words. -bool SameAsPreviousStorageElement(const ShaderRecompiler::DescriptorBinding& binding, std::uint32_t element) { +bool SameAsPreviousStorageElement(std::span guest, std::uint32_t element) { if (element == 0) return false; - const auto words = binding.guestDescriptor.begin() + static_cast(element) * 8u; + const auto words = guest.begin() + static_cast(element) * 8u; return std::equal(words, words + 8, words - 8); } @@ -1652,6 +1655,7 @@ void ShaderResources::Complete() { buildPrepare(shaders, nullptr, 0, 0, 0); } buildComplete(); + if (heapStage) RefreshHeapStage(shaders); forgetDeferredInputs(); } @@ -1666,6 +1670,7 @@ void ShaderResources::forgetDeferredInputs() { void ShaderResources::build(std::span shaders, const ColorTarget* target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::size_t indexBytes) { buildPrepare(shaders, target, colorAttachments, indexAddress, indexBytes); buildComplete(); + if (heapStage) RefreshHeapStage(shaders); } namespace { @@ -1855,16 +1860,16 @@ std::vector& ReusedTables() { return ShaderRecompiler::ThreadOwned(slot); } -bool SameTable(const ReusedTable& table, VkDevice device, const ShaderRecompiler::DescriptorBinding& binding) { - return table.device == device && table.words == binding.guestDescriptor && table.shapes == binding.imageShapes && table.depthCompare == binding.imageDepthCompare; +bool SameTable(const ReusedTable& table, VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, std::span words) { + return table.device == device && std::ranges::equal(table.words, words) && table.shapes == binding.imageShapes && table.depthCompare == binding.imageDepthCompare; } -ReusedTable* FindReusedTable(VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, const TableState& state) { +ReusedTable* FindReusedTable(VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, std::span words, const TableState& state) { if (state.epoch == 0) return nullptr; auto& tables = ReusedTables(); std::erase_if(tables, [&](const ReusedTable& table) { return table.state != state; }); for (auto& table : tables) { - if (SameTable(table, device, binding)) return &table; + if (SameTable(table, device, binding, words)) return &table; } return nullptr; } @@ -1897,10 +1902,10 @@ bool CachedTableTextures(const ReusedTable& table, std::vector words) { auto& tables = ReusedTables(); - std::erase_if(tables, [&](const ReusedTable& entry) { return SameTable(entry, table.device, binding); }); - table.words = binding.guestDescriptor; + std::erase_if(tables, [&](const ReusedTable& entry) { return SameTable(entry, table.device, binding, words); }); + table.words.assign(words.begin(), words.end()); table.shapes = binding.imageShapes; table.depthCompare = binding.imageDepthCompare; tables.insert(tables.begin(), std::move(table)); @@ -2010,27 +2015,39 @@ void ShaderResources::buildPrepare(std::span shaders, cons Require(stageStorageBuffers <= limits.maxPerStageDescriptorUpdateAfterBindStorageBuffers && stageResources <= limits.maxPerStageUpdateAfterBindResources, "shader descriptors exceed per-stage limits"); updateAfterBind = true; }; + const bool heapShader = shader.program->gpuResolvedImages; + if (heapShader) { + Require(DescriptorHeapEnabled(), "a GPU-mode stage needs VK_EXT_descriptor_heap (APS5_GPU_HEAP)"); + heapStage = true; + if (shader.stage == ShaderRecompiler::ShaderStage::Compute) NoteHeapComputeStage(); + } for (const auto& binding : shader.program->bindings) { - Require(binding.descriptorSet == ShaderRecompiler::RuntimeAbi::DescriptorSet || (shader.stage == ShaderRecompiler::ShaderStage::Fragment && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet), "unexpected descriptor set: a shader resource must use its stage's descriptor set"); + Require(binding.descriptorSet == ShaderRecompiler::RuntimeAbi::DescriptorSet || ((shader.stage == ShaderRecompiler::ShaderStage::Fragment || heapShader) && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet) || (heapShader && binding.role == ShaderRecompiler::DescriptorRole::Gds && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::GpuGdsSet), "unexpected descriptor set: a shader resource must use its stage's descriptor set"); if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable) { const bool storage = binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable; Require(binding.binding == (storage ? ShaderRecompiler::RuntimeAbi::ImageStorageTableBinding : ShaderRecompiler::RuntimeAbi::ImageTableBinding) && binding.kind == (storage ? ShaderRecompiler::DescriptorKind::StorageImage : ShaderRecompiler::DescriptorKind::SampledImage) && binding.guestDescriptor.size() == static_cast(binding.count) * 8u && binding.imageShapes.size() == binding.count && binding.imageDepthCompare.size() == binding.count && binding.imageSamplers.size() == binding.count, "image table binding is malformed"); + NoteImageTableBuild(); auto& table = tableStage(shader); Require(storage ? !table.storage : !table.sampled, "a stage binds two image tables"); Require(table.images == nullptr || table.images->count == binding.count, "a stage's image tables disagree on their elements"); (storage ? table.storage : table.sampled) = true; table.images = &binding; + table.imageWords = DrawGuestWords(shader, binding); + Require(table.imageWords.size() == static_cast(binding.count) * 8u, "a draw's image table words differ in size from its binding"); table.firstSampler = firstSampler; continue; } - Require(occupied.insert(binding.binding).second, "duplicate shader binding"); + const bool heapStorage = heapShader && binding.role == ShaderRecompiler::DescriptorRole::GuestImages && binding.kind == ShaderRecompiler::DescriptorKind::StorageImage && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet; + const bool sharedHeapArray = heapShader && (binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers || (binding.role == ShaderRecompiler::DescriptorRole::GuestImages && binding.kind == ShaderRecompiler::DescriptorKind::SampledImage) || heapStorage); + Require(occupied.insert(binding.binding).second || sharedHeapArray, "duplicate shader binding"); if (binding.role == ShaderRecompiler::DescriptorRole::SamplerTable) { - addSamplerTable(binding, flags, tableStage(shader)); + addSamplerTable(binding, DrawGuestWords(shader, binding), flags, tableStage(shader)); continue; } if (binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap) { - Require(binding.kind == ShaderRecompiler::DescriptorKind::StorageBuffer && binding.count == 1 && binding.guestDescriptor.size() >= ShaderRecompiler::ImageTableAbi::HeaderWords && !binding.readOnly && binding.guestDescriptor[ShaderRecompiler::ImageTableAbi::HeaderVersion] == ShaderRecompiler::ImageTableAbi::Version, "image table map binding is malformed"); - const auto size = binding.guestDescriptor.size() * sizeof(std::uint32_t); + const auto& mapWords = DrawGuestWords(shader, binding); + Require(binding.kind == ShaderRecompiler::DescriptorKind::StorageBuffer && binding.count == 1 && mapWords.size() >= ShaderRecompiler::ImageTableAbi::HeaderWords && !binding.readOnly && mapWords[ShaderRecompiler::ImageTableAbi::HeaderVersion] == ShaderRecompiler::ImageTableAbi::Version, "image table map binding is malformed"); + const auto size = mapWords.size() * sizeof(std::uint32_t); Require(size <= context.limits.maxStorageBufferRange, "image table map exceeds the storage buffer range limit"); stageStorageBuffers += 1; stageResources += 1; @@ -2038,19 +2055,48 @@ void ShaderResources::buildPrepare(std::span shaders, cons requireStageLimits(); auto& table = tableStage(shader); Require(table.mapAllocation == std::numeric_limits::max(), "a stage binds two image table maps"); - table.map = binding.guestDescriptor; + table.map = mapWords; allocations.push_back({0, size, false, std::make_unique(context, size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT), ShaderRecompiler::DescriptorRole::ImageTableMap}); table.mapAllocation = allocations.size() - 1u; bindings.push_back({{binding.binding, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, flags, nullptr}, {allocations.size() - 1u}}); + bindings.back().heap = table.heap; + continue; + } + if (heapShader) { + if (heapStorage) { + Require(ShaderRecompiler::RuntimeAbi::GpuHeapStorageKind(binding.binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)), "a heap storage image binding has an atomic or unknown kind"); + addImageBinding(binding, DrawGuestWords(shader, binding), flags); + bindings.back().heap = true; + continue; + } + if (binding.role == ShaderRecompiler::DescriptorRole::GuestImages && binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) goto perDrawBinding; + if (binding.role == ShaderRecompiler::DescriptorRole::GuestImages || binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers) { + Require(binding.kind == ShaderRecompiler::DescriptorKind::SampledImage || binding.kind == ShaderRecompiler::DescriptorKind::Sampler, "a GPU-mode stage binds sampled images and samplers only"); + addImageBinding(binding, DrawGuestWords(shader, binding), flags); + bindings.back().heap = true; + continue; + } + if (binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable || binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer || binding.role == ShaderRecompiler::DescriptorRole::Gds) goto perDrawBinding; + if (binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers) { + goto perDrawBinding; + } + Require(binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt, std::string("a GPU-mode fragment stage has an unsupported ") + roleName(binding.role) + " binding"); + Require(binding.count == 1 && !DrawGuestWords(shader, binding).empty(), "invalid GPU-mode shader data binding"); + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, DrawGuestWords(shader, binding)); + Binding item{{binding.binding, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, flags, nullptr}, {}, {}}; + item.heap = true; + item.role = binding.role; + bindings.push_back(std::move(item)); continue; } + perDrawBinding: const bool addressRole = binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable || binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer; const bool bufferRole = addressRole || binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers || binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt || binding.role == ShaderRecompiler::DescriptorRole::Gds; const bool imageRole = binding.role == ShaderRecompiler::DescriptorRole::GuestImages || binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers; if (imageRole) { if (binding.kind == ShaderRecompiler::DescriptorKind::SampledImage || binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) stageResources += binding.count; requireStageLimits(); - addImageBinding(binding, flags); + addImageBinding(binding, DrawGuestWords(shader, binding), flags); continue; } if (!bufferRole) Require(false, std::string("unsupported descriptor role ") + roleName(binding.role)); @@ -2063,7 +2109,8 @@ void ShaderResources::buildPrepare(std::span shaders, cons requireStageLimits(); Binding item{{binding.binding, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, binding.count, flags, nullptr}, {}}; if (binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers) { - Require(binding.guestDescriptor.size() == static_cast(binding.count) * 4, "guest buffer descriptor must contain four DWORDs per array element"); + const auto& guestWords = DrawGuestWords(shader, binding); + Require(guestWords.size() == static_cast(binding.count) * 4, "guest buffer descriptor must contain four DWORDs per array element"); for (std::uint32_t element = 0; element < binding.count; ++element) { // An element the recompiler did not classify (a producer without the // vector) counts as written, like imageWritten below. @@ -2071,11 +2118,11 @@ void ShaderResources::buildPrepare(std::span shaders, cons const bool atomic = element < binding.bufferAtomic.size() && binding.bufferAtomic[element]; const bool read = element < binding.bufferRead.size() && binding.bufferRead[element]; const std::uint32_t extent = element < binding.bufferExtent.size() ? binding.bufferExtent[element] : 0u; - const auto index = addGuestBuffer(std::span(binding.guestDescriptor).subspan(static_cast(element) * 4, 4), target, indexAddress, indexBytes, written, atomic, read, extent); + const auto index = addGuestBuffer(std::span(guestWords).subspan(static_cast(element) * 4, 4), target, indexAddress, indexBytes, written, atomic, read, extent); const bool classified = element < binding.bufferWritten.size() && element < binding.bufferRead.size() && element < binding.bufferAtomic.size(); allocations[index].writeOnly = classified && allocations[index].guest && allocations[index].written && binding.bufferWritten[element] && !read && !atomic; const auto& push = shader.program->pushConstants; - if (!push.empty()) { + if (!push.empty() && !shader.program->dataAddressPush) { const auto position = shader.program->memoryOffsetDword * 4u + element; Require(position < push.size(), "guest buffer offset lies outside the shader's push constants"); allocations[index].pushByte = static_cast(shader.pushConstantOffset + position); @@ -2085,27 +2132,42 @@ void ShaderResources::buildPrepare(std::span shaders, cons } item.allocations.push_back(index); } + if (heapShader && shader.program->bufferAddressCount != 0u) { + Require(shader.program->bufferAddressCount == binding.count, "a GPU-mode stage's buffer address words disagree with its buffer binding"); + item.heap = true; + item.addressed = true; + item.dataStage = static_cast(HeapStageIndex(shader.stage)); + item.addressDword = shader.program->bufferAddressDword; + addressedBuffers = true; + } } else if (addressRole) { item.allocations.push_back(allocations.size()); allocations.push_back({0, 0, false, nullptr, binding.role}); + item.heap = (heapShader && shader.program->dataAddressPush) || (heapStage && !heapShader && binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer); } else if (binding.role == ShaderRecompiler::DescriptorRole::Gds) { Require(binding.count == 1 && binding.guestDescriptor.empty(), "invalid GDS descriptor contract"); + static_assert(Pm4::GdsBytes == ShaderRecompiler::RuntimeAbi::GdsBytes); const auto gds = Pm4::GdsAddress(); guestMemory.AddWritable(gds, Pm4::GdsBytes, true); item.allocations.push_back(allocations.size()); allocations.push_back({gds, Pm4::GdsBytes, true, nullptr, ShaderRecompiler::DescriptorRole::ShaderData, true}); + if (heapShader && shader.program->dataAddressPush) { + item.heap = true; + if (gdsAllocation == std::numeric_limits::max()) gdsAllocation = item.allocations.back(); + } } else { Require(binding.count == 1, "shader data and flattened SRT descriptors must not be arrays"); - Require(!binding.guestDescriptor.empty(), "empty shader data descriptor"); + const auto& guestWords = DrawGuestWords(shader, binding); + Require(!guestWords.empty(), "empty shader data descriptor"); if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) { - ValidateRuntimeResources(shader, binding.guestDescriptor); + ValidateRuntimeResources(shader, guestWords); } - item.allocations.push_back(addDataBuffer(binding.guestDescriptor)); + item.allocations.push_back(addDataBuffer(guestWords)); if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) shaderData = static_cast(item.allocations.back()); } bindings.push_back(std::move(item)); } - for (const auto index : offsetsInData) allocations[index].dataAllocation = shaderData; + for (const auto index : offsetsInData) allocations[index].dataAllocation = heapShader ? HeapRingData(HeapStageIndex(shader.stage)) : shaderData; for (auto index = firstDeferred; index < deferredImages.size(); ++index) { deferredImages[index].firstSampler = firstSampler; deferredImages[index].samplerCount = samplers.size() - firstSampler; @@ -2126,8 +2188,8 @@ void ShaderResources::buildPrepare(std::span shaders, cons const auto faults = map[ShaderRecompiler::ImageTableAbi::HeaderElementFaults]; const auto samplerFaults = map[ShaderRecompiler::ImageTableAbi::HeaderSamplerFaults]; Require(static_cast(faults) + elements <= map.size() && static_cast(samplerFaults) + map[ShaderRecompiler::ImageTableAbi::HeaderSamplerCount] / 4u <= map.size(), "image table map is truncated"); - if (table.images == nullptr) continue; - table.set = splitSets && table.stage == ShaderRecompiler::ShaderStage::Fragment ? 1u : 0u; + if (table.images == nullptr || table.heap) continue; + table.set = splitSets && !heapStage && table.stage == ShaderRecompiler::ShaderStage::Fragment ? 1u : 0u; table.elementBase = tableElements[table.set]; table.map[ShaderRecompiler::ImageTableAbi::HeaderElementBase] = table.elementBase; tableElements[table.set] += elements; @@ -2154,13 +2216,29 @@ void ShaderResources::buildPrepare(std::span shaders, cons // For every build, locked ones included: their stage B then takes the fast path too, and the // collects cost the same wherever they run. if (precollectImages()) phase(BuildPhase::Precollect); - if (drawBuild && !usesBda && std::all_of(allocations.begin(), allocations.end(), [&](const Allocation& allocation) { return !allocation.guest || allocation.pushByte >= 0 || (allocation.dataAllocation >= 0 && allocation.dataByte < allocations[static_cast(allocation.dataAllocation)].size); })) guestMemory.AllowAdjustedRegions(); + const auto heapDataBytes = [&](std::int64_t ring) -> std::uint64_t { + const auto stage = HeapRingStage(ring); + for (const auto& shader : shaders) { + if (HeapStageIndex(shader.stage) != stage || shader.program == nullptr || !shader.program->gpuResolvedImages) continue; + for (const auto& binding : shader.program->bindings) { + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) return binding.guestDescriptor.size() * sizeof(std::uint32_t); + } + } + return 0; + }; + const auto patchable = [&](const Allocation& allocation) { + if (!allocation.guest || allocation.pushByte >= 0) return true; + if (IsHeapRingData(allocation.dataAllocation)) return allocation.dataByte < heapDataBytes(allocation.dataAllocation); + return allocation.dataAllocation >= 0 && allocation.dataByte < allocations[static_cast(allocation.dataAllocation)].size; + }; + if (drawBuild && !usesBda && std::all_of(allocations.begin(), allocations.end(), patchable)) guestMemory.AllowAdjustedRegions(); guestMemory.UploadPrepare(usesBda); timing.uploadMs = phase(BuildPhase::Upload); splitSets = SplitsSets(context, shaders); std::array, 2> descriptions; bool tablesUpdateAfterBind = false; for (const auto& binding : bindings) { + if (binding.heap) continue; const auto set = setOf(binding); descriptions[set].push_back(binding.layout); (set == 0 ? layoutBindingFlags : fragmentBindingFlags).push_back(binding.flags | (updateAfterBind && binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0)); @@ -2207,8 +2285,12 @@ void ShaderResources::buildPrepare(std::span shaders, cons owns = true; return CreateSetLayout(context, description, updateAfterBind, flags); }; + if (heapStage) { + Require(splitSets && descriptions[1].empty(), "a GPU-mode fragment stage needs split sets and no per-draw fragment bindings"); + fragmentLayoutKey = {0x48454150u}; + } _layout = createLayout(layoutKey, descriptions[0], layoutBindingFlags, ownsLayout); - if (splitSets) { + if (splitSets && !heapStage) { fragment.layout = createLayout(fragmentLayoutKey, descriptions[1], fragmentBindingFlags, fragment.ownsLayout); { const auto sizes = splitPoolSizes(1); @@ -2291,7 +2373,8 @@ void ShaderResources::buildPrepare(std::span shaders, cons bool SplitsSets(const Context& context, std::span shaders) { const auto fragmentSet = [](const CompiledShader& shader) { return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const auto& binding) { return binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet; }); }; const auto fragmentStage = [](const CompiledShader& shader) { return shader.stage == ShaderRecompiler::ShaderStage::Fragment; }; - return std::any_of(shaders.begin(), shaders.end(), fragmentSet) || (context.graphicsPipelineLibrary && std::any_of(shaders.begin(), shaders.end(), fragmentStage)); + const auto heapStage = [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->gpuResolvedImages; }; + return std::any_of(shaders.begin(), shaders.end(), fragmentSet) || std::any_of(shaders.begin(), shaders.end(), heapStage) || (context.graphicsPipelineLibrary && std::any_of(shaders.begin(), shaders.end(), fragmentStage)); } DescribedSetLayouts DescribeSetLayouts(const Context& context, std::span shaders) { @@ -2305,21 +2388,37 @@ DescribedSetLayouts DescribeSetLayouts(const Context& context, std::spangpuResolvedImages; }; + const bool heapStage = std::any_of(shaders.begin(), shaders.end(), heapShader); for (const auto& shader : shaders) { Require(shader.program != nullptr, "missing compiled shader"); const VkShaderStageFlags flags = VulkanStage(shader.stage); + const bool gpuMode = heapShader(shader); std::uint64_t stageStorageBuffers = 0; std::uint64_t stageResources = 0; + const bool addressedStage = gpuMode && shader.program->dataAddressPush; for (const auto& binding : shader.program->bindings) { - const auto set = binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet ? 1 : 0; + const auto set = !heapStage && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet ? 1 : 0; + if (heapStage && !gpuMode && binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer) continue; + if (addressedStage) { + using Role = ShaderRecompiler::DescriptorRole; + const bool tableRole = binding.role == Role::ImageTable || binding.role == Role::ImageStorageTable || binding.role == Role::SamplerTable || binding.role == Role::ImageTableMap; + const bool addressRole = binding.role == Role::BdaPagetable || binding.role == Role::FaultBuffer || (binding.role == Role::GuestBuffers && shader.program->bufferAddressCount != 0u) || (binding.role == Role::Gds && shader.program->dataAddressPush); + const bool heapStorage = binding.role == Role::GuestImages && binding.kind == ShaderRecompiler::DescriptorKind::StorageImage && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet; + if (tableRole || addressRole || heapStorage) continue; + } if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable) { - tableFlags[split && shader.stage == ShaderRecompiler::ShaderStage::Fragment ? 1 : 0] |= flags; + tableFlags[split && !heapStage && shader.stage == ShaderRecompiler::ShaderStage::Fragment ? 1 : 0] |= flags; continue; } if (binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable) { storageTableFlags[split && shader.stage == ShaderRecompiler::ShaderStage::Fragment ? 1 : 0] |= flags; continue; } + if (gpuMode) { + const bool heapImage = (binding.role == ShaderRecompiler::DescriptorRole::GuestImages && binding.kind != ShaderRecompiler::DescriptorKind::StorageImage) || binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers; + if (heapImage || binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt) continue; + } if (binding.role == ShaderRecompiler::DescriptorRole::SamplerTable) { descriptions[set].push_back({binding.binding, VK_DESCRIPTOR_TYPE_SAMPLER, context.samplerTableCapacity, flags, nullptr}); bindingFlags[set].push_back(VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | (context.samplerTableUpdateAfterBind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0)); @@ -2363,6 +2462,11 @@ DescribedSetLayouts DescribeSetLayouts(const Context& context, std::spanLayout(result.mainKey, descriptions[0], updateAfterBind, bindingFlags[0]); + if (heapStage) { + Require(split && descriptions[1].empty(), "a GPU-mode stage needs split sets and no per-draw fragment bindings"); + result.fragmentKey = {0x48454150u}; + return result; + } if (split) result.layouts.fragment = context.descriptorCache->Layout(result.fragmentKey, descriptions[1], updateAfterBind, bindingFlags[1]); return result; } @@ -2378,7 +2482,7 @@ void ShaderResources::buildComplete() { // storage elements of one mip chain share the previous element's image. previousSampled = {}; for (auto& source : samplerSources) source.singleLevelImage = source.mipmappedImage = false; - for (const auto& deferred : deferredImages) resolveImageBinding(*deferred.binding, bindings[deferred.index], std::span>(samplers).subspan(deferred.firstSampler, deferred.samplerCount)); + for (const auto& deferred : deferredImages) resolveImageBinding(*deferred.binding, deferred.words, bindings[deferred.index], std::span>(samplers).subspan(deferred.firstSampler, deferred.samplerCount)); previousSampled = {}; deferredImages.clear(); applyAnisoOverride(); @@ -2398,6 +2502,10 @@ void ShaderResources::buildComplete() { if (bda) bda->SetSrtGuards(std::move(srtGuardFaults)); finishImageTables(); phase(BuildPhase::Bda); + for (const auto& binding : bindings) { + if (!binding.addressed) continue; + for (const auto index : binding.allocations) static_cast(descriptor(allocations[index])); + } if (_set != VK_NULL_HANDLE || fragment.set != VK_NULL_HANDLE) { // One update call for the whole set: the info arrays are sized up front so every write's // pointer into them stays valid until the call. @@ -2420,6 +2528,7 @@ void ShaderResources::buildComplete() { return VkDescriptorImageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; }; for (const auto& binding : bindings) { + if (binding.heap) continue; if (binding.flags != 0) { const auto set = setOf(binding); const bool sampled = binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; @@ -2526,6 +2635,10 @@ void ShaderResources::buildComplete() { pushPatches.emplace_back(static_cast(allocation.pushByte), allocation.adjustment); continue; } + if (IsHeapRingData(allocation.dataAllocation)) { + heapStages[HeapRingStage(allocation.dataAllocation)].dataPatches.emplace_back(allocation.dataByte, allocation.adjustment); + continue; + } Require(allocation.dataAllocation >= 0, "a guest buffer off the storage buffer offset alignment in a shader without shader data is not implemented"); auto& data = allocations[static_cast(allocation.dataAllocation)]; Require(data.buffer != nullptr && allocation.dataByte < data.size, "guest buffer offset lies outside the shader's data buffer"); @@ -2594,10 +2707,17 @@ void ShaderResources::noteReusable() { // Taken whether or not the object turns out reusable: the lookups' records are this build's. captureValidation(); reusable = false; + spaceReuse = false; directRegions.clear(); - if (guestMemory.HasCopiedWrites() || HoldsLease() || usesBda || !multisampleSources.empty() || (bda != nullptr && LoopGuardEnabled())) return; + const bool spaceReusable = drawBuild && usesBda && bdaReadOnly && !SpaceReuseDisabled() && guestMemory.SpaceOnly() && !guestMemory.HasCopiedWrites() && multisampleSources.empty() && !(bda != nullptr && LoopGuardEnabled()); + if (!spaceReusable && (guestMemory.HasCopiedWrites() || HoldsLease() || usesBda || !multisampleSources.empty() || (bda != nullptr && LoopGuardEnabled()))) return; if (std::any_of(textures.begin(), textures.end(), [](const std::shared_ptr& texture) { return texture != nullptr && texture->RefreshedPerUse(); })) return; if (TemplateDataRefresh() && std::any_of(allocations.begin(), allocations.end(), [](const Allocation& allocation) { return allocation.buffer != nullptr && !allocation.guest && allocation.role != ShaderRecompiler::DescriptorRole::ImageTableMap && allocation.size > MaxRefreshBytes; })) return; + if (spaceReusable) { + spaceReuse = true; + reusable = true; + return; + } const auto regions = guestMemory.DirectRegions(); if (!regions.has_value()) return; for (const auto& [begin, end] : *regions) { @@ -2627,10 +2747,15 @@ std::uint64_t ShaderResources::DepthGuardRefusals() { bool ShaderResources::NeverReusable(std::span shaders) { const bool loopGuard = LoopGuardEnabled(); return std::any_of(shaders.begin(), shaders.end(), [loopGuard](const CompiledShader& shader) { - return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [loopGuard](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable || (loopGuard && binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer); }); + const bool readOnlyBda = shader.program != nullptr && !shader.program->bdaStores && !SpaceReuseDisabled(); + return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [loopGuard, readOnlyBda](const ShaderRecompiler::DescriptorBinding& binding) { return (binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable && !readOnlyBda) || (loopGuard && binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer); }); }); } +bool ShaderResources::SpaceReuseDisabled() { + return !GpuHeapEnabled(); +} + // APS5_PROFILE_DRAW: the per-device descriptor caches' counters, every 10 s. void ShaderResources::reportDescriptorCaches() const { static AgcDriver::Mutex reportMutex; @@ -2653,6 +2778,18 @@ void VisitContentKey(const CompiledShader& shader, bool dataWords, bool movableB visit(static_cast(shader.stage)); visit(static_cast(program.PipelineVariantId())); visit(static_cast(program.PipelineVariantId() >> 32u)); + if (shader.heap != nullptr && program.heapTemplateId != 0) { + visit(0u); + visit(0x48454150u); + visit(static_cast(program.heapTemplateId)); + visit(static_cast(program.heapTemplateId >> 32u)); + for (const auto& binding : program.bindings) { + if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages && binding.role != ShaderRecompiler::DescriptorRole::GuestSamplers) continue; + visit(binding.binding); + for (const auto word : DrawGuestWords(shader, binding)) visit(word); + } + return; + } visit(static_cast(program.bindings.size())); const auto packBits = [&](const std::vector& bits) { visit(static_cast(bits.size())); @@ -2666,17 +2803,17 @@ void VisitContentKey(const CompiledShader& shader, bool dataWords, bool movableB } }; for (const auto& binding : program.bindings) { - for (const auto word : {static_cast(binding.kind), static_cast(binding.role), binding.descriptorSet, binding.binding, binding.count, binding.readOnly ? 1u : 0u, binding.imageShape.has_value() ? static_cast(*binding.imageShape) + 1u : 0u, static_cast(binding.guestDescriptor.size())}) visit(word); - if (movableBuffers && binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers && binding.guestDescriptor.size() == static_cast(binding.count) * 4u) { + for (const auto word : {static_cast(binding.kind), static_cast(binding.role), binding.descriptorSet, binding.binding, binding.count, binding.readOnly ? 1u : 0u, binding.imageShape.has_value() ? static_cast(*binding.imageShape) + 1u : 0u, static_cast(DrawGuestWords(shader, binding).size())}) visit(word); + if (movableBuffers && binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers && DrawGuestWords(shader, binding).size() == static_cast(binding.count) * 4u) { for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto* words = binding.guestDescriptor.data() + static_cast(element) * 4u; + const auto* words = DrawGuestWords(shader, binding).data() + static_cast(element) * 4u; const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; const bool empty = words[2] == 0 || (words[0] == 0 && (words[1] & 0xffffu) == 0); if (written || empty) { for (std::uint32_t index = 0; index < 4u; ++index) visit(words[index]); } else { for (const auto word : {0u, words[1] & 0xffff0000u, 0u, words[3]}) visit(word); } } } else if ((dataWords && !movableBuffers) || !DataRole(binding.role)) { - for (const auto word : binding.guestDescriptor) visit(word); + for (const auto word : DrawGuestWords(shader, binding)) visit(word); } packBits(binding.imageWritten); packBits(binding.samplerDepthCompare); @@ -3336,7 +3473,7 @@ ShaderResources::OwnRefreshFallback ShaderResources::refreshOwnObjects(std::span if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages) continue; if (binding.kind == ShaderRecompiler::DescriptorKind::SampledImage) { for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = std::span(DrawGuestWords(shader, binding)).subspan(static_cast(element) * 8u, 8u); if (IsNullTextureResource(words)) continue; if (textureIndex >= textures.size()) return OwnRefreshFallback::Uncached; const auto index = textureIndex++; @@ -3346,7 +3483,7 @@ ShaderResources::OwnRefreshFallback ShaderResources::refreshOwnObjects(std::span } } else if (binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) { for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = std::span(DrawGuestWords(shader, binding)).subspan(static_cast(element) * 8u, 8u); if (IsNullTextureResource(words)) continue; if (storageIndex >= storageTextures.size()) return OwnRefreshFallback::Uncached; const auto index = storageIndex++; @@ -3392,11 +3529,13 @@ bool CompletePendingCpuWrites(const Context& context, std::uint64_t address, std return false; } -const ShaderRecompiler::DescriptorBinding* ShaderResources::tableImages(std::span shaders, ShaderRecompiler::ShaderStage stage) { +const ShaderRecompiler::DescriptorBinding* ShaderResources::tableImages(std::span shaders, ShaderRecompiler::ShaderStage stage, std::span& words) { for (const auto& shader : shaders) { if (shader.stage != stage || shader.program == nullptr) continue; for (const auto& binding : shader.program->bindings) { - if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable) return &binding; + if (binding.role != ShaderRecompiler::DescriptorRole::ImageTable) continue; + words = DrawGuestWords(shader, binding); + return &binding; } } return nullptr; @@ -3492,9 +3631,9 @@ bool ShaderResources::revalidateFull(std::span shaders, Pr for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages) continue; if (binding.kind == ShaderRecompiler::DescriptorKind::SampledImage) { - const auto elementWords = binding.count != 0 ? binding.guestDescriptor.size() / binding.count : 0; + const auto elementWords = binding.count != 0 ? DrawGuestWords(shader, binding).size() / binding.count : 0; for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto raw = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); + const auto raw = std::span(DrawGuestWords(shader, binding)).subspan(static_cast(element) * elementWords, elementWords); std::array narrowed{}; const auto words = firstLayerWords(raw, binding.imageShape, narrowed, false); if (IsNullTextureResource(words)) continue; @@ -3506,11 +3645,11 @@ bool ShaderResources::revalidateFull(std::span shaders, Pr } } else if (binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) { for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = std::span(DrawGuestWords(shader, binding)).subspan(static_cast(element) * 8u, 8u); if (IsNullTextureResource(words)) continue; if (storageIndex >= storageTextures.size()) return false; std::shared_ptr expected; - if (SameAsPreviousStorageElement(binding, element) && StorageDedupeEnabled()) expected = storageTextures[storageIndex - 1]; + if (SameAsPreviousStorageElement(DrawGuestWords(shader, binding), element) && StorageDedupeEnabled()) expected = storageTextures[storageIndex - 1]; else expected = cachedStorageTexture(context, words, DecodeTextureResource(words), storageMips[storageIndex], 0, storageWritten[storageIndex]); if (expected != storageTextures[storageIndex]) return false; ++storageIndex; @@ -3520,10 +3659,11 @@ bool ShaderResources::revalidateFull(std::span shaders, Pr } for (const auto& table : tableStages) { if (table.elementTextures.empty()) continue; - const auto* images = tableImages(shaders, table.stage); - if (images == nullptr || images->count != table.elementTextures.size()) return false; + std::span imageWords; + const auto* images = tableImages(shaders, table.stage, imageWords); + if (images == nullptr || images->count != table.elementTextures.size() || imageWords.size() != static_cast(images->count) * 8u) return false; std::vector> cached; - if (auto* reused = FindReusedTable(context.device, *images, CurrentTableState()); reused != nullptr && TableCurrent(*reused) && CachedTableTextures(*reused, cached)) { + if (auto* reused = FindReusedTable(context.device, *images, imageWords, CurrentTableState()); reused != nullptr && TableCurrent(*reused) && CachedTableTextures(*reused, cached)) { auto next = cached.begin(); bool same = true; for (std::uint32_t element = 0; same && element < images->count; ++element) { @@ -3544,7 +3684,7 @@ bool ShaderResources::revalidateFull(std::span shaders, Pr } for (std::uint32_t element = 0; element < images->count; ++element) { if (table.elementTextures[element] == std::numeric_limits::max()) continue; - const auto raw = std::span(images->guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto raw = imageWords.subspan(static_cast(element) * 8u, 8u); std::array narrowed{}; const auto words = firstLayerWords(raw, images->imageShapes.at(element), narrowed, false); const auto resource = DecodeTextureResource(words); @@ -4484,13 +4624,14 @@ std::uint64_t ShaderResources::DataWordsHash(const CompiledShader& shader) { Require(shader.program != nullptr, "missing compiled shader"); std::uint64_t hash = FnvOffset; for (const auto& binding : shader.program->bindings) { - if (DataRole(binding.role)) mixDataWords(hash, binding.guestDescriptor); + if (DataRole(binding.role)) mixDataWords(hash, DrawGuestWords(shader, binding)); } return hash; } bool ShaderResources::DataWordsDiffer(const CompiledShader& shader) const { Require(shader.program != nullptr, "missing compiled shader"); + if (heapStage) return false; const auto& program = *shader.program; if (program.bindings.size() != bindings.size()) return true; for (std::size_t index = 0; index < program.bindings.size(); ++index) { @@ -4498,7 +4639,7 @@ bool ShaderResources::DataWordsDiffer(const CompiledShader& shader) const { if (!DataRole(binding.role)) continue; if (bindings[index].allocations.size() != 1) return true; const auto& allocation = allocations[bindings[index].allocations.front()]; - if (allocation.dataWords.size() != binding.guestDescriptor.size() || !std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), binding.guestDescriptor.begin())) return true; + if (allocation.dataWords.size() != DrawGuestWords(shader, binding).size() || !std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), DrawGuestWords(shader, binding).begin())) return true; } return false; } @@ -4511,6 +4652,7 @@ bool ShaderResources::RefreshData(VkCommandBuffer commands, const CompiledShader bool ShaderResources::refreshData(VkCommandBuffer commands, const CompiledShader& shader, Recorder* recorder) { Require(shader.program != nullptr, "missing compiled shader"); + if (heapStage) return false; const auto& program = *shader.program; Require(program.bindings.size() == bindings.size(), "template bindings disagree with the shader"); bool recorded = false; @@ -4523,13 +4665,13 @@ bool ShaderResources::refreshData(VkCommandBuffer commands, const CompiledShader if (!DataRole(binding.role)) continue; Require(bindings[index].allocations.size() == 1, "data binding without its buffer"); auto& allocation = allocations[bindings[index].allocations.front()]; - const auto size = binding.guestDescriptor.size() * sizeof(std::uint32_t); + const auto size = DrawGuestWords(shader, binding).size() * sizeof(std::uint32_t); Require(allocation.buffer != nullptr && !allocation.guest && allocation.size == size && size <= MaxRefreshBytes, "template data buffer cannot take the dispatch's words"); - if (allocation.dataWords.size() == binding.guestDescriptor.size() && std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), binding.guestDescriptor.begin())) continue; - if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, binding.guestDescriptor); + if (allocation.dataWords.size() == DrawGuestWords(shader, binding).size() && std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), DrawGuestWords(shader, binding).begin())) continue; + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, DrawGuestWords(shader, binding)); if (recorder != nullptr && timing == Recorder::NoTiming) timing = recorder->BeginGpuTiming(Recorder::CommandClass::TemplateDataRefresh); - writeDataWords(commands, bindings[index].allocations.front(), binding.guestDescriptor); - allocation.dataWords.assign(binding.guestDescriptor.begin(), binding.guestDescriptor.end()); + writeDataWords(commands, bindings[index].allocations.front(), DrawGuestWords(shader, binding)); + allocation.dataWords.assign(DrawGuestWords(shader, binding).begin(), DrawGuestWords(shader, binding).end()); refreshedBytes += size; recorded = true; } @@ -4582,7 +4724,7 @@ void ShaderResources::PrecollectSurfaces() const { for (const auto& range : describedRanges) GuestMemory::CollectWrites(range.address, static_cast(range.bytes)); } -void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& binding, VkShaderStageFlags flags) { +void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& binding, std::span guest, VkShaderStageFlags flags) { Require(binding.count != 0, "empty descriptor binding"); const auto heap = static_cast(binding.binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)); const auto capacity = binding.count; @@ -4595,20 +4737,20 @@ void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& if (binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) { // Storage images are guest textures the shader writes (looked up in stage B). Require(binding.role == ShaderRecompiler::DescriptorRole::GuestImages, "storage image binding has a non-image role"); - Require(binding.guestDescriptor.size() == static_cast(binding.count) * 8u, "guest storage image descriptors must contain 8 dwords each"); + Require(guest.size() == static_cast(binding.count) * 8u, "guest storage image descriptors must contain 8 dwords each"); Require(context.detiler != nullptr, "device texture detiler is unavailable"); Require(capacity <= context.limits.maxPerStageDescriptorStorageImages, "shader storage-image descriptors exceed per-stage limits"); bindings.push_back({{binding.binding, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, capacity, flags, nullptr}, {}, {}}); plannedStorageImages += binding.count; - deferredImages.push_back({&binding, bindings.size() - 1}); + deferredImages.push_back({&binding, guest, bindings.size() - 1}); return; } const bool sampledImage = binding.kind == ShaderRecompiler::DescriptorKind::SampledImage; const bool samplerKind = binding.kind == ShaderRecompiler::DescriptorKind::Sampler; if (!(sampledImage || samplerKind)) Require(false, std::string("unsupported descriptor kind ") + kindName(binding.kind) + " for role " + roleName(binding.role)); Require((sampledImage && binding.role == ShaderRecompiler::DescriptorRole::GuestImages) || (samplerKind && binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers), "guest image descriptor role disagrees with its kind"); - Require(binding.guestDescriptor.size() % binding.count == 0, "guest image descriptor size is not a multiple of the binding count"); - const auto elementWords = binding.guestDescriptor.size() / binding.count; + Require(guest.size() % binding.count == 0, "guest image descriptor size is not a multiple of the binding count"); + const auto elementWords = guest.size() / binding.count; Binding item{{binding.binding, sampledImage ? VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE : VK_DESCRIPTOR_TYPE_SAMPLER, capacity, flags, nullptr}, {}, {}}; @@ -4626,7 +4768,7 @@ void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& Require(binding.samplerDepthCompare.size() == binding.count, "guest sampler binding is missing depth comparison metadata"); Require(binding.samplerUnnormalized.empty() || binding.samplerUnnormalized.size() == binding.count, "guest sampler binding has unnormalized coordinate metadata of another size"); for (std::uint32_t element = 0; element < binding.count; ++element) { - auto guestWords = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); + auto guestWords = std::span(guest).subspan(static_cast(element) * elementWords, elementWords); std::array normalizedWords{}; if (element < binding.samplerCoordinatesIgnored.size() && binding.samplerCoordinatesIgnored[element]) { std::copy(guestWords.begin(), guestWords.end(), normalizedWords.begin()); @@ -4651,7 +4793,7 @@ void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& } bindings.push_back(std::move(item)); - if (sampledImage) deferredImages.push_back({&binding, bindings.size() - 1}); + if (sampledImage) deferredImages.push_back({&binding, guest, bindings.size() - 1}); } namespace { @@ -4692,10 +4834,10 @@ bool ShaderResources::precollectImages() { auto& counters = TextureCounts(); for (const auto& deferred : deferredImages) { const auto& binding = *deferred.binding; - const auto elementWords = binding.guestDescriptor.size() / binding.count; + const auto elementWords = deferred.words.size() / binding.count; for (std::uint32_t element = 0; element < binding.count; ++element) { const bool sampled = binding.kind == ShaderRecompiler::DescriptorKind::SampledImage; - const auto raw = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); + const auto raw = std::span(deferred.words).subspan(static_cast(element) * elementWords, elementWords); std::array narrowed{}; const auto words = firstLayerWords(raw, sampled ? binding.imageShape : std::nullopt, narrowed, false); if (sampled && !imageRecords.empty()) { @@ -4814,15 +4956,15 @@ void ShaderResources::applyAnisoOverride() { } } -void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBinding& binding, Binding& item, std::span> shaderSamplers) { +void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBinding& binding, std::span guest, Binding& item, std::span> shaderSamplers) { auto& counters = TextureCounts(); // The element's stage-A record, when the pass ran (records follow the plan order exactly). const auto nextRecord = [&]() -> const ImageRecord* { return nextImageRecord < imageRecords.size() ? &imageRecords[nextImageRecord++] : nullptr; }; if (binding.kind == ShaderRecompiler::DescriptorKind::SampledImage) { Require(binding.imageSamplers.size() == binding.count, "guest sampled image binding is missing its image-sampler pairs"); - const auto elementWords = binding.guestDescriptor.size() / binding.count; + const auto elementWords = guest.size() / binding.count; for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto raw = std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords); + const auto raw = std::span(guest).subspan(static_cast(element) * elementWords, elementWords); std::array narrowed{}; const auto words = firstLayerWords(raw, binding.imageShape, narrowed, true); const auto* record = nextRecord(); @@ -4900,8 +5042,8 @@ void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBind // storage writes). std::uint32_t mipOffset = 0; for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); - const bool sameAsPrevious = SameAsPreviousStorageElement(binding, element); + const auto words = std::span(guest).subspan(static_cast(element) * 8u, 8u); + const bool sameAsPrevious = SameAsPreviousStorageElement(guest, element); if (sameAsPrevious) ++mipOffset; else mipOffset = 0; const auto* record = nextRecord(); @@ -5017,6 +5159,7 @@ ShaderResources::TableStage& ShaderResources::tableStage(const CompiledShader& s table.program = shader.program; table.poison = shader.program->imageTablePoison; table.messages.assign(table.poison.size(), std::string{}); + table.heap = shader.program->gpuResolvedImages && shader.program->dataAddressPush; return table; } @@ -5032,21 +5175,21 @@ std::uint32_t ShaderResources::rejectTableElement(TableStage& table, std::span(table.poison.size() - 1u)); } -void ShaderResources::addSamplerTable(const ShaderRecompiler::DescriptorBinding& binding, VkShaderStageFlags flags, TableStage& table) { +void ShaderResources::addSamplerTable(const ShaderRecompiler::DescriptorBinding& binding, std::span guest, VkShaderStageFlags flags, TableStage& table) { namespace Abi = ShaderRecompiler::ImageTableAbi; - Require(binding.kind == ShaderRecompiler::DescriptorKind::Sampler && binding.guestDescriptor.size() == static_cast(binding.count) * 4u && binding.samplerDepthCompare.size() == binding.count && binding.count % Abi::SamplerEntryElements == 0u, "sampler table binding is malformed"); - Require(context.samplerTableCapacity != 0, "sampler tables need runtimeDescriptorArray and descriptorBindingPartiallyBound, which the device lacks"); + Require(binding.kind == ShaderRecompiler::DescriptorKind::Sampler && guest.size() == static_cast(binding.count) * 4u && binding.samplerDepthCompare.size() == binding.count && binding.count % Abi::SamplerEntryElements == 0u, "sampler table binding is malformed"); + Require(table.heap || context.samplerTableCapacity != 0, "sampler tables need runtimeDescriptorArray and descriptorBindingPartiallyBound, which the device lacks"); const VkDescriptorBindingFlags samplerTableFlags = VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | (context.samplerTableUpdateAfterBind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0); Binding item{{binding.binding, VK_DESCRIPTOR_TYPE_SAMPLER, context.samplerTableCapacity, flags, nullptr}, {}, {}, samplerTableFlags}; static const bool noSamplerCache = std::getenv("APS5_NO_SAMPLER_CACHE") != nullptr; for (std::uint32_t entry = 0; entry < binding.count / Abi::SamplerEntryElements; ++entry) { const auto first = entry * Abi::SamplerEntryElements; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(first) * 4u, 4u); + const auto words = guest.subspan(static_cast(first) * 4u, 4u); std::string rejected; - if (first + Abi::SamplerEntryElements > context.samplerTableCapacity) rejected = "the sampler table exceeds the device's capacity of " + std::to_string(context.samplerTableCapacity) + " samplers"; + if (!table.heap && first + Abi::SamplerEntryElements > context.samplerTableCapacity) rejected = "the sampler table exceeds the device's capacity of " + std::to_string(context.samplerTableCapacity) + " samplers"; for (std::uint32_t element = first; rejected.empty() && element < first + Abi::SamplerEntryElements; ++element) { try { - const auto elementWords = std::span(binding.guestDescriptor.data() + static_cast(element) * 4u, 4u); + const auto elementWords = std::span(guest.data() + static_cast(element) * 4u, 4u); auto resource = DecodeSamplerResource(elementWords); resource.compareEnable = binding.samplerDepthCompare.at(element); Sampler::Validate(context, resource); @@ -5064,7 +5207,7 @@ void ShaderResources::addSamplerTable(const ShaderRecompiler::DescriptorBinding& continue; } for (std::uint32_t element = first; element < first + Abi::SamplerEntryElements; ++element) { - const auto elementWords = std::span(binding.guestDescriptor).subspan(static_cast(element) * 4u, 4u); + const auto elementWords = guest.subspan(static_cast(element) * 4u, 4u); const bool compareEnable = binding.samplerDepthCompare.at(element); if (context.samplerCache != nullptr && !noSamplerCache) { samplers.push_back(context.samplerCache->Get(context, elementWords, compareEnable, false)); @@ -5079,12 +5222,16 @@ void ShaderResources::addSamplerTable(const ShaderRecompiler::DescriptorBinding& } const auto setSamplers = context.samplerTableUpdateAfterBind ? context.descriptorIndexingLimits.maxDescriptorSetUpdateAfterBindSamplers : context.limits.maxDescriptorSetSamplers; Require(samplers.size() <= setSamplers, "pipeline sampler descriptors exceed device limits"); + if (table.heap) { + table.tableSamplers = std::move(item.imageAllocations); + return; + } bindings.push_back(std::move(item)); } void ShaderResources::resolveImageTables() { const auto none = [](const std::array& set) { return set[0] == std::numeric_limits::max() && set[1] == std::numeric_limits::max(); }; - if (none(tableBindings) && none(storageTableBindings)) return; + if (none(tableBindings) && none(storageTableBindings) && std::none_of(tableStages.begin(), tableStages.end(), [](const TableStage& table) { return table.heap && table.images != nullptr; })) return; auto& counters = TextureCounts(); for (std::size_t set = 0; set < tableBindings.size(); ++set) { if (storageTableBindings[set] != std::numeric_limits::max()) bindings[storageTableBindings[set]].imageAllocations.assign(std::min(tableElements[set], StorageTableCapacity(context)), std::numeric_limits::max()); @@ -5092,11 +5239,12 @@ void ShaderResources::resolveImageTables() { } for (auto& table : tableStages) { if (table.images == nullptr) continue; - auto* item = tableBindings[table.set] != std::numeric_limits::max() ? &bindings[tableBindings[table.set]] : nullptr; + auto* item = !table.heap && tableBindings[table.set] != std::numeric_limits::max() ? &bindings[tableBindings[table.set]] : nullptr; const auto& binding = *table.images; const auto faults = table.map[ShaderRecompiler::ImageTableAbi::HeaderElementFaults]; const auto stageSamplers = std::span>(samplers).subspan(table.firstSampler, table.samplerCount); table.elementTextures.assign(binding.count, std::numeric_limits::max()); + if (table.heap) table.elementStorage.assign(binding.count, std::numeric_limits::max()); const auto capacityMessage = [&] { return "the image table exceeds the device's capacity of " + std::to_string(context.imageTableCapacity) + " images"; }; std::vector samplerKey; for (std::uint32_t sampler = 0; sampler < table.samplerCount; ++sampler) { @@ -5109,7 +5257,7 @@ void ShaderResources::resolveImageTables() { textureFirstLayer.push_back(firstLayer); describedRanges.push_back({"texture", resource.baseAddress, guestBytes, resource.width, resource.height, resource.format, static_cast(resource.tileMode), resource.dccAddress, true}); table.elementTextures[element] = textures.size() - 1u; - item->imageAllocations[static_cast(table.elementBase) + element] = textures.size() - 1u; + if (item != nullptr) item->imageAllocations[static_cast(table.elementBase) + element] = textures.size() - 1u; }; const auto bind = [&](std::uint32_t element, std::span words, std::shared_ptr texture, const GuestTextureResource& resource, std::uint64_t guestBytes, bool firstLayer) -> std::string { try { @@ -5136,14 +5284,14 @@ void ShaderResources::resolveImageTables() { const auto state = CurrentTableState(); std::vector> cached; const bool storageTable = std::find(binding.imageWritten.begin(), binding.imageWritten.end(), true) != binding.imageWritten.end(); - if (auto* reused = storageTable || item == nullptr ? nullptr : FindReusedTable(context.device, binding, state); reused != nullptr && TableCurrent(*reused) && CachedTableTextures(*reused, cached)) { + if (auto* reused = storageTable || item == nullptr ? nullptr : FindReusedTable(context.device, binding, table.imageWords, state); reused != nullptr && TableCurrent(*reused) && CachedTableTextures(*reused, cached)) { const bool replay = TableReplay() && reused->replayable && reused->imageSamplers == binding.imageSamplers && reused->samplers == samplerKey; if (!replay) reused->bound.assign(binding.count, {}); auto next = cached.begin(); for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = table.imageWords.subspan(static_cast(element) * 8u, 8u); const auto& entry = reused->elements[element]; - if (static_cast(table.elementBase) + element >= context.imageTableCapacity) { + if (!table.heap && static_cast(table.elementBase) + element >= context.imageTableCapacity) { if (!entry.rejected) ++next; table.map[faults + element] = rejectTableElement(table, words, capacityMessage()); } else if (entry.rejected) { @@ -5172,9 +5320,9 @@ void ShaderResources::resolveImageTables() { fresh.bound.assign(binding.count, {}); bool reusable = state.epoch != 0; for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = table.imageWords.subspan(static_cast(element) * 8u, 8u); const auto absolute = static_cast(table.elementBase) + element; - if (absolute >= context.imageTableCapacity) { + if (!table.heap && absolute >= context.imageTableCapacity) { table.map[faults + element] = rejectTableElement(table, words, capacityMessage()); reusable = false; continue; @@ -5201,11 +5349,11 @@ void ShaderResources::resolveImageTables() { if (element < binding.imageWritten.size() && binding.imageWritten[element]) { reusable = false; const auto storageBinding = storageTableBindings[table.set]; - if (storageBinding == std::numeric_limits::max()) { + if (!table.heap && storageBinding == std::numeric_limits::max()) { table.map[faults + element] = rejectTableElement(table, words, "set " + std::to_string(table.set) + " has no image storage table, but the shader stores to its table element " + std::to_string(absolute)); continue; } - if (absolute >= StorageTableCapacity(context)) { + if (!table.heap && absolute >= StorageTableCapacity(context)) { table.map[faults + element] = rejectTableElement(table, words, "the stored table element " + std::to_string(absolute) + " of set " + std::to_string(table.set) + " is past the image storage table's capacity of " + std::to_string(StorageTableCapacity(context)) + " images"); continue; } @@ -5229,10 +5377,11 @@ void ShaderResources::resolveImageTables() { storageAtomic.push_back(element < binding.imageAtomic.size() && binding.imageAtomic[element]); storageAtomic64.push_back(false); describedRanges.push_back({"storage", resource.baseAddress, guestBytes, resource.width, resource.height, resource.format, static_cast(resource.tileMode), resource.dccAddress, true}); - bindings[storageBinding].imageAllocations[absolute] = storageTextures.size() - 1u; + if (table.heap) table.elementStorage[element] = storageTextures.size() - 1u; + else bindings[storageBinding].imageAllocations[absolute] = storageTextures.size() - 1u; continue; } - if (item == nullptr) { + if (item == nullptr && !table.heap) { table.map[faults + element] = rejectTableElement(table, words, "a sampled image table entry has no sampled image table binding"); reusable = false; continue; @@ -5278,10 +5427,11 @@ void ShaderResources::resolveImageTables() { fresh.imageSamplers = binding.imageSamplers; fresh.samplers = std::move(samplerKey); fresh.replayable = static_cast(table.elementBase) + binding.count <= context.imageTableCapacity; - RememberTable(std::move(fresh), binding); + RememberTable(std::move(fresh), binding, table.imageWords); } } } + for (auto& table : tableStages) table.imageWords = {}; reportTextureCounters(); } @@ -5456,6 +5606,7 @@ void ShaderResources::release() noexcept { std::uint32_t ShaderResources::setOf(const Binding& binding) const { constexpr auto count = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count); if (binding.set >= 0) return static_cast(binding.set); + if (heapStage) return 0u; return splitSets && binding.layout.binding / count == static_cast(ShaderRecompiler::RuntimeAbi::Stage::Fragment) ? 1u : 0u; } @@ -5486,29 +5637,33 @@ ShaderResources::DrawBindings::~DrawBindings() { std::optional> ShaderResources::MovedReadOnlyBuffers(std::span shaders, Recorder& recorder) const { std::vector moved; - if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE) || usesBda) return moved; + if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE && !heapStage) || (usesBda && !spaceReuse)) return moved; for (const auto& shader : shaders) { if (shader.program == nullptr) return std::nullopt; + const bool heapShader = shader.program->gpuResolvedImages; for (const auto& binding : shader.program->bindings) { + if (heapShader && (DataRole(binding.role) || binding.role == ShaderRecompiler::DescriptorRole::GuestImages || binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers)) continue; if (DataRole(binding.role)) { const auto kept = std::find_if(bindings.begin(), bindings.end(), [&](const Binding& item) { return item.layout.binding == binding.binding; }); if (kept == bindings.end() || kept->allocations.size() != 1) return std::nullopt; const auto index = kept->allocations.front(); const auto& item = allocations[index]; - if (item.guest || item.buffer == nullptr || item.size != binding.guestDescriptor.size() * sizeof(std::uint32_t)) return std::nullopt; + const auto& guestWords = DrawGuestWords(shader, binding); + if (item.guest || item.buffer == nullptr || item.size != guestWords.size() * sizeof(std::uint32_t)) return std::nullopt; const bool patched = std::any_of(dataPatches.begin(), dataPatches.end(), [&](const DataPatch& patch) { return patch.allocation == index; }); - const bool same = !item.dataWords.empty() ? item.dataWords == binding.guestDescriptor : !patched && std::memcmp(item.buffer->Bytes().data(), binding.guestDescriptor.data(), item.size) == 0; + const bool same = !item.dataWords.empty() ? item.dataWords == guestWords : !patched && std::memcmp(item.buffer->Bytes().data(), guestWords.data(), item.size) == 0; if (same) continue; if (item.dataWords.empty() && patched) return std::nullopt; if (moved.empty()) moved.reserve(allocations.size()); - moved.push_back({index, 0, item.size, binding.guestDescriptor}); + moved.push_back({index, 0, item.size, guestWords}); continue; } if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; + const auto& guestWords = DrawGuestWords(shader, binding); const auto kept = std::find_if(bindings.begin(), bindings.end(), [&](const Binding& item) { return item.layout.binding == binding.binding; }); - if (kept == bindings.end() || kept->allocations.size() != binding.count || binding.guestDescriptor.size() != static_cast(binding.count) * 4u) return std::nullopt; + if (kept == bindings.end() || kept->allocations.size() != binding.count || guestWords.size() != static_cast(binding.count) * 4u) return std::nullopt; for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto* words = binding.guestDescriptor.data() + static_cast(element) * 4u; + const auto* words = guestWords.data() + static_cast(element) * 4u; const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; const auto address = descriptor.Base48(); const auto size = descriptor.GetSize(); @@ -5557,7 +5712,7 @@ std::optional> ShaderResources::MovedD }; std::vector moved; if (shader.program == nullptr || usesBda) return refuse(MoveRefusal::Shape); - if (_set == VK_NULL_HANDLE) return moved; + if (_set == VK_NULL_HANDLE && !heapStage) return moved; for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; const auto kept = std::find_if(bindings.begin(), bindings.end(), [&](const Binding& item) { return item.layout.binding == binding.binding; }); @@ -5607,7 +5762,7 @@ std::size_t ShaderResources::DrawUploadLimit() { } std::shared_ptr ShaderResources::PrepareDrawBindings(Recorder& recorder, std::span moved, bool movedOnly) const { - if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE) || usesBda) return {}; + if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE && !heapStage) || (usesBda && !spaceReuse)) return {}; thread_local std::vector>* readsSlot = nullptr; auto& reads = ShaderRecompiler::ThreadOwned(readsSlot); guestMemory.InPlaceReads(reads); @@ -5708,6 +5863,7 @@ std::shared_ptr ShaderResources::PrepareDrawBindi auto& counts = ShaderRecompiler::ThreadOwned(countsSlot); for (auto& sizes : counts) sizes.clear(); for (const auto& binding : bindings) { + if (binding.heap) continue; const auto set = setOf(binding); described[set] = true; const auto count = (binding.flags & VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT) != 0 ? std::max(1u, static_cast(binding.imageAllocations.size())) : binding.layout.descriptorCount; @@ -5726,7 +5882,7 @@ std::shared_ptr ShaderResources::PrepareDrawBindi result->layout = _layout; Require(result->allocation.set != VK_NULL_HANDLE, "draw snapshot descriptor allocation failed"); } - if (described[1] || splitSets) { + if (!heapStage && (described[1] || splitSets)) { result->fragmentAllocation = result->cache->AllocateRewritten(fragment.layout, sizesOf(1), updateAfterBind, variableOf(1)); result->fragmentLayout = fragment.layout; Require(result->fragmentAllocation.set != VK_NULL_HANDLE, "draw snapshot descriptor allocation failed"); @@ -5743,6 +5899,7 @@ std::shared_ptr ShaderResources::PrepareDrawBindi for (std::size_t index = 0; index < selected.size(); ++index) snapshotIndices[selected[index]] = index; auto nextWrite = writes.begin(); for (const auto& binding : bindings) { + if (binding.heap) continue; const auto original = setOf(binding) == 0 ? _set : fragment.set; while (nextWrite != writes.end() && nextWrite->dstBinding == binding.layout.binding && nextWrite->dstSet == original) { auto& write = *nextWrite++; @@ -5759,15 +5916,411 @@ std::shared_ptr ShaderResources::PrepareDrawBindi } } Require(nextWrite == writes.end(), "draw snapshot writes disagree with their descriptor bindings"); + if (addressedBuffers) { + std::vector overrides(allocations.size(), VkDescriptorBufferInfo{VK_NULL_HANDLE, 0, 0}); + bool overridden = false; + for (std::size_t index = 0; index < selected.size(); ++index) { + const auto& snapshot = result->snapshots[index]; + overrides[selected[index]] = {snapshot.buffer->Handle(), snapshot.offset, snapshot.bytes}; + } + for (const auto& binding : bindings) { + if (!binding.addressed) continue; + for (const auto allocation : binding.allocations) overridden = overridden || overrides[allocation].buffer != VK_NULL_HANDLE; + } + if (overridden) { + result->heapOffsets = addressedOffsets(&overrides); + result->addressOffsets = true; + result->addressOverrides = std::move(overrides); + } + } context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); recorder.Keep(result); for (const auto& snapshot : result->snapshots) recorder.KeepBytes(snapshot.buffer.get(), snapshot.buffer->Bytes().size()); return result; } +void ShaderResources::RefreshMovedAddresses(DrawBindings& rewritten) const { + if (rewritten.addressOffsets) rewritten.heapOffsets = addressedOffsets(&rewritten.addressOverrides); +} + +std::array ShaderResources::addressedOffsets(const std::vector* overrides) const { + auto offsets = heapOffsets; + auto& heap = BindlessHeap::For(context); + for (std::size_t stage = 0; stage < stageDataWords.size(); ++stage) { + if (stageDataWords[stage].empty()) continue; + auto words = stageDataWords[stage]; + writeBufferAddresses(words, static_cast(stage), overrides); + auto span = heap.Allocate(words.size()); + std::memcpy(span.words.data(), words.data(), words.size() * sizeof(std::uint32_t)); + offsets[stageDataIndex[stage]] = span.offset; + } + return offsets; +} + void ShaderResources::Bind(VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout) const { - if (_set != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, bindPoint, layout, 0, 1, &_set, 0, nullptr); - if (fragment.set != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, bindPoint, layout, ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragment.set, 0, nullptr); + if (_set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, bindPoint, layout, 0, 1, &_set); + if (fragment.set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, bindPoint, layout, ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragment.set); +} + +PipelineSetLayouts ShaderResources::SetLayouts() const { + if (!heapStage) return {_layout, fragment.layout, splitSets, layoutKey, fragmentLayoutKey}; + return {_layout, VK_NULL_HANDLE, true, layoutKey, fragmentLayoutKey}; +} + +void ShaderResources::RefreshHeapStage(std::span shaders) { + for (const auto& shader : shaders) { + if (shader.program != nullptr && shader.program->gpuResolvedImages) writeHeapStage(shader); + } +} + +void ShaderResources::writeBufferAddresses(std::span words, std::uint32_t dataStage, const std::vector* overrides) const { + thread_local VkDevice addressDevice = VK_NULL_HANDLE; + thread_local PFN_vkGetBufferDeviceAddressKHR bufferAddress = nullptr; + if (addressDevice != context.device || bufferAddress == nullptr) { + bufferAddress = context.Function("vkGetBufferDeviceAddressKHR"); + addressDevice = context.device; + } + for (const auto& binding : bindings) { + if (!binding.addressed || binding.dataStage != dataStage) continue; + for (std::size_t element = 0; element < binding.allocations.size(); ++element) { + const auto index = binding.allocations[element]; + auto info = overrides != nullptr && (*overrides)[index].buffer != VK_NULL_HANDLE ? (*overrides)[index] : const_cast(this)->descriptor(const_cast(allocations[index])); + if (info.buffer == VK_NULL_HANDLE) info = {context.emptyBuffer, 0, EmptyBufferBytes}; + const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, info.buffer}; + const auto base = bufferAddress(context.device, &addressInfo); + Require(base != 0, "an addressed buffer has no device address"); + const auto address = base + info.offset; + const auto at = static_cast(binding.addressDword) + element * 4u; + Require(at + 3u < words.size(), "buffer address words lie outside the shader data"); + words[at] = static_cast(address); + words[at + 1u] = static_cast(address >> 32u); + words[at + 2u] = static_cast(std::min(info.range, 0xffffffffu)); + words[at + 3u] = 0u; + } + } +} + +namespace { + +std::size_t DataOffsetIndex(std::size_t stage, ShaderRecompiler::RuntimeAbi::Binding binding) { + Require(binding == ShaderRecompiler::RuntimeAbi::Binding::ShaderData || binding == ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt, "only shader data and the flattened SRT have ring offsets"); + return stage * 2u + (binding == ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt ? 1u : 0u); +} + +} + +void ShaderResources::PatchDataAddresses(std::span bytes, std::span shaders, const DrawBindings* rewritten) const { + namespace Abi = ShaderRecompiler::RuntimeAbi; + if (!heapStage) return; + const auto& offsets = rewritten != nullptr && rewritten->addressOffsets ? rewritten->heapOffsets : heapOffsets; + VkDeviceAddress ring = 0; + VkDeviceAddress table = 0; + VkDeviceAddress fault = 0; + std::uint32_t tableDwords = 0; + const auto binds = [&](ShaderRecompiler::DescriptorRole role) { + return std::any_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [&](const auto& binding) { return binding.role == role; }); }); + }; + const bool tableBound = binds(ShaderRecompiler::DescriptorRole::BdaPagetable); + const bool faultBound = binds(ShaderRecompiler::DescriptorRole::FaultBuffer); + if (bda != nullptr && (tableBound || faultBound)) { + const auto address = context.Function("vkGetBufferDeviceAddressKHR"); + const auto of = [&](const VkDescriptorBufferInfo& info) { + const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, info.buffer}; + const auto base = address(context.device, &addressInfo); + Require(base != 0, "a BDA buffer has no device address"); + return base + info.offset; + }; + if (tableBound) { + const auto tableInfo = bda->Table(); + table = of(tableInfo); + tableDwords = static_cast(tableInfo.range / sizeof(std::uint32_t)); + } + if (faultBound) fault = of(bda->Fault()); + } + std::array root{}; + bool rooted = false; + for (const auto& shader : shaders) { + if (shader.program == nullptr || !shader.program->dataAddressPush) continue; + if (ring == 0) ring = BindlessHeap::For(context).RingAddress(); + const auto stage = HeapStageIndex(shader.stage); + const auto record = [&](Abi::RootStageField field) -> std::uint32_t& { return root[Abi::RootStageDword(static_cast(stage), field)]; }; + record(Abi::RootStageField::ShaderData) = offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]; + record(Abi::RootStageField::FlattenedSrt) = offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)]; + record(Abi::RootStageField::SrtDwords) = heapSrtDwords[stage]; + record(Abi::RootStageField::TableMap) = heapTableMapSet[stage] ? heapTableMaps[stage] : 0u; + rooted = true; + } + if (!rooted) return; + const auto split = [&](std::uint32_t at, VkDeviceAddress address) { + root[at] = static_cast(address); + root[at + 1u] = static_cast(address >> 32u); + }; + split(Abi::RootRingAddress, ring); + split(Abi::RootPagetableAddress, table); + split(Abi::RootFaultAddress, fault); + root[Abi::RootPagetableDwords] = tableDwords; + if (gdsAllocation != std::numeric_limits::max()) { + const auto* overrides = rewritten != nullptr && rewritten->addressOffsets ? &rewritten->addressOverrides : nullptr; + auto info = overrides != nullptr && (*overrides)[gdsAllocation].buffer != VK_NULL_HANDLE ? (*overrides)[gdsAllocation] : const_cast(this)->descriptor(const_cast(allocations[gdsAllocation])); + Require(info.buffer != VK_NULL_HANDLE, "the GDS buffer is missing"); + const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, info.buffer}; + const auto base = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + Require(base != 0, "the GDS buffer has no device address"); + split(Abi::RootGdsAddress, base + info.offset); + } + std::memcpy(&root[Abi::RootStencilReference], bytes.data() + (Abi::RootDword + Abi::RootStencilReference) * sizeof(std::uint32_t), sizeof(std::uint32_t)); + static_assert((Abi::RootDword + Abi::RootDwords) * sizeof(std::uint32_t) <= PipelinePushConstantBytes); + std::memcpy(bytes.data() + Abi::RootDword * sizeof(std::uint32_t), root.data(), sizeof(root)); + NoteDataAddressPush(); +} + +void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_t stageIndex) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + namespace TableAbi = ShaderRecompiler::ImageTableAbi; + heapTableMapSet[stageIndex] = false; + const auto table = std::find_if(tableStages.begin(), tableStages.end(), [&](const TableStage& candidate) { return candidate.program == shader.program && candidate.heap; }); + if (table == tableStages.end() || table->mapAllocation == std::numeric_limits::max()) return; + auto& heap = BindlessHeap::For(context); + struct MapStorage {}; + auto& map = HostThreadLocal, MapStorage>(); + map.assign(table->map.begin(), table->map.end()); + const auto elements = table->images != nullptr ? static_cast(table->images->count) : std::size_t{0}; + const auto base = static_cast(map.size()); + map[TableAbi::HeaderElementBase] = base; + const auto sampledAbsent = heap.AbsentSlot(Abi::FirstImageBinding, context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(Abi::FirstImageBinding)); + const auto storageAbsent = heap.AbsentSlot(Abi::FirstStorageImageBinding, context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(Abi::FirstStorageImageBinding)); + for (std::size_t element = 0; element < elements; ++element) { + const auto index = element < table->elementTextures.size() ? table->elementTextures[element] : std::numeric_limits::max(); + if (index == std::numeric_limits::max()) { + map.push_back(sampledAbsent); + continue; + } + const auto view = textureFirstLayer[index] ? textures[index]->FirstLayerView() : textures[index]->View(); + const auto slot = heap.TextureSlot(Abi::FirstImageBinding, textures[index], view, textures[index]->Layout()); + Require(slot.has_value(), "the global image heap is full"); + map.push_back(*slot); + } + for (std::size_t element = 0; element < elements; ++element) { + const auto index = element < table->elementStorage.size() ? table->elementStorage[element] : std::numeric_limits::max(); + if (index == std::numeric_limits::max() || storageTextures[index] == nullptr) { + map.push_back(storageAbsent); + continue; + } + const auto slot = heap.StorageSlot(Abi::FirstStorageImageBinding, storageTextures[index], storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index])); + Require(slot.has_value(), "the global storage image heap is full"); + map.push_back(*slot); + } + std::uint32_t fallbackSampler = 0; + for (const auto index : table->tableSamplers) { + if (index == std::numeric_limits::max()) continue; + const auto slot = heap.SamplerSlot(samplers[index]); + Require(slot.has_value(), "the global sampler heap is full"); + fallbackSampler = *slot; + break; + } + for (const auto index : table->tableSamplers) { + if (index == std::numeric_limits::max()) { + map.push_back(fallbackSampler); + continue; + } + const auto slot = heap.SamplerSlot(samplers[index]); + Require(slot.has_value(), "the global sampler heap is full"); + map.push_back(*slot); + } + if (map.size() == base) map.push_back(sampledAbsent); + auto span = heap.Allocate(map.size()); + std::memcpy(span.words.data(), map.data(), map.size() * sizeof(std::uint32_t)); + heapTableMaps[stageIndex] = static_cast(span.offset); + heapTableMapSet[stageIndex] = true; +} + +void ShaderResources::writeHeapStage(const CompiledShader& shader) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + auto& heap = BindlessHeap::For(context); + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + const VkShaderStageFlags stageBit = VulkanStage(shader.stage); + const auto stageIndex = HeapStageIndex(shader.stage); + auto& stageState = heapStages[stageIndex]; + const auto ownHeap = [&](const Binding& binding) { return binding.heap && (binding.layout.stageFlags & stageBit) != 0u; }; + struct HeapKeyStorage {}; + auto& key = HostThreadLocal, HeapKeyStorage>(); + key.clear(); + for (const auto& binding : bindings) { + if (!ownHeap(binding)) continue; + if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) { + for (const auto index : binding.imageAllocations) { + if (index == std::numeric_limits::max()) { + key.push_back(0u); + continue; + } + const auto view = textureSrgb[index] ? textures[index]->SrgbView(textureFirstLayer[index], textureBaseLevel[index]) : textureBaseLevel[index] ? textures[index]->BaseLevelView() : textureFirstLayer[index] ? textures[index]->FirstLayerView() : textures[index]->View(); + key.insert(key.end(), {reinterpret_cast(textures[index].get()), reinterpret_cast(view), static_cast(textures[index]->Layout())}); + } + } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { + for (const auto index : binding.imageAllocations) { + if (index == std::numeric_limits::max() || storageTextures[index] == nullptr) { + key.push_back(0u); + continue; + } + key.insert(key.end(), {reinterpret_cast(storageTextures[index].get()), reinterpret_cast(storageAtomic64[index] ? storageTextures[index]->Atomic64View(storageMips[index], storageFirstLayer[index]) : storageAtomic[index] ? storageTextures[index]->AtomicView(storageMips[index], storageFirstLayer[index]) : storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index])), static_cast(VK_IMAGE_LAYOUT_GENERAL)}); + } + } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { + for (const auto index : binding.imageAllocations) key.push_back(reinterpret_cast(samplers[index].get())); + } + } + bool current = key == stageState.key; + const auto slotSerial = heap.SlotSerial(); + const bool unmoved = current && EpochProofs() && stageState.slotSerial == slotSerial; + if (!unmoved && current && CommitTrims()) { + current = heap.GenerationsCurrent(stageState.slots, stageState.slotGenerations, stageState.samplerSlots, stageState.samplerGenerations); + } else if (!unmoved && current) { + std::size_t generation = 0; + for (std::uint32_t kind = 0; current && kind < stageState.slots.size(); ++kind) { + for (const auto slot : stageState.slots[kind]) { + if (!current) break; + current = generation < stageState.slotGenerations.size() && heap.SlotGeneration(kind, slot) == stageState.slotGenerations[generation++]; + } + } + for (std::size_t i = 0; current && i < stageState.samplerSlots.size(); ++i) current = i < stageState.samplerGenerations.size() && heap.SamplerGeneration(stageState.samplerSlots[i]) == stageState.samplerGenerations[i]; + } + if (!current) { + stageState.key = key; + for (auto& kindSlots : stageState.slots) kindSlots.clear(); + stageState.samplerSlots.clear(); + std::size_t cursor = 0; + for (const auto& binding : bindings) { + if (!ownHeap(binding)) continue; + const auto kind = binding.layout.binding % bindingCount; + if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) { + auto& kindSlots = stageState.slots[kind]; + for (const auto index : binding.imageAllocations) { + if (index == std::numeric_limits::max()) { + ++cursor; + kindSlots.push_back(heap.AbsentSlot(kind, context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(kind))); + continue; + } + const auto view = reinterpret_cast(key[cursor + 1]); + cursor += 3; + const auto slot = heap.TextureSlot(kind, textures[index], view, textures[index]->Layout()); + Require(slot.has_value(), "the global image heap is full"); + kindSlots.push_back(*slot); + } + } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { + auto& kindSlots = stageState.slots[kind]; + for (const auto index : binding.imageAllocations) { + if (index == std::numeric_limits::max() || storageTextures[index] == nullptr) { + ++cursor; + kindSlots.push_back(heap.AbsentSlot(kind, context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(kind))); + continue; + } + const auto view = reinterpret_cast(key[cursor + 1]); + cursor += 3; + const auto slot = heap.StorageSlot(kind, storageTextures[index], view); + Require(slot.has_value(), "the global storage image heap is full"); + kindSlots.push_back(*slot); + } + } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { + for (const auto index : binding.imageAllocations) { + ++cursor; + const auto slot = heap.SamplerSlot(samplers[index]); + Require(slot.has_value(), "the global sampler heap is full"); + stageState.samplerSlots.push_back(*slot); + } + } + } + } + if (current) stageState.slotSerial = slotSerial; + if (!current) { + stageState.slotSerial = 0; + stageState.slotGenerations.clear(); + for (std::uint32_t kind = 0; kind < stageState.slots.size(); ++kind) { + for (const auto slot : stageState.slots[kind]) stageState.slotGenerations.push_back(heap.SlotGeneration(kind, slot)); + } + stageState.samplerGenerations.clear(); + for (const auto slot : stageState.samplerSlots) stageState.samplerGenerations.push_back(heap.SamplerGeneration(slot)); + stageState.slotSerial = slotSerial; + } + const auto& slots = stageState.slots; + const auto& samplerSlots = stageState.samplerSlots; + static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + if (verifySlots) { + static std::atomic checked{0}, wrong{0}; + for (const auto& binding : bindings) { + if (!ownHeap(binding) || binding.layout.descriptorType != VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) continue; + const auto kind = binding.layout.binding % bindingCount; + for (std::size_t element = 0; element < binding.imageAllocations.size(); ++element) { + const auto index = binding.imageAllocations[element]; + if (index == std::numeric_limits::max()) continue; + ++checked; + if (element >= stageState.slots[kind].size() || heap.SlotTexture(kind, stageState.slots[kind][element]) != textures[index].get()) ++wrong; + } + } + if (checked.load() % 100000u < 8u) std::fprintf(stderr, "[heap-slots] verify: %llu image slots checked, %llu hold another texture\n", static_cast(checked.load()), static_cast(wrong.load())); + } + const std::size_t dataIndex = DataOffsetIndex(stageIndex, Abi::Binding::ShaderData); + const std::size_t flatIndex = DataOffsetIndex(stageIndex, Abi::Binding::FlattenedSrt); + const auto& program = *shader.program; + if (program.dataAddressPush) writeHeapTableMap(shader, stageIndex); + for (const auto& binding : program.bindings) { + if (binding.role != ShaderRecompiler::DescriptorRole::ShaderData && binding.role != ShaderRecompiler::DescriptorRole::FlattenedSrt) continue; + const auto& words = binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt && shader.heap != nullptr && !shader.heap->flattenedSrt.empty() ? shader.heap->flattenedSrt : DrawGuestWords(shader, binding); + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, words); + auto span = heap.Allocate(words.size()); + if (binding.role != ShaderRecompiler::DescriptorRole::ShaderData) { + std::memcpy(span.words.data(), words.data(), words.size() * sizeof(std::uint32_t)); + heapOffsets[flatIndex] = span.offset; + heapSrtDwords[stageIndex] = static_cast(words.size()); + continue; + } + struct PatchedStorage {}; + auto& patched = HostThreadLocal, PatchedStorage>(); + patched.assign(words.begin(), words.end()); + if (shader.heap != nullptr) std::copy_n(shader.heap->userData.begin(), std::min(shader.heap->userData.size(), patched.size()), patched.begin()); + for (const auto& [byte, adjustment] : stageState.dataPatches) { + Require(byte < patched.size() * sizeof(std::uint32_t), "a GPU-mode guest buffer offset lies outside the shader data"); + reinterpret_cast(patched.data())[byte] = static_cast(adjustment); + } + { + constexpr auto metadataWords = sizeof(Abi::ResourceMetadata) / sizeof(std::uint32_t); + for (std::uint32_t image = 0; image < program.runtimeImageCount; ++image) { + const auto offset = program.imageMetadataDword + image * metadataWords; + const auto kind = patched[offset + offsetof(Abi::ResourceMetadata, binding) / 4u] % bindingCount; + if (kind >= Abi::FirstStorageImageBinding && kind < static_cast(Abi::Binding::Samplers) && (!Abi::GpuHeapStorageKind(kind) || slots[kind].empty())) continue; + auto& first = patched[offset + offsetof(Abi::ResourceMetadata, firstElement) / 4u]; + if (kind < Abi::FirstImageBinding) continue; + if (!(kind < slots.size() && first < slots[kind].size())) { + char text[320]; + std::snprintf(text, sizeof(text), "AGC graphics: GPU-mode image metadata names an element the stage does not bind (stage %u, image %u of %u, kind %u, first %u, slots of the kind %zu, flags 0x%x, element count %u, bindings %zu, stage state reused %d)", static_cast(shader.stage), image, program.runtimeImageCount, kind, first, kind < slots.size() ? slots[kind].size() : std::size_t{0}, patched[offset + offsetof(Abi::ResourceMetadata, flags) / 4u], patched[offset + offsetof(Abi::ResourceMetadata, elementCount) / 4u], bindings.size(), current ? 1 : 0); + throw std::runtime_error(text); + } + first = slots[kind][first]; + } + const bool slotWords = !program.registrationModule; + for (const auto& word : program.heapSlotWords) { + Require(word.dword < patched.size(), "a GPU-mode slot word lies outside the shader data"); + if (word.kind == static_cast(Abi::Binding::Samplers)) { + Require(word.element < samplerSlots.size(), "a GPU-mode slot word names a sampler the stage does not bind"); + patched[word.dword] = samplerSlots[word.element]; + continue; + } + if (!(word.kind < slots.size() && word.element < slots[word.kind].size())) { + char text[256]; + std::snprintf(text, sizeof(text), "AGC graphics: a GPU-mode slot word names an image the stage does not bind (stage %u, kind %u, element %u, slots of the kind %zu, bindings %zu)", static_cast(shader.stage), word.kind, word.element, word.kind < slots.size() ? slots[word.kind].size() : std::size_t{0}, bindings.size()); + throw std::runtime_error(text); + } + patched[word.dword] = slots[word.kind][word.element]; + } + Require(slotWords || program.samplerSlotDword + samplerSlots.size() <= patched.size(), "GPU-mode sampler slots exceed the shader data"); + if (!slotWords) std::copy(samplerSlots.begin(), samplerSlots.end(), patched.begin() + program.samplerSlotDword); + if (addressedBuffers) { + writeBufferAddresses(patched, static_cast(stageIndex), nullptr); + stageDataWords[stageIndex].assign(patched.begin(), patched.end()); + stageDataIndex[stageIndex] = dataIndex; + } + std::memcpy(span.words.data(), patched.data(), patched.size() * sizeof(std::uint32_t)); + heapOffsets[dataIndex] = span.offset; + } + } } namespace { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index 7dd97e43708e..536370a26cac 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -244,10 +244,11 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi capability == spv::CapabilitySignedZeroInfNanPreserve; const bool isBdaCapability = - shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version && - (capability == spv::CapabilityInt64 || - capability == spv::CapabilityPhysicalStorageBufferAddresses || - capability == spv::CapabilityStorageBuffer8BitAccess); + (shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version && + (capability == spv::CapabilityInt64 || + capability == spv::CapabilityPhysicalStorageBufferAddresses || + capability == spv::CapabilityStorageBuffer8BitAccess)) || + ((shader.bufferAddressCount != 0u || shader.dataAddressPush) && (capability == spv::CapabilityInt64 || capability == spv::CapabilityPhysicalStorageBufferAddresses)); const bool isTessellationCapability = (control || evaluation) && @@ -358,7 +359,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi terminateExtension = true; break; } - Require(extension == "SPV_KHR_float_controls" || (imageInt64Atomics && extension == "SPV_EXT_shader_image_int64") || (viewportIndexLayer && extension == "SPV_EXT_shader_viewport_index_layer") || (fragment && demoteToHelperInvocation && extension == "SPV_EXT_demote_to_helper_invocation") || (mesh && (extension == "SPV_EXT_mesh_shader" || extension == "SPV_KHR_physical_storage_buffer")) || (fragment && !primitiveLocations.empty() && extension == "SPV_EXT_mesh_shader") || ((descriptorIndexing || runtimeDescriptorArray) && extension == "SPV_EXT_descriptor_indexing") || (shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version && (extension == "SPV_KHR_physical_storage_buffer" || extension == "SPV_KHR_8bit_storage")), "unsupported SPIR-V extension"); + Require(extension == "SPV_KHR_float_controls" || (imageInt64Atomics && extension == "SPV_EXT_shader_image_int64") || (viewportIndexLayer && extension == "SPV_EXT_shader_viewport_index_layer") || (fragment && demoteToHelperInvocation && extension == "SPV_EXT_demote_to_helper_invocation") || (mesh && (extension == "SPV_EXT_mesh_shader" || extension == "SPV_KHR_physical_storage_buffer")) || (fragment && !primitiveLocations.empty() && extension == "SPV_EXT_mesh_shader") || ((descriptorIndexing || runtimeDescriptorArray) && extension == "SPV_EXT_descriptor_indexing") || (shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version && (extension == "SPV_KHR_physical_storage_buffer" || extension == "SPV_KHR_8bit_storage")) || ((shader.bufferAddressCount != 0u || shader.dataAddressPush) && extension == "SPV_KHR_physical_storage_buffer"), "unsupported SPIR-V extension"); break; } case spv::OpTerminateInvocation: @@ -563,7 +564,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi } } } else if (variable.storage == spv::StorageClassPushConstant) { - Require(!push && (!shader.pushConstants.empty() || shader.readsDepthRemapPush || mesh || (control && !rectListControl)) && (type[0] & 0xffffu) == spv::OpTypeStruct, "invalid push constant interface"); + Require(!push && (!shader.pushConstants.empty() || shader.readsDepthRemapPush || shader.dataAddressPush || mesh || (control && !rectListControl)) && (type[0] & 0xffffu) == spv::OpTypeStruct, "invalid push constant interface"); push = true; Require(type.size() == 3 && module.decorations[typeId].block, "push constant variable must be a Block struct with exactly one member"); const auto offset = module.offsets.find({typeId, 0}); @@ -571,7 +572,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi const auto& array = module.Type(type[2]); Require(array.size() == 4 && (array[0] & 0xffffu) == spv::OpTypeArray && module.Signature(array[2]) == "u32", "push constant member must be an array of u32"); const auto length = module.constants.find(array[3]); - Require(length != module.constants.end() && length->second == PipelinePushSlotBytes / 4, "push constant array must contain 32 elements"); + Require(length != module.constants.end() && length->second == (shader.dataAddressPush ? ShaderRecompiler::RuntimeAbi::PushDataDwords : PipelinePushSlotBytes / 4), "push constant array must contain 32 elements"); const auto stride = module.decorations[type[2]].stride; Require(stride.has_value() && *stride == 4, "push constant array must have an ArrayStride of 4"); } else if (variable.storage == spv::StorageClassWorkgroup) { @@ -580,7 +581,20 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi Require(decoration.set && decoration.binding, "unbound shader resource"); const auto key = std::make_pair(*decoration.set, *decoration.binding); const auto binding = std::find_if(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { return item.descriptorSet == key.first && item.binding == key.second; }); - Require(descriptors.insert(key).second || (binding != shader.bindings.end() && (binding->role == ShaderRecompiler::DescriptorRole::ImageTable || binding->role == ShaderRecompiler::DescriptorRole::ImageStorageTable)), "duplicate SPIR-V resource binding"); + bool tableAlias = false; + { + namespace Abi = ShaderRecompiler::RuntimeAbi; + const bool tables = shader.dataAddressPush && std::any_of(shader.bindings.begin(), shader.bindings.end(), [](const auto& item) { return item.role == ShaderRecompiler::DescriptorRole::ImageTable || item.role == ShaderRecompiler::DescriptorRole::ImageStorageTable || item.role == ShaderRecompiler::DescriptorRole::SamplerTable; }); + const bool samplerAlias = key.second == Abi::BindingNumber(Abi::Stage::Fragment, Abi::Binding::Samplers); + const bool imageAlias = key.second == Abi::BindingNumber(Abi::Stage::Fragment, static_cast(Abi::FirstImageBinding)) || key.second == Abi::BindingNumber(Abi::Stage::Fragment, static_cast(Abi::FirstStorageImageBinding)); + tableAlias = tables && key.first == Abi::FragmentDescriptorSet && (samplerAlias || imageAlias); + if (tableAlias && binding == shader.bindings.end()) { + const auto count = type.size() == 4 && (type[0] & 0xffffu) == spv::OpTypeArray ? module.constants.find(type[3]) : module.constants.end(); + Require(count != module.constants.end() && count->second == (samplerAlias ? Abi::GpuSamplerHeapSlots : Abi::GpuImageHeapSlots), "an image table's heap array length disagrees with the global heap"); + continue; + } + } + Require(descriptors.insert(key).second || tableAlias || (binding != shader.bindings.end() && (binding->role == ShaderRecompiler::DescriptorRole::ImageTable || binding->role == ShaderRecompiler::DescriptorRole::ImageStorageTable)), "duplicate SPIR-V resource binding"); Require(binding != shader.bindings.end(), "SPIR-V resource is absent from recompiler binding metadata"); Require(binding->kind == ShaderRecompiler::DescriptorKind::Sampler || binding->kind == ShaderRecompiler::DescriptorKind::SampledImage || binding->kind == ShaderRecompiler::DescriptorKind::StorageImage, "SPIR-V descriptor type disagrees with recompiler binding metadata"); if (binding->role == ShaderRecompiler::DescriptorRole::ImageTable || binding->role == ShaderRecompiler::DescriptorRole::ImageStorageTable || binding->role == ShaderRecompiler::DescriptorRole::SamplerTable) { @@ -591,7 +605,13 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi const auto heap = static_cast(binding->binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)); const auto capacity = ShaderRecompiler::RuntimeAbi::HeapCapacity(heap); const auto count = module.constants.find(type[3]); - Require(binding->count != 0u && binding->count <= capacity && count != module.constants.end() && count->second == binding->count, "typed heap array length disagrees with compact binding"); + const bool heapArray = binding->kind != ShaderRecompiler::DescriptorKind::StorageImage || (ShaderRecompiler::RuntimeAbi::GpuHeapStorageKind(static_cast(heap)) && binding->descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet); + if (shader.gpuResolvedImages && heapArray) { + const auto slots = binding->kind == ShaderRecompiler::DescriptorKind::Sampler ? ShaderRecompiler::RuntimeAbi::GpuSamplerHeapSlots : ShaderRecompiler::RuntimeAbi::GpuImageHeapSlots; + Require(binding->count != 0u && count != module.constants.end() && count->second == slots, "GPU-mode heap array length disagrees with the global heap"); + } else { + Require(binding->count != 0u && binding->count <= capacity && count != module.constants.end() && count->second == binding->count, "typed heap array length disagrees with compact binding"); + } } else { Require(variable.storage == spv::StorageClassStorageBuffer && decoration.set && decoration.binding, "unsupported or unbound shader resource"); const auto key = std::make_pair(*decoration.set, *decoration.binding); @@ -599,7 +619,8 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi Require(fragment && *decoration.binding == 0u, "pixel function LDS buffer binding is wrong"); continue; } - const auto binding = std::find_if(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { return item.descriptorSet == key.first && item.binding == key.second; }); + const bool gpuData = shader.gpuResolvedImages && key.first == ShaderRecompiler::RuntimeAbi::GpuDataSet; + const auto binding = std::find_if(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { return (gpuData || item.descriptorSet == key.first) && item.binding == key.second; }); const bool array = binding != shader.bindings.end() && binding->role == ShaderRecompiler::DescriptorRole::GuestBuffers; const auto [view, first] = bufferViews.emplace(key, decoration.aliased); Require(descriptors.insert(key).second || (!first && view->second && decoration.aliased && array), "duplicate SPIR-V resource binding"); @@ -638,8 +659,9 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi } else { Require(shader.vertexAttributes.empty(), "vertex attribute metadata is invalid for this stage"); } - Require(descriptors.size() == shader.bindings.size(), "recompiler binding metadata contains undeclared resources"); - Require(push == (!shader.pushConstants.empty() || shader.readsDepthRemapPush || mesh || (control && !rectListControl && !barycentricPatches)), "recompiler push constant metadata disagrees with SPIR-V"); + const auto addressedBindings = static_cast(std::count_if(shader.bindings.begin(), shader.bindings.end(), [&](const ShaderRecompiler::DescriptorBinding& binding) { return (shader.bufferAddressCount != 0u && binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers) || (shader.dataAddressPush && (binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt || binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable || binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer || binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable || binding.role == ShaderRecompiler::DescriptorRole::SamplerTable || binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap)); })); + Require(descriptors.size() + addressedBindings == shader.bindings.size(), "recompiler binding metadata contains undeclared resources"); + Require(push == (!shader.pushConstants.empty() || shader.readsDepthRemapPush || shader.dataAddressPush || mesh || (control && !rectListControl && !barycentricPatches)), "recompiler push constant metadata disagrees with SPIR-V"); for (const auto id : module.interface) Require(module.variables.contains(id), "entry point interface contains an unknown variable"); if (mesh) Require(module.primitiveIndices == state.stages.mesh->outputPrimitiveSize, "mesh shader does not export primitive indices"); if (fragment) Require(module.primitiveInputs == 0 || !primitiveLocations.empty(), "per-primitive pixel inputs need the barycentric emulation layout"); @@ -699,7 +721,7 @@ std::set ValidateShaders(std::span shaders, const auto expected = state.rectList || patches ? (i == 0 ? Stage::Vertex : tessStages[i]) : tessellation ? tessStages[i] : geometry && i == 1 ? Stage::Geometry : i == shaders.size() - 1 ? Stage::Fragment : state.stages.path == ShaderPath::Geometry ? Stage::Mesh : Stage::Vertex; Require(shaders[i].program != nullptr, "missing compiled shader"); Require(shaders[i].stage == expected, "graphics stage order disagrees"); - for (const auto& binding : shaders[i].program->bindings) Require(binding.descriptorSet == ShaderRecompiler::RuntimeAbi::DescriptorSet || (shaders[i].stage == ShaderRecompiler::ShaderStage::Fragment && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet), "graphics resource uses a descriptor set other than its stage's"); + for (const auto& binding : shaders[i].program->bindings) Require(binding.descriptorSet == ShaderRecompiler::RuntimeAbi::DescriptorSet || (shaders[i].program->dataAddressPush && binding.role == ShaderRecompiler::DescriptorRole::Gds && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::GpuGdsSet) || ((shaders[i].stage == ShaderRecompiler::ShaderStage::Fragment || shaders[i].program->gpuResolvedImages) && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet), "graphics resource uses a descriptor set other than its stage's"); const auto current = Inspect(shaders[i], state, subgroup, fragmentShaderBarycentric, descriptorIndexing, imageInt64Atomics, geometryShader, sampleRateShading, bufferInt64Atomics, shaderClipDistance, shaderCullDistance, viewportIndexLayer, runtimeDescriptorArray, demoteToHelperInvocation, shaderTerminateInvocation, primitiveLocations); if (i != 0) { for (const auto& [location, signature] : current.inputs) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index d8394b6c5e8e..61bb0cd0073e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -10,6 +10,7 @@ #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" // For the declaration of PendingStorageOverlaps, defined below. diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index 344d80c59467..1442273a2cfd 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureSwizzleEquations.hpp" @@ -238,7 +239,7 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode writes[1].pBufferInfo = &destinationInfo; context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, 0, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set); Push push{}; push.srcBase = static_cast(sourceBase); push.dstBase = static_cast(destinationBase); @@ -303,7 +304,7 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s } context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, repackPipeline); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, 0, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set); const std::array push{static_cast(sourceOffset - sourceDescriptorOffset), static_cast(destinationOffset - destinationDescriptorOffset), static_cast(words), static_cast(std::min(words, rowWords))}; context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); context.Function("vkCmdDispatch")(commands, static_cast((std::min(words, rowWords) + 63u) / 64u), static_cast(rows), 1); @@ -385,7 +386,7 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask constexpr VkAccessFlags anyAccess = anyWrite | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_HOST_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT; barrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, anyWrite, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipeline); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipelineLayout, 0, 1, &set, 0, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipelineLayout, 0, 1, &set); const std::uint32_t mask = elementBytes >= 4 ? 0xffffffffu : (1u << (elementBytes * 8u)) - 1u; const std::array push{static_cast(base), width, height, (width + 1023u) / 1024u, clearWords[0] & mask, elementBytes == 8 ? clearWords[1] : 0u, write ? 1u : 0u}; context.Function("vkCmdPushConstants")(commands, cmaskPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); @@ -428,7 +429,7 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til writes[1].pImageInfo = &imageInfo; context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0, 1, &set, 0, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0, 1, &set); Push push{}; push.srcBase = static_cast(retile ? 0 : base); push.dstBase = static_cast(retile ? base : 0); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp index 94b065530591..641d73649b32 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/UnitShadow.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/SlimMutex.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" @@ -192,12 +193,16 @@ std::shared_ptr makeSlab(const Context& context, std::uint64_t first VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = static_cast(units) * UnitBytes; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + const bool addressable = BufferPool::ForceAddresses() && context.bufferDeviceAddress; + if (addressable) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VkBuffer buffer = VK_NULL_HANDLE; if (context.Function("vkCreateBuffer")(context.device, &info, nullptr, &buffer) != VK_SUCCESS) return nullptr; VkMemoryRequirements requirements{}; context.Function("vkGetBufferMemoryRequirements")(context.device, buffer, &requirements); VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + const VkMemoryAllocateFlagsInfo addressFlags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, nullptr, VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, 0}; + if (addressable) allocation.pNext = &addressFlags; allocation.allocationSize = requirements.size; VkDeviceMemory memory = VK_NULL_HANDLE; try { diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp b/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp index ad805c3f66ad..fd6aadb9db7f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp @@ -13,109 +13,6 @@ namespace { -struct ScanWords { - std::vector words; - void Op(spv::Op opcode, std::initializer_list operands) { - words.push_back((static_cast(operands.size() + 1u) << 16u) | static_cast(opcode)); - words.insert(words.end(), operands.begin(), operands.end()); - } - void OpString(spv::Op opcode, std::initializer_list operands, const char* text) { - std::vector packed((std::strlen(text) + 4u) / 4u, 0u); - std::memcpy(packed.data(), text, std::strlen(text)); - words.push_back((static_cast(operands.size() + packed.size() + 1u) << 16u) | static_cast(opcode)); - words.insert(words.end(), operands.begin(), operands.end()); - words.insert(words.end(), packed.begin(), packed.end()); - } -}; - -enum ScanId : std::uint32_t { - IdVoid = 1, IdVoidFunction, IdUint, IdUlong, IdUintPointer, IdAddress, IdOne, IdDeviceScope, IdNoSemantics, IdPointerPointer, IdPointerFunction, IdBool, IdTrue, IdFloat, IdFloatPointer, IdGlsl, IdFunctionUintPointer, IdUntypedPointer, IdFloatOne, IdMain, IdMainLabel, IdPointer, IdHelper, IdHelperParameter, IdHelperLabel, IdBody, -}; - -bool ScanStores(const std::function& main, const std::function& after = {}) { - ScanWords module{{spv::MagicNumber, 0x00010500u, 0u, 200u, 0u}}; - module.Op(spv::OpCapability, {spv::CapabilityShader}); - module.Op(spv::OpCapability, {spv::CapabilityInt64}); - module.Op(spv::OpCapability, {spv::CapabilityPhysicalStorageBufferAddresses}); - module.OpString(spv::OpExtInstImport, {IdGlsl}, "GLSL.std.450"); - module.Op(spv::OpMemoryModel, {spv::AddressingModelPhysicalStorageBuffer64, spv::MemoryModelGLSL450}); - module.OpString(spv::OpEntryPoint, {spv::ExecutionModelGLCompute, IdMain}, "main"); - module.Op(spv::OpTypeVoid, {IdVoid}); - module.Op(spv::OpTypeFunction, {IdVoidFunction, IdVoid}); - module.Op(spv::OpTypeInt, {IdUint, 32u, 0u}); - module.Op(spv::OpTypeInt, {IdUlong, 64u, 0u}); - module.Op(spv::OpTypeFloat, {IdFloat, 32u}); - module.Op(spv::OpTypeBool, {IdBool}); - module.Op(spv::OpTypePointer, {IdUintPointer, spv::StorageClassPhysicalStorageBuffer, IdUint}); - module.Op(spv::OpTypePointer, {IdPointerPointer, spv::StorageClassPhysicalStorageBuffer, IdUintPointer}); - module.Op(spv::OpTypePointer, {IdFloatPointer, spv::StorageClassPhysicalStorageBuffer, IdFloat}); - module.Op(spv::OpTypePointer, {IdPointerFunction, spv::StorageClassFunction, IdUint}); - module.Op(spv::OpTypeUntypedPointerKHR, {IdUntypedPointer, spv::StorageClassPhysicalStorageBuffer}); - module.Op(spv::OpTypeFunction, {IdFunctionUintPointer, IdVoid, IdUintPointer}); - module.Op(spv::OpConstant, {IdUlong, IdAddress, 0x1000u, 0u}); - module.Op(spv::OpConstant, {IdUint, IdOne, 1u}); - module.Op(spv::OpConstant, {IdUint, IdDeviceScope, spv::ScopeDevice}); - module.Op(spv::OpConstant, {IdUint, IdNoSemantics, 0u}); - module.Op(spv::OpConstant, {IdFloat, IdFloatOne, 0x3f800000u}); - module.Op(spv::OpConstantTrue, {IdBool, IdTrue}); - module.Op(spv::OpFunction, {IdVoid, IdMain, spv::FunctionControlMaskNone, IdVoidFunction}); - module.Op(spv::OpLabel, {IdMainLabel}); - module.Op(spv::OpConvertUToPtr, {IdUintPointer, IdPointer, IdAddress}); - main(module); - module.Op(spv::OpReturn, {}); - module.Op(spv::OpFunctionEnd, {}); - if (after) after(module); - return AgcDriver::Graphics::SpirvStoresThroughAddresses(module.words); -} - -void RunAddressStoreScanTests() { - using AgcDriver::Graphics::Require; - Require(!ScanStores([](ScanWords& m) { m.Op(spv::OpLoad, {IdUint, IdBody, IdPointer}); }), "store scan: a load through a physical pointer was taken for a store"); - Require(!ScanStores([](ScanWords& m) { m.Op(spv::OpAtomicLoad, {IdUint, IdBody, IdPointer, IdDeviceScope, IdNoSemantics}); }), "store scan: an atomic load was taken for a store"); - Require(ScanStores([](ScanWords& m) { m.Op(spv::OpStore, {IdPointer, IdOne}); }), "store scan: a store was missed"); - Require(ScanStores([](ScanWords& m) { m.Op(spv::OpAtomicStore, {IdPointer, IdDeviceScope, IdNoSemantics, IdOne}); }), "store scan: an atomic store was missed"); - for (const auto opcode : {spv::OpAtomicExchange, spv::OpAtomicIAdd, spv::OpAtomicISub, spv::OpAtomicSMin, spv::OpAtomicUMin, spv::OpAtomicSMax, spv::OpAtomicUMax, spv::OpAtomicAnd, spv::OpAtomicOr, spv::OpAtomicXor}) { - Require(ScanStores([opcode](ScanWords& m) { m.Op(opcode, {IdUint, IdBody, IdPointer, IdDeviceScope, IdNoSemantics, IdOne}); }), "store scan: atomic opcode " + std::to_string(static_cast(opcode)) + " was missed"); - } - Require(ScanStores([](ScanWords& m) { m.Op(spv::OpAtomicIIncrement, {IdUint, IdBody, IdPointer, IdDeviceScope, IdNoSemantics}); }), "store scan: an atomic increment was missed"); - Require(ScanStores([](ScanWords& m) { m.Op(spv::OpAtomicCompareExchange, {IdUint, IdBody, IdPointer, IdDeviceScope, IdNoSemantics, IdNoSemantics, IdOne, IdOne}); }), "store scan: an atomic compare-exchange was missed"); - Require(ScanStores([](ScanWords& m) { - m.Op(spv::OpConvertUToPtr, {IdPointerPointer, IdBody, IdAddress}); - m.Op(spv::OpLoad, {IdUintPointer, IdBody + 1u, IdBody}); - m.Op(spv::OpStore, {IdBody + 1u, IdOne}); - }), "store scan: a store through a pointer loaded from guest memory was missed"); - Require(ScanStores([](ScanWords& m) { - m.Op(spv::OpSelect, {IdUintPointer, IdBody, IdTrue, IdPointer, IdPointer}); - m.Op(spv::OpStore, {IdBody, IdOne}); - }), "store scan: a store through a selected pointer was missed"); - Require(ScanStores([](ScanWords& m) { m.Op(spv::OpFunctionCall, {IdVoid, IdBody, IdHelper, IdPointer}); }, [](ScanWords& m) { - m.Op(spv::OpFunction, {IdVoid, IdHelper, spv::FunctionControlMaskNone, IdFunctionUintPointer}); - m.Op(spv::OpFunctionParameter, {IdUintPointer, IdHelperParameter}); - m.Op(spv::OpLabel, {IdHelperLabel}); - m.Op(spv::OpStore, {IdHelperParameter, IdOne}); - m.Op(spv::OpReturn, {}); - m.Op(spv::OpFunctionEnd, {}); - }), "store scan: a store through a pointer parameter of a called function was missed"); - Require(!ScanStores([](ScanWords& m) { - m.Op(spv::OpVariable, {IdPointerFunction, IdBody, spv::StorageClassFunction}); - m.Op(spv::OpCopyMemory, {IdBody, IdPointer}); - }), "store scan: a copy out of guest memory was taken for a store"); - Require(ScanStores([](ScanWords& m) { - m.Op(spv::OpVariable, {IdPointerFunction, IdBody, spv::StorageClassFunction}); - m.Op(spv::OpCopyMemory, {IdPointer, IdBody}); - }), "store scan: a copy into guest memory was missed"); - Require(ScanStores([](ScanWords& m) { - m.Op(spv::OpConvertUToPtr, {IdUntypedPointer, IdBody, IdAddress}); - m.Op(spv::OpStore, {IdBody, IdOne}); - }), "store scan: a store through an untyped physical pointer was missed"); - Require(ScanStores([](ScanWords& m) { - m.Op(spv::OpConvertUToPtr, {IdFloatPointer, IdBody, IdAddress}); - m.Op(spv::OpExtInst, {IdFloat, IdBody + 1u, IdGlsl, GLSLstd450Modf, IdFloatOne, IdBody}); - }), "store scan: an extended instruction writing through a physical pointer was missed"); - Require(ScanStores([](ScanWords& m) { m.Op(spv::OpCooperativeMatrixStoreKHR, {IdPointer, IdOne, IdNoSemantics}); }), "store scan: a cooperative matrix store was missed"); -} - - template void reject(TAction action, const char* expected) { try { action(); } @@ -141,21 +38,6 @@ std::uint32_t CallSites(const std::vector& spirv, const char* nam void RunBdaContractTests() { using namespace ShaderRecompiler; - using AgcDriver::Graphics::SpirvStoresThroughAddresses; - RunAddressStoreScanTests(); - AgcDriver::Graphics::Require(!SpirvStoresThroughAddresses(MakeBdaTestShader(0x1000, 32)), "a BDA read was taken for a store through an address"); - AgcDriver::Graphics::Require(!SpirvStoresThroughAddresses(MakeBdaDwordReadTestShader(0x1000, 4, false, false)), "BDA dword reads were taken for a store through an address"); - AgcDriver::Graphics::Require(SpirvStoresThroughAddresses(MakeBdaStoreTestShader(0x1000, 7, 32, false)), "a BDA store was not seen"); - AgcDriver::Graphics::Require(SpirvStoresThroughAddresses(MakeBdaWriteTestShader(0x1000, 7, 32, false)), "a BDA write was not seen"); - const std::array stored{7u, 9u}; - AgcDriver::Graphics::Require(SpirvStoresThroughAddresses(MakeBdaDwordWriteTestShader(0x1000, static_cast(stored.size()), stored.data())), "BDA dword writes were not seen"); - const std::array headerOnly{spv::MagicNumber, 0x00010300u, 0u, 1u, 0u}; - AgcDriver::Graphics::Require(!SpirvStoresThroughAddresses(headerOnly), "a module without physical pointers was taken for one storing through addresses"); - const std::array truncated{spv::MagicNumber, 0u}; - AgcDriver::Graphics::Require(SpirvStoresThroughAddresses(truncated), "an unreadable module was taken for one without stores"); - auto unparsed = MakeBdaStoreTestShader(0x1000, 7, 32, false); - unparsed[5] |= 0xffff0000u; - AgcDriver::Graphics::Require(SpirvStoresThroughAddresses(unparsed), "a module with an instruction past its end was taken for one without stores"); const std::array capabilities{spv::CapabilityInt64, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess}; const std::array extensions{"SPV_KHR_physical_storage_buffer", "SPV_KHR_8bit_storage"}; SpirvTargetOptions target{0x00401000u, 0x00010300u, 32, BdaAbi::Version, capabilities, extensions}; diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp b/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp index c2c44c6aed8b..15ad5d28b87f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp @@ -3596,6 +3596,7 @@ void RunBdaResourceTests(const Context& context, const BdaTestAccess& access) { const std::array snapshots{{{0x7fff12340000ULL, source}}}; ShaderRecompiler::RecompileResult shader; shader.bindings = {binding(Role::BdaPagetable, 4), binding(Role::FaultBuffer, 5)}; + shader.bdaStores = true; CompiledShader compiled{ShaderRecompiler::ShaderStage::Compute, &shader, 0}; reject([&] { ShaderResources resources(context, compiled, snapshots); }, "ABI version"); shader.bdaAbiVersion = ShaderRecompiler::BdaAbi::Version; diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp new file mode 100644 index 000000000000..bac8ddff51e7 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -0,0 +1,158 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/PlaceholderImages.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "RuntimeAbi.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace AgcDriver::Graphics; +namespace Abi = ShaderRecompiler::RuntimeAbi; + +constexpr int VulkanTestSkipped = 77; + +void require(bool condition, const std::string& what) { + if (!condition) throw std::runtime_error(what); +} + +alignas(Texture) std::array, 8> fakeTextures{}; + +std::shared_ptr fakeTexture(std::size_t index) { + return std::shared_ptr(reinterpret_cast(fakeTextures[index].data()), [](Texture*) {}); +} + +void textureSlots(const Context& context, VkImageView view) { + BindlessHeap heap(context); + const auto kind = Abi::FirstImageBinding; + auto first = fakeTexture(0); + const auto slot = heap.TextureSlot(kind, first, view, VK_IMAGE_LAYOUT_GENERAL); + require(slot.has_value(), "the first texture takes a slot"); + require(heap.SlotTexture(kind, *slot) == first.get(), "the slot holds the first texture"); + const auto generation = heap.SlotGeneration(kind, *slot); + + auto second = fakeTexture(1); + require(!heap.TextureSlot(kind, second, view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a held slot is not reused"); + first.reset(); + const auto reused = heap.TextureSlot(kind, second, view, VK_IMAGE_LAYOUT_GENERAL); + require(reused.has_value() && *reused == *slot, "the released texture's slot is reused"); + require(heap.SlotGeneration(kind, *slot) != generation, "a freed slot moves its generation"); + require(heap.SlotTexture(kind, *slot) == second.get(), "the reused slot holds the second texture"); + const auto counts = heap.Statistics(); + require(counts.slotsFreed == 1u && counts.slotsReused == 1u, "one slot freed and reused"); + + auto shared = fakeTexture(2); + const auto otherKind = kind + 1u; + const auto firstShared = heap.TextureSlot(kind, shared, view, VK_IMAGE_LAYOUT_GENERAL); + require(!firstShared.has_value(), "the capped kind has no slot left for a third texture"); + const auto sharedSlot = heap.TextureSlot(otherKind, shared, view, VK_IMAGE_LAYOUT_GENERAL); + require(sharedSlot.has_value() && shared->HeapHolds() == 1u, "a texture placed by the heap counts one heap hold"); + second.reset(); + shared.reset(); + const auto freedBefore = heap.Statistics().slotsFreed; + auto third = fakeTexture(0); + require(heap.TextureSlot(kind, third, view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture held only by the heap is swept"); + require(heap.Statistics().slotsFreed == freedBefore + 2u, "one sweep frees every slot whose texture only the heap holds"); +} + +void samplerSlots(const Context& context) { + BindlessHeap heap(context); + auto cache = std::make_unique(); + const std::array firstWords{0u, 0u, 0u, 0u}; + const std::array secondWords{0u, 0u, 0x00100000u, 0u}; + auto first = cache->Get(context, firstWords, false); + const auto slot = heap.SamplerSlot(first); + require(slot.has_value(), "the first sampler takes a slot"); + const auto generation = heap.SamplerGeneration(*slot); + require(first->CacheKey() != nullptr, "a cached sampler carries its key"); + first.reset(); + cache.reset(); + cache = std::make_unique(); + auto second = cache->Get(context, secondWords, false); + const auto reused = heap.SamplerSlot(second); + require(reused.has_value() && *reused == *slot, "the released sampler's slot is reused"); + require(heap.SamplerGeneration(*slot) != generation, "a freed sampler slot moves its generation"); +} + +} + +void heapComesBack(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + const auto kind = Abi::FirstImageBinding; + std::vector> held; + for (std::size_t index = 0; index < 7u; ++index) { + held.push_back(fakeTexture(index)); + require(heap.TextureSlot(kind, held.back(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture takes one of the eight capped slots"); + } + require(BindlessHeap::NearlyFull(), "one free slot of eight refuses the heap"); + BindlessHeap::SweepIfDue(); + require(BindlessHeap::NearlyFull(), "a sweep that is not due leaves the heap refused"); + BindlessHeap::NoteSweepDue(); + BindlessHeap::SweepIfDue(); + require(BindlessHeap::NearlyFull(), "a sweep that frees nothing leaves the heap refused"); + held.clear(); + BindlessHeap::NoteSweepDue(); + BindlessHeap::SweepIfDue(); + require(!BindlessHeap::NearlyFull(), "a sweep that frees the slots of textures only the heap held takes the heap again"); + BindlessHeap::Release(context.device); +} + +int main(int argc, char** argv) { + const bool comesBack = argc > 1 && std::string(argv[1]) == "comes-back"; + try { +#ifdef _WIN32 + _putenv_s("APS5_GPU_HEAP", "1"); +#else + setenv("APS5_GPU_HEAP", "1", 1); +#endif + std::unique_ptr device; + try { + device = std::make_unique(); + } catch (const std::exception& error) { + if (std::getenv("ANYPS5_REQUIRE_VULKAN") != nullptr) throw; + std::printf("skipped, no usable Vulkan device: %s\n", error.what()); + return VulkanTestSkipped; + } + if (!device->GraphicsContext().descriptorHeap) { + std::printf("skipped, the device has no VK_EXT_descriptor_heap\n"); + return VulkanTestSkipped; + } +#ifdef _WIN32 + _putenv_s("APS5_HEAP_SLOT_CAP", comesBack ? "8" : "1"); +#else + setenv("APS5_HEAP_SLOT_CAP", comesBack ? "8" : "1", 1); +#endif + if (comesBack) { + { + const auto context = device->GraphicsContext(); + const PlaceholderImages placeholders(context); + heapComesBack(context, placeholders.View(Abi::FirstImageBinding)); + device->WaitIdle(); + } + device.reset(); + std::cout << "the refused heap comes back after a sweep\n"; + return 0; + } + { + const auto context = device->GraphicsContext(); + const PlaceholderImages placeholders(context); + textureSlots(context, placeholders.View(Abi::FirstImageBinding)); + samplerSlots(context); + device->WaitIdle(); + } + device.reset(); + std::cout << "bindless heap slot reuse tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "bindless heap slot reuse tests failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/Mesh.cpp b/core/libs/prx/libSceAgcDriver/tests/Mesh.cpp index ce6f2d65f36e..e8f0997c4015 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Mesh.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Mesh.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "Recompiler.hpp" #include "MeshGeometryFixture.hpp" @@ -169,7 +170,8 @@ bool ReadsNumWorkgroups(std::span words) { } void DrawMesh(AgcDriver::VulkanDevice& device, const MeshDraw& setup) { - const auto target = device.Target(); + auto target = device.Target(); + target.gpuResolvedImages = AgcDriver::Graphics::DescriptorHeapEnabled(); std::vector userData(12, 0u); const auto index = AgcDriver::Graphics::MeshIndexBufferDescriptor(setup.draw); std::copy(index.begin(), index.end(), userData.begin() + ShaderRecompiler::MeshIndexBufferUserWord); @@ -186,7 +188,7 @@ void DrawMesh(AgcDriver::VulkanDevice& device, const MeshDraw& setup) { const auto meshResult = ShaderRecompiler::Recompile(geometry); Require(ReadsNumWorkgroups(meshResult.spirv), "the mesh program does not read NumWorkgroups, so RADV can keep a previous vertex pipeline's user SGPR count for its dispatch"); const auto meshPush = static_cast(meshResult.pushConstants.size()); - Require((meshPush == 0) == (setup.geometryPushBytes == 0), "the geometry program's push data does not follow its layout"); + Require(meshResult.gpuResolvedImages || (meshPush == 0) == (setup.geometryPushBytes == 0), "the geometry program's push data does not follow its layout"); ShaderRecompiler::ShaderPixelStageInfo pixel{}; pixel.interpolatorCount = 1; @@ -202,6 +204,7 @@ void DrawMesh(AgcDriver::VulkanDevice& device, const MeshDraw& setup) { std::nullopt }; const auto pixelResult = ShaderRecompiler::Recompile(fragment); + Require(meshResult.gpuResolvedImages == target.gpuResolvedImages && pixelResult.gpuResolvedImages == target.gpuResolvedImages, "the mesh draw's stages did not take GPU mode"); const std::array shaders{{ {ShaderStage::Mesh, &meshResult, 0}, {ShaderStage::Fragment, &pixelResult, PixelPushOffset(meshPush, target)} diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 4d7e4dc55154..23ebff9faf57 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -5026,6 +5026,28 @@ void verifySingleLaneVertexWave() { require(withoutKey != withKey, "single-lane vertex wave: vertex subgroup support did not change the cache key"); } +void verifyExtensionKey() { + using namespace ShaderRecompiler; + RecompileRequest request{}; + request.shader.stage = ShaderStage::Compute; + const std::array first{"VK_KHR_a", "VK_KHR_bb"}; + const std::string copied[2] = {"VK_KHR_a", "VK_KHR_bb"}; + const std::array same{copied[0], copied[1]}; + const std::array second{"VK_KHR_a", "VK_KHR_bc"}; + std::vector firstKey, againKey, sameKey, secondKey, backKey; + request.target.supportedExtensions = first; + RecompileCacheKey::BuildInterface(request, firstKey); + RecompileCacheKey::BuildInterface(request, againKey); + request.target.supportedExtensions = same; + RecompileCacheKey::BuildInterface(request, sameKey); + request.target.supportedExtensions = second; + RecompileCacheKey::BuildInterface(request, secondKey); + request.target.supportedExtensions = first; + RecompileCacheKey::BuildInterface(request, backKey); + require(firstKey == againKey && firstKey == sameKey && firstKey == backKey, "extension key: the same extension names built different keys"); + require(firstKey != secondKey, "extension key: a changed extension name kept the key"); +} + void verifyMeshConfiguration() { using namespace ShaderRecompiler; ShaderMeshInputInfo list; @@ -8547,6 +8569,7 @@ int main(int argc, char** argv) { verifyFusedExactArithmetic(); verifyNarrowVertexWave(); verifySingleLaneVertexWave(); + verifyExtensionKey(); verifyMeshConfiguration(); verifyPixelInputs(); verifyCanonicalVersion20And21Requests(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressPasses.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressPasses.cpp index 9278d6778785..7ef41abc43b7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/AddressPasses.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressPasses.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -208,9 +209,12 @@ std::string Counts(const AgcDriver::Graphics::DrawPassCounts& before, const AgcD void ReadersShareAPass(const GuestBlock& vertices, const GuestBlock& data, const GuestBlock& target) { const auto before = AddressDraws(); + const auto heapBinds = AgcDriver::Graphics::DescriptorHeapBinds(); Submit(vertices, target, {{PixelRead.data(), data.At(0)}, {PixelRead.data(), data.At(0)}}); const auto after = AddressDraws(); - std::printf("two draws reading through the table: %s\n", Counts(before, after).c_str()); + const auto binds = AgcDriver::Graphics::DescriptorHeapBinds() - heapBinds; + std::printf("two draws reading through the table: %s, %llu heap binds\n", Counts(before, after).c_str(), static_cast(binds)); + Expect(!AgcDriver::Graphics::DescriptorHeapEnabled() || binds == 1, "two heap draws in one command buffer bound the descriptor heaps " + std::to_string(binds) + " times"); Expect(after.draws - before.draws == 2 && after.passesContinued - before.passesContinued == 1, "a draw reading through the table after another did not continue its pass: " + Counts(before, after)); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/BindlessImages.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/BindlessImages.cpp index 3268ff39d811..cfeefcbba3ba 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/BindlessImages.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/BindlessImages.cpp @@ -1,9 +1,11 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" #include "ImageTableAbi.hpp" #include "VulkanTestDevice.hpp" #include #include +#include #include #include @@ -56,8 +58,12 @@ void Run(AgcDriver::VulkanDevice& device) { const auto output = Buffer(data.output.data(), 0u, 256u); std::copy(output.begin(), output.end(), data.srt.begin() + 12u); const ShaderComputeStageInfo compute{{threads, 1u, 1u}, 0u, {false, false, false}, false, 1u}; - RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, regions}, device.Target(), {0u, 0u, 0u, 128u}}; + const bool heap = AgcDriver::Graphics::DescriptorHeapEnabled(); + auto target = device.Target(); + target.gpuResolvedImages = heap; + RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, regions}, target, {0u, 0u, 0u, 128u}}; const auto shader = Recompile(request); + Require(shader.gpuResolvedImages == heap, heap ? "the compute heap did not take the table stage" : "a table stage took the heap without it"); if (artifact.variantId == 0u) artifact = shader; else Require(shader.cacheHit && shader.variantId == artifact.variantId, "bindless table changed the compiled artifact"); if (iteration == 1u) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/BufferAtomics.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/BufferAtomics.cpp index 550cbd7f0bea..88c1230b46b7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/BufferAtomics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/BufferAtomics.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" @@ -77,11 +78,12 @@ void Run(AgcDriver::VulkanDevice& device) { ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(32), {0, 0, 0, 128} }; request.useCache = false; const auto result = ShaderRecompiler::Recompile(request); + Require(result.gpuResolvedImages == AgcDriver::Graphics::DescriptorHeapEnabled(), "the compute heap did not take the buffer stage"); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/BufferFormat.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/BufferFormat.cpp index 7394269e39b1..3067384aad32 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/BufferFormat.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/BufferFormat.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" @@ -155,11 +156,12 @@ void Run(AgcDriver::VulkanDevice& device) { ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(32), {0, 0, 0, 128} }; request.useCache = false; const auto result = ShaderRecompiler::Recompile(request); + Require(result.gpuResolvedImages == AgcDriver::Graphics::DescriptorHeapEnabled(), "the compute heap did not take the buffer stage"); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/BufferLoadStore.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/BufferLoadStore.cpp index da69c6d9d0b6..0932f742a89f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/BufferLoadStore.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/BufferLoadStore.cpp @@ -304,7 +304,7 @@ void CheckRuntimeDescriptors(AgcDriver::VulkanDevice& device, std::uint32_t wave const auto output = BufferDescriptor(Output.data(), threads * 4u); std::copy(output.begin(), output.end(), userData.begin() + 4); const ShaderRecompiler::ShaderComputeStageInfo compute{{threads, 1u, 1u}, 0u, {false, false, false}, false, 1u}; - ShaderRecompiler::RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {waveSize, 0u, userData, compute, std::nullopt, std::nullopt, {}}, device.Target(), {0u, 0u, 0u, 128u}}; + ShaderRecompiler::RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {waveSize, 0u, userData, compute, std::nullopt, std::nullopt, {}}, device.ComputeTarget(waveSize), {0u, 0u, 0u, 128u}}; ShaderRecompiler::RecompileResult first; for (const auto& value : cases) { auto input = BufferDescriptor(Input.data(), value.records); @@ -345,9 +345,9 @@ int main() { try { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; - Run(*device, Wave32Code, 32, device->Target()); + Run(*device, Wave32Code, 32, device->ComputeTarget(32)); Check(Expected32, Names, "wave32"); - Run(*device, Wave64Code, 64, device->Target()); + Run(*device, Wave64Code, 64, device->ComputeTarget(64)); Check(Expected64, Names, "wave64"); Run(*device, Wave64Code, 64, device->ComputeTarget(32)); Check(Expected64, Names, "wave64 split"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp new file mode 100644 index 000000000000..55463a68eb08 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp @@ -0,0 +1,190 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Submit/include/Acb.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace { + +void Require(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; +constexpr std::array OtherTexel{0xf0u, 0x20u, 0x00u, 0x40u}; + +alignas(256) constexpr std::array SampleCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; + +alignas(256) constexpr std::array LdsSampleCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0x7e080280u, 0xbf8c0000u, 0xd8340000u, 0x00000004u, 0xbf8c0000u, 0xd8d80000u, 0x00000004u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u, 0xbf810000u}; + +alignas(256) std::array TextureMemory{}; +alignas(256) std::array OtherTextureMemory{}; +alignas(4096) std::array, 4> Outputs{}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header SampleHeader{}; + +void Registered(Header& header, const std::uint32_t* code, std::size_t bytes) { + header.shader.file_header = 0x34333231u; + header.shader.version = 0x18u; + header.shader.header_size = sizeof(Header); + header.shader.shader_size = static_cast(bytes); + header.shader.code = code; + header.shader.type = 0; + header.shader.user_data = &header.userData; + AgcDriverRegisterShader_nid_postfix(&header.shader); +} + +std::uint32_t Low(const void* pointer) { + return static_cast(reinterpret_cast(pointer)); +} + +std::uint32_t High(const void* pointer) { + return static_cast(static_cast(reinterpret_cast(pointer)) >> 32u); +} + +std::array Image(const void* pointer) { + const auto address = static_cast(reinterpret_cast(pointer)); + return {static_cast(address >> 8u), static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), 3u << 14u, 0xfacu | (9u << 28u), 0u, 0u, 0u, 0u}; +} + +void SetShaderRegister(std::vector& words, std::uint32_t offset, std::uint32_t value) { + words.insert(words.end(), {0xc0017600u, offset, value}); +} + +void Sample(std::vector& words, const void* image, float* output) { + const auto address = static_cast(reinterpret_cast(SampleCode.data())); + SetShaderRegister(words, 0x20c, static_cast(address >> 8u)); + SetShaderRegister(words, 0x20d, static_cast(address >> 40u) & 0xffu); + for (const std::uint32_t offset : {0x207u, 0x208u, 0x209u}) SetShaderRegister(words, offset, 1); + SetShaderRegister(words, 0x212, 0); + SetShaderRegister(words, 0x213, 16u << 1u); + std::vector userData; + const auto descriptor = Image(image); + userData.insert(userData.end(), descriptor.begin(), descriptor.end()); + userData.insert(userData.end(), {0u, 0u, 0u, 0u}); + userData.insert(userData.end(), {Low(output), High(output) & 0xffffu, static_cast(4u * sizeof(float)), 0x31016facu}); + std::uint32_t offset = 0x240; + for (const auto value : userData) SetShaderRegister(words, offset++, value); + words.insert(words.end(), {0xc0031500u, 1, 1, 1, 0x8041u}); +} + +void Submit(std::vector& words) { + Packet packet{words.data(), static_cast(words.size()), 0, {}}; + Require(sceAgcDriverSubmitAcb(0x20, &packet) == 0, "the compute submission failed"); + AgcDriverWaitIdle_nid_postfix(); +} + +void RequireSampled(const float* output, const std::array& expected, const std::string& what, bool heap) { + for (std::size_t channel = 0; channel < 4; ++channel) { + const float wanted = static_cast(expected[channel]) / 255.0f; + Require(std::fabs(output[channel] - wanted) < 1e-6f, what + ": channel " + std::to_string(channel) + " is " + std::to_string(output[channel]) + ", expected " + std::to_string(wanted) + (heap ? " through the heap" : "")); + } +} + +void Fill(std::array& memory, const std::array& texel) { + for (std::size_t offset = 0; offset < memory.size(); offset += texel.size()) std::memcpy(memory.data() + offset, texel.data(), texel.size()); +} + +void DriverSample(bool heap) { + Outputs[0].fill(-1.0f); + const auto before = AgcDriver::Graphics::HeapComputeStages(); + std::vector words; + Sample(words, TextureMemory.data(), Outputs[0].data()); + Sample(words, TextureMemory.data(), Outputs[0].data()); + Submit(words); + RequireSampled(Outputs[0].data(), Texel, "the sampled texture", heap); + if (heap) Require(AgcDriver::Graphics::HeapComputeStages() > before, "the heap did not take the sampling compute stage"); +} + +ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const void* image, float* output, std::span code = SampleCode, std::uint32_t ldsDwords = 0u) { + std::vector userData; + const auto descriptor = Image(image); + userData.insert(userData.end(), descriptor.begin(), descriptor.end()); + userData.insert(userData.end(), {0u, 0u, 0u, 0u}); + userData.insert(userData.end(), {Low(output), High(output) & 0xffffu, static_cast(4u * sizeof(float)), 0x31016facu}); + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{1u, 1u, 1u}, ldsDwords, {false, false, false}, false, 1u}; + ShaderRecompiler::RecompileRequest request{{ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, memory}, device.ComputeTarget(32u), {0u, 0u, 0u, 128u}}; + request.useCache = false; + return ShaderRecompiler::Recompile(request); +} + +void DeviceSample(AgcDriver::VulkanDevice& device, bool heap) { + for (std::size_t index = 1; index < Outputs.size(); ++index) Outputs[index].fill(-1.0f); + const auto first = Compile(device, OtherTextureMemory.data(), Outputs[1].data()); + const auto second = Compile(device, TextureMemory.data(), Outputs[2].data()); + Require(first.gpuResolvedImages == heap && second.gpuResolvedImages == heap, heap ? "a sampling compute stage is not GPU mode" : "a compute stage took the heap without it"); + const auto before = AgcDriver::Graphics::HeapComputeStages(); + const auto pushesBefore = AgcDriver::Graphics::DataAddressPushes(); + device.Dispatch(first, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); + device.Dispatch(second, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); + device.WaitIdle(); + RequireSampled(Outputs[1].data(), OtherTexel, "the first of two textures in one batch", heap); + RequireSampled(Outputs[2].data(), Texel, "the second of two textures in one batch", heap); + if (heap) Require(AgcDriver::Graphics::HeapComputeStages() >= before + 2u, "the heap did not take both sampling compute stages"); + if (heap) Require(AgcDriver::Graphics::DataAddressPushes() >= pushesBefore + 2u, "a heap dispatch did not read its shader data through pushed addresses"); + const auto again = Compile(device, TextureMemory.data(), Outputs[3].data()); + device.Dispatch(again, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); + device.WaitIdle(); + RequireSampled(Outputs[3].data(), Texel, "the first texture again in a later batch", heap); + Outputs[1].fill(-1.0f); + const auto lds = Compile(device, TextureMemory.data(), Outputs[1].data(), LdsSampleCode, (device.ComputeTarget(32u).maxWorkgroupSharedMemoryBytes + 4096u) / 4u); + Require(lds.workgroupMemoryDwords != 0u && lds.gpuResolvedImages == heap, "the LDS sampling stage did not get workgroup memory in the expected mode"); + const auto heapPipelines = device.DescriptorHeapComputePipelines(); + device.Dispatch(lds, 1u, 1u, 1u, {}, reinterpret_cast(LdsSampleCode.data())); + device.WaitIdle(); + RequireSampled(Outputs[1].data(), Texel, "the texture sampled through workgroup memory", heap); + if (heap && heapPipelines != 0u) Require(device.DescriptorHeapComputePipelines() > heapPipelines, "the LDS sampling stage did not take the descriptor heap"); +} + +} + +int main() { + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + const bool heap = AgcDriver::Graphics::DescriptorHeapEnabled(); + Fill(TextureMemory, Texel); + Fill(OtherTextureMemory, OtherTexel); + Registered(SampleHeader, SampleCode.data(), sizeof(SampleCode)); + DriverSample(heap); + AgcDriverShutdown_nid_postfix(); + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + DeviceSample(*device, heap); + } + std::cout << "compute stages sampled their textures" << (heap ? " through the heap" : "") << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + try { + AgcDriverShutdown_nid_postfix(); + } catch (const std::exception& shutdownError) { + std::cerr << shutdownError.what() << '\n'; + } + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp new file mode 100644 index 000000000000..4cc09dfc429d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -0,0 +1,263 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::byte Kept{0x40}; +constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array BufferPixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array GdsPixelCode{0xbefc03ffu, 0x0000ffffu, 0x7e0002f0u, 0x7e0202f0u, 0xd8fa0010u, 0x04000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array StoragePixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e100280u, 0x7e120280u, 0xf0201f08u, 0x00040008u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(4096) std::array StorageMemory{}; +alignas(256) constexpr std::array SamplingVertexCode{ + 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00820c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array InterpolantPixelCode{0xc8020002u, 0xc8060102u, 0xc80a0202u, 0xc80e0302u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array BdaPixelCode{0x7e0002f0u, 0x7e0202f0u, 0x7e08020cu, 0x7e0a020du, 0xdc308000u, 0x067d0004u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060306u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TablePixelCode{0xf4200404u, 0xfa000000u, 0xbf8cc07fu, 0x8f108510u, 0xf42c0500u, 0x20000000u, 0xbf8cc07fu, 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00250000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TableVertexCode{ + 0xf4200508u, 0xfa000000u, 0xbf8cc07fu, 0x8f148514u, 0xf42c0604u, 0x28000000u, 0xbf8cc07fu, 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00660c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) std::array TableMemory{}; +alignas(256) std::array MaterialMemory{}; +alignas(256) std::array OtherTextureMemory{}; +constexpr float BufferAlpha = 0.2f; +constexpr std::uint8_t BufferAlphaByte = 51u; +constexpr float SecondAlpha = 0.6f; +constexpr std::uint8_t SecondAlphaByte = 153u; +alignas(4096) std::array BufferMemory{}; +alignas(256) std::array ColorMemory{}; +alignas(256) std::array TextureMemory{}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(Header& header, const std::uint32_t* code, std::size_t bytes, std::uint8_t type) { + header.shader.file_header = 0x34333231u; + header.shader.version = 0x18u; + header.shader.header_size = sizeof(Header); + header.shader.shader_size = static_cast(bytes); + header.shader.code = code; + header.shader.type = type; + header.shader.user_data = &header.userData; + AgcDriverRegisterShader_nid_postfix(&header.shader); +} + +void Append(std::vector& commands, std::uint32_t opcode, std::initializer_list payload) { + commands.push_back(0xc0000000u | (static_cast(payload.size() - 1) << 16u) | (opcode << 8u)); + commands.insert(commands.end(), payload); +} + +enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture }; + +std::vector Draw(const std::uint32_t* pixelCode, Mode mode) { + const bool vertexSampling = mode == Mode::Vertex || mode == Mode::VertexTable; + const auto vertex = reinterpret_cast(mode == Mode::VertexTable ? TableVertexCode.data() : mode == Mode::Vertex ? SamplingVertexCode.data() : VertexCode.data()); + const auto pixel = reinterpret_cast(pixelCode); + const auto color = reinterpret_cast(ColorMemory.data()); + const auto texture = static_cast(reinterpret_cast(TextureMemory.data())); + const auto bufferAddress = static_cast(reinterpret_cast(BufferMemory.data() + 1)); + const auto storage = static_cast(reinterpret_cast(StorageMemory.data())); + const std::array descriptors{ + static_cast(texture >> 8u), static_cast((texture >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), 3u << 14u, 0xfacu | (9u << 28u), 0u, 0u, 0u, 0u, + 0u, 0u, 0u, 0u, + static_cast(bufferAddress), static_cast((bufferAddress >> 32u) & 0xffffu), static_cast(sizeof(BufferMemory) - sizeof(float)), 0xfacu, + static_cast(storage >> 8u), static_cast((storage >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), 3u << 14u, 0xfacu | (9u << 28u), 0u, 0u, 0u, 0u}; + const auto userWords = mode == Mode::Storage ? 24u : mode == Mode::Buffer || mode == Mode::MovedBuffer ? 16u : mode == Mode::Bda ? 14u : vertexSampling ? 0u : 12u; + const auto bufferWords = [](const void* pointer, std::uint32_t bytes) { + const auto address = static_cast(reinterpret_cast(pointer)); + return std::array{static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0xfacu}; + }; + const auto other = static_cast(reinterpret_cast(OtherTextureMemory.data())); + const std::array otherImage{static_cast(other >> 8u), static_cast((other >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), 3u << 14u, 0xfacu | (9u << 28u), 0u, 0u, 0u, 0u}; + std::copy(otherImage.begin(), otherImage.end(), TableMemory.begin()); + std::copy(descriptors.begin(), descriptors.begin() + 8, TableMemory.begin() + 8); + MaterialMemory = {1u, 0u, 0u, 0u}; + std::array tableWords{}; + const auto table = bufferWords(TableMemory.data(), sizeof(TableMemory)); + const auto material = bufferWords(MaterialMemory.data(), sizeof(MaterialMemory)); + std::copy(table.begin(), table.end(), tableWords.begin()); + std::copy(material.begin(), material.end(), tableWords.begin() + 8); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, {0x207, 0}, {0x200, 0}, {0x203, 0x800}, + {0x2dc, 0xaa00}, {0x2f8, 0}, {0x293, 0}, + {0x80, 0}, {0x8d, 0}, {0x83, 0xffff}, {0x8c, 0xa}, + {0x2f9, 0x2d}, {0x313, 0x6000}, {0x30e, 0xffffffff}, {0x30f, 0xffffffff}, + {0x206, 0x43f}, {0x204, 0x80000}, {0x205, 0x240}, + {0x8e, 0xf}, {0x8f, 0xf}, {0x202, 0xcc0010}, + {0x1c4, 0}, {0x1c5, 9}, {0x1c3, 4}, {0x31c, 0x28028}, + {0x31b, 0}, {0x31d, 0}, {0x3b0, (63u << 14u) | 3u}, + {0x3b8, 0x9000000}, {0x1e0, 0}, + {0xc, 0}, {0xd, 0x40040}, + {0x81, 0x80000000}, {0x82, 0x40040}, + {0x90, 0x80000000}, {0x91, 0x40040}, + {0x94, 0x80000000}, {0x95, 0x40040}, + {0x10f, std::bit_cast(32.0f)}, {0x110, std::bit_cast(32.0f)}, + {0x111, std::bit_cast(-2.0f)}, {0x112, std::bit_cast(2.0f)}, + {0x113, std::bit_cast(1.0f)}, {0x114, 0}, + {0xb4, 0}, {0xb5, std::bit_cast(1.0f)}, + {0x2fe, 0}, {0x302, 0}, {0x306, 0}, {0x30a, 0}, + {0x318, static_cast(color >> 8u)}, {0x390, static_cast(color >> 40u)}, {0x292, 2}, + }; + std::vector> shader{ + {0xc8, static_cast(vertex >> 8u)}, {0xc9, static_cast(vertex >> 40u)}, {0x8b, 1u << 1u}, {0x8c, 0}, + {0x008, static_cast(pixel >> 8u)}, {0x009, static_cast(pixel >> 40u)}, {0x00b, userWords << 1u}, + }; + for (std::uint32_t index = 0; index < userWords; ++index) shader.emplace_back(0x00cu + index, mode == Mode::Table ? tableWords[index] : mode == Mode::Bda && index >= 12u ? static_cast(reinterpret_cast(BufferMemory.data() + 1) >> (index == 12u ? 0u : 32u)) : descriptors[index]); + if (vertexSampling) { + shader.emplace_back(0x8bu, 12u << 1u); + for (std::uint32_t index = 0; index < 12u; ++index) shader.emplace_back(0x08cu + index, mode == Mode::VertexTable ? tableWords[index] : descriptors[index]); + shader.emplace_back(0x00bu, 0u); + } + std::vector commands; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + if (vertexSampling) { + Append(commands, 0x69, {0x1b6, 1}); + Append(commands, 0x69, {0x191, 1u << 10u}); + Append(commands, 0x69, {0x1b1, 0}); + } + for (const auto& [offset, value] : shader) Append(commands, 0x76, {offset, value}); + Append(commands, 0x2d, {3, 2}); + if (mode == Mode::Bda) { + const auto second = static_cast(reinterpret_cast(BufferMemory.data() + 2)); + Append(commands, 0x76, {0x00cu + 12u, static_cast(second)}); + Append(commands, 0x76, {0x00cu + 13u, static_cast(second >> 32u)}); + } + if (mode == Mode::MovedBuffer) { + const auto moved = bufferWords(BufferMemory.data() + 3, static_cast(sizeof(BufferMemory) - 3 * sizeof(float))); + for (std::uint32_t index = 0; index < 4u; ++index) Append(commands, 0x76, {0x00cu + 12u + index, moved[index]}); + } + if (mode == Mode::MovedTexture) { + for (std::uint32_t index = 0; index < 8u; ++index) Append(commands, 0x76, {0x00cu + index, otherImage[index]}); + } + Append(commands, 0x2d, {3, 2}); + return commands; +} + +void DrawSamplesTheTexture(bool heap, Mode mode) { + const bool buffer = mode == Mode::Buffer || mode == Mode::Bda || mode == Mode::MovedBuffer; + ColorMemory.fill(Kept); + StorageMemory.fill(0u); + BufferMemory.fill(0.0f); + BufferMemory[1] = BufferAlpha; + BufferMemory[2] = SecondAlpha; + BufferMemory[3] = SecondAlpha; + for (std::size_t offset = 0; offset < TextureMemory.size(); offset += Texel.size()) std::memcpy(TextureMemory.data() + offset, Texel.data(), Texel.size()); + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + for (std::size_t offset = 0; offset < OtherTextureMemory.size(); offset += 4) OtherTextureMemory[offset] = OtherTextureMemory[offset + 1] = OtherTextureMemory[offset + 2] = OtherTextureMemory[offset + 3] = 0x33u; + const bool vertexSampling = mode == Mode::Vertex || mode == Mode::VertexTable; + const auto* code = mode == Mode::Table ? TablePixelCode.data() : mode == Mode::Gds ? GdsPixelCode.data() : mode == Mode::Storage ? StoragePixelCode.data() : mode == Mode::Bda ? BdaPixelCode.data() : buffer ? BufferPixelCode.data() : vertexSampling ? InterpolantPixelCode.data() : PixelCode.data(); + const auto bytes = mode == Mode::Table ? sizeof(TablePixelCode) : mode == Mode::Gds ? sizeof(GdsPixelCode) : mode == Mode::Storage ? sizeof(StoragePixelCode) : mode == Mode::Bda ? sizeof(BdaPixelCode) : buffer ? sizeof(BufferPixelCode) : vertexSampling ? sizeof(InterpolantPixelCode) : sizeof(PixelCode); + if (mode == Mode::Vertex) Registered(VertexHeader, SamplingVertexCode.data(), sizeof(SamplingVertexCode), 2); + if (mode == Mode::VertexTable) Registered(VertexHeader, TableVertexCode.data(), sizeof(TableVertexCode), 2); + Registered(PixelHeader, code, bytes, 1); + const auto takenBefore = AgcDriver::DriverDetail::HeapStagesTaken(); + const auto tablesBefore = AgcDriver::Graphics::ImageTableBuilds(); + const auto pushesBefore = AgcDriver::Graphics::DataAddressPushes(); + auto* gdsCounter = reinterpret_cast(AgcDriver::Pm4::GdsAddress() + 0x10u); + if (mode == Mode::Gds) *gdsCounter = 0u; + auto commands = Draw(code, mode); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); + std::size_t drawn = 0; + for (std::size_t offset = 0; offset < ColorMemory.size(); offset += 4) { + if (std::all_of(ColorMemory.begin() + static_cast(offset), ColorMemory.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) continue; + for (std::size_t channel = 0; channel < 4; ++channel) { + const auto value = static_cast(ColorMemory[offset + channel]); + const unsigned expected = mode == Mode::MovedTexture ? 0x33u : (mode == Mode::Bda || mode == Mode::MovedBuffer) && channel == 3 ? SecondAlphaByte : buffer && channel == 3 ? BufferAlphaByte : Texel[channel]; + Require(value == expected, "pixel " + std::to_string(offset / 4) + " channel " + std::to_string(channel) + " is " + std::to_string(value) + ", expected " + std::to_string(expected) + (mode == Mode::Bda ? " (texture and BDA)" : mode == Mode::MovedBuffer ? " (texture and a buffer moved between two draws)" : mode == Mode::MovedTexture ? " (a texture changed between two draws)" : buffer ? " (texture and buffer)" : mode == Mode::Table ? " (image table)" : " (texture)") + (heap ? " through the heap" : "")); + } + ++drawn; + } + Require(drawn != 0, "the draw covered no pixel"); + if (mode == Mode::Table || mode == Mode::VertexTable) Require(AgcDriver::Graphics::ImageTableBuilds() > tablesBefore, std::string("the table draw's ") + (mode == Mode::Table ? "fragment" : "vertex") + " stage bound no image table"); + if (mode == Mode::Gds) Require(*gdsCounter != 0u, "the GDS append did not count the drawn lanes"); + if (mode == Mode::Storage) { + for (std::size_t channel = 0; channel < 4; ++channel) Require(StorageMemory[channel] == Texel[channel], "storage texel (0, 0) channel " + std::to_string(channel) + " is " + std::to_string(StorageMemory[channel]) + ", expected the sampled " + std::to_string(Texel[channel]) + (heap ? " through the heap" : "")); + } + if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) return; + const bool descriptorMemory = AgcDriver::Graphics::DescriptorHeapEnabled(); + if (heap && descriptorMemory && (mode == Mode::Vertex || mode == Mode::VertexTable)) Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, "the heap did not take the sampling vertex stage with descriptor memory"); + else if (heap && (mode == Mode::Vertex || mode == Mode::VertexTable)) Require(AgcDriver::DriverDetail::HeapStagesTaken() == takenBefore, "the heap took a vertex stage whose constants are read on the CPU"); + else if (heap) Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, std::string("the heap did not take the fragment stage") + (buffer ? " reading a buffer" : mode == Mode::Vertex ? " (vertex stage)" : mode == Mode::Bda ? " loading through BDA" : mode == Mode::Table ? " reading an image table" : mode == Mode::VertexTable ? " (vertex stage reading an image table)" : "")); + if (heap && descriptorMemory) Require(AgcDriver::Graphics::DataAddressPushes() > pushesBefore, "the heap stages did not read their shader data through pushed addresses"); +} + +} + +int main() { + setenv("APS5_EAGER_WRITEBACK", "1", 1); + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; + { + GuestAllocations::Mutation mutation; + mutation.Add(StorageMemory.data(), StorageMemory.size(), true, true, true); + mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); + } + DrawSamplesTheTexture(heap, Mode::Texture); + DrawSamplesTheTexture(heap, Mode::Buffer); + DrawSamplesTheTexture(heap, Mode::Storage); + DrawSamplesTheTexture(heap, Mode::Gds); + DrawSamplesTheTexture(heap, Mode::Vertex); + DrawSamplesTheTexture(heap, Mode::Bda); + DrawSamplesTheTexture(heap, Mode::Table); + DrawSamplesTheTexture(heap, Mode::VertexTable); + DrawSamplesTheTexture(heap, Mode::MovedBuffer); + DrawSamplesTheTexture(heap, Mode::MovedTexture); + if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) Require(AgcDriver::DriverDetail::HeapRefused(), "a draw found the capped heap full and the heap was not refused"); + AgcDriverShutdown_nid_postfix(); + if (heap && AgcDriver::Graphics::DescriptorHeapEnabled() && std::getenv("APS5_HEAP_SLOT_CAP") == nullptr) Require(AgcDriver::Graphics::EmptyResourceSets() != 0, "no heap draw bound without a per-draw resource set"); + std::cout << "A sampled texture reached the drawn pixels" << (heap ? " through the heap" : "") << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + AgcDriverShutdown_nid_postfix(); + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics.cpp index d603479954b0..6af312248bea 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" @@ -100,11 +101,12 @@ void Run(AgcDriver::VulkanDevice& device, std::uint32_t format) { ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(32), {0, 0, 0, 128} }; request.useCache = false; const auto result = ShaderRecompiler::Recompile(request); + Require(result.gpuResolvedImages == AgcDriver::Graphics::DescriptorHeapEnabled(), "the compute heap did not take the image atomic stage"); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics64.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics64.cpp index 02436563708e..c0777af38b0c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics64.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics64.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" @@ -123,11 +124,12 @@ void Run(AgcDriver::VulkanDevice& device, std::uint32_t format) { ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(32), {0, 0, 0, 128} }; request.useCache = false; const auto result = ShaderRecompiler::Recompile(request); + Require(result.gpuResolvedImages == AgcDriver::Graphics::DescriptorHeapEnabled(), "the compute heap did not take the image atomic stage"); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsBitwise.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsBitwise.cpp index ca6796d7a2c5..98f8b9c08264 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsBitwise.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsBitwise.cpp @@ -127,9 +127,9 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; FillInput(); - Run(*device, 32, device->Target()); + Run(*device, 32, device->ComputeTarget(32)); Check("wave32"); - Run(*device, 64, device->Target()); + Run(*device, 64, device->ComputeTarget(64)); Check("wave64"); Run(*device, 64, device->ComputeTarget(32)); Check("wave64 split"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsFloat.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsFloat.cpp index 78b36356c7db..b4e269aadbbd 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsFloat.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomicsFloat.cpp @@ -544,8 +544,8 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; for (const auto format : {Format32UInt, Format32SInt, Format32Float}) { - Run(*device, 32, device->Target(), "wave32", format); - Run(*device, 64, device->Target(), "wave64", format); + Run(*device, 32, device->ComputeTarget(32), "wave32", format); + Run(*device, 64, device->ComputeTarget(64), "wave64", format); Run(*device, 64, device->ComputeTarget(32), "wave64 split", format); } bool refused = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp index 765947dc99c7..2e4f4695e8be 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp @@ -7,6 +7,7 @@ #include "Optimization/ResourceMaterializer.hpp" #include "Optimization/SrtWalker.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "prx/libc/include/GuestArena.hpp" @@ -141,12 +142,17 @@ void Prepare(const GuestBlock& block) { void TablesChangingPerDispatch(const GuestBlock& block) { auto& cache = AgcDriver::Graphics::SharedResourceCache(); + const auto heapStages = AgcDriver::Graphics::HeapComputeStages(); std::uint64_t most = 0; for (std::uint32_t dispatch = 0; dispatch < 6; ++dispatch) { SetRecord(block, dispatch * 977u % Records, Elements + dispatch % Spare); Dispatch(block, 0); most = std::max(most, cache.TableElements()); } + if (AgcDriver::Graphics::DescriptorHeapEnabled()) { + Require(AgcDriver::Graphics::HeapComputeStages() > heapStages, "image table cache bounds: the dispatches did not take the descriptor heap"); + return; + } Require(most >= Elements, "image table cache bounds: no dispatch kept its table in the resource cache"); Require(most <= AgcDriver::Graphics::ResourceCache::TableElementBudget(), "image table cache bounds: tables that changed every dispatch kept " + std::to_string(most) + " table elements in the resource cache, over its budget of " + std::to_string(AgcDriver::Graphics::ResourceCache::TableElementBudget())); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MeshDrawRelocation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MeshDrawRelocation.cpp index 1b64d9d3dff9..5608ab54eae2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MeshDrawRelocation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MeshDrawRelocation.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" #include "../MeshGeometryFixture.hpp" #include "VulkanTestDevice.hpp" @@ -103,6 +104,7 @@ std::vector Setup(const std::array& descriptor) AgcDriver::DriverDetail::DrawEntryCounters Draw(const std::array& descriptor) { Pixels.fill(std::byte{0}); + const auto pushes = AgcDriver::Graphics::DataAddressPushes(); auto commands = Setup(descriptor); const auto address = reinterpret_cast(Indices.data()); commands.insert(commands.end(), {0xc0042700u, 3u, static_cast(address), static_cast(address >> 32u), 3u, 0u}); @@ -110,6 +112,7 @@ AgcDriver::DriverDetail::DrawEntryCounters Draw(const std::array(Pixels[(24u * Width + 16u) * 4u]) > 200u, "the mesh draw did not cover its triangle"); + Require(!AgcDriver::Graphics::DescriptorHeapEnabled() || AgcDriver::Graphics::DataAddressPushes() > pushes, "the submitted mesh draw did not take the descriptor heap"); return AgcDriver::DriverDetail::Driver::Get().DrawCacheCounters(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp index 5cc437a819d2..99a8a1b1cc4b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp @@ -299,8 +299,8 @@ class Run { realCreateImage = context.Function("vkCreateImage"); realDestroyImage = context.Function("vkDestroyImage"); realBindImageMemory = context.Function("vkBindImageMemory"); - realCreateImageView = context.Function("vkCreateImageView"); - realDestroyImageView = context.Function("vkDestroyImageView"); + realCreateImageView = reinterpret_cast(realProc(context.device, "vkCreateImageView")); + realDestroyImageView = reinterpret_cast(realProc(context.device, "vkDestroyImageView")); realClearColorImage = context.Function("vkCmdClearColorImage"); realCopyImage = context.Function("vkCmdCopyImage"); context.deviceProc = CountingDeviceProc; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp index 403380ca02f9..e1c84b912b70 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp @@ -1,6 +1,7 @@ #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" @@ -26,6 +27,7 @@ #endif #include #include +#include #include #include #include @@ -283,6 +285,65 @@ Totals Snapshot() { return {AgcDriver::Graphics::PipelineJournalTotals(), AgcDriver::Graphics::PipelineStoreTotals()}; } +alignas(256) constexpr std::array SampleCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; +constexpr std::array SampleTexel{0x10u, 0x80u, 0xc0u, 0xffu}; +alignas(256) std::array SampleTexture{}; +alignas(4096) std::array SampleOutput{}; + +ShaderRecompiler::RecompileResult CompileSample(AgcDriver::VulkanDevice& device) { + using namespace ShaderRecompiler; + const auto image = static_cast(reinterpret_cast(SampleTexture.data())); + const auto output = static_cast(reinterpret_cast(SampleOutput.data())); + const std::array userData{ + static_cast(image >> 8u), static_cast((image >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), 3u << 14u, 0xfacu | (9u << 28u), 0u, 0u, 0u, 0u, + 0u, 0u, 0u, 0u, + static_cast(output), static_cast(output >> 32u) & 0xffffu, static_cast(4u * sizeof(float)), 0x31016facu, + }; + const std::span code(SampleCode); + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderComputeStageInfo compute{{1u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; + RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, memory}, device.ComputeTarget(32u), {0u, 0u, 0u, 128u}}; + return Recompile(request); +} + +void DispatchSample(AgcDriver::VulkanDevice& device, const char* what) { + SampleOutput.fill(-1.0f); + const auto result = CompileSample(device); + Require(result.gpuResolvedImages, std::string(what) + ": the sampling compute stage is not GPU mode"); + const auto before = AgcDriver::Graphics::HeapComputeStages(); + device.Dispatch(result, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); + device.WaitIdle(); + Require(AgcDriver::Graphics::HeapComputeStages() > before, std::string(what) + ": the heap did not take the sampling compute stage"); + for (std::size_t channel = 0; channel < SampleTexel.size(); ++channel) { + const float wanted = static_cast(SampleTexel[channel]) / 255.0f; + Require(std::fabs(SampleOutput[channel] - wanted) < 1e-6f, std::string(what) + ": channel " + std::to_string(channel) + " is " + std::to_string(SampleOutput[channel]) + ", expected " + std::to_string(wanted)); + } +} + +void HeapJournalTests() { + for (std::size_t offset = 0; offset < SampleTexture.size(); offset += SampleTexel.size()) std::memcpy(SampleTexture.data() + offset, SampleTexel.data(), SampleTexel.size()); + { + const auto device = OpenVulkanTestDevice(); + Require(device != nullptr, "the first device is required once the second opened"); + device->WaitForPipelineJournalReplay(); + DispatchSample(*device, "first run"); + Require(device->ComputePipelinesCreated() == 1, "the first run did not build exactly one compute pipeline"); + AgcDriver::Graphics::FlushPipelineJournal(); + Require(Snapshot().journal.recordedCompute == 1, "the first run did not record the GPU-mode compute pipeline"); + } + { + const auto device = OpenVulkanTestDevice(); + Require(device != nullptr, "the second device could not be opened"); + device->WaitForPipelineJournalReplay(); + const auto replayed = Snapshot(); + Require(replayed.journal.replayedCompute == 1 && replayed.journal.replayFailed == 0 && replayed.journal.replayRejected == 0, "the replay did not build the GPU-mode compute pipeline"); + Require(device->ComputePipelinesCreated() == 1, "the replay did not build the compute pipeline on the new device"); + Require(device->DescriptorHeapComputePipelines() == 1, "the replay did not build the GPU-mode compute pipeline on the descriptor heap"); + DispatchSample(*device, "second run"); + Require(device->ComputePipelinesCreated() == 1, "the second run's dispatch built a compute pipeline the replay had built"); + } +} + void JournalTests() { using namespace NarrowConstantStoreFixture; Require(AgcDriver::Graphics::PipelineJournalEnabled(), "the pipeline journal is disabled although the shader cache directory is set"); @@ -720,6 +781,11 @@ int main(int argc, char** argv) { Benchmark(argc >= 3 ? static_cast(std::strtoul(argv[2], nullptr, 10)) : 24u); return 0; } + if (argc >= 2 && std::string(argv[1]) == "--gpu-heap") { + HeapJournalTests(); + std::puts("pipeline journal record and replay of a GPU-mode compute stage passed"); + return 0; + } JournalTests(); NewestEntriesTests(); EvictionTests(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PixelBarycentricEmulation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PixelBarycentricEmulation.cpp index 6eb4c60d138b..61585e0e2757 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PixelBarycentricEmulation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PixelBarycentricEmulation.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" #include "VulkanTestDevice.hpp" @@ -86,6 +87,7 @@ ShaderRecompiler::RecompileResult Draw(AgcDriver::VulkanDevice& device, Emulatio Pixels.fill(Unwritten); auto target = device.Target(); target.fragmentShaderBarycentricEnabled = false; + target.gpuResolvedImages = AgcDriver::Graphics::DescriptorHeapEnabled(); static const auto trianglePositions = ClipPositions(Emulation::Geometry); static const auto rectanglePositions = ClipPositions(Emulation::RectList); static const auto stripPositions = StripPositions(); @@ -124,6 +126,7 @@ ShaderRecompiler::RecompileResult Draw(AgcDriver::VulkanDevice& device, Emulatio }; fragment.useCache = false; auto pixelResult = ShaderRecompiler::Recompile(fragment); + AgcDriver::Graphics::Require(vertexResult.gpuResolvedImages == target.gpuResolvedImages && pixelResult.gpuResolvedImages == target.gpuResolvedImages, "the barycentric draw's stages did not take GPU mode"); std::vector shaders{{ShaderStage::Vertex, &vertexResult, 0}}; ShaderRecompiler::RecompileResult geometry; ShaderRecompiler::BarycentricTessellationShaders patches; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp index 56ea345d1fe3..160c69ad9227 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp @@ -23,6 +23,12 @@ namespace { +std::vector PreparePerDrawStages(const AgcDriver::DriverDetail::DrawDecode& decoded, const ShaderRecompiler::SpirvTarget& target) { + auto stages = AgcDriver::DriverDetail::PrepareGraphicsStages(decoded, target); + std::erase_if(stages, [](const AgcDriver::DriverDetail::PreparedGraphicsStage& stage) { return stage.heapVariant; }); + return stages; +} + void Require(bool condition, const char* message) { if (!condition) throw std::runtime_error(message); } @@ -134,7 +140,7 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path target.mesh = MeshTargetLimits{{128, 1, 1}, 128, 32768, 256, 256, 128, 32768, 1, 1}; target.spirvVersion = 0x00010400u; } - const auto stages = PrepareGraphicsStages(prepared, target); + const auto stages = PreparePerDrawStages(prepared, target); Require(stages.size() == (tessellation ? 4u : 2u), "graphics preparation compiled the wrong stages"); if (!mesh && !tessellation && target.registrationModules) { const auto prebuild = [&](const std::vector& group, std::initializer_list picked) { @@ -155,7 +161,7 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path Require(pixelOnly.second == 1u, "registration modules: the pixel stage alone did not build its fragment library"); const auto pair = prebuild(stages, {0u, 1u}); Require(pair.first == 0u && pair.second == 0u, "registration modules: the pair of stages did not find the libraries prebuilt one stage at a time"); - const auto again = PrepareGraphicsStages(prepared, target); + const auto again = PreparePerDrawStages(prepared, target); Require(again.front().registration != stages.front().registration, "registration modules: the second preparation reused the first result object"); const auto repeated = prebuild(again, {0u, 1u}); Require(repeated.first == 0u && repeated.second == 0u, "registration modules: another materialization of the same stages did not find the prebuilt libraries"); @@ -194,7 +200,7 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path auto changed = prepared; changed.state.stages.vertexWaveSize = 64; changed.pixel.interpolatorSettings[0] = 0x404u; - const auto newStages = PrepareGraphicsStages(changed, target); + const auto newStages = PreparePerDrawStages(changed, target); front.snapshot->prepared->entries.push_back(newStages.front().entry); ResolvePreparedGraphics(*front.snapshot, {}, 7, target); const auto newVertexId = GetPreparedArtifact(*newStages.front().entry.handle).variantId; @@ -216,7 +222,7 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path Require(front.snapshot->prepared->rectangleProgress.size() == 1 && !front.snapshot->prepared->rectangleProgress.front().fragment.expired(), "expired rectangle progress was not removed"); auto drawOnly = prepared; drawOnly.pixel.interpolatorSettings[0] = 0x405u; - const auto drawStages = PrepareGraphicsStages(drawOnly, target); + const auto drawStages = PreparePerDrawStages(drawOnly, target); auto unlinked = std::make_shared(); unlinked->type = 1; unlinked->prepared->entries.push_back(drawStages.back().entry); @@ -238,10 +244,10 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path } auto incomplete = prepared; incomplete.roles.pop_back(); - Reject([&] { static_cast(PrepareGraphicsStages(incomplete, target)); }, "program roles are incomplete"); + Reject([&] { static_cast(PreparePerDrawStages(incomplete, target)); }, "program roles are incomplete"); auto wrongEntry = prepared; wrongEntry.programs.front().binary.codeAddress += 4; - Reject([&] { static_cast(PrepareGraphicsStages(wrongEntry, target)); }, "entry point differs"); + Reject([&] { static_cast(PreparePerDrawStages(wrongEntry, target)); }, "entry point differs"); std::vector linked; std::vector memory; for (std::size_t index = 0; index < draw.programs.size(); ++index) { @@ -285,7 +291,7 @@ void Check(AgcDriver::VulkanDevice& device, AgcDriver::Graphics::ShaderPath path resolved.pixel = prepared.pixel; DecodeGraphicsPrograms(resolved, unbound, registry, true, true); Require(resolved.programs.size() == 3u && resolved.roles.front() == ProgramRole::Hull, "an unbound local program was not left to the draw"); - Require(PrepareGraphicsStages(resolved, target).size() == 3u, "graphics preparation without the local program compiled the wrong stages"); + Require(PreparePerDrawStages(resolved, target).size() == 3u, "graphics preparation without the local program compiled the wrong stages"); auto bound = queue; late.Bind(bound, 0x148u, 0x10bu); DrawDecode lateDraw{}; @@ -347,7 +353,7 @@ void PrebuildPolicyReadback(AgcDriver::VulkanDevice& device, bool disabled) { append(ShaderStage::Vertex, vertexCode, {static_cast(address), static_cast(address >> 32u) | (16u << 16u), 3u, 0x01016facu}); append(ShaderStage::Fragment, pixelCode, {}); const auto target = device.Target(); - const auto stages = PrepareGraphicsStages(decoded, target); + const auto stages = PreparePerDrawStages(decoded, target); Require(stages.size() == 2u, "prebuild policy lost a required graphics stage"); for (const auto& stage : stages) { Require(stage.entry.handle != nullptr && stage.snapshot != nullptr, "prebuild policy lost a required source handle"); @@ -449,7 +455,7 @@ void RetainedPixelMatchesNullProgram(AgcDriver::VulkanDevice& device) { Require(AgcDriver::Graphics::DrawKeyCovers(read), "a pixel substitution dependency is absent from the draw key"); Require(read.bank != AgcDriver::Graphics::RegisterBank::Shader || read.offset < 0x00bu || read.offset > 0x02bu, "the substituted program read fragment resources or userdata"); } - const auto stages = PrepareGraphicsStages(draw, device.Target()); + const auto stages = PreparePerDrawStages(draw, device.Target()); Require(stages.size() == 2 && stages.back().entry.handle != nullptr, "a retained-format null program was not prepared"); std::vector linked; std::vector memory; @@ -706,7 +712,7 @@ void NullPixelMatchesRegistration(AgcDriver::VulkanDevice& device) { DecodeGraphicsPrograms(draw, queue, registry, false, true); const auto& fragment = draw.programs.back(); Require(fragment.snapshot == null && fragment.userData.empty(), "a null pixel draw took the last pixel shader's user SGPRs"); - const auto stages = PrepareGraphicsStages(draw, device.Target()); + const auto stages = PreparePerDrawStages(draw, device.Target()); const auto& handle = stages.back().entry.handle; Require(std::ranges::any_of(registered, [&](const auto& entry) { return entry.handle == handle; }), "a null pixel draw did not match the variant prepared at registration"); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp index 88ecd918f86c..d3cdde12181a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp @@ -73,6 +73,7 @@ void RunUnregistered(AgcDriver::VulkanDevice& device, ShaderRecompiler::Recompil Require(snapshot.prepared->entries.size() == 1, "unregistered compute invocation did not cache exactly one artifact"); const auto handle = snapshot.prepared->entries.front().handle; const auto& artifact = ShaderRecompiler::GetPreparedArtifact(*handle); + const std::uint32_t* module = artifact.gpuResolvedImages ? nullptr : artifact.spirv.data(); for (const bool useCache : {false, true}) { request.useCache = useCache; Require(AgcDriver::DriverDetail::SourceHandleFor(snapshot, 0, request) == handle, "unregistered compute source was prepared again"); @@ -81,7 +82,8 @@ void RunUnregistered(AgcDriver::VulkanDevice& device, ShaderRecompiler::Recompil runtime.userData = request.context.userData; const auto capture = repeated.Capture(runtime); const auto result = repeated.Materialize(*capture); - Require(snapshot.prepared->entries.size() == 1 && result->variantId == artifact.variantId && result->spirv.data() == artifact.spirv.data(), "unregistered compute invocation replaced its cached artifact"); + if (module == nullptr) module = result->spirv.data(); + Require(snapshot.prepared->entries.size() == 1 && result->variantId == artifact.variantId && result->spirv.data() == module, "unregistered compute invocation replaced its cached artifact"); device.Dispatch(*result, 1, 1, 1); } device.WaitIdle(); @@ -124,6 +126,7 @@ void Run(AgcDriver::VulkanDevice& device) { snapshot.prepared->entries.push_back({0, handle}); ExpectFailure([&] { static_cast(AgcDriver::DriverDetail::SourceHandleFor(snapshot, 1, request)); }, "outside the snapshot"); const auto& artifact = ShaderRecompiler::GetPreparedArtifact(*handle); + const std::uint32_t* module = artifact.gpuResolvedImages ? nullptr : artifact.spirv.data(); for (std::uint32_t value = 0; value < 8; ++value) { users.fill(value); request.useCache = value % 2 == 0; @@ -132,7 +135,8 @@ void Run(AgcDriver::VulkanDevice& device) { runtime.userData = users; const auto capture = ShaderRecompiler::CaptureResources(request, runtime, *ready); const auto result = ShaderRecompiler::MaterializeShader(request, *capture, *ready); - Require(result->variantId == artifact.variantId && result->spirv.data() == artifact.spirv.data(), "invocation replaced the prepared artifact"); + if (module == nullptr) module = result->spirv.data(); + Require(result->variantId == artifact.variantId && result->spirv.data() == module, "invocation replaced the prepared artifact"); device.Dispatch(*result, 1, 1, 1); } device.WaitIdle(); @@ -168,7 +172,7 @@ void Run(AgcDriver::VulkanDevice& device) { const auto replacementInvocation = AgcDriver::DriverDetail::InvocationFor(snapshot, 0, replacementRequest); const auto replacementCapture = replacementInvocation.Capture(preparedRuntime); const auto replacementResult = replacementInvocation.Materialize(*replacementCapture); - Require(replacementResult->spirv.data() == artifact.spirv.data(), "device replacement recompiled the prepared shader"); + Require(replacementResult->spirv.data() == (artifact.gpuResolvedImages ? firstResult->spirv.data() : artifact.spirv.data()), "device replacement recompiled the prepared shader"); replacement->Dispatch(*replacementResult, 1, 1, 1); replacement->WaitIdle(); replacementRequest.target.nonConstantImageOffsets = !replacementRequest.target.nonConstantImageOffsets; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/Tessellation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/Tessellation.cpp index 7f13530d09a3..43b4a9525f12 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/Tessellation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/Tessellation.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libc/include/GuestAllocations.hpp" @@ -571,6 +572,8 @@ void Draw(AgcDriver::VulkanDevice& device, const Stages& stages, VkCullModeFlags for (std::size_t i = 0; i < Pixels.size(); i += 4) { for (std::size_t c = 0; c < 4; ++c) Pixels[i + c] = std::byte{Background[c]}; } + const bool heap = AgcDriver::Graphics::DescriptorHeapEnabled(); + Require(stages.local.gpuResolvedImages == heap && stages.hull.gpuResolvedImages == heap && stages.domain.gpuResolvedImages == heap && stages.fragment.gpuResolvedImages == heap, "the tessellation draw's stages did not take GPU mode"); std::uint32_t cursor = 0; const auto offset = [&](const ShaderRecompiler::RecompileResult& result) { const auto at = result.pushConstants.empty() ? 0u : cursor; @@ -1006,7 +1009,8 @@ int main() { try { auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; - const auto target = device->Target(); + auto target = device->Target(); + target.gpuResolvedImages = AgcDriver::Graphics::DescriptorHeapEnabled(); if (!target.tessellation.has_value()) { std::puts("tessellation: skipped, the device has no tessellation shaders"); return VulkanTestSkipped; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp new file mode 100644 index 000000000000..4dfb1bb9a642 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp @@ -0,0 +1,212 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::uint32_t Width = 256; +constexpr std::uint32_t Height = 80; +constexpr std::array Background{16, 24, 40, 255}; +alignas(256) std::array Pixels{}; +alignas(256) std::array HullUserMemory{}; + +alignas(256) constexpr std::array LocalCode{ + 0xd5480004, 0x02090502, 0xd5480005, 0x02090102, 0xd5480006, 0x02110902, 0xd5480007, 0x02111102, + 0x7e080d04, 0x7e0a0d05, 0x7e0c0d06, 0x7e0e0d07, 0x10100cff, 0x3f19999a, 0x061010ff, 0xbf666666, + 0x3e1008ff, 0x3e800000, 0xd54b0009, 0x03c5e105, 0x161406a0, 0xd9340000, 0x0000080a, 0xd8340008, + 0x0000070a, 0xd8340010, 0x0000070a, 0xbf8cc07f, 0xbefd2106, +}; + +alignas(256) constexpr std::array HullCode{ + 0xd7650000, 0x000100c1, 0xd7660000, 0x000200c1, 0xbf8a0000, 0x7da206f9, 0x81060000, 0xd5480014, + 0x02151101, 0x362402ff, 0x000000ff, 0x160028a0, 0xd5430015, 0x040224ff, 0x00000060, 0xdbfc0000, + 0x02000015, 0x162c2890, 0xd5430016, 0x045a24ff, 0x00000030, 0xbf8cc07f, 0xe0781000, 0x02020216, + 0x7da82881, 0xbe94047e, 0xb06a0060, 0x162602f9, 0x0086066a, 0xd8d80008, 0x06000013, 0xd8dc1008, + 0x07000013, 0xbf8cc07f, 0x7e300306, 0x7e320306, 0x7e340306, 0x7e360306, 0x34142484, 0xbefe0414, + 0xe0781000, 0x0403180a, 0x4a162481, 0x16161690, 0x4c1616ff, 0x00008000, 0xe0741000, 0x0202070b, + 0xbf810000, +}; + +alignas(256) constexpr std::array DomainCode{ + 0xf8000941, 0x00000000, 0x34020e84, 0x16020283, 0xe0341000, 0x04030a01, 0xe0341010, 0x04030c01, + 0xe0341020, 0x04030e01, 0xbf8c3f70, 0x08040af2, 0x08040d02, 0x10201505, 0x3e201906, 0x3e201d02, + 0x10221705, 0x3e221b06, 0x3e221f02, 0xd5510012, 0x040a0d05, 0x102424ff, 0x40400000, 0x7e260280, + 0x7e2802f2, 0xf80008cf, 0x14131110, 0xf800020f, 0x14131214, 0xbf810000, +}; + +alignas(256) constexpr std::array PixelCode{ + 0xc8020002, 0xc8060102, 0xc80a0202, 0xc80e0302, 0xf800180f, 0x03020100, 0xbf810000, +}; + +constexpr std::array PatchLevels{1u, 0u, 5u}; + +constexpr std::uint16_t Corner(std::uint32_t patch, std::uint32_t x, std::uint32_t y) { + return static_cast((PatchLevels[patch] << 8u) | (patch << 4u) | (x << 2u) | y); +} + +alignas(256) constexpr std::array Indices{ + Corner(0, 0, 0), Corner(0, 2, 0), Corner(0, 1, 2), + Corner(1, 0, 0), Corner(1, 2, 0), Corner(1, 1, 2), + Corner(2, 0, 0), Corner(2, 2, 0), Corner(2, 1, 2), +}; + +struct Header { + Shader shader{}; + ShaderUserData users{}; +}; + +Header LocalHeader{}; +Header HullHeader{}; +Header DomainHeader{}; +Header PixelHeader{}; + +void Register(Header& header, const std::uint32_t* code, std::size_t size, std::uint8_t type) { + header.shader.file_header = 0x34333231u; + header.shader.version = 0x18u; + header.shader.header_size = sizeof(header); + header.shader.shader_size = static_cast(size); + header.shader.code = code; + header.shader.type = type; + header.shader.user_data = &header.users; + AgcDriverRegisterShader_nid_postfix(&header.shader); +} + +void Write(std::vector& commands, std::uint32_t opcode, std::uint32_t offset, std::uint32_t value) { + commands.insert(commands.end(), {0xc0010000u | (opcode << 8u), offset, value}); +} + +std::uint32_t Lo(const void* address) { + return static_cast(reinterpret_cast(address) >> 8u); +} + +std::uint32_t Hi(const void* address) { + return static_cast(reinterpret_cast(address) >> 40u); +} + +std::vector Commands() { + const auto color = reinterpret_cast(Pixels.data()); + const auto users = reinterpret_cast(HullUserMemory.data()); + const std::vector> context{ + {0x2d5, 0x0200210du}, {0x2d6, 128u | (3u << 8u) | (3u << 14u)}, {0x2db, 1u | (2u << 2u) | (2u << 5u)}, + {0x286, std::bit_cast(64.0f)}, {0x287, std::bit_cast(1.0f)}, + {0x1b6, 1}, {0x191, 0x400}, {0x1b3, 0}, {0x1b4, 0}, + {0x260, 0}, {0x207, 0}, {0x200, 0}, {0x203, 0x800}, + {0x2dc, 0xaa00}, {0x2f8, 0}, {0x292, 2}, {0x293, 0}, + {0x80, 0}, {0x8d, 0}, {0x83, 0xffff}, {0x8c, 0xa}, + {0x2f9, 0x2d}, {0x313, 0x6000}, {0x30e, 0xffffffff}, {0x30f, 0xffffffff}, + {0x206, 0x43f}, {0x204, 0x80000}, {0x205, 0x240}, + {0x8e, 0xf}, {0x8f, 0xf}, {0x202, 0xcc0010}, + {0x1c4, 0}, {0x1c5, 9}, {0x1c3, 4}, {0x31c, 0x28028}, + {0x31b, 0}, {0x31d, 0}, {0x3b0, ((Width - 1u) << 14u) | (Height - 1u)}, + {0x3b8, 0x9000000}, {0x1e0, 0}, {0xc, 0}, {0xd, (Height << 16u) | Width}, + {0x81, 0x80000000}, {0x82, (Height << 16u) | Width}, + {0x90, 0x80000000}, {0x91, (Height << 16u) | Width}, + {0x94, 0x80000000}, {0x95, (Height << 16u) | Width}, + {0x318, static_cast(color >> 8u)}, {0x390, static_cast(color >> 40u)}, + {0x10f, std::bit_cast(Width / 2.0f)}, {0x110, std::bit_cast(Width / 2.0f)}, + {0x111, std::bit_cast(-(Height / 2.0f))}, {0x112, std::bit_cast(Height / 2.0f)}, + {0x113, std::bit_cast(1.0f)}, {0x114, 0}, + {0xb4, 0}, {0xb5, std::bit_cast(1.0f)} + }; + const std::vector> shaders{ + {0x148, Lo(LocalCode.data())}, {0x149, Hi(LocalCode.data())}, + {0x108, Lo(HullCode.data())}, {0x109, Hi(HullCode.data())}, + {0x102, static_cast(users)}, {0x103, static_cast(users >> 32u)}, {0x10b, 0}, + {0xc8, Lo(DomainCode.data())}, {0xc9, Hi(DomainCode.data())}, {0x8b, 0}, + {0x8, Lo(PixelCode.data())}, {0x9, Hi(PixelCode.data())}, {0xb, 0} + }; + std::vector commands; + Write(commands, 0x79, 0x242, 9); + for (const auto& [offset, value] : context) Write(commands, 0x69, offset, value); + for (const auto& [offset, value] : shaders) Write(commands, 0x76, offset, value); + commands.insert(commands.end(), {0xc0002a00u, 0u}); + const auto address = reinterpret_cast(Indices.data()); + commands.insert(commands.end(), {0xc0042700u, static_cast(Indices.size()), static_cast(address), static_cast(address >> 32u), static_cast(Indices.size()), 0u}); + return commands; +} + +std::array PixelAt(std::uint32_t x, std::uint32_t y) { + const auto offset = (static_cast(y) * Width + x) * 4u; + return {std::to_integer(Pixels[offset]), std::to_integer(Pixels[offset + 1]), std::to_integer(Pixels[offset + 2]), std::to_integer(Pixels[offset + 3])}; +} + +std::string PixelText(const std::array& pixel) { + return "(" + std::to_string(pixel[0]) + ", " + std::to_string(pixel[1]) + ", " + std::to_string(pixel[2]) + ", " + std::to_string(pixel[3]) + ")"; +} + +std::uint32_t Column(std::uint32_t patch, float offset) { + return static_cast((-0.9f + 0.6f * static_cast(patch) + offset + 1.0f) * 0.5f * Width); +} + +std::uint32_t Row(float y) { + return static_cast((1.0f - y) * 0.5f * Height); +} + +std::uint32_t CoveredPixels(std::uint32_t patch, bool interior) { + std::uint32_t count = 0; + for (std::uint32_t y = Row(0.5f); y <= Row(-0.5f) && y < Height; ++y) { + for (std::uint32_t x = Column(patch, 0.0f); x <= Column(patch, 0.5f) && x < Width; ++x) { + const auto pixel = PixelAt(x, y); + if (pixel == Background) continue; + Require(pixel[0] == 255 && pixel[2] == 0 && pixel[3] == 255, "patch " + std::to_string(patch) + " pixel (" + std::to_string(x) + ", " + std::to_string(y) + ") is " + PixelText(pixel)); + if (!interior || pixel[1] > 32) ++count; + } + } + return count; +} + +void SubmittedPatches() { + for (std::size_t i = 0; i < Pixels.size(); i += 4) { + for (std::size_t c = 0; c < 4; ++c) Pixels[i + c] = std::byte{Background[c]}; + } + const auto pushes = AgcDriver::Graphics::DataAddressPushes(); + auto commands = Commands(); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "tessellation submission failed"); + AgcDriverWaitIdle_nid_postfix(); + const auto center = Row(-0.5f + 1.0f / 3.0f); + Require(CoveredPixels(0, false) > 100 && CoveredPixels(0, true) == 0, "the level-1 patch was not drawn as one flat triangle, centre " + PixelText(PixelAt(Column(0, 0.25f), center))); + Require(CoveredPixels(1, false) == 0, "the patch with level 0 was not culled"); + Require(CoveredPixels(2, false) > 100 && PixelAt(Column(2, 0.25f), center)[1] > 32, "the level-5 patch has no interior domain points at its centre, " + PixelText(PixelAt(Column(2, 0.25f), center))); + Require(PixelAt(0, 0) == Background && PixelAt(Width - 1, Height - 1) == Background, "the corners changed"); + Require(!AgcDriver::Graphics::DescriptorHeapEnabled() || AgcDriver::Graphics::DataAddressPushes() > pushes, "the submitted tessellation draw did not take the descriptor heap"); +} + +} + +int main() { + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (!device->Target().tessellation.has_value()) { + std::cout << "skipped, the device has no tessellation shaders\n"; + return VulkanTestSkipped; + } + } + Register(LocalHeader, LocalCode.data(), sizeof(LocalCode), 5); + Register(HullHeader, HullCode.data(), sizeof(HullCode), 7); + Register(DomainHeader, DomainCode.data(), sizeof(DomainCode), 2); + Register(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1); + SubmittedPatches(); + AgcDriverShutdown_nid_postfix(); + std::cout << "A submitted tessellation draw drew its patches\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + AgcDriverShutdown_nid_postfix(); + return 1; + } +} diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index 7ef4a942a8ae..d0ba5adf8410 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -240,8 +240,13 @@ function(add_shader_recompiler target runtimeTarget) endif() set(shaderCacheReviewedNames BdaAbi::RangesOrdered + RuntimeAbi::GpuHeapStorageKind + StorageElementPointer + FirstAtomicStorageImageBinding BuildBarycentricGeometryShader BuildBarycentricTessellationShaders + HeapFragmentEligible + CompleteHeapDataWords BuildPreparedShaderKey BuildRectListShaders CaptureResources diff --git a/core/shader/recompiler/CacheKey.hpp b/core/shader/recompiler/CacheKey.hpp index 8c5d2b2678ba..e959bd7415e4 100644 --- a/core/shader/recompiler/CacheKey.hpp +++ b/core/shader/recompiler/CacheKey.hpp @@ -6,6 +6,10 @@ #include "prx/libc/include/HostThreadLocal.hpp" #include #include +#include +#include +#include +#include #include #include #include @@ -330,6 +334,8 @@ class RecompileCacheKey { append(key, value.largePixelFunctionLdsBuffer); append(key, value.pixelFunctionStorageDwords); append(key, value.deviceScopeLdsMemoryBarriers); + append(key, value.gpuResolvedImages); + append(key, value.descriptorMemory); } }; diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp index 809c3e0932e3..b15dfa3d3a46 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp @@ -39,12 +39,18 @@ struct IrDescriptorBinding { struct IrBindingLayout { std::uint32_t pushDataStartDword = PushData::NoStart; + std::uint32_t dataAddressDword = PushData::NoStart; std::uint32_t stencilReferenceDword = PushData::NoStart; std::uint32_t memoryOffsetDword = 0; std::uint32_t memoryOffsetCount = 0; bool dispatchThreadLimit = false; std::uint32_t runtimeImageCount = 0; std::uint32_t runtimeStateDwords = 0; + std::uint32_t samplerSlotDwords = 0; + std::uint32_t imageSlotDwords = 0; + std::uint32_t bufferAddressDwords = 0; + bool gpuResolvedImages = false; + bool heapStorageImages = false; std::vector userDataRegisters; std::vector descriptors; @@ -57,19 +63,33 @@ struct IrBindingLayout { [[nodiscard]] std::uint32_t RuntimeStateDword() const { return ImageMetadataDword() + runtimeImageCount * (sizeof(RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t)); } - [[nodiscard]] std::uint32_t ShaderDataDwords() const { + [[nodiscard]] std::uint32_t SamplerSlotDword() const { return RuntimeStateDword() + runtimeStateDwords; } + [[nodiscard]] std::uint32_t ImageSlotDword() const { + return SamplerSlotDword() + samplerSlotDwords; + } + [[nodiscard]] std::uint32_t BufferAddressDword() const { + return ImageSlotDword() + imageSlotDwords; + } + [[nodiscard]] std::uint32_t ShaderDataDwords() const { + return BufferAddressDword() + bufferAddressDwords; + } + [[nodiscard]] bool HeapImageKind(DescriptorBindingKind kind) const { + const auto value = static_cast(kind); + return (value >= RuntimeAbi::FirstImageBinding && value < RuntimeAbi::FirstStorageImageBinding) || (heapStorageImages && RuntimeAbi::GpuHeapStorageKind(value)); + } [[nodiscard]] bool UsesPushData() const { return pushDataStartDword != PushData::NoStart; } + [[nodiscard]] bool UsesDataAddress() const { + return dataAddressDword != PushData::NoStart; + } [[nodiscard]] std::uint32_t PushSlotDword() const { return UsesPushData() ? pushDataStartDword / PushData::DwordCount * PushData::DwordCount : 0u; } void AdvancePushData(std::uint32_t& cursor) const { - if (UsesPushData()) { - cursor = pushDataStartDword + ShaderDataDwords(); - } + if (UsesPushData()) cursor = pushDataStartDword + ShaderDataDwords(); } bool operator==(const IrBindingLayout& other) const = default; diff --git a/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp b/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp index 7396e8e96d78..0b402bdff22c 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp @@ -24,7 +24,7 @@ struct BindingAllocationResult : CompiledBindingLayout { class BindingAllocator { public: - [[nodiscard]] BindingAllocationResult Allocate(IrProgram& program, const BindingLayout& layout, bool registrationModules = false, bool stencilReplay = false) const; + [[nodiscard]] BindingAllocationResult Allocate(IrProgram& program, const BindingLayout& layout, bool registrationModules = false, bool stencilReplay = false, bool gpuResolvedImages = false, bool descriptorMemory = false) const; [[nodiscard]] const IrDescriptorBinding& FindBinding(const IrBindingLayout& layout, DescriptorBindingKind kind) const; }; diff --git a/core/shader/recompiler/Optimization/include/Optimization/DescriptorBindingBuilder.hpp b/core/shader/recompiler/Optimization/include/Optimization/DescriptorBindingBuilder.hpp index 9d48693abaa1..2fb5ee135427 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/DescriptorBindingBuilder.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/DescriptorBindingBuilder.hpp @@ -32,7 +32,10 @@ struct DescriptorBindingPlan { std::vector imageMetadata; std::vector specialization; std::vector runtimeState; + std::vector heapSlotWords; bool storageData = false; + bool addressedBuffers = false; + bool addressedData = false; }; class DescriptorBindingBuilder { diff --git a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp index 7067a1fc6cec..2a3a7612b843 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp @@ -62,16 +62,22 @@ class PreparedShaderInvocation { public: static std::optional TryCreate(const RecompileRequest& request, const std::shared_ptr& handle); static std::optional TryCreate(const RecompileRequest& request, const std::shared_ptr& handle, std::span key); + static std::optional TryCreate(RecompileRequest&& request, const std::shared_ptr& handle, std::span key); const RecompileRequest& Request() const { return request; } std::shared_ptr Capture(const SrtRuntime& runtime) const; std::shared_ptr Materialize(const ResourceCapture& capture) const; + std::shared_ptr MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words) const; + const std::shared_ptr& Plan() const; + std::uint64_t VariantId() const; private: - PreparedShaderInvocation(const RecompileRequest& request, const std::shared_ptr& handle); + PreparedShaderInvocation(RecompileRequest request, const std::shared_ptr& handle); RecompileRequest request; std::shared_ptr handle; }; [[nodiscard]] std::span GetPreparedCode(const SourceHandle& handle); +[[nodiscard]] bool HeapFragmentEligible(const IrResourcePlan& plan); +void CompleteHeapDataWords(const RecompileResult& shared, HeapStageWords& words); [[nodiscard]] std::shared_ptr PrepareShader(const RecompileRequest& request); [[nodiscard]] std::shared_ptr PrepareShader(const RecompileRequest& request, ShaderPreparationContext* preparation); [[nodiscard]] bool MatchesPreparedShader(const RecompileRequest& request, const SourceHandle& handle); diff --git a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp index 1f6c140f8d78..81fbcc7ce3f0 100644 --- a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp +++ b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp @@ -68,7 +68,7 @@ bool usesGds(const IrProgram& program) { } -BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const BindingLayout& layout, bool registrationModules, bool stencilReplay) const { +BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const BindingLayout& layout, bool registrationModules, bool stencilReplay, bool gpuResolvedImages, bool descriptorMemory) const { IrProgramMetadata& metadata = program.Metadata(); if (!metadata.shaderInfoComplete || metadata.bindingLayoutComplete) { fail(metadata.shaderInfoComplete ? "shader binding layout failed: binding layout already allocated" @@ -113,9 +113,16 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin } next.runtimeStateDwords = (attributes + RuntimeAbi::VertexSelectorsPerDword - 1u) / RuntimeAbi::VertexSelectorsPerDword; } + if (gpuResolvedImages) { + next.samplerSlotDwords = static_cast(info.samplers.size()) * 2u; + next.gpuResolvedImages = true; + } const auto pushSize = layout.pushConstantSizeBytes / 4u; - next.pushDataStartDword = next.runtimeImageCount == 0u && next.ShaderDataDwords() != 0u && next.ShaderDataDwords() <= pushSize ? layout.pushConstantOffsetBytes / 4u : PushData::NoStart; - if (stencilReplay) { + next.pushDataStartDword = !gpuResolvedImages && next.runtimeImageCount == 0u && next.ShaderDataDwords() != 0u && next.ShaderDataDwords() <= pushSize ? layout.pushConstantOffsetBytes / 4u : PushData::NoStart; + if (descriptorMemory && gpuResolvedImages) next.dataAddressDword = RuntimeAbi::RootDword; + if (stencilReplay && next.UsesDataAddress()) { + next.stencilReferenceDword = RuntimeAbi::RootDword + RuntimeAbi::RootStencilReference; + } else if (stencilReplay) { const auto offset = next.UsesPushData() ? next.ShaderDataDwords() : 0u; if (offset >= pushSize) fail("stencil replay requires an unused push constant dword"); next.stencilReferenceDword = offset; @@ -153,6 +160,14 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin } } + next.heapStorageImages = gpuResolvedImages && descriptorMemory && next.gpuResolvedImages; + if (gpuResolvedImages && !registrationModules) { + for (const auto& descriptor : next.descriptors) { + if (next.HeapImageKind(descriptor.kind)) next.imageSlotDwords += static_cast(descriptor.resources.size()); + } + } + if (descriptorMemory && next.gpuResolvedImages) next.bufferAddressDwords = static_cast(info.buffers.size()) * 4u; + std::vector samplers; for (std::uint32_t i = 0; i < info.samplers.size(); i++) { if (info.samplers[i].table == NoTable) { @@ -204,7 +219,7 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin result.pushConstantOffsetBytes = result.layout.pushDataStartDword * static_cast(sizeof(std::uint32_t)); result.pushConstantSizeBytes = result.layout.ShaderDataDwords() * static_cast(sizeof(std::uint32_t)); } - if (stencilReplay) { + if (stencilReplay && !result.layout.UsesDataAddress()) { result.pushConstantOffsetBytes = layout.pushConstantOffsetBytes; result.pushConstantSizeBytes += sizeof(std::uint32_t); } diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index f11023d4b41c..efe8529408b8 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -309,6 +309,8 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l if (stage == IrShaderStage::Pixel && exportMappings.size() != 8u) fail("fragment runtime export mappings are missing"); if (info.images.size() > ShaderInfo::MaxImages) fail("runtime image count exceeds the static capacity"); DescriptorBindingPlan plan; + plan.addressedBuffers = layout.bufferAddressDwords != 0u; + plan.addressedData = layout.UsesDataAddress(); const auto unnormalized = ProveUnnormalized(info, snapshot); for (std::uint32_t index = 0; index < info.samplers.size(); ++index) { if (FoldsTexelOffsets(info.samplers[index])) plan.specialization.push_back({PipelineSpecialization::FoldOffsetBase + index, unnormalized.samplers[index] ? 1u : 0u}); @@ -410,10 +412,14 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l if (last < first || last - first >= RuntimeAbi::StorageMipSlots) fail("invalid dynamic storage mip range"); if (!registrationModules) plan.specialization.push_back({PipelineSpecialization::MipCountBase + index, last - first + 1u}); } + std::vector> activeElements(info.images.size(), {UINT32_MAX, 0u}); plan.bindings.reserve(layout.descriptors.size()); + const bool slotWords = layout.gpuResolvedImages && !registrationModules; + std::uint32_t imageSlotBase = layout.ImageSlotDword(); for (const auto& logical : layout.descriptors) { const bool imageHeap = ImageBindingResourceClass(logical.kind) != ImageResourceClass::None; const bool samplerHeap = logical.kind == DescriptorBindingKind::Samplers; + const bool sampledSlots = slotWords && layout.HeapImageKind(logical.kind); IrDescriptorBinding compact{logical.kind, {}}; std::vector originals; std::vector inactive; @@ -436,18 +442,24 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l active = (samplerModes.at(resource) & (1u << (element & 1u))) != 0u; } if ((imageHeap || samplerHeap) && !registrationModules) plan.specialization.push_back({PipelineSpecialization::DescriptorIndex(static_cast(logical.kind), element), active ? static_cast(compact.resources.size()) : 0u}); + if (active && sampledSlots) plan.heapSlotWords.push_back({imageSlotBase + element, static_cast(logical.kind), static_cast(compact.resources.size())}); + if (active && slotWords && samplerHeap) plan.heapSlotWords.push_back({layout.SamplerSlotDword() + element, static_cast(logical.kind), static_cast(compact.resources.size())}); if (active || ((imageHeap || samplerHeap) && registrationModules)) { compact.resources.push_back(resource); originals.push_back(element); inactive.push_back(!active); } } + if (sampledSlots) imageSlotBase += static_cast(logical.resources.size()); if ((imageHeap || samplerHeap) && !registrationModules) plan.specialization.push_back({PipelineSpecialization::HeapCountBase + static_cast(logical.kind), std::max(1u, static_cast(compact.resources.size()))}); if ((imageHeap || samplerHeap) && compact.resources.empty()) continue; PreparedDescriptorBinding entry{}; auto& physical = entry.descriptor; - physical.descriptorSet = fragmentDescriptorSet && stage == IrShaderStage::Pixel ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet; - physical.binding = NativeBinding(stage, compact.kind); + const bool heapImage = layout.HeapImageKind(compact.kind); + const bool heapSetBinding = heapImage || samplerHeap || compact.kind == DescriptorBindingKind::ShaderData || compact.kind == DescriptorBindingKind::FlattenedSrt; + const bool sharedHeapArray = layout.gpuResolvedImages && (heapImage || samplerHeap); + physical.descriptorSet = compact.kind == DescriptorBindingKind::Gds && layout.UsesDataAddress() ? RuntimeAbi::GpuGdsSet : layout.gpuResolvedImages ? (heapSetBinding ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet) : fragmentDescriptorSet && stage == IrShaderStage::Pixel ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet; + physical.binding = NativeBinding(sharedHeapArray ? IrShaderStage::Pixel : stage, compact.kind); physical.count = compact.resources.empty() ? 1u : static_cast(compact.resources.size()); physical.kind = PhysicalKindFor(compact.kind); physical.role = RoleFor(compact.kind); @@ -478,6 +490,7 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l physical.imageUnnormalizedBaseLevel.push_back(unnormalized.imagesAtBaseLevel.at(resource)); physical.imageSamplers.push_back(0u); physical.imageAtomic64.push_back(image.atomic64); + if (layout.gpuResolvedImages && !inactive[element] && activeElements[resource].first == UINT32_MAX && DescriptorBindingForImage(mode) == compact.kind) activeElements[resource] = {static_cast(compact.kind), static_cast(element)}; } } else if (physical.role == DescriptorRole::GuestSamplers) { for (std::uint32_t element = 0; element < compact.resources.size(); ++element) { @@ -508,6 +521,10 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l RuntimeAbi::ResourceMetadata metadata{}; if (descriptor.dwordCount != metadata.descriptor.size()) fail("invalid runtime image descriptor width"); metadata.elementCount = 1u; + if (layout.gpuResolvedImages && activeElements[resource].first != UINT32_MAX) { + metadata.binding = activeElements[resource].first; + metadata.firstElement = activeElements[resource].second; + } if (imageModes[resource] > RuntimeAbi::ImageModeMask) fail("runtime image mode exceeds its metadata field"); metadata.flags = imageModes[resource] << 1u | (registrationModules ? (compareStates[resource] & RuntimeAbi::CompareStateMask) << RuntimeAbi::CompareStateShift : 0u); if (descriptor.dwords[0] == 0u && (descriptor.dwords[1] & 0xffu) == 0u) metadata.flags |= 1u; @@ -545,10 +562,16 @@ DescriptorBindingPlan DescriptorBindingBuilder::Select(const DescriptorBindingPl std::set remaining(bindings.begin(), bindings.end()); selected.bindings.reserve(remaining.size()); for (const auto& binding : plan.bindings) { - if (remaining.erase(binding.descriptor.binding) == 0u) continue; + const bool addressed = (plan.addressedBuffers && binding.descriptor.role == DescriptorRole::GuestBuffers) || (plan.addressedData && (binding.descriptor.role == DescriptorRole::ShaderData || binding.descriptor.role == DescriptorRole::FlattenedSrt || binding.descriptor.role == DescriptorRole::BdaPagetable || binding.descriptor.role == DescriptorRole::FaultBuffer || binding.descriptor.role == DescriptorRole::ImageTable || binding.descriptor.role == DescriptorRole::ImageStorageTable || binding.descriptor.role == DescriptorRole::SamplerTable || binding.descriptor.role == DescriptorRole::ImageTableMap)); + if (remaining.erase(binding.descriptor.binding) == 0u && !addressed) continue; selected.storageData |= binding.descriptor.role == DescriptorRole::ShaderData; selected.bindings.push_back(binding); } + if (plan.addressedData) { + remaining.erase(NativeBinding(IrShaderStage::Pixel, static_cast(RuntimeAbi::FirstImageBinding))); + remaining.erase(NativeBinding(IrShaderStage::Pixel, static_cast(RuntimeAbi::FirstStorageImageBinding))); + remaining.erase(NativeBinding(IrShaderStage::Pixel, DescriptorBindingKind::Samplers)); + } if (!remaining.empty()) fail("specialized module bindings disagree with the prepared plan"); const bool hasSamplers = std::any_of(selected.bindings.begin(), selected.bindings.end(), [](const auto& binding) { return binding.descriptor.role == DescriptorRole::GuestSamplers; }); if (!hasSamplers) { @@ -559,6 +582,9 @@ DescriptorBindingPlan DescriptorBindingBuilder::Select(const DescriptorBindingPl } selected.imageMetadata = plan.imageMetadata; selected.runtimeState = plan.runtimeState; + selected.heapSlotWords = plan.heapSlotWords; + selected.addressedBuffers = plan.addressedBuffers; + selected.addressedData = plan.addressedData; return selected; } diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index fad7606ef9f5..93a11688c901 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -370,6 +370,19 @@ constexpr std::size_t ResultMemoSets = 64; constexpr std::size_t ResultMemoWays = 4; using ResultMemoTable = std::array; +struct UsedBindingPlan { + std::shared_ptr owner; + const DescriptorBindingPlan* plan = nullptr; +}; + +struct HeapTemplate { + std::shared_ptr result; + UsedBindingPlan plan; + std::vector buffers; + std::vector images; + std::vector samplers; +}; + struct SourceEntry : std::enable_shared_from_this { std::mutex mutex; // The code the entry was built for: the key carries only a hash of it, so a candidate entry is @@ -388,6 +401,7 @@ struct SourceEntry : std::enable_shared_from_this { std::vector emissionFailures; std::unique_ptr memo; std::uint64_t memoClock = 0; + std::unordered_map heapTemplates; }; namespace { @@ -588,7 +602,9 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) bool registration = request.target.registrationModules && (request.shader.stage == ShaderStage::Vertex || request.shader.stage == ShaderStage::Fragment); program.Metadata().bindingLayoutComplete = false; const bool stencilReplay = request.shader.stage == ShaderStage::Fragment && std::ranges::any_of(program.Info().outputs, [](const StageOutput& output) { return output.kind == StageOutputKind::StencilRef; }) && std::ranges::find(request.target.supportedCapabilities, static_cast(spv::CapabilityStencilExportEXT)) == request.target.supportedCapabilities.end(); - auto bindings = bindingAllocator.Allocate(program, request.layout, registration, stencilReplay); + const bool gpuResolved = request.target.gpuResolvedImages; + auto bindings = bindingAllocator.Allocate(program, request.layout, registration, stencilReplay, gpuResolved, request.target.descriptorMemory); + const bool gpuMode = gpuResolved && bindings.layout.gpuResolvedImages; SpirvTargetOptions targetOptions {}; targetOptions.vulkanVersion = request.target.vulkanVersion; @@ -646,6 +662,7 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) } targetOptions.waveLdsMemoryBarriers = request.target.waveLdsMemoryBarriers; targetOptions.deviceScopeLdsMemoryBarriers = request.target.deviceScopeLdsMemoryBarriers; + targetOptions.gpuResolvedImages = gpuMode; constexpr SpirvEmitter spirvEmitter; CompiledShaderArtifact result; @@ -661,7 +678,8 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) if (registration && result.spirv.size() > request.target.registrationWordLimit) { registration = false; program.Metadata().bindingLayoutComplete = false; - bindings = bindingAllocator.Allocate(program, request.layout, false, stencilReplay); + bindings = bindingAllocator.Allocate(program, request.layout, false, stencilReplay, gpuResolved, request.target.descriptorMemory); + targetOptions.gpuResolvedImages = gpuResolved && bindings.layout.gpuResolvedImages; targetOptions.registrationModules = false; result.spirv = spirvEmitter.Emit(program, inputInfo, bindings, targetOptions, &emitted); } @@ -673,6 +691,12 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) result.stencilReferences = StencilReferenceValues(program, request.context.pixel.has_value() && request.context.pixel->stencilOperationValueExport ? 8u : 0u); result.stencilReferenceDword = bindings.layout.stencilReferenceDword; } + result.gpuResolvedImages = targetOptions.gpuResolvedImages; + result.samplerSlotDword = result.gpuResolvedImages ? bindings.layout.SamplerSlotDword() : 0u; + result.bufferAddressDword = bindings.layout.bufferAddressDwords != 0u ? bindings.layout.BufferAddressDword() : 0u; + result.bufferAddressCount = bindings.layout.bufferAddressDwords / 4u; + result.dataAddressPush = bindings.layout.UsesDataAddress(); + result.bdaStores = emitted.bdaStores; result.bdaAbiVersion = program.Info().usesDma || program.Info().usesFaultBuffer ? request.target.bdaAbiVersion : 0u; result.windowLaneGuards = 0; @@ -765,7 +789,7 @@ std::shared_ptr buildSpecializedModule(const CompiledSh const auto count = words[cursor] >> 16u; const auto op = static_cast(words[cursor] & 0xffffu); if (count == 0u || count > words.size() - cursor) throw std::runtime_error("truncated prepared specialization instruction"); - if (!artifact.stencilReferences.empty() && op == spv::OpTypePointer && count == 4u && words[cursor + 2u] == spv::StorageClassPushConstant) pushTypes.insert(words[cursor + 3u]); + if (!artifact.stencilReferences.empty() && !artifact.dataAddressPush && op == spv::OpTypePointer && count == 4u && words[cursor + 2u] == spv::StorageClassPushConstant) pushTypes.insert(words[cursor + 3u]); if (op == spv::OpDecorate && count == 4u && words[cursor + 2u] == spv::DecorationSpecId) { if (PipelineSpecialization::IsWorkgroupOffset(words[cursor + 3u])) { if (supplied.contains(words[cursor + 3u])) throw std::runtime_error("a workgroup offset is supplied at dispatch, not prepared"); @@ -914,33 +938,42 @@ std::shared_ptr registrationModule(std::uint64_t varian return entry->module; } -std::shared_ptr preparedBindingPlan(const CompiledVariant& variant, const ResourceSnapshot& snapshot, std::span exports, bool fragmentDescriptorSet) { - struct BindingPlanKeyStorage {}; - auto& key = HostThreadLocal, BindingPlanKeyStorage>(); - key.clear(); - key.push_back(variant.artifact.variantId); +template +void visitBindingPlanKey(const CompiledVariant& variant, const ResourceSnapshot& snapshot, std::span exports, TVisit&& visit) { + visit(variant.artifact.variantId); for (std::size_t index = 0; index < variant.info.info.buffers.size(); ++index) { const auto& descriptor = snapshot.buffers.at(index); - key.push_back(descriptor.dwordCount); - key.push_back(descriptor.dwords[1] & 0xffff0000u); - key.push_back(descriptor.dwords[3]); + visit(descriptor.dwordCount); + visit(descriptor.dwords[1] & 0xffff0000u); + visit(descriptor.dwords[3]); const bool present = descriptor.dwords[2] != 0u && (descriptor.dwords[0] != 0u || (descriptor.dwords[1] & 0xffffu) != 0u); - key.push_back(present ? 4u | (descriptor.dwords[0] & 3u) : 0u); + visit(present ? 4u | (descriptor.dwords[0] & 3u) : 0u); } for (std::size_t index = 0; index < variant.info.info.images.size(); ++index) { const auto& descriptor = snapshot.images.at(index); - key.push_back(descriptor.dwordCount); - key.push_back(descriptor.dwords[0] != 0u || (descriptor.dwords[1] & 0xffu) != 0u); - key.push_back(descriptor.dwords[1] & ~0xffu); - for (std::size_t word = 2; word < 8; ++word) key.push_back(descriptor.dwords[word]); + visit(descriptor.dwordCount); + visit(descriptor.dwords[0] != 0u || (descriptor.dwords[1] & 0xffu) != 0u); + visit(descriptor.dwords[1] & ~0xffu); + for (std::size_t word = 2; word < 8; ++word) visit(descriptor.dwords[word]); } for (std::size_t index = 0; index < variant.info.info.samplers.size(); ++index) { const auto& descriptor = snapshot.samplers.at(index); - key.push_back(descriptor.dwordCount); - for (std::size_t word = 0; word < 4; ++word) key.push_back(descriptor.dwords[word]); + visit(descriptor.dwordCount); + for (std::size_t word = 0; word < 4; ++word) visit(descriptor.dwords[word]); } - key.push_back(exports.size()); - for (const auto mapping : exports) key.push_back(mapping); + visit(exports.size()); + for (const auto mapping : exports) visit(mapping); +} + +void bindingPlanKey(std::vector& key, const CompiledVariant& variant, const ResourceSnapshot& snapshot, std::span exports) { + key.clear(); + visitBindingPlanKey(variant, snapshot, exports, [&](std::uint64_t word) { key.push_back(word); }); +} + +std::shared_ptr preparedBindingPlan(const CompiledVariant& variant, const ResourceSnapshot& snapshot, std::span exports, bool fragmentDescriptorSet) { + struct BindingPlanKeyStorage {}; + auto& key = HostThreadLocal, BindingPlanKeyStorage>(); + bindingPlanKey(key, variant, snapshot, exports); static PrimedSharedMutex mutex; static std::map, std::shared_ptr> plans; std::shared_ptr plan; @@ -1008,7 +1041,7 @@ const ResourceSnapshot& mergeTargetImage(const CompiledVariant& variant, const R return merged; } -RecompileResult materializeResult(const CompiledVariant& variant, const RecompileRequest& request, const ResourceSnapshot& captured, bool registrationDefaults = false) { +RecompileResult materializeResult(const CompiledVariant& variant, const RecompileRequest& request, const ResourceSnapshot& captured, bool registrationDefaults = false, UsedBindingPlan* usedPlan = nullptr) { ResourceSnapshot merged; const auto& snapshot = mergeTargetImage(variant, request, captured, registrationDefaults, merged); RecompileResult result; @@ -1020,6 +1053,12 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil .runtimeImageCount = artifact.runtimeImageCount, .runtimeImageResources = artifact.runtimeImageResources, .registrationModule = artifact.registrationModule, + .gpuResolvedImages = artifact.gpuResolvedImages, + .samplerSlotDword = artifact.samplerSlotDword, + .bufferAddressDword = artifact.bufferAddressDword, + .bufferAddressCount = artifact.bufferAddressCount, + .dataAddressPush = artifact.dataAddressPush, + .bdaStores = artifact.bdaStores, .bdaAbiVersion = artifact.bdaAbiVersion, .runtimeAbiVersion = artifact.runtimeAbiVersion, .vertexInputs = artifact.vertexInputs, @@ -1053,7 +1092,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil auto& moduleKey = HostThreadLocal, LocalModuleKeyStorage>(); moduleKey.clear(); if (variant.bindings.layout.UsesPushData()) moduleKey.push_back(request.layout.pushConstantOffsetBytes / 4u); - if (!artifact.stencilReferences.empty()) moduleKey.push_back(request.layout.pushConstantOffsetBytes / 4u + artifact.stencilReferenceDword); + if (!artifact.stencilReferences.empty() && !variant.bindings.layout.UsesDataAddress()) moduleKey.push_back(request.layout.pushConstantOffsetBytes / 4u + artifact.stencilReferenceDword); if (request.context.pixel) { for (const auto packing : request.context.pixel->targetExportPacking) moduleKey.push_back(static_cast(packing)); moduleKey.push_back(request.context.pixel->dualSourceBlend ? 1u : 0u); @@ -1102,7 +1141,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil if (artifact.registrationModule) runtimeSelectors.at(input.location / RuntimeAbi::VertexSelectorsPerDword) |= (selectors & 0xfffu) << (input.location % RuntimeAbi::VertexSelectorsPerDword * 16u); } } - if (!plan->bindings.specialization.empty() || variant.bindings.layout.UsesPushData() || !artifact.vertexInputPatches.empty() || request.context.pixel || depthRemap) { + if (!plan->bindings.specialization.empty() || variant.bindings.layout.UsesPushData() || variant.bindings.layout.UsesDataAddress() || !artifact.vertexInputPatches.empty() || request.context.pixel || depthRemap) { { std::shared_lock lock(plan->mutex); if (const auto found = plan->modules.find(moduleKey); found != plan->modules.end()) entry = found->second; @@ -1116,7 +1155,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil auto constants = plan->bindings.specialization; std::size_t index = 0; if (variant.bindings.layout.UsesPushData()) constants.push_back({PipelineSpecialization::PushDataOffset, moduleKey[index++]}); - if (!artifact.stencilReferences.empty()) constants.push_back({PipelineSpecialization::StencilReferenceOffset, moduleKey[index++]}); + if (!artifact.stencilReferences.empty() && !variant.bindings.layout.UsesDataAddress()) constants.push_back({PipelineSpecialization::StencilReferenceOffset, moduleKey[index++]}); if (request.context.pixel) { for (std::uint32_t target = 0; target < request.context.pixel->targetExportPacking.size(); ++target) constants.push_back({PipelineSpecialization::ExportPackingBase + target, moduleKey[index++]}); constants.push_back({PipelineSpecialization::DualSourceBlend, moduleKey[index++]}); @@ -1138,7 +1177,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil } } const auto module = artifact.registrationModule && plan->bindings.specialization.empty() ? registrationModule(artifact.variantId, moduleKey, [&] { return specializeModule(variant.artifact, vertexClasses, constants, request.target); }) : specializeModule(variant.artifact, vertexClasses, constants, request.target); - if (variant.bindings.layout.UsesPushData() && !module->pushData) throw std::runtime_error("specialization removed the prepared push constant interface"); + if ((variant.bindings.layout.UsesPushData() || variant.bindings.layout.UsesDataAddress()) && !module->pushData) throw std::runtime_error("specialization removed the prepared push constant interface"); auto selected = DescriptorBindingBuilder{}.Select(plan->bindings, module->bindings); entry->bindings = std::move(selected); entry->module = module; @@ -1160,6 +1199,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil } const auto resolved = ResourceMaterializer::ResolveImageTablesShared(variant.info.info, snapshot, artifact.variantId); const auto& tables = *resolved; + if (usedPlan != nullptr) *usedPlan = {entry != nullptr ? std::shared_ptr(entry) : std::shared_ptr(plan), bindingPlan}; BindingAllocationResult bindings; DescriptorBindingBuilder{}.Populate(bindings, variant.bindings, *bindingPlan, variant.info.userDataBase, snapshot, partialThreads(request), &tables); result.workgroupMemoryDwords = WorkgroupMemoryStrideDwords(variant.info.info); @@ -1170,7 +1210,8 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil if (request.shader.stage == ShaderStage::Compute) { for (std::uint32_t component = 0; component < PipelineSpecialization::WorkgroupOffsetWords; ++component) result.specialization.push_back({PipelineSpecialization::WorkgroupOffsetBase + component, 0u}); } - if (!artifact.stencilReferences.empty()) { + result.heapSlotWords = bindingPlan->heapSlotWords; + if (!artifact.stencilReferences.empty() && !variant.bindings.layout.UsesDataAddress()) { if (artifact.stencilReferenceDword * sizeof(std::uint32_t) != result.pushConstants.size() || result.pushConstants.size() + sizeof(std::uint32_t) > request.layout.pushConstantSizeBytes) throw std::runtime_error("stencil replay push constant lies outside the stage range"); result.pushConstants.resize(result.pushConstants.size() + sizeof(std::uint32_t)); } @@ -1362,6 +1403,8 @@ ResultMemoEntry* memoSet(SourceEntry& source, std::uint64_t index) { return source.memo->data() + static_cast((index ^ (index >> 32u)) % ResultMemoSets) * ResultMemoWays; } + + struct ResultMemoCounters { std::atomic hits{0}, misses{0}, evictions{0}, populateNanoseconds{0}; std::atomic lastReport{0}; @@ -1393,7 +1436,7 @@ void reportResultMemo() { // Everything materializeResult reads besides the variant: the snapshot (the descriptor words, the // flattened SRT, the user data, the uniform fill) and, for the vertex family, the V# table the // attributes are resolved from. -std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapshot& snapshot) { +std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapshot& snapshot, bool perDrawData = true, bool descriptors = true) { std::uint64_t hash = 0xcbf29ce484222325ull; const auto mix = [&](std::uint64_t value) { hash ^= value; @@ -1411,11 +1454,15 @@ std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapsh for (std::uint32_t i = 0; i < value.dwordCount && i < value.dwords.size(); ++i) mix(value.dwords[i]); } }; - mixDescriptors(snapshot.buffers); - mixDescriptors(snapshot.images); - mixDescriptors(snapshot.samplers); - mixWords(snapshot.flattenedSrt); - mixWords(snapshot.userData); + if (descriptors) { + mixDescriptors(snapshot.buffers); + mixDescriptors(snapshot.images); + mixDescriptors(snapshot.samplers); + } + if (perDrawData) { + mixWords(snapshot.flattenedSrt); + mixWords(snapshot.userData); + } mix(static_cast(snapshot.uniformFill.kind)); mix(snapshot.uniformFill.resource); for (const auto stride : snapshot.uniformFill.groupStride) mix(stride); @@ -1460,7 +1507,11 @@ std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapsh const auto count = std::min(vertex.resourcesNum, ShaderVertexStageInfo::MaxResources); mix(count); for (std::uint32_t i = 0; i < count; ++i) { - for (const auto field : vertex.resources[i].fields) mix(field); + if (perDrawData) { + for (const auto field : vertex.resources[i].fields) mix(field); + } else { + mix(vertex.resources[i].fields[3]); + } mix(vertex.resourcesDst[i].fetchIndex); } } else { @@ -1654,9 +1705,10 @@ bool MatchesPreparedShader(const RecompileRequest& request, const SourceHandle& if (layout.descriptorSet != handle.artifact->layout.descriptorSet || layout.firstBinding != handle.artifact->layout.firstBinding) return false; if (layout.pushConstantOffsetBytes % 4u != 0u || layout.pushConstantSizeBytes % 4u != 0u || layout.pushConstantOffsetBytes > NativePushConstantSize || layout.pushConstantSizeBytes > NativePushConstantSize - layout.pushConstantOffsetBytes) return false; const auto words = prepared.ShaderDataDwords(); - const bool usesPush = prepared.runtimeImageCount == 0u && words != 0u && words <= layout.pushConstantSizeBytes / 4u; + const bool usesPush = !prepared.gpuResolvedImages && prepared.runtimeImageCount == 0u && words != 0u && words <= layout.pushConstantSizeBytes / 4u; if (prepared.UsesPushData() != usesPush) return false; - if (!handle.artifact->artifact.stencilReferences.empty() && (prepared.stencilReferenceDword >= layout.pushConstantSizeBytes / 4u || prepared.stencilReferenceDword != (usesPush ? words : 0u))) return false; + if (!handle.artifact->artifact.stencilReferences.empty() && prepared.UsesDataAddress() && prepared.stencilReferenceDword != RuntimeAbi::RootDword + RuntimeAbi::RootStencilReference) return false; + if (!handle.artifact->artifact.stencilReferences.empty() && !prepared.UsesDataAddress() && (prepared.stencilReferenceDword >= layout.pushConstantSizeBytes / 4u || prepared.stencilReferenceDword != (usesPush ? words : 0u))) return false; if (!std::ranges::equal(key, handle.staticKey) || handle.source->code.size() != request.shader.code.size()) return false; return handle.source->code.data() == request.shader.code.data() || std::ranges::equal(handle.source->code, request.shader.code); } @@ -1666,7 +1718,7 @@ std::span GetPreparedCode(const SourceHandle& handle) { return handle.source->code; } -PreparedShaderInvocation::PreparedShaderInvocation(const RecompileRequest& request, const std::shared_ptr& handle) : request(request), handle(handle) { +PreparedShaderInvocation::PreparedShaderInvocation(RecompileRequest request, const std::shared_ptr& handle) : request(std::move(request)), handle(handle) { this->request.context.linkedCallFallbacks = handle->source->linkedCallFallbacks; } @@ -1683,6 +1735,12 @@ std::optional PreparedShaderInvocation::TryCreate(cons return PreparedShaderInvocation(request, handle); } +std::optional PreparedShaderInvocation::TryCreate(RecompileRequest&& request, const std::shared_ptr& handle, std::span key) { + if (handle == nullptr || !MatchesPreparedShader(request, *handle, key)) return std::nullopt; + if (request.shader.stage != ShaderStage::Compute && request.shader.stage != ShaderStage::Fragment) static_cast(RequestInputInfo(request)); + return PreparedShaderInvocation(std::move(request), handle); +} + std::shared_ptr PreparedShaderInvocation::Capture(const SrtRuntime& runtime) const { auto capture = std::make_shared(); capture->source = handle->source; @@ -1691,6 +1749,112 @@ std::shared_ptr PreparedShaderInvocation::Capture(const S return capture; } +std::shared_ptr PreparedShaderInvocation::MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words) const { + if (capture.source != handle->source || capture.plan != handle->source->plan) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); + const auto& variant = handle->artifact; + if (!variant->artifact.gpuResolvedImages || !variant->artifact.registrationModule || variant->bindings.layout.UsesPushData()) return nullptr; + const auto& snapshot = capture.snapshot; + const auto& layout = variant->bindings.layout; + const auto userDataBase = request.context.userDataBaseRegister; + words.userData.resize(layout.userDataRegisters.size()); + for (std::size_t i = 0; i < layout.userDataRegisters.size(); ++i) { + const auto reg = layout.userDataRegisters[i]; + if (reg < userDataBase || reg - userDataBase >= snapshot.userData.size()) throw std::runtime_error("ShaderRecompiler: shader user-data register is out of range"); + words.userData[i] = snapshot.userData[reg - userDataBase]; + } + words.flattenedSrt.assign(snapshot.flattenedSrt.begin(), snapshot.flattenedSrt.end()); + words.bindings.clear(); + const bool tables = std::ranges::any_of(layout.descriptors, [](const IrDescriptorBinding& descriptor) { return descriptor.kind == DescriptorBindingKind::ImageTable || descriptor.kind == DescriptorBindingKind::SamplerTable || descriptor.kind == DescriptorBindingKind::ImageTableMap; }); + const bool perDrawBindings = (request.shader.stage == ShaderStage::Fragment || request.shader.stage == ShaderStage::Vertex) && !tables; + auto& source = *handle->source; + std::uint64_t key = snapshotHash(request, snapshot, false, !perDrawBindings) ^ variant->artifact.variantId * 0x9e3779b97f4a7c15ull; + if (perDrawBindings) { + visitBindingPlanKey(*variant, snapshot, request.context.pixel ? std::span(request.context.pixel->targetExportMapping) : std::span{}, [&](std::uint64_t word) { key = (key ^ word) * 0x100000001b3ull; }); + } + const auto useAttributes = [&](const std::shared_ptr& result) { + words.vertexAttributes.clear(); + if (!request.context.vertex) return; + const auto& vertex = *request.context.vertex; + words.vertexAttributes = result->vertexAttributes; + for (auto& attribute : words.vertexAttributes) { + if (attribute.location >= vertex.resourcesNum || attribute.location >= vertex.resources.size()) throw std::runtime_error("ShaderRecompiler: vertex attribute outside the draw's vertex resources"); + attribute.resource = vertex.resources[attribute.location]; + if (vertex.fetchEmbedded) attribute.fetchIndex = vertex.resourcesDst[attribute.location].fetchIndex; + } + }; + const auto useBindings = [&](const HeapTemplate& shared) { + if (!perDrawBindings) return; + if (shared.plan.plan == nullptr) throw std::runtime_error("ShaderRecompiler: a heap template has no binding plan"); + const bool sameBuffers = snapshot.buffers == shared.buffers; + const bool sameImages = snapshot.images == shared.images && snapshot.samplers == shared.samplers; + if (sameBuffers && sameImages) return; + const auto count = shared.result->bindings.size(); + if (shared.plan.plan->bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap template's binding plan differs from its bindings"); + if (sameImages) { + words.bindings.assign(count, {}); + for (std::size_t index = 0; index < count; ++index) { + const auto& entry = shared.plan.plan->bindings[index]; + if (entry.descriptor.role != DescriptorRole::GuestBuffers) continue; + auto& descriptor = words.bindings[index]; + descriptor.reserve(entry.resources.size() * 4u); + for (const auto resource : entry.resources) { + if (resource >= snapshot.buffers.size() || snapshot.buffers[resource].dwordCount != 4u) throw std::runtime_error("ShaderRecompiler: a heap stage's guest buffer descriptor is out of range"); + descriptor.insert(descriptor.end(), snapshot.buffers[resource].dwords.begin(), snapshot.buffers[resource].dwords.begin() + 4); + } + if (descriptor == shared.result->bindings[index].guestDescriptor) descriptor.clear(); + } + if (std::all_of(words.bindings.begin(), words.bindings.end(), [](const std::vector& descriptor) { return descriptor.empty(); })) words.bindings.clear(); + return; + } + const auto tables = ResourceMaterializer::ResolveImageTables(variant->info.info, snapshot, variant->artifact.variantId); + BindingAllocationResult bindings; + DescriptorBindingBuilder{}.Populate(bindings, variant->bindings, *shared.plan.plan, variant->info.userDataBase, snapshot, partialThreads(request), &tables); + if (bindings.bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw bindings differ from its template"); + words.bindings.reserve(count); + for (auto& binding : bindings.bindings) words.bindings.push_back(std::move(binding.guestDescriptor)); + if (variant->artifact.registrationModule && request.shader.stage != ShaderStage::Fragment && layout.runtimeStateDwords != 0u) { + const auto first = layout.RuntimeStateDword() + RuntimeAbi::StateVertexSelectors; + for (std::size_t index = 0; index < words.bindings.size(); ++index) { + if (shared.result->bindings[index].role != DescriptorRole::ShaderData) continue; + const auto& kept = shared.result->bindings[index].guestDescriptor; + if (first + layout.runtimeStateDwords > kept.size() || first + layout.runtimeStateDwords > words.bindings[index].size()) throw std::runtime_error("ShaderRecompiler: vertex selector state lies outside a heap stage's shader data"); + std::copy_n(kept.begin() + first, layout.runtimeStateDwords, words.bindings[index].begin() + first); + } + } + for (std::size_t index = 0; index < count; ++index) { + if (words.bindings[index] == shared.result->bindings[index].guestDescriptor) words.bindings[index].clear(); + } + if (std::all_of(words.bindings.begin(), words.bindings.end(), [](const std::vector& descriptor) { return descriptor.empty(); })) words.bindings.clear(); + }; + { + std::lock_guard lock(source.mutex); + const auto found = source.heapTemplates.find(key); + if (found != source.heapTemplates.end()) { + const auto shared = found->second; + useAttributes(shared.result); + useBindings(shared); + CompleteHeapDataWords(*shared.result, words); + return shared.result; + } + } + UsedBindingPlan usedPlan; + auto built = std::make_shared(materializeResult(*variant, request, snapshot, false, &usedPlan)); + built->cacheHit = true; + for (const auto reg : layout.userDataRegisters) built->heapUserWords.push_back(reg - userDataBase); + static std::atomic templateIds{0}; + built->heapTemplateId = templateIds.fetch_add(1, std::memory_order_relaxed) + 1u; + HeapTemplate shared{std::move(built), std::move(usedPlan), perDrawBindings ? snapshot.buffers : std::vector{}, perDrawBindings ? snapshot.images : std::vector{}, perDrawBindings ? snapshot.samplers : std::vector{}}; + { + std::lock_guard lock(source.mutex); + if (source.heapTemplates.size() >= 4096) source.heapTemplates.clear(); + shared = source.heapTemplates.emplace(key, shared).first->second; + } + useAttributes(shared.result); + useBindings(shared); + CompleteHeapDataWords(*shared.result, words); + return shared.result; +} + std::shared_ptr PreparedShaderInvocation::Materialize(const ResourceCapture& capture) const { if (capture.source != handle->source) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); if (request.useCache && ResultMemo()) return materializePreparedMemoized(*handle->source, handle->artifact, request, capture.snapshot, true, nullptr); @@ -1699,6 +1863,45 @@ std::shared_ptr PreparedShaderInvocation::Materialize(con return result; } +const std::shared_ptr& PreparedShaderInvocation::Plan() const { + static const std::shared_ptr none; + return handle != nullptr && handle->source != nullptr ? handle->source->plan : none; +} + +std::uint64_t PreparedShaderInvocation::VariantId() const { + return handle != nullptr && handle->artifact != nullptr ? handle->artifact->artifact.variantId : 0u; +} + +void CompleteHeapDataWords(const RecompileResult& shared, HeapStageWords& words) { + const auto count = shared.bindings.size(); + if (!words.bindings.empty() && words.bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw bindings differ in number from its template"); + for (std::size_t index = 0; index < count; ++index) { + const auto& binding = shared.bindings[index]; + if (binding.role != DescriptorRole::ShaderData && binding.role != DescriptorRole::FlattenedSrt) continue; + if (!words.bindings.empty() && !words.bindings[index].empty()) continue; + std::vector descriptor; + if (binding.role == DescriptorRole::FlattenedSrt) { + if (words.flattenedSrt.empty() || words.flattenedSrt == binding.guestDescriptor) continue; + descriptor = words.flattenedSrt; + } else { + const auto patched = std::min(words.userData.size(), binding.guestDescriptor.size()); + if (std::equal(words.userData.begin(), words.userData.begin() + static_cast(patched), binding.guestDescriptor.begin())) continue; + descriptor = binding.guestDescriptor; + std::copy_n(words.userData.begin(), patched, descriptor.begin()); + } + if (words.bindings.empty()) words.bindings.assign(count, {}); + words.bindings[index] = std::move(descriptor); + } +} + +bool HeapFragmentEligible(const IrResourcePlan& plan) { + if (plan.stage == IrShaderStage::Unknown || plan.stage == IrShaderStage::Fetch) return false; + for (const auto& image : plan.info.images) { + if (image.source >= plan.descriptorSources.size()) return false; + } + return true; +} + const CompiledShaderArtifact& GetPreparedArtifact(const SourceHandle& handle) { if (handle.artifact == nullptr) throw std::runtime_error("ShaderRecompiler: prepared artifact is missing"); return handle.artifact->artifact; diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 9462ba07215c..7af032c4d980 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -327,6 +327,8 @@ struct SpirvTarget { bool largePixelFunctionLdsBuffer = false; std::uint32_t pixelFunctionStorageDwords = 4096u; bool deviceScopeLdsMemoryBarriers = false; + bool gpuResolvedImages = false; + bool descriptorMemory = false; }; struct BindingLayout { @@ -395,6 +397,7 @@ inline constexpr std::uint32_t MeshRestartLengthDword = MeshArgumentBytes / 4; inline constexpr std::uint32_t MeshRestartTableDword = MeshRestartLengthDword + 1; inline constexpr std::uint32_t MeshIndexBufferUserWord = 4; inline constexpr std::uint32_t WorkgroupMemoryDescriptorSet = 1; +inline constexpr std::uint32_t GpuWorkgroupMemoryDescriptorSet = 3; struct GraphicsDrawParameters { std::uint64_t indexAddress; @@ -438,6 +441,15 @@ struct GraphicsCompileContext { std::optional meshBarycentrics; }; +struct VertexAttribute; + +struct HeapStageWords { + std::vector userData; + std::vector flattenedSrt; + std::vector vertexAttributes; + std::vector> bindings; +}; + struct RecompileRequest { ShaderBinary shader; GuestContext context; @@ -691,6 +703,12 @@ struct CompiledShaderArtifact { std::uint32_t runtimeImageCount = 0; std::vector runtimeImageResources; bool registrationModule = false; + bool gpuResolvedImages = false; + std::uint32_t samplerSlotDword = 0; + std::uint32_t bufferAddressDword = 0; + std::uint32_t bufferAddressCount = 0; + bool dataAddressPush = false; + bool bdaStores = false; std::uint32_t bdaAbiVersion = 0; std::uint32_t windowLaneGuards = 0; std::uint32_t runtimeAbiVersion = RuntimeAbi::Version; @@ -717,6 +735,7 @@ struct CompiledShaderArtifact { struct ShaderInvocation { std::vector specialization; + std::vector heapSlotWords; std::uint64_t specializationId = 0; std::vector bindings; std::vector pushConstants; @@ -756,6 +775,8 @@ struct ResultKeyMemo { }; struct RecompileResult : CompiledShaderArtifact, ShaderInvocation { + std::uint64_t heapTemplateId = 0; + std::vector heapUserWords; ResultKeyMemo drawKeyMemo; bool cacheHit = false; std::uint32_t workgroupMemoryDwords = 0; diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index 52d25ba4396a..f82d801cb3e2 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -18,6 +18,7 @@ inline constexpr std::uint32_t FirstImageBinding = 1u; inline constexpr std::uint32_t FirstComparisonImageBinding = 22u; inline constexpr std::uint32_t FirstStorageImageBinding = 29u; inline constexpr std::uint32_t ImageBindingCount = 56u; +inline constexpr bool GpuHeapStorageKind(std::uint32_t kind) { return kind >= FirstStorageImageBinding && kind < FirstImageBinding + ImageBindingCount; } enum class Binding : std::uint32_t { Buffers = 0u, @@ -44,6 +45,31 @@ inline constexpr std::uint32_t BindlessTableSlots = 16u; inline constexpr std::uint32_t StorageMipSlots = 16u; inline constexpr std::uint32_t StorageHeapCapacity = 64u; inline constexpr std::uint32_t SamplerHeapCapacity = 64u; +inline constexpr std::uint32_t GpuImageHeapSlots = 4096u; +inline constexpr std::uint32_t GpuSamplerHeapSlots = 256u; +inline constexpr std::uint32_t GpuDataSet = 2u; +inline constexpr std::uint32_t GpuGdsSet = 4u; +inline constexpr std::uint32_t GdsBytes = 0x10000u; +inline constexpr std::uint32_t PushDataDwords = 64u; +inline constexpr std::uint32_t RootDword = 38u; +inline constexpr std::uint32_t RootRingAddress = 0u; +inline constexpr std::uint32_t RootPagetableAddress = 2u; +inline constexpr std::uint32_t RootFaultAddress = 4u; +inline constexpr std::uint32_t RootGdsAddress = 6u; +inline constexpr std::uint32_t RootPagetableDwords = 8u; +inline constexpr std::uint32_t RootStencilReference = 9u; +inline constexpr std::uint32_t RootStageRecords = 10u; +enum class RootStageField : std::uint32_t { ShaderData, FlattenedSrt, SrtDwords, TableMap, Count }; +inline constexpr std::uint32_t RootStageDword(Stage stage, RootStageField field) { return RootStageRecords + static_cast(stage) * static_cast(RootStageField::Count) + static_cast(field); } +inline constexpr std::uint32_t RootDwords = RootStageRecords + StageCount * static_cast(RootStageField::Count); +static_assert(RootDword * 4u % 8u == 0u && RootDword + RootDwords == PushDataDwords); +struct HeapSlotWord { + std::uint32_t dword = 0; + std::uint32_t kind = 0; + std::uint32_t element = 0; + + bool operator==(const HeapSlotWord& other) const = default; +}; inline constexpr std::uint32_t StateExportMappings = 0u; inline constexpr std::uint32_t StateDwords = 2u; inline constexpr std::uint32_t StateVertexSelectors = 0u; diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index aca1cb4eeacd..683c0d8b7afe 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -85,14 +85,14 @@ std::filesystem::path ShaderCacheDirectory() { namespace ShaderRecompiler::ShaderDiskCache { #if defined(__linux__) && defined(__x86_64__) && defined(__GLIBCXX__) -static_assert(sizeof(CompiledShaderArtifact) == 280, "CompiledShaderArtifact changed: update the artifact encoder"); -static_assert(sizeof(ShaderInvocation) == 216, "ShaderInvocation changed: update the invocation encoder"); -static_assert(sizeof(RecompileResult) == 544, "RecompileResult changed: update EncodeResult and DecodeResult"); +static_assert(sizeof(CompiledShaderArtifact) == 296, "CompiledShaderArtifact changed: update the artifact encoder"); +static_assert(sizeof(ShaderInvocation) == 240, "ShaderInvocation changed: update the invocation encoder"); +static_assert(sizeof(RecompileResult) == 616, "RecompileResult changed: update EncodeResult and DecodeResult"); static_assert(sizeof(DescriptorBinding) == 656, "DescriptorBinding changed: update the binding encoder"); static_assert(sizeof(VertexAttribute) == 32, "VertexAttribute changed: update the attribute encoder"); static_assert(sizeof(VertexInput) == 16, "VertexInput changed: update the vertex input encoder"); static_assert(sizeof(FragmentParameter) == 16, "FragmentParameter changed: update the parameter encoder"); -static_assert(sizeof(CompiledShaderInfo) == 352, "CompiledShaderInfo changed: update the info encoder"); +static_assert(sizeof(CompiledShaderInfo) == 368, "CompiledShaderInfo changed: update the info encoder"); static_assert(sizeof(ShaderInfo) == 232, "ShaderInfo changed: update the info encoder"); static_assert(sizeof(BufferResource) == 32, "BufferResource changed: update the info encoder"); static_assert(sizeof(ImageResource) == 96, "ImageResource changed: update the info encoder"); @@ -100,10 +100,10 @@ static_assert(sizeof(SamplerResource) == 24, "SamplerResource changed: update th static_assert(sizeof(SampledResourcePair) == 12, "SampledResourcePair changed: update the info encoder"); static_assert(sizeof(StageInput) == 56, "StageInput changed: update the info encoder"); static_assert(sizeof(StageOutput) == 48, "StageOutput changed: update the info encoder"); -static_assert(sizeof(IrBindingLayout) == 80, "IrBindingLayout changed: update the layout encoder"); +static_assert(sizeof(IrBindingLayout) == 96, "IrBindingLayout changed: update the layout encoder"); static_assert(sizeof(IrDescriptorBinding) == 32, "IrDescriptorBinding changed: update the layout encoder"); -static_assert(sizeof(BindingAllocationResult) == 184, "BindingAllocationResult changed: update the allocation encoder"); -static_assert(sizeof(CompiledBindingLayout) == 88, "CompiledBindingLayout changed: update the allocation encoder"); +static_assert(sizeof(BindingAllocationResult) == 200, "BindingAllocationResult changed: update the allocation encoder"); +static_assert(sizeof(CompiledBindingLayout) == 104, "CompiledBindingLayout changed: update the allocation encoder"); static_assert(sizeof(BindingLayout) == 16, "BindingLayout changed: update BuildKey"); static_assert(sizeof(IrResourcePlan) == 728, "IrResourcePlan changed: update EncodePlan and DecodePlan"); static_assert(sizeof(IrValue) == 128, "IrValue changed: update the plan value encoder"); @@ -520,6 +520,12 @@ void encodeArtifact(Writer& writer, const CompiledShaderArtifact& result) { writer.Value(result.runtimeImageCount); writer.Values(std::span(result.runtimeImageResources)); writer.Value(result.registrationModule); + writer.Value(result.gpuResolvedImages); + writer.Value(result.samplerSlotDword); + writer.Value(result.bufferAddressDword); + writer.Value(result.bufferAddressCount); + writer.Value(result.dataAddressPush); + writer.Value(result.bdaStores); writer.List(result.vertexInputPatches, [](Writer& out, const VertexInputPatch& patch) { out.Value(patch.location); out.Value(patch.word); @@ -583,6 +589,12 @@ void decodeArtifact(Reader& reader, CompiledShaderArtifact& result) { reader.Value(result.runtimeImageCount); reader.Values(result.runtimeImageResources); reader.Value(result.registrationModule); + reader.Value(result.gpuResolvedImages); + reader.Value(result.samplerSlotDword); + reader.Value(result.bufferAddressDword); + reader.Value(result.bufferAddressCount); + reader.Value(result.dataAddressPush); + reader.Value(result.bdaStores); reader.List(result.vertexInputPatches, 20, [](Reader& in, VertexInputPatch& patch) { in.Value(patch.location); in.Value(patch.word); @@ -646,6 +658,11 @@ void encodeInvocation(Writer& writer, const ShaderInvocation& invocation) { out.Value(constant.value); }); writer.List(invocation.bindings, encodeBinding); + writer.List(invocation.heapSlotWords, [](Writer& out, const RuntimeAbi::HeapSlotWord& word) { + out.Value(word.dword); + out.Value(word.kind); + out.Value(word.element); + }); writer.Value(invocation.pushConstants.size()); for (const auto byte : invocation.pushConstants) writer.Value(static_cast(byte)); writer.Value(invocation.readsDepthRemapPush); @@ -676,6 +693,7 @@ void encodeInvocation(Writer& writer, const ShaderInvocation& invocation) { }); writer.Value(invocation.imageTableShader); writer.Value(invocation.imageTableFaults); + writer.Value(invocation.userDataRegisterReads); } void decodeInvocation(Reader& reader, ShaderInvocation& invocation) { @@ -685,6 +703,11 @@ void decodeInvocation(Reader& reader, ShaderInvocation& invocation) { in.Value(constant.value); }); reader.List(invocation.bindings, 8, decodeBinding); + reader.List(invocation.heapSlotWords, 12, [](Reader& in, RuntimeAbi::HeapSlotWord& word) { + in.Value(word.dword); + in.Value(word.kind); + in.Value(word.element); + }); std::vector pushConstants; reader.Values(pushConstants); invocation.pushConstants.resize(pushConstants.size()); @@ -717,16 +740,23 @@ void decodeInvocation(Reader& reader, ShaderInvocation& invocation) { }); reader.Value(invocation.imageTableShader); reader.Value(invocation.imageTableFaults); + reader.Value(invocation.userDataRegisterReads); } void encodeLayout(Writer& writer, const IrBindingLayout& layout) { writer.Value(layout.pushDataStartDword); + writer.Value(layout.dataAddressDword); writer.Value(layout.stencilReferenceDword); writer.Value(layout.memoryOffsetDword); writer.Value(layout.memoryOffsetCount); writer.Value(layout.dispatchThreadLimit); writer.Value(layout.runtimeImageCount); writer.Value(layout.runtimeStateDwords); + writer.Value(layout.samplerSlotDwords); + writer.Value(layout.imageSlotDwords); + writer.Value(layout.bufferAddressDwords); + writer.Value(layout.heapStorageImages); + writer.Value(layout.gpuResolvedImages); writer.Values(std::span(layout.userDataRegisters)); writer.List(layout.descriptors, [](Writer& out, const IrDescriptorBinding& descriptor) { out.Value(descriptor.kind); @@ -736,12 +766,18 @@ void encodeLayout(Writer& writer, const IrBindingLayout& layout) { void decodeLayout(Reader& reader, IrBindingLayout& layout) { reader.Value(layout.pushDataStartDword); + reader.Value(layout.dataAddressDword); reader.Value(layout.stencilReferenceDword); reader.Value(layout.memoryOffsetDword); reader.Value(layout.memoryOffsetCount); reader.Value(layout.dispatchThreadLimit); reader.Value(layout.runtimeImageCount); reader.Value(layout.runtimeStateDwords); + reader.Value(layout.samplerSlotDwords); + reader.Value(layout.imageSlotDwords); + reader.Value(layout.bufferAddressDwords); + reader.Value(layout.heapStorageImages); + reader.Value(layout.gpuResolvedImages); reader.Values(layout.userDataRegisters); reader.List(layout.descriptors, 12, [](Reader& in, IrDescriptorBinding& descriptor) { in.Value(descriptor.kind); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp index 146fb2318a18..4653570b3ff0 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp @@ -42,11 +42,13 @@ struct SpirvTargetOptions { bool largePixelFunctionLdsBuffer = false; std::uint32_t pixelFunctionStorageDwords = 4096u; bool deviceScopeLdsMemoryBarriers = false; + bool gpuResolvedImages = false; }; struct SpirvEmitInfo { bool fullSubgroups = false; bool functionLdsBuffer = false; + bool bdaStores = false; }; struct SpannedWaveUnsupported : std::runtime_error { diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp index 4be0132c1db6..ae4251bf2b10 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp @@ -40,6 +40,7 @@ std::uint32_t TypeStorageBufferU8Block(SpirvEmitterState& state); std::uint32_t TypeStorageBufferU8Pointer(SpirvEmitterState& state); std::uint32_t TypeStorageBufferU8ElementPointer(SpirvEmitterState& state); std::uint32_t TypePhysicalU32Pointer(SpirvEmitterState& state); +std::uint32_t TypePhysicalBufferPointer(SpirvEmitterState& state, bool wide); std::uint32_t TypePushConstantElementPointer(SpirvEmitterState& state); std::uint32_t TypeU32ArrayPointer(SpirvEmitterState& state, std::uint32_t storageClass, std::uint32_t dwords); std::uint32_t TypeU32ElementPointer(SpirvEmitterState& state, std::uint32_t storageClass); @@ -111,6 +112,7 @@ std::uint32_t EmitSubgroupLaneActiveBool(SpirvEmitterState& state, std::uint32_t std::uint32_t EmitBinaryU32(SpirvEmitterState& state, std::uint32_t opcode, std::uint32_t lhs, std::uint32_t rhs); std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dwordIndex); void EmitMemoryOffsets(SpirvEmitterState& state); +void EmitHeapSlotPreload(SpirvEmitterState& state); std::uint32_t LdsDwordCount(const SpirvEmitterState& state); bool LdsInDeviceMemory(const SpirvEmitterState& state); std::uint32_t LdsMemorySemantics(const SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index 5c75b23f821a..f75d93697035 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -71,6 +71,7 @@ struct MemoryResourceAccess { bool addIndexOffset = false; std::uint32_t memoryAccess = 0; std::uint32_t misalignment = 0; + bool physical = false; }; struct SpirvTableImageVariable { @@ -84,6 +85,7 @@ struct SpirvTableAccess { std::uint32_t samplerElement = 0; bool active = false; bool uniform = false; + bool heap = false; }; struct SpirvEmitterState { @@ -108,6 +110,8 @@ struct SpirvEmitterState { bool depthRangeRemap = false; std::uint32_t depthRemapClipIndex = 0; bool registrationModules = false; + bool gpuResolvedImages = false; + bool addressedBuffers = false; bool fragmentDescriptorSet = false; bool float16DenormPreserve = false; bool robustBufferAccess2 = false; @@ -204,7 +208,12 @@ struct SpirvEmitterState { std::uint32_t gdsLength = 0; std::uint32_t pushConstantVariable = 0; std::uint32_t shaderDataStorageVariable = 0; + std::unordered_map heapSlotVariables; std::uint32_t flattenedSrtVariable = 0; + bool flattenedSrtAddressed = false; + bool bdaAddressed = false; + bool tableMapAddressed = false; + bool tableHeap = false; std::uint32_t ldsVariable = 0; std::uint32_t ldsBufferVariable = 0; std::uint32_t ldsBufferU64Variable = 0; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp index 18e703456fee..41d3ef400a1e 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp @@ -9,7 +9,16 @@ namespace ShaderRecompiler { std::uint32_t EmitBinaryU32(SpirvEmitterState& state, std::uint32_t opcode, std::uint32_t lhs, std::uint32_t rhs); std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dwordIndex); +std::uint32_t EmitShaderDataWordLoad(SpirvEmitterState& state, std::uint32_t index); +std::uint32_t EmitRootDword(SpirvEmitterState& state, std::uint32_t field); +std::uint32_t EmitStageRootDword(SpirvEmitterState& state, RuntimeAbi::RootStageField field); +std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, std::uint32_t field, std::uint32_t index); +std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::RootStageField field, std::uint32_t index); +std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index); +bool HasFlattenedSrt(const SpirvEmitterState& state); void EmitMemoryOffsets(SpirvEmitterState& state); +void EmitHeapSlotPreload(SpirvEmitterState& state); +std::uint32_t LoadHeapSlotWord(SpirvEmitterState& state, std::uint32_t dword); std::uint32_t LdsDwordCount(const SpirvEmitterState& state); bool LdsInDeviceMemory(const SpirvEmitterState& state); std::uint32_t LdsMemorySemantics(const SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp index 53f65c7c1c57..60feb78eac5c 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp @@ -1,6 +1,7 @@ #include "SpirvBackend/SpirvBda.hpp" #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include #include #include @@ -12,6 +13,8 @@ std::uint32_t BdaConstant(SpirvEmitterState& state, std::uint64_t value) { } std::uint32_t BdaWord(SpirvEmitterState& state, std::uint32_t variable, std::uint32_t index) { + if (state.bdaAddressed && variable == state.bdaPagetableVariable) return EmitRootAddressWordPointer(state, RuntimeAbi::RootPagetableAddress, index); + if (state.bdaAddressed && variable == state.faultBufferVariable) return EmitRootAddressWordPointer(state, RuntimeAbi::RootFaultAddress, index); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, variable, ConstantU32(state, 0u), index); return pointer; @@ -19,7 +22,8 @@ std::uint32_t BdaWord(SpirvEmitterState& state, std::uint32_t variable, std::uin std::uint32_t BdaLoadWord(SpirvEmitterState& state, std::uint32_t index) { const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, BdaWord(state, state.bdaPagetableVariable, index)); + if (state.bdaAddressed) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, BdaWord(state, state.bdaPagetableVariable, index), spv::MemoryAccessAlignedMask, 4u); + else state.module.AddFunction(spv::OpLoad, TypeU32(state), value, BdaWord(state, state.bdaPagetableVariable, index)); return value; } @@ -60,7 +64,8 @@ void DefineBdaFaultFunction(SpirvEmitterState& state) { const auto won = Binary(state, spv::OpIEqual, TypeBool(state), previous, ConstantU32(state, 0u)); EmitIfCondition(state, won, [&] { const auto store = [&](std::uint32_t index, std::uint32_t value) { - state.module.AddFunction(spv::OpStore, BdaWord(state, state.faultBufferVariable, ConstantU32(state, index)), value); + if (state.bdaAddressed) state.module.AddFunction(spv::OpStore, BdaWord(state, state.faultBufferVariable, ConstantU32(state, index)), value, spv::MemoryAccessAlignedMask, 4u); + else state.module.AddFunction(spv::OpStore, BdaWord(state, state.faultBufferVariable, ConstantU32(state, index)), value); }; store(1, reason); store(2, words ? address : Unary(state, spv::OpUConvert, TypeU32(state), address)); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp index d1889a85fe02..7f94dadba526 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp @@ -1,6 +1,8 @@ #include "SpirvBackend/SpirvBda.hpp" #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" +#include #include #include #include @@ -64,8 +66,8 @@ std::uint32_t DefineBdaLookup(SpirvEmitterState& state, const char* name, bool r } leaveIf(binary(spv::OpINotEqual, boolean, reason, constant(0u)), reason); }; - const auto length = state.module.AllocateId(); - state.module.AddFunction(spv::OpArrayLength, u32, length, state.bdaPagetableVariable, 0u); + auto length = state.bdaAddressed ? EmitRootDword(state, RuntimeAbi::RootPagetableDwords) : state.module.AllocateId(); + if (!state.bdaAddressed) state.module.AddFunction(spv::OpArrayLength, u32, length, state.bdaPagetableVariable, 0u); fail(binary(spv::OpULessThan, boolean, length, constant(4)), BdaAbi::FaultReason::InvalidTable); const auto count = BdaLoadWord(state, constant(1)); const auto available = binary(spv::OpISub, u32, length, constant(4)); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp index 96ddd6f796f6..aaf04281418c 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp @@ -266,6 +266,7 @@ std::vector SpirvEmitter::Emit(const IrProgram& program, const Sh state.float64DenormPreserve = target.float64DenormPreserve; state.depthRangeRemap = target.depthRangeRemap; state.registrationModules = target.registrationModules; + state.gpuResolvedImages = target.gpuResolvedImages; state.fragmentDescriptorSet = target.fragmentDescriptorSet; state.meshBarycentricPixel = target.meshBarycentricPixel; state.meshBarycentricVertex = target.meshBarycentricVertex; @@ -328,6 +329,7 @@ std::vector SpirvEmitter::Emit(const IrProgram& program, const Sh if (info != nullptr) { info->fullSubgroups = state.spannedWave; info->functionLdsBuffer = state.pixelFunctionLdsBuffer; + info->bdaStores = state.bdaWritePointerFunction != 0; } return state.module.Finalize(); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp index 60c9ac87794a..b851678b3563 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp @@ -101,7 +101,8 @@ void EmitReturnTerminator(SpirvValueEmitContext& ctx) { state.module.AddFunction(spv::OpLoad, TypeI32(state), value, state.stencilRefVariable); const auto reference = Unary(state, spv::OpBitcast, TypeU32(state), value); const auto masked = Binary(state, spv::OpBitwiseAnd, TypeU32(state), reference, ConstantU32(state, 0xffu)); - const auto offset = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::StencilReferenceOffset, state.program.Metadata().bindings.stencilReferenceDword); + const auto& layout = state.program.Metadata().bindings; + const auto offset = layout.UsesDataAddress() ? ConstantU32(state, layout.stencilReferenceDword) : state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::StencilReferenceOffset, layout.stencilReferenceDword); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0u), offset); const auto expected = state.module.AllocateId(); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp index 601bed36a232..a356d40dd4d4 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp @@ -8,6 +8,7 @@ #include "RdnaDecoder/RdnaDescriptorFormat.hpp" #include "RdnaDecoder/RdnaImageOpDecoder.hpp" #include "ImageTableAbi.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include #include #include @@ -1743,6 +1744,11 @@ ScalarBufferDword EmitScalarBufferDword(SpirvEmitterState& state, std::uint32_t } std::uint32_t LoadTableMap(SpirvEmitterState& state, std::uint32_t index) { + if (state.tableMapAddressed) { + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, EmitStageRingWordPointer(state, RuntimeAbi::RootStageField::TableMap, index), spv::MemoryAccessAlignedMask, 4u); + return value; + } const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.tableMapVariable, ConstantU32(state, 0u), index); const auto value = state.module.AllocateId(); @@ -1885,7 +1891,8 @@ TableAccessResult EmitTableAccess(SpirvValueEmitContext& ctx, const IrValue& ins result.valid = both(checked, negate(driverRejected)); result.flags = flags; live = selected; - state.tableAccess.element = Binary(state, spv::OpIAdd, u32, LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)), element); + state.tableAccess.element = state.tableHeap ? Select(state, u32, checked, element, ConstantU32(state, 0u)) : Binary(state, spv::OpIAdd, u32, LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)), element); + state.tableAccess.heap = state.tableHeap; const auto& sources = state.program.Resources().descriptorSources; state.tableAccess.uniform = base.source < sources.size() && sources[base.source].tableColumn.has_value() && sources[base.source].tableColumn->selected; if (!state.tableAccess.uniform) DecorateTableNonUniform(state, state.tableAccess.element); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index e2f95214eecd..217410f73498 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -3,6 +3,7 @@ #include "SpirvBackend/SpirvEmitterHelpers.hpp" #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvDescriptors.hpp" +#include "SpirvBackend/SpirvBda.hpp" #include #include #include @@ -32,8 +33,99 @@ std::uint32_t EmitBinaryU32(SpirvEmitterState& state, std::uint32_t opcode, std: return result; } +RuntimeAbi::Stage RootStage(const SpirvEmitterState& state) { + switch (state.program.Resources().stage) { + case IrShaderStage::Pixel: return RuntimeAbi::Stage::Fragment; + case IrShaderStage::TessellationControl: return RuntimeAbi::Stage::TessellationControl; + case IrShaderStage::TessellationEvaluation: return RuntimeAbi::Stage::TessellationEvaluation; + default: return RuntimeAbi::Stage::Main; + } +} + +std::uint32_t EmitRootDword(SpirvEmitterState& state, std::uint32_t field) { + if (!state.program.Metadata().bindings.UsesDataAddress()) FailEmit("the root is read only by stages that take their data through it"); + const auto u32 = TypeU32(state); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), ConstantU32(state, RuntimeAbi::RootDword + field)); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, u32, value, pointer); + return value; +} + +std::uint32_t EmitStageRootDword(SpirvEmitterState& state, RuntimeAbi::RootStageField field) { + return EmitRootDword(state, RuntimeAbi::RootStageDword(RootStage(state), field)); +} + +namespace { + +std::uint32_t rootAddress(SpirvEmitterState& state, std::uint32_t field) { + const auto u64 = TypeScalarU64(state); + const auto low = Unary(state, spv::OpUConvert, u64, EmitRootDword(state, field)); + const auto high = Binary(state, spv::OpShiftLeftLogical, u64, Unary(state, spv::OpUConvert, u64, EmitRootDword(state, field + 1u)), BdaConstant(state, 32u)); + return Binary(state, spv::OpBitwiseOr, u64, low, high); +} + +std::uint32_t wordPointer(SpirvEmitterState& state, std::uint32_t base, std::uint32_t index) { + const auto u64 = TypeScalarU64(state); + const auto offset = Binary(state, spv::OpShiftLeftLogical, u64, Unary(state, spv::OpUConvert, u64, index), BdaConstant(state, 2u)); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, Binary(state, spv::OpIAdd, u64, base, offset)); + return pointer; +} + +} + +std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, std::uint32_t field, std::uint32_t index) { + return wordPointer(state, rootAddress(state, field), index); +} + +std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::RootStageField field, std::uint32_t index) { + const auto u64 = TypeScalarU64(state); + const auto base = Binary(state, spv::OpIAdd, u64, rootAddress(state, RuntimeAbi::RootRingAddress), Unary(state, spv::OpUConvert, u64, EmitStageRootDword(state, field))); + return wordPointer(state, base, index); +} + +namespace { + +std::uint32_t dataAddressLoad(SpirvEmitterState& state, RuntimeAbi::RootStageField field, std::uint32_t index) { + const auto pointer = EmitStageRingWordPointer(state, field, index); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, spv::MemoryAccessAlignedMask, 4u); + return value; +} + +} + +bool HasFlattenedSrt(const SpirvEmitterState& state) { + return state.flattenedSrtVariable != 0 || state.flattenedSrtAddressed; +} + +std::uint32_t EmitShaderDataWordLoad(SpirvEmitterState& state, std::uint32_t index) { + if (state.program.Metadata().bindings.UsesDataAddress()) return dataAddressLoad(state, RuntimeAbi::RootStageField::ShaderData, index); + if (state.shaderDataStorageVariable == 0) FailEmit("shader data is neither in push constants nor in a storage buffer"); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.shaderDataStorageVariable, ConstantU32(state, 0u), index); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); + return value; +} + +std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index) { + if (state.flattenedSrtAddressed) { + const auto inBounds = Binary(state, spv::OpULessThan, TypeBool(state), index, EmitStageRootDword(state, RuntimeAbi::RootStageField::SrtDwords)); + return EmitValueOrZeroIfCondition(state, inBounds, [&] { return dataAddressLoad(state, RuntimeAbi::RootStageField::FlattenedSrt, index); }); + } + if (state.flattenedSrtVariable == 0) FailEmit("the flattened SRT descriptor is missing"); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.flattenedSrtVariable, ConstantU32(state, 0u), index); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); + return value; +} + std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dwordIndex) { const IrBindingLayout& layout = state.program.Metadata().bindings; + if (layout.UsesDataAddress()) return dataAddressLoad(state, RuntimeAbi::RootStageField::ShaderData, ConstantU32(state, dwordIndex)); const auto pointer = state.module.AllocateId(); const auto value = state.module.AllocateId(); if (layout.UsesPushData()) { @@ -59,6 +151,31 @@ void EmitMemoryOffsets(SpirvEmitterState& state) { } } +void EmitHeapSlotPreload(SpirvEmitterState& state) { + if (!state.gpuResolvedImages || (state.shaderDataStorageVariable == 0 && !state.program.Metadata().bindings.UsesDataAddress())) return; + const IrBindingLayout& layout = state.program.Metadata().bindings; + std::vector dwords; + for (auto dword = layout.SamplerSlotDword(); dword < layout.ShaderDataDwords(); ++dword) dwords.push_back(dword); + constexpr auto metadataWords = static_cast(sizeof(RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t)); + constexpr auto firstElement = static_cast(offsetof(RuntimeAbi::ResourceMetadata, firstElement) / sizeof(std::uint32_t)); + for (std::uint32_t image = 0; image < layout.runtimeImageCount; ++image) dwords.push_back(layout.ImageMetadataDword() + image * metadataWords + firstElement); + const auto pointerType = TypePointer(state, spv::StorageClassPrivate, TypeU32(state)); + for (const auto dword : dwords) { + if (dword >= layout.ShaderDataDwords() || state.heapSlotVariables.contains(dword)) continue; + const auto variable = state.module.DefineGlobalVariable(pointerType, spv::StorageClassPrivate); + state.module.AddFunction(spv::OpStore, variable, EmitShaderDataDwordLoad(state, dword)); + state.heapSlotVariables.emplace(dword, variable); + } +} + +std::uint32_t LoadHeapSlotWord(SpirvEmitterState& state, std::uint32_t dword) { + const auto found = state.heapSlotVariables.find(dword); + if (found == state.heapSlotVariables.end()) return EmitShaderDataDwordLoad(state, dword); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, found->second); + return value; +} + std::uint32_t LdsDwordCount(const SpirvEmitterState& state) { const auto* workgroup = ShaderWorkgroupInput(state); if (workgroup != nullptr) return workgroup->ldsSizeDwords; @@ -243,7 +360,7 @@ std::uint32_t LdsStorageDwords(const SpirvEmitterState& state) { bool LoadsSelectable(const SpirvEmitterState& state, const MemoryResourceAccess& access) { if (access.kind == ResourceKind::Scratch) return true; - if (access.kind == ResourceKind::Lds) return false; + if (access.kind == ResourceKind::Lds || access.physical) return false; return state.robustBufferAccess2; } @@ -270,6 +387,10 @@ std::uint32_t EmitMemoryElementPointer(SpirvEmitterState& state, const MemoryRes } std::uint32_t EmitStorageBufferElementPointer(SpirvEmitterState& state, const MemoryResourceAccess& access, std::uint32_t index, std::uint32_t pointerType) { + if (access.physical) { + if (pointerType == TypeStorageBufferU64ElementPointer(state)) pointerType = TypePointer(state, spv::StorageClassPhysicalStorageBuffer, TypeScalarU64(state)); + else pointerType = TypePhysicalU32Pointer(state); + } const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, access.objectPointer, ConstantU32(state, 0), index); return pointer; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp index 7a5fe34450c5..586f71e7662f 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp @@ -2,9 +2,12 @@ #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" #include "SpirvBackend/SpirvEmitterHelpers.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include "PipelineSpecialization.hpp" +#include "ImageTableAbi.hpp" #include #include +#include #include #include @@ -57,11 +60,7 @@ std::uint32_t DescriptorElementPointer(SpirvEmitterState& state, std::uint32_t r std::uint32_t RuntimeImageDword(SpirvEmitterState& state, std::uint32_t resource, std::uint32_t member) { const auto index = ConstantU32(state, resource); const auto dword = Binary(state, spv::OpIAdd, TypeU32(state), ConstantU32(state, state.program.Metadata().bindings.ImageMetadataDword() + member), Binary(state, spv::OpIMul, TypeU32(state), index, ConstantU32(state, sizeof(RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t)))); - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.shaderDataStorageVariable, ConstantU32(state, 0u), dword); - const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); - return value; + return EmitShaderDataWordLoad(state, dword); } std::uint32_t RuntimeMipCount(SpirvEmitterState& state, std::uint32_t resource) { @@ -79,11 +78,32 @@ void DecorateTableNonUniform(SpirvEmitterState& state, std::uint32_t id) { state.module.AddAnnotation(spv::OpDecorate, id, spv::DecorationNonUniform); } +namespace { + +std::uint32_t tableMapWord(SpirvEmitterState& state, std::uint32_t index) { + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, EmitStageRingWordPointer(state, RuntimeAbi::RootStageField::TableMap, index), spv::MemoryAccessAlignedMask, 4u); + return value; +} + +std::uint32_t tableHeapSlot(SpirvEmitterState& state, std::uint32_t part, std::uint32_t element, std::uint32_t slots) { + const auto u32 = TypeU32(state); + const auto base = tableMapWord(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)); + const auto count = tableMapWord(state, ConstantU32(state, ImageTableAbi::HeaderElementCount)); + const auto partBase = part == 0u ? base : Binary(state, spv::OpIAdd, u32, base, Binary(state, spv::OpIMul, u32, count, ConstantU32(state, part))); + const auto slot = tableMapWord(state, Binary(state, spv::OpIAdd, u32, partBase, element)); + const auto clamped = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), slot, ConstantU32(state, slots)), slot, ConstantU32(state, 0u)); + DecorateTableNonUniform(state, clamped); + return clamped; +} + +} + std::uint32_t TableStorageImagePointer(SpirvEmitterState& state, DescriptorBindingKind kind, std::uint32_t resource, std::uint32_t pointerType) { const auto found = std::find_if(state.tableImageVariables.begin(), state.tableImageVariables.end(), [&](const SpirvTableImageVariable& variable) { return variable.kind == kind; }); if (found == state.tableImageVariables.end() || !state.tableAccess.active) ExitDescriptorBindingFailure(state, kind, resource, "image storage table array was not emitted for the mode"); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.element); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, 1u, state.tableAccess.element, RuntimeAbi::GpuImageHeapSlots) : state.tableAccess.element); DecorateTableNonUniform(state, pointer); return pointer; } @@ -153,6 +173,40 @@ std::uint32_t ImageViewSizeType(SpirvEmitterState& state, RdnaImageDimension dim } } +std::uint32_t HeapImageSlot(SpirvEmitterState& state, DescriptorBindingKind kind, std::uint32_t resource) { + const auto supported = std::find(state.supportedCapabilities.begin(), state.supportedCapabilities.end(), spv::CapabilitySampledImageArrayDynamicIndexing) != state.supportedCapabilities.end(); + if (!supported) ExitDescriptorBindingFailure(state, kind, resource, "the image heap needs image array dynamic indexing, which the device lacks"); + state.module.EmitCapability(spv::CapabilitySampledImageArrayDynamicIndexing); + const auto dword = state.program.Metadata().bindings.ImageMetadataDword() + resource * static_cast(sizeof(RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t)) + static_cast(offsetof(RuntimeAbi::ResourceMetadata, firstElement) / sizeof(std::uint32_t)); + return LoadHeapSlotWord(state, dword); +} + +std::uint32_t HeapImageSlotWord(SpirvEmitterState& state, DescriptorBindingKind kind, std::uint32_t resource, std::uint32_t arrayIndex) { + const auto supported = std::find(state.supportedCapabilities.begin(), state.supportedCapabilities.end(), spv::CapabilitySampledImageArrayDynamicIndexing) != state.supportedCapabilities.end(); + if (!supported) ExitDescriptorBindingFailure(state, kind, resource, "the image heap needs image array dynamic indexing, which the device lacks"); + state.module.EmitCapability(spv::CapabilitySampledImageArrayDynamicIndexing); + const auto& layout = state.program.Metadata().bindings; + auto dword = layout.ImageSlotDword(); + for (const auto& descriptor : layout.descriptors) { + if (descriptor.kind == kind) break; + if (state.program.Metadata().bindings.HeapImageKind(descriptor.kind)) dword += static_cast(descriptor.resources.size()); + } + dword += arrayIndex; + if (dword >= layout.ShaderDataDwords()) ExitDescriptorBindingFailure(state, kind, resource, "image heap slot word lies outside the shader data"); + return LoadHeapSlotWord(state, dword); +} + +std::uint32_t StorageElementPointer(SpirvEmitterState& state, std::uint32_t pointerType, std::uint32_t variable, std::uint32_t arrayIndex, DescriptorBindingKind kind, std::uint32_t resource) { + if (!state.gpuResolvedImages || !state.program.Metadata().bindings.HeapImageKind(kind)) return DescriptorElementPointer(state, pointerType, variable, arrayIndex, kind, resource, "storage image descriptor array was not emitted"); + if (variable == 0) ExitDescriptorBindingFailure(state, kind, resource, "storage image heap array was not emitted"); + const auto supported = std::find(state.supportedCapabilities.begin(), state.supportedCapabilities.end(), spv::CapabilityStorageImageArrayDynamicIndexing) != state.supportedCapabilities.end(); + if (!supported) ExitDescriptorBindingFailure(state, kind, resource, "the storage image heap needs storage image array dynamic indexing, which the device lacks"); + state.module.EmitCapability(spv::CapabilityStorageImageArrayDynamicIndexing); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, variable, state.registrationModules ? HeapImageSlot(state, kind, resource) : HeapImageSlotWord(state, kind, resource, arrayIndex)); + return pointer; +} + std::uint32_t LoadSampledImageDescriptor(SpirvEmitterState& state, std::uint32_t resource) { const auto& imageResource = state.runtimeImage != nullptr ? *state.runtimeImage : state.program.Info().images.at(resource); if (imageResource.resourceClass != ImageResourceClass::Sampled) { @@ -165,7 +219,7 @@ std::uint32_t LoadSampledImageDescriptor(SpirvEmitterState& state, std::uint32_t const auto found = std::find_if(state.tableImageVariables.begin(), state.tableImageVariables.end(), [&](const SpirvTableImageVariable& variable) { return variable.kind == kind; }); if (found == state.tableImageVariables.end() || !state.tableAccess.active) ExitDescriptorBindingFailure(state, kind, resource, "image table array was not emitted for the mode"); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.element); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, 0u, state.tableAccess.element, RuntimeAbi::GpuImageHeapSlots) : state.tableAccess.element); if (!state.tableAccess.uniform) DecorateTableNonUniform(state, pointer); const auto image = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, imageType, image, pointer); @@ -177,7 +231,13 @@ std::uint32_t LoadSampledImageDescriptor(SpirvEmitterState& state, std::uint32_t if (variable == 0) { ExitDescriptorBindingFailure(state, kind, resource, "sampled image descriptor array was not emitted"); } - const auto pointer = DescriptorElementPointer(state, pointerType, variable, arrayIndex, kind, resource, "sampled image descriptor array was not emitted"); + std::uint32_t pointer = 0; + if (state.gpuResolvedImages) { + pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, variable, state.registrationModules ? HeapImageSlot(state, kind, resource) : HeapImageSlotWord(state, kind, resource, arrayIndex)); + } else { + pointer = DescriptorElementPointer(state, pointerType, variable, arrayIndex, kind, resource, "sampled image descriptor array was not emitted"); + } const auto image = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, imageType, image, pointer); return image; @@ -195,7 +255,7 @@ std::uint32_t LoadSamplerDescriptor(SpirvEmitterState& state, std::uint32_t samp const auto variant = image != nullptr && image->depthCompare ? 2u : 0u; const auto element = Binary(state, spv::OpIAdd, TypeU32(state), state.tableAccess.samplerElement, ConstantU32(state, variant + (point ? 1u : 0u))); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.tableSamplerVariable, element); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.tableSamplerVariable, state.tableHeap ? tableHeapSlot(state, 2u, element, RuntimeAbi::GpuSamplerHeapSlots) : element); DecorateTableNonUniform(state, pointer); const auto loaded = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, samplerType, loaded, pointer); @@ -203,7 +263,16 @@ std::uint32_t LoadSamplerDescriptor(SpirvEmitterState& state, std::uint32_t samp return loaded; } const auto arrayIndex = ResourceForDescriptor(state, DescriptorBindingKind::Samplers, sampler) + (point ? 1u : 0u); - const auto pointer = DescriptorElementPointer(state, pointerType, state.samplerVariable, arrayIndex, DescriptorBindingKind::Samplers, sampler, "sampler descriptor array was not emitted"); + std::uint32_t pointer = 0; + if (state.gpuResolvedImages) { + if (state.samplerVariable == 0) ExitDescriptorBindingFailure(state, DescriptorBindingKind::Samplers, sampler, "sampler descriptor array was not emitted"); + state.module.EmitCapability(spv::CapabilitySampledImageArrayDynamicIndexing); + const auto slot = LoadHeapSlotWord(state, state.program.Metadata().bindings.SamplerSlotDword() + arrayIndex); + pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.samplerVariable, slot); + } else { + pointer = DescriptorElementPointer(state, pointerType, state.samplerVariable, arrayIndex, DescriptorBindingKind::Samplers, sampler, "sampler descriptor array was not emitted"); + } const auto samplerId = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, samplerType, samplerId, pointer); return samplerId; @@ -230,7 +299,7 @@ std::uint32_t StorageImageDescriptorPointer(SpirvEmitterState& state, std::uint3 if (image.table != NoTable) return TableStorageImagePointer(state, kind, resource, pointerType); const auto arrayIndex = ResourceForDescriptor(state, kind, resource); const auto variable = state.imageVariables.at(ImageBindingIndex(kind)); - return DescriptorElementPointer(state, pointerType, variable, arrayIndex, kind, resource, "storage image descriptor array was not emitted"); + return StorageElementPointer(state, pointerType, variable, arrayIndex, kind, resource); } std::uint32_t EmitStorageImageRead(SpirvEmitterState& state, std::uint32_t resource, std::uint32_t coord, std::uint32_t sample) { @@ -276,7 +345,7 @@ void EmitStorageImageWrite(SpirvEmitterState& state, std::uint32_t resource, std const auto arrayIndex = ResourceForDescriptor(state, kind, resource); const auto variable = state.imageVariables.at(ImageBindingIndex(kind)); const auto loadAt = [&](std::uint32_t index) { - const auto pointer = DescriptorElementPointer(state, pointerType, variable, index, kind, resource, "storage image descriptor array was not emitted"); + const auto pointer = StorageElementPointer(state, pointerType, variable, index, kind, resource); const auto descriptor = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, imageType, descriptor, pointer); return descriptor; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index f71d15cbca60..2d353c698826 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -136,7 +136,7 @@ std::uint32_t StorageBufferU64BlockType(SpirvEmitterState& state) { } std::uint32_t PushConstantArrayType(SpirvEmitterState& state) { - const auto count = ConstantU32(state, PushData::DwordCount); + const auto count = ConstantU32(state, state.program.Metadata().bindings.UsesDataAddress() ? RuntimeAbi::PushDataDwords : PushData::DwordCount); return state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, static_cast(sizeof(std::uint32_t))}}}, TypeU32(state), count); @@ -163,7 +163,7 @@ void CheckBindings(const IrProgram& program, const CompiledBindingLayout& bindin void EmitBaseHeader(SpirvModule& module, const IrProgram& program) { module.EmitCapability(spv::CapabilityShader); - const bool physical = program.Info().usesDma || program.Resources().stage == IrShaderStage::Mesh; + const bool physical = program.Info().usesDma || program.Resources().stage == IrShaderStage::Mesh || program.Metadata().bindings.bufferAddressDwords != 0u || program.Metadata().bindings.UsesDataAddress(); if (physical) { module.EmitCapability(spv::CapabilityInt64); module.EmitCapability(spv::CapabilityPhysicalStorageBufferAddresses); @@ -460,7 +460,7 @@ void DefineOutputs(SpirvEmitterState& state) { void DefineDescriptors(SpirvEmitterState& state) { const IrBindingLayout& layout = state.program.Metadata().bindings; const IrShaderStage stage = state.program.Resources().stage; - if (layout.UsesPushData() || state.stencilReplay || stage == IrShaderStage::Mesh || stage == IrShaderStage::TessellationControl || (state.depthRangeRemap && stage == IrShaderStage::Vertex)) { + if (layout.UsesPushData() || layout.UsesDataAddress() || state.stencilReplay || stage == IrShaderStage::Mesh || stage == IrShaderStage::TessellationControl || (state.depthRangeRemap && stage == IrShaderStage::Vertex)) { const auto type = PushConstantBlockType(state); state.pushConstantVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassPushConstant, type), spv::StorageClassPushConstant); state.module.AddName(type, "BufferResource"); @@ -470,18 +470,27 @@ void DefineDescriptors(SpirvEmitterState& state) { const auto Define = [&](std::uint32_t type, const char* name, std::uint32_t storage = spv::StorageClassStorageBuffer) { const auto variable = state.module.DefineGlobalVariable(TypePointer(state, storage, type), storage); state.module.AddName(variable, name); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, state.fragmentDescriptorSet && stage == IrShaderStage::Pixel ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, NativeBinding(stage, binding.kind)); + const bool gpuData = state.gpuResolvedImages && (binding.kind == DescriptorBindingKind::ShaderData || binding.kind == DescriptorBindingKind::FlattenedSrt); + const bool gpuHeap = binding.kind == DescriptorBindingKind::Samplers || layout.HeapImageKind(binding.kind); + const bool sharedHeap = state.gpuResolvedImages && gpuHeap; + const bool fragmentSet = sharedHeap || (!state.gpuResolvedImages && state.fragmentDescriptorSet && stage == IrShaderStage::Pixel); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, binding.kind == DescriptorBindingKind::Gds && layout.UsesDataAddress() ? RuntimeAbi::GpuGdsSet : gpuData ? RuntimeAbi::GpuDataSet : fragmentSet ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, NativeBinding(sharedHeap ? IrShaderStage::Pixel : stage, binding.kind)); return variable; }; const auto ArrayType = [&](std::uint32_t type) { const bool heap = binding.kind == DescriptorBindingKind::Samplers || ImageBindingResourceClass(binding.kind) != ImageResourceClass::None; - const auto count = static_cast(binding.resources.size()); - const auto length = heap && !state.registrationModules ? state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::HeapCountBase + static_cast(binding.kind), count) : ConstantU32(state, count); + const bool gpuHeap = state.gpuResolvedImages && (binding.kind == DescriptorBindingKind::Samplers || layout.HeapImageKind(binding.kind)); + const auto count = gpuHeap ? (binding.kind == DescriptorBindingKind::Samplers ? RuntimeAbi::GpuSamplerHeapSlots : RuntimeAbi::GpuImageHeapSlots) : static_cast(binding.resources.size()); + const auto length = heap && !gpuHeap && !state.registrationModules ? state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::HeapCountBase + static_cast(binding.kind), count) : ConstantU32(state, count); return state.module.Type(spv::OpTypeArray, type, length); }; switch (binding.kind) { case DescriptorBindingKind::Buffers: + if (layout.bufferAddressDwords != 0u) { + state.addressedBuffers = true; + break; + } state.storageBufferVariable = Define(ArrayType(StorageBufferBlockType(state)), "buffers"); if (state.requirements.coherentBufferAlias) state.storageBufferCoherentVariable = Define(ArrayType(StorageBufferBlockType(state)), "buffers_coherent"); if (state.requirements.bufferU64View) state.storageBufferU64Variable = Define(ArrayType(StorageBufferU64BlockType(state)), "buffers_u64"); @@ -496,18 +505,31 @@ void DefineDescriptors(SpirvEmitterState& state) { } break; case DescriptorBindingKind::BdaPagetable: - state.bdaPagetableVariable = Define(StorageBufferBlockType(state), "bda_pagetable"); - state.module.AddAnnotation(spv::OpDecorate, state.bdaPagetableVariable, spv::DecorationNonWritable); + if (layout.UsesDataAddress()) { + state.bdaPagetableVariable = state.module.AllocateId(); + state.bdaAddressed = true; + } else { + state.bdaPagetableVariable = Define(StorageBufferBlockType(state), "bda_pagetable"); + state.module.AddAnnotation(spv::OpDecorate, state.bdaPagetableVariable, spv::DecorationNonWritable); + } break; case DescriptorBindingKind::FaultBuffer: - state.faultBufferVariable = Define(StorageBufferBlockType(state), "fault_buffer"); + if (layout.UsesDataAddress()) { + state.faultBufferVariable = state.module.AllocateId(); + state.bdaAddressed = true; + } else { + state.faultBufferVariable = Define(StorageBufferBlockType(state), "fault_buffer"); + } break; case DescriptorBindingKind::ShaderData: - state.shaderDataStorageVariable = Define(StorageBufferBlockType(state), "shader_data"); + if (!layout.UsesDataAddress()) state.shaderDataStorageVariable = Define(StorageBufferBlockType(state), "shader_data"); break; case DescriptorBindingKind::FlattenedSrt: - state.flattenedSrtVariable = Define(StorageBufferBlockType(state), "flattened_srt"); - state.module.AddAnnotation(spv::OpDecorate, state.flattenedSrtVariable, spv::DecorationNonWritable); + if (layout.UsesDataAddress()) state.flattenedSrtAddressed = true; + else { + state.flattenedSrtVariable = Define(StorageBufferBlockType(state), "flattened_srt"); + state.module.AddAnnotation(spv::OpDecorate, state.flattenedSrtVariable, spv::DecorationNonWritable); + } break; case DescriptorBindingKind::Samplers: state.samplerVariable = Define(ArrayType(state.module.Type(spv::OpTypeSampler)), "samplers", spv::StorageClassUniformConstant); @@ -520,6 +542,7 @@ void DefineDescriptors(SpirvEmitterState& state) { case DescriptorBindingKind::ImageStorageTable: RequireTableIndexing(state); if (binding.kind == DescriptorBindingKind::ImageStorageTable) state.module.EmitCapability(spv::CapabilityStorageImageArrayDynamicIndexing); + state.tableHeap = state.gpuResolvedImages && layout.UsesDataAddress(); for (std::uint32_t resource = 0; resource < state.program.Info().images.size(); ++resource) { const auto& image = state.program.Info().images[resource]; if (image.table == NoTable) continue; @@ -529,18 +552,42 @@ void DefineDescriptors(SpirvEmitterState& state) { if ((ImageBindingResourceClass(kind) == ImageResourceClass::Storage) != (binding.kind == DescriptorBindingKind::ImageStorageTable)) continue; if (std::any_of(state.tableImageVariables.begin(), state.tableImageVariables.end(), [&](const SpirvTableImageVariable& variable) { return variable.kind == kind; })) continue; const auto name = "table_images_" + std::to_string(static_cast(kind)); - state.tableImageVariables.push_back({kind, Define(state.module.Type(spv::OpTypeRuntimeArray, ImageType(state, mode)), name.c_str(), spv::StorageClassUniformConstant)}); + if (state.tableHeap) { + const auto heapKind = binding.kind == DescriptorBindingKind::ImageStorageTable ? RuntimeAbi::FirstStorageImageBinding : RuntimeAbi::FirstImageBinding; + const auto type = state.module.Type(spv::OpTypeArray, ImageType(state, mode), ConstantU32(state, RuntimeAbi::GpuImageHeapSlots)); + const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniformConstant, type), spv::StorageClassUniformConstant); + state.module.AddName(variable, name.c_str()); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, RuntimeAbi::FragmentDescriptorSet); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, NativeBinding(IrShaderStage::Pixel, static_cast(heapKind))); + state.tableImageVariables.push_back({kind, variable}); + } else { + state.tableImageVariables.push_back({kind, Define(state.module.Type(spv::OpTypeRuntimeArray, ImageType(state, mode)), name.c_str(), spv::StorageClassUniformConstant)}); + } if (mode.dimension == RdnaImageDimension::Dim1D || mode.dimension == RdnaImageDimension::Dim1DArray) state.module.EmitCapability(binding.kind == DescriptorBindingKind::ImageStorageTable ? spv::CapabilityImage1D : spv::CapabilitySampled1D); } } break; case DescriptorBindingKind::SamplerTable: RequireTableIndexing(state); - state.tableSamplerVariable = Define(state.module.Type(spv::OpTypeRuntimeArray, state.module.Type(spv::OpTypeSampler)), "table_samplers", spv::StorageClassUniformConstant); + if (state.gpuResolvedImages && layout.UsesDataAddress()) { + const auto type = state.module.Type(spv::OpTypeArray, state.module.Type(spv::OpTypeSampler), ConstantU32(state, RuntimeAbi::GpuSamplerHeapSlots)); + state.tableSamplerVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniformConstant, type), spv::StorageClassUniformConstant); + state.module.AddName(state.tableSamplerVariable, "table_samplers"); + state.module.AddAnnotation(spv::OpDecorate, state.tableSamplerVariable, spv::DecorationDescriptorSet, RuntimeAbi::FragmentDescriptorSet); + state.module.AddAnnotation(spv::OpDecorate, state.tableSamplerVariable, spv::DecorationBinding, NativeBinding(IrShaderStage::Pixel, DescriptorBindingKind::Samplers)); + state.tableHeap = true; + } else { + state.tableSamplerVariable = Define(state.module.Type(spv::OpTypeRuntimeArray, state.module.Type(spv::OpTypeSampler)), "table_samplers", spv::StorageClassUniformConstant); + } break; case DescriptorBindingKind::ImageTableMap: - state.tableMapVariable = Define(StorageBufferBlockType(state), "table_map"); - state.module.AddAnnotation(spv::OpDecorate, state.tableMapVariable, spv::DecorationNonWritable); + if (layout.UsesDataAddress()) { + state.tableMapVariable = state.module.AllocateId(); + state.tableMapAddressed = true; + } else { + state.tableMapVariable = Define(StorageBufferBlockType(state), "table_map"); + state.module.AddAnnotation(spv::OpDecorate, state.tableMapVariable, spv::DecorationNonWritable); + } break; default: { if (ImageBindingResourceClass(binding.kind) == ImageResourceClass::None) { @@ -563,13 +610,13 @@ void DefineDescriptors(SpirvEmitterState& state) { if (LdsInDeviceMemory(state)) { state.ldsBufferVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassStorageBuffer, StorageBufferBlockType(state)), spv::StorageClassStorageBuffer); state.module.AddName(state.ldsBufferVariable, "workgroup_memory"); - state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferVariable, spv::DecorationDescriptorSet, WorkgroupMemoryDescriptorSet); + state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferVariable, spv::DecorationDescriptorSet, state.gpuResolvedImages ? GpuWorkgroupMemoryDescriptorSet : WorkgroupMemoryDescriptorSet); state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferVariable, spv::DecorationBinding, 0u); state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferVariable, spv::DecorationCoherent); if (state.requirements.ldsBufferInt64Atomics) { state.ldsBufferU64Variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassStorageBuffer, StorageBufferU64BlockType(state)), spv::StorageClassStorageBuffer); state.module.AddName(state.ldsBufferU64Variable, "workgroup_memory_u64"); - state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferU64Variable, spv::DecorationDescriptorSet, WorkgroupMemoryDescriptorSet); + state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferU64Variable, spv::DecorationDescriptorSet, state.gpuResolvedImages ? GpuWorkgroupMemoryDescriptorSet : WorkgroupMemoryDescriptorSet); state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferU64Variable, spv::DecorationBinding, 0u); state.module.AddAnnotation(spv::OpDecorate, state.ldsBufferU64Variable, spv::DecorationCoherent); for (const auto variable : {state.ldsBufferVariable, state.ldsBufferU64Variable}) state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationAliased); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp index 78314c2247c2..83459d26148b 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp @@ -3,6 +3,7 @@ #include "SpirvBackend/SpirvEmitterInstructions.hpp" #include "SpirvBackend/SpirvMemory/SpirvSubgroup.hpp" #include "SpirvBackend/SpirvBufferFormat.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include "RdnaDecoder/RdnaInstructionDecoder.hpp" #include #include @@ -1533,7 +1534,7 @@ std::uint32_t AtomicFloatCompareSwap(SpirvEmitterState& state, std::uint32_t old std::uint32_t EmitReadConst(SpirvValueEmitContext& ctx, const IrValue& inst) { auto& state = ctx.state; - if (state.flattenedSrtVariable == 0) { + if (!HasFlattenedSrt(state)) { ctx.Fail(inst, "requires the flattened SRT descriptor"); } const auto& resources = state.program.Resources(); @@ -1549,13 +1550,7 @@ std::uint32_t EmitReadConst(SpirvValueEmitContext& ctx, const IrValue& inst) { ctx.Fail(inst, "reads a guarded SRT slot without a fault buffer"); } const auto u32 = TypeU32(state); - const auto load = [&](std::uint32_t index) { - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.flattenedSrtVariable, ConstantU32(state, 0u), index); - const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, u32, value, pointer); - return value; - }; + const auto load = [&](std::uint32_t index) { return EmitFlattenedSrtLoad(state, index); }; const auto guard = static_cast(found - guarded.begin()); const auto flag = load(ConstantU32(state, resources.srtGuardOffset + guard)); const auto poisoned = Binary(state, spv::OpINotEqual, TypeBool(state), flag, ConstantU32(state, 0u)); @@ -1571,11 +1566,7 @@ std::uint32_t EmitReadConst(SpirvValueEmitContext& ctx, const IrValue& inst) { StopBdaInvocationIf(state, poisoned); } } - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.flattenedSrtVariable, ConstantU32(state, 0u), ctx.Arg(inst, 1)); - const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); - return value; + return EmitFlattenedSrtLoad(state, ctx.Arg(inst, 1)); } void EmitReadConstBuffer(SpirvValueEmitContext& ctx, const IrValue& inst) { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp index 1265fd1b0280..9cd1f5537d43 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp @@ -137,6 +137,10 @@ std::uint32_t TypeStorageBufferU8ElementPointer(SpirvEmitterState& state) { return TypePointer(state, spv::StorageClassStorageBuffer, TypeU8(state)); } +std::uint32_t TypePhysicalBufferPointer(SpirvEmitterState& state, bool wide) { + return TypePointer(state, spv::StorageClassPhysicalStorageBuffer, wide ? StorageBufferU64Type(state) : StorageBufferType(state)); +} + std::uint32_t TypePhysicalU32Pointer(SpirvEmitterState& state) { return TypePointer(state, spv::StorageClassPhysicalStorageBuffer, TypeU32(state)); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp index 1bc242f265a8..ec21054749ce 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp @@ -1653,7 +1653,9 @@ void EmitProgram(SpirvEmitterState& state) { }); state.module.AddFunction(spv::OpControlBarrier, ConstantU32(state, spv::ScopeWorkgroup), ConstantU32(state, spv::ScopeWorkgroup), ConstantU32(state, spv::MemorySemanticsAcquireReleaseMask | LdsMemorySemantics(state))); } - if (state.gdsVariable != 0u) { + if (state.gdsVariable != 0u && state.program.Metadata().bindings.UsesDataAddress()) { + state.gdsLength = ConstantU32(state, RuntimeAbi::GdsBytes / 4u); + } else if (state.gdsVariable != 0u) { state.gdsLength = state.module.AllocateId(); state.module.AddFunction(spv::OpArrayLength, TypeU32(state), state.gdsLength, state.gdsVariable, 0u); } @@ -1686,6 +1688,7 @@ void EmitProgram(SpirvEmitterState& state) { state.module.AddFunction(spv::OpBeginInvocationInterlockEXT); } EmitMemoryOffsets(state); + EmitHeapSlotPreload(state); if (state.program.Resources().stage == IrShaderStage::Pixel && state.inputInfo.pixel != nullptr && state.inputInfo.pixel->QuadMasked()) { const auto& pixel = *state.inputInfo.pixel; const auto quad = EmitQuadPixel(state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index f3736dc698b3..aee0795089fc 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -155,6 +155,23 @@ RuntimeAddress address(SpirvValueEmitContext& context, const IrValue& instructio MemoryResourceAccess directAccess(SpirvValueEmitContext& context, const IrValue& instruction, bool wide = false, bool plainLoad = false) { auto& state = context.state; const auto& memory = context.Memory(instruction); + if (state.addressedBuffers) { + const auto element = ResourceForDescriptor(state, DescriptorBindingKind::Buffers, memory.resource); + const auto dword = state.program.Metadata().bindings.BufferAddressDword() + element * 4u; + const auto u64 = TypeScalarU64(state); + const auto low = Unary(state, spv::OpUConvert, u64, EmitShaderDataDwordLoad(state, dword)); + const auto high = Binary(state, spv::OpShiftLeftLogical, u64, Unary(state, spv::OpUConvert, u64, EmitShaderDataDwordLoad(state, dword + 1u)), BdaConstant(state, 32u)); + const auto address = Binary(state, spv::OpBitwiseOr, u64, low, high); + MemoryResourceAccess access; + access.kind = memory.kind; + access.physical = true; + access.objectPointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpConvertUToPtr, TypePhysicalBufferPointer(state, wide), access.objectPointer, address); + access.byteOffset = state.memoryByteOffsets.at(element); + access.memoryAccess = memory.coherent ? spv::MemoryAccessVolatileMask : 0u; + access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), EmitShaderDataDwordLoad(state, dword + 2u), ConstantU32(state, wide ? 3u : 2u)); + return access; + } const auto variable = wide ? state.storageBufferU64Variable : plainLoad || state.storageBufferCoherentVariable == 0u ? state.storageBufferVariable : state.storageBufferCoherentVariable; if (variable == 0u) context.Fail(instruction, "direct buffer descriptor array is missing"); const auto element = ResourceForDescriptor(state, DescriptorBindingKind::Buffers, memory.resource); @@ -208,7 +225,8 @@ std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruct const auto load = [&](std::uint32_t word) { const auto value = state.module.AllocateId(); const auto pointer = EmitMemoryElementPointer(state, access, word); - if (access.memoryAccess != 0u) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access.memoryAccess); + if (access.physical) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access.memoryAccess | spv::MemoryAccessAlignedMask, 4u); + else if (access.memoryAccess != 0u) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access.memoryAccess); else state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); return value; }; @@ -237,6 +255,7 @@ std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruct } std::uint32_t byteBuffers(SpirvEmitterState& state) { + if (state.addressedBuffers) return 0u; if (state.storageBufferU8Variable != 0u) return state.storageBufferU8Variable; if (state.program.Resources().stage != IrShaderStage::Compute) return 0u; if (std::find(state.supportedCapabilities.begin(), state.supportedCapabilities.end(), static_cast(spv::CapabilityStorageBuffer8BitAccess)) == state.supportedCapabilities.end()) return 0u; @@ -305,7 +324,8 @@ void writeBuffer(SpirvValueEmitContext& context, const IrValue& instruction, std if (bits == 32u) { EmitIfCondition(state, Unary(state, spv::OpLogicalNot, TypeBool(state), unaligned), [&] { const auto pointer = EmitMemoryElementPointer(state, access, index); - if (access.memoryAccess != 0u) state.module.AddFunction(spv::OpStore, pointer, value, access.memoryAccess); + if (access.physical) state.module.AddFunction(spv::OpStore, pointer, value, access.memoryAccess | spv::MemoryAccessAlignedMask, 4u); + else if (access.memoryAccess != 0u) state.module.AddFunction(spv::OpStore, pointer, value, access.memoryAccess); else state.module.AddFunction(spv::OpStore, pointer, value); }); } diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 6c47cfa19742..78d01a7e7820 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -131,6 +131,7 @@ flowchart LR - Queue 0's packet worker decodes, captures and prepares a draw and hands its recording (`Graphics::Draw` under the GPU lock) to a committer thread in [`DrawPipeline.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp), so the next packet is decoded while the previous draw is recorded. Each queued item carries the guest ranges it will write (`DrawWriteRanges`: written buffers and storage images, color targets with their DCC and CMASK, depth and stencil). A later packet that reads or writes one of those ranges, or that the pipeline can't order, drains it first; labels, submission ends, buffer fills and (with `APS5_PIPELINE_DMA=1`) DMA packets are queued as items instead. With `APS5_PIPELINE_DISPATCH=1` (off by default), a `DISPATCH_DIRECT` whose dispatch-cache entry hits with a recipe is queued as an item too, carrying the dispatch's written buffers and storage images (`DispatchWriteRanges`); the capture and the cache lookup stay on the worker and the recipe is recorded on the committer. A dispatch still drains when its lookup misses, when what it reads overlaps a write still pending, when the hit is verified against data or when its writes cannot be ranged (bindless access, GDS, fault buffer). An indirect draw resolved on the CPU (its records read by the worker) drains only when its records or its count overlap a queued write; the records it draws inline drain first, and its last drawn record is queued like a direct draw (`APS5_NO_PIPELINED_INDIRECT=1` drains at every indirect draw). An exception thrown by a commit is rethrown on the worker at its next enqueue or drain, as an inline draw error would be. On by default; `APS5_PIPELINED_DRAWS=0` records every draw inline, and `APS5_EXACT_DRAW_WRITES=0` widens the color and depth ranges to estimates. - A dispatch's resource build runs stage A (binding plan, buffers, descriptor set) without the GPU lock and stage B (image lookups) under it. Between them `VulkanDevice::presync` waits, still without the lock, for recorded work that writes a surface stage B would read on the CPU and for recorded work that writes the DCC keys of an image the dispatch binds (`ShaderResources::PresyncSurfaces`), so the locked `WaitForKeyWriters` finds nothing pending to synchronize with. A key range is waited for only when recorded work writes it, the key-store memo does not give its value (`DccKeyWritersPending`, without the mutex) and the pending stores do not give it either (`DccKeyWriterNeedsSync`, under the mutex, the same test `WaitForKeyWriters` makes before it synchronizes). Stage A's own key scan runs before that wait, and stage B compares it with the keys it reads under the lock as before. `APS5_NO_DCC_PRESYNC=1` leaves the key ranges out; `APS5_NO_PRESYNC=1` disables the whole pre-sync. - `APS5_DRAW_PIPELINE=1` (off by default, meant with `APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1`) takes more of a draw off the worker. A `DrawFinisher` thread runs the second half of a direct pipelined draw (stage materialization, the draw cache insert and the hand-off to the committer) while the worker reads the next packets; the worker drains it before the next draw's cache lookup, before packets other than register writes and draws, and before guest reads, and finishes in place a draw whose stages may write memory (`ProgramWritesMemory`) or write through the BDA page table. The committer skips the fragment-output validation and storage-image layer scans whose inputs match its last commit (`CommitTrims`), and a resource or storage image proved current keeps its proof for the rest of the collect epoch until `GuestMemory::BreakProofs` (a CPU write, a write-back, a recorded write) moves `ProofSerial`. Color metadata passes go through the pipeline with their write ranges (`PipelinedColorMetadataPassWrites`) instead of draining it. A data-only hit whose shape entry belongs to an older draw replaces that entry in place at the second sight of the same read user words. On Linux the main image's pages get a page table entry, and capture pages are pooled across threads. `APS5_VERIFY_DRAW_PIPELINE=1` runs a full check next to 1 in 64 reused proofs and prints `[epoch-proofs]` counts. +- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 4096 image slots per binding kind and 256 sampler slots, per-draw shader data and flattened SRT in a ring the shaders reach by address) instead of per-draw descriptor sets. Without the extension every stage takes the per-draw path. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; a stage stays GPU-mode only if its compiled module maps onto the heap and every stage of its draw is GPU-mode too; otherwise it is rebuilt on the per-draw path. A draw whose stages come out mixed is rebuilt once with what the first pass learned, and a stage pair that is still mixed takes the per-draw path from then on. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the heap ring and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap is recompiled on the per-dispatch path. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the heap ring per draw with its address in two more pushed dwords. Tables with image atomics stay off the heap. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers by device address (`addressedBuffers`: four shader data words per buffer, 64-bit address and byte size, after the slot words) instead of storage buffer descriptors; a draw whose buffers are snapshotted gets its own copy of the words with the snapshot addresses. - The shader registry maps a code address to every header registered for that code, in registration order. Static, graphics and rectangle ABI resolution pick the header at the bound address (or one equal to it, `SameHeader`, which also takes a hull header fused by `sceAgcFuseShaderHalves` (type 3) as the registered back half (type 7) it copies, the fused registers aside; graphics ABI resolution then uses the fused header's shader registers); draws and dispatches pick the program by the stage's binary type (`RegisteredProgram`), and a front entry matching both type 2 and type 4 throws. Within a type the last registration wins; re-registering an identical earlier header makes its snapshot current again without preparing it again, and changed code drops the older headers. - The snapshot is published as pending. `SourceHandleFor`, `InvocationFor` and `ShaderPreparationTransaction::Edit` / `Read` wait for the pending job before reading `PreparedShaders`, and rethrow its failure. `APS5_SYNC_SHADER_PREPARE=1` prepares on the registering thread instead. - `APS5_LAZY_SHADER_PREPARE=1` retains registration validation and decoding but discards the temporary plan without queueing preparation. The snapshot is deferred, not pending; draws and dispatches prepare and cache it on first use. A compute or pixel stage's explicit ABI resolution (`ResolveShaderAbi`) plans the stage with the ABI's state, records the ABI and leaves its preparation to the shader's first use, which prepares it with that state (`PreparedShaders::deferredAbis`), so a shader that never draws or dispatches stays unprepared; a graphics-stage ABI is still prepared when it is resolved. This opt-in mode takes precedence over synchronous registration preparation and trades background CPU/memory use for possible first-use stalls; disk caches and shader output are unchanged. diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 3a728911cd48..4d46c7e0b63f 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -159,11 +159,13 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_FULL_BARRIERS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records every barrier instead of merging redundant ones | | `APS5_GPU_CHECKPOINTS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | attaches device diagnostic checkpoints through VK_NV_device_diagnostic_checkpoints, or buffer markers through VK_AMD_buffer_marker on a device without it | | `APS5_GPU_COPY_MAX_KIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 1024 | size cap in KiB on a descriptor sub-range copied through the GPU path, larger ones staying on the CPU | +| `APS5_GPU_HEAP` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | | binds the sampled and storage images and samplers of eligible stages through the device's VK_EXT_descriptor_heap heaps; without the extension it does nothing | | `APS5_GPU_NO_WRITEBACK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | skips writing GPU results back into guest memory | | `APS5_GPU_WAIT_TIMEOUT_MS` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp` | 1000 | milliseconds a GPU wait may run before a warning is printed | | `APS5_GROUP_CAPTURE_ALL_QUEUES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp` | | resolves group-ahead capture on queue 0 as well | | `APS5_HANDOFF_SPIN_US` | integer | `core/libs/prx/libSceAgcDriver/Execution/include/HandoffSpin.hpp` | | microseconds a thread spins for a handed-off draw's work or for the GPU mutex before blocking, clamped to 0..10000; unset spins 150 us when the process has more than 8 usable processors and not at all otherwise | | `APS5_HEAP_MIRROR_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 24576 | budget in MiB for the heap mirrors held for registered allocations | +| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 4096 | number of image slots per binding kind the GPU heap uses; 0 keeps the default | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | | `APS5_HOOK_LOCKED_WAIT` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | keeps the flush hook's pending-write wait under the GpuMutex | @@ -453,6 +455,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_VERIFY_DRAW_PIPELINE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | runs a full check next to 1 in 64 reused proofs and prints `[epoch-proofs]` counts | | `APS5_VERIFY_DRAW_RECIPE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | re-decodes a draw recipe instead of using the cache and checks the result | | `APS5_VERIFY_DRAW_SNAPSHOTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | re-reads a reused draw snapshot and counts the ones that differ | +| `APS5_VERIFY_GPU_HEAP` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | | checks heap slots and GPU-read constants, and rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (0 or no number means every stage) | | `APS5_VERIFY_KNOWN_VALUES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferCopy.cpp` | | serves known values through the hook too and counts mismatches | | `APS5_VERIFY_PROOFS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | runs the full walk beside every own-object refresh proof and aborts on a different decision | | `APS5_VERIFY_RECIPE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | makes the ordinary prepare path beside a recipe hit and compares the answers | diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 36535fa9b418..7a301169a4d7 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -264,3 +264,4 @@ ### Opt-in draw paths - [Draw finisher](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp) (`APS5_DRAW_PIPELINE`) - opt-in. The Linux main-image page table it adds matches what Windows already does by default. +- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap`. A stage whose module keeps a set 0 binding (storage images of registration modules, GDS, the fault buffer), mesh and tessellation pipelines, image tables with atomics and compute stages without images take the per-draw path, and so does every other stage of their draw. diff --git a/docs/user/USAGE.md b/docs/user/USAGE.md index 3a4dc187ee57..834ac26dadc6 100644 --- a/docs/user/USAGE.md +++ b/docs/user/USAGE.md @@ -324,6 +324,10 @@ Besides the recompiled shaders, the shader cache directory holds `pipelines.jour `APS5_DRAW_PIPELINE=1` (off by default) moves more of each draw off the thread that reads the title's command buffers: a second thread finishes each draw while the next one is read, the thread that records draws skips work whose inputs did not change, and checks that a draw's resources are still current are reused until the title or the GPU writes memory. It is meant with `APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1`. The picture does not change; if it does, that is a bug, and a run without the switch shows whether it is the cause. `APS5_VERIFY_DRAW_PIPELINE=1` runs the full checks next to the reused ones, at a cost in speed, and prints `[epoch-proofs]` lines with how many differed (any nonzero count is a bug). `APS5_PROFILE_DRAW=1` finishes every draw on the reading thread, so a run with it does not measure this switch. To see the hand-off without that, set `APS5_PIPELINE_STATS` (any value; `1` also turns on Vulkan pipeline statistics, which cost time): every 10 s a `[finisher]` line counts the draws handed to the second thread and those finished on the reading thread, and `[finisher-held]` lines count the draws held back by why their writes are not known. +### GPU descriptor heap + +`APS5_GPU_HEAP=1` (off by default) binds the textures and samplers of most draws through one table the GPU indexes, instead of building them again for each draw. It needs a GPU driver with `VK_EXT_descriptor_heap`; without it the switch does nothing. Use it with `APS5_DRAW_PIPELINE=1` and the switches listed there. The first run with the switch compiles its own variant of each shader, so expect the same stutter as with an empty shader cache once. Wrong or missing textures or flicker that go away without the switch are bugs. `APS5_VERIFY_GPU_HEAP=1` checks the table against the bound textures, and builds some draws the old way and compares them; it prints `[heap-slots]` and `[gpu-heap]` lines (a slot holding another texture or a differing draw is a bug). + ### Texture cache budget Image and buffer memory allocations retry after releasing unused pooled buffers and reclaimable texture cache entries. Recovery preserves storage images with pending GPU results and resources retained by recorded work. `[bufferpool]` recovery and failure lines report the requested allocation, memory released and retry count. An allocation still fails if recovery cannot free enough memory. From 086fd887475dc9acc74383420d9a603ded364c52 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 05:24:10 +0530 Subject: [PATCH 002/269] chore(agc): heap coverage, set-bind and fallback counters under APS5_PIPELINE_STATS --- .../src/Driver/Dispatch/Dispatch.cpp | 2 + .../Execution/src/Driver/Draw/Draw.cpp | 1 + .../Execution/src/Driver/Draw/DrawCapture.cpp | 1 + .../Execution/src/PresentationPass.cpp | 2 +- .../Execution/src/VulkanDevice.cpp | 5 +- .../Graphics/include/BindlessHeap.hpp | 6 ++- .../Graphics/src/BindlessHeap.cpp | 49 ++++++++++++++++++- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 5 +- .../Graphics/src/GpuColorTransfer.cpp | 2 +- .../Graphics/src/ShaderResources.cpp | 4 +- .../Graphics/src/TextureDetiler.cpp | 8 +-- 11 files changed, 71 insertions(+), 14 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index d7fac001535a..2c487a7e5160 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -3,6 +3,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DrawWriteRanges.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/BufferCopy.hpp" @@ -372,6 +373,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, timing.Mark("capture_resources"); compiledResult = invocation.Materialize(*capture); if (compiledResult->gpuResolvedImages && !HeapStageMappable(*compiledResult, compiledResult->workgroupMemoryDwords != 0)) { + Graphics::NoteHeapFallback(Graphics::HeapFallback::DispatchUnmapped); NoteHeapFragment(&snapshot, codeOffset | computeHeapKey, false); request.target.gpuResolvedImages = false; invocation = InvocationFor(snapshot, codeOffset, request); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index d7ab7abf638e..e1c42a11e558 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -1035,6 +1035,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { if (const auto verdict = runStages()) return *verdict; for (std::uint32_t retry = 0; heapCheck && mixedHeap(); ++retry) { require(retry < 2u, "a draw mixes GPU-mode and per-draw stages after taking the per-draw path"); + Graphics::NoteHeapFallback(retry == 0u ? Graphics::HeapFallback::DrawMixedRetry : Graphics::HeapFallback::DrawRefusedPair); if (retry == 1u) RefuseHeapPair(heapPair); stages.resize(stagesBefore); compiledStages.resize(compiledBefore); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 7d920f1bdb35..ceb6e72e8aa5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -149,6 +149,7 @@ std::shared_ptr Driver::materializeDraw return std::runtime_error(where.str() + error.what()); }; const auto unmapped = [&] { + Graphics::NoteHeapFallback(Graphics::HeapFallback::DrawUnmapped); NoteHeapFragment(program.snapshot.get(), heapKey, false); return materializeDrawStage(i, pushOffset, queue, submission, packetOffset, traceToken, programs, graphics, pixel, vertexInfos, memory, linked, drawParameters, localDevice, shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics, heapPartners); }; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp index 210daab380e4..c63c627ab08b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp @@ -274,7 +274,7 @@ void PresentationPass::draw(VkCommandBuffer commands, const Slot& slot, const Ta const VkRect2D scissor{{0, 0}, extent}; context.Function("vkCmdSetViewport")(commands, 0, 1, &viewport); context.Function("vkCmdSetScissor")(commands, 0, 1, &scissor); - Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &slot.set); + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &slot.set, Graphics::SetBindSite::Presentation); context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), parameters); context.Function("vkCmdDraw")(commands, 3, 1, 0, 0); context.Function("vkCmdEndRenderPass")(commands); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 74129acbb352..1ac7adbbc50f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -5141,11 +5141,12 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { } } context.Resolved(&Graphics::DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->pipeline); + Graphics::NoteHeapRecord(true, record.objects->descriptorHeap); if (record.objects->descriptorHeap) { Graphics::BindlessHeap::For(context).BindDescriptorHeaps(commands); } else if (record.bindings != nullptr) { Graphics::Require(record.bindings->allocation.set != VK_NULL_HANDLE && !resources.HeapStage(), "dispatch overlay has no descriptor set"); - Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, 0, 1, &record.bindings->allocation.set); + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, 0, 1, &record.bindings->allocation.set, Graphics::SetBindSite::Dispatch); } else { Graphics::Require(!resources.HeapStage(), "a GPU-mode dispatch needs a VK_EXT_descriptor_heap pipeline"); resources.Bind(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout); @@ -5161,7 +5162,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { context.Function("vkCmdPushDataEXT")(commands, &push); } } else { - Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, workgroupSet, 1, &memory->set); + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, workgroupSet, 1, &memory->set, Graphics::SetBindSite::Dispatch); } recorder.Keep(std::move(memory)); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 98bf412f3c33..4e79ffcc6915 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -142,8 +142,12 @@ void NoteDataAddressPush(); void NoteEmptyResourceSet(); std::uint64_t EmptyResourceSets(); std::uint64_t DataAddressPushes(); +enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, Count }; +enum class HeapFallback : std::uint8_t { DrawUnmapped, DrawMixedRetry, DrawRefusedPair, DispatchUnmapped, Count }; +void NoteHeapRecord(bool compute, bool heap); +void NoteHeapFallback(HeapFallback reason); void NoteCommandBufferBegun(VkCommandBuffer commands); -void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets); +void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site); std::uint64_t DescriptorHeapBinds(); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 330ac1f42919..d1e586cdd968 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -638,6 +639,40 @@ namespace { std::mutex boundHeapsMutex; std::unordered_set boundHeaps; std::atomic heapBinds{0}; +std::atomic heapBindWindow{0}; +std::atomic commandBuffersBegun{0}; +std::array, static_cast(SetBindSite::Count)> setBinds{}; +std::array, static_cast(HeapFallback::Count)> heapFallbacks{}; +std::array, 4> heapRecords{}; +constexpr std::array(SetBindSite::Count)> SetBindSiteNames{"draw", "dispatch", "detiler", "color transfer", "presentation"}; +constexpr std::array(HeapFallback::Count)> HeapFallbackNames{"draw unmapped", "draw mixed retry", "draw refused pair", "dispatch unmapped"}; + +std::uint64_t takeCount(std::atomic& counter) { + return counter.exchange(0, std::memory_order_relaxed); +} + +void reportHeapStatistics() { + static const bool enabled = std::getenv("APS5_PIPELINE_STATS") != nullptr; + if (!enabled) return; + static std::atomic calls{0}; + if ((calls.fetch_add(1, std::memory_order_relaxed) & 1023u) != 0u) return; + static std::mutex reportMutex; + static auto last = std::chrono::steady_clock::now(); + std::unique_lock lock(reportMutex, std::try_to_lock); + if (!lock.owns_lock()) return; + const auto now = std::chrono::steady_clock::now(); + if (now - last < std::chrono::seconds(10)) return; + last = now; + std::string binds; + for (std::size_t i = 0; i < setBinds.size(); ++i) binds += " " + std::string(SetBindSiteNames[i]) + " " + std::to_string(takeCount(setBinds[i])); + std::string fallbacks; + for (std::size_t i = 0; i < heapFallbacks.size(); ++i) fallbacks += " " + std::string(HeapFallbackNames[i]) + " " + std::to_string(takeCount(heapFallbacks[i])); + const auto heapDraws = takeCount(heapRecords[1]); + const auto plainDraws = takeCount(heapRecords[0]); + const auto heapDispatches = takeCount(heapRecords[3]); + const auto plainDispatches = takeCount(heapRecords[2]); + std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s\n", static_cast(heapDraws), static_cast(plainDraws), static_cast(heapDispatches), static_cast(plainDispatches), static_cast(takeCount(heapBindWindow)), static_cast(takeCount(commandBuffersBegun)), binds.c_str(), fallbacks.c_str()); +} void forgetHeapBinding(VkCommandBuffer commands) { if (!DescriptorHeapEnabled()) return; @@ -647,12 +682,23 @@ void forgetHeapBinding(VkCommandBuffer commands) { } +void NoteHeapRecord(bool compute, bool heap) { + heapRecords[(compute ? 2u : 0u) + (heap ? 1u : 0u)].fetch_add(1, std::memory_order_relaxed); + reportHeapStatistics(); +} + +void NoteHeapFallback(HeapFallback reason) { + heapFallbacks[static_cast(reason)].fetch_add(1, std::memory_order_relaxed); +} + void NoteCommandBufferBegun(VkCommandBuffer commands) { + commandBuffersBegun.fetch_add(1, std::memory_order_relaxed); forgetHeapBinding(commands); } -void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets) { +void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site) { context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, bindPoint, layout, firstSet, setCount, sets, 0, nullptr); + setBinds[static_cast(site)].fetch_add(1, std::memory_order_relaxed); forgetHeapBinding(commands); } @@ -667,6 +713,7 @@ void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { if (!boundHeaps.insert(commands).second) return; } heapBinds.fetch_add(1, std::memory_order_relaxed); + heapBindWindow.fetch_add(1, std::memory_order_relaxed); VkBindHeapInfoEXT info{VK_STRUCTURE_TYPE_BIND_HEAP_INFO_EXT}; info.heapRange = {resourceHeap->DeviceAddress(), resourceHeapUsed + context.descriptorHeapProperties.minResourceHeapReservedRange}; info.reservedRangeOffset = resourceHeapUsed; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 552d002c92e7..910137ff581a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -2326,6 +2326,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam record.pipeline->Begin(commands, *record.framebuffer, state.renderExtent, state); } APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); + NoteHeapRecord(false, record.pipeline->DescriptorHeap()); if (record.pipeline->DescriptorHeap()) { BindlessHeap::For(context).BindDescriptorHeaps(commands); NoteEmptyResourceSet(); @@ -2333,8 +2334,8 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam Require(!resources.HeapStage(), "a GPU-mode draw needs a VK_EXT_descriptor_heap pipeline"); const auto set = drawBindings->allocation.set; const auto fragmentSet = drawBindings->fragmentAllocation.set; - if (set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), 0, 1, &set); - if (fragmentSet != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet); + if (set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), 0, 1, &set, SetBindSite::Draw); + if (fragmentSet != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet, SetBindSite::Draw); } else { Require(!resources.HeapStage(), "a GPU-mode draw needs a VK_EXT_descriptor_heap pipeline"); resources.Bind(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout()); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp index 920370bf89d6..64fe19a8c884 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp @@ -148,7 +148,7 @@ void GpuColorTransfer::dispatch(VkCommandBuffer commands, bool toTiled, bool swa barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr); const std::array push{width, height, (width + 127u) / 128u, (toTiled ? 1u : 0u) | (swapRedBlue ? 2u : 0u) | (tiledSource ? 4u : 0u) | (tenBit ? 8u : 0u) | (halfFloat ? 16u : 0u) | (pqWhiteNits ? 32u : 0u), std::bit_cast(pqWhiteNits.value_or(0.0f))}; context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); - CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &descriptorSet); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &descriptorSet, SetBindSite::ColorTransfer); context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); context.Function("vkCmdDispatch")(commands, (width + 7u) / 8u, (height + 7u) / 8u, 1); VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 5411b3d534a1..7ef9c354ec7b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -5958,8 +5958,8 @@ std::array ShaderR } void ShaderResources::Bind(VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout) const { - if (_set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, bindPoint, layout, 0, 1, &_set); - if (fragment.set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, bindPoint, layout, ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragment.set); + if (_set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, bindPoint, layout, 0, 1, &_set, bindPoint == VK_PIPELINE_BIND_POINT_COMPUTE ? SetBindSite::Dispatch : SetBindSite::Draw); + if (fragment.set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, bindPoint, layout, ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragment.set, bindPoint == VK_PIPELINE_BIND_POINT_COMPUTE ? SetBindSite::Dispatch : SetBindSite::Draw); } PipelineSetLayouts ShaderResources::SetLayouts() const { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index 1442273a2cfd..b7caf2e3307f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -239,7 +239,7 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode writes[1].pBufferInfo = &destinationInfo; context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target); - CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, SetBindSite::Detiler); Push push{}; push.srcBase = static_cast(sourceBase); push.dstBase = static_cast(destinationBase); @@ -304,7 +304,7 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s } context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, repackPipeline); - CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, SetBindSite::Detiler); const std::array push{static_cast(sourceOffset - sourceDescriptorOffset), static_cast(destinationOffset - destinationDescriptorOffset), static_cast(words), static_cast(std::min(words, rowWords))}; context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); context.Function("vkCmdDispatch")(commands, static_cast((std::min(words, rowWords) + 63u) / 64u), static_cast(rows), 1); @@ -386,7 +386,7 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask constexpr VkAccessFlags anyAccess = anyWrite | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_HOST_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT; barrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, anyWrite, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipeline); - CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipelineLayout, 0, 1, &set); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipelineLayout, 0, 1, &set, SetBindSite::Detiler); const std::uint32_t mask = elementBytes >= 4 ? 0xffffffffu : (1u << (elementBytes * 8u)) - 1u; const std::array push{static_cast(base), width, height, (width + 1023u) / 1024u, clearWords[0] & mask, elementBytes == 8 ? clearWords[1] : 0u, write ? 1u : 0u}; context.Function("vkCmdPushConstants")(commands, cmaskPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); @@ -429,7 +429,7 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til writes[1].pImageInfo = &imageInfo; context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target); - CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0, 1, &set); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0, 1, &set, SetBindSite::Detiler); Push push{}; push.srcBase = static_cast(retile ? 0 : base); push.dstBase = static_cast(retile ? base : 0); From 79b497d08273930ad7f46d5f4a84fbd7f5eaf0fd Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 05:51:46 +0530 Subject: [PATCH 003/269] fix(agc): find a joined import run from its first piece; count boot-state CPU copies and draw-stage heap reasons --- .../include/Driver/Draw/HeapStages.hpp | 2 ++ .../Execution/src/Driver/Draw/DrawCapture.cpp | 9 ++++++++- .../Execution/src/Driver/Draw/HeapStages.cpp | 14 ++++++++++++-- .../Graphics/include/BindlessHeap.hpp | 3 +++ .../Graphics/src/BindlessHeap.cpp | 17 ++++++++++++++++- .../Graphics/src/GuestBufferMemory.cpp | 1 + .../prx/libSceAgcDriver/tests/BdaResources.cpp | 3 +++ 7 files changed, 45 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index 151abcd55cb3..67df55b64290 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -3,6 +3,7 @@ #include "Optimization/ResourceProgram.hpp" #include "UserDataUse.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include #include @@ -16,6 +17,7 @@ namespace AgcDriver::DriverDetail { bool HeapFragmentsEnabled(); bool HeapRefused(); bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage); +Graphics::HeapStageReason HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex); bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex); std::optional HeapFragmentKnown(const void* snapshot, std::size_t codeOffset); void NoteHeapFragment(const void* snapshot, std::size_t codeOffset, bool eligible); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index ceb6e72e8aa5..1b89432f143f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -112,18 +112,25 @@ std::shared_ptr Driver::materializeDraw }; auto invocation = invocationFor(); const auto heapEligible = [&](const std::shared_ptr& plan) { return HeapStageEligible(program.binary.stage, plan.get(), heapVertex); }; + using StageReason = Graphics::HeapStageReason; + StageReason stageReason = StageReason::Heap; + if (!heapCandidate) stageReason = !HeapFragmentsEnabled() ? StageReason::Disabled : !heapPartners ? StageReason::PairRefused : StageReason::StageKind; + else if (heapKnown == std::optional(false)) stageReason = StageReason::KnownIneligible; if (heapKnown.value_or(false) && !heapEligible(invocation.Plan())) { + stageReason = HeapStageIneligibility(program.binary.stage, invocation.Plan().get(), heapVertex); NoteHeapFragment(program.snapshot.get(), heapKey, false); request.target.gpuResolvedImages = false; invocation = invocationFor(); } else if (heapCandidate && !heapKnown.has_value()) { - const bool eligible = heapEligible(invocation.Plan()); + stageReason = HeapStageIneligibility(program.binary.stage, invocation.Plan().get(), heapVertex); + const bool eligible = stageReason == StageReason::Heap; NoteHeapFragment(program.snapshot.get(), heapKey, eligible); if (eligible) { request.target.gpuResolvedImages = true; invocation = invocationFor(); } } + Graphics::NoteHeapStageReason(stageReason); timing.Mark("prepared_invocation"); auto& stageCapture = stageCaptures[i]; stageCapture.direct = false; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 2a4535836d42..d860cb7829cd 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -112,9 +112,19 @@ bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage) { return stage == Stage::Vertex || stage == Stage::Local || stage == Stage::TessellationControl || stage == Stage::TessellationEvaluation || stage == Stage::Mesh; } +Graphics::HeapStageReason HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex) { + using Reason = Graphics::HeapStageReason; + if (stage != ShaderRecompiler::ShaderStage::Fragment && !HeapPreRasterStage(stage)) return Reason::StageKind; + if (plan == nullptr) return Reason::NoPlan; + if (stage != ShaderRecompiler::ShaderStage::Fragment && !heapVertex) return Reason::FragmentOffHeap; + if (plan->stage == ShaderRecompiler::IrShaderStage::Unknown || plan->stage == ShaderRecompiler::IrShaderStage::Fetch) return Reason::PlanStage; + if (!ShaderRecompiler::HeapFragmentEligible(*plan)) return Reason::UnresolvedImageSource; + if (std::any_of(plan->info.images.begin(), plan->info.images.end(), [](const ShaderRecompiler::ImageResource& image) { return image.table != ShaderRecompiler::NoTable && (image.atomic || image.atomic64); })) return Reason::AtomicTableImage; + return Reason::Heap; +} + bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex) { - if (plan == nullptr || (stage != ShaderRecompiler::ShaderStage::Fragment && !HeapPreRasterStage(stage))) return false; - return (stage == ShaderRecompiler::ShaderStage::Fragment || heapVertex) && ShaderRecompiler::HeapFragmentEligible(*plan) && std::none_of(plan->info.images.begin(), plan->info.images.end(), [](const ShaderRecompiler::ImageResource& image) { return image.table != ShaderRecompiler::NoTable && (image.atomic || image.atomic64); }); + return HeapStageIneligibility(stage, plan, heapVertex) == Graphics::HeapStageReason::Heap; } namespace { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 4e79ffcc6915..e15624f6bf9c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -144,8 +144,11 @@ std::uint64_t EmptyResourceSets(); std::uint64_t DataAddressPushes(); enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, Count }; enum class HeapFallback : std::uint8_t { DrawUnmapped, DrawMixedRetry, DrawRefusedPair, DispatchUnmapped, Count }; +enum class HeapStageReason : std::uint8_t { Heap, Disabled, PairRefused, FragmentOffHeap, StageKind, NoPlan, PlanStage, UnresolvedImageSource, AtomicTableImage, KnownIneligible, Count }; +void NoteHeapStageReason(HeapStageReason reason); void NoteHeapRecord(bool compute, bool heap); void NoteHeapFallback(HeapFallback reason); +void NoteCpuBufferCopy(std::uint64_t bytes); void NoteCommandBufferBegun(VkCommandBuffer commands); void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site); std::uint64_t DescriptorHeapBinds(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index d1e586cdd968..df06390cb657 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -641,9 +641,13 @@ std::unordered_set boundHeaps; std::atomic heapBinds{0}; std::atomic heapBindWindow{0}; std::atomic commandBuffersBegun{0}; +std::atomic cpuBufferCopies{0}; +std::atomic cpuBufferCopyBytes{0}; std::array, static_cast(SetBindSite::Count)> setBinds{}; std::array, static_cast(HeapFallback::Count)> heapFallbacks{}; std::array, 4> heapRecords{}; +std::array, static_cast(HeapStageReason::Count)> heapStageReasons{}; +constexpr std::array(HeapStageReason::Count)> HeapStageReasonNames{"heap", "disabled", "pair refused", "fragment off heap", "stage kind", "no plan", "plan stage", "unresolved image source", "atomic table image", "known ineligible"}; constexpr std::array(SetBindSite::Count)> SetBindSiteNames{"draw", "dispatch", "detiler", "color transfer", "presentation"}; constexpr std::array(HeapFallback::Count)> HeapFallbackNames{"draw unmapped", "draw mixed retry", "draw refused pair", "dispatch unmapped"}; @@ -667,11 +671,13 @@ void reportHeapStatistics() { for (std::size_t i = 0; i < setBinds.size(); ++i) binds += " " + std::string(SetBindSiteNames[i]) + " " + std::to_string(takeCount(setBinds[i])); std::string fallbacks; for (std::size_t i = 0; i < heapFallbacks.size(); ++i) fallbacks += " " + std::string(HeapFallbackNames[i]) + " " + std::to_string(takeCount(heapFallbacks[i])); + std::string stageReasons; + for (std::size_t i = 0; i < heapStageReasons.size(); ++i) stageReasons += " " + std::string(HeapStageReasonNames[i]) + " " + std::to_string(takeCount(heapStageReasons[i])); const auto heapDraws = takeCount(heapRecords[1]); const auto plainDraws = takeCount(heapRecords[0]); const auto heapDispatches = takeCount(heapRecords[3]); const auto plainDispatches = takeCount(heapRecords[2]); - std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s\n", static_cast(heapDraws), static_cast(plainDraws), static_cast(heapDispatches), static_cast(plainDispatches), static_cast(takeCount(heapBindWindow)), static_cast(takeCount(commandBuffersBegun)), binds.c_str(), fallbacks.c_str()); + std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; CPU buffer copies %llu (%llu MiB)\n", static_cast(heapDraws), static_cast(plainDraws), static_cast(heapDispatches), static_cast(plainDispatches), static_cast(takeCount(heapBindWindow)), static_cast(takeCount(commandBuffersBegun)), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), static_cast(takeCount(cpuBufferCopies)), static_cast(takeCount(cpuBufferCopyBytes) >> 20u)); } void forgetHeapBinding(VkCommandBuffer commands) { @@ -687,6 +693,15 @@ void NoteHeapRecord(bool compute, bool heap) { reportHeapStatistics(); } +void NoteHeapStageReason(HeapStageReason reason) { + heapStageReasons[static_cast(reason)].fetch_add(1, std::memory_order_relaxed); +} + +void NoteCpuBufferCopy(std::uint64_t bytes) { + cpuBufferCopies.fetch_add(1, std::memory_order_relaxed); + cpuBufferCopyBytes.fetch_add(bytes, std::memory_order_relaxed); +} + void NoteHeapFallback(HeapFallback reason) { heapFallbacks[static_cast(reason)].fetch_add(1, std::memory_order_relaxed); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 365107c5160f..259ecaf9ab2d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -5244,6 +5244,7 @@ void GuestBufferMemory::copyRegion(Region& region, bool addressable) { readBytes += region.snapshot.size(); } region.snapshot.clear(); + NoteCpuBufferCopy(readBytes); if (profile) readUs.fetch_add(microsecondsSince(readStart), std::memory_order_relaxed); if (profile) { static AgcDriver::Mutex reasonsMutex; diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp b/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp index 15ad5d28b87f..ca5a036ae865 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp @@ -607,6 +607,9 @@ void importJoinTests(const Context& context) { Require(prefix != nullptr && prefix->base == heapBase && prefix->bytes == 3 * piece && prefixBuffer == prefix->buffer && prefixCopied == 0, "a buffer bound from the first of three pieces into the last was not imported over the pieces it crosses"); const auto* kept = HostImportFor(importing, first, 16); Require(kept != nullptr && kept->buffer == joinedBuffer && kept->bytes == 2 * large, "a registry change elsewhere re-imported the joined ranges"); + const auto [startedBuffer, startedCopied] = bind(heapBase, 2 * piece + 32); + const auto* started = HostImportFor(importing, heapBase, 2 * piece + 32); + Require(started != nullptr && started->base == heapBase && started->bytes == 3 * piece && startedBuffer == started->buffer && startedCopied == 0, "a buffer bound from the start of one piece into the next was not imported as one run"); change(guest + 2 * large, large, true); Require(HostImportFor(importing, first, 16)->buffer == joinedBuffer, "a range registered next to the joined ranges re-imported them"); const auto [grownBuffer, grownCopied] = bind(third - 16); From 404ccd1f7122fff279d5f2a0b34ab5282219ba13 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 06:00:58 +0530 Subject: [PATCH 004/269] fix(agc): agree heap mode across a draw's stages before refusing the pair Load a released resource plan instead of treating the stage as planless, and on the first mixed retry drop reused per-draw stages so they rebuild in GPU mode. Co-Authored-By: Claude Opus 5.5 --- .../libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp | 10 +++++++++- .../Execution/src/Driver/Draw/DrawCapture.cpp | 7 ++++--- .../libSceAgcDriver/Graphics/include/BindlessHeap.hpp | 2 +- .../prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp | 2 +- .../include/Optimization/ResourceProgram.hpp | 1 + core/shader/recompiler/Recompiler.cpp | 5 +++++ 6 files changed, 21 insertions(+), 6 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index e1c42a11e558..97f819198aa4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -954,6 +954,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { std::uint64_t heapPair = 0xcbf29ce484222325ull; for (const auto& program : programs) heapPair = (heapPair ^ reinterpret_cast(program.snapshot.get()) ^ (static_cast(program.codeOffset) << 1u)) * 0x100000001b3ull; const bool heapPairRefused = heapCheck && HeapPairRefused(heapPair); + bool heapRetry = false; const auto runStages = [&]() -> std::optional { for (std::size_t i = 0; i < programs.size(); ++i) { if (roles[i] == Role::GeometryBack) continue; @@ -966,7 +967,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); ringWords(i); } else { - const bool afterHeap = std::any_of(programResults.begin(), programResults.begin() + static_cast(i), [](const ShaderRecompiler::RecompileResult* earlier) { return earlier != nullptr && earlier->gpuResolvedImages; }); + const bool afterHeap = heapRetry || std::any_of(programResults.begin(), programResults.begin() + static_cast(i), [](const ShaderRecompiler::RecompileResult* earlier) { return earlier != nullptr && earlier->gpuResolvedImages; }); if (reused[i] && afterHeap && !matched[i]->compiled->gpuResolvedImages) { reused[i] = false; matched[i] = nullptr; @@ -1037,6 +1038,13 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { require(retry < 2u, "a draw mixes GPU-mode and per-draw stages after taking the per-draw path"); Graphics::NoteHeapFallback(retry == 0u ? Graphics::HeapFallback::DrawMixedRetry : Graphics::HeapFallback::DrawRefusedPair); if (retry == 1u) RefuseHeapPair(heapPair); + for (std::size_t i = 0; i < programs.size(); ++i) { + if (reused[i] && programResults[i] != nullptr && !programResults[i]->gpuResolvedImages) { + Graphics::NoteHeapFallback(Graphics::HeapFallback::DrawMixedReused); + break; + } + } + heapRetry = retry == 0u; stages.resize(stagesBefore); compiledStages.resize(compiledBefore); pushCursorBytes = pushBefore; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 1b89432f143f..d8b121baf0cc 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -112,17 +112,18 @@ std::shared_ptr Driver::materializeDraw }; auto invocation = invocationFor(); const auto heapEligible = [&](const std::shared_ptr& plan) { return HeapStageEligible(program.binary.stage, plan.get(), heapVertex); }; + const auto plan = heapCandidate && invocation.Plan() == nullptr ? invocation.LoadPlan() : invocation.Plan(); using StageReason = Graphics::HeapStageReason; StageReason stageReason = StageReason::Heap; if (!heapCandidate) stageReason = !HeapFragmentsEnabled() ? StageReason::Disabled : !heapPartners ? StageReason::PairRefused : StageReason::StageKind; else if (heapKnown == std::optional(false)) stageReason = StageReason::KnownIneligible; - if (heapKnown.value_or(false) && !heapEligible(invocation.Plan())) { - stageReason = HeapStageIneligibility(program.binary.stage, invocation.Plan().get(), heapVertex); + if (heapKnown.value_or(false) && !heapEligible(plan)) { + stageReason = HeapStageIneligibility(program.binary.stage, plan.get(), heapVertex); NoteHeapFragment(program.snapshot.get(), heapKey, false); request.target.gpuResolvedImages = false; invocation = invocationFor(); } else if (heapCandidate && !heapKnown.has_value()) { - stageReason = HeapStageIneligibility(program.binary.stage, invocation.Plan().get(), heapVertex); + stageReason = HeapStageIneligibility(program.binary.stage, plan.get(), heapVertex); const bool eligible = stageReason == StageReason::Heap; NoteHeapFragment(program.snapshot.get(), heapKey, eligible); if (eligible) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index e15624f6bf9c..416ccab28147 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -143,7 +143,7 @@ void NoteEmptyResourceSet(); std::uint64_t EmptyResourceSets(); std::uint64_t DataAddressPushes(); enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, Count }; -enum class HeapFallback : std::uint8_t { DrawUnmapped, DrawMixedRetry, DrawRefusedPair, DispatchUnmapped, Count }; +enum class HeapFallback : std::uint8_t { DrawUnmapped, DrawMixedRetry, DrawRefusedPair, DrawMixedReused, DispatchUnmapped, Count }; enum class HeapStageReason : std::uint8_t { Heap, Disabled, PairRefused, FragmentOffHeap, StageKind, NoPlan, PlanStage, UnresolvedImageSource, AtomicTableImage, KnownIneligible, Count }; void NoteHeapStageReason(HeapStageReason reason); void NoteHeapRecord(bool compute, bool heap); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index df06390cb657..367e17e3b0bd 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -649,7 +649,7 @@ std::array, 4> heapRecords{}; std::array, static_cast(HeapStageReason::Count)> heapStageReasons{}; constexpr std::array(HeapStageReason::Count)> HeapStageReasonNames{"heap", "disabled", "pair refused", "fragment off heap", "stage kind", "no plan", "plan stage", "unresolved image source", "atomic table image", "known ineligible"}; constexpr std::array(SetBindSite::Count)> SetBindSiteNames{"draw", "dispatch", "detiler", "color transfer", "presentation"}; -constexpr std::array(HeapFallback::Count)> HeapFallbackNames{"draw unmapped", "draw mixed retry", "draw refused pair", "dispatch unmapped"}; +constexpr std::array(HeapFallback::Count)> HeapFallbackNames{"draw unmapped", "draw mixed retry", "draw refused pair", "draw mixed reused", "dispatch unmapped"}; std::uint64_t takeCount(std::atomic& counter) { return counter.exchange(0, std::memory_order_relaxed); diff --git a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp index 2a3a7612b843..9d1af4624486 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp @@ -68,6 +68,7 @@ class PreparedShaderInvocation { std::shared_ptr Materialize(const ResourceCapture& capture) const; std::shared_ptr MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words) const; const std::shared_ptr& Plan() const; + std::shared_ptr LoadPlan() const; std::uint64_t VariantId() const; private: diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 93a11688c901..03d90f6712de 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -1868,6 +1868,11 @@ const std::shared_ptr& PreparedShaderInvocation::Plan() co return handle != nullptr && handle->source != nullptr ? handle->source->plan : none; } +std::shared_ptr PreparedShaderInvocation::LoadPlan() const { + if (handle == nullptr || handle->source == nullptr) return nullptr; + return acquirePlan(request, handle->source, false, handle.get()); +} + std::uint64_t PreparedShaderInvocation::VariantId() const { return handle != nullptr && handle->artifact != nullptr ? handle->artifact->artifact.variantId : 0u; } From 113a6e1b55671b7d081e74cfc098ae209c938b8e Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 07:11:42 +0530 Subject: [PATCH 005/269] perf(agc): keep unchanged heap stage data spans instead of rewriting them per use A GPU-mode stage's shader data, flattened SRT and image table map reuse the ring span written for the same words while the batch still holds its chunk, so a repeated draw or dispatch points at the table already in the heap. [gpu-heap] reports ring spans written and kept. Co-Authored-By: Claude Opus 5.5 --- .../Graphics/include/BindlessHeap.hpp | 9 ++++++ .../Graphics/include/ShaderResources.hpp | 7 ++++ .../Graphics/src/BindlessHeap.cpp | 32 +++++++++++++++++-- .../Graphics/src/ShaderResources.cpp | 20 +++++++----- .../tests/BindlessHeapSlots.cpp | 19 +++++++++++ 5 files changed, 77 insertions(+), 10 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 416ccab28147..b6c271f8fc2f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -56,6 +56,13 @@ class BindlessHeap { std::span words; }; DataSpan Allocate(std::size_t words); + struct SpanMark { + std::uint32_t offset = 0; + std::uint32_t words = 0; + std::uint64_t entry = 0; + }; + DataSpan Allocate(std::size_t words, SpanMark& mark); + bool Held(const SpanMark& mark); static constexpr std::uint32_t SamplerKind = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Samplers); void Submitted(Recorder& recorder, std::uint64_t serial); @@ -63,6 +70,7 @@ class BindlessHeap { struct Counts { std::uint64_t textures = 0, samplers = 0, full = 0, ringWraps = 0; std::uint64_t slotsFreed = 0, slotsReused = 0, sweeps = 0, chunkWaits = 0; + std::uint64_t spansWritten = 0, spansKept = 0; }; Counts Statistics() const; @@ -83,6 +91,7 @@ class BindlessHeap { Recorder* recorder = nullptr; std::uint64_t serial = 0; bool open = false; + std::uint64_t entries = 0; }; std::vector ringChunks; std::size_t ringChunk = ~std::size_t{0}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 36fec5502f29..96caa6ad20f0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -3,6 +3,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" @@ -620,8 +621,14 @@ class ShaderResources { std::vector samplerGenerations; std::uint64_t slotSerial = 0; std::vector> dataPatches; + struct KeptSpan { + std::vector words; + BindlessHeap::SpanMark mark; + }; + KeptSpan data, flat, map; }; std::array heapStages; + std::uint32_t heapSpan(HeapStageState::KeptSpan& kept, std::span words); static constexpr std::int64_t HeapRingDataFirst = -2; static constexpr std::int64_t HeapRingData(std::size_t stage) { return HeapRingDataFirst - static_cast(stage); } static constexpr bool IsHeapRingData(std::int64_t allocation) { return allocation <= HeapRingDataFirst && allocation > HeapRingDataFirst - static_cast(ShaderRecompiler::RuntimeAbi::StageCount); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 367e17e3b0bd..a24ea963d921 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -36,6 +36,9 @@ std::uint32_t fragmentBinding(std::uint32_t kind) { return Abi::BindingNumber(Abi::Stage::Fragment, static_cast(kind)); } +std::atomic spansWrittenWindow{0}; +std::atomic spansKeptWindow{0}; + } bool GpuHeapEnabled() { @@ -448,6 +451,24 @@ std::optional BindlessHeap::SamplerSlot(const std::shared_ptr(mark.words) * sizeof(std::uint32_t) - 1u) / RingChunkBytes; + if (first != last) return false; + std::lock_guard lock(mutex); + const auto& chunk = ringChunks[first]; + if (chunk.entries != mark.entry || !(chunk.open || first == ringChunk)) return false; + ++counts.spansKept; + spansKeptWindow.fetch_add(1, std::memory_order_relaxed); + return true; +} + +BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) { const auto bytes = words * sizeof(std::uint32_t); if (bytes > RingChunkBytes) throw std::runtime_error("AGC bindless heap: per-draw data exceeds a ring chunk"); std::lock_guard lock(mutex); @@ -459,6 +480,9 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words) { ringCursor = offset + bytes; for (auto chunk = offset / RingChunkBytes; chunk <= (offset + std::max(bytes, 1u) - 1u) / RingChunkBytes; ++chunk) enterChunk(ringChunks, chunk, ringChunk, "shader data"); auto* base = reinterpret_cast(ring->Bytes().data() + offset); + ++counts.spansWritten; + spansWrittenWindow.fetch_add(1, std::memory_order_relaxed); + mark = {static_cast(offset), static_cast(words), ringChunks[offset / RingChunkBytes].entries}; return {static_cast(offset), std::span(base, words)}; } @@ -474,6 +498,7 @@ void BindlessHeap::enterChunk(std::vector& chunks, std::size_t index, std chunk.serial = 0u; } chunk.open = true; + ++chunk.entries; } VkDeviceSize BindlessHeap::ImageHeapOffset(std::uint32_t kind) const { @@ -677,7 +702,7 @@ void reportHeapStatistics() { const auto plainDraws = takeCount(heapRecords[0]); const auto heapDispatches = takeCount(heapRecords[3]); const auto plainDispatches = takeCount(heapRecords[2]); - std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; CPU buffer copies %llu (%llu MiB)\n", static_cast(heapDraws), static_cast(plainDraws), static_cast(heapDispatches), static_cast(plainDispatches), static_cast(takeCount(heapBindWindow)), static_cast(takeCount(commandBuffersBegun)), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), static_cast(takeCount(cpuBufferCopies)), static_cast(takeCount(cpuBufferCopyBytes) >> 20u)); + std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept\n", static_cast(heapDraws), static_cast(plainDraws), static_cast(heapDispatches), static_cast(plainDispatches), static_cast(takeCount(heapBindWindow)), static_cast(takeCount(commandBuffersBegun)), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), static_cast(takeCount(cpuBufferCopies)), static_cast(takeCount(cpuBufferCopyBytes) >> 20u), static_cast(takeCount(spansWrittenWindow)), static_cast(takeCount(spansKeptWindow))); } void forgetHeapBinding(VkCommandBuffer commands) { @@ -747,7 +772,10 @@ VkDeviceAddress BindlessHeap::RingAddress() const { void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { std::lock_guard lock(mutex); for (std::size_t index = 0; index < ringChunks.size(); ++index) { - if (ringChunks[index].open || index == ringChunk) ringChunks[index] = {&recorder, serial, index == ringChunk}; + if (!ringChunks[index].open && index != ringChunk) continue; + ringChunks[index].recorder = &recorder; + ringChunks[index].serial = serial; + ringChunks[index].open = index == ringChunk; } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 7ef9c354ec7b..0665d086ba69 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6128,12 +6128,19 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ map.push_back(*slot); } if (map.size() == base) map.push_back(sampledAbsent); - auto span = heap.Allocate(map.size()); - std::memcpy(span.words.data(), map.data(), map.size() * sizeof(std::uint32_t)); - heapTableMaps[stageIndex] = static_cast(span.offset); + heapTableMaps[stageIndex] = heapSpan(heapStages[stageIndex].map, map); heapTableMapSet[stageIndex] = true; } +std::uint32_t ShaderResources::heapSpan(HeapStageState::KeptSpan& kept, std::span words) { + auto& heap = BindlessHeap::For(context); + if (std::ranges::equal(kept.words, words) && heap.Held(kept.mark)) return kept.mark.offset; + auto span = heap.Allocate(words.size(), kept.mark); + std::memcpy(span.words.data(), words.data(), words.size() * sizeof(std::uint32_t)); + kept.words.assign(words.begin(), words.end()); + return span.offset; +} + void ShaderResources::writeHeapStage(const CompiledShader& shader) { namespace Abi = ShaderRecompiler::RuntimeAbi; auto& heap = BindlessHeap::For(context); @@ -6265,10 +6272,8 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { if (binding.role != ShaderRecompiler::DescriptorRole::ShaderData && binding.role != ShaderRecompiler::DescriptorRole::FlattenedSrt) continue; const auto& words = binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt && shader.heap != nullptr && !shader.heap->flattenedSrt.empty() ? shader.heap->flattenedSrt : DrawGuestWords(shader, binding); if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, words); - auto span = heap.Allocate(words.size()); if (binding.role != ShaderRecompiler::DescriptorRole::ShaderData) { - std::memcpy(span.words.data(), words.data(), words.size() * sizeof(std::uint32_t)); - heapOffsets[flatIndex] = span.offset; + heapOffsets[flatIndex] = heapSpan(stageState.flat, words); heapSrtDwords[stageIndex] = static_cast(words.size()); continue; } @@ -6317,8 +6322,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { stageDataWords[stageIndex].assign(patched.begin(), patched.end()); stageDataIndex[stageIndex] = dataIndex; } - std::memcpy(span.words.data(), patched.data(), patched.size() * sizeof(std::uint32_t)); - heapOffsets[dataIndex] = span.offset; + heapOffsets[dataIndex] = heapSpan(stageState.data, patched); } } } diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index bac8ddff51e7..f7afa2d7544b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -82,6 +82,24 @@ void samplerSlots(const Context& context) { require(heap.SamplerGeneration(*slot) != generation, "a freed sampler slot moves its generation"); } +void ringSpans(const Context& context) { + BindlessHeap heap(context); + BindlessHeap::SpanMark unwritten; + require(!heap.Held(unwritten), "a span never written is not held"); + BindlessHeap::SpanMark first; + const auto span = heap.Allocate(16u, first); + require(first.offset == span.offset && first.words == 16u && heap.Held(first), "a span written in the open chunk is held"); + constexpr std::size_t chunkWords = (4u << 20u) / sizeof(std::uint32_t); + BindlessHeap::SpanMark filler; + static_cast(heap.Allocate(chunkWords - 1024u, filler)); + BindlessHeap::SpanMark crossing; + static_cast(heap.Allocate(4096u, crossing)); + require(!heap.Held(crossing), "a span over two chunks is never kept"); + require(heap.Held(first), "a span stays held while its batch keeps the chunk open"); + const auto counts = heap.Statistics(); + require(counts.spansWritten == 3u && counts.spansKept == 2u, "three spans written and two kept"); +} + } void heapComesBack(const Context& context, VkImageView view) { @@ -146,6 +164,7 @@ int main(int argc, char** argv) { const PlaceholderImages placeholders(context); textureSlots(context, placeholders.View(Abi::FirstImageBinding)); samplerSlots(context); + ringSpans(context); device->WaitIdle(); } device.reset(); From 725a42116b74c5acddb0f67fd8930994ecfee629 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 07:39:31 +0530 Subject: [PATCH 006/269] perf(agc): reuse a GPU-mode stage's shader data span when its inputs and slots are unchanged writeHeapStage skips validating, patching and copying the shader data words when the guest words and user data match the previous write, the stage's slots are current and the span is still held. APS5_VERIFY_GPU_HEAP recomputes the words and fails if they would differ. Co-Authored-By: Claude Opus 5.5 --- .../libSceAgcDriver/Graphics/include/ShaderResources.hpp | 1 + .../prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 96caa6ad20f0..bfb0f419a89a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -626,6 +626,7 @@ class ShaderResources { BindlessHeap::SpanMark mark; }; KeptSpan data, flat, map; + std::vector dataInput; }; std::array heapStages; std::uint32_t heapSpan(HeapStageState::KeptSpan& kept, std::span words); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 0665d086ba69..56fad2d1e298 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6271,6 +6271,12 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { for (const auto& binding : program.bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::ShaderData && binding.role != ShaderRecompiler::DescriptorRole::FlattenedSrt) continue; const auto& words = binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt && shader.heap != nullptr && !shader.heap->flattenedSrt.empty() ? shader.heap->flattenedSrt : DrawGuestWords(shader, binding); + const auto userData = shader.heap != nullptr ? std::span(shader.heap->userData) : std::span{}; + const bool sameInput = binding.role == ShaderRecompiler::DescriptorRole::ShaderData && current && stageState.dataInput.size() == words.size() + userData.size() && std::equal(words.begin(), words.end(), stageState.dataInput.begin()) && std::equal(userData.begin(), userData.end(), stageState.dataInput.begin() + static_cast(words.size())); + if (sameInput && !verifySlots && heap.Held(stageState.data.mark)) { + heapOffsets[dataIndex] = stageState.data.mark.offset; + continue; + } if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, words); if (binding.role != ShaderRecompiler::DescriptorRole::ShaderData) { heapOffsets[flatIndex] = heapSpan(stageState.flat, words); @@ -6322,7 +6328,10 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { stageDataWords[stageIndex].assign(patched.begin(), patched.end()); stageDataIndex[stageIndex] = dataIndex; } + if (verifySlots && sameInput && !std::ranges::equal(stageState.data.words, patched)) throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its inputs and slots did not"); heapOffsets[dataIndex] = heapSpan(stageState.data, patched); + stageState.dataInput.assign(words.begin(), words.end()); + stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); } } } From 583e604282f73960feffa554c2493c0f92f6752a Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 07:42:30 +0530 Subject: [PATCH 007/269] chore(agc): name the descriptor binding that keeps a stage off the heap under APS5_PIPELINE_STATS Co-Authored-By: Claude Opus 5.5 --- .../Graphics/src/BindlessHeap.cpp | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index a24ea963d921..30247c10ecf0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -546,7 +546,7 @@ namespace { const std::uint32_t GeneratedFaultBinding = Abi::BindingNumber(Abi::Stage::TessellationControl, Abi::Binding::FaultBuffer); -bool heapBindings(std::span spirv, bool workgroupAddress, bool gdsAddress, bool faultAddress, std::vector& bindings, bool& workgroupMemory, std::uint32_t& gdsBinding, bool& faultMemory) { +bool heapBindings(std::span spirv, bool workgroupAddress, bool gdsAddress, bool faultAddress, std::vector& bindings, bool& workgroupMemory, std::uint32_t& gdsBinding, bool& faultMemory, std::pair* refused = nullptr) { bindings.clear(); workgroupMemory = false; gdsBinding = ~0u; @@ -582,7 +582,10 @@ bool heapBindings(std::span spirv, bool workgroupAddress, b faultMemory = true; continue; } - if (entry.first != Abi::FragmentDescriptorSet || entry.second < bindingCount + Abi::FirstImageBinding || entry.second > bindingCount + samplerBinding) return false; + if (entry.first != Abi::FragmentDescriptorSet || entry.second < bindingCount + Abi::FirstImageBinding || entry.second > bindingCount + samplerBinding) { + if (refused != nullptr) *refused = entry; + return false; + } if (std::find(bindings.begin(), bindings.end(), entry.second) == bindings.end()) bindings.push_back(entry.second); } return (!workgroupAddress || workgroupMemory) && (!faultAddress || faultMemory); @@ -595,7 +598,17 @@ bool DescriptorHeapMappable(std::span spirv, bool workgroup bool workgroupMemory = false; std::uint32_t gdsBinding = ~0u; bool faultMemory = false; - return heapBindings(spirv, workgroupAddress, gdsAddress, false, bindings, workgroupMemory, gdsBinding, faultMemory); + std::pair refused{~0u, ~0u}; + const bool mappable = heapBindings(spirv, workgroupAddress, gdsAddress, false, bindings, workgroupMemory, gdsBinding, faultMemory, &refused); + static const bool stats = std::getenv("APS5_PIPELINE_STATS") != nullptr; + if (!mappable && stats) { + static std::mutex causesMutex; + static std::map, std::uint64_t> causes; + std::lock_guard lock(causesMutex); + const auto count = ++causes[refused]; + if (count == 1u || (count & (count - 1u)) == 0u) std::fprintf(stderr, "[gpu-heap] unmappable stage: descriptor set %d binding %d (workgroup address %d, gds address %d); %llu stage variants with this cause\n", static_cast(refused.first), static_cast(refused.second), workgroupAddress ? 1 : 0, gdsAddress ? 1 : 0, static_cast(count)); + } + return mappable; } bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset, bool rootGds, bool rootFault) const { From fcb79ef676d1dd6d0952f5325e2548ea10c295d1 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 07:52:53 +0530 Subject: [PATCH 008/269] perf(agc): detile and repack through buffer addresses when the descriptor heap is on --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 25 ++++ .../Graphics/include/TextureDetiler.hpp | 8 +- .../Graphics/shaders/TextureDetile.comp | 14 ++ .../Graphics/shaders/TextureRepack.comp | 16 ++ .../Graphics/src/TextureDetiler.cpp | 137 ++++++++++++++---- 5 files changed, 170 insertions(+), 30 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index a8292e61c990..3375c88383ee 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -116,6 +116,18 @@ add_custom_command( VERBATIM ) +set(agcTextureDetileAddressedShaderSpv ${agcTextureDetileGeneratedDir}/TextureDetileAddressed.spv) +set(agcTextureDetileAddressedShaderHeader ${agcTextureDetileGeneratedDir}/TextureDetileAddressed_spv.h) +add_custom_command( + OUTPUT "${agcTextureDetileAddressedShaderHeader}" + COMMAND ${CMAKE_COMMAND} -E make_directory "${agcTextureDetileGeneratedDir}" + COMMAND "$" -V --target-env vulkan1.1 -DADDRESSED=1 -o "${agcTextureDetileAddressedShaderSpv}" "${agcTextureDetileShaderSource}" + COMMAND ${CMAKE_COMMAND} -DINPUT=${agcTextureDetileAddressedShaderSpv} -DOUTPUT=${agcTextureDetileAddressedShaderHeader} + -DSYMBOL=TEXTURE_DETILE_ADDRESSED_SPV -P "${CMAKE_CURRENT_SOURCE_DIR}/embed_spirv.cmake" + DEPENDS "${agcTextureDetileShaderSource}" glslang-standalone + VERBATIM +) + set(agcTextureRepackShaderSource ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/shaders/TextureRepack.comp) set(agcTextureRepackShaderSpv ${agcTextureDetileGeneratedDir}/TextureRepack.spv) set(agcTextureRepackShaderHeader ${agcTextureDetileGeneratedDir}/TextureRepack_spv.h) @@ -128,6 +140,17 @@ add_custom_command( DEPENDS "${agcTextureRepackShaderSource}" glslang-standalone VERBATIM ) +set(agcTextureRepackAddressedShaderSpv ${agcTextureDetileGeneratedDir}/TextureRepackAddressed.spv) +set(agcTextureRepackAddressedShaderHeader ${agcTextureDetileGeneratedDir}/TextureRepackAddressed_spv.h) +add_custom_command( + OUTPUT "${agcTextureRepackAddressedShaderHeader}" + COMMAND ${CMAKE_COMMAND} -E make_directory "${agcTextureDetileGeneratedDir}" + COMMAND "$" -V --target-env vulkan1.1 -DADDRESSED=1 -o "${agcTextureRepackAddressedShaderSpv}" "${agcTextureRepackShaderSource}" + COMMAND ${CMAKE_COMMAND} -DINPUT=${agcTextureRepackAddressedShaderSpv} -DOUTPUT=${agcTextureRepackAddressedShaderHeader} + -DSYMBOL=TEXTURE_REPACK_ADDRESSED_SPV -P "${CMAKE_CURRENT_SOURCE_DIR}/embed_spirv.cmake" + DEPENDS "${agcTextureRepackShaderSource}" glslang-standalone + VERBATIM +) set(agcDispatchArgumentsShaderSource ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/shaders/DispatchArguments.comp) set(agcDispatchArgumentsShaderSpv ${agcTextureDetileGeneratedDir}/DispatchArguments.spv) @@ -365,6 +388,8 @@ set(agcDriverSources ${agcMeshArgumentsShaderHeader} ${agcTextureDetileImageShaderHeader} ${agcTextureRepackShaderHeader} + ${agcTextureDetileAddressedShaderHeader} + ${agcTextureRepackAddressedShaderHeader} ${agcDispatchArgumentsShaderHeader} ${agcSampleCounterShaderHeader} ${agcSampleDumpsShaderHeader} diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp index d0b15ac51c8a..3647a8549445 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp @@ -61,7 +61,8 @@ namespace AgcDriver::Graphics { private: VkPipeline multisampleReadbackPipeline(std::uint32_t elementBytes, bool depth); VkPipeline multisampleUploadPipeline(std::uint32_t elementBytes); - VkPipeline pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image = false); + VkPipeline pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image = false, bool addressed = false); + VkDeviceAddress bufferAddress(VkBuffer buffer) const; void release() noexcept; struct DescriptorRing { std::vector pools; @@ -90,6 +91,11 @@ namespace AgcDriver::Graphics { VkShaderModule imageModule = VK_NULL_HANDLE; VkShaderModule repackModule = VK_NULL_HANDLE; VkPipeline repackPipeline = VK_NULL_HANDLE; + VkPipelineLayout addressedPipelineLayout = VK_NULL_HANDLE; + VkPipelineLayout addressedRepackLayout = VK_NULL_HANDLE; + VkShaderModule addressedModule = VK_NULL_HANDLE; + VkShaderModule addressedRepackModule = VK_NULL_HANDLE; + VkPipeline addressedRepackPipeline = VK_NULL_HANDLE; DescriptorRing imageDescriptorSets; VkDescriptorSetLayout readbackDescriptorLayout = VK_NULL_HANDLE; VkPipelineLayout readbackPipelineLayout = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureDetile.comp b/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureDetile.comp index fcff04497b3c..2aae1c574ba4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureDetile.comp +++ b/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureDetile.comp @@ -35,6 +35,11 @@ layout(local_size_x = 8, local_size_y = 8) in; #ifdef LINEAR_IMAGE layout(set = 0, binding = 0, std430) buffer Tiled { uint data[]; } tiledBuffer; layout(set = 0, binding = 1) uniform uimage2D linearImage; +#elif defined(ADDRESSED) +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer Input { uint data[]; }; +layout(buffer_reference, std430, buffer_reference_align = 4) buffer Output { uint data[]; }; #else layout(set = 0, binding = 0, std430) readonly buffer Input { uint data[]; } inputBuffer; layout(set = 0, binding = 1, std430) buffer Output { uint data[]; } outputBuffer; @@ -64,8 +69,17 @@ layout(push_constant) uniform Push { uint columnBegin; uint rowBegin; uint pipeBankXor; +#ifdef ADDRESSED + uvec2 inputAddress; + uvec2 outputAddress; +#endif } params; +#ifdef ADDRESSED +#define inputBuffer Input(params.inputAddress) +#define outputBuffer Output(params.outputAddress) +#endif + uint equationBit(uint mask, uvec2 p) { uint selected = (p.x & (mask & 0xfffu)) ^ ((p.y << 12) & (mask & 0xfff000u)) ^ ((params.slice << 24) & (mask & 0xff000000u)); return bitCount(selected) & 1u; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureRepack.comp b/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureRepack.comp index 6de2f05e4a82..2febfe6ae06b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureRepack.comp +++ b/core/libs/prx/libSceAgcDriver/Graphics/shaders/TextureRepack.comp @@ -2,16 +2,32 @@ layout(local_size_x = 64) in; +#ifdef ADDRESSED +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_buffer_reference_uvec2 : require +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer Source { uint data[]; }; +layout(buffer_reference, std430, buffer_reference_align = 4) buffer Destination { uint data[]; }; +#else layout(std430, set = 0, binding = 0) readonly buffer Source { uint source[]; }; layout(std430, set = 0, binding = 1) buffer Destination { uint destination[]; }; +#endif layout(push_constant) uniform Push { uint sourceBase; uint destinationBase; uint words; uint rowWords; +#ifdef ADDRESSED + uvec2 sourceAddress; + uvec2 destinationAddress; +#endif } push; +#ifdef ADDRESSED +#define source Source(push.sourceAddress).data +#define destination Destination(push.destinationAddress).data +#endif + void main() { const uint index = gl_GlobalInvocationID.y * push.rowWords + gl_GlobalInvocationID.x; if (gl_GlobalInvocationID.x >= push.rowWords || index >= push.words) return; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index b7caf2e3307f..78c6d647d702 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -7,9 +7,13 @@ #include "prx/libSceAgcDriver/Graphics/shaders/CmaskClear_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/TextureDetileImage_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/TextureRepack_spv.h" +#include "prx/libSceAgcDriver/Graphics/shaders/TextureDetileAddressed_spv.h" +#include "prx/libSceAgcDriver/Graphics/shaders/TextureRepackAddressed_spv.h" +#include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include #include #include +#include #include #include #include @@ -40,6 +44,21 @@ struct Push { std::uint32_t pipeBankXor; }; +struct AddressedPush { + Push push; + std::uint64_t input; + std::uint64_t output; +}; + +struct AddressedRepackPush { + std::array push; + std::uint64_t source; + std::uint64_t destination; +}; + +static_assert(offsetof(AddressedPush, input) == 72 && sizeof(AddressedPush) == 88); +static_assert(offsetof(AddressedRepackPush, source) == 16 && sizeof(AddressedRepackPush) == 32); + std::uint32_t BlockBytesFor(TextureTileMode tileMode) { switch (tileMode) { case TextureTileMode::kLinear: return 0u; @@ -61,8 +80,8 @@ std::uint32_t BlockBytesFor(TextureTileMode tileMode) { throw std::runtime_error("AGC graphics: TextureDetiler encountered an unknown tile mode"); } -std::uint32_t PipelineKey(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image) { - return (image ? 1u << 18 : 0u) | (thick ? 1u << 17 : 0u) | (retile ? 1u << 16 : 0u) | (static_cast(tileMode) << 8) | elementBytes; +std::uint32_t PipelineKey(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, bool addressed) { + return (addressed ? 1u << 19 : 0u) | (image ? 1u << 18 : 0u) | (thick ? 1u << 17 : 0u) | (retile ? 1u << 16 : 0u) | (static_cast(tileMode) << 8) | elementBytes; } } @@ -95,6 +114,14 @@ TextureDetiler::TextureDetiler(const Context& context) : context(context) { Check(context.Function("vkCreateDescriptorSetLayout")(context.device, &layoutInfo, nullptr, &imageDescriptorLayout), "vkCreateDescriptorSetLayout"); pipelineLayoutInfo.pSetLayouts = &imageDescriptorLayout; Check(context.Function("vkCreatePipelineLayout")(context.device, &pipelineLayoutInfo, nullptr, &imagePipelineLayout), "vkCreatePipelineLayout"); + if (context.bufferDeviceAddress) { + pipelineLayoutInfo.setLayoutCount = 0; + pipelineLayoutInfo.pSetLayouts = nullptr; + pushRange.size = sizeof(AddressedPush); + Check(context.Function("vkCreatePipelineLayout")(context.device, &pipelineLayoutInfo, nullptr, &addressedPipelineLayout), "vkCreatePipelineLayout"); + pushRange.size = sizeof(AddressedRepackPush); + Check(context.Function("vkCreatePipelineLayout")(context.device, &pipelineLayoutInfo, nullptr, &addressedRepackLayout), "vkCreatePipelineLayout"); + } } catch (...) { release(); throw; @@ -120,6 +147,11 @@ void TextureDetiler::release() noexcept { for (const auto pool : descriptorSets.pools) context.Function("vkDestroyDescriptorPool")(context.device, pool, nullptr); for (const auto pool : imageDescriptorSets.pools) context.Function("vkDestroyDescriptorPool")(context.device, pool, nullptr); if (imageModule) context.Function("vkDestroyShaderModule")(context.device, imageModule, nullptr); + if (addressedRepackPipeline) context.Function("vkDestroyPipeline")(context.device, addressedRepackPipeline, nullptr); + if (addressedRepackModule) context.Function("vkDestroyShaderModule")(context.device, addressedRepackModule, nullptr); + if (addressedModule) context.Function("vkDestroyShaderModule")(context.device, addressedModule, nullptr); + if (addressedRepackLayout) context.Function("vkDestroyPipelineLayout")(context.device, addressedRepackLayout, nullptr); + if (addressedPipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, addressedPipelineLayout, nullptr); if (repackPipeline) context.Function("vkDestroyPipeline")(context.device, repackPipeline, nullptr); if (repackModule) context.Function("vkDestroyShaderModule")(context.device, repackModule, nullptr); if (imagePipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, imagePipelineLayout, nullptr); @@ -141,9 +173,15 @@ VkFormat TextureDetiler::ImageElementFormat(std::uint32_t elementBytes) { } } -VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image) { +VkDeviceAddress TextureDetiler::bufferAddress(VkBuffer buffer) const { + if (addressedPipelineLayout == VK_NULL_HANDLE || !BufferPool::ForceAddresses()) return 0; + const VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer}; + return context.Function("vkGetBufferDeviceAddressKHR")(context.device, &info); +} + +VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, bool addressed) { Require(std::has_single_bit(elementBytes) && elementBytes <= 16u, "unsupported element size for texture detiling"); - const auto key = PipelineKey(tileMode, elementBytes, retile, thick, image); + const auto key = PipelineKey(tileMode, elementBytes, retile, thick, image, addressed); for (const auto& entry : pipelines) { if (entry.first == key) return entry.second; } @@ -166,6 +204,12 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem values[2] = 2u; std::copy(equation->bits.begin(), equation->bits.end(), values.begin() + 4); } + if (addressed && addressedModule == VK_NULL_HANDLE) { + VkShaderModuleCreateInfo moduleInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + moduleInfo.codeSize = sizeof(TEXTURE_DETILE_ADDRESSED_SPV); + moduleInfo.pCode = TEXTURE_DETILE_ADDRESSED_SPV; + Check(context.Function("vkCreateShaderModule")(context.device, &moduleInfo, nullptr, &addressedModule), "vkCreateShaderModule"); + } if (image && imageModule == VK_NULL_HANDLE) { imageModule = CreateShaderModule(context, TEXTURE_DETILE_IMAGE_SPV, sizeof(TEXTURE_DETILE_IMAGE_SPV), "vkCreateShaderModule"); } @@ -178,12 +222,12 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem specialization.pData = values.data(); VkPipelineShaderStageCreateInfo stage{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - stage.module = image ? imageModule : module; + stage.module = addressed ? addressedModule : image ? imageModule : module; stage.pName = "main"; stage.pSpecializationInfo = &specialization; VkComputePipelineCreateInfo createInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; createInfo.stage = stage; - createInfo.layout = image ? imagePipelineLayout : pipelineLayout; + createInfo.layout = addressed ? addressedPipelineLayout : image ? imagePipelineLayout : pipelineLayout; VkPipeline result = VK_NULL_HANDLE; { auto pipelineCacheLock = context.LockPipelineCacheForUse(); @@ -207,7 +251,6 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode Require(source != VK_NULL_HANDLE && destination != VK_NULL_HANDLE, "texture detiling requires source and destination buffers"); std::uint32_t columnEnd = 0, rowEnd = 0; checkWindow(layout, window, columnEnd, rowEnd); - const auto target = pipeline(tileMode, elementBytes, retile, thick); const auto alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); const auto sourceDescriptorOffset = sourceOffset - sourceOffset % alignment; const auto destinationDescriptorOffset = destinationOffset - destinationOffset % alignment; @@ -221,25 +264,32 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode const auto sourceRange = (sourceBase + (retile ? linearBytes : tiledBytes) + 3) / 4 * 4; const auto destinationRange = (destinationBase + (retile ? tiledBytes : linearBytes) + 3) / 4 * 4; Require(sourceRange <= context.limits.maxStorageBufferRange && destinationRange <= context.limits.maxStorageBufferRange, "texture detiling buffer range exceeds device limits"); - const auto set = allocateSet(); - const VkDescriptorBufferInfo sourceInfo{source, sourceDescriptorOffset, sourceRange}; - const VkDescriptorBufferInfo destinationInfo{destination, destinationDescriptorOffset, destinationRange}; - std::array writes{}; - writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[0].dstSet = set; - writes[0].dstBinding = 0; - writes[0].descriptorCount = 1; - writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[0].pBufferInfo = &sourceInfo; - writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[1].dstSet = set; - writes[1].dstBinding = 1; - writes[1].descriptorCount = 1; - writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[1].pBufferInfo = &destinationInfo; - context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); - context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target); - CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, SetBindSite::Detiler); + const auto sourceAddress = bufferAddress(source); + const auto destinationAddress = sourceAddress != 0 ? bufferAddress(destination) : 0; + const bool addressed = sourceAddress != 0 && destinationAddress != 0; + if (addressed) { + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline(tileMode, elementBytes, retile, thick, false, true)); + } else { + const auto set = allocateSet(); + const VkDescriptorBufferInfo sourceInfo{source, sourceDescriptorOffset, sourceRange}; + const VkDescriptorBufferInfo destinationInfo{destination, destinationDescriptorOffset, destinationRange}; + std::array writes{}; + writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[0].dstSet = set; + writes[0].dstBinding = 0; + writes[0].descriptorCount = 1; + writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + writes[0].pBufferInfo = &sourceInfo; + writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[1].dstSet = set; + writes[1].dstBinding = 1; + writes[1].descriptorCount = 1; + writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + writes[1].pBufferInfo = &destinationInfo; + context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline(tileMode, elementBytes, retile, thick)); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, SetBindSite::Detiler); + } Push push{}; push.srcBase = static_cast(sourceBase); push.dstBase = static_cast(destinationBase); @@ -259,7 +309,12 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode push.columnBegin = window.columnBegin; push.rowBegin = window.rowBegin; push.pipeBankXor = window.pipeBankXor; - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); + if (addressed) { + const AddressedPush pushed{push, sourceAddress + sourceDescriptorOffset, destinationAddress + destinationDescriptorOffset}; + context.Function("vkCmdPushConstants")(commands, addressedPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pushed), &pushed); + } else { + context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); + } const auto groupsX = (columnEnd - window.columnBegin + 7u) / 8u; const auto groupsY = (rowEnd - window.rowBegin + 7u) / 8u; context.Function("vkCmdDispatch")(commands, groupsX, groupsY, 1); @@ -290,6 +345,31 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s constexpr std::uint64_t rowWords = 64u * 1024u; const auto rows = (words + rowWords - 1u) / rowWords; Require(words <= UINT32_MAX && rows <= context.limits.maxComputeWorkGroupCount[1], "a texel repack exceeds the device's dispatch limits"); + const std::array repackPush{static_cast(sourceOffset - sourceDescriptorOffset), static_cast(destinationOffset - destinationDescriptorOffset), static_cast(words), static_cast(std::min(words, rowWords))}; + const auto sourceAddress = bufferAddress(source); + const auto destinationAddress = sourceAddress != 0 ? bufferAddress(destination) : 0; + if (sourceAddress != 0 && destinationAddress != 0) { + if (addressedRepackPipeline == VK_NULL_HANDLE) { + VkShaderModuleCreateInfo moduleInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + moduleInfo.codeSize = sizeof(TEXTURE_REPACK_ADDRESSED_SPV); + moduleInfo.pCode = TEXTURE_REPACK_ADDRESSED_SPV; + Check(context.Function("vkCreateShaderModule")(context.device, &moduleInfo, nullptr, &addressedRepackModule), "vkCreateShaderModule repack"); + VkPipelineShaderStageCreateInfo stage{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + stage.module = addressedRepackModule; + stage.pName = "main"; + VkComputePipelineCreateInfo createInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + createInfo.stage = stage; + createInfo.layout = addressedRepackLayout; + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &createInfo, nullptr, &addressedRepackPipeline), "vkCreateComputePipelines repack"); + } + const AddressedRepackPush pushed{repackPush, sourceAddress + sourceDescriptorOffset, destinationAddress + destinationDescriptorOffset}; + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, addressedRepackPipeline); + context.Function("vkCmdPushConstants")(commands, addressedRepackLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pushed), &pushed); + context.Function("vkCmdDispatch")(commands, static_cast((std::min(words, rowWords) + 63u) / 64u), static_cast(rows), 1); + return; + } const auto set = allocateSet(); const VkDescriptorBufferInfo sourceInfo{source, sourceDescriptorOffset, sourceRange}; const VkDescriptorBufferInfo destinationInfo{destination, destinationDescriptorOffset, destinationRange}; @@ -305,8 +385,7 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, repackPipeline); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, SetBindSite::Detiler); - const std::array push{static_cast(sourceOffset - sourceDescriptorOffset), static_cast(destinationOffset - destinationDescriptorOffset), static_cast(words), static_cast(std::min(words, rowWords))}; - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); + context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(repackPush), repackPush.data()); context.Function("vkCmdDispatch")(commands, static_cast((std::min(words, rowWords) + 63u) / 64u), static_cast(rows), 1); } From b280ff455ae50806619ceb6c2b90677084e9306e Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 14:54:54 +0530 Subject: [PATCH 009/269] perf(agc): keep heap spans until the ring comes back, detile images on the heap Ring spans stay held while their chunk was not re-entered: a kept span reopens its chunk for the batch, and the ring skips chunks a batch still reads from. The [gpu-heap] line counts expired spans. Image detiles in heap mode push the tiled buffer address and index a storage view slot that the texture releases when it is destroyed, so they bind no descriptor set. [rescache] gains the fast/full revalidate time split and why storage keys fail the fast proof. Co-Authored-By: Claude Opus 5.5 --- .../Graphics/include/BindlessHeap.hpp | 5 +- .../Graphics/include/TextureDetiler.hpp | 4 +- .../Graphics/src/BindlessHeap.cpp | 70 +++++++++++- .../Graphics/src/ShaderResources.cpp | 38 ++++++- .../libSceAgcDriver/Graphics/src/Texture.cpp | 11 +- .../Graphics/src/TextureDetiler.cpp | 106 +++++++++++++----- .../tests/BindlessHeapSlots.cpp | 33 ++++++ 7 files changed, 224 insertions(+), 43 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index b6c271f8fc2f..3510edfba652 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -40,6 +40,8 @@ class BindlessHeap { std::optional TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, VkImageLayout layout); std::optional StorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view); + std::optional ViewSlot(std::uint32_t kind, const void* owner, VkImageView view); + void ReleaseViewSlots(const void* owner); std::uint32_t SlotGeneration(std::uint32_t kind, std::uint32_t slot) const; const Texture* SlotTexture(std::uint32_t kind, std::uint32_t slot) const; std::optional SamplerSlot(const std::shared_ptr& sampler); @@ -70,7 +72,7 @@ class BindlessHeap { struct Counts { std::uint64_t textures = 0, samplers = 0, full = 0, ringWraps = 0; std::uint64_t slotsFreed = 0, slotsReused = 0, sweeps = 0, chunkWaits = 0; - std::uint64_t spansWritten = 0, spansKept = 0; + std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0; }; Counts Statistics() const; @@ -111,6 +113,7 @@ class BindlessHeap { std::size_t operator()(const TextureKey& key) const { return std::hash{}(key.texture) ^ std::hash{}(reinterpret_cast(key.view)) ^ (static_cast(key.kind) << 48u) ^ (static_cast(key.layout) << 40u); } }; std::unordered_map textureSlots; + std::unordered_map>> viewSlots; std::vector nextTextureSlot; struct SlotOwner { std::shared_ptr texture; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp index 3647a8549445..12a9dd99dcc2 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp @@ -48,7 +48,7 @@ namespace AgcDriver::Graphics { // restricts the move to part of the mip (a partial upload or write-back, StorageTexture), // leaving the other elements of both buffers alone. void Dispatch(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, bool thick = false, const DetileWindow& window = {}); - void DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, const DetileWindow& window = {}); + void DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, const DetileWindow& window = {}, const void* owner = nullptr); void DispatchRepack(VkCommandBuffer commands, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, std::uint64_t bytes); static VkFormat ImageElementFormat(std::uint32_t elementBytes); // Recycles the descriptor sets of the previous batch; call before recording a new command batch. @@ -61,7 +61,7 @@ namespace AgcDriver::Graphics { private: VkPipeline multisampleReadbackPipeline(std::uint32_t elementBytes, bool depth); VkPipeline multisampleUploadPipeline(std::uint32_t elementBytes); - VkPipeline pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image = false, bool addressed = false); + VkPipeline pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image = false, bool addressed = false, bool heap = false); VkDeviceAddress bufferAddress(VkBuffer buffer) const; void release() noexcept; struct DescriptorRing { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 30247c10ecf0..dcca350d38b0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -38,6 +38,7 @@ std::uint32_t fragmentBinding(std::uint32_t kind) { std::atomic spansWrittenWindow{0}; std::atomic spansKeptWindow{0}; +std::atomic spansExpiredWindow{0}; } @@ -246,6 +247,49 @@ std::optional BindlessHeap::StorageSlot(std::uint32_t kind, std:: return slot; } +std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const void* owner, VkImageView view) { + if (!Abi::GpuHeapStorageKind(kind) || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid view slot request"); + std::vector> dropped; + std::lock_guard lock(mutex); + const TextureKey key{kind, owner, view, VK_IMAGE_LAYOUT_GENERAL}; + if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; + auto slot = takeSlotLocked(kind); + if (!slot) { + sweepLocked(dropped); + slot = takeSlotLocked(kind); + } + if (!slot) { + ++counts.full; + return std::nullopt; + } + const VkDescriptorImageInfo image{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; + const VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, VK_NULL_HANDLE, fragmentBinding(kind), *slot, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &image, nullptr, nullptr}; + writeDescriptorHeap(write); + textureSlots.emplace(key, *slot); + auto& kindOwners = owners[kind]; + if (kindOwners.size() <= *slot) kindOwners.resize(*slot + 1u); + kindOwners[*slot].key = key; + viewSlots[owner].emplace_back(kind, *slot); + ++counts.textures; + return slot; +} + +void BindlessHeap::ReleaseViewSlots(const void* owner) { + std::lock_guard lock(mutex); + const auto found = viewSlots.find(owner); + if (found == viewSlots.end()) return; + for (const auto& [kind, slot] : found->second) { + auto& entry = owners[kind][slot]; + textureSlots.erase(entry.key); + entry.key = {}; + ++entry.generation; + freeSlots[kind].push_back(slot); + ++counts.slotsFreed; + } + slotSerial.fetch_add(1, std::memory_order_release); + viewSlots.erase(found); +} + std::optional BindlessHeap::takeSlotLocked(std::uint32_t kind) { auto& free = freeSlots[kind]; if (!free.empty()) { @@ -461,8 +505,13 @@ bool BindlessHeap::Held(const SpanMark& mark) { const auto last = (mark.offset + static_cast(mark.words) * sizeof(std::uint32_t) - 1u) / RingChunkBytes; if (first != last) return false; std::lock_guard lock(mutex); - const auto& chunk = ringChunks[first]; - if (chunk.entries != mark.entry || !(chunk.open || first == ringChunk)) return false; + auto& chunk = ringChunks[first]; + if (chunk.entries != mark.entry) { + ++counts.spansExpired; + spansExpiredWindow.fetch_add(1, std::memory_order_relaxed); + return false; + } + chunk.open = true; ++counts.spansKept; spansKeptWindow.fetch_add(1, std::memory_order_relaxed); return true; @@ -477,6 +526,21 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) offset = 0; ++counts.ringWraps; } + const auto keptAhead = [&] { + for (auto chunk = offset / RingChunkBytes; chunk <= (offset + std::max(bytes, 1u) - 1u) / RingChunkBytes; ++chunk) { + if (chunk != ringChunk && ringChunks[chunk].open) return true; + } + return false; + }; + for (std::size_t skipped = 0; keptAhead(); ++skipped) { + if (skipped == ringChunks.size()) throw std::runtime_error("AGC bindless heap: one batch's shader data exceeds its ring"); + offset = (offset / RingChunkBytes + 1u) * RingChunkBytes; + if (offset + bytes > RingBytes) { + offset = 0; + ++counts.ringWraps; + } + ++counts.keptChunksSkipped; + } ringCursor = offset + bytes; for (auto chunk = offset / RingChunkBytes; chunk <= (offset + std::max(bytes, 1u) - 1u) / RingChunkBytes; ++chunk) enterChunk(ringChunks, chunk, ringChunk, "shader data"); auto* base = reinterpret_cast(ring->Bytes().data() + offset); @@ -715,7 +779,7 @@ void reportHeapStatistics() { const auto plainDraws = takeCount(heapRecords[0]); const auto heapDispatches = takeCount(heapRecords[3]); const auto plainDispatches = takeCount(heapRecords[2]); - std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept\n", static_cast(heapDraws), static_cast(plainDraws), static_cast(heapDispatches), static_cast(plainDispatches), static_cast(takeCount(heapBindWindow)), static_cast(takeCount(commandBuffersBegun)), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), static_cast(takeCount(cpuBufferCopies)), static_cast(takeCount(cpuBufferCopyBytes) >> 20u), static_cast(takeCount(spansWrittenWindow)), static_cast(takeCount(spansKeptWindow))); + std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired\n", static_cast(heapDraws), static_cast(plainDraws), static_cast(heapDispatches), static_cast(plainDispatches), static_cast(takeCount(heapBindWindow)), static_cast(takeCount(commandBuffersBegun)), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), static_cast(takeCount(cpuBufferCopies)), static_cast(takeCount(cpuBufferCopyBytes) >> 20u), static_cast(takeCount(spansWrittenWindow)), static_cast(takeCount(spansKeptWindow)), static_cast(takeCount(spansExpiredWindow))); } void forgetHeapBinding(VkCommandBuffer commands) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 56fad2d1e298..db3b7b4841b7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -3009,6 +3009,11 @@ struct RevalidateProfile { std::atomic ownSourceViews{0}; std::atomic refreshedOverlaps{0}; std::atomic proofsVerified{0}; + std::atomic fastNanoseconds{0}; + std::atomic fullNanoseconds{0}; + std::atomic storageMetadataMoved{0}; + std::atomic storageKeysUnproved{0}; + std::array, 81> storageKeysMoved{}; std::atomic lastReport{0}; }; @@ -3080,7 +3085,9 @@ void countRevalidate(bool fast, bool ok, std::chrono::steady_clock::time_point s auto& profile = Revalidations(); const auto now = std::chrono::steady_clock::now(); profile.calls.fetch_add(1, std::memory_order_relaxed); - profile.nanoseconds.fetch_add(static_cast(std::chrono::duration_cast(now - start).count()), std::memory_order_relaxed); + const auto elapsed = static_cast(std::chrono::duration_cast(now - start).count()); + profile.nanoseconds.fetch_add(elapsed, std::memory_order_relaxed); + (fast && ok ? profile.fastNanoseconds : profile.fullNanoseconds).fetch_add(elapsed, std::memory_order_relaxed); (!ok ? profile.failed : fast ? profile.fast : profile.full).fetch_add(1, std::memory_order_relaxed); const auto nowMs = std::chrono::duration_cast(now.time_since_epoch()).count(); auto last = profile.lastReport.load(); @@ -3097,6 +3104,12 @@ void countRevalidate(bool fast, bool ok, std::chrono::steady_clock::time_point s const auto reasons = byReason(profile.fastFails, FastFailNames); const auto fullReasons = byReason(profile.fullByReason, FastFailNames); const auto fallbacks = byReason(profile.ownFallbacks, OwnRefreshFallbackNames); + std::string storageKeys; + for (std::size_t i = 0; i < profile.storageKeysMoved.size(); ++i) { + const auto count = profile.storageKeysMoved[i].exchange(0, std::memory_order_relaxed); + if (count != 0) storageKeys += " " + std::string(DccKeysName(static_cast(i / 9u))) + "->" + DccKeysName(static_cast(i % 9u)) + " " + std::to_string(count); + } + AgcDriver::ProfilePrint_nid_no_patch("[rescache] revalidate time (10 s): fast %.1f ms, full or failed %.1f ms; storage keys fails: metadata moved %llu, no key proofs %llu, uploaded->proved keys:%s\n", profile.fastNanoseconds.exchange(0, std::memory_order_relaxed) / 1e6, profile.fullNanoseconds.exchange(0, std::memory_order_relaxed) / 1e6, static_cast(profile.storageMetadataMoved.exchange(0, std::memory_order_relaxed)), static_cast(profile.storageKeysUnproved.exchange(0, std::memory_order_relaxed)), storageKeys.c_str()); AgcDriver::ProfilePrint_nid_no_patch("[rescache] revalidate (10 s): %llu calls %.1f ms: fast %llu, full %llu, failed %llu; fast-fail by reason:%s; full walks: T1 refreshed %llu (%llu storage images, %llu view sources, %llu views served by their own pending source, %llu overlaps left by the refresh accepted), full by reason:%s, T1 fallback by reason:%s, proofs verified %llu; fast-fail pending image: own 0 (the query excepts the own object), foreign %llu, snapshot %llu, T1 eligible %llu; keys proven: %llu sampled, %llu storage; epoch gate: %llu registry scans skipped, %llu import loops skipped; lookup log: %llu builds and full walks kept their records past the bound\n", static_cast(profile.calls.exchange(0, std::memory_order_relaxed)), profile.nanoseconds.exchange(0, std::memory_order_relaxed) / 1e6, static_cast(profile.fast.exchange(0, std::memory_order_relaxed)), static_cast(profile.full.exchange(0, std::memory_order_relaxed)), static_cast(profile.failed.exchange(0, std::memory_order_relaxed)), reasons.c_str(), static_cast(profile.ownRefreshed.exchange(0, std::memory_order_relaxed)), static_cast(profile.ownStorageRefreshes.exchange(0, std::memory_order_relaxed)), static_cast(profile.ownViewRefreshes.exchange(0, std::memory_order_relaxed)), static_cast(profile.ownSourceViews.exchange(0, std::memory_order_relaxed)), static_cast(profile.refreshedOverlaps.exchange(0, std::memory_order_relaxed)), fullReasons.c_str(), fallbacks.c_str(), static_cast(profile.proofsVerified.exchange(0, std::memory_order_relaxed)), static_cast(profile.pendingForeign.exchange(0, std::memory_order_relaxed)), static_cast(profile.pendingSnapshot.exchange(0, std::memory_order_relaxed)), static_cast(profile.pendingT1Eligible.exchange(0, std::memory_order_relaxed)), static_cast(profile.keysProven.exchange(0, std::memory_order_relaxed)), static_cast(profile.storageKeysProven.exchange(0, std::memory_order_relaxed)), static_cast(profile.serialSkips.exchange(0, std::memory_order_relaxed)), static_cast(profile.importSkips.exchange(0, std::memory_order_relaxed)), static_cast(lookupBuildsPastBound.exchange(0, std::memory_order_relaxed))); } @@ -3284,7 +3297,10 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::span= storageKeys.size() || !StorageImageServesKeys(*storageTextures[i], storageKeys[i]))) return fail(FastFail::StorageKeys); + if (storageTextures[i] != nullptr && (i >= storageKeys.size() || !StorageImageServesKeys(*storageTextures[i], storageKeys[i]))) { + if (BuildProfiled()) Revalidations().storageMetadataMoved.fetch_add(1, std::memory_order_relaxed); + return fail(FastFail::StorageKeys); + } if (i != 0 && storageTextures[i] == storageTextures[i - 1]) continue; const auto* image = storageTextures[i].get(); if (image == nullptr) return fail(FastFail::NoRecord); @@ -3300,7 +3316,14 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::spanProvedKeys() != image->UploadedKeys()) return fail(FastFail::StorageKeys); + if (!keyProofs) { + if (BuildProfiled()) Revalidations().storageKeysUnproved.fetch_add(1, std::memory_order_relaxed); + return fail(FastFail::StorageKeys); + } + if (const auto proved = image->ProvedKeys(); proved != image->UploadedKeys()) { + if (BuildProfiled()) Revalidations().storageKeysMoved[static_cast(image->UploadedKeys()) * 9u + static_cast(proved)].fetch_add(1, std::memory_order_relaxed); + return fail(FastFail::StorageKeys); + } countKeysProven(true); } if (!unchanged) query(address, address + bytes, image, nullptr, {i, true, false}); @@ -6273,9 +6296,12 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { const auto& words = binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt && shader.heap != nullptr && !shader.heap->flattenedSrt.empty() ? shader.heap->flattenedSrt : DrawGuestWords(shader, binding); const auto userData = shader.heap != nullptr ? std::span(shader.heap->userData) : std::span{}; const bool sameInput = binding.role == ShaderRecompiler::DescriptorRole::ShaderData && current && stageState.dataInput.size() == words.size() + userData.size() && std::equal(words.begin(), words.end(), stageState.dataInput.begin()) && std::equal(userData.begin(), userData.end(), stageState.dataInput.begin() + static_cast(words.size())); - if (sameInput && !verifySlots && heap.Held(stageState.data.mark)) { - heapOffsets[dataIndex] = stageState.data.mark.offset; - continue; + if (sameInput && !verifySlots) { + if (heap.Held(stageState.data.mark)) { + heapOffsets[dataIndex] = stageState.data.mark.offset; + continue; + } + stageState.data.mark.entry = 0; } if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, words); if (binding.role != ShaderRecompiler::DescriptorRole::ShaderData) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index 61bb0cd0073e..4567d5ec500a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -2776,7 +2776,7 @@ void StorageTexture::upload(const std::vector* layers) { for (std::uint32_t level = 0; level < mips.size(); ++level) { if (!geometry.HasLayer(level, layer)) continue; const auto& mip = mips[level]; - detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, import->buffer, importOffset + geometry.GuestLayerOffset(layer) + mip.tiledOffset, elementLayerView(level, layer), mip, false, layer, {.pipeBankXor = descriptor.pipeBankXor}); + detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, import->buffer, importOffset + geometry.GuestLayerOffset(layer) + mip.tiledOffset, elementLayerView(level, layer), mip, false, layer, {.pipeBankXor = descriptor.pipeBankXor}, this); } } recordDirectUploadDone(commands); @@ -3243,10 +3243,10 @@ std::uint64_t StorageTexture::uploadWindows(const HostImport& import, std::span< detile.pipeBankXor = descriptor.pipeBankXor; const auto view = elementLayerView(window.level, window.layer); if (source.shadow) { - detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, source.buffer, source.offset + (window.tiledBegin - source.begin), view, mip, false, window.layer, detile); + detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, source.buffer, source.offset + (window.tiledBegin - source.begin), view, mip, false, window.layer, detile, this); } else { detile.tiledBase = 0; - detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, import.buffer, importOffset + geometry.GuestLayerOffset(window.layer) + mip.tiledOffset, view, mip, false, window.layer, detile); + detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, import.buffer, importOffset + geometry.GuestLayerOffset(window.layer) + mip.tiledOffset, view, mip, false, window.layer, detile, this); } } recordDirectUploadDone(commands); @@ -3604,9 +3604,9 @@ std::uint64_t StorageTexture::writeBackWindows(std::span se for (auto k = directRanges[i].first; k < directRanges[i].second; ++k) { auto piece = directPieces[k].window; piece.pipeBankXor = descriptor.pipeBankXor; - detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, directPieces[k].slab, directPieces[k].offset, elementLayerView(window.level, window.layer), mips[window.level], true, window.layer, piece); + detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, directPieces[k].slab, directPieces[k].offset, elementLayerView(window.level, window.layer), mips[window.level], true, window.layer, piece, this); } - if (directRanges[i].first == directRanges[i].second) detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, tiledScratch->Handle(), scratchPositions[i], elementLayerView(window.level, window.layer), mips[window.level], true, window.layer, retile); + if (directRanges[i].first == directRanges[i].second) detiler.DispatchImage(commands, descriptor.tileMode, elementBytes, tiledScratch->Handle(), scratchPositions[i], elementLayerView(window.level, window.layer), mips[window.level], true, window.layer, retile, this); } singlePassMoves.fetch_add(1, std::memory_order_relaxed); } else { @@ -5922,6 +5922,7 @@ StorageTexture::~StorageTexture() { } void StorageTexture::release() noexcept { + if (auto* heap = BindlessHeap::Existing(context)) heap->ReleaseViewSlots(this); for (const auto& [mip, extra] : extraViews) context.Function("vkDestroyImageView")(context.device, extra, nullptr); extraViews.clear(); for (const auto& [mip, extra] : firstLayerViews) context.Function("vkDestroyImageView")(context.device, extra, nullptr); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index 78c6d647d702..a15263e13bed 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -56,7 +57,18 @@ struct AddressedRepackPush { std::uint64_t destination; }; +struct HeapImagePush { + Push push; + std::uint64_t tiled; + std::uint32_t slot; + std::uint32_t pad; +}; + +constexpr std::uint32_t DetileHeapKind = ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 27u; + static_assert(offsetof(AddressedPush, input) == 72 && sizeof(AddressedPush) == 88); +static_assert(offsetof(HeapImagePush, tiled) == 72 && offsetof(HeapImagePush, slot) == 80 && sizeof(HeapImagePush) == 88); +static_assert(ShaderRecompiler::RuntimeAbi::GpuHeapStorageKind(DetileHeapKind)); static_assert(offsetof(AddressedRepackPush, source) == 16 && sizeof(AddressedRepackPush) == 32); std::uint32_t BlockBytesFor(TextureTileMode tileMode) { @@ -80,8 +92,8 @@ std::uint32_t BlockBytesFor(TextureTileMode tileMode) { throw std::runtime_error("AGC graphics: TextureDetiler encountered an unknown tile mode"); } -std::uint32_t PipelineKey(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, bool addressed) { - return (addressed ? 1u << 19 : 0u) | (image ? 1u << 18 : 0u) | (thick ? 1u << 17 : 0u) | (retile ? 1u << 16 : 0u) | (static_cast(tileMode) << 8) | elementBytes; +std::uint32_t PipelineKey(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, bool addressed, bool heap) { + return (heap ? 1u << 20 : 0u) | (addressed ? 1u << 19 : 0u) | (image ? 1u << 18 : 0u) | (thick ? 1u << 17 : 0u) | (retile ? 1u << 16 : 0u) | (static_cast(tileMode) << 8) | elementBytes; } } @@ -179,9 +191,9 @@ VkDeviceAddress TextureDetiler::bufferAddress(VkBuffer buffer) const { return context.Function("vkGetBufferDeviceAddressKHR")(context.device, &info); } -VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, bool addressed) { +VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, bool addressed, bool heap) { Require(std::has_single_bit(elementBytes) && elementBytes <= 16u, "unsupported element size for texture detiling"); - const auto key = PipelineKey(tileMode, elementBytes, retile, thick, image, addressed); + const auto key = PipelineKey(tileMode, elementBytes, retile, thick, image, addressed, heap); for (const auto& entry : pipelines) { if (entry.first == key) return entry.second; } @@ -228,6 +240,36 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem VkComputePipelineCreateInfo createInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; createInfo.stage = stage; createInfo.layout = addressed ? addressedPipelineLayout : image ? imagePipelineLayout : pipelineLayout; + std::array mappings{}; + VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; + VkPipelineCreateFlags2CreateInfoKHR heapFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR}; + if (heap) { + Require(image && !addressed, "only the image detiler runs on the descriptor heap"); + const auto& bindless = BindlessHeap::For(context); + mappings[0] = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mappings[0].descriptorSet = 0; + mappings[0].firstBinding = 0; + mappings[0].bindingCount = 1; + mappings[0].resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; + mappings[0].source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; + mappings[0].sourceData.pushAddressOffset = offsetof(HeapImagePush, tiled); + mappings[1] = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mappings[1].descriptorSet = 0; + mappings[1].firstBinding = 1; + mappings[1].bindingCount = 1; + mappings[1].resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; + mappings[1].source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; + mappings[1].sourceData.pushIndex.heapOffset = static_cast(bindless.ImageHeapOffset(DetileHeapKind)); + mappings[1].sourceData.pushIndex.pushOffset = offsetof(HeapImagePush, slot); + mappings[1].sourceData.pushIndex.heapIndexStride = static_cast(bindless.ImageHeapStride()); + mappings[1].sourceData.pushIndex.heapArrayStride = static_cast(bindless.ImageHeapStride()); + mappingInfo.mappingCount = static_cast(mappings.size()); + mappingInfo.pMappings = mappings.data(); + createInfo.stage.pNext = &mappingInfo; + heapFlags.flags = VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT; + createInfo.pNext = &heapFlags; + createInfo.layout = VK_NULL_HANDLE; + } VkPipeline result = VK_NULL_HANDLE; { auto pipelineCacheLock = context.LockPipelineCacheForUse(); @@ -475,14 +517,13 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask barrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, anyAccess); } -void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile, std::uint32_t slice, const DetileWindow& window) { +void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile, std::uint32_t slice, const DetileWindow& window, const void* owner) { Require(commands != VK_NULL_HANDLE, "texture detiling requires an active command buffer"); Require(window.rangeBegin < window.rangeEnd && window.tiledBase <= window.rangeBegin, "texture detiling window is empty"); Require(tiled != VK_NULL_HANDLE && view != VK_NULL_HANDLE, "texture detiling requires a tiled buffer and an image view"); Require(ImageElementFormat(elementBytes) != VK_FORMAT_UNDEFINED, "unsupported element size for texture detiling through an image"); std::uint32_t columnEnd = 0, rowEnd = 0; checkWindow(layout, window, columnEnd, rowEnd); - const auto target = pipeline(tileMode, elementBytes, retile, false, true); const auto alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); const auto descriptorOffset = tiledOffset - tiledOffset % alignment; const auto base = tiledOffset - descriptorOffset; @@ -490,25 +531,6 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til const std::uint64_t tiledBytes = window.rangeEnd == 0xffffffffu ? layout.tiledSize : std::min(layout.tiledSize, window.rangeEnd) - window.tiledBase; const auto range = (base + tiledBytes + 3) / 4 * 4; Require(range <= context.limits.maxStorageBufferRange, "texture detiling buffer range exceeds device limits"); - const auto set = allocateSet(true); - const VkDescriptorBufferInfo bufferInfo{tiled, descriptorOffset, range}; - const VkDescriptorImageInfo imageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; - std::array writes{}; - writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[0].dstSet = set; - writes[0].dstBinding = 0; - writes[0].descriptorCount = 1; - writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[0].pBufferInfo = &bufferInfo; - writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[1].dstSet = set; - writes[1].dstBinding = 1; - writes[1].descriptorCount = 1; - writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - writes[1].pImageInfo = &imageInfo; - context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); - context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target); - CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0, 1, &set, SetBindSite::Detiler); Push push{}; push.srcBase = static_cast(retile ? 0 : base); push.dstBase = static_cast(retile ? base : 0); @@ -528,7 +550,39 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til push.columnBegin = window.columnBegin; push.rowBegin = window.rowBegin; push.pipeBankXor = window.pipeBankXor; - context.Function("vkCmdPushConstants")(commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); + std::optional slot; + const auto tiledAddress = owner != nullptr && DescriptorHeapEnabled() ? bufferAddress(tiled) : 0; + if (tiledAddress != 0) slot = BindlessHeap::For(context).ViewSlot(DetileHeapKind, owner, view); + if (slot) { + auto& bindless = BindlessHeap::For(context); + bindless.BindDescriptorHeaps(commands); + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline(tileMode, elementBytes, retile, false, true, false, true)); + const HeapImagePush pushed{push, tiledAddress + descriptorOffset, *slot, 0u}; + const VkPushDataInfoEXT data{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {&pushed, sizeof(pushed)}}; + context.Function("vkCmdPushDataEXT")(commands, &data); + } else { + const auto target = pipeline(tileMode, elementBytes, retile, false, true); + const auto set = allocateSet(true); + const VkDescriptorBufferInfo bufferInfo{tiled, descriptorOffset, range}; + const VkDescriptorImageInfo imageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; + std::array writes{}; + writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[0].dstSet = set; + writes[0].dstBinding = 0; + writes[0].descriptorCount = 1; + writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + writes[0].pBufferInfo = &bufferInfo; + writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[1].dstSet = set; + writes[1].dstBinding = 1; + writes[1].descriptorCount = 1; + writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + writes[1].pImageInfo = &imageInfo; + context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0, 1, &set, SetBindSite::Detiler); + context.Function("vkCmdPushConstants")(commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); + } const auto groupsX = (columnEnd - window.columnBegin + 7u) / 8u; const auto groupsY = (rowEnd - window.rowBegin + 7u) / 8u; context.Function("vkCmdDispatch")(commands, groupsX, groupsY, 1); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index f7afa2d7544b..33e4db2c3e2d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -1,6 +1,7 @@ #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/PlaceholderImages.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "RuntimeAbi.hpp" @@ -82,6 +83,20 @@ void samplerSlots(const Context& context) { require(heap.SamplerGeneration(*slot) != generation, "a freed sampler slot moves its generation"); } +void viewSlots(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + const auto kind = Abi::FirstStorageImageBinding + 27u; + const int first = 0, second = 0; + const auto slot = heap.ViewSlot(kind, &first, view); + require(slot.has_value() && heap.ViewSlot(kind, &first, view) == slot, "a view keeps its slot"); + require(!heap.ViewSlot(kind, &second, view).has_value(), "a full kind refuses another owner's view"); + const auto generation = heap.SlotGeneration(kind, *slot); + heap.ReleaseViewSlots(&first); + require(heap.SlotGeneration(kind, *slot) != generation, "a released view slot moves its generation"); + require(heap.ViewSlot(kind, &second, view) == slot, "a released view slot is reused"); + heap.ReleaseViewSlots(&second); +} + void ringSpans(const Context& context) { BindlessHeap heap(context); BindlessHeap::SpanMark unwritten; @@ -98,6 +113,23 @@ void ringSpans(const Context& context) { require(heap.Held(first), "a span stays held while its batch keeps the chunk open"); const auto counts = heap.Statistics(); require(counts.spansWritten == 3u && counts.spansKept == 2u, "three spans written and two kept"); + BindlessHeap::SpanMark third; + static_cast(heap.Allocate(chunkWords, third)); + Recorder recorder(context); + heap.Submitted(recorder, 0u); + require(heap.Held(first), "a span stays held after its batch is submitted while the ring has not come back to its chunk"); + BindlessHeap::SpanMark fill; + const auto untilWrap = [&] { + const auto wraps = heap.Statistics().ringWraps; + BindlessHeap::DataSpan last{}; + while (heap.Statistics().ringWraps == wraps) last = heap.Allocate(chunkWords, fill); + return last.offset; + }; + require(untilWrap() == (4u << 20u), "the ring skips a chunk a later batch still reads kept spans from"); + require(heap.Held(first), "the skipped chunk's kept span is still held"); + require(heap.Statistics().keptChunksSkipped == 1u, "one kept chunk skipped"); + heap.Submitted(recorder, 0u); + require(untilWrap() == 0u && !heap.Held(first) && heap.Statistics().spansExpired == 1u, "a span the ring wrote over has expired"); } } @@ -165,6 +197,7 @@ int main(int argc, char** argv) { textureSlots(context, placeholders.View(Abi::FirstImageBinding)); samplerSlots(context); ringSpans(context); + viewSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); device->WaitIdle(); } device.reset(); From 9b5fa9f1b6bf850180cfe980fc662c62a628042a Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 15:03:56 +0530 Subject: [PATCH 010/269] fix(agc): release swept storage owners after the heap locks A storage owner the sweep drops last can be a StorageTexture whose release frees its view slots through the heap; dropping it under the heap mutex deadlocked. The sweep now hands such owners out and they are released once the locks are gone. Co-Authored-By: Claude Opus 5.5 --- .../Graphics/src/BindlessHeap.cpp | 15 ++++++++++++++- .../tests/BindlessHeapSlots.cpp | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index dcca350d38b0..de0f863cb989 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -134,6 +134,15 @@ BindlessHeap::~BindlessHeap() = default; namespace { +thread_local std::vector> sweptStorage; + +struct SweptStorageRelease { + ~SweptStorageRelease() { + auto released = std::move(sweptStorage); + sweptStorage.clear(); + } +}; + std::mutex& heapsMutex() { static std::mutex mutex; return mutex; @@ -192,6 +201,7 @@ BindlessHeap* BindlessHeap::Existing(const Context& context) { std::optional BindlessHeap::TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, VkImageLayout layout) { if (kind < Abi::FirstImageBinding || kind >= Abi::FirstStorageImageBinding || texture == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid texture slot request"); std::vector> dropped; + SweptStorageRelease swept; std::lock_guard lock(mutex); const TextureKey key{kind, texture.get(), view, layout}; if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; @@ -222,6 +232,7 @@ std::optional BindlessHeap::TextureSlot(std::uint32_t kind, const std::optional BindlessHeap::StorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view) { if (!Abi::GpuHeapStorageKind(kind) || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid storage slot request"); std::vector> dropped; + SweptStorageRelease swept; std::lock_guard lock(mutex); const TextureKey key{kind, owner.get(), view, VK_IMAGE_LAYOUT_GENERAL}; if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; @@ -250,6 +261,7 @@ std::optional BindlessHeap::StorageSlot(std::uint32_t kind, std:: std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const void* owner, VkImageView view) { if (!Abi::GpuHeapStorageKind(kind) || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid view slot request"); std::vector> dropped; + SweptStorageRelease swept; std::lock_guard lock(mutex); const TextureKey key{kind, owner, view, VK_IMAGE_LAYOUT_GENERAL}; if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; @@ -313,7 +325,7 @@ void BindlessHeap::sweepLocked(std::vector>& dropped) { if (owner.storage != nullptr) { if (owner.storage.use_count() > 1) continue; textureSlots.erase(owner.key); - owner.storage.reset(); + sweptStorage.push_back(std::move(owner.storage)); owner.key = {}; ++owner.generation; slotSerial.fetch_add(1, std::memory_order_release); @@ -376,6 +388,7 @@ void BindlessHeap::NoteSweepDue() { void BindlessHeap::SweepIfDue() { if (!sweepDue.load(std::memory_order_relaxed) || !sweepDue.exchange(false, std::memory_order_relaxed)) return; std::vector> dropped; + SweptStorageRelease swept; std::vector> droppedSamplers; std::lock_guard heapsLock(heapsMutex()); bool room = true; diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 33e4db2c3e2d..ff63d3af5efa 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -97,6 +97,24 @@ void viewSlots(const Context& context, VkImageView view) { heap.ReleaseViewSlots(&second); } +void sweptOwnerReentry(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + const auto kind = Abi::FirstStorageImageBinding + 1u; + int released = 0; + const auto owner = [&] { + return std::shared_ptr(new int(0), [&context, &released](void* pointer) { + if (auto* existing = BindlessHeap::Existing(context)) existing->ReleaseViewSlots(pointer); + ++released; + delete static_cast(pointer); + }); + }; + require(heap.StorageSlot(kind, owner(), view).has_value(), "the first storage owner takes the kind's only slot"); + require(heap.StorageSlot(kind, owner(), view).has_value() && released == 1, "a full kind sweeps an owner whose release calls back into the heap"); + BindlessHeap::NoteSweepDue(); + BindlessHeap::SweepIfDue(); + require(released == 2, "a due sweep releases an owner that calls back into the heap"); +} + void ringSpans(const Context& context) { BindlessHeap heap(context); BindlessHeap::SpanMark unwritten; @@ -198,6 +216,7 @@ int main(int argc, char** argv) { samplerSlots(context); ringSpans(context); viewSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); + sweptOwnerReentry(context, placeholders.View(Abi::FirstStorageImageBinding)); device->WaitIdle(); } device.reset(); From 0513ad78a351e172932078ab4a3568d4aef0bba1 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 15:26:51 +0530 Subject: [PATCH 011/269] perf(agc): refresh a fast-cleared storage image in place, CMASK clears on the heap A storage image whose keys moved since its upload (a fast clear over a surface uploaded uncompressed) no longer sends the revalidation to the full walk: the image's own refresh applies the clear and the fast proof runs again, as for foreign pending images. The refresh proof tests get their own ctest entry and cover the path. CMASK clears in heap mode push the CMASK and error buffer addresses and index the target's view slot instead of binding a descriptor set. The heap registry mutex outlives static destruction, so a storage image released at exit can still free its view slots. The heap draw test replays the first texture draw after another texture churned the slots. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 2 + .../Graphics/include/TextureDetiler.hpp | 3 +- .../Graphics/src/BindlessHeap.cpp | 2 +- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 2 +- .../Graphics/src/ShaderResources.cpp | 10 +- .../Graphics/src/TextureDetiler.cpp | 122 ++++++++++++------ .../prx/libSceAgcDriver/tests/Recorder.cpp | 46 +++++++ .../tests/execution/HeapDrawSample.cpp | 1 + 8 files changed, 147 insertions(+), 41 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 3375c88383ee..5ee846fd80fe 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -1677,6 +1677,8 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() add_test(NAME agc_storage_kept_unit_settle COMMAND agc_driver_recorder_tests --kept-unit-settle-only) + add_test(NAME agc_storage_refresh_proofs COMMAND agc_driver_recorder_tests --refresh-proofs-only) + set_tests_properties(agc_storage_refresh_proofs PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) set_tests_properties(agc_storage_kept_unit_settle PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) if(WIN32) set_tests_properties(agc_storage_kept_unit_settle PROPERTIES ENVIRONMENT_MODIFICATION diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp index 12a9dd99dcc2..a453fd0942df 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp @@ -53,7 +53,7 @@ namespace AgcDriver::Graphics { static VkFormat ImageElementFormat(std::uint32_t elementBytes); // Recycles the descriptor sets of the previous batch; call before recording a new command batch. void BeginBatch(); - void DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write); + void DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write, const void* owner = nullptr); std::uint32_t CmaskErrors(); void DispatchMultisampleReadback(VkCommandBuffer commands, VkFormat format, VkBuffer destination, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements); void DispatchMultisampleImage(VkCommandBuffer commands, std::uint32_t elementBytes, VkBuffer source, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements); @@ -84,6 +84,7 @@ namespace AgcDriver::Graphics { VkDescriptorSetLayout cmaskDescriptorLayout = VK_NULL_HANDLE; VkPipelineLayout cmaskPipelineLayout = VK_NULL_HANDLE; VkPipeline cmaskPipeline = VK_NULL_HANDLE; + VkPipeline cmaskHeapPipeline = VK_NULL_HANDLE; DescriptorRing cmaskDescriptorSets; std::unique_ptr cmaskErrors; VkDescriptorSetLayout imageDescriptorLayout = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index de0f863cb989..6d126f94a864 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -144,7 +144,7 @@ struct SweptStorageRelease { }; std::mutex& heapsMutex() { - static std::mutex mutex; + static auto& mutex = *new std::mutex(); return mutex; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 910137ff581a..b8c45ab13bc7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -468,7 +468,7 @@ void recordCmaskClear(const Context& context, Recorder& recorder, const HostImpo const auto commands = recorder.Commands(); if (resident != nullptr && !resident->Cached()) recorder.KeepBytes(resident.get(), static_cast(resident->BudgetBytes())); recorder.Keep(resident); - context.detiler->DispatchCmaskClear(commands, import.buffer, HostImportOffset(import, address), bytes, view, color.extent.width, color.extent.height, color.elementBytes, color.clearWords, color.dccAddress == 0); + context.detiler->DispatchCmaskClear(commands, import.buffer, HostImportOffset(import, address), bytes, view, color.extent.width, color.extent.height, color.elementBytes, color.clearWords, color.dccAddress == 0, resident.get()); recorder.NotePendingWrite(address, bytes); proveCmask(address, bytes, GuestMemory::MarkWritten(address, bytes)); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index db3b7b4841b7..ded72c751630 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -3212,7 +3212,8 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::span= storageKeys.size() || !StorageImageServesKeys(*storageTextures[i], storageKeys[i]))) { if (BuildProfiled()) Revalidations().storageMetadataMoved.fetch_add(1, std::memory_order_relaxed); @@ -3322,7 +3324,10 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::spanProvedKeys(); proved != image->UploadedKeys()) { if (BuildProfiled()) Revalidations().storageKeysMoved[static_cast(image->UploadedKeys()) * 9u + static_cast(proved)].fetch_add(1, std::memory_order_relaxed); - return fail(FastFail::StorageKeys); + if (!OwnImageRefreshEnabled()) return fail(FastFail::StorageKeys); + keysMoved = true; + overlapping.push_back({i, true, false}); + continue; } countKeysProven(true); } @@ -3331,6 +3336,7 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::spanGenerationFor(address, bytes)}); images.push_back(image); } + if (keysMoved) return fail(FastFail::StorageKeys); if (!pending.empty()) { if (!StorageTexture::ScanPending(pending)) return fail(FastFail::ClearedView); // A foreign image over a view under uncompressed keys is no failure while FindPending diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index a15263e13bed..4ca992597fb1 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -64,6 +64,42 @@ struct HeapImagePush { std::uint32_t pad; }; +struct HeapCmaskPush { + std::array push; + std::uint32_t pad; + std::uint64_t cmask; + std::uint64_t errors; + std::uint32_t slot; + std::uint32_t pad2; +}; + +static_assert(offsetof(HeapCmaskPush, cmask) == 32 && offsetof(HeapCmaskPush, errors) == 40 && offsetof(HeapCmaskPush, slot) == 48); + +VkDescriptorSetAndBindingMappingEXT PushAddressMapping(std::uint32_t binding, std::uint32_t offset) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = 0; + mapping.firstBinding = binding; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; + mapping.sourceData.pushAddressOffset = offset; + return mapping; +} + +VkDescriptorSetAndBindingMappingEXT PushIndexMapping(const BindlessHeap& heap, std::uint32_t binding, std::uint32_t kind, std::uint32_t offset) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = 0; + mapping.firstBinding = binding; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; + mapping.sourceData.pushIndex.heapOffset = static_cast(heap.ImageHeapOffset(kind)); + mapping.sourceData.pushIndex.pushOffset = offset; + mapping.sourceData.pushIndex.heapIndexStride = static_cast(heap.ImageHeapStride()); + mapping.sourceData.pushIndex.heapArrayStride = static_cast(heap.ImageHeapStride()); + return mapping; +} + constexpr std::uint32_t DetileHeapKind = ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 27u; static_assert(offsetof(AddressedPush, input) == 72 && sizeof(AddressedPush) == 88); @@ -153,6 +189,7 @@ void TextureDetiler::release() noexcept { if (readbackDescriptorLayout) context.Function("vkDestroyDescriptorSetLayout")(context.device, readbackDescriptorLayout, nullptr); for (const auto pool : cmaskDescriptorSets.pools) context.Function("vkDestroyDescriptorPool")(context.device, pool, nullptr); if (cmaskPipeline) context.Function("vkDestroyPipeline")(context.device, cmaskPipeline, nullptr); + if (cmaskHeapPipeline) context.Function("vkDestroyPipeline")(context.device, cmaskHeapPipeline, nullptr); if (cmaskPipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, cmaskPipelineLayout, nullptr); if (cmaskDescriptorLayout) context.Function("vkDestroyDescriptorSetLayout")(context.device, cmaskDescriptorLayout, nullptr); cmaskErrors.reset(); @@ -246,23 +283,8 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem if (heap) { Require(image && !addressed, "only the image detiler runs on the descriptor heap"); const auto& bindless = BindlessHeap::For(context); - mappings[0] = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mappings[0].descriptorSet = 0; - mappings[0].firstBinding = 0; - mappings[0].bindingCount = 1; - mappings[0].resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; - mappings[0].source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; - mappings[0].sourceData.pushAddressOffset = offsetof(HeapImagePush, tiled); - mappings[1] = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mappings[1].descriptorSet = 0; - mappings[1].firstBinding = 1; - mappings[1].bindingCount = 1; - mappings[1].resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; - mappings[1].source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; - mappings[1].sourceData.pushIndex.heapOffset = static_cast(bindless.ImageHeapOffset(DetileHeapKind)); - mappings[1].sourceData.pushIndex.pushOffset = offsetof(HeapImagePush, slot); - mappings[1].sourceData.pushIndex.heapIndexStride = static_cast(bindless.ImageHeapStride()); - mappings[1].sourceData.pushIndex.heapArrayStride = static_cast(bindless.ImageHeapStride()); + mappings[0] = PushAddressMapping(0, offsetof(HeapImagePush, tiled)); + mappings[1] = PushIndexMapping(bindless, 1, DetileHeapKind, offsetof(HeapImagePush, slot)); mappingInfo.mappingCount = static_cast(mappings.size()); mappingInfo.pMappings = mappings.data(); createInfo.stage.pNext = &mappingInfo; @@ -438,7 +460,7 @@ std::uint32_t TextureDetiler::CmaskErrors() { return codes; } -void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write) { +void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write, const void* owner) { Require(commands != VK_NULL_HANDLE && cmask != VK_NULL_HANDLE && view != VK_NULL_HANDLE, "a CMASK clear needs a command buffer, the CMASK buffer and the target view"); Require(elementBytes == 1 || elementBytes == 2 || elementBytes == 4 || elementBytes == 8, "a CMASK clear of this element size is not modeled"); Require(cmaskOffset % 4 == 0 && cmaskBytes % 4 == 0 && cmaskBytes != 0, "a CMASK clear needs a word-aligned CMASK"); @@ -473,30 +495,50 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask auto pipelineCacheLock = context.LockPipelineCacheForUse(); created = context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &cmaskPipeline); } + if (created == VK_SUCCESS && addressedPipelineLayout != VK_NULL_HANDLE && DescriptorHeapEnabled() && BindlessHeap::For(context).DescriptorHeapMode()) { + const auto& bindless = BindlessHeap::For(context); + const std::array mappings{PushAddressMapping(0, offsetof(HeapCmaskPush, cmask)), PushAddressMapping(1, offsetof(HeapCmaskPush, errors)), PushIndexMapping(bindless, 2, DetileHeapKind, offsetof(HeapCmaskPush, slot))}; + VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; + mappingInfo.mappingCount = static_cast(mappings.size()); + mappingInfo.pMappings = mappings.data(); + VkPipelineCreateFlags2CreateInfoKHR heapFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR}; + heapFlags.flags = VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT; + auto heapInfo = pipelineInfo; + heapInfo.pNext = &heapFlags; + heapInfo.stage.pNext = &mappingInfo; + heapInfo.layout = VK_NULL_HANDLE; + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + created = context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &heapInfo, nullptr, &cmaskHeapPipeline); + } context.Function("vkDestroyShaderModule")(context.device, cmaskModule, nullptr); Check(created, "vkCreateComputePipelines CMASK clear"); cmaskErrors = std::make_unique(context, 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); std::memset(cmaskErrors->Bytes().data(), 0, 4); } - const auto set = allocateFrom(cmaskDescriptorSets, cmaskDescriptorLayout, {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 64 * 2}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 64}}, "vkCreateDescriptorPool CMASK clear", "vkAllocateDescriptorSets CMASK clear", "vkResetDescriptorPool CMASK clear"); + const auto cmaskAddress = cmaskHeapPipeline != VK_NULL_HANDLE && owner != nullptr ? bufferAddress(cmask) : 0; + const auto errorsAddress = cmaskAddress != 0 ? bufferAddress(cmaskErrors->Handle()) : 0; + const auto slot = errorsAddress != 0 ? BindlessHeap::For(context).ViewSlot(DetileHeapKind, owner, view) : std::nullopt; + const auto set = slot ? VK_NULL_HANDLE : allocateFrom(cmaskDescriptorSets, cmaskDescriptorLayout, {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 64 * 2}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 64}}, "vkCreateDescriptorPool CMASK clear", "vkAllocateDescriptorSets CMASK clear", "vkResetDescriptorPool CMASK clear"); const auto alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); const auto descriptorOffset = cmaskOffset - cmaskOffset % alignment; const auto base = cmaskOffset - descriptorOffset; - const VkDescriptorBufferInfo cmaskInfo{cmask, descriptorOffset, base + cmaskBytes}; - const VkDescriptorBufferInfo errorInfo{cmaskErrors->Handle(), 0, 4}; - const VkDescriptorImageInfo imageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; - std::array writes{}; - for (std::uint32_t index = 0; index < writes.size(); ++index) { - writes[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[index].dstSet = set; - writes[index].dstBinding = index; - writes[index].descriptorCount = 1; - writes[index].descriptorType = index == 2 ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + if (!slot) { + const VkDescriptorBufferInfo cmaskInfo{cmask, descriptorOffset, base + cmaskBytes}; + const VkDescriptorBufferInfo errorInfo{cmaskErrors->Handle(), 0, 4}; + const VkDescriptorImageInfo imageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; + std::array writes{}; + for (std::uint32_t index = 0; index < writes.size(); ++index) { + writes[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[index].dstSet = set; + writes[index].dstBinding = index; + writes[index].descriptorCount = 1; + writes[index].descriptorType = index == 2 ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + } + writes[0].pBufferInfo = &cmaskInfo; + writes[1].pBufferInfo = &errorInfo; + writes[2].pImageInfo = &imageInfo; + context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); } - writes[0].pBufferInfo = &cmaskInfo; - writes[1].pBufferInfo = &errorInfo; - writes[2].pImageInfo = &imageInfo; - context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); const auto barrier = [&](VkPipelineStageFlags source, VkPipelineStageFlags destination, VkAccessFlags sourceAccess, VkAccessFlags destinationAccess) { VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; memory.srcAccessMask = sourceAccess; @@ -506,11 +548,19 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask constexpr VkAccessFlags anyWrite = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT; constexpr VkAccessFlags anyAccess = anyWrite | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_HOST_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT; barrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, anyWrite, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); - context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipeline); - CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipelineLayout, 0, 1, &set, SetBindSite::Detiler); const std::uint32_t mask = elementBytes >= 4 ? 0xffffffffu : (1u << (elementBytes * 8u)) - 1u; const std::array push{static_cast(base), width, height, (width + 1023u) / 1024u, clearWords[0] & mask, elementBytes == 8 ? clearWords[1] : 0u, write ? 1u : 0u}; - context.Function("vkCmdPushConstants")(commands, cmaskPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); + if (slot) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskHeapPipeline); + const HeapCmaskPush pushed{push, 0u, cmaskAddress + descriptorOffset, errorsAddress, *slot, 0u}; + const VkPushDataInfoEXT data{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {&pushed, sizeof(pushed)}}; + context.Function("vkCmdPushDataEXT")(commands, &data); + } else { + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipeline); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipelineLayout, 0, 1, &set, SetBindSite::Detiler); + context.Function("vkCmdPushConstants")(commands, cmaskPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); + } context.Function("vkCmdDispatch")(commands, (width + 7u) / 8u, (height + 7u) / 8u, 1); barrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT, anyAccess); context.Function("vkCmdFillBuffer")(commands, cmask, cmaskOffset, cmaskBytes, 0xffffffffu); diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index a86232068f00..b25b6563774e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -13,6 +13,7 @@ #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/PlaceholderImages.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" @@ -6942,6 +6943,46 @@ void refreshProofTests(const Device& device, Recorder& recorder) { recorder.Sync(); } recorder.Sync(); + { + std::memset(keys, 0xff, keyCount); + const auto meta = resource.dccAddress >> 8u; + const std::vector words{ + static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (((side - 1u) & 3u) << 30u), + ((side - 1u) >> 2u) | ((side - 1u) << 14u), + 0xfacu | (0x1bu << 20u) | (9u << 28u), + 0u, + 0u, + (1u << 19u) | (1u << 20u) | (1u << 21u) | (static_cast(meta & 0xffu) << 24u), + static_cast(meta >> 8u), + }; + ShaderRecompiler::RecompileResult program; + ShaderRecompiler::DescriptorBinding images{ShaderRecompiler::DescriptorKind::StorageImage, ShaderRecompiler::DescriptorRole::GuestImages, 0, ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding, 1, words}; + images.imageShape = ShaderRecompiler::DescriptorImageShape::Image2D; + images.imageWritten = {true}; + program.bindings.push_back(images); + const CompiledShader compute{ShaderRecompiler::ShaderStage::Compute, &program, 0}; + const PlaceholderImages placeholders(context); + auto imageContext = context; + imageContext.placeholderImages = &placeholders; + std::lock_guard gpu(GpuMutex()); + ShaderResources resources(imageContext, compute); + Require(resources.Reusable(), "a set writing a keyed storage image is not kept for reuse"); + ShaderResources::ProofReport report; + Require(resources.Revalidate(std::span(&compute, 1), &report), "a set over an unchanged keyed storage image did not revalidate"); + Require(resources.Revalidate(std::span(&compute, 1), &report) && report.path == ShaderResources::ProofPath::Fast, "a set over an unchanged keyed storage image left the fast proof"); + const auto image = StorageTexture::FindLive(address, surfaceBytes); + Require(image != nullptr && image->UploadedKeys() == DccKeys::Uncompressed, "the storage image was not uploaded under uncompressed keys"); + std::memset(keys, 0x00, keyCount); + Require(resources.Revalidate(std::span(&compute, 1), &report), "a set over a fast-cleared keyed storage image did not revalidate"); + Require(report.path == ShaderResources::ProofPath::OwnRefreshed, "a fast clear of a storage image's keys took the full walk instead of the image's own refresh"); + Require(image->UploadedKeys() != DccKeys::Uncompressed, "the own refresh did not apply the fast clear"); + Require(resources.Revalidate(std::span(&compute, 1), &report) && report.path == ShaderResources::ProofPath::Fast, "the set did not return to the fast proof after the fast clear"); + recorder.Submit(); + device.WaitQueue(); + recorder.Sync(); + ClearCachedTextures(context.device); + } } @@ -11115,6 +11156,11 @@ int main(int argc, char** argv) { unchangedCpuStampTests(device, recorder); return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--refresh-proofs-only") { + refreshProofTests(device, recorder); + std::cout << "refresh proof tests passed\n"; + return 0; + } if (argc == 2 && std::string_view(argv[1]) == "--kept-unit-settle-only") { keptUnitSettleTests(device, recorder); return 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index 4cc09dfc429d..1dda02fc3a89 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -250,6 +250,7 @@ int main() { DrawSamplesTheTexture(heap, Mode::VertexTable); DrawSamplesTheTexture(heap, Mode::MovedBuffer); DrawSamplesTheTexture(heap, Mode::MovedTexture); + DrawSamplesTheTexture(heap, Mode::Texture); if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) Require(AgcDriver::DriverDetail::HeapRefused(), "a draw found the capped heap full and the heap was not refused"); AgcDriverShutdown_nid_postfix(); if (heap && AgcDriver::Graphics::DescriptorHeapEnabled() && std::getenv("APS5_HEAP_SLOT_CAP") == nullptr) Require(AgcDriver::Graphics::EmptyResourceSets() != 0, "no heap draw bound without a per-draw resource set"); From 730b98a2d600c409bc658b2a87edcf741f93676d Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 15:42:37 +0530 Subject: [PATCH 012/269] chore(agc): time heap ring waits and slot sweeps in the [gpu-heap] line Co-Authored-By: Claude Opus 5.5 --- .../Graphics/src/BindlessHeap.cpp | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 6d126f94a864..e0c11746b5c5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -39,6 +39,18 @@ std::uint32_t fragmentBinding(std::uint32_t kind) { std::atomic spansWrittenWindow{0}; std::atomic spansKeptWindow{0}; std::atomic spansExpiredWindow{0}; +std::atomic ringWrapWindow{0}; +std::atomic chunkWaitWindow{0}, chunkWaitNanoseconds{0}, chunkWaitMaxNanoseconds{0}; +std::atomic sweepWindow{0}, sweepNanoseconds{0}, sweepMaxNanoseconds{0}; + +void noteTimed(std::atomic& count, std::atomic& total, std::atomic& maximum, std::chrono::steady_clock::time_point start) { + const auto elapsed = static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count()); + count.fetch_add(1, std::memory_order_relaxed); + total.fetch_add(elapsed, std::memory_order_relaxed); + auto seen = maximum.load(std::memory_order_relaxed); + while (elapsed > seen && !maximum.compare_exchange_weak(seen, elapsed, std::memory_order_relaxed)) { + } +} } @@ -317,6 +329,10 @@ std::optional BindlessHeap::takeSlotLocked(std::uint32_t kind) { void BindlessHeap::sweepLocked(std::vector>& dropped) { ++counts.sweeps; + struct Timed { + std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); + ~Timed() { noteTimed(sweepWindow, sweepNanoseconds, sweepMaxNanoseconds, start); } + } timed; const auto firstDropped = dropped.size(); for (std::uint32_t kind = 0; kind < owners.size(); ++kind) { auto& kindOwners = owners[kind]; @@ -538,6 +554,7 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) if (offset + bytes > RingBytes) { offset = 0; ++counts.ringWraps; + ringWrapWindow.fetch_add(1, std::memory_order_relaxed); } const auto keptAhead = [&] { for (auto chunk = offset / RingChunkBytes; chunk <= (offset + std::max(bytes, 1u) - 1u) / RingChunkBytes; ++chunk) { @@ -551,6 +568,7 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) if (offset + bytes > RingBytes) { offset = 0; ++counts.ringWraps; + ringWrapWindow.fetch_add(1, std::memory_order_relaxed); } ++counts.keptChunksSkipped; } @@ -571,7 +589,9 @@ void BindlessHeap::enterChunk(std::vector& chunks, std::size_t index, std if (chunk.serial != 0u) { ++counts.chunkWaits; if (!chunk.recorder->HasTimeline()) throw std::runtime_error(std::string("AGC bindless heap: the ") + what + " ring needs the recorder timeline to wait for a batch"); + const auto waitStart = std::chrono::steady_clock::now(); chunk.recorder->WaitSerial(chunk.serial); + noteTimed(chunkWaitWindow, chunkWaitNanoseconds, chunkWaitMaxNanoseconds, waitStart); chunk.serial = 0u; } chunk.open = true; @@ -792,7 +812,7 @@ void reportHeapStatistics() { const auto plainDraws = takeCount(heapRecords[0]); const auto heapDispatches = takeCount(heapRecords[3]); const auto plainDispatches = takeCount(heapRecords[2]); - std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired\n", static_cast(heapDraws), static_cast(plainDraws), static_cast(heapDispatches), static_cast(plainDispatches), static_cast(takeCount(heapBindWindow)), static_cast(takeCount(commandBuffersBegun)), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), static_cast(takeCount(cpuBufferCopies)), static_cast(takeCount(cpuBufferCopyBytes) >> 20u), static_cast(takeCount(spansWrittenWindow)), static_cast(takeCount(spansKeptWindow)), static_cast(takeCount(spansExpiredWindow))); + std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired, %llu ring wraps; chunk waits %llu (%.2f ms, max %.2f ms); sweeps %llu (%.2f ms, max %.2f ms)\n", static_cast(heapDraws), static_cast(plainDraws), static_cast(heapDispatches), static_cast(plainDispatches), static_cast(takeCount(heapBindWindow)), static_cast(takeCount(commandBuffersBegun)), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), static_cast(takeCount(cpuBufferCopies)), static_cast(takeCount(cpuBufferCopyBytes) >> 20u), static_cast(takeCount(spansWrittenWindow)), static_cast(takeCount(spansKeptWindow)), static_cast(takeCount(spansExpiredWindow)), static_cast(takeCount(ringWrapWindow)), static_cast(takeCount(chunkWaitWindow)), takeCount(chunkWaitNanoseconds) / 1e6, takeCount(chunkWaitMaxNanoseconds) / 1e6, static_cast(takeCount(sweepWindow)), takeCount(sweepNanoseconds) / 1e6, takeCount(sweepMaxNanoseconds) / 1e6); } void forgetHeapBinding(VkCommandBuffer commands) { From 3ae07ec6f2a8281278e3ca199e2932d3457e4542 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 15:57:33 +0530 Subject: [PATCH 013/269] perf(agc): age the heap walk memo instead of clearing it when full The memo keys mix every user data word, so a title whose user data moves each frame fills its 16384 keys within seconds; clearing it then sent every heap stage of the next frame through a full walk and materialize at once (20 ms frames every few seconds in Minecraft Dungeons II). A full memo now becomes the previous generation, and a hit there moves the entry back. Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/Driver/Draw/HeapStages.cpp | 43 ++++++++++++++----- 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index d860cb7829cd..20765b71aaf6 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -217,9 +217,35 @@ struct HeapWalkEntry { constexpr std::size_t HeapWalkWays = 4; -std::unordered_map>& heapWalkMemo() { +constexpr std::size_t HeapWalkMemoKeys = 16384; + +struct HeapWalkMemo { + std::unordered_map> current; + std::unordered_map> previous; + + std::vector* find(std::uint64_t key) { + if (const auto found = current.find(key); found != current.end()) return &found->second; + const auto old = previous.find(key); + if (old == previous.end()) return nullptr; + auto moved = std::move(old->second); + previous.erase(old); + auto& ways = slot(key); + ways = std::move(moved); + return &ways; + } + + std::vector& slot(std::uint64_t key) { + if (current.size() >= HeapWalkMemoKeys && !current.contains(key)) { + previous = std::move(current); + current.clear(); + } + return current[key]; + } +}; + +HeapWalkMemo& heapWalkMemo() { struct WalkMemoStorage {}; - auto& memo = HostThreadLocal>, WalkMemoStorage>(); + auto& memo = HostThreadLocal(); return memo; } @@ -254,10 +280,9 @@ std::shared_ptr MaterializeHeapStage(co if (memoOn) { memoKey = (invocation.VariantId() * 0x9e3779b97f4a7c15ull ^ shaderBase) + invocation.Request().layout.pushConstantOffsetBytes; for (const auto word : userData) memoKey = (memoKey ^ word) * 0x100000001b3ull; - auto& memo = heapWalkMemo(); - const auto found = memo.find(memoKey); - for (std::size_t way = 0; found != memo.end() && way < found->second.size(); ++way) { - const auto& entry = found->second[way]; + auto* found = heapWalkMemo().find(memoKey); + for (std::size_t way = 0; found != nullptr && way < found->size(); ++way) { + const auto& entry = (*found)[way]; bool equal = entry.variant == invocation.VariantId() && entry.shaderBase == shaderBase && entry.pushOffset == invocation.Request().layout.pushConstantOffsetBytes && std::equal(entry.userData.begin(), entry.userData.end(), userData.begin(), userData.end()); if (!equal) continue; std::size_t cursor = 0; @@ -281,7 +306,7 @@ std::shared_ptr MaterializeHeapStage(co else *words = *entry.words; if (stageReads != nullptr) *stageReads = {entry.ranges, entry.values, entry.userDataUse, entry.capture, true}; auto result = entry.result; - if (way != 0) std::rotate(found->second.begin(), found->second.begin() + static_cast(way), found->second.begin() + static_cast(way) + 1); + if (way != 0) std::rotate(found->begin(), found->begin() + static_cast(way), found->begin() + static_cast(way) + 1); return result; } } @@ -337,9 +362,7 @@ std::shared_ptr MaterializeHeapStage(co auto result = finish(capture); if (stageReads != nullptr && !reads.failed && result != nullptr) *stageReads = {ranges, values, capture->userDataUse, capture, true}; if (memoOn && !reads.failed && result != nullptr) { - auto& memo = heapWalkMemo(); - if (memo.size() >= 16384) memo.clear(); - auto& ways = memo[memoKey]; + auto& ways = heapWalkMemo().slot(memoKey); if (ways.size() >= HeapWalkWays) ways.pop_back(); ways.emplace(ways.begin()); auto& entry = ways.front(); From 949e8a0fcdcb41beb6edf7694579a427b443ee20 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 17:25:08 +0530 Subject: [PATCH 014/269] feat(agc): image atomics through image tables, on the descriptor heap too Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 6 ++- .../Execution/src/Driver/Draw/HeapStages.cpp | 1 - .../Graphics/include/BindlessHeap.hpp | 2 +- .../Graphics/src/BindlessHeap.cpp | 2 +- .../Graphics/src/ShaderResources.cpp | 31 +++++++++++++ .../tests/execution/ImageTableCacheBounds.cpp | 45 +++++++++++++++++++ .../src/DescriptorBindingBuilder.cpp | 5 ++- core/shader/recompiler/RuntimeAbi.hpp | 4 ++ .../src/SpirvMemory/SpirvDescriptors.cpp | 4 +- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 3 +- docs/dev/ARCHITECTURE.md | 2 +- docs/dev/debt/libSceAgcDriver.md | 2 +- 12 files changed, 98 insertions(+), 9 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 5ee846fd80fe..addfd924af44 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -2525,10 +2525,14 @@ if(BUILD_TESTING) set_tests_properties(agc_shader_table_snapshot_reuse PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") add_test(NAME agc_driver_image_table_vouched_lookups COMMAND agc_driver_image_table_cache_bounds_tests --vouched-lookups) set_tests_properties(agc_driver_image_table_vouched_lookups PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_WRITE_WATCH_IMPORTS=watch" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) + add_test(NAME agc_driver_image_table_atomics COMMAND agc_driver_image_table_cache_bounds_tests --atomic-table) + set_tests_properties(agc_driver_image_table_atomics PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) + add_test(NAME agc_driver_image_table_atomics_gpu_heap COMMAND agc_driver_image_table_cache_bounds_tests --atomic-table) + set_tests_properties(agc_driver_image_table_atomics_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) add_test(NAME agc_driver_image_table_vouch_queued_draws COMMAND agc_driver_image_table_cache_bounds_tests --queued-draws) set_tests_properties(agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) if(WIN32) - set_tests_properties(agc_shader_table_snapshot_reuse agc_driver_image_table_vouched_lookups agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + set_tests_properties(agc_shader_table_snapshot_reuse agc_driver_image_table_vouched_lookups agc_driver_image_table_vouch_queued_draws agc_driver_image_table_atomics agc_driver_image_table_atomics_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() add_test(NAME agc_shader_type_zero_image_materialization COMMAND agc_shader_memory_tests --type-zero-image-materialization) set_tests_properties(agc_shader_type_zero_image_materialization PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 20765b71aaf6..656a82685889 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -119,7 +119,6 @@ Graphics::HeapStageReason HeapStageIneligibility(ShaderRecompiler::ShaderStage s if (stage != ShaderRecompiler::ShaderStage::Fragment && !heapVertex) return Reason::FragmentOffHeap; if (plan->stage == ShaderRecompiler::IrShaderStage::Unknown || plan->stage == ShaderRecompiler::IrShaderStage::Fetch) return Reason::PlanStage; if (!ShaderRecompiler::HeapFragmentEligible(*plan)) return Reason::UnresolvedImageSource; - if (std::any_of(plan->info.images.begin(), plan->info.images.end(), [](const ShaderRecompiler::ImageResource& image) { return image.table != ShaderRecompiler::NoTable && (image.atomic || image.atomic64); })) return Reason::AtomicTableImage; return Reason::Heap; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 3510edfba652..551dab123ad8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -156,7 +156,7 @@ std::uint64_t EmptyResourceSets(); std::uint64_t DataAddressPushes(); enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, Count }; enum class HeapFallback : std::uint8_t { DrawUnmapped, DrawMixedRetry, DrawRefusedPair, DrawMixedReused, DispatchUnmapped, Count }; -enum class HeapStageReason : std::uint8_t { Heap, Disabled, PairRefused, FragmentOffHeap, StageKind, NoPlan, PlanStage, UnresolvedImageSource, AtomicTableImage, KnownIneligible, Count }; +enum class HeapStageReason : std::uint8_t { Heap, Disabled, PairRefused, FragmentOffHeap, StageKind, NoPlan, PlanStage, UnresolvedImageSource, KnownIneligible, Count }; void NoteHeapStageReason(HeapStageReason reason); void NoteHeapRecord(bool compute, bool heap); void NoteHeapFallback(HeapFallback reason); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index e0c11746b5c5..78c1d2406438 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -782,7 +782,7 @@ std::array, static_cast(SetBindSite::Cou std::array, static_cast(HeapFallback::Count)> heapFallbacks{}; std::array, 4> heapRecords{}; std::array, static_cast(HeapStageReason::Count)> heapStageReasons{}; -constexpr std::array(HeapStageReason::Count)> HeapStageReasonNames{"heap", "disabled", "pair refused", "fragment off heap", "stage kind", "no plan", "plan stage", "unresolved image source", "atomic table image", "known ineligible"}; +constexpr std::array(HeapStageReason::Count)> HeapStageReasonNames{"heap", "disabled", "pair refused", "fragment off heap", "stage kind", "no plan", "plan stage", "unresolved image source", "known ineligible"}; constexpr std::array(SetBindSite::Count)> SetBindSiteNames{"draw", "dispatch", "detiler", "color transfer", "presentation"}; constexpr std::array(HeapFallback::Count)> HeapFallbackNames{"draw unmapped", "draw mixed retry", "draw refused pair", "draw mixed reused", "dispatch unmapped"}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index ded72c751630..5d0a11841f53 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6156,6 +6156,37 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ Require(slot.has_value(), "the global sampler heap is full"); map.push_back(*slot); } + const auto atomicElement = [&](std::size_t element, bool wide) { + if (table->images == nullptr) return false; + const auto& flags = wide ? table->images->imageAtomic64 : table->images->imageAtomic; + return element < flags.size() && flags[element]; + }; + const auto anyAtomic = [&](bool wide) { + for (std::size_t element = 0; element < elements; ++element) { + if (atomicElement(element, wide)) return true; + } + return false; + }; + if (anyAtomic(false) || anyAtomic(true)) { + Require(table->tableSamplers.size() <= elements, "an image table with atomics has more table samplers than elements"); + map.resize(base + 3u * elements, fallbackSampler); + for (const bool wide : {false, true}) { + const auto kind = wide ? Abi::FirstAtomic64ImageBinding : Abi::FirstAtomicImageBinding; + const auto absent = heap.AbsentSlot(kind, context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(kind)); + for (std::size_t element = 0; element < elements; ++element) { + const auto index = element < table->elementStorage.size() ? table->elementStorage[element] : std::numeric_limits::max(); + if (!atomicElement(element, wide) || index == std::numeric_limits::max() || storageTextures[index] == nullptr) { + map.push_back(absent); + continue; + } + auto& image = *storageTextures[index]; + const auto view = wide ? image.Atomic64View(storageMips[index], storageFirstLayer[index]) : image.AtomicView(storageMips[index], storageFirstLayer[index]); + const auto slot = heap.StorageSlot(kind, storageTextures[index], view); + Require(slot.has_value(), "the global atomic image heap is full"); + map.push_back(*slot); + } + } + } if (map.size() == base) map.push_back(sampledAbsent); heapTableMaps[stageIndex] = heapSpan(heapStages[stageIndex].map, map); heapTableMapSet[stageIndex] = true; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp index 2e4f4695e8be..7bfacc618e61 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp @@ -65,6 +65,13 @@ constexpr std::size_t WideKernelOffset = 2048; constexpr std::size_t WideHeapOffset = 65536; constexpr std::array WideSlots{SrtSlots - 1u, SrtSlots - 2u, SrtSlots - 3u}; constexpr std::array WideTableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x7e200500u, 0x9310b010u, 0xf42c0502u, 0x20000000u, 0xf09c0f08u, 0x00450000u, 0xe0700000u, 0x80070000u, 0xbf810000u}; +constexpr std::uint32_t Format32UInt = 20; +constexpr std::uint32_t AtomicRecords = 16; +constexpr std::uint32_t AtomicWidth = 64; +constexpr std::size_t AtomicKernelOffset = 1024; +constexpr std::size_t AtomicSurfaceBytes = AtomicWidth * 4u; +constexpr std::uint32_t AtomicElement = 5; +constexpr std::array AtomicTableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x4a220085u, 0x7e200511u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0x7e020280u, 0x7e040281u, 0x34060082u, 0xbf8c3f70u, 0xf0442108u, 0x00050200u, 0xbf8c3f70u, 0xe0701000u, 0x80070203u, 0xbf8c3f70u, 0xbf810000u}; constexpr std::array TableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x7e200500u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0xf09c0f08u, 0x00450000u, 0xe0700000u, 0x80070000u, 0xbf810000u}; class GuestBlock { @@ -259,6 +266,39 @@ void VouchedLookups(const GuestBlock& block) { std::puts("image table vouched lookups passed"); } +std::uint32_t AtomicStart(std::uint32_t texel) { return texel * 7u + 3u; } + +void AtomicTable(const GuestBlock& block) { + std::memcpy(block.Bytes(AtomicKernelOffset), AtomicTableCode.data(), sizeof(AtomicTableCode)); + for (std::uint32_t record = 0; record < AtomicRecords; ++record) { + const auto surface = TexturesOffset + static_cast(record) * AtomicSurfaceBytes; + auto* texels = reinterpret_cast(block.Bytes(surface)); + for (std::uint32_t texel = 0; texel < AtomicWidth; ++texel) texels[texel] = AtomicStart(texel) + record * 1000u; + const auto address = block.At(surface); + const std::array words{static_cast(address >> 8u), static_cast((address >> 40u) & 0xffu) | (Format32UInt << 20u) | (((AtomicWidth - 1u) & 3u) << 30u), (AtomicWidth - 1u) >> 2u, 0xfacu | (Type2D << 28u), 0u, 0u, 0u, 0u}; + std::memcpy(block.Bytes(HeapOffset + static_cast(record) * Stride), words.data(), sizeof(words)); + } + auto* srt = reinterpret_cast(block.Bytes(SrtOffset)); + std::fill(srt, srt + SrtBytes / 4u, 0u); + const auto heap = V(block.At(HeapOffset), Stride, AtomicRecords); + const auto output = V(block.At(OutputOffset), 0u, 4096u); + std::copy(heap.begin(), heap.end(), srt); + std::copy(output.begin(), output.end(), srt + 12); + const auto heapStages = AgcDriver::Graphics::HeapComputeStages(); + for (std::uint32_t dispatch = 0; dispatch < 2; ++dispatch) { + std::memset(block.Bytes(OutputOffset), 0xee, AtomicWidth * 4u); + Dispatch(block, 0, AtomicKernelOffset); + std::array returned{}; + AgcDriver::GuestMemory::Read(block.At(OutputOffset), std::as_writable_bytes(std::span(returned))); + for (std::uint32_t texel = 0; texel < AtomicWidth; ++texel) { + const auto expected = AtomicStart(texel) + AtomicElement * 1000u + dispatch; + Require(returned[texel] == expected, "image table atomics: dispatch " + std::to_string(dispatch) + " texel " + std::to_string(texel) + " returned " + std::to_string(returned[texel]) + ", expected " + std::to_string(expected)); + } + } + if (AgcDriver::Graphics::DescriptorHeapEnabled()) Require(AgcDriver::Graphics::HeapComputeStages() > heapStages, "image table atomics: the dispatches did not take the descriptor heap"); + std::puts("image table atomics passed"); +} + struct QueuedDraw { std::atomic release{false}; @@ -397,6 +437,11 @@ int main(int argc, char** argv) { AgcDriverShutdown_nid_postfix(); return 0; } + if (argc == 2 && std::string(argv[1]) == "--atomic-table") { + AtomicTable(block); + AgcDriverShutdown_nid_postfix(); + return 0; + } if (argc == 2 && std::string(argv[1]) == "--queued-draws") { VouchUnderQueuedDraws(block); AgcDriverShutdown_nid_postfix(); diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index efe8529408b8..aa565004a30f 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -570,6 +570,8 @@ DescriptorBindingPlan DescriptorBindingBuilder::Select(const DescriptorBindingPl if (plan.addressedData) { remaining.erase(NativeBinding(IrShaderStage::Pixel, static_cast(RuntimeAbi::FirstImageBinding))); remaining.erase(NativeBinding(IrShaderStage::Pixel, static_cast(RuntimeAbi::FirstStorageImageBinding))); + remaining.erase(NativeBinding(IrShaderStage::Pixel, static_cast(RuntimeAbi::FirstAtomicImageBinding))); + remaining.erase(NativeBinding(IrShaderStage::Pixel, static_cast(RuntimeAbi::FirstAtomic64ImageBinding))); remaining.erase(NativeBinding(IrShaderStage::Pixel, DescriptorBindingKind::Samplers)); } if (!remaining.empty()) fail("specialized module bindings disagree with the prepared plan"); @@ -641,7 +643,8 @@ void DescriptorBindingBuilder::Populate(BindingAllocationResult& allocation, con physical.imageShapes.push_back(ImageShapeForResource(shape)); physical.imageDepthCompare.push_back(element.depthCompare); physical.imageWritten.push_back(ImageBindingResourceClass(element.kind) == ImageResourceClass::Storage); - physical.imageAtomic.push_back(element.atomic); + physical.imageAtomic.push_back(element.atomic || RuntimeAbi::AtomicImageKind(static_cast(element.kind))); + physical.imageAtomic64.push_back(RuntimeAbi::Atomic64ImageKind(static_cast(element.kind))); std::uint32_t samplers = 0; for (std::uint32_t sampler = 0; sampler < entry.tableSamplerMasks.size(); ++sampler) { if ((element.samplers & (1u << sampler)) != 0u) samplers |= entry.tableSamplerMasks[sampler]; diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index f82d801cb3e2..a929bba80af1 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -19,6 +19,10 @@ inline constexpr std::uint32_t FirstComparisonImageBinding = 22u; inline constexpr std::uint32_t FirstStorageImageBinding = 29u; inline constexpr std::uint32_t ImageBindingCount = 56u; inline constexpr bool GpuHeapStorageKind(std::uint32_t kind) { return kind >= FirstStorageImageBinding && kind < FirstImageBinding + ImageBindingCount; } +inline constexpr std::uint32_t FirstAtomicImageBinding = FirstStorageImageBinding + 14u; +inline constexpr std::uint32_t FirstAtomic64ImageBinding = FirstStorageImageBinding + 21u; +inline constexpr bool AtomicImageKind(std::uint32_t kind) { return kind >= FirstAtomicImageBinding && kind < FirstAtomic64ImageBinding; } +inline constexpr bool Atomic64ImageKind(std::uint32_t kind) { return kind >= FirstAtomic64ImageBinding && kind < FirstImageBinding + ImageBindingCount; } enum class Binding : std::uint32_t { Buffers = 0u, diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp index 586f71e7662f..7ccb74b08e7e 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp @@ -103,7 +103,9 @@ std::uint32_t TableStorageImagePointer(SpirvEmitterState& state, DescriptorBindi const auto found = std::find_if(state.tableImageVariables.begin(), state.tableImageVariables.end(), [&](const SpirvTableImageVariable& variable) { return variable.kind == kind; }); if (found == state.tableImageVariables.end() || !state.tableAccess.active) ExitDescriptorBindingFailure(state, kind, resource, "image storage table array was not emitted for the mode"); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, 1u, state.tableAccess.element, RuntimeAbi::GpuImageHeapSlots) : state.tableAccess.element); + const auto value = static_cast(kind); + const auto part = RuntimeAbi::AtomicImageKind(value) ? 3u : RuntimeAbi::Atomic64ImageKind(value) ? 4u : 1u; + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, part, state.tableAccess.element, RuntimeAbi::GpuImageHeapSlots) : state.tableAccess.element); DecorateTableNonUniform(state, pointer); return pointer; } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index 2d353c698826..100f3b0bdc94 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -553,7 +553,8 @@ void DefineDescriptors(SpirvEmitterState& state) { if (std::any_of(state.tableImageVariables.begin(), state.tableImageVariables.end(), [&](const SpirvTableImageVariable& variable) { return variable.kind == kind; })) continue; const auto name = "table_images_" + std::to_string(static_cast(kind)); if (state.tableHeap) { - const auto heapKind = binding.kind == DescriptorBindingKind::ImageStorageTable ? RuntimeAbi::FirstStorageImageBinding : RuntimeAbi::FirstImageBinding; + const auto value = static_cast(kind); + const auto heapKind = binding.kind != DescriptorBindingKind::ImageStorageTable ? RuntimeAbi::FirstImageBinding : RuntimeAbi::AtomicImageKind(value) ? RuntimeAbi::FirstAtomicImageBinding : RuntimeAbi::Atomic64ImageKind(value) ? RuntimeAbi::FirstAtomic64ImageBinding : RuntimeAbi::FirstStorageImageBinding; const auto type = state.module.Type(spv::OpTypeArray, ImageType(state, mode), ConstantU32(state, RuntimeAbi::GpuImageHeapSlots)); const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniformConstant, type), spv::StorageClassUniformConstant); state.module.AddName(variable, name.c_str()); diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 78d01a7e7820..d9ea45074279 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -131,7 +131,7 @@ flowchart LR - Queue 0's packet worker decodes, captures and prepares a draw and hands its recording (`Graphics::Draw` under the GPU lock) to a committer thread in [`DrawPipeline.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp), so the next packet is decoded while the previous draw is recorded. Each queued item carries the guest ranges it will write (`DrawWriteRanges`: written buffers and storage images, color targets with their DCC and CMASK, depth and stencil). A later packet that reads or writes one of those ranges, or that the pipeline can't order, drains it first; labels, submission ends, buffer fills and (with `APS5_PIPELINE_DMA=1`) DMA packets are queued as items instead. With `APS5_PIPELINE_DISPATCH=1` (off by default), a `DISPATCH_DIRECT` whose dispatch-cache entry hits with a recipe is queued as an item too, carrying the dispatch's written buffers and storage images (`DispatchWriteRanges`); the capture and the cache lookup stay on the worker and the recipe is recorded on the committer. A dispatch still drains when its lookup misses, when what it reads overlaps a write still pending, when the hit is verified against data or when its writes cannot be ranged (bindless access, GDS, fault buffer). An indirect draw resolved on the CPU (its records read by the worker) drains only when its records or its count overlap a queued write; the records it draws inline drain first, and its last drawn record is queued like a direct draw (`APS5_NO_PIPELINED_INDIRECT=1` drains at every indirect draw). An exception thrown by a commit is rethrown on the worker at its next enqueue or drain, as an inline draw error would be. On by default; `APS5_PIPELINED_DRAWS=0` records every draw inline, and `APS5_EXACT_DRAW_WRITES=0` widens the color and depth ranges to estimates. - A dispatch's resource build runs stage A (binding plan, buffers, descriptor set) without the GPU lock and stage B (image lookups) under it. Between them `VulkanDevice::presync` waits, still without the lock, for recorded work that writes a surface stage B would read on the CPU and for recorded work that writes the DCC keys of an image the dispatch binds (`ShaderResources::PresyncSurfaces`), so the locked `WaitForKeyWriters` finds nothing pending to synchronize with. A key range is waited for only when recorded work writes it, the key-store memo does not give its value (`DccKeyWritersPending`, without the mutex) and the pending stores do not give it either (`DccKeyWriterNeedsSync`, under the mutex, the same test `WaitForKeyWriters` makes before it synchronizes). Stage A's own key scan runs before that wait, and stage B compares it with the keys it reads under the lock as before. `APS5_NO_DCC_PRESYNC=1` leaves the key ranges out; `APS5_NO_PRESYNC=1` disables the whole pre-sync. - `APS5_DRAW_PIPELINE=1` (off by default, meant with `APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1`) takes more of a draw off the worker. A `DrawFinisher` thread runs the second half of a direct pipelined draw (stage materialization, the draw cache insert and the hand-off to the committer) while the worker reads the next packets; the worker drains it before the next draw's cache lookup, before packets other than register writes and draws, and before guest reads, and finishes in place a draw whose stages may write memory (`ProgramWritesMemory`) or write through the BDA page table. The committer skips the fragment-output validation and storage-image layer scans whose inputs match its last commit (`CommitTrims`), and a resource or storage image proved current keeps its proof for the rest of the collect epoch until `GuestMemory::BreakProofs` (a CPU write, a write-back, a recorded write) moves `ProofSerial`. Color metadata passes go through the pipeline with their write ranges (`PipelinedColorMetadataPassWrites`) instead of draining it. A data-only hit whose shape entry belongs to an older draw replaces that entry in place at the second sight of the same read user words. On Linux the main image's pages get a page table entry, and capture pages are pooled across threads. `APS5_VERIFY_DRAW_PIPELINE=1` runs a full check next to 1 in 64 reused proofs and prints `[epoch-proofs]` counts. -- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 4096 image slots per binding kind and 256 sampler slots, per-draw shader data and flattened SRT in a ring the shaders reach by address) instead of per-draw descriptor sets. Without the extension every stage takes the per-draw path. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; a stage stays GPU-mode only if its compiled module maps onto the heap and every stage of its draw is GPU-mode too; otherwise it is rebuilt on the per-draw path. A draw whose stages come out mixed is rebuilt once with what the first pass learned, and a stage pair that is still mixed takes the per-draw path from then on. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the heap ring and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap is recompiled on the per-dispatch path. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the heap ring per draw with its address in two more pushed dwords. Tables with image atomics stay off the heap. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers by device address (`addressedBuffers`: four shader data words per buffer, 64-bit address and byte size, after the slot words) instead of storage buffer descriptors; a draw whose buffers are snapshotted gets its own copy of the words with the snapshot addresses. +- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 4096 image slots per binding kind and 256 sampler slots, per-draw shader data and flattened SRT in a ring the shaders reach by address) instead of per-draw descriptor sets. Without the extension every stage takes the per-draw path. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; a stage stays GPU-mode only if its compiled module maps onto the heap and every stage of its draw is GPU-mode too; otherwise it is rebuilt on the per-draw path. A draw whose stages come out mixed is rebuilt once with what the first pass learned, and a stage pair that is still mixed takes the per-draw path from then on. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the heap ring and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap is recompiled on the per-dispatch path. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the heap ring per draw with its address in two more pushed dwords. Tables with image atomics index the heap too. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers by device address (`addressedBuffers`: four shader data words per buffer, 64-bit address and byte size, after the slot words) instead of storage buffer descriptors; a draw whose buffers are snapshotted gets its own copy of the words with the snapshot addresses. - The shader registry maps a code address to every header registered for that code, in registration order. Static, graphics and rectangle ABI resolution pick the header at the bound address (or one equal to it, `SameHeader`, which also takes a hull header fused by `sceAgcFuseShaderHalves` (type 3) as the registered back half (type 7) it copies, the fused registers aside; graphics ABI resolution then uses the fused header's shader registers); draws and dispatches pick the program by the stage's binary type (`RegisteredProgram`), and a front entry matching both type 2 and type 4 throws. Within a type the last registration wins; re-registering an identical earlier header makes its snapshot current again without preparing it again, and changed code drops the older headers. - The snapshot is published as pending. `SourceHandleFor`, `InvocationFor` and `ShaderPreparationTransaction::Edit` / `Read` wait for the pending job before reading `PreparedShaders`, and rethrow its failure. `APS5_SYNC_SHADER_PREPARE=1` prepares on the registering thread instead. - `APS5_LAZY_SHADER_PREPARE=1` retains registration validation and decoding but discards the temporary plan without queueing preparation. The snapshot is deferred, not pending; draws and dispatches prepare and cache it on first use. A compute or pixel stage's explicit ABI resolution (`ResolveShaderAbi`) plans the stage with the ABI's state, records the ABI and leaves its preparation to the shader's first use, which prepares it with that state (`PreparedShaders::deferredAbis`), so a shader that never draws or dispatches stays unprepared; a graphics-stage ABI is still prepared when it is resolved. This opt-in mode takes precedence over synchronous registration preparation and trades background CPU/memory use for possible first-use stalls; disk caches and shader output are unchanged. diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 7a301169a4d7..fd903c295b76 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -264,4 +264,4 @@ ### Opt-in draw paths - [Draw finisher](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp) (`APS5_DRAW_PIPELINE`) - opt-in. The Linux main-image page table it adds matches what Windows already does by default. -- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap`. A stage whose module keeps a set 0 binding (storage images of registration modules, GDS, the fault buffer), mesh and tessellation pipelines, image tables with atomics and compute stages without images take the per-draw path, and so does every other stage of their draw. +- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap`. A stage whose module keeps a set 0 binding (storage images of registration modules, GDS, the fault buffer), mesh and tessellation pipelines and compute stages without images take the per-draw path, and so does every other stage of their draw. From 711e5c57b84d7c34815aa9f2e9952d2997e49e28 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 17:36:17 +0530 Subject: [PATCH 015/269] chore(agc): drop the heap ring, sweep and revalidate-time hunt timers Co-Authored-By: Claude Opus 5.5 --- .../Graphics/src/BindlessHeap.cpp | 22 +-------------- .../Graphics/src/ShaderResources.cpp | 28 +++---------------- 2 files changed, 5 insertions(+), 45 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 78c1d2406438..2c4c080b5b20 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -39,18 +39,6 @@ std::uint32_t fragmentBinding(std::uint32_t kind) { std::atomic spansWrittenWindow{0}; std::atomic spansKeptWindow{0}; std::atomic spansExpiredWindow{0}; -std::atomic ringWrapWindow{0}; -std::atomic chunkWaitWindow{0}, chunkWaitNanoseconds{0}, chunkWaitMaxNanoseconds{0}; -std::atomic sweepWindow{0}, sweepNanoseconds{0}, sweepMaxNanoseconds{0}; - -void noteTimed(std::atomic& count, std::atomic& total, std::atomic& maximum, std::chrono::steady_clock::time_point start) { - const auto elapsed = static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count()); - count.fetch_add(1, std::memory_order_relaxed); - total.fetch_add(elapsed, std::memory_order_relaxed); - auto seen = maximum.load(std::memory_order_relaxed); - while (elapsed > seen && !maximum.compare_exchange_weak(seen, elapsed, std::memory_order_relaxed)) { - } -} } @@ -329,10 +317,6 @@ std::optional BindlessHeap::takeSlotLocked(std::uint32_t kind) { void BindlessHeap::sweepLocked(std::vector>& dropped) { ++counts.sweeps; - struct Timed { - std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); - ~Timed() { noteTimed(sweepWindow, sweepNanoseconds, sweepMaxNanoseconds, start); } - } timed; const auto firstDropped = dropped.size(); for (std::uint32_t kind = 0; kind < owners.size(); ++kind) { auto& kindOwners = owners[kind]; @@ -554,7 +538,6 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) if (offset + bytes > RingBytes) { offset = 0; ++counts.ringWraps; - ringWrapWindow.fetch_add(1, std::memory_order_relaxed); } const auto keptAhead = [&] { for (auto chunk = offset / RingChunkBytes; chunk <= (offset + std::max(bytes, 1u) - 1u) / RingChunkBytes; ++chunk) { @@ -568,7 +551,6 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) if (offset + bytes > RingBytes) { offset = 0; ++counts.ringWraps; - ringWrapWindow.fetch_add(1, std::memory_order_relaxed); } ++counts.keptChunksSkipped; } @@ -589,9 +571,7 @@ void BindlessHeap::enterChunk(std::vector& chunks, std::size_t index, std if (chunk.serial != 0u) { ++counts.chunkWaits; if (!chunk.recorder->HasTimeline()) throw std::runtime_error(std::string("AGC bindless heap: the ") + what + " ring needs the recorder timeline to wait for a batch"); - const auto waitStart = std::chrono::steady_clock::now(); chunk.recorder->WaitSerial(chunk.serial); - noteTimed(chunkWaitWindow, chunkWaitNanoseconds, chunkWaitMaxNanoseconds, waitStart); chunk.serial = 0u; } chunk.open = true; @@ -812,7 +792,7 @@ void reportHeapStatistics() { const auto plainDraws = takeCount(heapRecords[0]); const auto heapDispatches = takeCount(heapRecords[3]); const auto plainDispatches = takeCount(heapRecords[2]); - std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired, %llu ring wraps; chunk waits %llu (%.2f ms, max %.2f ms); sweeps %llu (%.2f ms, max %.2f ms)\n", static_cast(heapDraws), static_cast(plainDraws), static_cast(heapDispatches), static_cast(plainDispatches), static_cast(takeCount(heapBindWindow)), static_cast(takeCount(commandBuffersBegun)), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), static_cast(takeCount(cpuBufferCopies)), static_cast(takeCount(cpuBufferCopyBytes) >> 20u), static_cast(takeCount(spansWrittenWindow)), static_cast(takeCount(spansKeptWindow)), static_cast(takeCount(spansExpiredWindow)), static_cast(takeCount(ringWrapWindow)), static_cast(takeCount(chunkWaitWindow)), takeCount(chunkWaitNanoseconds) / 1e6, takeCount(chunkWaitMaxNanoseconds) / 1e6, static_cast(takeCount(sweepWindow)), takeCount(sweepNanoseconds) / 1e6, takeCount(sweepMaxNanoseconds) / 1e6); + std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired\n", static_cast(heapDraws), static_cast(plainDraws), static_cast(heapDispatches), static_cast(plainDispatches), static_cast(takeCount(heapBindWindow)), static_cast(takeCount(commandBuffersBegun)), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), static_cast(takeCount(cpuBufferCopies)), static_cast(takeCount(cpuBufferCopyBytes) >> 20u), static_cast(takeCount(spansWrittenWindow)), static_cast(takeCount(spansKeptWindow)), static_cast(takeCount(spansExpiredWindow))); } void forgetHeapBinding(VkCommandBuffer commands) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 5d0a11841f53..45b0c279c248 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -3009,11 +3009,6 @@ struct RevalidateProfile { std::atomic ownSourceViews{0}; std::atomic refreshedOverlaps{0}; std::atomic proofsVerified{0}; - std::atomic fastNanoseconds{0}; - std::atomic fullNanoseconds{0}; - std::atomic storageMetadataMoved{0}; - std::atomic storageKeysUnproved{0}; - std::array, 81> storageKeysMoved{}; std::atomic lastReport{0}; }; @@ -3085,9 +3080,7 @@ void countRevalidate(bool fast, bool ok, std::chrono::steady_clock::time_point s auto& profile = Revalidations(); const auto now = std::chrono::steady_clock::now(); profile.calls.fetch_add(1, std::memory_order_relaxed); - const auto elapsed = static_cast(std::chrono::duration_cast(now - start).count()); - profile.nanoseconds.fetch_add(elapsed, std::memory_order_relaxed); - (fast && ok ? profile.fastNanoseconds : profile.fullNanoseconds).fetch_add(elapsed, std::memory_order_relaxed); + profile.nanoseconds.fetch_add(static_cast(std::chrono::duration_cast(now - start).count()), std::memory_order_relaxed); (!ok ? profile.failed : fast ? profile.fast : profile.full).fetch_add(1, std::memory_order_relaxed); const auto nowMs = std::chrono::duration_cast(now.time_since_epoch()).count(); auto last = profile.lastReport.load(); @@ -3104,12 +3097,6 @@ void countRevalidate(bool fast, bool ok, std::chrono::steady_clock::time_point s const auto reasons = byReason(profile.fastFails, FastFailNames); const auto fullReasons = byReason(profile.fullByReason, FastFailNames); const auto fallbacks = byReason(profile.ownFallbacks, OwnRefreshFallbackNames); - std::string storageKeys; - for (std::size_t i = 0; i < profile.storageKeysMoved.size(); ++i) { - const auto count = profile.storageKeysMoved[i].exchange(0, std::memory_order_relaxed); - if (count != 0) storageKeys += " " + std::string(DccKeysName(static_cast(i / 9u))) + "->" + DccKeysName(static_cast(i % 9u)) + " " + std::to_string(count); - } - AgcDriver::ProfilePrint_nid_no_patch("[rescache] revalidate time (10 s): fast %.1f ms, full or failed %.1f ms; storage keys fails: metadata moved %llu, no key proofs %llu, uploaded->proved keys:%s\n", profile.fastNanoseconds.exchange(0, std::memory_order_relaxed) / 1e6, profile.fullNanoseconds.exchange(0, std::memory_order_relaxed) / 1e6, static_cast(profile.storageMetadataMoved.exchange(0, std::memory_order_relaxed)), static_cast(profile.storageKeysUnproved.exchange(0, std::memory_order_relaxed)), storageKeys.c_str()); AgcDriver::ProfilePrint_nid_no_patch("[rescache] revalidate (10 s): %llu calls %.1f ms: fast %llu, full %llu, failed %llu; fast-fail by reason:%s; full walks: T1 refreshed %llu (%llu storage images, %llu view sources, %llu views served by their own pending source, %llu overlaps left by the refresh accepted), full by reason:%s, T1 fallback by reason:%s, proofs verified %llu; fast-fail pending image: own 0 (the query excepts the own object), foreign %llu, snapshot %llu, T1 eligible %llu; keys proven: %llu sampled, %llu storage; epoch gate: %llu registry scans skipped, %llu import loops skipped; lookup log: %llu builds and full walks kept their records past the bound\n", static_cast(profile.calls.exchange(0, std::memory_order_relaxed)), profile.nanoseconds.exchange(0, std::memory_order_relaxed) / 1e6, static_cast(profile.fast.exchange(0, std::memory_order_relaxed)), static_cast(profile.full.exchange(0, std::memory_order_relaxed)), static_cast(profile.failed.exchange(0, std::memory_order_relaxed)), reasons.c_str(), static_cast(profile.ownRefreshed.exchange(0, std::memory_order_relaxed)), static_cast(profile.ownStorageRefreshes.exchange(0, std::memory_order_relaxed)), static_cast(profile.ownViewRefreshes.exchange(0, std::memory_order_relaxed)), static_cast(profile.ownSourceViews.exchange(0, std::memory_order_relaxed)), static_cast(profile.refreshedOverlaps.exchange(0, std::memory_order_relaxed)), fullReasons.c_str(), fallbacks.c_str(), static_cast(profile.proofsVerified.exchange(0, std::memory_order_relaxed)), static_cast(profile.pendingForeign.exchange(0, std::memory_order_relaxed)), static_cast(profile.pendingSnapshot.exchange(0, std::memory_order_relaxed)), static_cast(profile.pendingT1Eligible.exchange(0, std::memory_order_relaxed)), static_cast(profile.keysProven.exchange(0, std::memory_order_relaxed)), static_cast(profile.storageKeysProven.exchange(0, std::memory_order_relaxed)), static_cast(profile.serialSkips.exchange(0, std::memory_order_relaxed)), static_cast(profile.importSkips.exchange(0, std::memory_order_relaxed)), static_cast(lookupBuildsPastBound.exchange(0, std::memory_order_relaxed))); } @@ -3299,10 +3286,7 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::span= storageKeys.size() || !StorageImageServesKeys(*storageTextures[i], storageKeys[i]))) { - if (BuildProfiled()) Revalidations().storageMetadataMoved.fetch_add(1, std::memory_order_relaxed); - return fail(FastFail::StorageKeys); - } + if (storageTextures[i] != nullptr && (i >= storageKeys.size() || !StorageImageServesKeys(*storageTextures[i], storageKeys[i]))) return fail(FastFail::StorageKeys); if (i != 0 && storageTextures[i] == storageTextures[i - 1]) continue; const auto* image = storageTextures[i].get(); if (image == nullptr) return fail(FastFail::NoRecord); @@ -3318,12 +3302,8 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::spanProvedKeys(); proved != image->UploadedKeys()) { - if (BuildProfiled()) Revalidations().storageKeysMoved[static_cast(image->UploadedKeys()) * 9u + static_cast(proved)].fetch_add(1, std::memory_order_relaxed); + if (!keyProofs) return fail(FastFail::StorageKeys); + if (image->ProvedKeys() != image->UploadedKeys()) { if (!OwnImageRefreshEnabled()) return fail(FastFail::StorageKeys); keysMoved = true; overlapping.push_back({i, true, false}); From e4a517c25f6eae8ad408850e5c8a14e90c6edd78 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 17:36:17 +0530 Subject: [PATCH 016/269] perf(agc): presentation pass draws from the descriptor heap Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 5 +- .../Execution/include/PresentationPass.hpp | 5 +- .../Execution/src/PresentationPass.cpp | 67 +++++++++++++++++-- .../Graphics/src/BindlessHeap.cpp | 4 +- .../tests/PresentationPass.cpp | 14 +++- 5 files changed, 84 insertions(+), 11 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index addfd924af44..1ed14c73d0c2 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -1954,6 +1954,7 @@ target_include_directories(agc_driver_presentation_pass_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/core/shader/recompiler ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} + ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR} ) target_link_libraries(agc_driver_presentation_pass_tests PRIVATE @@ -1968,8 +1969,10 @@ if(BUILD_TESTING) set_target_properties(agc_driver_presentation_pass_tests PROPERTIES EXCLUDE_FROM_ALL OFF) add_test(NAME agc_driver_presentation_pass COMMAND agc_driver_presentation_pass_tests) set_tests_properties(agc_driver_presentation_pass PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + add_test(NAME agc_driver_presentation_pass_gpu_heap COMMAND agc_driver_presentation_pass_tests) + set_tests_properties(agc_driver_presentation_pass_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") if(WIN32) - set_tests_properties(agc_driver_presentation_pass PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(agc_driver_presentation_pass agc_driver_presentation_pass_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endif() diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/PresentationPass.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/PresentationPass.hpp index 337bfb080504..b0e56bbadb34 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/PresentationPass.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/PresentationPass.hpp @@ -34,6 +34,7 @@ class PresentationPass { struct Target { VkRenderPass renderPass = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + VkPipeline heapPipeline = VK_NULL_HANDLE; }; struct Slot { VkDescriptorSet set = VK_NULL_HANDLE; @@ -55,11 +56,13 @@ class PresentationPass { VkFramebuffer createFramebuffer(VkRenderPass renderPass, VkImageView view, VkExtent2D extent) const; void ensureDumpTarget(Slot& slot, VkExtent2D extent); void releaseDumpTarget(Slot& slot) noexcept; - void draw(VkCommandBuffer commands, const Slot& slot, const Target& target, VkFramebuffer framebuffer, VkExtent2D extent, const std::int32_t (¶meters)[9]) const; + void draw(VkCommandBuffer commands, Slot& slot, const Target& target, VkFramebuffer framebuffer, VkExtent2D extent, const std::int32_t (¶meters)[9]) const; void release() noexcept; Graphics::Context context; + VkSamplerCreateInfo samplerInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; VkSampler sampler = VK_NULL_HANDLE; + bool heap = false; VkDescriptorSetLayout descriptorLayout = VK_NULL_HANDLE; VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; VkDescriptorPool descriptorPool = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp index c63c627ab08b..c3591be558da 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp @@ -8,8 +8,11 @@ #include "prx/libSceAgcDriver/Graphics/shaders/PresentationPassVert_spv.h" #include #include +#include #include +#include #include +#include namespace AgcDriver { namespace { @@ -19,13 +22,24 @@ constexpr std::uint32_t ModeRedLow = 2; constexpr std::uint32_t ModeKeepTenBit = 4; constexpr std::uint32_t ModeSubsample = 8; constexpr std::uint32_t ModePq = 16; +constexpr std::uint32_t PresentHeapKind = ShaderRecompiler::RuntimeAbi::FirstImageBinding + 9u; + +struct HeapPush { + std::int32_t parameters[9]; + std::uint32_t pad; + std::uint64_t pqNits; + std::uint32_t slot; + std::uint32_t pad2; +}; + +static_assert(offsetof(HeapPush, pqNits) == 40 && offsetof(HeapPush, slot) == 48); } PresentationPass::PresentationPass(const Graphics::Context& context, std::size_t slotCount) : context(context), slots(slotCount) { Graphics::Require(slotCount != 0, "presentation pass needs at least one slot"); try { - VkSamplerCreateInfo samplerInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; + heap = Graphics::DescriptorHeapEnabled() && Graphics::BindlessHeap::For(context).DescriptorHeapMode(); samplerInfo.magFilter = VK_FILTER_NEAREST; samplerInfo.minFilter = VK_FILTER_NEAREST; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; @@ -59,7 +73,7 @@ PresentationPass::PresentationPass(const Graphics::Context& context, std::size_t Graphics::Check(context.Function("vkAllocateDescriptorSets")(context.device, &allocation, &slot.set), "vkAllocateDescriptorSets presentation pass"); } const auto& luminance = PqEotfNits(); - pqNits = std::make_unique(context, sizeof(luminance), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + pqNits = std::make_unique(context, sizeof(luminance), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (heap ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u)); std::memcpy(pqNits->Bytes().data(), luminance.data(), sizeof(luminance)); const VkDescriptorBufferInfo tableInfo{pqNits->Handle(), 0, sizeof(luminance)}; std::vector tableWrites(slots.size(), VkWriteDescriptorSet{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}); @@ -90,6 +104,7 @@ void PresentationPass::release() noexcept { } for (const auto& [key, entry] : targets) { if (entry.pipeline) context.Function("vkDestroyPipeline")(context.device, entry.pipeline, nullptr); + if (entry.heapPipeline) context.Function("vkDestroyPipeline")(context.device, entry.heapPipeline, nullptr); if (entry.renderPass) context.Function("vkDestroyRenderPass")(context.device, entry.renderPass, nullptr); } targets.clear(); @@ -124,6 +139,9 @@ void PresentationPass::Release(std::size_t index) noexcept { if (view) context.Function("vkDestroyImageView")(context.device, view, nullptr); } slot.transient.clear(); + if (slot.source && heap) { + if (auto* bindless = Graphics::BindlessHeap::Existing(context)) bindless->ReleaseViewSlots(&slot); + } if (slot.source) context.Function("vkDestroyImageView")(context.device, slot.source, nullptr); slot.source = VK_NULL_HANDLE; } @@ -234,7 +252,35 @@ const PresentationPass::Target& PresentationPass::target(VkFormat format, VkImag pipelineInfo.layout = pipelineLayout; pipelineInfo.renderPass = created.renderPass; Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.pipeline), "vkCreateGraphicsPipelines presentation pass"); + if (heap) { + const auto& bindless = Graphics::BindlessHeap::For(context); + std::array mappings{{{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}, {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}}}; + mappings[0].firstBinding = 0; + mappings[0].bindingCount = 1; + mappings[0].resourceMask = VK_SPIRV_RESOURCE_TYPE_COMBINED_SAMPLED_IMAGE_BIT_EXT; + mappings[0].source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; + mappings[0].sourceData.pushIndex.heapOffset = static_cast(bindless.ImageHeapOffset(PresentHeapKind)); + mappings[0].sourceData.pushIndex.pushOffset = offsetof(HeapPush, slot); + mappings[0].sourceData.pushIndex.heapIndexStride = static_cast(bindless.ImageHeapStride()); + mappings[0].sourceData.pushIndex.heapArrayStride = static_cast(bindless.ImageHeapStride()); + mappings[0].sourceData.pushIndex.pEmbeddedSampler = &samplerInfo; + mappings[1].firstBinding = 1; + mappings[1].bindingCount = 1; + mappings[1].resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT; + mappings[1].source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; + mappings[1].sourceData.pushAddressOffset = offsetof(HeapPush, pqNits); + VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; + mappingInfo.mappingCount = static_cast(mappings.size()); + mappingInfo.pMappings = mappings.data(); + stages[1].pNext = &mappingInfo; + VkPipelineCreateFlags2CreateInfoKHR heapFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR}; + heapFlags.flags = VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT; + pipelineInfo.pNext = &heapFlags; + pipelineInfo.layout = VK_NULL_HANDLE; + Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.heapPipeline), "vkCreateGraphicsPipelines presentation pass heap"); + } } catch (...) { + if (created.pipeline) context.Function("vkDestroyPipeline")(context.device, created.pipeline, nullptr); if (created.renderPass) context.Function("vkDestroyRenderPass")(context.device, created.renderPass, nullptr); throw; } @@ -263,19 +309,28 @@ void PresentationPass::Bind(std::size_t index, VkImage image, std::uint32_t widt context.Function("vkUpdateDescriptorSets")(context.device, 1, &write, 0, nullptr); } -void PresentationPass::draw(VkCommandBuffer commands, const Slot& slot, const Target& entry, VkFramebuffer framebuffer, VkExtent2D extent, const std::int32_t (¶meters)[9]) const { +void PresentationPass::draw(VkCommandBuffer commands, Slot& slot, const Target& entry, VkFramebuffer framebuffer, VkExtent2D extent, const std::int32_t (¶meters)[9]) const { VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; begin.renderPass = entry.renderPass; begin.framebuffer = framebuffer; begin.renderArea = {{0, 0}, extent}; context.Function("vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE); - context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, entry.pipeline); + const auto heapSlot = entry.heapPipeline != VK_NULL_HANDLE ? Graphics::BindlessHeap::For(context).ViewSlot(PresentHeapKind, &slot, slot.source) : std::nullopt; + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, heapSlot ? entry.heapPipeline : entry.pipeline); const VkViewport viewport{0.0f, 0.0f, static_cast(extent.width), static_cast(extent.height), 0.0f, 1.0f}; const VkRect2D scissor{{0, 0}, extent}; context.Function("vkCmdSetViewport")(commands, 0, 1, &viewport); context.Function("vkCmdSetScissor")(commands, 0, 1, &scissor); - Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &slot.set, Graphics::SetBindSite::Presentation); - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), parameters); + if (heapSlot) { + Graphics::BindlessHeap::For(context).BindDescriptorHeaps(commands); + HeapPush pushed{{}, 0u, pqNits->DeviceAddress(), *heapSlot, 0u}; + std::copy(std::begin(parameters), std::end(parameters), pushed.parameters); + const VkPushDataInfoEXT data{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {&pushed, sizeof(pushed)}}; + context.Function("vkCmdPushDataEXT")(commands, &data); + } else { + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &slot.set, Graphics::SetBindSite::Presentation); + context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), parameters); + } context.Function("vkCmdDraw")(commands, 3, 1, 0, 0); context.Function("vkCmdEndRenderPass")(commands); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 2c4c080b5b20..c9915914736e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -259,7 +259,7 @@ std::optional BindlessHeap::StorageSlot(std::uint32_t kind, std:: } std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const void* owner, VkImageView view) { - if (!Abi::GpuHeapStorageKind(kind) || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid view slot request"); + if (kind < Abi::FirstImageBinding || kind >= static_cast(Abi::Binding::Samplers) || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid view slot request"); std::vector> dropped; SweptStorageRelease swept; std::lock_guard lock(mutex); @@ -275,7 +275,7 @@ std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const vo return std::nullopt; } const VkDescriptorImageInfo image{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; - const VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, VK_NULL_HANDLE, fragmentBinding(kind), *slot, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &image, nullptr, nullptr}; + const VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, VK_NULL_HANDLE, fragmentBinding(kind), *slot, 1, Abi::GpuHeapStorageKind(kind) ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, &image, nullptr, nullptr}; writeDescriptorHeap(write); textureSlots.emplace(key, *slot); auto& kindOwners = owners[kind]; diff --git a/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp index 11915c857509..adb1714f16d8 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp @@ -1,3 +1,5 @@ +#include "execution/VulkanTestDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/AspectFit.hpp" #include "prx/libSceAgcDriver/Execution/include/DisplayBuffer.hpp" #include "prx/libSceAgcDriver/Execution/include/DisplayFormat.hpp" @@ -26,7 +28,6 @@ using AgcDriver::DisplayBuffer; using AgcDriver::PresentationPass; using AgcDriver::PresentationScaler; -constexpr int VulkanTestSkipped = 77; constexpr std::uint64_t Bgra8 = 0x8000000000000000ull; constexpr std::uint64_t Rgba8 = 0x8000000022000000ull; constexpr std::uint64_t TenBit = 0x0100000000000000ull; @@ -582,6 +583,17 @@ int main() { return VulkanTestSkipped; } residentPresentTests(device->GetContext()); + if (GpuHeapEnabled()) { + const auto heapDevice = OpenVulkanTestDevice(); + if (!heapDevice) return VulkanTestSkipped; + if (!DescriptorHeapEnabled()) { + std::printf("skipped, the device has no descriptor heap\n"); + return VulkanTestSkipped; + } + const auto context = heapDevice->GraphicsContext(); + Require(BindlessHeap::For(context).DescriptorHeapMode(), "the test device did not open the descriptor heap"); + residentPresentTests(context); + } std::cout << "resident present format, presentation pass and letterbox tests passed\n"; return 0; } catch (const std::exception& error) { From 14c6af4b1c6715da7dfeeb54a698acc27e814055 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 19:53:55 +0530 Subject: [PATCH 017/269] fix(agc): keep heap ring words on relocated draw-cache variants A relocated copy of a cached draw dropped ring, ringAttributes, ringFlat and ringBindings, so a heap stage hitting it ran without per-draw heap words and drew with the donor's template data (Hades II black flicker). Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/Driver/Draw/DrawRelocate.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp index ef4c9d3aeb6e..6a23d8905c72 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp @@ -234,6 +234,10 @@ void Driver::relocateDrawEntry(const QueueState& queue, std::uint64_t alias, std copy->flatBinding = variant->flatBinding; copy->pushOffset = variant->pushOffset; copy->vertexInfo = variant->vertexInfo; + copy->ring = variant->ring; + copy->ringAttributes = variant->ringAttributes; + copy->ringFlat = variant->ringFlat; + copy->ringBindings = variant->ringBindings; for (const auto& move : moves) { if (move.program != i) continue; const auto delta = AlignedWord(move.to) - AlignedWord(move.from); From 6ec4137b1a210ff1193d0b89bad972e3c94aa4eb Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 19:53:55 +0530 Subject: [PATCH 018/269] fix(agc): keep a ring hit's shader data words beyond the user words buildRingWords cleared the stored ShaderData words, so a ring hit fell back to the template's words past the user-data prefix; it now copies the current user words over the stored ones. Co-Authored-By: Claude Opus 5.5 --- .../prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 97f819198aa4..d5c81e46f615 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -895,7 +895,11 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { require(words->bindings.size() == variant.compiled->bindings.size(), "a ring vertex hit's bindings differ in number from its template"); for (std::size_t index = 0; index < words->bindings.size(); ++index) { const auto role = variant.compiled->bindings[index].role; - if (role == ShaderRecompiler::DescriptorRole::ShaderData || role == ShaderRecompiler::DescriptorRole::FlattenedSrt) words->bindings[index].clear(); + auto& descriptor = words->bindings[index]; + if (role == ShaderRecompiler::DescriptorRole::FlattenedSrt) descriptor.clear(); + if (role != ShaderRecompiler::DescriptorRole::ShaderData || descriptor.empty()) continue; + std::copy_n(words->userData.begin(), std::min(words->userData.size(), descriptor.size()), descriptor.begin()); + if (descriptor == variant.compiled->bindings[index].guestDescriptor) descriptor.clear(); } } ShaderRecompiler::CompleteHeapDataWords(*variant.compiled, *words); From c5ec4dc719999111e7bb3c3f3daa764c2eba94d9 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 20:20:10 +0530 Subject: [PATCH 019/269] perf(agc): drain the old heap walk memo generation per insert Rotating the two-generation memo destroyed the whole previous generation (up to 16384 keys of captures and words) on the draw thread, a 16-20 ms heap_direct stall every few seconds in MC D2. Each insert now frees two old entries, so the old generation is empty before the next rotation. Co-Authored-By: Claude Opus 5.5 --- .../libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 656a82685889..c9f6ee9f938f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -218,6 +218,8 @@ constexpr std::size_t HeapWalkWays = 4; constexpr std::size_t HeapWalkMemoKeys = 16384; +constexpr std::size_t HeapWalkDrain = 2; + struct HeapWalkMemo { std::unordered_map> current; std::unordered_map> previous; @@ -234,6 +236,7 @@ struct HeapWalkMemo { } std::vector& slot(std::uint64_t key) { + for (std::size_t drained = 0; drained < HeapWalkDrain && !previous.empty(); ++drained) previous.erase(previous.begin()); if (current.size() >= HeapWalkMemoKeys && !current.contains(key)) { previous = std::move(current); current.clear(); From 55361e01b2aaa812020e2e67592b63eaa475ac58 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 21:25:05 +0530 Subject: [PATCH 020/269] chore(agc): heap stage cost timers in the [gpu-heap] line under APS5_PIPELINE_STATS Per-call time of the draw stage's preparation, heap stage call, walk memo, walk, materialize and finish on the queue worker, and of the resource template find and build, slot mapping, stage data and buffer address writes on the committer. Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/Driver/Draw/DrawCapture.cpp | 5 ++++ .../Execution/src/Driver/Draw/HeapStages.cpp | 6 +++++ .../Graphics/include/BindlessHeap.hpp | 20 ++++++++++++++++ .../Graphics/src/BindlessHeap.cpp | 23 +++++++++++++++++++ .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 4 ++++ .../Graphics/src/ShaderResources.cpp | 5 ++++ 6 files changed, 63 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index d8b121baf0cc..1927b97ac85f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -82,6 +82,7 @@ std::shared_ptr Driver::materializeDraw const auto index = *tail - program.firstUserSgpr; return index + 1u < 64u ? std::uint64_t{3} << index : ~std::uint64_t{0}; }; + Graphics::HeapCostScope prepareCost(Graphics::HeapCost::StagePrepare); const auto waveSize = program.binary.stage == Stage::Fragment ? graphics.stages.fragmentWaveSize : graphics.stages.vertexWaveSize; ShaderRecompiler::RecompileRequest request{ program.binary, @@ -132,6 +133,7 @@ std::shared_ptr Driver::materializeDraw } } Graphics::NoteHeapStageReason(stageReason); + prepareCost.Stop(); timing.Mark("prepared_invocation"); auto& stageCapture = stageCaptures[i]; stageCapture.direct = false; @@ -166,11 +168,14 @@ std::shared_ptr Driver::materializeDraw std::shared_ptr reusedWords; HeapStageReads reads; decltype(MaterializeHeapStage(invocation, program.userData, program.binary.codeAddress, words.get(), &reusedWords, &reads)) direct; + Graphics::HeapCostScope callCost(Graphics::HeapCost::HeapStageCall); try { direct = MaterializeHeapStage(invocation, program.userData, program.binary.codeAddress, words.get(), &reusedWords, &reads); } catch (const std::exception& error) { throw named(error, request.context.memory); } + callCost.Stop(); + Graphics::HeapCostScope finishCost(Graphics::HeapCost::StageFinish); if (direct == nullptr) goto heapCapture; if (!HeapStageMappable(*direct)) return unmapped(); NoteHeapDirect(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index c9f6ee9f938f..d62833a34df0 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -279,6 +279,7 @@ std::shared_ptr MaterializeHeapStage(co const auto generation = GuestMemory::TrackerGeneration(); const bool memoOn = words != nullptr && !invocation.Request().context.vertex.has_value(); std::uint64_t memoKey = 0; + Graphics::HeapCostScope memoCost(Graphics::HeapCost::WalkMemo); if (memoOn) { memoKey = (invocation.VariantId() * 0x9e3779b97f4a7c15ull ^ shaderBase) + invocation.Request().layout.pushConstantOffsetBytes; for (const auto word : userData) memoKey = (memoKey ^ word) * 0x100000001b3ull; @@ -312,6 +313,8 @@ std::shared_ptr MaterializeHeapStage(co return result; } } + memoCost.Stop(); + Graphics::HeapCostScope walkCost(Graphics::HeapCost::Walk); ShaderRecompiler::SrtRuntime plain; plain.userData = userData; plain.shaderBase = shaderBase; @@ -359,9 +362,12 @@ std::shared_ptr MaterializeHeapStage(co } bool settled = !(DrawPipeline::Active() && DrawPipeline::Queue0().Busy() && DrawPipeline::Queue0().OverlapsAny(ranges)) && Graphics::Recorder::ReadsSettled(ranges, before.get()); for (std::size_t i = 0; settled && i < ranges.size(); ++i) settled = GuestMemory::NewestStamp(ranges[i].first, static_cast(ranges[i].second - ranges[i].first)) <= generation; + walkCost.Stop(); if (settled) { for (const auto& [begin, end] : ranges) GuestMemory::GuardRead(begin, static_cast(end - begin)); + Graphics::HeapCostScope materializeCost(Graphics::HeapCost::Materialize); auto result = finish(capture); + materializeCost.Stop(); if (stageReads != nullptr && !reads.failed && result != nullptr) *stageReads = {ranges, values, capture->userDataUse, capture, true}; if (memoOn && !reads.failed && result != nullptr) { auto& ways = heapWalkMemo().slot(memoKey); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 551dab123ad8..5d159eb382aa 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -4,6 +4,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include "RuntimeAbi.hpp" #include +#include #include #include #include @@ -161,6 +162,25 @@ void NoteHeapStageReason(HeapStageReason reason); void NoteHeapRecord(bool compute, bool heap); void NoteHeapFallback(HeapFallback reason); void NoteCpuBufferCopy(std::uint64_t bytes); +enum class HeapCost : std::uint8_t { StagePrepare, HeapStageCall, StageFinish, WalkMemo, Walk, Materialize, TemplateFind, TemplateBuild, Slots, StageData, BufferAddresses, Count }; +bool HeapCostTimed(); +void NoteHeapCost(HeapCost cost, std::uint64_t nanoseconds); +class HeapCostScope { +public: + explicit HeapCostScope(HeapCost cost) : cost(cost), start(HeapCostTimed() ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}) {} + ~HeapCostScope() { Stop(); } + HeapCostScope(const HeapCostScope&) = delete; + HeapCostScope& operator=(const HeapCostScope&) = delete; + void Stop() { + if (start == std::chrono::steady_clock::time_point{}) return; + NoteHeapCost(cost, static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count())); + start = {}; + } + +private: + HeapCost cost; + std::chrono::steady_clock::time_point start; +}; void NoteCommandBufferBegun(VkCommandBuffer commands); void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site); std::uint64_t DescriptorHeapBinds(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index c9915914736e..28969e3af3b8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -770,6 +770,10 @@ std::uint64_t takeCount(std::atomic& counter) { return counter.exchange(0, std::memory_order_relaxed); } +std::array, static_cast(HeapCost::Count)> heapCostNs{}; +std::array, static_cast(HeapCost::Count)> heapCostCalls{}; +constexpr std::array(HeapCost::Count)> HeapCostNames{"stage prepare", "heap stage call", "stage finish", "walk memo", "walk", "materialize", "template find", "template build", "slots", "stage data", "buffer addresses"}; + void reportHeapStatistics() { static const bool enabled = std::getenv("APS5_PIPELINE_STATS") != nullptr; if (!enabled) return; @@ -788,6 +792,15 @@ void reportHeapStatistics() { for (std::size_t i = 0; i < heapFallbacks.size(); ++i) fallbacks += " " + std::string(HeapFallbackNames[i]) + " " + std::to_string(takeCount(heapFallbacks[i])); std::string stageReasons; for (std::size_t i = 0; i < heapStageReasons.size(); ++i) stageReasons += " " + std::string(HeapStageReasonNames[i]) + " " + std::to_string(takeCount(heapStageReasons[i])); + std::string costs; + for (std::size_t i = 0; i < heapCostNs.size(); ++i) { + const auto calls = takeCount(heapCostCalls[i]); + const auto ns = takeCount(heapCostNs[i]); + char cost[96]; + std::snprintf(cost, sizeof(cost), " %s %llu x %.2f us = %.0f ms", HeapCostNames[i], static_cast(calls), calls != 0 ? static_cast(ns) / static_cast(calls) / 1000.0 : 0.0, static_cast(ns) / 1e6); + costs += cost; + } + if (HeapCostTimed()) std::fprintf(stderr, "[gpu-heap] cost (10 s):%s\n", costs.c_str()); const auto heapDraws = takeCount(heapRecords[1]); const auto plainDraws = takeCount(heapRecords[0]); const auto heapDispatches = takeCount(heapRecords[3]); @@ -812,6 +825,16 @@ void NoteHeapStageReason(HeapStageReason reason) { heapStageReasons[static_cast(reason)].fetch_add(1, std::memory_order_relaxed); } +bool HeapCostTimed() { + static const bool timed = std::getenv("APS5_PIPELINE_STATS") != nullptr; + return timed; +} + +void NoteHeapCost(HeapCost cost, std::uint64_t nanoseconds) { + heapCostNs[static_cast(cost)].fetch_add(nanoseconds, std::memory_order_relaxed); + heapCostCalls[static_cast(cost)].fetch_add(1, std::memory_order_relaxed); +} + void NoteCpuBufferCopy(std::uint64_t bytes) { cpuBufferCopies.fetch_add(1, std::memory_order_relaxed); cpuBufferCopyBytes.fetch_add(bytes, std::memory_order_relaxed); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index b8c45ab13bc7..76972d957ba7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1688,6 +1688,7 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat // the alias checks instead. Debug aid: APS5_NO_DRAW_KEY_TRIM=1 keys them as before. static const bool trimKey = std::getenv("APS5_NO_DRAW_KEY_TRIM") == nullptr; resolved.cacheable = recordable && !noDrawResourceCache && !noTextureCache && std::all_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->PipelineVariantId() != 0; }) && !ShaderResources::NeverReusable(shaders); + HeapCostScope findCost(HeapCost::TemplateFind); if (resolved.cacheable) { resolved.contentKey = DrawResourceKey(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, indexBytes, !trimKey); if (auto cached = SharedResourceCache().Find(resolved.contentKey)) { @@ -1720,9 +1721,12 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat } else { countCache(&DrawProfile::uncacheable); } + findCost.Stop(); timer.phase(PhaseLookup); if (resolved.resources == nullptr) { + HeapCostScope buildCost(HeapCost::TemplateBuild); resolved.resources = std::make_shared(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, static_cast(indexBytes), snapshots); + buildCost.Stop(); resolved.built = &resolved.resources->Timing(); outcome.addressBased = resolved.resources->HoldsLease(); outcome.kind = outcome.addressBased ? KindBda : KindBuild; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 45b0c279c248..13000d7316db 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6183,6 +6183,7 @@ std::uint32_t ShaderResources::heapSpan(HeapStageState::KeptSpan& kept, std::spa void ShaderResources::writeHeapStage(const CompiledShader& shader) { namespace Abi = ShaderRecompiler::RuntimeAbi; + HeapCostScope slotsCost(HeapCost::Slots); auto& heap = BindlessHeap::For(context); constexpr auto bindingCount = static_cast(Abi::Binding::Count); const VkShaderStageFlags stageBit = VulkanStage(shader.stage); @@ -6304,6 +6305,8 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { } if (checked.load() % 100000u < 8u) std::fprintf(stderr, "[heap-slots] verify: %llu image slots checked, %llu hold another texture\n", static_cast(checked.load()), static_cast(wrong.load())); } + slotsCost.Stop(); + HeapCostScope dataCost(HeapCost::StageData); const std::size_t dataIndex = DataOffsetIndex(stageIndex, Abi::Binding::ShaderData); const std::size_t flatIndex = DataOffsetIndex(stageIndex, Abi::Binding::FlattenedSrt); const auto& program = *shader.program; @@ -6367,7 +6370,9 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { Require(slotWords || program.samplerSlotDword + samplerSlots.size() <= patched.size(), "GPU-mode sampler slots exceed the shader data"); if (!slotWords) std::copy(samplerSlots.begin(), samplerSlots.end(), patched.begin() + program.samplerSlotDword); if (addressedBuffers) { + HeapCostScope bufferCost(HeapCost::BufferAddresses); writeBufferAddresses(patched, static_cast(stageIndex), nullptr); + bufferCost.Stop(); stageDataWords[stageIndex].assign(patched.begin(), patched.end()); stageDataIndex[stageIndex] = dataIndex; } From 04ca39c0beb638e5ee2d82586492a5afb8439999 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 21:50:58 +0530 Subject: [PATCH 021/269] chore(agc): heap walk memo insert and guard timers in the [gpu-heap] cost line Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp | 2 +- core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 5d159eb382aa..0735ec66b921 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -162,7 +162,7 @@ void NoteHeapStageReason(HeapStageReason reason); void NoteHeapRecord(bool compute, bool heap); void NoteHeapFallback(HeapFallback reason); void NoteCpuBufferCopy(std::uint64_t bytes); -enum class HeapCost : std::uint8_t { StagePrepare, HeapStageCall, StageFinish, WalkMemo, Walk, Materialize, TemplateFind, TemplateBuild, Slots, StageData, BufferAddresses, Count }; +enum class HeapCost : std::uint8_t { StagePrepare, HeapStageCall, StageFinish, WalkMemo, Walk, Materialize, TemplateFind, TemplateBuild, Slots, StageData, BufferAddresses, MemoInsert, Guards, Count }; bool HeapCostTimed(); void NoteHeapCost(HeapCost cost, std::uint64_t nanoseconds); class HeapCostScope { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 28969e3af3b8..052fea7bf95a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -772,7 +772,7 @@ std::uint64_t takeCount(std::atomic& counter) { std::array, static_cast(HeapCost::Count)> heapCostNs{}; std::array, static_cast(HeapCost::Count)> heapCostCalls{}; -constexpr std::array(HeapCost::Count)> HeapCostNames{"stage prepare", "heap stage call", "stage finish", "walk memo", "walk", "materialize", "template find", "template build", "slots", "stage data", "buffer addresses"}; +constexpr std::array(HeapCost::Count)> HeapCostNames{"stage prepare", "heap stage call", "stage finish", "walk memo", "walk", "materialize", "template find", "template build", "slots", "stage data", "buffer addresses", "memo insert", "guards"}; void reportHeapStatistics() { static const bool enabled = std::getenv("APS5_PIPELINE_STATS") != nullptr; From faa10c1d044dc9b24aec6ede3283b988e4f64c2b Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 20 Oct 2026 21:50:58 +0530 Subject: [PATCH 022/269] perf(agc): admit a heap walk into the memo on the second sighting of its key Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/Driver/Draw/HeapStages.cpp | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index d62833a34df0..7721dd365b3c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -220,9 +220,19 @@ constexpr std::size_t HeapWalkMemoKeys = 16384; constexpr std::size_t HeapWalkDrain = 2; +constexpr std::size_t HeapWalkSeenKeys = 1u << 16; + struct HeapWalkMemo { std::unordered_map> current; std::unordered_map> previous; + std::vector seen = std::vector(HeapWalkSeenKeys, 0); + + bool admit(std::uint64_t key) { + auto& last = seen[(key ^ (key >> 29)) & (HeapWalkSeenKeys - 1u)]; + if (last == key) return true; + last = key; + return false; + } std::vector* find(std::uint64_t key) { if (const auto found = current.find(key); found != current.end()) return &found->second; @@ -275,15 +285,19 @@ std::shared_ptr MaterializeHeapStage(co reads.accessible.clear(); reads.failed = false; reads.page = ~std::uint64_t{0}; + Graphics::HeapCostScope snapshotCost(Graphics::HeapCost::Guards); const auto before = Graphics::Recorder::PendingWriteSnapshot(); + snapshotCost.Stop(); const auto generation = GuestMemory::TrackerGeneration(); const bool memoOn = words != nullptr && !invocation.Request().context.vertex.has_value(); std::uint64_t memoKey = 0; + bool memoKnown = false; Graphics::HeapCostScope memoCost(Graphics::HeapCost::WalkMemo); if (memoOn) { memoKey = (invocation.VariantId() * 0x9e3779b97f4a7c15ull ^ shaderBase) + invocation.Request().layout.pushConstantOffsetBytes; for (const auto word : userData) memoKey = (memoKey ^ word) * 0x100000001b3ull; auto* found = heapWalkMemo().find(memoKey); + memoKnown = found != nullptr; for (std::size_t way = 0; found != nullptr && way < found->size(); ++way) { const auto& entry = (*found)[way]; bool equal = entry.variant == invocation.VariantId() && entry.shaderBase == shaderBase && entry.pushOffset == invocation.Request().layout.pushConstantOffsetBytes && std::equal(entry.userData.begin(), entry.userData.end(), userData.begin(), userData.end()); @@ -364,12 +378,15 @@ std::shared_ptr MaterializeHeapStage(co for (std::size_t i = 0; settled && i < ranges.size(); ++i) settled = GuestMemory::NewestStamp(ranges[i].first, static_cast(ranges[i].second - ranges[i].first)) <= generation; walkCost.Stop(); if (settled) { + Graphics::HeapCostScope guardCost(Graphics::HeapCost::Guards); for (const auto& [begin, end] : ranges) GuestMemory::GuardRead(begin, static_cast(end - begin)); + guardCost.Stop(); Graphics::HeapCostScope materializeCost(Graphics::HeapCost::Materialize); auto result = finish(capture); materializeCost.Stop(); if (stageReads != nullptr && !reads.failed && result != nullptr) *stageReads = {ranges, values, capture->userDataUse, capture, true}; - if (memoOn && !reads.failed && result != nullptr) { + Graphics::HeapCostScope insertCost(Graphics::HeapCost::MemoInsert); + if (memoOn && !reads.failed && result != nullptr && (memoKnown || heapWalkMemo().admit(memoKey))) { auto& ways = heapWalkMemo().slot(memoKey); if (ways.size() >= HeapWalkWays) ways.pop_back(); ways.emplace(ways.begin()); From dd60d029bab7b61929180c4e052834ef00270dd9 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 22 Oct 2026 04:21:35 +0530 Subject: [PATCH 023/269] perf(agc): store thread-dimension dispatch limits in the heap ring An indirect dispatch with USE_THREAD_DIMENSIONS stores its thread limit in the ShaderData words at record time, which heap stages keep in a ring span, so these dispatches were kept off the heap. The limit now goes into the dispatch's ring span: the stage takes a fresh span before its data is written and drops it afterwards, so a kept span that other dispatches read never changes. The ring takes transfer writes for the copy. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 2 +- .../Execution/src/Driver/Dispatch/Dispatch.cpp | 1 - .../libSceAgcDriver/Execution/src/VulkanDevice.cpp | 5 +++-- .../Graphics/include/BindlessHeap.hpp | 1 + .../Graphics/include/ShaderResources.hpp | 1 + .../libSceAgcDriver/Graphics/src/BindlessHeap.cpp | 6 +++++- .../libSceAgcDriver/Graphics/src/ShaderResources.cpp | 12 ++++++++++++ 7 files changed, 23 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 1ed14c73d0c2..939780e51171 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -2658,7 +2658,7 @@ if(BUILD_TESTING) set_tests_properties(${agcTestName}_draw_pipeline PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endforeach() - set(agcGpuHeapTests ${agcDrawPipelineTests} agc_driver_rect_list_indirect agc_driver_provoking_vertex agc_driver_pixel_barycentric_emulation agc_driver_bindless_images agc_driver_image_sample_shared_sampler agc_driver_image_sample_border_color agc_driver_image_sample_lod_clamp agc_driver_image_sample_derivatives agc_driver_image_gather_one_dimensional agc_driver_image_load_packed agc_driver_sampled_cache_budget agc_driver_image_atomics agc_driver_image_atomics64 agc_driver_image_atomics_bitwise agc_driver_image_atomics_float agc_driver_gpu_indirect_arguments_misaligned_writer_ahead agc_driver_gpu_indirect_arguments_written_ahead agc_driver_indirect_arguments_written_ahead agc_driver_indirect_patched_stage agc_driver_compute_table_calls agc_driver_buffer_atomics agc_driver_buffer_format agc_driver_mesh agc_driver_tessellation agc_driver_mesh_draw_relocation agc_driver_mesh_index_cache agc_driver_mesh_provoking_vertex agc_driver_tessellation_submit agc_driver_fragment_user_data_tail agc_driver_image_table_cache_bounds agc_driver_lds_beyond_device_limit agc_driver_address_passes) + set(agcGpuHeapTests ${agcDrawPipelineTests} agc_driver_rect_list_indirect agc_driver_provoking_vertex agc_driver_pixel_barycentric_emulation agc_driver_bindless_images agc_driver_image_sample_shared_sampler agc_driver_image_sample_border_color agc_driver_image_sample_lod_clamp agc_driver_image_sample_derivatives agc_driver_image_gather_one_dimensional agc_driver_image_load_packed agc_driver_sampled_cache_budget agc_driver_image_atomics agc_driver_image_atomics64 agc_driver_image_atomics_bitwise agc_driver_image_atomics_float agc_driver_gpu_indirect_arguments_misaligned_writer_ahead agc_driver_gpu_indirect_arguments_written_ahead agc_driver_indirect_arguments_written_ahead agc_driver_indirect_thread_dimensions agc_driver_indirect_patched_stage agc_driver_compute_table_calls agc_driver_buffer_atomics agc_driver_buffer_format agc_driver_mesh agc_driver_tessellation agc_driver_mesh_draw_relocation agc_driver_mesh_index_cache agc_driver_mesh_provoking_vertex agc_driver_tessellation_submit agc_driver_fragment_user_data_tail agc_driver_image_table_cache_bounds agc_driver_lds_beyond_device_limit agc_driver_address_passes) foreach(agcTestName IN LISTS agcGpuHeapTests) add_test(NAME ${agcTestName}_gpu_heap COMMAND ${agcTestName}_tests) set_tests_properties(${agcTestName}_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index 2c487a7e5160..e934d51cd5fe 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -172,7 +172,6 @@ void Driver::dispatch(QueueState& queue, std::span packet, }; constexpr std::size_t computeHeapKey = std::size_t{1} << 61u; if (request.target.gpuResolvedImages && HeapFragmentKnown(&snapshot, codeOffset | computeHeapKey) == std::optional(false)) request.target.gpuResolvedImages = false; - if (threadGroup != std::array{}) request.target.gpuResolvedImages = false; static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; static double captureMs = 0, keyMs = 0, recompileMs = 0, deviceMs = 0; static std::uint64_t cacheHits = 0; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 1ac7adbbc50f..8b3a6b137ac9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -5058,6 +5058,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { } recordStep(PhaseRecordKeeps); if (resources.HeapStage()) { + if (record.threadGroup != std::array{}) resources.forgetShaderDataWords(*record.shader); resources.RefreshHeapStage(std::span(record.shader, 1)); if (record.bindings != nullptr) resources.RefreshMovedAddresses(*record.bindings); } @@ -5079,10 +5080,10 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { } std::shared_ptr threadArguments; if (record.threadGroup != std::array{}) { - const auto data = resources.shaderDataBuffer(*record.shader); + const auto [data, dataOffset] = resources.shaderDataLocation(*record.shader, record.bindings.get()); const auto limitDword = record.shader->program->imageMetadataDword; Graphics::Require(data != VK_NULL_HANDLE && limitDword >= 3, "Vulkan dispatch: a thread-dimension dispatch has no ShaderData thread limit"); - const VkDeviceSize limitByte = static_cast(limitDword - 3) * sizeof(std::uint32_t); + const VkDeviceSize limitByte = dataOffset + static_cast(limitDword - 3) * sizeof(std::uint32_t); Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); if (argumentImport != nullptr) { threadArguments = std::make_shared(context, 24, VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 0735ec66b921..8f92ba556b0e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -38,6 +38,7 @@ class BindlessHeap { void BindDescriptorHeaps(VkCommandBuffer commands) const; bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset = ~0u, bool rootGds = false, bool rootFault = false) const; VkDeviceAddress RingAddress() const; + VkBuffer RingBuffer() const; std::optional TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, VkImageLayout layout); std::optional StorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index bfb0f419a89a..9230f65adb10 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -370,6 +370,7 @@ class ShaderResources { bool refreshData(VkCommandBuffer commands, const CompiledShader& shader, Recorder* recorder); std::optional shaderDataAllocation(const CompiledShader& shader) const; VkBuffer shaderDataBuffer(const CompiledShader& shader) const; + std::pair shaderDataLocation(const CompiledShader& shader, const DrawBindings* rewritten) const; void forgetShaderDataWords(const CompiledShader& shader); struct DescribedRange { const char* kind; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 052fea7bf95a..9432f8c2525e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -114,7 +114,7 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { samplerHeap = std::make_unique(context, static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage); std::fill(resourceHeap->Bytes().begin(), resourceHeap->Bytes().end(), std::byte{0}); std::fill(samplerHeap->Bytes().begin(), samplerHeap->Bytes().end(), std::byte{0}); - constexpr VkBufferUsageFlags ringUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + constexpr VkBufferUsageFlags ringUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; try { ring = std::make_unique(context, RingBytes, ringUsage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); } catch (const std::exception&) { @@ -882,6 +882,10 @@ VkDeviceAddress BindlessHeap::RingAddress() const { return ring->DeviceAddress(); } +VkBuffer BindlessHeap::RingBuffer() const { + return ring->Handle(); +} + void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { std::lock_guard lock(mutex); for (std::size_t index = 0; index < ringChunks.size(); ++index) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 13000d7316db..983236bf16e3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -4708,6 +4708,12 @@ VkBuffer ShaderResources::shaderDataBuffer(const CompiledShader& shader) const { } void ShaderResources::forgetShaderDataWords(const CompiledShader& shader) { + if (shader.program != nullptr && shader.program->gpuResolvedImages) { + auto& stageState = heapStages[HeapStageIndex(shader.stage)]; + stageState.data.mark.entry = 0; + stageState.data.words.clear(); + stageState.dataInput.clear(); + } if (const auto allocation = shaderDataAllocation(shader)) { allocations[*allocation].dataWords.clear(); rehashDataWords(); @@ -6018,6 +6024,12 @@ std::size_t DataOffsetIndex(std::size_t stage, ShaderRecompiler::RuntimeAbi::Bin } +std::pair ShaderResources::shaderDataLocation(const CompiledShader& shader, const DrawBindings* rewritten) const { + if (!heapStage || shader.program == nullptr || !shader.program->gpuResolvedImages) return {shaderDataBuffer(shader), 0}; + const auto& offsets = rewritten != nullptr && rewritten->addressOffsets ? rewritten->heapOffsets : heapOffsets; + return {BindlessHeap::For(context).RingBuffer(), offsets[DataOffsetIndex(HeapStageIndex(shader.stage), ShaderRecompiler::RuntimeAbi::Binding::ShaderData)]}; +} + void ShaderResources::PatchDataAddresses(std::span bytes, std::span shaders, const DrawBindings* rewritten) const { namespace Abi = ShaderRecompiler::RuntimeAbi; if (!heapStage) return; From cbc10e65e4321bc1ad3681d461173576990c9586 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 22 Oct 2026 05:12:59 +0530 Subject: [PATCH 024/269] perf(agc): hold 2048 samplers in the GPU heap and turn it off on devices too small for its slots The sampler heap held 256 samplers, an eighth of what D3D12 allows, so scenes with many samplers swept it early. It now holds 2048, which fits NVIDIA's sampler heap beside its embedded sampler range. A device whose resource or sampler heap cannot hold the slots no longer enables the heap and takes the per-draw path, instead of failing at the first heap use. Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/VulkanDevice.cpp | 6 ++-- .../Graphics/include/BindlessHeap.hpp | 1 + .../Graphics/src/BindlessHeap.cpp | 36 +++++++++++++++---- core/shader/recompiler/RuntimeAbi.hpp | 2 +- core/shader/recompiler/ShaderDiskCache.hpp | 2 +- docs/dev/ARCHITECTURE.md | 2 +- 6 files changed, 37 insertions(+), 12 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 8b3a6b137ac9..22ae09ac37e0 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -1870,10 +1870,12 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &heapMaintenance5}; state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &features); if (descriptorHeapFeatures.descriptorHeap == VK_TRUE && heapMaintenance5.maintenance5 == VK_TRUE) { - state->descriptorHeap = true; - state->maintenance5 = true; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &state->descriptorHeapProperties}; state->InstanceFunction("vkGetPhysicalDeviceProperties2")(selected, &properties); + } + if (descriptorHeapFeatures.descriptorHeap == VK_TRUE && heapMaintenance5.maintenance5 == VK_TRUE && Graphics::BindlessHeap::Fits(state->descriptorHeapProperties)) { + state->descriptorHeap = true; + state->maintenance5 = true; deviceExtensions.push_back(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME); for (const char* required : {VK_KHR_MAINTENANCE_5_EXTENSION_NAME, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME}) { if (std::find_if(deviceExtensions.begin(), deviceExtensions.end(), [&](const char* name) { return std::strcmp(name, required) == 0; }) == deviceExtensions.end()) deviceExtensions.push_back(required); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 8f92ba556b0e..e28a06e488c4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -30,6 +30,7 @@ class BindlessHeap { static BindlessHeap& For(const Context& context); static BindlessHeap* Existing(const Context& context); static void Release(VkDevice device); + static bool Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties); bool DescriptorHeapMode() const { return resourceHeap != nullptr; } VkDeviceSize ImageHeapOffset(std::uint32_t kind) const; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 9432f8c2525e..eb5067568362 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -99,16 +99,38 @@ bool HeapComputeEnabled() { return DescriptorHeapEnabled(); } +namespace { + +struct HeapSizes { + VkDeviceSize imageStride = 0, samplerStride = 0, resourceUsed = 0, samplerUsed = 0; +}; + +HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { + const auto align = [](VkDeviceSize value, VkDeviceSize alignment) { return alignment == 0 ? value : (value + alignment - 1) / alignment * alignment; }; + HeapSizes sizes; + sizes.imageStride = align(properties.imageDescriptorSize, properties.imageDescriptorAlignment); + sizes.samplerStride = align(properties.samplerDescriptorSize, properties.samplerDescriptorAlignment); + sizes.resourceUsed = align(static_cast(static_cast(Abi::Binding::Samplers)) * Abi::GpuImageHeapSlots * sizes.imageStride, properties.resourceHeapAlignment); + sizes.samplerUsed = align(static_cast(Abi::GpuSamplerHeapSlots) * sizes.samplerStride, properties.samplerHeapAlignment); + return sizes; +} + +} + +bool BindlessHeap::Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { + const auto sizes = heapSizes(properties); + return sizes.resourceUsed + properties.minResourceHeapReservedRange <= properties.maxResourceHeapSize && sizes.samplerUsed + properties.minSamplerHeapReservedRangeWithEmbedded <= properties.maxSamplerHeapSize; +} + BindlessHeap::BindlessHeap(const Context& context) : context(context) { Require(context.descriptorHeap, "the GPU heap needs VK_EXT_descriptor_heap"); const auto& heapProperties = context.descriptorHeapProperties; - const auto align = [](VkDeviceSize value, VkDeviceSize alignment) { return alignment == 0 ? value : (value + alignment - 1) / alignment * alignment; }; - imageHeapStride = align(heapProperties.imageDescriptorSize, heapProperties.imageDescriptorAlignment); - samplerHeapStride = align(heapProperties.samplerDescriptorSize, heapProperties.samplerDescriptorAlignment); - resourceHeapUsed = align(static_cast(static_cast(Abi::Binding::Samplers)) * Abi::GpuImageHeapSlots * imageHeapStride, heapProperties.resourceHeapAlignment); - samplerHeapUsed = align(static_cast(Abi::GpuSamplerHeapSlots) * samplerHeapStride, heapProperties.samplerHeapAlignment); - Require(resourceHeapUsed + heapProperties.minResourceHeapReservedRange <= heapProperties.maxResourceHeapSize, "the GPU heap's image slots exceed the device's resource heap size"); - Require(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded <= heapProperties.maxSamplerHeapSize, "the GPU heap's sampler slots exceed the device's sampler heap size"); + const auto sizes = heapSizes(heapProperties); + imageHeapStride = sizes.imageStride; + samplerHeapStride = sizes.samplerStride; + resourceHeapUsed = sizes.resourceUsed; + samplerHeapUsed = sizes.samplerUsed; + Require(Fits(heapProperties), "the GPU heap's slots exceed the device's descriptor heap sizes"); constexpr VkBufferUsageFlags heapUsage = VK_BUFFER_USAGE_DESCRIPTOR_HEAP_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; resourceHeap = std::make_unique(context, static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange), heapUsage); samplerHeap = std::make_unique(context, static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage); diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index a929bba80af1..ff0ced78a505 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -50,7 +50,7 @@ inline constexpr std::uint32_t StorageMipSlots = 16u; inline constexpr std::uint32_t StorageHeapCapacity = 64u; inline constexpr std::uint32_t SamplerHeapCapacity = 64u; inline constexpr std::uint32_t GpuImageHeapSlots = 4096u; -inline constexpr std::uint32_t GpuSamplerHeapSlots = 256u; +inline constexpr std::uint32_t GpuSamplerHeapSlots = 2048u; inline constexpr std::uint32_t GpuDataSet = 2u; inline constexpr std::uint32_t GpuGdsSet = 4u; inline constexpr std::uint32_t GdsBytes = 0x10000u; diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index d4cf9e2f300b..8eba383469b2 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -13,7 +13,7 @@ namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 47; +inline constexpr std::uint32_t FormatVersion = 48; enum class LoadStatus { Loaded, diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index d9ea45074279..bc90f3157c9a 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -131,7 +131,7 @@ flowchart LR - Queue 0's packet worker decodes, captures and prepares a draw and hands its recording (`Graphics::Draw` under the GPU lock) to a committer thread in [`DrawPipeline.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp), so the next packet is decoded while the previous draw is recorded. Each queued item carries the guest ranges it will write (`DrawWriteRanges`: written buffers and storage images, color targets with their DCC and CMASK, depth and stencil). A later packet that reads or writes one of those ranges, or that the pipeline can't order, drains it first; labels, submission ends, buffer fills and (with `APS5_PIPELINE_DMA=1`) DMA packets are queued as items instead. With `APS5_PIPELINE_DISPATCH=1` (off by default), a `DISPATCH_DIRECT` whose dispatch-cache entry hits with a recipe is queued as an item too, carrying the dispatch's written buffers and storage images (`DispatchWriteRanges`); the capture and the cache lookup stay on the worker and the recipe is recorded on the committer. A dispatch still drains when its lookup misses, when what it reads overlaps a write still pending, when the hit is verified against data or when its writes cannot be ranged (bindless access, GDS, fault buffer). An indirect draw resolved on the CPU (its records read by the worker) drains only when its records or its count overlap a queued write; the records it draws inline drain first, and its last drawn record is queued like a direct draw (`APS5_NO_PIPELINED_INDIRECT=1` drains at every indirect draw). An exception thrown by a commit is rethrown on the worker at its next enqueue or drain, as an inline draw error would be. On by default; `APS5_PIPELINED_DRAWS=0` records every draw inline, and `APS5_EXACT_DRAW_WRITES=0` widens the color and depth ranges to estimates. - A dispatch's resource build runs stage A (binding plan, buffers, descriptor set) without the GPU lock and stage B (image lookups) under it. Between them `VulkanDevice::presync` waits, still without the lock, for recorded work that writes a surface stage B would read on the CPU and for recorded work that writes the DCC keys of an image the dispatch binds (`ShaderResources::PresyncSurfaces`), so the locked `WaitForKeyWriters` finds nothing pending to synchronize with. A key range is waited for only when recorded work writes it, the key-store memo does not give its value (`DccKeyWritersPending`, without the mutex) and the pending stores do not give it either (`DccKeyWriterNeedsSync`, under the mutex, the same test `WaitForKeyWriters` makes before it synchronizes). Stage A's own key scan runs before that wait, and stage B compares it with the keys it reads under the lock as before. `APS5_NO_DCC_PRESYNC=1` leaves the key ranges out; `APS5_NO_PRESYNC=1` disables the whole pre-sync. - `APS5_DRAW_PIPELINE=1` (off by default, meant with `APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1`) takes more of a draw off the worker. A `DrawFinisher` thread runs the second half of a direct pipelined draw (stage materialization, the draw cache insert and the hand-off to the committer) while the worker reads the next packets; the worker drains it before the next draw's cache lookup, before packets other than register writes and draws, and before guest reads, and finishes in place a draw whose stages may write memory (`ProgramWritesMemory`) or write through the BDA page table. The committer skips the fragment-output validation and storage-image layer scans whose inputs match its last commit (`CommitTrims`), and a resource or storage image proved current keeps its proof for the rest of the collect epoch until `GuestMemory::BreakProofs` (a CPU write, a write-back, a recorded write) moves `ProofSerial`. Color metadata passes go through the pipeline with their write ranges (`PipelinedColorMetadataPassWrites`) instead of draining it. A data-only hit whose shape entry belongs to an older draw replaces that entry in place at the second sight of the same read user words. On Linux the main image's pages get a page table entry, and capture pages are pooled across threads. `APS5_VERIFY_DRAW_PIPELINE=1` runs a full check next to 1 in 64 reused proofs and prints `[epoch-proofs]` counts. -- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 4096 image slots per binding kind and 256 sampler slots, per-draw shader data and flattened SRT in a ring the shaders reach by address) instead of per-draw descriptor sets. Without the extension every stage takes the per-draw path. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; a stage stays GPU-mode only if its compiled module maps onto the heap and every stage of its draw is GPU-mode too; otherwise it is rebuilt on the per-draw path. A draw whose stages come out mixed is rebuilt once with what the first pass learned, and a stage pair that is still mixed takes the per-draw path from then on. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the heap ring and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap is recompiled on the per-dispatch path. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the heap ring per draw with its address in two more pushed dwords. Tables with image atomics index the heap too. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers by device address (`addressedBuffers`: four shader data words per buffer, 64-bit address and byte size, after the slot words) instead of storage buffer descriptors; a draw whose buffers are snapshotted gets its own copy of the words with the snapshot addresses. +- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 4096 image slots per binding kind and 2048 sampler slots, per-draw shader data and flattened SRT in a ring the shaders reach by address) instead of per-draw descriptor sets. Without the extension, or when the device's heaps cannot hold those slots, every stage takes the per-draw path. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; a stage stays GPU-mode only if its compiled module maps onto the heap and every stage of its draw is GPU-mode too; otherwise it is rebuilt on the per-draw path. A draw whose stages come out mixed is rebuilt once with what the first pass learned, and a stage pair that is still mixed takes the per-draw path from then on. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the heap ring and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap is recompiled on the per-dispatch path. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the heap ring per draw with its address in two more pushed dwords. Tables with image atomics index the heap too. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers by device address (`addressedBuffers`: four shader data words per buffer, 64-bit address and byte size, after the slot words) instead of storage buffer descriptors; a draw whose buffers are snapshotted gets its own copy of the words with the snapshot addresses. - The shader registry maps a code address to every header registered for that code, in registration order. Static, graphics and rectangle ABI resolution pick the header at the bound address (or one equal to it, `SameHeader`, which also takes a hull header fused by `sceAgcFuseShaderHalves` (type 3) as the registered back half (type 7) it copies, the fused registers aside; graphics ABI resolution then uses the fused header's shader registers); draws and dispatches pick the program by the stage's binary type (`RegisteredProgram`), and a front entry matching both type 2 and type 4 throws. Within a type the last registration wins; re-registering an identical earlier header makes its snapshot current again without preparing it again, and changed code drops the older headers. - The snapshot is published as pending. `SourceHandleFor`, `InvocationFor` and `ShaderPreparationTransaction::Edit` / `Read` wait for the pending job before reading `PreparedShaders`, and rethrow its failure. `APS5_SYNC_SHADER_PREPARE=1` prepares on the registering thread instead. - `APS5_LAZY_SHADER_PREPARE=1` retains registration validation and decoding but discards the temporary plan without queueing preparation. The snapshot is deferred, not pending; draws and dispatches prepare and cache it on first use. A compute or pixel stage's explicit ABI resolution (`ResolveShaderAbi`) plans the stage with the ABI's state, records the ABI and leaves its preparation to the shader's first use, which prepares it with that state (`PreparedShaders::deferredAbis`), so a shader that never draws or dispatches stays unprepared; a graphics-stage ABI is still prepared when it is resolved. This opt-in mode takes precedence over synchronous registration preparation and trades background CPU/memory use for possible first-use stalls; disk caches and shader output are unchanged. From a24ef5a95281f0eac9def1ec9e609a8031f8e18e Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 22 Oct 2026 07:01:24 +0530 Subject: [PATCH 025/269] test(agc): a draw whose fragment stage does not map onto the heap takes the per-draw path Co-Authored-By: Claude Opus 5.5 --- .../include/Driver/Draw/HeapStages.hpp | 2 + .../Execution/src/Driver/Draw/DrawCapture.cpp | 4 +- .../Execution/src/Driver/Draw/HeapStages.cpp | 14 ++++++ .../Graphics/include/BindlessHeap.hpp | 1 + .../Graphics/src/BindlessHeap.cpp | 4 ++ .../tests/execution/HeapDrawSample.cpp | 48 ++++++++++++++++++- 6 files changed, 69 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index 67df55b64290..0d6b1d28d2fa 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -22,6 +22,8 @@ bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompil std::optional HeapFragmentKnown(const void* snapshot, std::size_t codeOffset); void NoteHeapFragment(const void* snapshot, std::size_t codeOffset, bool eligible); bool HeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress = false); +void SetHeapStageUnmapped(std::optional stage); +bool HeapDrawStageMappable(const ShaderRecompiler::RecompileResult& result, ShaderRecompiler::ShaderStage stage); bool HeapPairRefused(std::uint64_t pair); void RefuseHeapPair(std::uint64_t pair); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 1927b97ac85f..2d7edbc06df4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -177,7 +177,7 @@ std::shared_ptr Driver::materializeDraw callCost.Stop(); Graphics::HeapCostScope finishCost(Graphics::HeapCost::StageFinish); if (direct == nullptr) goto heapCapture; - if (!HeapStageMappable(*direct)) return unmapped(); + if (!HeapDrawStageMappable(*direct, program.binary.stage)) return unmapped(); NoteHeapDirect(); stageCapture.compiled = std::move(direct); if (reusedWords != nullptr) words = std::const_pointer_cast(std::move(reusedWords)); @@ -283,7 +283,7 @@ std::shared_ptr Driver::materializeDraw throw named(error, request.context.memory); } } - if (stageCapture.compiled->gpuResolvedImages && !HeapStageMappable(*stageCapture.compiled)) return unmapped(); + if (stageCapture.compiled->gpuResolvedImages && !HeapDrawStageMappable(*stageCapture.compiled, program.binary.stage)) return unmapped(); stageCapture.capture = capture; timing.Mark("materialize"); const auto walked = capture->userDataUse.asValue | capture->userDataUse.asBase; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 7721dd365b3c..2abf962ea09b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -409,6 +409,20 @@ std::shared_ptr MaterializeHeapStage(co return nullptr; } +namespace { + +std::atomic unmappedStage{-1}; + +} + +void SetHeapStageUnmapped(std::optional stage) { + unmappedStage.store(stage.has_value() ? static_cast(*stage) : -1, std::memory_order_relaxed); +} + +bool HeapDrawStageMappable(const ShaderRecompiler::RecompileResult& result, ShaderRecompiler::ShaderStage stage) { + return unmappedStage.load(std::memory_order_relaxed) != static_cast(stage) && HeapStageMappable(result); +} + std::uint64_t HeapStagesTaken() { return heapStages().load(); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index e28a06e488c4..9fdd51683b25 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -163,6 +163,7 @@ enum class HeapStageReason : std::uint8_t { Heap, Disabled, PairRefused, Fragmen void NoteHeapStageReason(HeapStageReason reason); void NoteHeapRecord(bool compute, bool heap); void NoteHeapFallback(HeapFallback reason); +std::uint64_t HeapFallbacks(HeapFallback reason); void NoteCpuBufferCopy(std::uint64_t bytes); enum class HeapCost : std::uint8_t { StagePrepare, HeapStageCall, StageFinish, WalkMemo, Walk, Materialize, TemplateFind, TemplateBuild, Slots, StageData, BufferAddresses, MemoInsert, Guards, Count }; bool HeapCostTimed(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index eb5067568362..8db813a1498d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -866,6 +866,10 @@ void NoteHeapFallback(HeapFallback reason) { heapFallbacks[static_cast(reason)].fetch_add(1, std::memory_order_relaxed); } +std::uint64_t HeapFallbacks(HeapFallback reason) { + return heapFallbacks[static_cast(reason)].load(std::memory_order_relaxed); +} + void NoteCommandBufferBegun(VkCommandBuffer commands) { commandBuffersBegun.fetch_add(1, std::memory_order_relaxed); forgetHeapBinding(commands); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index 1dda02fc3a89..969a8d43eea2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -53,6 +54,8 @@ alignas(256) constexpr std::array TableVertexCode{ 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, }; alignas(256) std::array TableMemory{}; +alignas(256) std::array MixedVertexCode{}; +alignas(256) std::array MixedPixelCode{}; alignas(256) std::array MaterialMemory{}; alignas(256) std::array OtherTextureMemory{}; constexpr float BufferAlpha = 0.2f; @@ -89,9 +92,9 @@ void Append(std::vector& commands, std::uint32_t opcode, std::ini enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture }; -std::vector Draw(const std::uint32_t* pixelCode, Mode mode) { +std::vector Draw(const std::uint32_t* pixelCode, Mode mode, const std::uint32_t* vertexCode = nullptr) { const bool vertexSampling = mode == Mode::Vertex || mode == Mode::VertexTable; - const auto vertex = reinterpret_cast(mode == Mode::VertexTable ? TableVertexCode.data() : mode == Mode::Vertex ? SamplingVertexCode.data() : VertexCode.data()); + const auto vertex = reinterpret_cast(vertexCode != nullptr ? vertexCode : mode == Mode::VertexTable ? TableVertexCode.data() : mode == Mode::Vertex ? SamplingVertexCode.data() : VertexCode.data()); const auto pixel = reinterpret_cast(pixelCode); const auto color = reinterpret_cast(ColorMemory.data()); const auto texture = static_cast(reinterpret_cast(TextureMemory.data())); @@ -225,6 +228,46 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { if (heap && descriptorMemory) Require(AgcDriver::Graphics::DataAddressPushes() > pushesBefore, "the heap stages did not read their shader data through pushed addresses"); } +void MixedDrawTakesThePerDrawPath() { + using AgcDriver::Graphics::HeapFallback; + using AgcDriver::Graphics::HeapFallbacks; + MixedVertexCode = SamplingVertexCode; + MixedPixelCode = InterpolantPixelCode; + for (std::size_t offset = 0; offset < TextureMemory.size(); offset += Texel.size()) std::memcpy(TextureMemory.data() + offset, Texel.data(), Texel.size()); + Registered(PixelHeader, MixedPixelCode.data(), sizeof(MixedPixelCode), 1); + { + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + auto commands = Draw(MixedPixelCode.data(), Mode::Texture); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw putting the fragment stage on the heap failed"); + AgcDriverWaitIdle_nid_postfix(); + Registered(VertexHeader, MixedVertexCode.data(), sizeof(MixedVertexCode), 2); + } + AgcDriver::DriverDetail::SetHeapStageUnmapped(ShaderRecompiler::ShaderStage::Fragment); + for (const char* draw : {"first", "repeated"}) { + const auto takenBefore = AgcDriver::DriverDetail::HeapStagesTaken(); + const auto retriesBefore = HeapFallbacks(HeapFallback::DrawMixedRetry); + const auto refusedBefore = HeapFallbacks(HeapFallback::DrawRefusedPair); + ColorMemory.fill(Kept); + auto commands = Draw(MixedPixelCode.data(), Mode::Vertex, MixedVertexCode.data()); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, std::string("the ") + draw + " mixed draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); + std::size_t drawn = 0; + for (std::size_t offset = 0; offset < ColorMemory.size(); offset += 4) { + if (std::all_of(ColorMemory.begin() + static_cast(offset), ColorMemory.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) continue; + for (std::size_t channel = 0; channel < 4; ++channel) Require(static_cast(ColorMemory[offset + channel]) == Texel[channel], std::string("the ") + draw + " mixed draw: pixel " + std::to_string(offset / 4) + " channel " + std::to_string(channel) + " is " + std::to_string(static_cast(ColorMemory[offset + channel])) + ", expected " + std::to_string(Texel[channel])); + ++drawn; + } + Require(drawn != 0, std::string("the ") + draw + " mixed draw covered no pixel"); + const bool first = std::strcmp(draw, "first") == 0; + if (first) Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, "the heap did not take the vertex stage of the mixed draw"); + Require(HeapFallbacks(HeapFallback::DrawMixedRetry) - retriesBefore == (first ? 1u : 0u), std::string("the ") + draw + " mixed draw retried on the per-draw path " + std::to_string(HeapFallbacks(HeapFallback::DrawMixedRetry) - retriesBefore) + " times, expected " + (first ? "once" : "never")); + Require(HeapFallbacks(HeapFallback::DrawRefusedPair) == refusedBefore, std::string("the ") + draw + " mixed draw stayed mixed after its per-draw retry"); + } + AgcDriver::DriverDetail::SetHeapStageUnmapped(std::nullopt); +} + } int main() { @@ -251,6 +294,7 @@ int main() { DrawSamplesTheTexture(heap, Mode::MovedBuffer); DrawSamplesTheTexture(heap, Mode::MovedTexture); DrawSamplesTheTexture(heap, Mode::Texture); + if (heap && AgcDriver::Graphics::DescriptorHeapEnabled() && std::getenv("APS5_HEAP_SLOT_CAP") == nullptr) MixedDrawTakesThePerDrawPath(); if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) Require(AgcDriver::DriverDetail::HeapRefused(), "a draw found the capped heap full and the heap was not refused"); AgcDriverShutdown_nid_postfix(); if (heap && AgcDriver::Graphics::DescriptorHeapEnabled() && std::getenv("APS5_HEAP_SLOT_CAP") == nullptr) Require(AgcDriver::Graphics::EmptyResourceSets() != 0, "no heap draw bound without a per-draw resource set"); From eb7b736f4f232f6a4e94e19e598c1646baf2a7cd Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 22 Oct 2026 07:56:17 +0530 Subject: [PATCH 026/269] fix(agc): rebind the descriptor heaps after push constants put a command buffer back in classic descriptor mode Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/PerformanceOverlay.cpp | 3 ++- .../Execution/src/PresentationPass.cpp | 2 +- .../libSceAgcDriver/Execution/src/VulkanDevice.cpp | 2 +- .../Graphics/include/BindlessHeap.hpp | 1 + .../libSceAgcDriver/Graphics/include/Recorder.hpp | 1 - .../libSceAgcDriver/Graphics/src/BindlessHeap.cpp | 5 +++++ .../Graphics/src/GpuColorTransfer.cpp | 2 +- .../Graphics/src/MultisampleReadback.cpp | 5 +++-- .../Graphics/src/MultisampleUpload.cpp | 5 +++-- .../prx/libSceAgcDriver/Graphics/src/Pipeline.cpp | 6 +++--- .../prx/libSceAgcDriver/Graphics/src/Recorder.cpp | 9 ++++----- .../prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp | 9 +++++---- .../libSceAgcDriver/Graphics/src/TextureDetiler.cpp | 12 ++++++------ 13 files changed, 35 insertions(+), 27 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceOverlay.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceOverlay.cpp index ca74a794d9d7..3ba5c52bf157 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceOverlay.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceOverlay.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceOverlay.hpp" #include "prx/libSceAgcDriver/Execution/include/Presentation.hpp" #include "prx/libSceAgcDriver/Execution/include/PqToSdr.hpp" @@ -769,7 +770,7 @@ OverlayRect PerformanceOverlay::Record(VkCommandBuffer commands, std::size_t ind context.Function("vkCmdSetViewport")(commands, 0, 1, &viewport); context.Function("vkCmdSetScissor")(commands, 0, 1, &area); const OverlayParameters parameters{OverlayPalette(format, colorSpace), {static_cast(extent.width), static_cast(extent.height)}}; - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), ¶meters); + Graphics::CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), ¶meters); const VkBuffer buffer = slot.rects->Handle(); const VkDeviceSize offset = 0; context.Function("vkCmdBindVertexBuffers")(commands, 0, 1, &buffer, &offset); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp index c3591be558da..901af9230200 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp @@ -329,7 +329,7 @@ void PresentationPass::draw(VkCommandBuffer commands, Slot& slot, const Target& context.Function("vkCmdPushDataEXT")(commands, &data); } else { Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &slot.set, Graphics::SetBindSite::Presentation); - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), parameters); + Graphics::CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), parameters); } context.Function("vkCmdDraw")(commands, 3, 1, 0, 0); context.Function("vkCmdEndRenderPass")(commands); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 22ae09ac37e0..fc17d90bc204 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -5177,7 +5177,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { const VkPushDataInfoEXT push{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {pushed.data(), pushed.size()}}; context.Function("vkCmdPushDataEXT")(commands, &push); } else { - context.Resolved(&Graphics::DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, record.objects->layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, Graphics::ComputePushConstantBytes, pushed.data()); + Graphics::CmdPushConstants(context, commands, record.objects->layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, Graphics::ComputePushConstantBytes, pushed.data()); } } const auto gpuTiming = recorder.BeginGpuTiming(record.programAddress != 0 ? record.programAddress : record.shader->program->variantId); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 9fdd51683b25..decce0fe3c22 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -185,6 +185,7 @@ class HeapCostScope { std::chrono::steady_clock::time_point start; }; void NoteCommandBufferBegun(VkCommandBuffer commands); +void CmdPushConstants(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, std::uint32_t size, const void* values); void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site); std::uint64_t DescriptorHeapBinds(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index 81a89e117d69..468759f65089 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -757,7 +757,6 @@ class Recorder { PFN_vkCmdResetQueryPool cmdResetQueryPool = nullptr; PFN_vkCmdCopyQueryPoolResults cmdCopyQueryPoolResults = nullptr; PFN_vkCmdBindPipeline cmdBindPipeline = nullptr; - PFN_vkCmdPushConstants cmdPushConstants = nullptr; PFN_vkCmdDispatch cmdDispatch = nullptr; template TFunction function(TFunction resolved, const char* name) const { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 8db813a1498d..92384eba9a80 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -875,6 +875,11 @@ void NoteCommandBufferBegun(VkCommandBuffer commands) { forgetHeapBinding(commands); } +void CmdPushConstants(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, std::uint32_t size, const void* values) { + context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, stages, offset, size, values); + forgetHeapBinding(commands); +} + void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site) { context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, bindPoint, layout, firstSet, setCount, sets, 0, nullptr); setBinds[static_cast(site)].fetch_add(1, std::memory_order_relaxed); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp index 64fe19a8c884..690654ab9985 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp @@ -149,7 +149,7 @@ void GpuColorTransfer::dispatch(VkCommandBuffer commands, bool toTiled, bool swa const std::array push{width, height, (width + 127u) / 128u, (toTiled ? 1u : 0u) | (swapRedBlue ? 2u : 0u) | (tiledSource ? 4u : 0u) | (tenBit ? 8u : 0u) | (halfFloat ? 16u : 0u) | (pqWhiteNits ? 32u : 0u), std::bit_cast(pqWhiteNits.value_or(0.0f))}; context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &descriptorSet, SetBindSite::ColorTransfer); - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); + CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); context.Function("vkCmdDispatch")(commands, (width + 7u) / 8u, (height + 7u) / 8u, 1); VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleReadback.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleReadback.cpp index fe92fa1b979a..37125033c923 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleReadback.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleReadback.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/MultisampleReadbackUint_spv.h" @@ -97,9 +98,9 @@ void TextureDetiler::DispatchMultisampleReadback(VkCommandBuffer commands, VkFor }}; context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0u, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, readbackPipelineLayout, 0u, 1u, &set, 0u, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, readbackPipelineLayout, 0u, 1u, &set, SetBindSite::ColorTransfer); const std::array push{width, height, layers, fragments, firstElement, elements, static_cast(groupsX * 64u)}; - context.Function("vkCmdPushConstants")(commands, readbackPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(push), push.data()); + CmdPushConstants(context, commands, readbackPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(push), push.data()); context.Function("vkCmdDispatch")(commands, static_cast(groupsX), static_cast(groupsY), 1u); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleUpload.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleUpload.cpp index 419ed7648e38..ca9f2fd37edb 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleUpload.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleUpload.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/MultisampleUpload_spv.h" #include @@ -59,9 +60,9 @@ void TextureDetiler::DispatchMultisampleImage(VkCommandBuffer commands, std::uin const std::array writes{{{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, set, 0u, 0u, 1u, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, nullptr, &buffer, nullptr}, {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, set, 1u, 0u, 1u, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &image, nullptr, nullptr}}}; context.Function("vkUpdateDescriptorSets")(context.device, 2u, writes.data(), 0u, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0u, 1u, &set, 0u, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0u, 1u, &set, SetBindSite::ColorTransfer); const std::array push{width, height, layers, fragments, firstElement, elements, static_cast(groupsX * 64u)}; - context.Function("vkCmdPushConstants")(commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(push), push.data()); + CmdPushConstants(context, commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(push), push.data()); context.Function("vkCmdDispatch")(commands, static_cast(groupsX), static_cast(groupsY), 1u); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index fa6f4bf2cf7c..47e61cfade5c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -1003,11 +1003,11 @@ void Pipeline::PushConstants(VkCommandBuffer commands, VkShaderStageFlags stages return; } if (dynamicRendering) { - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, pushStagesOf(context), 0, PipelinePushSlotBytes, bytes.data()); - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, VK_SHADER_STAGE_FRAGMENT_BIT, PipelinePushSlotBytes, PipelinePushSlotBytes, bytes.data() + PipelinePushSlotBytes); + CmdPushConstants(context, commands, layout, pushStagesOf(context), 0, PipelinePushSlotBytes, bytes.data()); + CmdPushConstants(context, commands, layout, VK_SHADER_STAGE_FRAGMENT_BIT, PipelinePushSlotBytes, PipelinePushSlotBytes, bytes.data() + PipelinePushSlotBytes); return; } - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, stages, 0, PipelinePushSlotBytes, bytes.data()); + CmdPushConstants(context, commands, layout, stages, 0, PipelinePushSlotBytes, bytes.data()); } namespace { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index c75c62e7e686..c6418b1efad2 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -1178,7 +1178,6 @@ Recorder::Recorder(const Context& context, bool timelineSemaphores) : context(co cmdResetQueryPool = context.Function("vkCmdResetQueryPool"); cmdCopyQueryPoolResults = context.Function("vkCmdCopyQueryPoolResults"); cmdBindPipeline = context.Function("vkCmdBindPipeline"); - cmdPushConstants = context.Function("vkCmdPushConstants"); cmdDispatch = context.Function("vkCmdDispatch"); } if (!timelineSemaphores) return; @@ -2112,7 +2111,7 @@ bool Recorder::RecordDispatchArguments(VkCommandBuffer commands, VkDeviceAddress } parameters{source, arguments, {limit[0], limit[1], limit[2], threadGroup != nullptr ? 1u : 0u}, {1u, 1u, 1u, 0u}}; if (threadGroup != nullptr) std::copy(threadGroup->begin(), threadGroup->end(), parameters.group.begin()); static_assert(sizeof(parameters) == PushBytes); - function(cmdPushConstants, "vkCmdPushConstants")(commands, dispatchArgumentLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); + CmdPushConstants(context, commands, dispatchArgumentLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, 1, 1, 1); const VkPipelineStageFlags readers = VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | (threadGroup != nullptr ? VK_PIPELINE_STAGE_TRANSFER_BIT : 0u); const VkAccessFlags reads = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | (threadGroup != nullptr ? VK_ACCESS_TRANSFER_READ_BIT : 0u); @@ -2424,7 +2423,7 @@ void Recorder::dispatchDumps(VkCommandBuffer commands, std::uint32_t firstDump, std::uint32_t phase; } parameters{sampleCounter->DeviceAddress(), sampleCounter->DeviceAddress() + DumpListOffset, firstDump, dumps, firstSegment, lastSegment, 0u}; static_assert(sizeof(parameters) == SampleDumpPushBytes); - const auto push = function(cmdPushConstants, "vkCmdPushConstants"); + const auto push = [&](VkCommandBuffer target, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, std::uint32_t size, const void* values) { CmdPushConstants(context, target, layout, stages, offset, size, values); }; const auto dispatch = function(cmdDispatch, "vkCmdDispatch"); push(commands, dumpLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleDumpPushBytes, ¶meters); dispatch(commands, 1, 1, 1); @@ -2475,7 +2474,7 @@ void Recorder::foldSamples(Batch& batch, VkDeviceAddress target) { const auto commands = batch.commands; const auto copy = function(cmdCopyQueryPoolResults, "vkCmdCopyQueryPoolResults"); const auto bind = function(cmdBindPipeline, "vkCmdBindPipeline"); - const auto push = function(cmdPushConstants, "vkCmdPushConstants"); + const auto push = [&](VkCommandBuffer target, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, std::uint32_t size, const void* values) { CmdPushConstants(context, target, layout, stages, offset, size, values); }; const auto dispatch = function(cmdDispatch, "vkCmdDispatch"); std::size_t done = 0; do { @@ -2587,7 +2586,7 @@ bool Recorder::RecordMeshArguments(VkCommandBuffer commands, VkDeviceAddress rec std::array rules; } parameters{record, arguments, {rules[0], rules[1], rules[2], rules[3], rules[4], rules[5], rules[6], 0u}}; static_assert(sizeof(parameters) == PushBytes); - function(cmdPushConstants, "vkCmdPushConstants")(commands, meshArgumentLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); + CmdPushConstants(context, commands, meshArgumentLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, 1, 1, 1); recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_MESH_SHADER_BIT_EXT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_SHADER_READ_BIT); CountBarriers(CommandClass::Draw, 2); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp index 647b38274cc6..3fafb3ee6c18 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" @@ -175,8 +176,8 @@ class SampleOrders { context.Function("vkUpdateDescriptorSets")(context.device, 1, &write, 0, nullptr); const StoragePush push{map, {region.width, region.height}, target.samples}; context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, storagePipelineLayout, 0, 1, &set, 0, nullptr); - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, storagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, storagePipelineLayout, 0, 1, &set, SetBindSite::Detiler); + CmdPushConstants(context, commands, storagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, ((region.width + 1u) / 2u + 7u) / 8u, ((region.height + 1u) / 2u + 7u) / 8u, 1); } @@ -244,13 +245,13 @@ class SampleOrders { const VkRect2D scissor{{0, 0}, region}; context.Resolved(&DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, 1, &viewport); context.Resolved(&DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, 1, &scissor); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, sampledPipelineLayout, 0, 1, &set, 0, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, sampledPipelineLayout, 0, 1, &set, SetBindSite::Detiler); const auto draw = [&](VkPipeline pipeline, std::uint32_t bit, std::uint32_t writeMask, std::uint32_t reference) { context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); context.Resolved(&DeviceFunctions::cmdSetStencilWriteMask, "vkCmdSetStencilWriteMask")(commands, VK_STENCIL_FACE_FRONT_AND_BACK, writeMask); context.Resolved(&DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference")(commands, VK_STENCIL_FACE_FRONT_AND_BACK, reference); const DepthPush push{map, bit}; - context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, sampledPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push), &push); + CmdPushConstants(context, commands, sampledPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push), &push); context.Resolved(&DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, 3, 1, 0, 0); }; draw(pass.depth, 0u, 0xffu, 0u); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index 4ca992597fb1..b2b7c740eb5c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -375,9 +375,9 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode push.pipeBankXor = window.pipeBankXor; if (addressed) { const AddressedPush pushed{push, sourceAddress + sourceDescriptorOffset, destinationAddress + destinationDescriptorOffset}; - context.Function("vkCmdPushConstants")(commands, addressedPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pushed), &pushed); + CmdPushConstants(context, commands, addressedPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pushed), &pushed); } else { - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); + CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); } const auto groupsX = (columnEnd - window.columnBegin + 7u) / 8u; const auto groupsY = (rowEnd - window.rowBegin + 7u) / 8u; @@ -430,7 +430,7 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s } const AddressedRepackPush pushed{repackPush, sourceAddress + sourceDescriptorOffset, destinationAddress + destinationDescriptorOffset}; context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, addressedRepackPipeline); - context.Function("vkCmdPushConstants")(commands, addressedRepackLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pushed), &pushed); + CmdPushConstants(context, commands, addressedRepackLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pushed), &pushed); context.Function("vkCmdDispatch")(commands, static_cast((std::min(words, rowWords) + 63u) / 64u), static_cast(rows), 1); return; } @@ -449,7 +449,7 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, repackPipeline); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, SetBindSite::Detiler); - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(repackPush), repackPush.data()); + CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(repackPush), repackPush.data()); context.Function("vkCmdDispatch")(commands, static_cast((std::min(words, rowWords) + 63u) / 64u), static_cast(rows), 1); } @@ -559,7 +559,7 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask } else { context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipeline); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipelineLayout, 0, 1, &set, SetBindSite::Detiler); - context.Function("vkCmdPushConstants")(commands, cmaskPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); + CmdPushConstants(context, commands, cmaskPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); } context.Function("vkCmdDispatch")(commands, (width + 7u) / 8u, (height + 7u) / 8u, 1); barrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT, anyAccess); @@ -631,7 +631,7 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0, 1, &set, SetBindSite::Detiler); - context.Function("vkCmdPushConstants")(commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); + CmdPushConstants(context, commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); } const auto groupsX = (columnEnd - window.columnBegin + 7u) / 8u; const auto groupsY = (rowEnd - window.rowBegin + 7u) / 8u; From a3a04de99852e9280efce7c136e63543c12d6673 Mon Sep 17 00:00:00 2001 From: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> Date: Thu, 22 Oct 2026 05:12:17 +0000 Subject: [PATCH 027/269] test(agc): skip the GPU heap draw and journal tests without a descriptor heap agc_driver_heap_draw_sample_heap, _nogpl_heap, _full_heap and _full_heap_pipelined, and agc_driver_pipeline_journal_gpu_heap set APS5_GPU_HEAP and then require the heap to take the draw's stages, to refuse a capped heap or to put a compute stage in GPU mode. On a device where DescriptorHeapEnabled() stays false (no VK_EXT_descriptor_heap, or one without maintenance5, room for the heap's slots or enough push data) none of that can happen, and they failed instead of skipping. They now exit 77 with a "skipped, the device lacks VK_EXT_descriptor_heap, ..." line there, and run as before on a device with the heap. (cherry picked from commit 0a0134070212ef8c0240b81d41fb1f936e61e44a) --- .../prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp | 4 ++++ .../prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index 969a8d43eea2..6740ccae09ad 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -278,6 +278,10 @@ int main() { if (!device) return VulkanTestSkipped; } const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; + if (heap && !AgcDriver::Graphics::DescriptorHeapEnabled()) { + std::cout << "skipped, the device lacks VK_EXT_descriptor_heap, or the maintenance5, slot room and push data the GPU heap needs with it, so APS5_GPU_HEAP has no heap to draw through\n"; + return VulkanTestSkipped; + } { GuestAllocations::Mutation mutation; mutation.Add(StorageMemory.data(), StorageMemory.size(), true, true, true); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp index e1c84b912b70..49f89383b2ff 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp @@ -782,6 +782,10 @@ int main(int argc, char** argv) { return 0; } if (argc >= 2 && std::string(argv[1]) == "--gpu-heap") { + if (AgcDriver::Graphics::GpuHeapEnabled() && !AgcDriver::Graphics::DescriptorHeapEnabled()) { + std::puts("skipped, the device lacks VK_EXT_descriptor_heap, or the maintenance5, slot room and push data the GPU heap needs with it, so no compute stage can run in GPU mode to record"); + return VulkanTestSkipped; + } HeapJournalTests(); std::puts("pipeline journal record and replay of a GPU-mode compute stage passed"); return 0; From ece08c894b284155e71a57162657e6314cbaf395 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 23 Oct 2026 04:44:06 +0530 Subject: [PATCH 028/269] fix(agc): keep GPU heap pipelines in their own journal A run with APS5_GPU_HEAP recorded its pipelines in the same journal as a run without it, so each mode replayed the other's records: those failed at the pipeline layout check, and they took places in the replay limit. Co-Authored-By: Claude Opus 5.5 --- .../prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp | 6 ++++-- .../prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp | 2 ++ docs/dev/ARCHITECTURE.md | 2 +- docs/user/USAGE.md | 2 +- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp index 7eba2c79ac3a..3e8059cfea8f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/PipelineJournal.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libc/include/HostThreadLocal.hpp" @@ -866,8 +867,9 @@ class Journal { if (error) throw std::filesystem::filesystem_error("cannot resolve the pipeline journal directory", directory, error); directory = native; #endif - path = directory / "pipelines.journal"; - lockPath = directory / "pipelines.journal.lock"; + const std::string name = GpuHeapEnabled() ? "pipelines-heap.journal" : "pipelines.journal"; + path = directory / name; + lockPath = directory / (name + ".lock"); maxBytes = configured("APS5_PIPELINE_JOURNAL_MAX_MIB", 1024u) << 20u; std::thread([this] { run(); }).detach(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp index 49f89383b2ff..af567ecfcb14 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp @@ -330,6 +330,7 @@ void HeapJournalTests() { Require(device->ComputePipelinesCreated() == 1, "the first run did not build exactly one compute pipeline"); AgcDriver::Graphics::FlushPipelineJournal(); Require(Snapshot().journal.recordedCompute == 1, "the first run did not record the GPU-mode compute pipeline"); + Require(AgcDriver::Graphics::PipelineJournalPath().filename() == "pipelines-heap.journal", "the GPU-mode pipelines were recorded in the journal the per-draw binding model replays"); } { const auto device = OpenVulkanTestDevice(); @@ -348,6 +349,7 @@ void JournalTests() { using namespace NarrowConstantStoreFixture; Require(AgcDriver::Graphics::PipelineJournalEnabled(), "the pipeline journal is disabled although the shader cache directory is set"); const auto journalPath = AgcDriver::Graphics::PipelineJournalPath(); + Require(journalPath.filename() == (AgcDriver::Graphics::GpuHeapEnabled() ? "pipelines-heap.journal" : "pipelines.journal"), "the pipeline journal file does not match the GPU heap mode"); Block compute(BlockBytes); Block target(ColorTargetLayout(Width, Height, ColorTileMode::Linear, 2).Bytes()); const auto computeCode = ComputeCode(0); diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index bc90f3157c9a..d66c2da8b2e6 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -124,7 +124,7 @@ flowchart LR - [`Recompiler.cpp`](../../core/shader/recompiler/Recompiler.cpp) runs the stages in this order. With `ANYPS5_ENABLE_SPIRV_TOOLS`, the SPIR-V is also validated and optimized with SPIRV-Tools. - `ShaderRecompiler::Recompile` keeps compiled variants in memory, and `ShaderDiskCache` stores them on disk so later runs reuse them. Before the writable cache, a miss is also looked up in read-only prebuilt packs and loose entry folders under `shader_cache/prebuilt`; pack entries are ordinary encoded cache entries behind a sorted key-hash index, validated by magic, compiler source version and index checksum when mapped, and a miss or rejected entry falls through to the writable cache and the compiler. Cache format 35 also stores the finite stencil-reference set, its replay-safety proof and reserved push-data word in the artifact and binding layouts. Entries from formats 31 to 34 are rejected. -- The Vulkan pipelines are journaled as well ([`PipelineJournal.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp)): a graphics pipeline the store builds (`CachedPipeline`) or a compute pipeline a dispatch builds is appended to `pipelines.journal` next to the shader cache entries, as the materialized result of each stage (the specialized SPIR-V, bindings and push constants, through `ShaderDiskCache::EncodeResult`) plus the recipe the pipeline was built from (`GraphicsPipelineRecipe`: the stages' identities, vertex input layout, descriptor set layout keys and the state fields the `Pipeline` constructor reads, `CanonicalPipelineState`). When a `VulkanDevice` is created, the journal is loaded and its pipelines are built on a pool of `hardware_concurrency() / 2` threads (`APS5_PIPELINE_JOURNAL_THREADS`) while the title loads. The load parses the file a record at a time and keeps it open, and a replay thread reads an entry's modules from it when it builds that entry (a record that no longer reads back as loaded rejects the entry), so the replay holds the modules of the entries being built rather than the file, so the first draw or dispatch of a configuration seen on an earlier run finds its pipeline resident. The pipeline stores key on `RecompileResult::Identity`, a hash of the module words, specialization constants, subgroup width and bindings that is the same on every run (`SharedSpirv::ContentHash`, computed once per shared module), rather than on the process-lifetime variant ids, and a graphics pipeline is built outside the store's mutex, so the replay threads and the queue workers build in parallel. A draw that arrives before its replayed entry builds the pipeline itself; the first inserted wins. A replayed entry enters the store at its least recently used end and a full store takes none, so the title's own pipelines are never evicted for a replayed one, and the optimized relink of a replayed pipeline (`OptimizedPipeline::Schedule`) waits for the first draw that binds it, so the relink thread serves the title's pipelines first. A device created without a window starts its replay at its first draw or dispatch rather than at creation, since `Driver::AttachWindow` usually replaces it before the title draws. The journal records a pipeline once (modules and recipes are deduplicated by content), keeps at most `APS5_PIPELINE_JOURNAL_MAX_MIB` (1024), replays the first `APS5_PIPELINE_JOURNAL_ENTRIES` recorded (1024, the pipeline store's bound, `APS5_PIPELINE_STORE_ENTRIES`; a run reaches those first), and is disabled with `APS5_NO_PIPELINE_JOURNAL=1` or without a shader cache directory. The file header names the device (`PipelineJournalDeviceFingerprint`, the properties the driver's pipeline cache file is named by), so a journal written for another GPU or driver is started over rather than replayed; appends and reads hold `pipelines.journal.lock` against another process sharing the directory, and a device cancels its replay before it is replaced (`PrepareForReplacement`) or destroyed, so a replaced headless device never inserts entries the window's device then sweeps. `APS5_PROFILE_DRAW=1` prints a `[pipeline-journal]` summary when the replay finishes and at teardown. +- The Vulkan pipelines are journaled as well ([`PipelineJournal.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp)): a graphics pipeline the store builds (`CachedPipeline`) or a compute pipeline a dispatch builds is appended to `pipelines.journal` (`pipelines-heap.journal` under `GpuHeapEnabled`, so the two binding models never replay each other's pipelines) next to the shader cache entries, as the materialized result of each stage (the specialized SPIR-V, bindings and push constants, through `ShaderDiskCache::EncodeResult`) plus the recipe the pipeline was built from (`GraphicsPipelineRecipe`: the stages' identities, vertex input layout, descriptor set layout keys and the state fields the `Pipeline` constructor reads, `CanonicalPipelineState`). When a `VulkanDevice` is created, the journal is loaded and its pipelines are built on a pool of `hardware_concurrency() / 2` threads (`APS5_PIPELINE_JOURNAL_THREADS`) while the title loads. The load parses the file a record at a time and keeps it open, and a replay thread reads an entry's modules from it when it builds that entry (a record that no longer reads back as loaded rejects the entry), so the replay holds the modules of the entries being built rather than the file, so the first draw or dispatch of a configuration seen on an earlier run finds its pipeline resident. The pipeline stores key on `RecompileResult::Identity`, a hash of the module words, specialization constants, subgroup width and bindings that is the same on every run (`SharedSpirv::ContentHash`, computed once per shared module), rather than on the process-lifetime variant ids, and a graphics pipeline is built outside the store's mutex, so the replay threads and the queue workers build in parallel. A draw that arrives before its replayed entry builds the pipeline itself; the first inserted wins. A replayed entry enters the store at its least recently used end and a full store takes none, so the title's own pipelines are never evicted for a replayed one, and the optimized relink of a replayed pipeline (`OptimizedPipeline::Schedule`) waits for the first draw that binds it, so the relink thread serves the title's pipelines first. A device created without a window starts its replay at its first draw or dispatch rather than at creation, since `Driver::AttachWindow` usually replaces it before the title draws. The journal records a pipeline once (modules and recipes are deduplicated by content), keeps at most `APS5_PIPELINE_JOURNAL_MAX_MIB` (1024), replays the first `APS5_PIPELINE_JOURNAL_ENTRIES` recorded (1024, the pipeline store's bound, `APS5_PIPELINE_STORE_ENTRIES`; a run reaches those first), and is disabled with `APS5_NO_PIPELINE_JOURNAL=1` or without a shader cache directory. The file header names the device (`PipelineJournalDeviceFingerprint`, the properties the driver's pipeline cache file is named by), so a journal written for another GPU or driver is started over rather than replayed; appends and reads hold the file's `.lock` against another process sharing the directory, and a device cancels its replay before it is replaced (`PrepareForReplacement`) or destroyed, so a replaced headless device never inserts entries the window's device then sweeps. `APS5_PROFILE_DRAW=1` prints a `[pipeline-journal]` summary when the replay finishes and at teardown. - A compute shader whose LDS plus its lock dword exceeds the host's `maxComputeSharedMemorySize` is not given a `Workgroup` array. `Recompile` sets `ShaderInfo::sharedMemoryBytes` for it and the SPIR-V backend addresses the LDS in a coherent storage buffer at descriptor set 1 (`WorkgroupMemoryDescriptorSet`), with a slice of `RecompileResult::workgroupMemoryDwords` per workgroup, indexed by `WorkgroupID` and `NumWorkGroups`. `VulkanDevice` keeps one such buffer, sized from the dispatch dimensions, and binds it after the resource set; programs that fit keep using shared memory. - `Driver::RegisterShader` splits shader preparation in two. `PlanRegistered` runs on the registering guest thread: it validates the registers and entry point, decodes the code and builds the recompile request, so invalid registrations still fail there. The RDNA to IR translation and resource plan (`PrepareShader`) run on a background pool of `hardware_concurrency() / 2` detached threads (at least 2, 64 MiB stacks). - A thread that needs the GPU mutex, the committer's next item or the end of the committer's queue spins before it blocks (`HandoffSpin.hpp`): `GpuMutexType::lock` retries `try_lock` for the window, the committer polls its item count, and `DrawPipeline::Drain` polls it for twice the window, so a hand-off that completes within the window costs no kernel wake-up. The window is 150 us when the process may run on more than 8 logical processors (its affinity mask, via `CpuTopology`) and 0 otherwise, where the spinning threads would compete with the holder; `APS5_HANDOFF_SPIN_US=` sets it (0 turns it off, at most 10000). Ordering and the lock's semantics are unchanged. diff --git a/docs/user/USAGE.md b/docs/user/USAGE.md index 834ac26dadc6..8ba7ca8dd7ae 100644 --- a/docs/user/USAGE.md +++ b/docs/user/USAGE.md @@ -318,7 +318,7 @@ Recompiled shaders and the Vulkan pipeline cache are kept in a `shader_cache/` d ### Pipeline journal -Besides the recompiled shaders, the shader cache directory holds `pipelines.journal`: every Vulkan graphics pipeline the pipeline store kept and every compute pipeline a run built, with the specialized shader modules they were built from. The next run of the title builds those pipelines on background threads while it loads, so a draw or dispatch the earlier run already made does not compile its pipeline when it is first reached. The journal belongs to the GPU and driver that wrote it, like the driver's pipeline cache file next to it: a run on another GPU or driver version starts it over, and the driver's own pipeline cache decides how fast each pipeline is rebuilt. Two runs sharing the directory take turns on `pipelines.journal.lock`; a run that cannot lock it records nothing. `APS5_NO_PIPELINE_JOURNAL=1` disables recording and replay; `APS5_PIPELINE_JOURNAL_THREADS` sets the replay threads (half the CPU threads by default; `0` records without replaying), `APS5_PIPELINE_JOURNAL_ENTRIES` how many pipelines are replayed (the first recorded, which a run reaches first) and `APS5_PIPELINE_STORE_ENTRIES` how many graphics pipelines stay resident (1024 each), and `APS5_PIPELINE_JOURNAL_MAX_MIB` (1024) the file size at which recording stops. Deleting the file loses nothing but the head start. With `APS5_PROFILE_DRAW=1` a `[pipeline-journal]` line reports what was loaded, replayed and recorded. +Besides the recompiled shaders, the shader cache directory holds `pipelines.journal` (`pipelines-heap.journal` with `APS5_GPU_HEAP`, whose pipelines differ): every Vulkan graphics pipeline the pipeline store kept and every compute pipeline a run built, with the specialized shader modules they were built from. The next run of the title builds those pipelines on background threads while it loads, so a draw or dispatch the earlier run already made does not compile its pipeline when it is first reached. The journal belongs to the GPU and driver that wrote it, like the driver's pipeline cache file next to it: a run on another GPU or driver version starts it over, and the driver's own pipeline cache decides how fast each pipeline is rebuilt. Two runs sharing the directory take turns on the file's `.lock`; a run that cannot lock it records nothing. `APS5_NO_PIPELINE_JOURNAL=1` disables recording and replay; `APS5_PIPELINE_JOURNAL_THREADS` sets the replay threads (half the CPU threads by default; `0` records without replaying), `APS5_PIPELINE_JOURNAL_ENTRIES` how many pipelines are replayed (the first recorded, which a run reaches first) and `APS5_PIPELINE_STORE_ENTRIES` how many graphics pipelines stay resident (1024 each), and `APS5_PIPELINE_JOURNAL_MAX_MIB` (1024) the file size at which recording stops. Deleting the file loses nothing but the head start. With `APS5_PROFILE_DRAW=1` a `[pipeline-journal]` line reports what was loaded, replayed and recorded. ### Draw pipeline From b744510fdff9e059ac65b2d65ece8c45f239e5df Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 23 Oct 2026 21:33:54 +0530 Subject: [PATCH 029/269] fix(agc): keep GLC buffer accesses coherent through buffer addresses With the descriptor heap on, buffers are reached through buffer addresses, which have no Coherent buffer array and no 64-bit view. GLC loads and stores became plain 32-bit accesses, so a compute shader that polls a queue slot another workgroup writes never saw the write and the GPU hung (RoboCop: Rogue City at the splash, Xid 109). GLC dword accesses through a buffer address are now device-scope atomic loads and stores, and GLC two-dword accesses use one 64-bit atomic as the storage-buffer path does. Co-Authored-By: Claude Opus 5.5 --- .../libSceAgcDriver/tests/ShaderMemory.cpp | 64 +++++++++++++++++++ .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 9 ++- 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 23ebff9faf57..26509ce2e54d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -39,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -6703,6 +6704,68 @@ void verifyCoherentBufferAccesses() { require(only(invalidated.loads, "buffers") && only(invalidated.stores, "buffers"), "coherent buffers: a program that invalidates the vector caches does not use the coherent buffer array"); } +void verifyAddressedCoherentBufferAccesses() { + using namespace ShaderRecompiler; + alignas(256) static std::array input{}; + alignas(256) static std::array output{}; + const auto inputAddress = static_cast(reinterpret_cast(input.data())); + const auto outputAddress = static_cast(reinterpret_cast(output.data())); + const std::array userData{ + static_cast(inputAddress), static_cast((inputAddress >> 32u) & 0xffffu), 256u, 0x31016facu, + static_cast(outputAddress), static_cast((outputAddress >> 32u) & 0xffffu), 256u, 0x31016facu}; + const std::array extensions{"SPV_KHR_physical_storage_buffer", "SPV_KHR_8bit_storage"}; + const std::array capabilities{spv::CapabilityInt64, spv::CapabilityInt64Atomics, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess}; + struct Counts { + std::uint32_t loads = 0, stores = 0, wideLoads = 0; + }; + const auto compile = [&](bool glc, bool pair) { + const std::uint32_t loadOp = pair ? 0xe0341000u : 0xe0301000u; + const std::uint32_t storeOp = pair ? 0xe0741000u : 0xe0701000u; + std::vector code{0x34020082u, loadOp | (glc ? 0x4000u : 0u), 0x80000201u, 0xbf8c3f70u, storeOp | (glc ? 0x4000u : 0u), 0x80010201u, 0xbf810000u}; + RecompileRequest request{}; + request.shader = {ShaderStage::Compute, 0x5b000u, code, 0, {}}; + request.context.waveSize = 32; + request.context.userDataBaseRegister = 0; + request.context.userData = userData; + request.context.compute = ShaderComputeStageInfo{{32u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; + request.target.vulkanVersion = 0x00401000u; + request.target.spirvVersion = 0x00010300u; + request.target.subgroupSize = 32; + request.target.bdaAbiVersion = BdaAbi::Version; + request.target.supportedCapabilities = capabilities; + request.target.supportedExtensions = extensions; + request.target.fragmentShaderBarycentricEnabled = false; + request.target.gpuResolvedImages = true; + request.target.descriptorMemory = true; + request.layout.pushConstantSizeBytes = 128; + request.useCache = false; + const auto words = Recompile(request).spirv; + std::set wideTypes; + Counts counts; + for (std::size_t cursor = 5; cursor < words.size();) { + const auto count = words[cursor] >> 16u; + const auto opcode = words[cursor] & 0xffffu; + require(count != 0 && count <= words.size() - cursor, "addressed coherent buffers: truncated SPIR-V instruction"); + if (opcode == spv::OpTypeInt && words[cursor + 2] == 64u) wideTypes.insert(words[cursor + 1]); + if (opcode == spv::OpAtomicLoad) ++(wideTypes.contains(words[cursor + 1]) ? counts.wideLoads : counts.loads); + if (opcode == spv::OpAtomicStore) ++counts.stores; + cursor += count; + } + return counts; + }; + + const auto plain = compile(false, false); + require(plain.loads == 0u && plain.stores == 0u && plain.wideLoads == 0u, "addressed coherent buffers: accesses without GLC became atomics"); + + const auto single = compile(true, false); + require(single.loads != 0u, "addressed coherent buffers: a GLC load through a buffer address is not an atomic load"); + require(single.stores != 0u, "addressed coherent buffers: a GLC store through a buffer address is not an atomic store"); + + const auto wide = compile(true, true); + require(wide.wideLoads != 0u, "addressed coherent buffers: a GLC two-dword load through a buffer address is not one 64-bit atomic load"); + require(wide.stores != 0u, "addressed coherent buffers: a GLC two-dword store through a buffer address is not an atomic store"); +} + void verifyUnnormalizedSamplers() { using namespace ShaderRecompiler; constexpr std::uint32_t Format8888UNorm = 56; @@ -8587,6 +8650,7 @@ int main(int argc, char** argv) { verifyInt64AtomicCapabilities(); verifySpecializedBufferAtomicBindings(); verifyCoherentBufferAccesses(); + verifyAddressedCoherentBufferAccesses(); verifyUnnormalizedSamplers(); verifyUnusedUnnormalizedSampler(); verifyNullVolumeUnnormalizedSampler(); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index aee0795089fc..6caeabd64ee5 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -225,7 +225,8 @@ std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruct const auto load = [&](std::uint32_t word) { const auto value = state.module.AllocateId(); const auto pointer = EmitMemoryElementPointer(state, access, word); - if (access.physical) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access.memoryAccess | spv::MemoryAccessAlignedMask, 4u); + if (access.physical && context.Memory(instruction).coherent) state.module.AddFunction(spv::OpAtomicLoad, TypeU32(state), value, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone)); + else if (access.physical) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access.memoryAccess | spv::MemoryAccessAlignedMask, 4u); else if (access.memoryAccess != 0u) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access.memoryAccess); else state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); return value; @@ -324,7 +325,8 @@ void writeBuffer(SpirvValueEmitContext& context, const IrValue& instruction, std if (bits == 32u) { EmitIfCondition(state, Unary(state, spv::OpLogicalNot, TypeBool(state), unaligned), [&] { const auto pointer = EmitMemoryElementPointer(state, access, index); - if (access.physical) state.module.AddFunction(spv::OpStore, pointer, value, access.memoryAccess | spv::MemoryAccessAlignedMask, 4u); + if (access.physical && context.Memory(instruction).coherent) state.module.AddFunction(spv::OpAtomicStore, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone), value); + else if (access.physical) state.module.AddFunction(spv::OpStore, pointer, value, access.memoryAccess | spv::MemoryAccessAlignedMask, 4u); else if (access.memoryAccess != 0u) state.module.AddFunction(spv::OpStore, pointer, value, access.memoryAccess); else state.module.AddFunction(spv::OpStore, pointer, value); }); @@ -789,7 +791,8 @@ struct CoherentPair { std::optional coherentPair(SpirvValueEmitContext& context, const IrValue& instruction, const RuntimeDescriptor& resource, std::uint32_t components) { auto& state = context.state; const auto& memory = context.Memory(instruction); - if (components != 2u || !memory.coherent || memory.gpuDescriptor || memory.dataBits != 32u || state.storageBufferU64Variable == 0u) return std::nullopt; + const bool wideView = state.addressedBuffers ? state.requirements.bufferU64View : state.storageBufferU64Variable != 0u; + if (components != 2u || !memory.coherent || memory.gpuDescriptor || memory.dataBits != 32u || !wideView) return std::nullopt; const auto low = address(context, instruction, resource, 0u, 4u); const auto high = address(context, instruction, resource, 4u, 4u); const auto wide = directAccess(context, instruction, true); From 76a8bf3dacebbe8661eb9fd43851f429d74f76fd Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 23 Oct 2026 21:52:59 +0530 Subject: [PATCH 030/269] fix(agc): keep buffer accesses coherent through buffer addresses after cache invalidation A program with GLC or DLC accesses that invalidates the vector caches reads the whole guest buffer array as Coherent on the storage-buffer path, so its loads without GLC see other work-groups' writes after the invalidation. Through buffer addresses those loads and stores stayed plain. They are now device-scope atomic loads and stores in such programs, as GLC accesses already are. Co-Authored-By: Claude Opus 5.5 --- .../prx/libSceAgcDriver/tests/ShaderMemory.cpp | 18 +++++++++++++----- .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 9 +++++++-- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 26509ce2e54d..2bcafbb763a6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -6718,10 +6718,12 @@ void verifyAddressedCoherentBufferAccesses() { struct Counts { std::uint32_t loads = 0, stores = 0, wideLoads = 0; }; - const auto compile = [&](bool glc, bool pair) { + const auto compile = [&](bool glcLoad, bool glcStore, bool pair, bool invalidate) { const std::uint32_t loadOp = pair ? 0xe0341000u : 0xe0301000u; const std::uint32_t storeOp = pair ? 0xe0741000u : 0xe0701000u; - std::vector code{0x34020082u, loadOp | (glc ? 0x4000u : 0u), 0x80000201u, 0xbf8c3f70u, storeOp | (glc ? 0x4000u : 0u), 0x80010201u, 0xbf810000u}; + std::vector code{0x34020082u}; + if (invalidate) code.insert(code.end(), {0xe1c40000u, 0u}); + code.insert(code.end(), {loadOp | (glcLoad ? 0x4000u : 0u), 0x80000201u, 0xbf8c3f70u, storeOp | (glcStore ? 0x4000u : 0u), 0x80010201u, 0xbf810000u}); RecompileRequest request{}; request.shader = {ShaderStage::Compute, 0x5b000u, code, 0, {}}; request.context.waveSize = 32; @@ -6754,16 +6756,22 @@ void verifyAddressedCoherentBufferAccesses() { return counts; }; - const auto plain = compile(false, false); + const auto plain = compile(false, false, false, false); require(plain.loads == 0u && plain.stores == 0u && plain.wideLoads == 0u, "addressed coherent buffers: accesses without GLC became atomics"); - const auto single = compile(true, false); + const auto single = compile(true, true, false, false); require(single.loads != 0u, "addressed coherent buffers: a GLC load through a buffer address is not an atomic load"); require(single.stores != 0u, "addressed coherent buffers: a GLC store through a buffer address is not an atomic store"); - const auto wide = compile(true, true); + const auto wide = compile(true, true, true, false); require(wide.wideLoads != 0u, "addressed coherent buffers: a GLC two-dword load through a buffer address is not one 64-bit atomic load"); require(wide.stores != 0u, "addressed coherent buffers: a GLC two-dword store through a buffer address is not an atomic store"); + + const auto invalidated = compile(false, true, false, true); + require(invalidated.loads != 0u, "addressed coherent buffers: a load without GLC in a program that invalidates the vector caches is not an atomic load"); + + const auto invalidatedPlain = compile(false, false, false, true); + require(invalidatedPlain.loads == 0u && invalidatedPlain.stores == 0u, "addressed coherent buffers: a program that invalidates the vector caches without GLC or DLC accesses made its accesses atomic"); } void verifyUnnormalizedSamplers() { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index 6caeabd64ee5..4f5bea8b427b 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -211,6 +211,11 @@ std::uint32_t directWordIndex(SpirvEmitterState& state, const MemoryResourceAcce return EmitAddU32(state, relative, base); } +bool addressedCoherent(SpirvValueEmitContext& context, const IrValue& instruction) { + const auto& state = context.state; + return context.Memory(instruction).coherent || (state.requirements.coherentBuffers && state.program.Metadata().invalidatesCaches); +} + std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruction, std::uint32_t address, std::uint32_t bits, std::uint32_t enable = 0u) { if (context.Memory(instruction).gpuDescriptor) return EmitBdaRead(context, instruction, address, bits); auto& state = context.state; @@ -225,7 +230,7 @@ std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruct const auto load = [&](std::uint32_t word) { const auto value = state.module.AllocateId(); const auto pointer = EmitMemoryElementPointer(state, access, word); - if (access.physical && context.Memory(instruction).coherent) state.module.AddFunction(spv::OpAtomicLoad, TypeU32(state), value, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone)); + if (access.physical && addressedCoherent(context, instruction)) state.module.AddFunction(spv::OpAtomicLoad, TypeU32(state), value, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone)); else if (access.physical) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access.memoryAccess | spv::MemoryAccessAlignedMask, 4u); else if (access.memoryAccess != 0u) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, access.memoryAccess); else state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); @@ -325,7 +330,7 @@ void writeBuffer(SpirvValueEmitContext& context, const IrValue& instruction, std if (bits == 32u) { EmitIfCondition(state, Unary(state, spv::OpLogicalNot, TypeBool(state), unaligned), [&] { const auto pointer = EmitMemoryElementPointer(state, access, index); - if (access.physical && context.Memory(instruction).coherent) state.module.AddFunction(spv::OpAtomicStore, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone), value); + if (access.physical && addressedCoherent(context, instruction)) state.module.AddFunction(spv::OpAtomicStore, pointer, ConstantU32(state, spv::ScopeDevice), ConstantU32(state, spv::MemorySemanticsMaskNone), value); else if (access.physical) state.module.AddFunction(spv::OpStore, pointer, value, access.memoryAccess | spv::MemoryAccessAlignedMask, 4u); else if (access.memoryAccess != 0u) state.module.AddFunction(spv::OpStore, pointer, value, access.memoryAccess); else state.module.AddFunction(spv::OpStore, pointer, value); From 9719c4a447f899efb7ddf0681d267022d32b8088 Mon Sep 17 00:00:00 2001 From: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:10:46 -0700 Subject: [PATCH 031/269] test(agc): build and run the heap draw sample and refresh proof tests on Windows MinGW declares no setenv, so the heap draw sample did not build on Windows; it now sets its environment with _putenv_s there, as the other tests that set a variable before opening the device do. Those tests and agc_storage_refresh_proofs also exited with 0xc0000135 on Windows without libc's directory on PATH, which they now get like the rest of the driver's tests. --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 12 ++++++++++++ .../tests/execution/HeapDrawSample.cpp | 4 ++++ 2 files changed, 16 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 939780e51171..785e33a409e4 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -1679,6 +1679,9 @@ if(BUILD_TESTING) add_test(NAME agc_storage_kept_unit_settle COMMAND agc_driver_recorder_tests --kept-unit-settle-only) add_test(NAME agc_storage_refresh_proofs COMMAND agc_driver_recorder_tests --refresh-proofs-only) set_tests_properties(agc_storage_refresh_proofs PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + if(WIN32) + set_tests_properties(agc_storage_refresh_proofs PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() set_tests_properties(agc_storage_kept_unit_settle PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) if(WIN32) set_tests_properties(agc_storage_kept_unit_settle PROPERTIES ENVIRONMENT_MODIFICATION @@ -3105,6 +3108,9 @@ if(BUILD_TESTING) if(TARGET agc_driver_heap_draw_sample_tests) add_test(NAME agc_driver_heap_draw_sample_heap COMMAND agc_driver_heap_draw_sample_tests) set_tests_properties(agc_driver_heap_draw_sample_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_heap_draw_sample_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() endif() add_test(NAME agc_driver_heap_slots_comes_back COMMAND agc_driver_heap_slots_tests comes-back) set_tests_properties(agc_driver_heap_slots_comes_back PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") @@ -3116,12 +3122,18 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_heap_draw_sample_full_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_HEAP_SLOT_CAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") add_test(NAME agc_driver_heap_draw_sample_full_heap_pipelined COMMAND agc_driver_heap_draw_sample_tests) set_tests_properties(agc_driver_heap_draw_sample_full_heap_pipelined PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_HEAP_SLOT_CAP=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_heap_draw_sample_full_heap agc_driver_heap_draw_sample_full_heap_pipelined PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() endif() if(TARGET agc_driver_heap_draw_sample_tests) add_test(NAME agc_driver_heap_draw_sample_nogpl COMMAND agc_driver_heap_draw_sample_tests) set_tests_properties(agc_driver_heap_draw_sample_nogpl PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_GPL=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") add_test(NAME agc_driver_heap_draw_sample_nogpl_heap COMMAND agc_driver_heap_draw_sample_tests) set_tests_properties(agc_driver_heap_draw_sample_nogpl_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_GPL=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_heap_draw_sample_nogpl agc_driver_heap_draw_sample_nogpl_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() endif() if(TARGET agc_driver_heap_compute_sample_tests) add_test(NAME agc_driver_heap_compute_sample_heap_pipelined COMMAND agc_driver_heap_compute_sample_tests) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index 6740ccae09ad..f0fd13ebba9b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -271,7 +271,11 @@ void MixedDrawTakesThePerDrawPath() { } int main() { +#ifdef _WIN32 + _putenv_s("APS5_EAGER_WRITEBACK", "1"); +#else setenv("APS5_EAGER_WRITEBACK", "1", 1); +#endif try { { const auto device = OpenVulkanTestDevice(); From e57f0405d1646a6c02d59c2edc9247910a91a8f3 Mon Sep 17 00:00:00 2001 From: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> Date: Fri, 23 Oct 2026 23:56:51 -0700 Subject: [PATCH 032/269] test(agc): keep the image table atomics key wave-uniform on narrow subgroups The atomics kernel built its table key with v_readfirstlane_b32 of 5 plus the lane index, which is 5 for the whole wave64 only when the host runs the wave as one subgroup. lavapipe runs it as 8-lane subgroups and each takes its own first lane, so lanes 8 to 63 read records 13 and up ("dispatch 0 texel 8 returned 13059, expected 5059"). The key now adds the lane index shifted right by 6, which is 0 in every lane of the wave and still a value the planner can't evaluate. --- .../libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp index 7bfacc618e61..8c622be580f2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp @@ -71,7 +71,7 @@ constexpr std::uint32_t AtomicWidth = 64; constexpr std::size_t AtomicKernelOffset = 1024; constexpr std::size_t AtomicSurfaceBytes = AtomicWidth * 4u; constexpr std::uint32_t AtomicElement = 5; -constexpr std::array AtomicTableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x4a220085u, 0x7e200511u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0x7e020280u, 0x7e040281u, 0x34060082u, 0xbf8c3f70u, 0xf0442108u, 0x00050200u, 0xbf8c3f70u, 0xe0701000u, 0x80070203u, 0xbf8c3f70u, 0xbf810000u}; +constexpr std::array AtomicTableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x2c240086u, 0x4a222485u, 0x7e200511u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0x7e020280u, 0x7e040281u, 0x34060082u, 0xbf8c3f70u, 0xf0442108u, 0x00050200u, 0xbf8c3f70u, 0xe0701000u, 0x80070203u, 0xbf8c3f70u, 0xbf810000u}; constexpr std::array TableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x7e200500u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0xf09c0f08u, 0x00450000u, 0xe0700000u, 0x80070000u, 0xbf810000u}; class GuestBlock { From f6ed4bba57a225e305c6924d0c3338befb813619 Mon Sep 17 00:00:00 2001 From: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> Date: Sat, 24 Oct 2026 02:06:08 -0700 Subject: [PATCH 033/269] fix(agc): re-query the address of a pooled allocation that has none DeviceBuffer returns its allocation to the pool without a device address. With the GPU heap's forced addresses, a texture's DeviceBuffer and a device-local Buffer with SHADER_DEVICE_ADDRESS share one pool key, so a Buffer of the same size took that allocation and kept the address 0. Its first DeviceAddress() threw "buffer has no device address" from a compute dispatch's BDA table. Query the address when a reused allocation has none. --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 5 ++- .../Graphics/src/Resources.cpp | 7 +++ .../prx/libSceAgcDriver/tests/Graphics.cpp | 44 +++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 785e33a409e4..c76c07a80650 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -2756,7 +2756,8 @@ if(BUILD_TESTING) add_test(NAME agc_sparse_buffer_holes COMMAND agc_driver_graphics_tests --sparse-buffer-holes) add_test(NAME agc_copy_input_kept_bytes COMMAND agc_driver_graphics_tests --copy-input-kept-bytes) add_test(NAME agc_depth_copy_kept_bytes COMMAND agc_driver_graphics_tests --depth-copy-kept-bytes) - set_tests_properties(agc_copy_input_kept_bytes agc_depth_copy_kept_bytes PROPERTIES + add_test(NAME agc_pooled_buffer_address COMMAND agc_driver_graphics_tests --pooled-buffer-address) + set_tests_properties(agc_copy_input_kept_bytes agc_depth_copy_kept_bytes agc_pooled_buffer_address PROPERTIES TIMEOUT 30 ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" ENVIRONMENT_MODIFICATION "APS5_CPU_COPIES=unset:;APS5_GPU_COPY_MAX_KIB=unset:;APS5_CAPTURE_GPU_COPIES=unset:;APS5_BUFFER_POOL_SLOTS=unset:;APS5_BUFFER_POOL_SHARED=unset:;APS5_NO_BUFFER_CLASSES=unset:;APS5_STAGING_POOL_MIB=unset:") if(WIN32) @@ -2764,6 +2765,8 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") set_property(TEST agc_depth_copy_kept_bytes APPEND PROPERTY ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + set_property(TEST agc_pooled_buffer_address APPEND PROPERTY ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") endif() set_tests_properties(agc_driver_native_multisample_depth PROPERTIES TIMEOUT 30) set_tests_properties(agc_driver_sample_order PROPERTIES TIMEOUT 30) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp index b43442fdc207..bf37eaad90d2 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp @@ -65,6 +65,13 @@ Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usag release(); throw; } + } else if (deviceAddress == 0) { + try { + initializeAddress(this->usage); + } catch (...) { + release(); + throw; + } } ready = true; return; diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index 7afcaac27e53..5dc0d87c0311 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -5679,6 +5679,45 @@ void copyInputKeptBytesTests() { Require(mock.live == 0, "copy input accounting tests leaked Vulkan objects"); } +void pooledBufferAddressTests() { + using namespace AgcDriver::Graphics; + constexpr std::size_t bytes = 4096; + constexpr auto properties = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + const bool forced = BufferPool::ForceAddresses(); + mock = MockVulkan{}; + { + auto context = mockContext(); + context.device = makeHandle(); + context.bufferDeviceAddress = true; + context.memory.memoryTypes[0].propertyFlags |= properties; + context.memory.memoryHeapCount = 1; + context.memory.memoryHeaps[0] = {std::uint64_t{4} << 30u, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + context.limits.maxMemoryAllocationCount = 4096; + context.bufferPool = std::make_shared(context); + BufferPool::SetForceAddresses(true); + VkBuffer pooled = VK_NULL_HANDLE; + { + DeviceBuffer texture(context, bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); + pooled = texture.Handle(); + } + VkDeviceAddress address = 0; + VkDeviceAddress expected = 0; + { + Buffer staging(context, bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, properties); + Require(staging.Handle() == pooled, "a device-local buffer of the pooled device buffer's size and usage did not reuse its allocation"); + const VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, pooled}; + expected = mockGetBufferDeviceAddress(context.device, &info); + try { + address = staging.DeviceAddress(); + } catch (const std::exception&) { + } + } + BufferPool::SetForceAddresses(forced); + Require(address == expected, "a buffer that reuses a pooled device buffer's allocation has no device address"); + } + Require(mock.live == 0, "pooled buffer address tests leaked Vulkan objects"); +} + void depthCopyKeptBytesTests() { using namespace AgcDriver::Graphics; constexpr std::size_t bytes = (8 * 8 + 4 * 4) * sizeof(float); @@ -11820,6 +11859,11 @@ int main(int argc, char** argv) { std::cout << "GPU-copy input snapshot accounting and retention passed\n"; return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--pooled-buffer-address") { + pooledBufferAddressTests(); + std::cout << "a reused pooled allocation keeps a device address\n"; + return 0; + } if (argc == 2 && std::string_view(argv[1]) == "--depth-copy-kept-bytes") { depthCopyKeptBytesTests(); std::cout << "Depth-copy linear buffer accounting and retention passed\n"; From a5f62f67c7990cd2ae24fba50ca9dd0c51972e1d Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 24 Oct 2026 17:15:34 +0530 Subject: [PATCH 034/269] feat(agc): map pixel function LDS onto the GPU heap A pixel stage whose LDS lives in the pixel function LDS buffer used its own descriptor set, which heap pipelines cannot bind, so the stage was refused and the whole draw fell back to per-draw descriptor sets. The resource heap now keeps one storage buffer descriptor after the image slots. The pool buffer gets a device address when the device has the heap, and its descriptor is written into that slot the first time a heap draw prepares it. The pixel LDS set maps onto the slot with a constant offset, so heap pipelines no longer bind the set. Tested: agc_driver_heap_draw_sample* draws a texture through LDS at dword 4352 (past the 4096-dword private storage, so it uses the pool) with and without the heap. With the mapping disabled the heap run refuses "the heap did not take the fragment stage". Full ctest -j4 -E agc_driver_bda_device: only the three sample_order tests fail, as before. Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/Driver/Draw/HeapStages.cpp | 2 +- .../Graphics/include/BindlessHeap.hpp | 6 ++- .../Graphics/src/BindlessHeap.cpp | 48 +++++++++++++++---- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 25 ++++++++-- .../libSceAgcDriver/Graphics/src/Pipeline.cpp | 2 +- .../tests/execution/HeapDrawSample.cpp | 8 ++-- 6 files changed, 73 insertions(+), 18 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 2abf962ea09b..eb7e341340f7 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -151,7 +151,7 @@ bool HeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool wor const auto key = result.variantId * 2u + (workgroupAddress ? 1u : 0u); if (const auto found = known.find(key); found != known.end()) return found->second; if (known.size() >= 65536u) known.clear(); - const bool mappable = Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), workgroupAddress, result.dataAddressPush); + const bool mappable = Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), workgroupAddress, result.dataAddressPush, result.functionLdsBuffer); known.emplace(key, mappable); return mappable; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index decce0fe3c22..3f5e67b5b04c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -37,7 +37,8 @@ class BindlessHeap { VkDeviceSize ImageHeapStride() const { return imageHeapStride; } VkDeviceSize SamplerHeapStride() const { return samplerHeapStride; } void BindDescriptorHeaps(VkCommandBuffer commands) const; - bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset = ~0u, bool rootGds = false, bool rootFault = false) const; + bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset = ~0u, bool rootGds = false, bool rootFault = false, bool pixelLds = false) const; + void WritePixelLdsBuffer(VkDeviceAddress address, VkDeviceSize bytes); VkDeviceAddress RingAddress() const; VkBuffer RingBuffer() const; @@ -89,6 +90,7 @@ class BindlessHeap { VkDeviceSize imageHeapStride = 0; VkDeviceSize samplerHeapStride = 0; VkDeviceSize resourceHeapUsed = 0; + VkDeviceSize pixelLdsHeapOffset = 0; VkDeviceSize samplerHeapUsed = 0; void writeDescriptorHeap(const VkWriteDescriptorSet& write); static constexpr std::size_t RingChunkBytes = 4u << 20u; @@ -148,7 +150,7 @@ bool GpuHeapEnabled(); void SetDescriptorHeapDevice(bool available); bool DescriptorHeapEnabled(); bool HeapComputeEnabled(); -bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress); +bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds = false); void NoteHeapComputeStage(); std::uint64_t HeapComputeStages(); void NoteImageTableBuild(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 92384eba9a80..6c1492ff2561 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -9,6 +9,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "RuntimeAbi.hpp" +#include "SpirvBackend/SpirvAnalysis.hpp" #include #include #include @@ -102,7 +103,7 @@ bool HeapComputeEnabled() { namespace { struct HeapSizes { - VkDeviceSize imageStride = 0, samplerStride = 0, resourceUsed = 0, samplerUsed = 0; + VkDeviceSize imageStride = 0, samplerStride = 0, pixelLdsOffset = 0, resourceUsed = 0, samplerUsed = 0; }; HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { @@ -110,7 +111,8 @@ HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& propertie HeapSizes sizes; sizes.imageStride = align(properties.imageDescriptorSize, properties.imageDescriptorAlignment); sizes.samplerStride = align(properties.samplerDescriptorSize, properties.samplerDescriptorAlignment); - sizes.resourceUsed = align(static_cast(static_cast(Abi::Binding::Samplers)) * Abi::GpuImageHeapSlots * sizes.imageStride, properties.resourceHeapAlignment); + sizes.pixelLdsOffset = align(static_cast(static_cast(Abi::Binding::Samplers)) * Abi::GpuImageHeapSlots * sizes.imageStride, properties.bufferDescriptorAlignment); + sizes.resourceUsed = align(sizes.pixelLdsOffset + properties.bufferDescriptorSize, properties.resourceHeapAlignment); sizes.samplerUsed = align(static_cast(Abi::GpuSamplerHeapSlots) * sizes.samplerStride, properties.samplerHeapAlignment); return sizes; } @@ -129,6 +131,7 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { imageHeapStride = sizes.imageStride; samplerHeapStride = sizes.samplerStride; resourceHeapUsed = sizes.resourceUsed; + pixelLdsHeapOffset = sizes.pixelLdsOffset; samplerHeapUsed = sizes.samplerUsed; Require(Fits(heapProperties), "the GPU heap's slots exceed the device's descriptor heap sizes"); constexpr VkBufferUsageFlags heapUsage = VK_BUFFER_USAGE_DESCRIPTOR_HEAP_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; @@ -645,11 +648,12 @@ namespace { const std::uint32_t GeneratedFaultBinding = Abi::BindingNumber(Abi::Stage::TessellationControl, Abi::Binding::FaultBuffer); -bool heapBindings(std::span spirv, bool workgroupAddress, bool gdsAddress, bool faultAddress, std::vector& bindings, bool& workgroupMemory, std::uint32_t& gdsBinding, bool& faultMemory, std::pair* refused = nullptr) { +bool heapBindings(std::span spirv, bool workgroupAddress, bool gdsAddress, bool faultAddress, bool pixelLds, std::vector& bindings, bool& workgroupMemory, std::uint32_t& gdsBinding, bool& faultMemory, bool& pixelLdsMemory, std::pair* refused = nullptr) { bindings.clear(); workgroupMemory = false; gdsBinding = ~0u; faultMemory = false; + pixelLdsMemory = false; if (spirv.size() < 5u) return false; constexpr std::uint32_t opDecorate = 71u; constexpr std::uint32_t decorationBinding = 33u; @@ -681,24 +685,29 @@ bool heapBindings(std::span spirv, bool workgroupAddress, b faultMemory = true; continue; } + if (pixelLds && !pixelLdsMemory && entry.first == ShaderRecompiler::PixelFunctionLdsDescriptorSet && entry.second == 0u) { + pixelLdsMemory = true; + continue; + } if (entry.first != Abi::FragmentDescriptorSet || entry.second < bindingCount + Abi::FirstImageBinding || entry.second > bindingCount + samplerBinding) { if (refused != nullptr) *refused = entry; return false; } if (std::find(bindings.begin(), bindings.end(), entry.second) == bindings.end()) bindings.push_back(entry.second); } - return (!workgroupAddress || workgroupMemory) && (!faultAddress || faultMemory); + return (!workgroupAddress || workgroupMemory) && (!faultAddress || faultMemory) && (!pixelLds || pixelLdsMemory); } } -bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress) { +bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds) { std::vector bindings; bool workgroupMemory = false; std::uint32_t gdsBinding = ~0u; bool faultMemory = false; + bool pixelLdsMemory = false; std::pair refused{~0u, ~0u}; - const bool mappable = heapBindings(spirv, workgroupAddress, gdsAddress, false, bindings, workgroupMemory, gdsBinding, faultMemory, &refused); + const bool mappable = heapBindings(spirv, workgroupAddress, gdsAddress, false, pixelLds, bindings, workgroupMemory, gdsBinding, faultMemory, pixelLdsMemory, &refused); static const bool stats = std::getenv("APS5_PIPELINE_STATS") != nullptr; if (!mappable && stats) { static std::mutex causesMutex; @@ -710,13 +719,14 @@ bool DescriptorHeapMappable(std::span spirv, bool workgroup return mappable; } -bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset, bool rootGds, bool rootFault) const { +bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset, bool rootGds, bool rootFault, bool pixelLds) const { mappings.clear(); std::vector bindings; bool workgroupMemory = false; std::uint32_t gdsBinding = ~0u; bool faultMemory = false; - if (resourceHeap == nullptr || !heapBindings(spirv, workgroupAddressOffset != ~0u, rootGds, rootFault, bindings, workgroupMemory, gdsBinding, faultMemory)) return false; + bool pixelLdsMemory = false; + if (resourceHeap == nullptr || !heapBindings(spirv, workgroupAddressOffset != ~0u, rootGds, rootFault, pixelLds, bindings, workgroupMemory, gdsBinding, faultMemory, pixelLdsMemory)) return false; constexpr auto bindingCount = static_cast(Abi::Binding::Count); constexpr auto samplerBinding = static_cast(Abi::Binding::Samplers); std::sort(bindings.begin(), bindings.end()); @@ -768,9 +778,31 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, mapping.sourceData.pushAddressOffset = (Abi::RootDword + Abi::RootFaultAddress) * sizeof(std::uint32_t); mappings.push_back(mapping); } + if (pixelLdsMemory) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = ShaderRecompiler::PixelFunctionLdsDescriptorSet; + mapping.firstBinding = 0; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT; + mapping.sourceData.constantOffset.heapOffset = static_cast(pixelLdsHeapOffset); + mapping.sourceData.constantOffset.heapArrayStride = 0; + mappings.push_back(mapping); + } return true; } +void BindlessHeap::WritePixelLdsBuffer(VkDeviceAddress address, VkDeviceSize bytes) { + const auto& properties = context.descriptorHeapProperties; + Require(pixelLdsHeapOffset + properties.bufferDescriptorSize <= resourceHeapUsed, "the pixel function LDS descriptor lies outside the resource heap"); + const VkDeviceAddressRangeEXT buffer{address, bytes}; + VkResourceDescriptorInfoEXT resource{VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT}; + resource.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + resource.data.pAddressRange = &buffer; + const VkHostAddressRangeEXT range{resourceHeap->Bytes().data() + pixelLdsHeapOffset, static_cast(properties.bufferDescriptorSize)}; + Check(context.Function("vkWriteResourceDescriptorsEXT")(context.device, 1, &resource, &range), "vkWriteResourceDescriptorsEXT pixel function LDS"); +} + namespace { std::mutex boundHeapsMutex; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 76972d957ba7..1ea7fbdb95c7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -59,6 +59,9 @@ struct PixelFunctionLdsPool { std::uint32_t* header = nullptr; std::uint32_t subgroupSize = 0; std::uint32_t slots = 0; + VkDeviceSize bytes = 0; + VkDeviceAddress address = 0; + const BindlessHeap* heapWritten = nullptr; bool announced = false; }; @@ -122,12 +125,15 @@ void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, s const auto bytes = 16ull + stride * pool.slots; VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bufferInfo.size = bytes; - bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + const bool addressed = context.descriptorHeap && context.bufferDeviceAddress; + bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | (addressed ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u); bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; Check(context.Function("vkCreateBuffer")(context.device, &bufferInfo, nullptr, &pool.buffer), "vkCreateBuffer pixel function LDS"); VkMemoryRequirements requirements{}; context.Function("vkGetBufferMemoryRequirements")(context.device, pool.buffer, &requirements); VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + const VkMemoryAllocateFlagsInfo addressFlags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, nullptr, VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, 0}; + if (addressed) allocation.pNext = &addressFlags; allocation.allocationSize = requirements.size; constexpr auto hostCoherent = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; constexpr auto deviceLocalHost = hostCoherent | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; @@ -158,6 +164,11 @@ void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, s Check(allocated, "vkAllocateMemory pixel function LDS"); } Check(context.Function("vkBindBufferMemory")(context.device, pool.buffer, pool.memory, 0), "vkBindBufferMemory pixel function LDS"); + pool.bytes = bytes; + if (addressed) { + const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, pool.buffer}; + pool.address = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + } Check(context.Function("vkMapMemory")(context.device, pool.memory, 0, 16, 0, reinterpret_cast(&pool.header)), "vkMapMemory pixel function LDS"); pool.header[0] = 0u; pool.header[1] = 0u; @@ -185,6 +196,14 @@ void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, s pool.announced = true; } Require(pool.subgroupSize == subgroupSize, "pixel function LDS subgroup size does not match the pool"); + if (context.descriptorHeap && DescriptorHeapEnabled()) { + auto& heap = BindlessHeap::For(context); + if (pool.heapWritten != &heap) { + Require(pool.address != 0, "the pixel function LDS pool has no device address for the GPU heap"); + heap.WritePixelLdsBuffer(pool.address, pool.bytes); + pool.heapWritten = &heap; + } + } const VkMemoryBarrier beforeFill{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT}; context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &beforeFill, 0, nullptr, 0, nullptr); context.Resolved(&DeviceFunctions::cmdFillBuffer, "vkCmdFillBuffer")(commands, pool.buffer, 0, 4, 0u); @@ -2344,7 +2363,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam Require(!resources.HeapStage(), "a GPU-mode draw needs a VK_EXT_descriptor_heap pipeline"); resources.Bind(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout()); } - if (std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; })) BindPixelFunctionLds(context, commands, record.pipeline->Layout()); + if (!record.pipeline->DescriptorHeap() && std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; })) BindPixelFunctionLds(context, commands, record.pipeline->Layout()); APS5_LOG_CHARS_OUT_DEBUG("Resources bound"); pushDrawConstants(*record.pipeline, commands, state, draw, shaders, resources, record.pushBytes, record.pushStages, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty(), drawBindings.get()); APS5_LOG_CHARS_OUT_DEBUG("Push constants recorded"); @@ -3083,7 +3102,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D BindlessHeap::For(context).BindDescriptorHeaps(commands); NoteEmptyResourceSet(); } else resources->Bind(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->Layout()); - if (pixelLdsSubgroup != 0u) BindPixelFunctionLds(context, commands, pipeline->Layout()); + if (pixelLdsSubgroup != 0u && !pipeline->DescriptorHeap()) BindPixelFunctionLds(context, commands, pipeline->Layout()); APS5_LOG_CHARS_OUT_DEBUG("Resources bound"); pushDrawConstants(*pipeline, commands, state, draw, shaders, *resources, nullptr, 0, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty()); APS5_LOG_CHARS_OUT_DEBUG("Push constants recorded"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index 47e61cfade5c..cd8da20e46af 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -512,7 +512,7 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput descriptorHeap = std::all_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { const auto index = static_cast(&shader - shaders.data()); const bool generatedFault = !shader.program->gpuResolvedImages && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const auto& binding) { return binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer; }); - return heap.DescriptorHeapMappings(std::span(shader.program->spirv.data(), shader.program->spirv.size()), heapMappings[index], ~0u, shader.program->dataAddressPush, generatedFault && rooted); + return heap.DescriptorHeapMappings(std::span(shader.program->spirv.data(), shader.program->spirv.size()), heapMappings[index], ~0u, shader.program->dataAddressPush, generatedFault && rooted, shader.program->functionLdsBuffer); }); } Require(descriptorHeap || std::none_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program->gpuResolvedImages; }), "a pipeline with GPU-mode stages does not map onto VK_EXT_descriptor_heap"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index f0fd13ebba9b..bc43c050fac0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -39,6 +39,7 @@ alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e alignas(256) constexpr std::array BufferPixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; alignas(256) constexpr std::array GdsPixelCode{0xbefc03ffu, 0x0000ffffu, 0x7e0002f0u, 0x7e0202f0u, 0xd8fa0010u, 0x04000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; alignas(256) constexpr std::array StoragePixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e100280u, 0x7e120280u, 0xf0201f08u, 0x00040008u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array LdsPixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e080280u, 0xd8344400u, 0x00000004u, 0xbf8cc07fu, 0xd8d84400u, 0x00000004u, 0xbf8cc07fu, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; alignas(4096) std::array StorageMemory{}; alignas(256) constexpr std::array SamplingVertexCode{ 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00820c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, @@ -90,7 +91,7 @@ void Append(std::vector& commands, std::uint32_t opcode, std::ini commands.insert(commands.end(), payload); } -enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture }; +enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds }; std::vector Draw(const std::uint32_t* pixelCode, Mode mode, const std::uint32_t* vertexCode = nullptr) { const bool vertexSampling = mode == Mode::Vertex || mode == Mode::VertexTable; @@ -190,8 +191,8 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); for (std::size_t offset = 0; offset < OtherTextureMemory.size(); offset += 4) OtherTextureMemory[offset] = OtherTextureMemory[offset + 1] = OtherTextureMemory[offset + 2] = OtherTextureMemory[offset + 3] = 0x33u; const bool vertexSampling = mode == Mode::Vertex || mode == Mode::VertexTable; - const auto* code = mode == Mode::Table ? TablePixelCode.data() : mode == Mode::Gds ? GdsPixelCode.data() : mode == Mode::Storage ? StoragePixelCode.data() : mode == Mode::Bda ? BdaPixelCode.data() : buffer ? BufferPixelCode.data() : vertexSampling ? InterpolantPixelCode.data() : PixelCode.data(); - const auto bytes = mode == Mode::Table ? sizeof(TablePixelCode) : mode == Mode::Gds ? sizeof(GdsPixelCode) : mode == Mode::Storage ? sizeof(StoragePixelCode) : mode == Mode::Bda ? sizeof(BdaPixelCode) : buffer ? sizeof(BufferPixelCode) : vertexSampling ? sizeof(InterpolantPixelCode) : sizeof(PixelCode); + const auto* code = mode == Mode::PixelLds ? LdsPixelCode.data() : mode == Mode::Table ? TablePixelCode.data() : mode == Mode::Gds ? GdsPixelCode.data() : mode == Mode::Storage ? StoragePixelCode.data() : mode == Mode::Bda ? BdaPixelCode.data() : buffer ? BufferPixelCode.data() : vertexSampling ? InterpolantPixelCode.data() : PixelCode.data(); + const auto bytes = mode == Mode::PixelLds ? sizeof(LdsPixelCode) : mode == Mode::Table ? sizeof(TablePixelCode) : mode == Mode::Gds ? sizeof(GdsPixelCode) : mode == Mode::Storage ? sizeof(StoragePixelCode) : mode == Mode::Bda ? sizeof(BdaPixelCode) : buffer ? sizeof(BufferPixelCode) : vertexSampling ? sizeof(InterpolantPixelCode) : sizeof(PixelCode); if (mode == Mode::Vertex) Registered(VertexHeader, SamplingVertexCode.data(), sizeof(SamplingVertexCode), 2); if (mode == Mode::VertexTable) Registered(VertexHeader, TableVertexCode.data(), sizeof(TableVertexCode), 2); Registered(PixelHeader, code, bytes, 1); @@ -301,6 +302,7 @@ int main() { DrawSamplesTheTexture(heap, Mode::VertexTable); DrawSamplesTheTexture(heap, Mode::MovedBuffer); DrawSamplesTheTexture(heap, Mode::MovedTexture); + DrawSamplesTheTexture(heap, Mode::PixelLds); DrawSamplesTheTexture(heap, Mode::Texture); if (heap && AgcDriver::Graphics::DescriptorHeapEnabled() && std::getenv("APS5_HEAP_SLOT_CAP") == nullptr) MixedDrawTakesThePerDrawPath(); if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) Require(AgcDriver::DriverDetail::HeapRefused(), "a draw found the capped heap full and the heap was not refused"); From 436a82de5ce477c5dfb13a9332f8b25f81fc3a06 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 24 Oct 2026 17:33:12 +0530 Subject: [PATCH 035/269] refactor(agc): split the GPU heap's long functions and wrap its lines No behaviour change. Only code this branch adds is touched; functions that exist on main keep their shape. - BindlessHeap: the texture, storage and view slot requests share one take-or-sweep, claim and free path; image and sampler descriptors are written directly instead of through a VkWriteDescriptorSet that was unpacked again; heapBindings returns one result struct instead of five out parameters, and the heap mappings are built by two helpers. - MaterializeHeapStage: the memo lookup, the walk's reads, the settle check (written twice before), the guards and the memo insert are separate functions. - ShaderResources::writeHeapStage: slot key, slot currency, slot taking, generations, verification and slot word patching are separate members; the table map and slot code share one placeholder view helper. - Statistics lines, the compute heap pipeline call and the heap draw sample's shader and message selection no longer sit in one line each. - The files this branch adds, and its heap functions in ShaderResources, are wrapped at 140 columns with clang-format (4-space indent, attached braces, short ifs and loops kept on one line, includes not sorted, string literals not split). Tested: full ctest -j4 -E agc_driver_bda_device passes as before (only the three sample_order tests fail); agc_driver_heap_draw_sample with and without APS5_GPU_HEAP under VK_LAYER_KHRONOS_validation reports no VUID. Co-Authored-By: Claude Opus 5.5 --- .../include/Driver/Draw/HeapStages.hpp | 17 +- .../Execution/src/Driver/Draw/HeapStages.cpp | 425 +++++++----- .../Execution/src/VulkanDevice.cpp | 10 +- .../Graphics/include/BindlessHeap.hpp | 65 +- .../Graphics/include/ShaderResources.hpp | 10 + .../Graphics/src/BindlessHeap.cpp | 646 ++++++++++-------- .../Graphics/src/DescriptorHeapObjects.cpp | 8 +- .../Graphics/src/GuestBufferMemory.cpp | 6 +- .../Graphics/src/ShaderResources.cpp | 398 ++++++----- .../tests/BindlessHeapSlots.cpp | 6 +- .../tests/execution/HeapComputeSample.cpp | 49 +- .../tests/execution/HeapDrawSample.cpp | 329 +++++++-- .../tests/execution/TessellationSubmit.cpp | 152 +++-- 13 files changed, 1337 insertions(+), 784 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index 0d6b1d28d2fa..ac20067074f4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -17,7 +17,8 @@ namespace AgcDriver::DriverDetail { bool HeapFragmentsEnabled(); bool HeapRefused(); bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage); -Graphics::HeapStageReason HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex); +Graphics::HeapStageReason HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, + bool heapVertex); bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex); std::optional HeapFragmentKnown(const void* snapshot, std::size_t codeOffset); void NoteHeapFragment(const void* snapshot, std::size_t codeOffset, bool eligible); @@ -48,13 +49,19 @@ struct HeapStageReads { bool complete = false; }; -std::shared_ptr MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase, ShaderRecompiler::HeapStageWords* words = nullptr, std::shared_ptr* sharedWords = nullptr, HeapStageReads* stageReads = nullptr); +std::shared_ptr +MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, + std::uint64_t shaderBase, ShaderRecompiler::HeapStageWords* words = nullptr, + std::shared_ptr* sharedWords = nullptr, HeapStageReads* stageReads = nullptr); void NoteHeapDirect(); -void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const ShaderRecompiler::RecompileResult& expected, const ShaderRecompiler::ResourceCapture* expectedCapture = nullptr); +void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const ShaderRecompiler::RecompileResult& expected, + const ShaderRecompiler::ResourceCapture* expectedCapture = nullptr); std::uint64_t HeapStagesTaken(); -std::shared_ptr PatchedHeapResult(const ShaderRecompiler::RecompileResult& shared, const ShaderRecompiler::HeapStageWords& words); +std::shared_ptr PatchedHeapResult(const ShaderRecompiler::RecompileResult& shared, + const ShaderRecompiler::HeapStageWords& words); void VerifyHeapAccessor(const Graphics::CompiledShader& stage); -void VerifyRingWords(const ShaderRecompiler::RecompileResult& kept, const ShaderRecompiler::HeapStageWords& ring, const ShaderRecompiler::RecompileResult& fresh, const ShaderRecompiler::HeapStageWords* freshWords); +void VerifyRingWords(const ShaderRecompiler::RecompileResult& kept, const ShaderRecompiler::HeapStageWords& ring, + const ShaderRecompiler::RecompileResult& fresh, const ShaderRecompiler::HeapStageWords* freshWords); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index eb7e341340f7..9b05e143cbb6 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -24,7 +24,8 @@ std::atomic& heapStages() { return count; } -const char* resultDifference(const ShaderRecompiler::RecompileResult& left, const ShaderRecompiler::RecompileResult& right, std::size_t& index) { +const char* resultDifference(const ShaderRecompiler::RecompileResult& left, const ShaderRecompiler::RecompileResult& right, + std::size_t& index) { index = 0; if (left.PipelineVariantId() != right.PipelineVariantId()) return "variant"; if (left.pushConstants != right.pushConstants) return "push constants"; @@ -37,14 +38,18 @@ const char* resultDifference(const ShaderRecompiler::RecompileResult& left, cons if (a.guestDescriptor != b.guestDescriptor) return "binding words"; } for (index = 0; index < left.specialization.size(); ++index) { - if (left.specialization[index].id != right.specialization[index].id || left.specialization[index].value != right.specialization[index].value) return "specialization"; + if (left.specialization[index].id != right.specialization[index].id || + left.specialization[index].value != right.specialization[index].value) + return "specialization"; } index = 0; if (left.vertexAttributes.size() != right.vertexAttributes.size()) return "attribute count"; for (index = 0; index < left.vertexAttributes.size(); ++index) { const auto& a = left.vertexAttributes[index]; const auto& b = right.vertexAttributes[index]; - if (a.location != b.location || a.components != b.components || a.resource.fields != b.resource.fields || a.fetchIndex != b.fetchIndex || a.formatComponents != b.formatComponents) return "attribute"; + const bool sameAttribute = a.location == b.location && a.components == b.components && a.resource.fields == b.resource.fields && + a.fetchIndex == b.fetchIndex && a.formatComponents == b.formatComponents; + if (!sameAttribute) return "attribute"; } return nullptr; } @@ -59,24 +64,42 @@ void reportHeapMismatch(const char* check, const char* what, const ShaderRecompi if (printed.fetch_add(1, std::memory_order_relaxed) >= 64u) return; const int role = index < result.bindings.size() ? static_cast(result.bindings[index].role) : -1; const int kind = index < result.bindings.size() ? static_cast(result.bindings[index].kind) : -1; - std::fprintf(stderr, "[heap-verify] %s: %s differ at %zu (role %d kind %d, template %llu, variant 0x%llx)\n", check, what, index, role, kind, static_cast(result.heapTemplateId), static_cast(result.PipelineVariantId())); + std::fprintf(stderr, "[heap-verify] %s: %s differ at %zu (role %d kind %d, template %llu, variant 0x%llx)\n", check, what, index, role, + kind, static_cast(result.heapTemplateId), static_cast(result.PipelineVariantId())); std::fflush(stderr); } struct VerifyCounts { - std::atomic verified{0}, differ{0}, notComparable{0}, accessor{0}, accessorDiffer{0}, ring{0}, ringDiffer{0}; + std::atomic verified{0}; + std::atomic differ{0}; + std::atomic notComparable{0}; + std::atomic accessor{0}; + std::atomic accessorDiffer{0}; + std::atomic ring{0}; + std::atomic ringDiffer{0}; }; +unsigned long long loaded(const std::atomic& counter) { + return static_cast(counter.load()); +} + +void reportVerifyCounts(const VerifyCounts& c) { + if (c.verified.load() != 0u || c.notComparable.load() != 0u) { + std::fprintf( + stderr, + "[heap-verify] %llu heap stages compared with a full capture, %llu differed, %llu not comparable (the full capture could not read every descriptor)\n", + loaded(c.verified), loaded(c.differ), loaded(c.notComparable)); + } + if (c.accessor.load() != 0u || c.ring.load() != 0u) { + std::fprintf(stderr, "[heap-verify] %llu accessor checks, %llu differed; %llu ring hits checked, %llu differed\n", + loaded(c.accessor), loaded(c.accessorDiffer), loaded(c.ring), loaded(c.ringDiffer)); + } +} + VerifyCounts& verifyCounts() { static VerifyCounts counts; static std::once_flag registered; - std::call_once(registered, [] { - std::atexit([] { - auto& c = verifyCounts(); - if (c.verified.load() != 0u || c.notComparable.load() != 0u) std::fprintf(stderr, "[heap-verify] %llu heap stages compared with a full capture, %llu differed, %llu not comparable (the full capture could not read every descriptor)\n", static_cast(c.verified.load()), static_cast(c.differ.load()), static_cast(c.notComparable.load())); - if (c.accessor.load() != 0u || c.ring.load() != 0u) std::fprintf(stderr, "[heap-verify] %llu accessor checks, %llu differed; %llu ring hits checked, %llu differed\n", static_cast(c.accessor.load()), static_cast(c.accessorDiffer.load()), static_cast(c.ring.load()), static_cast(c.ringDiffer.load())); - }); - }); + std::call_once(registered, [] { std::atexit([] { reportVerifyCounts(verifyCounts()); }); }); return counts; } @@ -109,15 +132,18 @@ bool HeapFragmentsEnabled() { bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage) { using Stage = ShaderRecompiler::ShaderStage; - return stage == Stage::Vertex || stage == Stage::Local || stage == Stage::TessellationControl || stage == Stage::TessellationEvaluation || stage == Stage::Mesh; + return stage == Stage::Vertex || stage == Stage::Local || stage == Stage::TessellationControl || + stage == Stage::TessellationEvaluation || stage == Stage::Mesh; } -Graphics::HeapStageReason HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex) { +Graphics::HeapStageReason HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, + bool heapVertex) { using Reason = Graphics::HeapStageReason; if (stage != ShaderRecompiler::ShaderStage::Fragment && !HeapPreRasterStage(stage)) return Reason::StageKind; if (plan == nullptr) return Reason::NoPlan; if (stage != ShaderRecompiler::ShaderStage::Fragment && !heapVertex) return Reason::FragmentOffHeap; - if (plan->stage == ShaderRecompiler::IrShaderStage::Unknown || plan->stage == ShaderRecompiler::IrShaderStage::Fetch) return Reason::PlanStage; + if (plan->stage == ShaderRecompiler::IrShaderStage::Unknown || plan->stage == ShaderRecompiler::IrShaderStage::Fetch) + return Reason::PlanStage; if (!ShaderRecompiler::HeapFragmentEligible(*plan)) return Reason::UnresolvedImageSource; return Reason::Heap; } @@ -151,7 +177,8 @@ bool HeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool wor const auto key = result.variantId * 2u + (workgroupAddress ? 1u : 0u); if (const auto found = known.find(key); found != known.end()) return found->second; if (known.size() >= 65536u) known.clear(); - const bool mappable = Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), workgroupAddress, result.dataAddressPush, result.functionLdsBuffer); + const bool mappable = Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), + workgroupAddress, result.dataAddressPush, result.functionLdsBuffer); known.emplace(key, mappable); return mappable; } @@ -165,7 +192,9 @@ struct HeapFragmentKey { }; struct HeapFragmentKeyHash { - std::size_t operator()(const HeapFragmentKey& key) const { return std::hash{}(key.snapshot) ^ (key.codeOffset * 0x9e3779b97f4a7c15ull); } + std::size_t operator()(const HeapFragmentKey& key) const { + return std::hash{}(key.snapshot) ^ (key.codeOffset * 0x9e3779b97f4a7c15ull); + } }; std::unordered_map& heapFragments() { @@ -263,150 +292,200 @@ HeapWalkMemo& heapWalkMemo() { } -std::shared_ptr MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase, ShaderRecompiler::HeapStageWords* words, std::shared_ptr* sharedWords, HeapStageReads* stageReads) { - const auto finish = [&](const std::shared_ptr& capture) { - if (words != nullptr) { - if (auto shared = invocation.MaterializeHeap(*capture, *words)) return shared; - } - return invocation.Materialize(*capture); - }; - { - struct Reads { - std::vector words; - std::uint64_t page = ~std::uint64_t{0}; - std::vector> accessible; - bool failed = false; - }; - struct ReadsStorage {}; - struct RangesStorage {}; - auto& reads = HostThreadLocal(); - auto& ranges = HostThreadLocal>, RangesStorage>(); - reads.words.clear(); - reads.accessible.clear(); - reads.failed = false; - reads.page = ~std::uint64_t{0}; - Graphics::HeapCostScope snapshotCost(Graphics::HeapCost::Guards); - const auto before = Graphics::Recorder::PendingWriteSnapshot(); - snapshotCost.Stop(); - const auto generation = GuestMemory::TrackerGeneration(); - const bool memoOn = words != nullptr && !invocation.Request().context.vertex.has_value(); - std::uint64_t memoKey = 0; - bool memoKnown = false; - Graphics::HeapCostScope memoCost(Graphics::HeapCost::WalkMemo); - if (memoOn) { - memoKey = (invocation.VariantId() * 0x9e3779b97f4a7c15ull ^ shaderBase) + invocation.Request().layout.pushConstantOffsetBytes; - for (const auto word : userData) memoKey = (memoKey ^ word) * 0x100000001b3ull; - auto* found = heapWalkMemo().find(memoKey); - memoKnown = found != nullptr; - for (std::size_t way = 0; found != nullptr && way < found->size(); ++way) { - const auto& entry = (*found)[way]; - bool equal = entry.variant == invocation.VariantId() && entry.shaderBase == shaderBase && entry.pushOffset == invocation.Request().layout.pushConstantOffsetBytes && std::equal(entry.userData.begin(), entry.userData.end(), userData.begin(), userData.end()); - if (!equal) continue; - std::size_t cursor = 0; - for (std::size_t r = 0; equal && r < entry.ranges.size(); ++r) { - const auto [begin, end] = entry.ranges[r]; - const auto count = static_cast((end - begin) / 4u); - equal = GuestMemory::CompareMapped(begin, std::as_bytes(std::span(entry.values.data() + cursor, count))) == GuestMemory::Compare::Equal; - cursor += count; - } - for (std::size_t a = 0; equal && a < entry.accessible.size(); ++a) equal = GuestMemory::Accessible(reinterpret_cast(entry.accessible[a].first), static_cast(entry.accessible[a].second)); - if (!equal) { - continue; - } - bool settled = !(DrawPipeline::Active() && DrawPipeline::Queue0().Busy() && DrawPipeline::Queue0().OverlapsAny(entry.ranges)) && Graphics::Recorder::ReadsSettled(entry.ranges, before.get()); - for (std::size_t r = 0; settled && r < entry.ranges.size(); ++r) settled = GuestMemory::NewestStamp(entry.ranges[r].first, static_cast(entry.ranges[r].second - entry.ranges[r].first)) <= generation; - if (!settled) { - break; - } - for (const auto& [begin, end] : entry.ranges) GuestMemory::GuardRead(begin, static_cast(end - begin)); - if (sharedWords != nullptr) *sharedWords = entry.words; - else *words = *entry.words; - if (stageReads != nullptr) *stageReads = {entry.ranges, entry.values, entry.userDataUse, entry.capture, true}; - auto result = entry.result; - if (way != 0) std::rotate(found->begin(), found->begin() + static_cast(way), found->begin() + static_cast(way) + 1); - return result; - } - } - memoCost.Stop(); - Graphics::HeapCostScope walkCost(Graphics::HeapCost::Walk); - ShaderRecompiler::SrtRuntime plain; - plain.userData = userData; - plain.shaderBase = shaderBase; - plain.userContext = &reads; - plain.readMemory = [](void* context, std::uint64_t address, std::uint32_t* value) { - auto& self = *static_cast(context); - const auto page = address & ~std::uint64_t{0xfff}; - if (page != self.page || (address & 0xfffu) > 0x1000u - sizeof(*value)) { - if (GuestMemory::Accessible(reinterpret_cast(page), 0x1000u)) self.page = page; - else if (!GuestMemory::Accessible(reinterpret_cast(address), sizeof(*value))) { - self.failed = true; - return false; - } - } - std::memcpy(value, reinterpret_cast(address), sizeof(*value)); - self.words.push_back(address); - return true; - }; - plain.accessible = [](void* context, std::uint64_t address, std::uint64_t bytes) { - auto& self = *static_cast(context); - const bool accessible = GuestMemory::Accessible(reinterpret_cast(address), static_cast(bytes)); - if (accessible) self.accessible.emplace_back(address, bytes); - else self.failed = true; - return accessible; - }; - auto capture = invocation.Capture(plain); - std::sort(reads.words.begin(), reads.words.end()); - ranges.clear(); - for (const auto address : reads.words) { - if (!ranges.empty() && address <= ranges.back().second) { - ranges.back().second = std::max(ranges.back().second, address + 4u); - continue; - } - ranges.emplace_back(address, address + 4u); +namespace { + +using AddressRanges = std::vector>; + +struct WalkReads { + std::vector words; + std::uint64_t page = ~std::uint64_t{0}; + AddressRanges accessible; + bool failed = false; + + void Reset() { + words.clear(); + accessible.clear(); + failed = false; + page = ~std::uint64_t{0}; + } +}; + +bool readWalkWord(void* context, std::uint64_t address, std::uint32_t* value) { + auto& reads = *static_cast(context); + const auto page = address & ~std::uint64_t{0xfff}; + const bool crossesPage = (address & 0xfffu) > 0x1000u - sizeof(*value); + if (page != reads.page || crossesPage) { + if (GuestMemory::Accessible(reinterpret_cast(page), 0x1000u)) reads.page = page; + else if (!GuestMemory::Accessible(reinterpret_cast(address), sizeof(*value))) { + reads.failed = true; + return false; } - struct ValuesStorage {}; - auto& values = HostThreadLocal, ValuesStorage>(); - if ((memoOn || stageReads != nullptr) && !reads.failed) { - values.clear(); - for (const auto& [begin, end] : ranges) { - const auto offset = values.size(); - values.resize(offset + static_cast((end - begin) / 4u)); - std::memcpy(values.data() + offset, reinterpret_cast(begin), static_cast(end - begin)); - } + } + std::memcpy(value, reinterpret_cast(address), sizeof(*value)); + reads.words.push_back(address); + return true; +} + +bool walkAccessible(void* context, std::uint64_t address, std::uint64_t bytes) { + auto& reads = *static_cast(context); + const bool accessible = GuestMemory::Accessible(reinterpret_cast(address), static_cast(bytes)); + if (accessible) reads.accessible.emplace_back(address, bytes); + else reads.failed = true; + return accessible; +} + +void coalesceWords(std::vector& words, AddressRanges& ranges) { + std::sort(words.begin(), words.end()); + ranges.clear(); + for (const auto address : words) { + if (!ranges.empty() && address <= ranges.back().second) { + ranges.back().second = std::max(ranges.back().second, address + 4u); + continue; } - bool settled = !(DrawPipeline::Active() && DrawPipeline::Queue0().Busy() && DrawPipeline::Queue0().OverlapsAny(ranges)) && Graphics::Recorder::ReadsSettled(ranges, before.get()); - for (std::size_t i = 0; settled && i < ranges.size(); ++i) settled = GuestMemory::NewestStamp(ranges[i].first, static_cast(ranges[i].second - ranges[i].first)) <= generation; - walkCost.Stop(); - if (settled) { - Graphics::HeapCostScope guardCost(Graphics::HeapCost::Guards); - for (const auto& [begin, end] : ranges) GuestMemory::GuardRead(begin, static_cast(end - begin)); - guardCost.Stop(); - Graphics::HeapCostScope materializeCost(Graphics::HeapCost::Materialize); - auto result = finish(capture); - materializeCost.Stop(); - if (stageReads != nullptr && !reads.failed && result != nullptr) *stageReads = {ranges, values, capture->userDataUse, capture, true}; - Graphics::HeapCostScope insertCost(Graphics::HeapCost::MemoInsert); - if (memoOn && !reads.failed && result != nullptr && (memoKnown || heapWalkMemo().admit(memoKey))) { - auto& ways = heapWalkMemo().slot(memoKey); - if (ways.size() >= HeapWalkWays) ways.pop_back(); - ways.emplace(ways.begin()); - auto& entry = ways.front(); - entry.variant = invocation.VariantId(); - entry.pushOffset = invocation.Request().layout.pushConstantOffsetBytes; - entry.shaderBase = shaderBase; - entry.userData.assign(userData.begin(), userData.end()); - entry.ranges = ranges; - entry.values = values; - entry.accessible = reads.accessible; - entry.userDataUse = capture->userDataUse; - entry.capture = capture; - entry.result = result; - entry.words = std::make_shared(*words); - } + ranges.emplace_back(address, address + 4u); + } +} + +void copyRangeValues(const AddressRanges& ranges, std::vector& values) { + values.clear(); + for (const auto& [begin, end] : ranges) { + const auto offset = values.size(); + values.resize(offset + static_cast((end - begin) / 4u)); + std::memcpy(values.data() + offset, reinterpret_cast(begin), static_cast(end - begin)); + } +} + +bool rangesSettled(const AddressRanges& ranges, const Graphics::Recorder::WriteRanges* before, std::uint64_t generation) { + const bool queuedWrite = DrawPipeline::Active() && DrawPipeline::Queue0().Busy() && DrawPipeline::Queue0().OverlapsAny(ranges); + if (queuedWrite || !Graphics::Recorder::ReadsSettled(ranges, before)) return false; + for (const auto& [begin, end] : ranges) { + if (GuestMemory::NewestStamp(begin, static_cast(end - begin)) > generation) return false; + } + return true; +} + +void guardRanges(const AddressRanges& ranges) { + for (const auto& [begin, end] : ranges) GuestMemory::GuardRead(begin, static_cast(end - begin)); +} + +std::uint64_t walkMemoKey(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, + std::uint64_t shaderBase) { + auto key = (invocation.VariantId() * 0x9e3779b97f4a7c15ull ^ shaderBase) + invocation.Request().layout.pushConstantOffsetBytes; + for (const auto word : userData) key = (key ^ word) * 0x100000001b3ull; + return key; +} + +bool sameWalkInputs(const HeapWalkEntry& entry, const ShaderRecompiler::PreparedShaderInvocation& invocation, + std::span userData, std::uint64_t shaderBase) { + const bool sameStage = entry.variant == invocation.VariantId() && entry.shaderBase == shaderBase && + entry.pushOffset == invocation.Request().layout.pushConstantOffsetBytes; + if (!sameStage || !std::equal(entry.userData.begin(), entry.userData.end(), userData.begin(), userData.end())) return false; + std::size_t cursor = 0; + for (const auto& [begin, end] : entry.ranges) { + const auto count = static_cast((end - begin) / 4u); + if (GuestMemory::CompareMapped(begin, std::as_bytes(std::span(entry.values.data() + cursor, count))) != GuestMemory::Compare::Equal) + return false; + cursor += count; + } + for (const auto& [address, bytes] : entry.accessible) { + if (!GuestMemory::Accessible(reinterpret_cast(address), static_cast(bytes))) return false; + } + return true; +} + +void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderInvocation& invocation, + std::span userData, std::uint64_t shaderBase, const AddressRanges& ranges, + const std::vector& values, const AddressRanges& accessible, + const std::shared_ptr& capture, + const std::shared_ptr& result, const ShaderRecompiler::HeapStageWords& words) { + auto& ways = heapWalkMemo().slot(memoKey); + if (ways.size() >= HeapWalkWays) ways.pop_back(); + ways.emplace(ways.begin()); + auto& entry = ways.front(); + entry.variant = invocation.VariantId(); + entry.pushOffset = invocation.Request().layout.pushConstantOffsetBytes; + entry.shaderBase = shaderBase; + entry.userData.assign(userData.begin(), userData.end()); + entry.ranges = ranges; + entry.values = values; + entry.accessible = accessible; + entry.userDataUse = capture->userDataUse; + entry.capture = capture; + entry.result = result; + entry.words = std::make_shared(words); +} + +} + +std::shared_ptr +MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, + std::uint64_t shaderBase, ShaderRecompiler::HeapStageWords* words, + std::shared_ptr* sharedWords, HeapStageReads* stageReads) { + struct ReadsStorage {}; + struct RangesStorage {}; + struct ValuesStorage {}; + auto& reads = HostThreadLocal(); + auto& ranges = HostThreadLocal(); + reads.Reset(); + Graphics::HeapCostScope snapshotCost(Graphics::HeapCost::Guards); + const auto before = Graphics::Recorder::PendingWriteSnapshot(); + snapshotCost.Stop(); + const auto generation = GuestMemory::TrackerGeneration(); + const bool memoOn = words != nullptr && !invocation.Request().context.vertex.has_value(); + std::uint64_t memoKey = 0; + bool memoKnown = false; + + Graphics::HeapCostScope memoCost(Graphics::HeapCost::WalkMemo); + if (memoOn) { + memoKey = walkMemoKey(invocation, userData, shaderBase); + auto* found = heapWalkMemo().find(memoKey); + memoKnown = found != nullptr; + for (std::size_t way = 0; found != nullptr && way < found->size(); ++way) { + const auto& entry = (*found)[way]; + if (!sameWalkInputs(entry, invocation, userData, shaderBase)) continue; + if (!rangesSettled(entry.ranges, before.get(), generation)) break; + guardRanges(entry.ranges); + if (sharedWords != nullptr) *sharedWords = entry.words; + else *words = *entry.words; + if (stageReads != nullptr) *stageReads = {entry.ranges, entry.values, entry.userDataUse, entry.capture, true}; + auto result = entry.result; + if (way != 0) + std::rotate(found->begin(), found->begin() + static_cast(way), + found->begin() + static_cast(way) + 1); return result; } } - return nullptr; + memoCost.Stop(); + + Graphics::HeapCostScope walkCost(Graphics::HeapCost::Walk); + ShaderRecompiler::SrtRuntime runtime; + runtime.userData = userData; + runtime.shaderBase = shaderBase; + runtime.userContext = &reads; + runtime.readMemory = readWalkWord; + runtime.accessible = walkAccessible; + auto capture = invocation.Capture(runtime); + coalesceWords(reads.words, ranges); + auto& values = HostThreadLocal, ValuesStorage>(); + if ((memoOn || stageReads != nullptr) && !reads.failed) copyRangeValues(ranges, values); + const bool settled = rangesSettled(ranges, before.get(), generation); + walkCost.Stop(); + if (!settled) return nullptr; + + Graphics::HeapCostScope guardCost(Graphics::HeapCost::Guards); + guardRanges(ranges); + guardCost.Stop(); + Graphics::HeapCostScope materializeCost(Graphics::HeapCost::Materialize); + std::shared_ptr result; + if (words != nullptr) result = invocation.MaterializeHeap(*capture, *words); + if (result == nullptr) result = invocation.Materialize(*capture); + materializeCost.Stop(); + const bool complete = !reads.failed && result != nullptr; + if (stageReads != nullptr && complete) *stageReads = {ranges, values, capture->userDataUse, capture, true}; + Graphics::HeapCostScope insertCost(Graphics::HeapCost::MemoInsert); + if (memoOn && complete && (memoKnown || heapWalkMemo().admit(memoKey))) + rememberWalk(memoKey, invocation, userData, shaderBase, ranges, values, reads.accessible, capture, result, *words); + return result; } namespace { @@ -427,17 +506,24 @@ std::uint64_t HeapStagesTaken() { return heapStages().load(); } -std::shared_ptr PatchedHeapResult(const ShaderRecompiler::RecompileResult& shared, const ShaderRecompiler::HeapStageWords& words) { +std::shared_ptr PatchedHeapResult(const ShaderRecompiler::RecompileResult& shared, + const ShaderRecompiler::HeapStageWords& words) { auto result = std::make_shared(shared); for (auto& binding : result->bindings) { - if (binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt && !words.flattenedSrt.empty()) binding.guestDescriptor = words.flattenedSrt; - if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) std::copy_n(words.userData.begin(), std::min(words.userData.size(), binding.guestDescriptor.size()), binding.guestDescriptor.begin()); + if (binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt && !words.flattenedSrt.empty()) + binding.guestDescriptor = words.flattenedSrt; + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) + std::copy_n(words.userData.begin(), std::min(words.userData.size(), binding.guestDescriptor.size()), + binding.guestDescriptor.begin()); } if (!words.bindings.empty()) { - if (words.bindings.size() != result->bindings.size()) throw std::runtime_error("a heap stage's per-draw bindings differ in number from its template"); + if (words.bindings.size() != result->bindings.size()) + throw std::runtime_error("a heap stage's per-draw bindings differ in number from its template"); for (std::size_t index = 0; index < words.bindings.size(); ++index) { if (words.bindings[index].empty()) continue; - if (result->bindings[index].role != ShaderRecompiler::DescriptorRole::FlattenedSrt && words.bindings[index].size() != result->bindings[index].guestDescriptor.size()) throw std::runtime_error("a heap stage's per-draw descriptor words differ in size from its template"); + if (result->bindings[index].role != ShaderRecompiler::DescriptorRole::FlattenedSrt && + words.bindings[index].size() != result->bindings[index].guestDescriptor.size()) + throw std::runtime_error("a heap stage's per-draw descriptor words differ in size from its template"); result->bindings[index].guestDescriptor = words.bindings[index]; } } @@ -449,11 +535,14 @@ void NoteHeapDirect() { heapStages().fetch_add(1, std::memory_order_relaxed); } -void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const ShaderRecompiler::RecompileResult& expected, const ShaderRecompiler::ResourceCapture* expectedCapture) { +void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const ShaderRecompiler::RecompileResult& expected, + const ShaderRecompiler::ResourceCapture* expectedCapture) { auto& counts = verifyCounts(); if (expectedCapture != nullptr) { const auto partial = [](const std::vector& values) { - return std::ranges::any_of(values, [](const ShaderRecompiler::DescriptorValue& value) { return value.availableDwordMask != static_cast((1u << value.dwordCount) - 1u); }); + return std::ranges::any_of(values, [](const ShaderRecompiler::DescriptorValue& value) { + return value.availableDwordMask != static_cast((1u << value.dwordCount) - 1u); + }); }; const auto& snapshot = expectedCapture->snapshot; if (partial(snapshot.buffers) || partial(snapshot.images) || partial(snapshot.samplers)) { @@ -481,16 +570,20 @@ void VerifyHeapAccessor(const Graphics::CompiledShader& stage) { } const auto& attributes = Graphics::DrawVertexAttributes(stage); bool sameAttributes = attributes.size() == patched->vertexAttributes.size(); - for (std::size_t index = 0; sameAttributes && index < attributes.size(); ++index) sameAttributes = attributes[index].resource.fields == patched->vertexAttributes[index].resource.fields && attributes[index].fetchIndex == patched->vertexAttributes[index].fetchIndex; + for (std::size_t index = 0; sameAttributes && index < attributes.size(); ++index) + sameAttributes = attributes[index].resource.fields == patched->vertexAttributes[index].resource.fields && + attributes[index].fetchIndex == patched->vertexAttributes[index].fetchIndex; if (!sameAttributes) { counts.accessorDiffer.fetch_add(1, std::memory_order_relaxed); reportHeapMismatch("accessor vs patched result", "vertex attributes", *patched, 0); } } -void VerifyRingWords(const ShaderRecompiler::RecompileResult& kept, const ShaderRecompiler::HeapStageWords& ring, const ShaderRecompiler::RecompileResult& fresh, const ShaderRecompiler::HeapStageWords* freshWords) { +void VerifyRingWords(const ShaderRecompiler::RecompileResult& kept, const ShaderRecompiler::HeapStageWords& ring, + const ShaderRecompiler::RecompileResult& fresh, const ShaderRecompiler::HeapStageWords* freshWords) { const auto reused = PatchedHeapResult(kept, ring); - const auto expected = freshWords != nullptr ? PatchedHeapResult(fresh, *freshWords) : std::make_shared(fresh); + const auto expected = + freshWords != nullptr ? PatchedHeapResult(fresh, *freshWords) : std::make_shared(fresh); auto& counts = verifyCounts(); counts.ring.fetch_add(1, std::memory_order_relaxed); std::size_t index = 0; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index fc17d90bc204..2a674c6e29f4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -5311,10 +5311,14 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons if (profile && shader.spirv.size() > 100000) std::fprintf(stderr, "[dispatch] creating a pipeline for %zu SPIR-V words (program 0x%llx)\n", shader.spirv.size(), static_cast(programAddress)); std::vector heapMappings; const bool workgroupAddress = shader.workgroupMemoryDwords != 0; - objects->descriptorHeap = gpuMode && context.descriptorHeap && Graphics::DescriptorHeapEnabled() && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(std::span(shader.spirv.data(), shader.spirv.size()), heapMappings, workgroupAddress ? Graphics::ComputePushConstantBytes : ~0u, shader.dataAddressPush); + const bool heapDevice = gpuMode && context.descriptorHeap && Graphics::DescriptorHeapEnabled(); + const auto workgroupAddressOffset = workgroupAddress ? Graphics::ComputePushConstantBytes : ~0u; + const std::span spirv(shader.spirv.data(), shader.spirv.size()); + objects->descriptorHeap = heapDevice && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(spirv, heapMappings, workgroupAddressOffset, shader.dataAddressPush); require(!gpuMode || objects->descriptorHeap, "a GPU-mode compute stage does not map onto VK_EXT_descriptor_heap"); - if (objects->descriptorHeap) CreateComputeHeapPipeline(state->device, state->DeviceFunction("vkCreateComputePipelines"), context.pipelineCache, objects->module, computePipelineFlags(), stageFlags, specialization.Info(), subgroupSize, heapMappings, &objects->pipeline, context.pipelineCacheSynchronization); - else CreateComputePipeline(state->device, state->DeviceFunction("vkCreateComputePipelines"), context.pipelineCache, objects->module, objects->layout, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, &objects->pipeline, context.pipelineCacheSynchronization); + const auto createPipelines = state->DeviceFunction("vkCreateComputePipelines"); + if (objects->descriptorHeap) CreateComputeHeapPipeline(state->device, createPipelines, context.pipelineCache, objects->module, computePipelineFlags(), stageFlags, specialization.Info(), subgroupSize, heapMappings, &objects->pipeline, context.pipelineCacheSynchronization); + else CreateComputePipeline(state->device, createPipelines, context.pipelineCache, objects->module, objects->layout, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, &objects->pipeline, context.pipelineCacheSynchronization); objects->destroyModule(objects->device, objects->module, nullptr); objects->module = VK_NULL_HANDLE; if (!state->probingFloatControls) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 3f5e67b5b04c..63fe11727f81 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -37,12 +37,15 @@ class BindlessHeap { VkDeviceSize ImageHeapStride() const { return imageHeapStride; } VkDeviceSize SamplerHeapStride() const { return samplerHeapStride; } void BindDescriptorHeaps(VkCommandBuffer commands) const; - bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset = ~0u, bool rootGds = false, bool rootFault = false, bool pixelLds = false) const; + bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, + std::uint32_t workgroupAddressOffset = ~0u, bool rootGds = false, bool rootFault = false, + bool pixelLds = false) const; void WritePixelLdsBuffer(VkDeviceAddress address, VkDeviceSize bytes); VkDeviceAddress RingAddress() const; VkBuffer RingBuffer() const; - std::optional TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, VkImageLayout layout); + std::optional TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, + VkImageLayout layout); std::optional StorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view); std::optional ViewSlot(std::uint32_t kind, const void* owner, VkImageView view); void ReleaseViewSlots(const void* owner); @@ -51,7 +54,8 @@ class BindlessHeap { std::optional SamplerSlot(const std::shared_ptr& sampler); std::uint32_t SamplerGeneration(std::uint32_t slot) const; std::uint64_t SlotSerial() const { return slotSerial.load(std::memory_order_acquire); } - bool GenerationsCurrent(std::span> slots, std::span slotGenerations, std::span samplerSlots, std::span samplerGenerations) const; + bool GenerationsCurrent(std::span> slots, std::span slotGenerations, + std::span samplerSlots, std::span samplerGenerations) const; std::uint32_t AbsentSlot(std::uint32_t kind, VkImageView view); static bool NearlyFull(); static void NoteSweepDue(); @@ -92,7 +96,8 @@ class BindlessHeap { VkDeviceSize resourceHeapUsed = 0; VkDeviceSize pixelLdsHeapOffset = 0; VkDeviceSize samplerHeapUsed = 0; - void writeDescriptorHeap(const VkWriteDescriptorSet& write); + void writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImageView view, VkImageLayout layout); + void writeSamplerSlot(std::uint32_t slot, VkSampler sampler); static constexpr std::size_t RingChunkBytes = 4u << 20u; struct Chunk { Recorder* recorder = nullptr; @@ -115,7 +120,11 @@ class BindlessHeap { bool operator==(const TextureKey&) const = default; }; struct TextureKeyHash { - std::size_t operator()(const TextureKey& key) const { return std::hash{}(key.texture) ^ std::hash{}(reinterpret_cast(key.view)) ^ (static_cast(key.kind) << 48u) ^ (static_cast(key.layout) << 40u); } + std::size_t operator()(const TextureKey& key) const { + const auto texture = std::hash{}(key.texture); + const auto view = std::hash{}(reinterpret_cast(key.view)); + return texture ^ view ^ (static_cast(key.kind) << 48u) ^ (static_cast(key.layout) << 40u); + } }; std::unordered_map textureSlots; std::unordered_map>> viewSlots; @@ -132,6 +141,10 @@ class BindlessHeap { std::uint64_t slotRequests = 0; void sweepLocked(std::vector>& dropped); std::optional takeSlotLocked(std::uint32_t kind); + std::optional takeOrSweepLocked(std::uint32_t kind, std::vector>& dropped); + SlotOwner& claimSlotLocked(const TextureKey& key, std::uint32_t slot); + void freeSlotLocked(std::uint32_t kind, std::uint32_t slot); + const SlotOwner* ownerLocked(std::uint32_t kind, std::uint32_t slot) const; std::unordered_map samplerSlots; std::unordered_map absentSlots; std::vector> heldSamplers; @@ -161,24 +174,52 @@ std::uint64_t EmptyResourceSets(); std::uint64_t DataAddressPushes(); enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, Count }; enum class HeapFallback : std::uint8_t { DrawUnmapped, DrawMixedRetry, DrawRefusedPair, DrawMixedReused, DispatchUnmapped, Count }; -enum class HeapStageReason : std::uint8_t { Heap, Disabled, PairRefused, FragmentOffHeap, StageKind, NoPlan, PlanStage, UnresolvedImageSource, KnownIneligible, Count }; +enum class HeapStageReason : std::uint8_t { + Heap, + Disabled, + PairRefused, + FragmentOffHeap, + StageKind, + NoPlan, + PlanStage, + UnresolvedImageSource, + KnownIneligible, + Count +}; void NoteHeapStageReason(HeapStageReason reason); void NoteHeapRecord(bool compute, bool heap); void NoteHeapFallback(HeapFallback reason); std::uint64_t HeapFallbacks(HeapFallback reason); void NoteCpuBufferCopy(std::uint64_t bytes); -enum class HeapCost : std::uint8_t { StagePrepare, HeapStageCall, StageFinish, WalkMemo, Walk, Materialize, TemplateFind, TemplateBuild, Slots, StageData, BufferAddresses, MemoInsert, Guards, Count }; +enum class HeapCost : std::uint8_t { + StagePrepare, + HeapStageCall, + StageFinish, + WalkMemo, + Walk, + Materialize, + TemplateFind, + TemplateBuild, + Slots, + StageData, + BufferAddresses, + MemoInsert, + Guards, + Count +}; bool HeapCostTimed(); void NoteHeapCost(HeapCost cost, std::uint64_t nanoseconds); class HeapCostScope { public: - explicit HeapCostScope(HeapCost cost) : cost(cost), start(HeapCostTimed() ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}) {} + explicit HeapCostScope(HeapCost cost) : + cost(cost), start(HeapCostTimed() ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}) {} ~HeapCostScope() { Stop(); } HeapCostScope(const HeapCostScope&) = delete; HeapCostScope& operator=(const HeapCostScope&) = delete; void Stop() { if (start == std::chrono::steady_clock::time_point{}) return; - NoteHeapCost(cost, static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count())); + NoteHeapCost(cost, static_cast( + std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count())); start = {}; } @@ -187,8 +228,10 @@ class HeapCostScope { std::chrono::steady_clock::time_point start; }; void NoteCommandBufferBegun(VkCommandBuffer commands); -void CmdPushConstants(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, std::uint32_t size, const void* values); -void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site); +void CmdPushConstants(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout, VkShaderStageFlags stages, + std::uint32_t offset, std::uint32_t size, const void* values); +void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, + std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site); std::uint64_t DescriptorHeapBinds(); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 9230f65adb10..b92c65456927 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -631,6 +631,16 @@ class ShaderResources { }; std::array heapStages; std::uint32_t heapSpan(HeapStageState::KeptSpan& kept, std::span words); + bool ownsHeapBinding(const Binding& binding, VkShaderStageFlags stageBit) const; + VkImageView heapPlaceholderView(std::uint32_t kind) const; + VkImageView heapSampledView(std::size_t index) const; + VkImageView heapStorageView(std::size_t index) const; + void appendHeapSlotKey(VkShaderStageFlags stageBit, std::vector& key) const; + static bool heapSlotsCurrent(const BindlessHeap& heap, const HeapStageState& state); + void takeHeapSlots(BindlessHeap& heap, HeapStageState& state, VkShaderStageFlags stageBit, std::span key); + static void noteHeapSlotGenerations(const BindlessHeap& heap, HeapStageState& state); + void verifyHeapSlots(const BindlessHeap& heap, const HeapStageState& state, VkShaderStageFlags stageBit) const; + void patchHeapSlotWords(const CompiledShader& shader, const HeapStageState& stageState, std::vector& patched, bool current) const; static constexpr std::int64_t HeapRingDataFirst = -2; static constexpr std::int64_t HeapRingData(std::size_t stage) { return HeapRingDataFirst - static_cast(stage); } static constexpr bool IsHeapRingData(std::int64_t allocation) { return allocation <= HeapRingDataFirst && allocation > HeapRingDataFirst - static_cast(ShaderRecompiler::RuntimeAbi::StageCount); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 6c1492ff2561..4cbb7a8943e0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -1,8 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" - -#include -#include #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" @@ -10,18 +7,19 @@ #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "RuntimeAbi.hpp" #include "SpirvBackend/SpirvAnalysis.hpp" -#include #include #include #include #include #include #include +#include #include -#include #include #include #include +#include +#include namespace AgcDriver::Graphics { @@ -30,16 +28,18 @@ namespace { namespace Abi = ShaderRecompiler::RuntimeAbi; void check(VkResult result, const char* what) { - if (result != VK_SUCCESS) throw std::runtime_error(std::string("AGC bindless heap: ") + what + " failed: " + std::to_string(static_cast(result))); -} - -std::uint32_t fragmentBinding(std::uint32_t kind) { - return Abi::BindingNumber(Abi::Stage::Fragment, static_cast(kind)); + if (result != VK_SUCCESS) + throw std::runtime_error(std::string("AGC bindless heap: ") + what + " failed: " + std::to_string(static_cast(result))); } std::atomic spansWrittenWindow{0}; std::atomic spansKeptWindow{0}; std::atomic spansExpiredWindow{0}; +std::atomic heapComputeStages{0}; +std::atomic descriptorHeapDevice{false}; +std::atomic imageTableBuilds{0}; +std::atomic dataAddressPushes{0}; +std::atomic emptyResourceSets{0}; } @@ -48,14 +48,6 @@ bool GpuHeapEnabled() { return enabled; } -namespace { -std::atomic heapComputeStages{0}; -std::atomic descriptorHeapDevice{false}; -std::atomic imageTableBuilds{0}; -std::atomic dataAddressPushes{0}; -std::atomic emptyResourceSets{0}; -} - void NoteImageTableBuild() { imageTableBuilds.fetch_add(1, std::memory_order_relaxed); } @@ -103,17 +95,26 @@ bool HeapComputeEnabled() { namespace { struct HeapSizes { - VkDeviceSize imageStride = 0, samplerStride = 0, pixelLdsOffset = 0, resourceUsed = 0, samplerUsed = 0; + VkDeviceSize imageStride = 0; + VkDeviceSize samplerStride = 0; + VkDeviceSize pixelLdsOffset = 0; + VkDeviceSize resourceUsed = 0; + VkDeviceSize samplerUsed = 0; }; +VkDeviceSize alignUp(VkDeviceSize value, VkDeviceSize alignment) { + return alignment == 0 ? value : (value + alignment - 1) / alignment * alignment; +} + HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { - const auto align = [](VkDeviceSize value, VkDeviceSize alignment) { return alignment == 0 ? value : (value + alignment - 1) / alignment * alignment; }; + constexpr auto imageKinds = static_cast(BindlessHeap::SamplerKind); HeapSizes sizes; - sizes.imageStride = align(properties.imageDescriptorSize, properties.imageDescriptorAlignment); - sizes.samplerStride = align(properties.samplerDescriptorSize, properties.samplerDescriptorAlignment); - sizes.pixelLdsOffset = align(static_cast(static_cast(Abi::Binding::Samplers)) * Abi::GpuImageHeapSlots * sizes.imageStride, properties.bufferDescriptorAlignment); - sizes.resourceUsed = align(sizes.pixelLdsOffset + properties.bufferDescriptorSize, properties.resourceHeapAlignment); - sizes.samplerUsed = align(static_cast(Abi::GpuSamplerHeapSlots) * sizes.samplerStride, properties.samplerHeapAlignment); + sizes.imageStride = alignUp(properties.imageDescriptorSize, properties.imageDescriptorAlignment); + sizes.samplerStride = alignUp(properties.samplerDescriptorSize, properties.samplerDescriptorAlignment); + const auto imageBytes = imageKinds * Abi::GpuImageHeapSlots * sizes.imageStride; + sizes.pixelLdsOffset = alignUp(imageBytes, properties.bufferDescriptorAlignment); + sizes.resourceUsed = alignUp(sizes.pixelLdsOffset + properties.bufferDescriptorSize, properties.resourceHeapAlignment); + sizes.samplerUsed = alignUp(static_cast(Abi::GpuSamplerHeapSlots) * sizes.samplerStride, properties.samplerHeapAlignment); return sizes; } @@ -121,7 +122,9 @@ HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& propertie bool BindlessHeap::Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { const auto sizes = heapSizes(properties); - return sizes.resourceUsed + properties.minResourceHeapReservedRange <= properties.maxResourceHeapSize && sizes.samplerUsed + properties.minSamplerHeapReservedRangeWithEmbedded <= properties.maxSamplerHeapSize; + const bool resourcesFit = sizes.resourceUsed + properties.minResourceHeapReservedRange <= properties.maxResourceHeapSize; + const bool samplersFit = sizes.samplerUsed + properties.minSamplerHeapReservedRangeWithEmbedded <= properties.maxSamplerHeapSize; + return resourcesFit && samplersFit; } BindlessHeap::BindlessHeap(const Context& context) : context(context) { @@ -135,13 +138,18 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { samplerHeapUsed = sizes.samplerUsed; Require(Fits(heapProperties), "the GPU heap's slots exceed the device's descriptor heap sizes"); constexpr VkBufferUsageFlags heapUsage = VK_BUFFER_USAGE_DESCRIPTOR_HEAP_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - resourceHeap = std::make_unique(context, static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange), heapUsage); - samplerHeap = std::make_unique(context, static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage); + resourceHeap = std::make_unique( + context, static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange), heapUsage); + samplerHeap = std::make_unique( + context, static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage); std::fill(resourceHeap->Bytes().begin(), resourceHeap->Bytes().end(), std::byte{0}); std::fill(samplerHeap->Bytes().begin(), samplerHeap->Bytes().end(), std::byte{0}); - constexpr VkBufferUsageFlags ringUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + constexpr VkBufferUsageFlags ringUsage = + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; try { - ring = std::make_unique(context, RingBytes, ringUsage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + ring = std::make_unique(context, RingBytes, ringUsage, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); } catch (const std::exception&) { ring = std::make_unique(context, RingBytes, ringUsage); } @@ -150,9 +158,11 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { ringChunks.resize(RingBytes / RingChunkBytes); owners.resize(static_cast(Abi::Binding::Samplers)); freeSlots.resize(static_cast(Abi::Binding::Samplers)); - const char* cap = std::getenv("APS5_HEAP_SLOT_CAP"); - slotCap = cap != nullptr ? std::min(static_cast(std::strtoul(cap, nullptr, 10)), Abi::GpuImageHeapSlots) : Abi::GpuImageHeapSlots; - if (slotCap == 0u) slotCap = Abi::GpuImageHeapSlots; + slotCap = Abi::GpuImageHeapSlots; + if (const char* cap = std::getenv("APS5_HEAP_SLOT_CAP")) { + const auto requested = static_cast(std::strtoul(cap, nullptr, 10)); + if (requested != 0u) slotCap = std::min(requested, Abi::GpuImageHeapSlots); + } } BindlessHeap::~BindlessHeap() = default; @@ -178,10 +188,8 @@ std::unordered_map>& heaps() { return map; } -} - -namespace { std::atomic heapsEpoch{0}; + } BindlessHeap& BindlessHeap::For(const Context& context) { @@ -223,91 +231,56 @@ BindlessHeap* BindlessHeap::Existing(const Context& context) { return found == heaps().end() ? nullptr : found->second.get(); } -std::optional BindlessHeap::TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, VkImageLayout layout) { - if (kind < Abi::FirstImageBinding || kind >= Abi::FirstStorageImageBinding || texture == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid texture slot request"); +std::optional BindlessHeap::TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, + VkImageLayout layout) { + const bool sampledKind = kind >= Abi::FirstImageBinding && kind < Abi::FirstStorageImageBinding; + if (!sampledKind || texture == nullptr || view == VK_NULL_HANDLE) + throw std::runtime_error("AGC bindless heap: invalid texture slot request"); std::vector> dropped; SweptStorageRelease swept; std::lock_guard lock(mutex); const TextureKey key{kind, texture.get(), view, layout}; if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; if (++slotRequests % 1024u == 0u) NoteSweepDue(); - auto slot = takeSlotLocked(kind); - if (!slot) { - sweepLocked(dropped); - slot = takeSlotLocked(kind); - } - if (!slot) { - ++counts.full; - return std::nullopt; - } - const VkDescriptorImageInfo image{VK_NULL_HANDLE, view, layout}; - const VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, VK_NULL_HANDLE, fragmentBinding(kind), *slot, 1, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, &image, nullptr, nullptr}; - writeDescriptorHeap(write); - textureSlots.emplace(key, *slot); - auto& kindOwners = owners[kind]; - if (kindOwners.size() <= *slot) kindOwners.resize(*slot + 1u); - kindOwners[*slot].texture = texture; - kindOwners[*slot].key = key; + const auto slot = takeOrSweepLocked(kind, dropped); + if (!slot) return std::nullopt; + writeImageSlot(kind, *slot, view, layout); + auto& owner = claimSlotLocked(key, *slot); + owner.texture = texture; texture->AddHeapHold(); - ++counts.textures; noteTakenLocked(kind, dropped); return slot; } std::optional BindlessHeap::StorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view) { - if (!Abi::GpuHeapStorageKind(kind) || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid storage slot request"); + if (!Abi::GpuHeapStorageKind(kind) || owner == nullptr || view == VK_NULL_HANDLE) + throw std::runtime_error("AGC bindless heap: invalid storage slot request"); std::vector> dropped; SweptStorageRelease swept; std::lock_guard lock(mutex); const TextureKey key{kind, owner.get(), view, VK_IMAGE_LAYOUT_GENERAL}; if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; if (++slotRequests % 1024u == 0u) NoteSweepDue(); - auto slot = takeSlotLocked(kind); - if (!slot) { - sweepLocked(dropped); - slot = takeSlotLocked(kind); - } - if (!slot) { - ++counts.full; - return std::nullopt; - } - const VkDescriptorImageInfo image{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; - const VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, VK_NULL_HANDLE, fragmentBinding(kind), *slot, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &image, nullptr, nullptr}; - writeDescriptorHeap(write); - textureSlots.emplace(key, *slot); - auto& kindOwners = owners[kind]; - if (kindOwners.size() <= *slot) kindOwners.resize(*slot + 1u); - kindOwners[*slot].storage = std::move(owner); - kindOwners[*slot].key = key; - ++counts.textures; + const auto slot = takeOrSweepLocked(kind, dropped); + if (!slot) return std::nullopt; + writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); + claimSlotLocked(key, *slot).storage = std::move(owner); return slot; } std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const void* owner, VkImageView view) { - if (kind < Abi::FirstImageBinding || kind >= static_cast(Abi::Binding::Samplers) || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid view slot request"); + const bool imageKind = kind >= Abi::FirstImageBinding && kind < SamplerKind; + if (!imageKind || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid view slot request"); std::vector> dropped; SweptStorageRelease swept; std::lock_guard lock(mutex); const TextureKey key{kind, owner, view, VK_IMAGE_LAYOUT_GENERAL}; if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; - auto slot = takeSlotLocked(kind); - if (!slot) { - sweepLocked(dropped); - slot = takeSlotLocked(kind); - } - if (!slot) { - ++counts.full; - return std::nullopt; - } - const VkDescriptorImageInfo image{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; - const VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, VK_NULL_HANDLE, fragmentBinding(kind), *slot, 1, Abi::GpuHeapStorageKind(kind) ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, &image, nullptr, nullptr}; - writeDescriptorHeap(write); - textureSlots.emplace(key, *slot); - auto& kindOwners = owners[kind]; - if (kindOwners.size() <= *slot) kindOwners.resize(*slot + 1u); - kindOwners[*slot].key = key; + const auto slot = takeOrSweepLocked(kind, dropped); + if (!slot) return std::nullopt; + writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); + claimSlotLocked(key, *slot); viewSlots[owner].emplace_back(kind, *slot); - ++counts.textures; return slot; } @@ -315,18 +288,43 @@ void BindlessHeap::ReleaseViewSlots(const void* owner) { std::lock_guard lock(mutex); const auto found = viewSlots.find(owner); if (found == viewSlots.end()) return; - for (const auto& [kind, slot] : found->second) { - auto& entry = owners[kind][slot]; - textureSlots.erase(entry.key); - entry.key = {}; - ++entry.generation; - freeSlots[kind].push_back(slot); - ++counts.slotsFreed; - } + for (const auto& [kind, slot] : found->second) freeSlotLocked(kind, slot); slotSerial.fetch_add(1, std::memory_order_release); viewSlots.erase(found); } +std::optional BindlessHeap::takeOrSweepLocked(std::uint32_t kind, std::vector>& dropped) { + auto slot = takeSlotLocked(kind); + if (!slot) { + sweepLocked(dropped); + slot = takeSlotLocked(kind); + } + if (!slot) ++counts.full; + return slot; +} + +BindlessHeap::SlotOwner& BindlessHeap::claimSlotLocked(const TextureKey& key, std::uint32_t slot) { + textureSlots.emplace(key, slot); + auto& kindOwners = owners[key.kind]; + if (kindOwners.size() <= slot) kindOwners.resize(slot + 1u); + kindOwners[slot].key = key; + ++counts.textures; + return kindOwners[slot]; +} + +void BindlessHeap::freeSlotLocked(std::uint32_t kind, std::uint32_t slot) { + auto& owner = owners[kind][slot]; + textureSlots.erase(owner.key); + owner.key = {}; + ++owner.generation; + freeSlots[kind].push_back(slot); + ++counts.slotsFreed; +} + +const BindlessHeap::SlotOwner* BindlessHeap::ownerLocked(std::uint32_t kind, std::uint32_t slot) const { + return kind < owners.size() && slot < owners[kind].size() ? &owners[kind][slot] : nullptr; +} + std::optional BindlessHeap::takeSlotLocked(std::uint32_t kind) { auto& free = freeSlots[kind]; if (!free.empty()) { @@ -349,23 +347,15 @@ void BindlessHeap::sweepLocked(std::vector>& dropped) { auto& owner = kindOwners[slot]; if (owner.storage != nullptr) { if (owner.storage.use_count() > 1) continue; - textureSlots.erase(owner.key); sweptStorage.push_back(std::move(owner.storage)); - owner.key = {}; - ++owner.generation; - slotSerial.fetch_add(1, std::memory_order_release); - freeSlots[kind].push_back(slot); - ++counts.slotsFreed; - continue; + } else { + const bool heldElsewhere = + owner.texture == nullptr || owner.texture.use_count() > static_cast(owner.texture->HeapHolds()); + if (heldElsewhere) continue; + dropped.push_back(std::move(owner.texture)); } - if (owner.texture == nullptr || owner.texture.use_count() > static_cast(owner.texture->HeapHolds())) continue; - textureSlots.erase(owner.key); - dropped.push_back(std::move(owner.texture)); - owner.key = {}; - ++owner.generation; + freeSlotLocked(kind, slot); slotSerial.fetch_add(1, std::memory_order_release); - freeSlots[kind].push_back(slot); - ++counts.slotsFreed; } } for (auto index = firstDropped; index < dropped.size(); ++index) dropped[index]->DropHeapHold(); @@ -391,7 +381,8 @@ constexpr std::uint32_t SamplerSlotMargin = Abi::GpuSamplerHeapSlots / 4u; std::atomic nearlyFull{false}; void noteNearlyFull(const char* what, std::uint32_t margin) { - if (!nearlyFull.exchange(true, std::memory_order_relaxed)) std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; draws take the per-draw path from now on\n", margin, what); + if (!nearlyFull.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; draws take the per-draw path from now on\n", margin, what); } } @@ -424,7 +415,8 @@ void BindlessHeap::SweepIfDue() { heap->sweepSamplersLocked(droppedSamplers); room = room && heap->roomLocked(); } - if (room && nearlyFull.exchange(false, std::memory_order_relaxed)) std::fprintf(stderr, "[gpu-heap] a sweep left twice the margin of slots free; draws take the heap again\n"); + if (room && nearlyFull.exchange(false, std::memory_order_relaxed)) + std::fprintf(stderr, "[gpu-heap] a sweep left twice the margin of slots free; draws take the heap again\n"); } std::uint32_t BindlessHeap::imageMargin() const { @@ -464,43 +456,48 @@ std::uint32_t BindlessHeap::SamplerGeneration(std::uint32_t slot) const { return slot < samplerGenerations.size() ? samplerGenerations[slot] : 0u; } -bool BindlessHeap::GenerationsCurrent(std::span> slots, std::span slotGenerations, std::span samplerSlots, std::span samplerGenerations) const { +bool BindlessHeap::GenerationsCurrent(std::span> slots, std::span slotGenerations, + std::span samplerSlots, + std::span samplerGenerations) const { std::lock_guard lock(mutex); std::size_t generation = 0; for (std::uint32_t kind = 0; kind < slots.size(); ++kind) { for (const auto slot : slots[kind]) { - const auto current = kind < owners.size() && slot < owners[kind].size() ? owners[kind][slot].generation : 0u; + const auto* owner = ownerLocked(kind, slot); + const auto current = owner != nullptr ? owner->generation : 0u; if (generation >= slotGenerations.size() || current != slotGenerations[generation++]) return false; } } + const auto samplerGenerationOf = [&](std::uint32_t slot) { + return slot < this->samplerGenerations.size() ? this->samplerGenerations[slot] : 0u; + }; for (std::size_t i = 0; i < samplerSlots.size(); ++i) { - if (i >= samplerGenerations.size() || (samplerSlots[i] < this->samplerGenerations.size() ? this->samplerGenerations[samplerSlots[i]] : 0u) != samplerGenerations[i]) return false; + if (i >= samplerGenerations.size() || samplerGenerationOf(samplerSlots[i]) != samplerGenerations[i]) return false; } return true; } std::uint32_t BindlessHeap::SlotGeneration(std::uint32_t kind, std::uint32_t slot) const { std::lock_guard lock(mutex); - return kind < owners.size() && slot < owners[kind].size() ? owners[kind][slot].generation : 0u; + const auto* owner = ownerLocked(kind, slot); + return owner != nullptr ? owner->generation : 0u; } const Texture* BindlessHeap::SlotTexture(std::uint32_t kind, std::uint32_t slot) const { std::lock_guard lock(mutex); - return kind < owners.size() && slot < owners[kind].size() ? owners[kind][slot].texture.get() : nullptr; + const auto* owner = ownerLocked(kind, slot); + return owner != nullptr ? owner->texture.get() : nullptr; } std::uint32_t BindlessHeap::AbsentSlot(std::uint32_t kind, VkImageView view) { - if (kind < Abi::FirstImageBinding || kind >= static_cast(Abi::Binding::Samplers)) throw std::runtime_error("AGC bindless heap: invalid absent slot request"); + if (kind < Abi::FirstImageBinding || kind >= SamplerKind) throw std::runtime_error("AGC bindless heap: invalid absent slot request"); std::lock_guard lock(mutex); if (const auto found = absentSlots.find(kind); found != absentSlots.end()) return found->second; - const auto taken = takeSlotLocked(kind); - if (!taken) throw std::runtime_error("AGC bindless heap: the image heap is full"); - const auto slot = *taken; - const VkDescriptorImageInfo image{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; - const VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, VK_NULL_HANDLE, fragmentBinding(kind), slot, 1, Abi::GpuHeapStorageKind(kind) ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, &image, nullptr, nullptr}; - writeDescriptorHeap(write); - absentSlots.emplace(kind, slot); - return slot; + const auto slot = takeSlotLocked(kind); + if (!slot) throw std::runtime_error("AGC bindless heap: the image heap is full"); + writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); + absentSlots.emplace(kind, *slot); + return *slot; } std::optional BindlessHeap::SamplerSlot(const std::shared_ptr& sampler) { @@ -522,9 +519,7 @@ std::optional BindlessHeap::SamplerSlot(const std::shared_ptrHandle(), VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; - const VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, VK_NULL_HANDLE, fragmentBinding(static_cast(Abi::Binding::Samplers)), slot, 1, VK_DESCRIPTOR_TYPE_SAMPLER, &info, nullptr, nullptr}; - writeDescriptorHeap(write); + writeSamplerSlot(slot, sampler->Handle()); samplerSlots.emplace(sampler.get(), slot); heldSamplers[slot] = sampler; ++counts.samplers; @@ -564,8 +559,9 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) offset = 0; ++counts.ringWraps; } + const auto lastChunk = [&] { return (offset + std::max(bytes, 1u) - 1u) / RingChunkBytes; }; const auto keptAhead = [&] { - for (auto chunk = offset / RingChunkBytes; chunk <= (offset + std::max(bytes, 1u) - 1u) / RingChunkBytes; ++chunk) { + for (auto chunk = offset / RingChunkBytes; chunk <= lastChunk(); ++chunk) { if (chunk != ringChunk && ringChunks[chunk].open) return true; } return false; @@ -580,7 +576,7 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) ++counts.keptChunksSkipped; } ringCursor = offset + bytes; - for (auto chunk = offset / RingChunkBytes; chunk <= (offset + std::max(bytes, 1u) - 1u) / RingChunkBytes; ++chunk) enterChunk(ringChunks, chunk, ringChunk, "shader data"); + for (auto chunk = offset / RingChunkBytes; chunk <= lastChunk(); ++chunk) enterChunk(ringChunks, chunk, ringChunk, "shader data"); auto* base = reinterpret_cast(ring->Bytes().data() + offset); ++counts.spansWritten; spansWrittenWindow.fetch_add(1, std::memory_order_relaxed); @@ -595,7 +591,9 @@ void BindlessHeap::enterChunk(std::vector& chunks, std::size_t index, std if (chunk.open) throw std::runtime_error(std::string("AGC bindless heap: one batch's ") + what + " exceeds its ring"); if (chunk.serial != 0u) { ++counts.chunkWaits; - if (!chunk.recorder->HasTimeline()) throw std::runtime_error(std::string("AGC bindless heap: the ") + what + " ring needs the recorder timeline to wait for a batch"); + if (!chunk.recorder->HasTimeline()) + throw std::runtime_error(std::string("AGC bindless heap: the ") + what + + " ring needs the recorder timeline to wait for a batch"); chunk.recorder->WaitSerial(chunk.serial); chunk.serial = 0u; } @@ -607,200 +605,210 @@ VkDeviceSize BindlessHeap::ImageHeapOffset(std::uint32_t kind) const { return static_cast(kind) * Abi::GpuImageHeapSlots * imageHeapStride; } -void BindlessHeap::writeDescriptorHeap(const VkWriteDescriptorSet& write) { - constexpr auto bindingCount = static_cast(Abi::Binding::Count); - const auto kind = write.dstBinding % bindingCount; - if (write.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { - const auto writeSamplers = context.Function("vkWriteSamplerDescriptorsEXT"); - for (std::uint32_t element = 0; element < write.descriptorCount; ++element) { - auto record = FindSampler(write.pImageInfo[element].sampler); - Require(record.has_value(), "a GPU heap sampler has no recorded create info"); - const auto offset = static_cast(write.dstArrayElement + element) * samplerHeapStride; - Require(offset + samplerHeapStride <= samplerHeapUsed, "a GPU heap sampler slot lies outside the sampler heap"); - const VkHostAddressRangeEXT target{samplerHeap->Bytes().data() + offset, static_cast(samplerHeapStride)}; - check(writeSamplers(context.device, 1, record->Chain(), &target), "vkWriteSamplerDescriptorsEXT"); - } +void BindlessHeap::writeSamplerSlot(std::uint32_t slot, VkSampler sampler) { + auto record = FindSampler(sampler); + Require(record.has_value(), "a GPU heap sampler has no recorded create info"); + const auto offset = static_cast(slot) * samplerHeapStride; + Require(offset + samplerHeapStride <= samplerHeapUsed, "a GPU heap sampler slot lies outside the sampler heap"); + const VkHostAddressRangeEXT target{samplerHeap->Bytes().data() + offset, static_cast(samplerHeapStride)}; + check(context.Function("vkWriteSamplerDescriptorsEXT")(context.device, 1, record->Chain(), &target), + "vkWriteSamplerDescriptorsEXT"); +} + +void BindlessHeap::writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImageView view, VkImageLayout layout) { + const auto offset = ImageHeapOffset(kind) + static_cast(slot) * imageHeapStride; + Require(offset + imageHeapStride <= resourceHeapUsed, "a GPU heap image slot lies outside the resource heap"); + auto* target = resourceHeap->Bytes().data() + offset; + if (view == VK_NULL_HANDLE) { + std::memset(target, 0, static_cast(imageHeapStride)); return; } - Require(write.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE || write.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, "the GPU heap writes only images and samplers into the descriptor heap"); - const auto writeResources = context.Function("vkWriteResourceDescriptorsEXT"); - for (std::uint32_t element = 0; element < write.descriptorCount; ++element) { - const auto& image = write.pImageInfo[element]; - const auto offset = ImageHeapOffset(kind) + static_cast(write.dstArrayElement + element) * imageHeapStride; - Require(offset + imageHeapStride <= resourceHeapUsed, "a GPU heap image slot lies outside the resource heap"); - auto* target = resourceHeap->Bytes().data() + offset; - if (image.imageView == VK_NULL_HANDLE) { - std::memset(target, 0, static_cast(imageHeapStride)); - continue; - } - auto record = FindImageView(image.imageView); - Require(record.has_value(), "a GPU heap image view has no recorded create info"); - const VkImageDescriptorInfoEXT imageInfo{VK_STRUCTURE_TYPE_IMAGE_DESCRIPTOR_INFO_EXT, nullptr, record->Chain(), image.imageLayout}; - VkResourceDescriptorInfoEXT resource{VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT}; - resource.type = write.descriptorType; - resource.data.pImage = &imageInfo; - const VkHostAddressRangeEXT range{target, static_cast(imageHeapStride)}; - check(writeResources(context.device, 1, &resource, &range), "vkWriteResourceDescriptorsEXT"); - } + auto record = FindImageView(view); + Require(record.has_value(), "a GPU heap image view has no recorded create info"); + const VkImageDescriptorInfoEXT imageInfo{VK_STRUCTURE_TYPE_IMAGE_DESCRIPTOR_INFO_EXT, nullptr, record->Chain(), layout}; + VkResourceDescriptorInfoEXT resource{VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT}; + resource.type = Abi::GpuHeapStorageKind(kind) ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; + resource.data.pImage = &imageInfo; + const VkHostAddressRangeEXT range{target, static_cast(imageHeapStride)}; + check(context.Function("vkWriteResourceDescriptorsEXT")(context.device, 1, &resource, &range), + "vkWriteResourceDescriptorsEXT"); } namespace { const std::uint32_t GeneratedFaultBinding = Abi::BindingNumber(Abi::Stage::TessellationControl, Abi::Binding::FaultBuffer); -bool heapBindings(std::span spirv, bool workgroupAddress, bool gdsAddress, bool faultAddress, bool pixelLds, std::vector& bindings, bool& workgroupMemory, std::uint32_t& gdsBinding, bool& faultMemory, bool& pixelLdsMemory, std::pair* refused = nullptr) { - bindings.clear(); - workgroupMemory = false; - gdsBinding = ~0u; - faultMemory = false; - pixelLdsMemory = false; - if (spirv.size() < 5u) return false; +struct HeapBindingRoots { + bool workgroupAddress = false; + bool gdsAddress = false; + bool faultAddress = false; + bool pixelLds = false; +}; + +struct HeapBindingUse { + std::vector imageBindings; + bool workgroupMemory = false; + std::uint32_t gdsBinding = ~0u; + bool faultMemory = false; + bool pixelLdsMemory = false; + std::pair refused{~0u, ~0u}; +}; + +using SetAndBinding = std::pair; + +std::optional> decoratedVariables(std::span spirv) { constexpr std::uint32_t opDecorate = 71u; constexpr std::uint32_t decorationBinding = 33u; constexpr std::uint32_t decorationSet = 34u; - std::unordered_map> decorated; - for (std::size_t at = 5; at < spirv.size();) { + constexpr std::size_t headerWords = 5u; + if (spirv.size() < headerWords) return std::nullopt; + std::unordered_map decorated; + for (std::size_t at = headerWords; at < spirv.size();) { const auto count = spirv[at] >> 16u; - if (count == 0u || at + count > spirv.size()) return false; + if (count == 0u || at + count > spirv.size()) return std::nullopt; if ((spirv[at] & 0xffffu) == opDecorate && count >= 4u) { - auto& entry = decorated.try_emplace(spirv[at + 1u], std::pair{~0u, ~0u}).first->second; + auto& entry = decorated.try_emplace(spirv[at + 1u], SetAndBinding{~0u, ~0u}).first->second; if (spirv[at + 2u] == decorationSet) entry.first = spirv[at + 3u]; if (spirv[at + 2u] == decorationBinding) entry.second = spirv[at + 3u]; } at += count; } + return decorated; +} + +bool heapBindings(std::span spirv, const HeapBindingRoots& roots, HeapBindingUse& use) { + use = {}; + const auto decorated = decoratedVariables(spirv); + if (!decorated) return false; constexpr auto bindingCount = static_cast(Abi::Binding::Count); - constexpr auto samplerBinding = static_cast(Abi::Binding::Samplers); - for (const auto& [id, entry] : decorated) { - if (entry.first == ~0u && entry.second == ~0u) continue; - if (workgroupAddress && entry.first == ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet && entry.second == 0u) { - workgroupMemory = true; + constexpr auto firstImage = bindingCount + Abi::FirstImageBinding; + constexpr auto samplers = bindingCount + BindlessHeap::SamplerKind; + for (const auto& [id, entry] : *decorated) { + const auto [set, binding] = entry; + if (set == ~0u && binding == ~0u) continue; + if (roots.workgroupAddress && set == ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet && binding == 0u) { + use.workgroupMemory = true; continue; } - if (gdsAddress && entry.first == Abi::GpuGdsSet && gdsBinding == ~0u) { - gdsBinding = entry.second; + if (roots.gdsAddress && set == Abi::GpuGdsSet && use.gdsBinding == ~0u) { + use.gdsBinding = binding; continue; } - if (faultAddress && entry.first == Abi::DescriptorSet && entry.second == GeneratedFaultBinding) { - faultMemory = true; + if (roots.faultAddress && set == Abi::DescriptorSet && binding == GeneratedFaultBinding) { + use.faultMemory = true; continue; } - if (pixelLds && !pixelLdsMemory && entry.first == ShaderRecompiler::PixelFunctionLdsDescriptorSet && entry.second == 0u) { - pixelLdsMemory = true; + if (roots.pixelLds && !use.pixelLdsMemory && set == ShaderRecompiler::PixelFunctionLdsDescriptorSet && binding == 0u) { + use.pixelLdsMemory = true; continue; } - if (entry.first != Abi::FragmentDescriptorSet || entry.second < bindingCount + Abi::FirstImageBinding || entry.second > bindingCount + samplerBinding) { - if (refused != nullptr) *refused = entry; + const bool heapImageOrSampler = set == Abi::FragmentDescriptorSet && binding >= firstImage && binding <= samplers; + if (!heapImageOrSampler) { + use.refused = entry; return false; } - if (std::find(bindings.begin(), bindings.end(), entry.second) == bindings.end()) bindings.push_back(entry.second); + if (std::find(use.imageBindings.begin(), use.imageBindings.end(), binding) == use.imageBindings.end()) + use.imageBindings.push_back(binding); } - return (!workgroupAddress || workgroupMemory) && (!faultAddress || faultMemory) && (!pixelLds || pixelLdsMemory); + return (!roots.workgroupAddress || use.workgroupMemory) && (!roots.faultAddress || use.faultMemory) && + (!roots.pixelLds || use.pixelLdsMemory); +} + +VkDescriptorSetAndBindingMappingEXT heapMapping(std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, + VkDeviceSize heapOffset, VkDeviceSize stride) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = set; + mapping.firstBinding = binding; + mapping.bindingCount = 1; + mapping.resourceMask = resources; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT; + mapping.sourceData.constantOffset.heapOffset = static_cast(heapOffset); + mapping.sourceData.constantOffset.heapArrayStride = static_cast(stride); + return mapping; +} + +VkDescriptorSetAndBindingMappingEXT pushAddressMapping(std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = set; + mapping.firstBinding = binding; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; + mapping.sourceData.pushAddressOffset = pushOffset; + return mapping; +} + +constexpr std::uint32_t rootAddressOffset(std::uint32_t rootField) { + return (Abi::RootDword + rootField) * sizeof(std::uint32_t); } } bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds) { - std::vector bindings; - bool workgroupMemory = false; - std::uint32_t gdsBinding = ~0u; - bool faultMemory = false; - bool pixelLdsMemory = false; - std::pair refused{~0u, ~0u}; - const bool mappable = heapBindings(spirv, workgroupAddress, gdsAddress, false, pixelLds, bindings, workgroupMemory, gdsBinding, faultMemory, pixelLdsMemory, &refused); + HeapBindingUse use; + const bool mappable = heapBindings(spirv, {.workgroupAddress = workgroupAddress, .gdsAddress = gdsAddress, .pixelLds = pixelLds}, use); static const bool stats = std::getenv("APS5_PIPELINE_STATS") != nullptr; if (!mappable && stats) { static std::mutex causesMutex; - static std::map, std::uint64_t> causes; + static std::map causes; std::lock_guard lock(causesMutex); - const auto count = ++causes[refused]; - if (count == 1u || (count & (count - 1u)) == 0u) std::fprintf(stderr, "[gpu-heap] unmappable stage: descriptor set %d binding %d (workgroup address %d, gds address %d); %llu stage variants with this cause\n", static_cast(refused.first), static_cast(refused.second), workgroupAddress ? 1 : 0, gdsAddress ? 1 : 0, static_cast(count)); + const auto count = ++causes[use.refused]; + const bool powerOfTwo = (count & (count - 1u)) == 0u; + if (powerOfTwo) { + std::fprintf( + stderr, + "[gpu-heap] unmappable stage: descriptor set %d binding %d (workgroup address %d, gds address %d); %llu stage variants with this cause\n", + static_cast(use.refused.first), static_cast(use.refused.second), workgroupAddress ? 1 : 0, gdsAddress ? 1 : 0, + static_cast(count)); + } } return mappable; } -bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset, bool rootGds, bool rootFault, bool pixelLds) const { +bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::vector& mappings, + std::uint32_t workgroupAddressOffset, bool rootGds, bool rootFault, bool pixelLds) const { mappings.clear(); - std::vector bindings; - bool workgroupMemory = false; - std::uint32_t gdsBinding = ~0u; - bool faultMemory = false; - bool pixelLdsMemory = false; - if (resourceHeap == nullptr || !heapBindings(spirv, workgroupAddressOffset != ~0u, rootGds, rootFault, pixelLds, bindings, workgroupMemory, gdsBinding, faultMemory, pixelLdsMemory)) return false; + if (resourceHeap == nullptr) return false; + HeapBindingUse use; + const HeapBindingRoots roots{ + .workgroupAddress = workgroupAddressOffset != ~0u, .gdsAddress = rootGds, .faultAddress = rootFault, .pixelLds = pixelLds}; + if (!heapBindings(spirv, roots, use)) return false; constexpr auto bindingCount = static_cast(Abi::Binding::Count); - constexpr auto samplerBinding = static_cast(Abi::Binding::Samplers); - std::sort(bindings.begin(), bindings.end()); - for (const auto binding : bindings) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = Abi::FragmentDescriptorSet; - mapping.firstBinding = binding; - mapping.bindingCount = 1; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT; + constexpr VkSpirvResourceTypeFlagsEXT imageResources = VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT | + VK_SPIRV_RESOURCE_TYPE_READ_ONLY_IMAGE_BIT_EXT | + VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; + std::sort(use.imageBindings.begin(), use.imageBindings.end()); + for (const auto binding : use.imageBindings) { const auto kind = binding - bindingCount; - if (kind == samplerBinding) { - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT; - mapping.sourceData.constantOffset.heapOffset = 0; - mapping.sourceData.constantOffset.heapArrayStride = static_cast(samplerHeapStride); - } else { - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_IMAGE_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; - mapping.sourceData.constantOffset.heapOffset = static_cast(ImageHeapOffset(kind)); - mapping.sourceData.constantOffset.heapArrayStride = static_cast(imageHeapStride); - } - mappings.push_back(mapping); - } - if (workgroupMemory) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet; - mapping.firstBinding = 0; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; - mapping.sourceData.pushAddressOffset = workgroupAddressOffset; - mappings.push_back(mapping); - } - if (gdsBinding != ~0u) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = Abi::GpuGdsSet; - mapping.firstBinding = gdsBinding; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; - mapping.sourceData.pushAddressOffset = (Abi::RootDword + Abi::RootGdsAddress) * sizeof(std::uint32_t); - mappings.push_back(mapping); - } - if (faultMemory) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = Abi::DescriptorSet; - mapping.firstBinding = GeneratedFaultBinding; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; - mapping.sourceData.pushAddressOffset = (Abi::RootDword + Abi::RootFaultAddress) * sizeof(std::uint32_t); - mappings.push_back(mapping); - } - if (pixelLdsMemory) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = ShaderRecompiler::PixelFunctionLdsDescriptorSet; - mapping.firstBinding = 0; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT; - mapping.sourceData.constantOffset.heapOffset = static_cast(pixelLdsHeapOffset); - mapping.sourceData.constantOffset.heapArrayStride = 0; - mappings.push_back(mapping); - } + if (kind == SamplerKind) + mappings.push_back( + heapMapping(Abi::FragmentDescriptorSet, binding, VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT, 0, samplerHeapStride)); + else mappings.push_back(heapMapping(Abi::FragmentDescriptorSet, binding, imageResources, ImageHeapOffset(kind), imageHeapStride)); + } + if (use.workgroupMemory) + mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset)); + if (use.gdsBinding != ~0u) + mappings.push_back(pushAddressMapping(Abi::GpuGdsSet, use.gdsBinding, rootAddressOffset(Abi::RootGdsAddress))); + if (use.faultMemory) + mappings.push_back(pushAddressMapping(Abi::DescriptorSet, GeneratedFaultBinding, rootAddressOffset(Abi::RootFaultAddress))); + if (use.pixelLdsMemory) + mappings.push_back(heapMapping(ShaderRecompiler::PixelFunctionLdsDescriptorSet, 0, + VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT, pixelLdsHeapOffset, 0)); return true; } void BindlessHeap::WritePixelLdsBuffer(VkDeviceAddress address, VkDeviceSize bytes) { const auto& properties = context.descriptorHeapProperties; - Require(pixelLdsHeapOffset + properties.bufferDescriptorSize <= resourceHeapUsed, "the pixel function LDS descriptor lies outside the resource heap"); + Require(pixelLdsHeapOffset + properties.bufferDescriptorSize <= resourceHeapUsed, + "the pixel function LDS descriptor lies outside the resource heap"); const VkDeviceAddressRangeEXT buffer{address, bytes}; VkResourceDescriptorInfoEXT resource{VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT}; resource.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; resource.data.pAddressRange = &buffer; - const VkHostAddressRangeEXT range{resourceHeap->Bytes().data() + pixelLdsHeapOffset, static_cast(properties.bufferDescriptorSize)}; - Check(context.Function("vkWriteResourceDescriptorsEXT")(context.device, 1, &resource, &range), "vkWriteResourceDescriptorsEXT pixel function LDS"); + const VkHostAddressRangeEXT range{resourceHeap->Bytes().data() + pixelLdsHeapOffset, + static_cast(properties.bufferDescriptorSize)}; + Check(context.Function("vkWriteResourceDescriptorsEXT")(context.device, 1, &resource, &range), + "vkWriteResourceDescriptorsEXT pixel function LDS"); } namespace { @@ -815,18 +823,45 @@ std::atomic cpuBufferCopyBytes{0}; std::array, static_cast(SetBindSite::Count)> setBinds{}; std::array, static_cast(HeapFallback::Count)> heapFallbacks{}; std::array, 4> heapRecords{}; + +std::size_t heapRecordIndex(bool compute, bool heap) { + return (compute ? 2u : 0u) + (heap ? 1u : 0u); +} std::array, static_cast(HeapStageReason::Count)> heapStageReasons{}; -constexpr std::array(HeapStageReason::Count)> HeapStageReasonNames{"heap", "disabled", "pair refused", "fragment off heap", "stage kind", "no plan", "plan stage", "unresolved image source", "known ineligible"}; -constexpr std::array(SetBindSite::Count)> SetBindSiteNames{"draw", "dispatch", "detiler", "color transfer", "presentation"}; -constexpr std::array(HeapFallback::Count)> HeapFallbackNames{"draw unmapped", "draw mixed retry", "draw refused pair", "draw mixed reused", "dispatch unmapped"}; +constexpr std::array(HeapStageReason::Count)> HeapStageReasonNames{"heap", + "disabled", + "pair refused", + "fragment off heap", + "stage kind", + "no plan", + "plan stage", + "unresolved image source", + "known ineligible"}; +constexpr std::array(SetBindSite::Count)> SetBindSiteNames{"draw", "dispatch", "detiler", + "color transfer", "presentation"}; +constexpr std::array(HeapFallback::Count)> HeapFallbackNames{ + "draw unmapped", "draw mixed retry", "draw refused pair", "draw mixed reused", "dispatch unmapped"}; std::uint64_t takeCount(std::atomic& counter) { return counter.exchange(0, std::memory_order_relaxed); } +template +std::string takeNamedCounts(std::array, N>& counters, const std::array& names) { + std::string text; + for (std::size_t i = 0; i < N; ++i) text += " " + std::string(names[i]) + " " + std::to_string(takeCount(counters[i])); + return text; +} + +unsigned long long printed(std::uint64_t value) { + return static_cast(value); +} + std::array, static_cast(HeapCost::Count)> heapCostNs{}; std::array, static_cast(HeapCost::Count)> heapCostCalls{}; -constexpr std::array(HeapCost::Count)> HeapCostNames{"stage prepare", "heap stage call", "stage finish", "walk memo", "walk", "materialize", "template find", "template build", "slots", "stage data", "buffer addresses", "memo insert", "guards"}; +constexpr std::array(HeapCost::Count)> HeapCostNames{ + "stage prepare", "heap stage call", "stage finish", "walk memo", "walk", "materialize", "template find", + "template build", "slots", "stage data", "buffer addresses", "memo insert", "guards"}; void reportHeapStatistics() { static const bool enabled = std::getenv("APS5_PIPELINE_STATS") != nullptr; @@ -840,26 +875,37 @@ void reportHeapStatistics() { const auto now = std::chrono::steady_clock::now(); if (now - last < std::chrono::seconds(10)) return; last = now; - std::string binds; - for (std::size_t i = 0; i < setBinds.size(); ++i) binds += " " + std::string(SetBindSiteNames[i]) + " " + std::to_string(takeCount(setBinds[i])); - std::string fallbacks; - for (std::size_t i = 0; i < heapFallbacks.size(); ++i) fallbacks += " " + std::string(HeapFallbackNames[i]) + " " + std::to_string(takeCount(heapFallbacks[i])); - std::string stageReasons; - for (std::size_t i = 0; i < heapStageReasons.size(); ++i) stageReasons += " " + std::string(HeapStageReasonNames[i]) + " " + std::to_string(takeCount(heapStageReasons[i])); + const auto binds = takeNamedCounts(setBinds, SetBindSiteNames); + const auto fallbacks = takeNamedCounts(heapFallbacks, HeapFallbackNames); + const auto stageReasons = takeNamedCounts(heapStageReasons, HeapStageReasonNames); std::string costs; for (std::size_t i = 0; i < heapCostNs.size(); ++i) { const auto calls = takeCount(heapCostCalls[i]); - const auto ns = takeCount(heapCostNs[i]); + const auto ns = static_cast(takeCount(heapCostNs[i])); + const auto averageUs = calls != 0 ? ns / static_cast(calls) / 1000.0 : 0.0; char cost[96]; - std::snprintf(cost, sizeof(cost), " %s %llu x %.2f us = %.0f ms", HeapCostNames[i], static_cast(calls), calls != 0 ? static_cast(ns) / static_cast(calls) / 1000.0 : 0.0, static_cast(ns) / 1e6); + std::snprintf(cost, sizeof(cost), " %s %llu x %.2f us = %.0f ms", HeapCostNames[i], printed(calls), averageUs, ns / 1e6); costs += cost; } if (HeapCostTimed()) std::fprintf(stderr, "[gpu-heap] cost (10 s):%s\n", costs.c_str()); - const auto heapDraws = takeCount(heapRecords[1]); - const auto plainDraws = takeCount(heapRecords[0]); - const auto heapDispatches = takeCount(heapRecords[3]); - const auto plainDispatches = takeCount(heapRecords[2]); - std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired\n", static_cast(heapDraws), static_cast(plainDraws), static_cast(heapDispatches), static_cast(plainDispatches), static_cast(takeCount(heapBindWindow)), static_cast(takeCount(commandBuffersBegun)), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), static_cast(takeCount(cpuBufferCopies)), static_cast(takeCount(cpuBufferCopyBytes) >> 20u), static_cast(takeCount(spansWrittenWindow)), static_cast(takeCount(spansKeptWindow)), static_cast(takeCount(spansExpiredWindow))); + const auto heapDraws = takeCount(heapRecords[heapRecordIndex(false, true)]); + const auto plainDraws = takeCount(heapRecords[heapRecordIndex(false, false)]); + const auto heapDispatches = takeCount(heapRecords[heapRecordIndex(true, true)]); + const auto plainDispatches = takeCount(heapRecords[heapRecordIndex(true, false)]); + const auto heapBindsSeen = takeCount(heapBindWindow); + const auto commandBuffers = takeCount(commandBuffersBegun); + const auto copies = takeCount(cpuBufferCopies); + const auto copiedMiB = takeCount(cpuBufferCopyBytes) >> 20u; + const auto spansWritten = takeCount(spansWrittenWindow); + const auto spansKept = takeCount(spansKeptWindow); + const auto spansExpired = takeCount(spansExpiredWindow); + std::fprintf(stderr, + "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " + "heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; " + "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired\n", + printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), + printed(commandBuffers), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), + printed(spansWritten), printed(spansKept), printed(spansExpired)); } void forgetHeapBinding(VkCommandBuffer commands) { @@ -871,7 +917,7 @@ void forgetHeapBinding(VkCommandBuffer commands) { } void NoteHeapRecord(bool compute, bool heap) { - heapRecords[(compute ? 2u : 0u) + (heap ? 1u : 0u)].fetch_add(1, std::memory_order_relaxed); + heapRecords[heapRecordIndex(compute, heap)].fetch_add(1, std::memory_order_relaxed); reportHeapStatistics(); } @@ -907,13 +953,16 @@ void NoteCommandBufferBegun(VkCommandBuffer commands) { forgetHeapBinding(commands); } -void CmdPushConstants(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, std::uint32_t size, const void* values) { +void CmdPushConstants(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout, VkShaderStageFlags stages, + std::uint32_t offset, std::uint32_t size, const void* values) { context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, layout, stages, offset, size, values); forgetHeapBinding(commands); } -void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site) { - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, bindPoint, layout, firstSet, setCount, sets, 0, nullptr); +void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, + std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site) { + context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, bindPoint, layout, firstSet, setCount, + sets, 0, nullptr); setBinds[static_cast(site)].fetch_add(1, std::memory_order_relaxed); forgetHeapBinding(commands); } @@ -935,7 +984,8 @@ void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { info.reservedRangeOffset = resourceHeapUsed; info.reservedRangeSize = context.descriptorHeapProperties.minResourceHeapReservedRange; context.Function("vkCmdBindResourceHeapEXT")(commands, &info); - info.heapRange = {samplerHeap->DeviceAddress(), samplerHeapUsed + context.descriptorHeapProperties.minSamplerHeapReservedRangeWithEmbedded}; + info.heapRange = {samplerHeap->DeviceAddress(), + samplerHeapUsed + context.descriptorHeapProperties.minSamplerHeapReservedRangeWithEmbedded}; info.reservedRangeOffset = samplerHeapUsed; info.reservedRangeSize = context.descriptorHeapProperties.minSamplerHeapReservedRangeWithEmbedded; context.Function("vkCmdBindSamplerHeapEXT")(commands, &info); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp index 66005bfc1289..47360a964ae4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp @@ -58,7 +58,8 @@ SamplerRecord recordOf(const VkSamplerCreateInfo& info) { return record; } -VKAPI_ATTR VkResult VKAPI_CALL createImageView(VkDevice device, const VkImageViewCreateInfo* info, const VkAllocationCallbacks* allocator, VkImageView* view) { +VKAPI_ATTR VkResult VKAPI_CALL createImageView(VkDevice device, const VkImageViewCreateInfo* info, const VkAllocationCallbacks* allocator, + VkImageView* view) { const auto result = realCreateImageView.load(std::memory_order_acquire)(device, info, allocator, view); if (result == VK_SUCCESS) { auto record = recordOf(*info); @@ -76,7 +77,8 @@ VKAPI_ATTR void VKAPI_CALL destroyImageView(VkDevice device, VkImageView view, c realDestroyImageView.load(std::memory_order_acquire)(device, view, allocator); } -VKAPI_ATTR VkResult VKAPI_CALL createSampler(VkDevice device, const VkSamplerCreateInfo* info, const VkAllocationCallbacks* allocator, VkSampler* sampler) { +VKAPI_ATTR VkResult VKAPI_CALL createSampler(VkDevice device, const VkSamplerCreateInfo* info, const VkAllocationCallbacks* allocator, + VkSampler* sampler) { const auto result = realCreateSampler.load(std::memory_order_acquire)(device, info, allocator, sampler); if (result == VK_SUCCESS) { auto record = recordOf(*info); @@ -94,7 +96,7 @@ VKAPI_ATTR void VKAPI_CALL destroySampler(VkDevice device, VkSampler sampler, co realDestroySampler.load(std::memory_order_acquire)(device, sampler, allocator); } -template +template bool resolve(std::atomic& real, VkDevice device, PFN_vkGetDeviceProcAddr deviceProc, const char* name) { const auto function = reinterpret_cast(deviceProc(device, name)); if (function == nullptr) return false; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 259ecaf9ab2d..5b1d7ba29f31 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -4364,7 +4364,11 @@ void noteEpochMirrors(bool reused, const GuestBufferMemory::AddressSpace& space) const auto count = (reused ? reuses : refreshes).fetch_add(1, std::memory_order_relaxed) + 1u; static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; if (!verify && !profile) return; - if (count % 65536u == 0u || (count & (count - 1u)) == 0u) std::fprintf(stderr, "[epoch-mirrors] address space uses: %llu reused the epoch's refresh, %llu refreshed; verify: %llu blocks compared, %llu differ\n", static_cast(reuses.load()), static_cast(refreshes.load()), static_cast(compared.load()), static_cast(differing.load())); + const bool report = count % 65536u == 0u || (count & (count - 1u)) == 0u; + if (report) { + std::fprintf(stderr, "[epoch-mirrors] address space uses: %llu reused the epoch's refresh, %llu refreshed; verify: %llu blocks compared, %llu differ\n", + static_cast(reuses.load()), static_cast(refreshes.load()), static_cast(compared.load()), static_cast(differing.load())); + } } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 983236bf16e3..1b34c08c6b16 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6095,12 +6095,18 @@ void ShaderResources::PatchDataAddresses(std::spanView(kind); +} + void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_t stageIndex) { + constexpr auto noElement = std::numeric_limits::max(); namespace Abi = ShaderRecompiler::RuntimeAbi; namespace TableAbi = ShaderRecompiler::ImageTableAbi; heapTableMapSet[stageIndex] = false; - const auto table = std::find_if(tableStages.begin(), tableStages.end(), [&](const TableStage& candidate) { return candidate.program == shader.program && candidate.heap; }); - if (table == tableStages.end() || table->mapAllocation == std::numeric_limits::max()) return; + const auto table = std::find_if(tableStages.begin(), tableStages.end(), + [&](const TableStage& candidate) { return candidate.program == shader.program && candidate.heap; }); + if (table == tableStages.end() || table->mapAllocation == noElement) return; auto& heap = BindlessHeap::For(context); struct MapStorage {}; auto& map = HostThreadLocal, MapStorage>(); @@ -6108,11 +6114,11 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ const auto elements = table->images != nullptr ? static_cast(table->images->count) : std::size_t{0}; const auto base = static_cast(map.size()); map[TableAbi::HeaderElementBase] = base; - const auto sampledAbsent = heap.AbsentSlot(Abi::FirstImageBinding, context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(Abi::FirstImageBinding)); - const auto storageAbsent = heap.AbsentSlot(Abi::FirstStorageImageBinding, context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(Abi::FirstStorageImageBinding)); + const auto sampledAbsent = heap.AbsentSlot(Abi::FirstImageBinding, heapPlaceholderView(Abi::FirstImageBinding)); + const auto storageAbsent = heap.AbsentSlot(Abi::FirstStorageImageBinding, heapPlaceholderView(Abi::FirstStorageImageBinding)); for (std::size_t element = 0; element < elements; ++element) { - const auto index = element < table->elementTextures.size() ? table->elementTextures[element] : std::numeric_limits::max(); - if (index == std::numeric_limits::max()) { + const auto index = element < table->elementTextures.size() ? table->elementTextures[element] : noElement; + if (index == noElement) { map.push_back(sampledAbsent); continue; } @@ -6122,25 +6128,26 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ map.push_back(*slot); } for (std::size_t element = 0; element < elements; ++element) { - const auto index = element < table->elementStorage.size() ? table->elementStorage[element] : std::numeric_limits::max(); - if (index == std::numeric_limits::max() || storageTextures[index] == nullptr) { + const auto index = element < table->elementStorage.size() ? table->elementStorage[element] : noElement; + if (index == noElement || storageTextures[index] == nullptr) { map.push_back(storageAbsent); continue; } - const auto slot = heap.StorageSlot(Abi::FirstStorageImageBinding, storageTextures[index], storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index])); + const auto slot = heap.StorageSlot(Abi::FirstStorageImageBinding, storageTextures[index], + storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index])); Require(slot.has_value(), "the global storage image heap is full"); map.push_back(*slot); } std::uint32_t fallbackSampler = 0; for (const auto index : table->tableSamplers) { - if (index == std::numeric_limits::max()) continue; + if (index == noElement) continue; const auto slot = heap.SamplerSlot(samplers[index]); Require(slot.has_value(), "the global sampler heap is full"); fallbackSampler = *slot; break; } for (const auto index : table->tableSamplers) { - if (index == std::numeric_limits::max()) { + if (index == noElement) { map.push_back(fallbackSampler); continue; } @@ -6164,15 +6171,16 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ map.resize(base + 3u * elements, fallbackSampler); for (const bool wide : {false, true}) { const auto kind = wide ? Abi::FirstAtomic64ImageBinding : Abi::FirstAtomicImageBinding; - const auto absent = heap.AbsentSlot(kind, context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(kind)); + const auto absent = heap.AbsentSlot(kind, heapPlaceholderView(kind)); for (std::size_t element = 0; element < elements; ++element) { - const auto index = element < table->elementStorage.size() ? table->elementStorage[element] : std::numeric_limits::max(); - if (!atomicElement(element, wide) || index == std::numeric_limits::max() || storageTextures[index] == nullptr) { + const auto index = element < table->elementStorage.size() ? table->elementStorage[element] : noElement; + if (!atomicElement(element, wide) || index == noElement || storageTextures[index] == nullptr) { map.push_back(absent); continue; } auto& image = *storageTextures[index]; - const auto view = wide ? image.Atomic64View(storageMips[index], storageFirstLayer[index]) : image.AtomicView(storageMips[index], storageFirstLayer[index]); + const auto view = wide ? image.Atomic64View(storageMips[index], storageFirstLayer[index]) + : image.AtomicView(storageMips[index], storageFirstLayer[index]); const auto slot = heap.StorageSlot(kind, storageTextures[index], view); Require(slot.has_value(), "the global atomic image heap is full"); map.push_back(*slot); @@ -6193,141 +6201,245 @@ std::uint32_t ShaderResources::heapSpan(HeapStageState::KeptSpan& kept, std::spa return span.offset; } -void ShaderResources::writeHeapStage(const CompiledShader& shader) { - namespace Abi = ShaderRecompiler::RuntimeAbi; - HeapCostScope slotsCost(HeapCost::Slots); - auto& heap = BindlessHeap::For(context); - constexpr auto bindingCount = static_cast(Abi::Binding::Count); - const VkShaderStageFlags stageBit = VulkanStage(shader.stage); - const auto stageIndex = HeapStageIndex(shader.stage); - auto& stageState = heapStages[stageIndex]; - const auto ownHeap = [&](const Binding& binding) { return binding.heap && (binding.layout.stageFlags & stageBit) != 0u; }; - struct HeapKeyStorage {}; - auto& key = HostThreadLocal, HeapKeyStorage>(); +bool ShaderResources::ownsHeapBinding(const Binding& binding, VkShaderStageFlags stageBit) const { + return binding.heap && (binding.layout.stageFlags & stageBit) != 0u; +} + +VkImageView ShaderResources::heapSampledView(std::size_t index) const { + const auto& texture = textures[index]; + if (textureSrgb[index]) return texture->SrgbView(textureFirstLayer[index], textureBaseLevel[index]); + if (textureBaseLevel[index]) return texture->BaseLevelView(); + if (textureFirstLayer[index]) return texture->FirstLayerView(); + return texture->View(); +} + +VkImageView ShaderResources::heapStorageView(std::size_t index) const { + const auto& texture = storageTextures[index]; + if (storageAtomic64[index]) return texture->Atomic64View(storageMips[index], storageFirstLayer[index]); + if (storageAtomic[index]) return texture->AtomicView(storageMips[index], storageFirstLayer[index]); + return texture->StorageView(storageMips[index], storageFirstLayer[index]); +} + +void ShaderResources::appendHeapSlotKey(VkShaderStageFlags stageBit, std::vector& key) const { + constexpr auto absent = std::numeric_limits::max(); key.clear(); for (const auto& binding : bindings) { - if (!ownHeap(binding)) continue; + if (!ownsHeapBinding(binding, stageBit)) continue; if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) { for (const auto index : binding.imageAllocations) { - if (index == std::numeric_limits::max()) { + if (index == absent) { key.push_back(0u); continue; } - const auto view = textureSrgb[index] ? textures[index]->SrgbView(textureFirstLayer[index], textureBaseLevel[index]) : textureBaseLevel[index] ? textures[index]->BaseLevelView() : textureFirstLayer[index] ? textures[index]->FirstLayerView() : textures[index]->View(); - key.insert(key.end(), {reinterpret_cast(textures[index].get()), reinterpret_cast(view), static_cast(textures[index]->Layout())}); + key.insert(key.end(), {reinterpret_cast(textures[index].get()), + reinterpret_cast(heapSampledView(index)), + static_cast(textures[index]->Layout())}); } } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { for (const auto index : binding.imageAllocations) { - if (index == std::numeric_limits::max() || storageTextures[index] == nullptr) { + if (index == absent || storageTextures[index] == nullptr) { key.push_back(0u); continue; } - key.insert(key.end(), {reinterpret_cast(storageTextures[index].get()), reinterpret_cast(storageAtomic64[index] ? storageTextures[index]->Atomic64View(storageMips[index], storageFirstLayer[index]) : storageAtomic[index] ? storageTextures[index]->AtomicView(storageMips[index], storageFirstLayer[index]) : storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index])), static_cast(VK_IMAGE_LAYOUT_GENERAL)}); + key.insert(key.end(), {reinterpret_cast(storageTextures[index].get()), + reinterpret_cast(heapStorageView(index)), + static_cast(VK_IMAGE_LAYOUT_GENERAL)}); } } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { for (const auto index : binding.imageAllocations) key.push_back(reinterpret_cast(samplers[index].get())); } } - bool current = key == stageState.key; - const auto slotSerial = heap.SlotSerial(); - const bool unmoved = current && EpochProofs() && stageState.slotSerial == slotSerial; - if (!unmoved && current && CommitTrims()) { - current = heap.GenerationsCurrent(stageState.slots, stageState.slotGenerations, stageState.samplerSlots, stageState.samplerGenerations); - } else if (!unmoved && current) { - std::size_t generation = 0; - for (std::uint32_t kind = 0; current && kind < stageState.slots.size(); ++kind) { - for (const auto slot : stageState.slots[kind]) { - if (!current) break; - current = generation < stageState.slotGenerations.size() && heap.SlotGeneration(kind, slot) == stageState.slotGenerations[generation++]; - } +} + +bool ShaderResources::heapSlotsCurrent(const BindlessHeap& heap, const HeapStageState& state) { + std::size_t generation = 0; + for (std::uint32_t kind = 0; kind < state.slots.size(); ++kind) { + for (const auto slot : state.slots[kind]) { + if (generation >= state.slotGenerations.size() || heap.SlotGeneration(kind, slot) != state.slotGenerations[generation++]) + return false; } - for (std::size_t i = 0; current && i < stageState.samplerSlots.size(); ++i) current = i < stageState.samplerGenerations.size() && heap.SamplerGeneration(stageState.samplerSlots[i]) == stageState.samplerGenerations[i]; } - if (!current) { - stageState.key = key; - for (auto& kindSlots : stageState.slots) kindSlots.clear(); - stageState.samplerSlots.clear(); - std::size_t cursor = 0; - for (const auto& binding : bindings) { - if (!ownHeap(binding)) continue; - const auto kind = binding.layout.binding % bindingCount; - if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) { - auto& kindSlots = stageState.slots[kind]; - for (const auto index : binding.imageAllocations) { - if (index == std::numeric_limits::max()) { - ++cursor; - kindSlots.push_back(heap.AbsentSlot(kind, context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(kind))); - continue; - } - const auto view = reinterpret_cast(key[cursor + 1]); - cursor += 3; - const auto slot = heap.TextureSlot(kind, textures[index], view, textures[index]->Layout()); - Require(slot.has_value(), "the global image heap is full"); - kindSlots.push_back(*slot); - } - } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { - auto& kindSlots = stageState.slots[kind]; - for (const auto index : binding.imageAllocations) { - if (index == std::numeric_limits::max() || storageTextures[index] == nullptr) { - ++cursor; - kindSlots.push_back(heap.AbsentSlot(kind, context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(kind))); - continue; - } - const auto view = reinterpret_cast(key[cursor + 1]); - cursor += 3; - const auto slot = heap.StorageSlot(kind, storageTextures[index], view); - Require(slot.has_value(), "the global storage image heap is full"); - kindSlots.push_back(*slot); + for (std::size_t i = 0; i < state.samplerSlots.size(); ++i) { + if (i >= state.samplerGenerations.size() || heap.SamplerGeneration(state.samplerSlots[i]) != state.samplerGenerations[i]) + return false; + } + return true; +} + +void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, VkShaderStageFlags stageBit, + std::span key) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + constexpr auto absent = std::numeric_limits::max(); + for (auto& kindSlots : state.slots) kindSlots.clear(); + state.samplerSlots.clear(); + std::size_t cursor = 0; + for (const auto& binding : bindings) { + if (!ownsHeapBinding(binding, stageBit)) continue; + const auto kind = binding.layout.binding % bindingCount; + if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) { + auto& kindSlots = state.slots[kind]; + for (const auto index : binding.imageAllocations) { + if (index == absent) { + ++cursor; + kindSlots.push_back(heap.AbsentSlot(kind, heapPlaceholderView(kind))); + continue; } - } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { - for (const auto index : binding.imageAllocations) { + const auto view = reinterpret_cast(key[cursor + 1]); + cursor += 3; + const auto slot = heap.TextureSlot(kind, textures[index], view, textures[index]->Layout()); + Require(slot.has_value(), "the global image heap is full"); + kindSlots.push_back(*slot); + } + } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { + auto& kindSlots = state.slots[kind]; + for (const auto index : binding.imageAllocations) { + if (index == absent || storageTextures[index] == nullptr) { ++cursor; - const auto slot = heap.SamplerSlot(samplers[index]); - Require(slot.has_value(), "the global sampler heap is full"); - stageState.samplerSlots.push_back(*slot); + kindSlots.push_back(heap.AbsentSlot(kind, heapPlaceholderView(kind))); + continue; } + const auto view = reinterpret_cast(key[cursor + 1]); + cursor += 3; + const auto slot = heap.StorageSlot(kind, storageTextures[index], view); + Require(slot.has_value(), "the global storage image heap is full"); + kindSlots.push_back(*slot); + } + } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { + for (const auto index : binding.imageAllocations) { + ++cursor; + const auto slot = heap.SamplerSlot(samplers[index]); + Require(slot.has_value(), "the global sampler heap is full"); + state.samplerSlots.push_back(*slot); } } } - if (current) stageState.slotSerial = slotSerial; - if (!current) { - stageState.slotSerial = 0; - stageState.slotGenerations.clear(); - for (std::uint32_t kind = 0; kind < stageState.slots.size(); ++kind) { - for (const auto slot : stageState.slots[kind]) stageState.slotGenerations.push_back(heap.SlotGeneration(kind, slot)); +} + +void ShaderResources::noteHeapSlotGenerations(const BindlessHeap& heap, HeapStageState& state) { + state.slotGenerations.clear(); + for (std::uint32_t kind = 0; kind < state.slots.size(); ++kind) { + for (const auto slot : state.slots[kind]) state.slotGenerations.push_back(heap.SlotGeneration(kind, slot)); + } + state.samplerGenerations.clear(); + for (const auto slot : state.samplerSlots) state.samplerGenerations.push_back(heap.SamplerGeneration(slot)); +} + +void ShaderResources::verifyHeapSlots(const BindlessHeap& heap, const HeapStageState& state, VkShaderStageFlags stageBit) const { + constexpr auto bindingCount = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count); + static std::atomic checked{0}, wrong{0}; + for (const auto& binding : bindings) { + if (!ownsHeapBinding(binding, stageBit) || binding.layout.descriptorType != VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) continue; + const auto kind = binding.layout.binding % bindingCount; + for (std::size_t element = 0; element < binding.imageAllocations.size(); ++element) { + const auto index = binding.imageAllocations[element]; + if (index == std::numeric_limits::max()) continue; + ++checked; + const bool holdsTexture = + element < state.slots[kind].size() && heap.SlotTexture(kind, state.slots[kind][element]) == textures[index].get(); + if (!holdsTexture) ++wrong; } - stageState.samplerGenerations.clear(); - for (const auto slot : stageState.samplerSlots) stageState.samplerGenerations.push_back(heap.SamplerGeneration(slot)); - stageState.slotSerial = slotSerial; } + if (checked.load() % 100000u < 8u) { + std::fprintf(stderr, "[heap-slots] verify: %llu image slots checked, %llu hold another texture\n", + static_cast(checked.load()), static_cast(wrong.load())); + } +} + +void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const HeapStageState& stageState, + std::vector& patched, bool current) const { + namespace Abi = ShaderRecompiler::RuntimeAbi; + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + constexpr auto metadataWords = sizeof(Abi::ResourceMetadata) / sizeof(std::uint32_t); + const auto& program = *shader.program; const auto& slots = stageState.slots; const auto& samplerSlots = stageState.samplerSlots; - static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; - if (verifySlots) { - static std::atomic checked{0}, wrong{0}; - for (const auto& binding : bindings) { - if (!ownHeap(binding) || binding.layout.descriptorType != VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) continue; - const auto kind = binding.layout.binding % bindingCount; - for (std::size_t element = 0; element < binding.imageAllocations.size(); ++element) { - const auto index = binding.imageAllocations[element]; - if (index == std::numeric_limits::max()) continue; - ++checked; - if (element >= stageState.slots[kind].size() || heap.SlotTexture(kind, stageState.slots[kind][element]) != textures[index].get()) ++wrong; - } + for (std::uint32_t image = 0; image < program.runtimeImageCount; ++image) { + const auto offset = program.imageMetadataDword + image * metadataWords; + const auto kind = patched[offset + offsetof(Abi::ResourceMetadata, binding) / 4u] % bindingCount; + const bool storageKind = kind >= Abi::FirstStorageImageBinding && kind < static_cast(Abi::Binding::Samplers); + if (storageKind && (!Abi::GpuHeapStorageKind(kind) || slots[kind].empty())) continue; + auto& first = patched[offset + offsetof(Abi::ResourceMetadata, firstElement) / 4u]; + if (kind < Abi::FirstImageBinding) continue; + if (!(kind < slots.size() && first < slots[kind].size())) { + char text[320]; + std::snprintf( + text, sizeof(text), + "AGC graphics: GPU-mode image metadata names an element the stage does not bind (stage %u, image %u of %u, kind %u, first %u, slots of the kind %zu, flags 0x%x, element count %u, bindings %zu, stage state reused %d)", + static_cast(shader.stage), image, program.runtimeImageCount, kind, first, + kind < slots.size() ? slots[kind].size() : std::size_t{0}, patched[offset + offsetof(Abi::ResourceMetadata, flags) / 4u], + patched[offset + offsetof(Abi::ResourceMetadata, elementCount) / 4u], bindings.size(), current ? 1 : 0); + throw std::runtime_error(text); + } + first = slots[kind][first]; + } + for (const auto& word : program.heapSlotWords) { + Require(word.dword < patched.size(), "a GPU-mode slot word lies outside the shader data"); + if (word.kind == static_cast(Abi::Binding::Samplers)) { + Require(word.element < samplerSlots.size(), "a GPU-mode slot word names a sampler the stage does not bind"); + patched[word.dword] = samplerSlots[word.element]; + continue; } - if (checked.load() % 100000u < 8u) std::fprintf(stderr, "[heap-slots] verify: %llu image slots checked, %llu hold another texture\n", static_cast(checked.load()), static_cast(wrong.load())); + if (!(word.kind < slots.size() && word.element < slots[word.kind].size())) { + char text[256]; + std::snprintf( + text, sizeof(text), + "AGC graphics: a GPU-mode slot word names an image the stage does not bind (stage %u, kind %u, element %u, slots of the kind %zu, bindings %zu)", + static_cast(shader.stage), word.kind, word.element, + word.kind < slots.size() ? slots[word.kind].size() : std::size_t{0}, bindings.size()); + throw std::runtime_error(text); + } + patched[word.dword] = slots[word.kind][word.element]; + } + const bool slotWords = !program.registrationModule; + Require(slotWords || program.samplerSlotDword + samplerSlots.size() <= patched.size(), "GPU-mode sampler slots exceed the shader data"); + if (!slotWords) std::copy(samplerSlots.begin(), samplerSlots.end(), patched.begin() + program.samplerSlotDword); +} + +void ShaderResources::writeHeapStage(const CompiledShader& shader) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + HeapCostScope slotsCost(HeapCost::Slots); + auto& heap = BindlessHeap::For(context); + const VkShaderStageFlags stageBit = VulkanStage(shader.stage); + const auto stageIndex = HeapStageIndex(shader.stage); + auto& stageState = heapStages[stageIndex]; + struct HeapKeyStorage {}; + auto& key = HostThreadLocal, HeapKeyStorage>(); + appendHeapSlotKey(stageBit, key); + bool current = key == stageState.key; + const auto slotSerial = heap.SlotSerial(); + const bool unmoved = current && EpochProofs() && stageState.slotSerial == slotSerial; + if (!unmoved && current && CommitTrims()) + current = + heap.GenerationsCurrent(stageState.slots, stageState.slotGenerations, stageState.samplerSlots, stageState.samplerGenerations); + else if (!unmoved && current) current = heapSlotsCurrent(heap, stageState); + if (!current) { + stageState.key = key; + takeHeapSlots(heap, stageState, stageBit, key); + noteHeapSlotGenerations(heap, stageState); } + stageState.slotSerial = slotSerial; + static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + if (verifySlots) verifyHeapSlots(heap, stageState, stageBit); slotsCost.Stop(); + HeapCostScope dataCost(HeapCost::StageData); const std::size_t dataIndex = DataOffsetIndex(stageIndex, Abi::Binding::ShaderData); const std::size_t flatIndex = DataOffsetIndex(stageIndex, Abi::Binding::FlattenedSrt); const auto& program = *shader.program; if (program.dataAddressPush) writeHeapTableMap(shader, stageIndex); for (const auto& binding : program.bindings) { - if (binding.role != ShaderRecompiler::DescriptorRole::ShaderData && binding.role != ShaderRecompiler::DescriptorRole::FlattenedSrt) continue; - const auto& words = binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt && shader.heap != nullptr && !shader.heap->flattenedSrt.empty() ? shader.heap->flattenedSrt : DrawGuestWords(shader, binding); - const auto userData = shader.heap != nullptr ? std::span(shader.heap->userData) : std::span{}; - const bool sameInput = binding.role == ShaderRecompiler::DescriptorRole::ShaderData && current && stageState.dataInput.size() == words.size() + userData.size() && std::equal(words.begin(), words.end(), stageState.dataInput.begin()) && std::equal(userData.begin(), userData.end(), stageState.dataInput.begin() + static_cast(words.size())); + const bool shaderData = binding.role == ShaderRecompiler::DescriptorRole::ShaderData; + if (!shaderData && binding.role != ShaderRecompiler::DescriptorRole::FlattenedSrt) continue; + const bool heapFlattened = !shaderData && shader.heap != nullptr && !shader.heap->flattenedSrt.empty(); + const auto& words = heapFlattened ? shader.heap->flattenedSrt : DrawGuestWords(shader, binding); + const auto userData = + shader.heap != nullptr ? std::span(shader.heap->userData) : std::span{}; + const bool sameInput = + binding.role == ShaderRecompiler::DescriptorRole::ShaderData && current && + stageState.dataInput.size() == words.size() + userData.size() && + std::equal(words.begin(), words.end(), stageState.dataInput.begin()) && + std::equal(userData.begin(), userData.end(), stageState.dataInput.begin() + static_cast(words.size())); if (sameInput && !verifySlots) { if (heap.Held(stageState.data.mark)) { heapOffsets[dataIndex] = stageState.data.mark.offset; @@ -6335,64 +6447,34 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { } stageState.data.mark.entry = 0; } - if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, words); - if (binding.role != ShaderRecompiler::DescriptorRole::ShaderData) { + if (!shaderData) { heapOffsets[flatIndex] = heapSpan(stageState.flat, words); heapSrtDwords[stageIndex] = static_cast(words.size()); continue; } + ValidateRuntimeResources(shader, words); struct PatchedStorage {}; auto& patched = HostThreadLocal, PatchedStorage>(); patched.assign(words.begin(), words.end()); - if (shader.heap != nullptr) std::copy_n(shader.heap->userData.begin(), std::min(shader.heap->userData.size(), patched.size()), patched.begin()); + if (shader.heap != nullptr) + std::copy_n(shader.heap->userData.begin(), std::min(shader.heap->userData.size(), patched.size()), patched.begin()); for (const auto& [byte, adjustment] : stageState.dataPatches) { Require(byte < patched.size() * sizeof(std::uint32_t), "a GPU-mode guest buffer offset lies outside the shader data"); reinterpret_cast(patched.data())[byte] = static_cast(adjustment); } - { - constexpr auto metadataWords = sizeof(Abi::ResourceMetadata) / sizeof(std::uint32_t); - for (std::uint32_t image = 0; image < program.runtimeImageCount; ++image) { - const auto offset = program.imageMetadataDword + image * metadataWords; - const auto kind = patched[offset + offsetof(Abi::ResourceMetadata, binding) / 4u] % bindingCount; - if (kind >= Abi::FirstStorageImageBinding && kind < static_cast(Abi::Binding::Samplers) && (!Abi::GpuHeapStorageKind(kind) || slots[kind].empty())) continue; - auto& first = patched[offset + offsetof(Abi::ResourceMetadata, firstElement) / 4u]; - if (kind < Abi::FirstImageBinding) continue; - if (!(kind < slots.size() && first < slots[kind].size())) { - char text[320]; - std::snprintf(text, sizeof(text), "AGC graphics: GPU-mode image metadata names an element the stage does not bind (stage %u, image %u of %u, kind %u, first %u, slots of the kind %zu, flags 0x%x, element count %u, bindings %zu, stage state reused %d)", static_cast(shader.stage), image, program.runtimeImageCount, kind, first, kind < slots.size() ? slots[kind].size() : std::size_t{0}, patched[offset + offsetof(Abi::ResourceMetadata, flags) / 4u], patched[offset + offsetof(Abi::ResourceMetadata, elementCount) / 4u], bindings.size(), current ? 1 : 0); - throw std::runtime_error(text); - } - first = slots[kind][first]; - } - const bool slotWords = !program.registrationModule; - for (const auto& word : program.heapSlotWords) { - Require(word.dword < patched.size(), "a GPU-mode slot word lies outside the shader data"); - if (word.kind == static_cast(Abi::Binding::Samplers)) { - Require(word.element < samplerSlots.size(), "a GPU-mode slot word names a sampler the stage does not bind"); - patched[word.dword] = samplerSlots[word.element]; - continue; - } - if (!(word.kind < slots.size() && word.element < slots[word.kind].size())) { - char text[256]; - std::snprintf(text, sizeof(text), "AGC graphics: a GPU-mode slot word names an image the stage does not bind (stage %u, kind %u, element %u, slots of the kind %zu, bindings %zu)", static_cast(shader.stage), word.kind, word.element, word.kind < slots.size() ? slots[word.kind].size() : std::size_t{0}, bindings.size()); - throw std::runtime_error(text); - } - patched[word.dword] = slots[word.kind][word.element]; - } - Require(slotWords || program.samplerSlotDword + samplerSlots.size() <= patched.size(), "GPU-mode sampler slots exceed the shader data"); - if (!slotWords) std::copy(samplerSlots.begin(), samplerSlots.end(), patched.begin() + program.samplerSlotDword); - if (addressedBuffers) { - HeapCostScope bufferCost(HeapCost::BufferAddresses); - writeBufferAddresses(patched, static_cast(stageIndex), nullptr); - bufferCost.Stop(); - stageDataWords[stageIndex].assign(patched.begin(), patched.end()); - stageDataIndex[stageIndex] = dataIndex; - } - if (verifySlots && sameInput && !std::ranges::equal(stageState.data.words, patched)) throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its inputs and slots did not"); - heapOffsets[dataIndex] = heapSpan(stageState.data, patched); - stageState.dataInput.assign(words.begin(), words.end()); - stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); - } + patchHeapSlotWords(shader, stageState, patched, current); + if (addressedBuffers) { + HeapCostScope bufferCost(HeapCost::BufferAddresses); + writeBufferAddresses(patched, static_cast(stageIndex), nullptr); + bufferCost.Stop(); + stageDataWords[stageIndex].assign(patched.begin(), patched.end()); + stageDataIndex[stageIndex] = dataIndex; + } + if (verifySlots && sameInput && !std::ranges::equal(stageState.data.words, patched)) + throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its inputs and slots did not"); + heapOffsets[dataIndex] = heapSpan(stageState.data, patched); + stageState.dataInput.assign(words.begin(), words.end()); + stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); } } diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index ff63d3af5efa..1c55a37fb6ec 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -109,7 +109,8 @@ void sweptOwnerReentry(const Context& context, VkImageView view) { }); }; require(heap.StorageSlot(kind, owner(), view).has_value(), "the first storage owner takes the kind's only slot"); - require(heap.StorageSlot(kind, owner(), view).has_value() && released == 1, "a full kind sweeps an owner whose release calls back into the heap"); + require(heap.StorageSlot(kind, owner(), view).has_value() && released == 1, + "a full kind sweeps an owner whose release calls back into the heap"); BindlessHeap::NoteSweepDue(); BindlessHeap::SweepIfDue(); require(released == 2, "a due sweep releases an owner that calls back into the heap"); @@ -158,7 +159,8 @@ void heapComesBack(const Context& context, VkImageView view) { std::vector> held; for (std::size_t index = 0; index < 7u; ++index) { held.push_back(fakeTexture(index)); - require(heap.TextureSlot(kind, held.back(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture takes one of the eight capped slots"); + require(heap.TextureSlot(kind, held.back(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), + "a texture takes one of the eight capped slots"); } require(BindlessHeap::NearlyFull(), "one free slot of eight refuses the heap"); BindlessHeap::SweepIfDue(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp index 55463a68eb08..74676d1af8e0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp @@ -18,7 +18,6 @@ #include #include - namespace { void Require(bool condition, const std::string& message) { @@ -28,9 +27,12 @@ void Require(bool condition, const std::string& message) { constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; constexpr std::array OtherTexel{0xf0u, 0x20u, 0x00u, 0x40u}; -alignas(256) constexpr std::array SampleCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; +alignas(256) constexpr std::array SampleCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; -alignas(256) constexpr std::array LdsSampleCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0x7e080280u, 0xbf8c0000u, 0xd8340000u, 0x00000004u, 0xbf8c0000u, 0xd8d80000u, 0x00000004u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array LdsSampleCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0x7e080280u, 0xbf8c0000u, 0xd8340000u, 0x00000004u, + 0xbf8c0000u, 0xd8d80000u, 0x00000004u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u, 0xbf810000u}; alignas(256) std::array TextureMemory{}; alignas(256) std::array OtherTextureMemory{}; @@ -64,7 +66,14 @@ std::uint32_t High(const void* pointer) { std::array Image(const void* pointer) { const auto address = static_cast(reinterpret_cast(pointer)); - return {static_cast(address >> 8u), static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), 3u << 14u, 0xfacu | (9u << 28u), 0u, 0u, 0u, 0u}; + return {static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u}; } void SetShaderRegister(std::vector& words, std::uint32_t offset, std::uint32_t value) { @@ -97,12 +106,15 @@ void Submit(std::vector& words) { void RequireSampled(const float* output, const std::array& expected, const std::string& what, bool heap) { for (std::size_t channel = 0; channel < 4; ++channel) { const float wanted = static_cast(expected[channel]) / 255.0f; - Require(std::fabs(output[channel] - wanted) < 1e-6f, what + ": channel " + std::to_string(channel) + " is " + std::to_string(output[channel]) + ", expected " + std::to_string(wanted) + (heap ? " through the heap" : "")); + Require(std::fabs(output[channel] - wanted) < 1e-6f, what + ": channel " + std::to_string(channel) + " is " + + std::to_string(output[channel]) + ", expected " + std::to_string(wanted) + + (heap ? " through the heap" : "")); } } void Fill(std::array& memory, const std::array& texel) { - for (std::size_t offset = 0; offset < memory.size(); offset += texel.size()) std::memcpy(memory.data() + offset, texel.data(), texel.size()); + for (std::size_t offset = 0; offset < memory.size(); offset += texel.size()) + std::memcpy(memory.data() + offset, texel.data(), texel.size()); } void DriverSample(bool heap) { @@ -116,7 +128,8 @@ void DriverSample(bool heap) { if (heap) Require(AgcDriver::Graphics::HeapComputeStages() > before, "the heap did not take the sampling compute stage"); } -ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const void* image, float* output, std::span code = SampleCode, std::uint32_t ldsDwords = 0u) { +ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const void* image, float* output, + std::span code = SampleCode, std::uint32_t ldsDwords = 0u) { std::vector userData; const auto descriptor = Image(image); userData.insert(userData.end(), descriptor.begin(), descriptor.end()); @@ -124,7 +137,11 @@ ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const userData.insert(userData.end(), {Low(output), High(output) & 0xffffu, static_cast(4u * sizeof(float)), 0x31016facu}); const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; const ShaderRecompiler::ShaderComputeStageInfo compute{{1u, 1u, 1u}, ldsDwords, {false, false, false}, false, 1u}; - ShaderRecompiler::RecompileRequest request{{ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, memory}, device.ComputeTarget(32u), {0u, 0u, 0u, 128u}}; + ShaderRecompiler::RecompileRequest request{ + {ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, + {32u, 0u, userData, compute, std::nullopt, std::nullopt, memory}, + device.ComputeTarget(32u), + {0u, 0u, 0u, 128u}}; request.useCache = false; return ShaderRecompiler::Recompile(request); } @@ -133,7 +150,8 @@ void DeviceSample(AgcDriver::VulkanDevice& device, bool heap) { for (std::size_t index = 1; index < Outputs.size(); ++index) Outputs[index].fill(-1.0f); const auto first = Compile(device, OtherTextureMemory.data(), Outputs[1].data()); const auto second = Compile(device, TextureMemory.data(), Outputs[2].data()); - Require(first.gpuResolvedImages == heap && second.gpuResolvedImages == heap, heap ? "a sampling compute stage is not GPU mode" : "a compute stage took the heap without it"); + Require(first.gpuResolvedImages == heap && second.gpuResolvedImages == heap, + heap ? "a sampling compute stage is not GPU mode" : "a compute stage took the heap without it"); const auto before = AgcDriver::Graphics::HeapComputeStages(); const auto pushesBefore = AgcDriver::Graphics::DataAddressPushes(); device.Dispatch(first, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); @@ -142,19 +160,24 @@ void DeviceSample(AgcDriver::VulkanDevice& device, bool heap) { RequireSampled(Outputs[1].data(), OtherTexel, "the first of two textures in one batch", heap); RequireSampled(Outputs[2].data(), Texel, "the second of two textures in one batch", heap); if (heap) Require(AgcDriver::Graphics::HeapComputeStages() >= before + 2u, "the heap did not take both sampling compute stages"); - if (heap) Require(AgcDriver::Graphics::DataAddressPushes() >= pushesBefore + 2u, "a heap dispatch did not read its shader data through pushed addresses"); + if (heap) + Require(AgcDriver::Graphics::DataAddressPushes() >= pushesBefore + 2u, + "a heap dispatch did not read its shader data through pushed addresses"); const auto again = Compile(device, TextureMemory.data(), Outputs[3].data()); device.Dispatch(again, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); device.WaitIdle(); RequireSampled(Outputs[3].data(), Texel, "the first texture again in a later batch", heap); Outputs[1].fill(-1.0f); - const auto lds = Compile(device, TextureMemory.data(), Outputs[1].data(), LdsSampleCode, (device.ComputeTarget(32u).maxWorkgroupSharedMemoryBytes + 4096u) / 4u); - Require(lds.workgroupMemoryDwords != 0u && lds.gpuResolvedImages == heap, "the LDS sampling stage did not get workgroup memory in the expected mode"); + const auto lds = Compile(device, TextureMemory.data(), Outputs[1].data(), LdsSampleCode, + (device.ComputeTarget(32u).maxWorkgroupSharedMemoryBytes + 4096u) / 4u); + Require(lds.workgroupMemoryDwords != 0u && lds.gpuResolvedImages == heap, + "the LDS sampling stage did not get workgroup memory in the expected mode"); const auto heapPipelines = device.DescriptorHeapComputePipelines(); device.Dispatch(lds, 1u, 1u, 1u, {}, reinterpret_cast(LdsSampleCode.data())); device.WaitIdle(); RequireSampled(Outputs[1].data(), Texel, "the texture sampled through workgroup memory", heap); - if (heap && heapPipelines != 0u) Require(device.DescriptorHeapComputePipelines() > heapPipelines, "the LDS sampling stage did not take the descriptor heap"); + if (heap && heapPipelines != 0u) + Require(device.DescriptorHeapComputePipelines() > heapPipelines, "the LDS sampling stage did not take the descriptor heap"); } } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index bc43c050fac0..d68fe30067aa 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -23,7 +23,6 @@ #include #include - namespace { using AgcDriver::Graphics::Require; @@ -35,24 +34,39 @@ alignas(256) constexpr std::array VertexCode{ 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, }; -alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array BufferPixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array GdsPixelCode{0xbefc03ffu, 0x0000ffffu, 0x7e0002f0u, 0x7e0202f0u, 0xd8fa0010u, 0x04000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array StoragePixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e100280u, 0x7e120280u, 0xf0201f08u, 0x00040008u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array LdsPixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e080280u, 0xd8344400u, 0x00000004u, 0xbf8cc07fu, 0xd8d84400u, 0x00000004u, 0xbf8cc07fu, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, + 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array BufferPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array GdsPixelCode{ + 0xbefc03ffu, 0x0000ffffu, 0x7e0002f0u, 0x7e0202f0u, 0xd8fa0010u, 0x04000000u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array StoragePixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e100280u, 0x7e120280u, 0xf0201f08u, + 0x00040008u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array LdsPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e080280u, 0xd8344400u, 0x00000004u, + 0xbf8cc07fu, 0xd8d84400u, 0x00000004u, 0xbf8cc07fu, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; alignas(4096) std::array StorageMemory{}; alignas(256) constexpr std::array SamplingVertexCode{ - 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00820c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, - 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, - 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, + 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00820c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, + 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, + 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, }; -alignas(256) constexpr std::array InterpolantPixelCode{0xc8020002u, 0xc8060102u, 0xc80a0202u, 0xc80e0302u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array BdaPixelCode{0x7e0002f0u, 0x7e0202f0u, 0x7e08020cu, 0x7e0a020du, 0xdc308000u, 0x067d0004u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060306u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array TablePixelCode{0xf4200404u, 0xfa000000u, 0xbf8cc07fu, 0x8f108510u, 0xf42c0500u, 0x20000000u, 0xbf8cc07fu, 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00250000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array InterpolantPixelCode{0xc8020002u, 0xc8060102u, 0xc80a0202u, 0xc80e0302u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array BdaPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0x7e08020cu, 0x7e0a020du, 0xdc308000u, 0x067d0004u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0x7e060306u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TablePixelCode{ + 0xf4200404u, 0xfa000000u, 0xbf8cc07fu, 0x8f108510u, 0xf42c0500u, 0x20000000u, 0xbf8cc07fu, 0x7e0002f0u, + 0x7e0202f0u, 0xf09c0f08u, 0x00250000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; alignas(256) constexpr std::array TableVertexCode{ - 0xf4200508u, 0xfa000000u, 0xbf8cc07fu, 0x8f148514u, 0xf42c0604u, 0x28000000u, 0xbf8cc07fu, 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00660c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, - 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, - 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, + 0xf4200508u, 0xfa000000u, 0xbf8cc07fu, 0x8f148514u, 0xf42c0604u, 0x28000000u, 0xbf8cc07fu, 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, + 0x00660c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, + 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, }; alignas(256) std::array TableMemory{}; alignas(256) std::array MixedVertexCode{}; @@ -93,26 +107,98 @@ void Append(std::vector& commands, std::uint32_t opcode, std::ini enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds }; +const std::uint32_t* VertexProgram(Mode mode) { + if (mode == Mode::VertexTable) return TableVertexCode.data(); + if (mode == Mode::Vertex) return SamplingVertexCode.data(); + return VertexCode.data(); +} + +std::uint32_t PixelUserWords(Mode mode, bool vertexSampling) { + switch (mode) { + case Mode::Storage: + return 24u; + case Mode::Buffer: + case Mode::MovedBuffer: + return 16u; + case Mode::Bda: + return 14u; + default: + return vertexSampling ? 0u : 12u; + } +} + +unsigned ExpectedChannel(Mode mode, bool buffer, std::size_t channel) { + if (mode == Mode::MovedTexture) return 0x33u; + if ((mode == Mode::Bda || mode == Mode::MovedBuffer) && channel == 3) return SecondAlphaByte; + if (buffer && channel == 3) return BufferAlphaByte; + return Texel[channel]; +} + +const char* DrawnWhat(Mode mode, bool buffer) { + if (mode == Mode::Bda) return " (texture and BDA)"; + if (mode == Mode::MovedBuffer) return " (texture and a buffer moved between two draws)"; + if (mode == Mode::MovedTexture) return " (a texture changed between two draws)"; + if (buffer) return " (texture and buffer)"; + if (mode == Mode::Table) return " (image table)"; + return " (texture)"; +} + +const char* TakenWhat(Mode mode, bool buffer) { + if (buffer) return " reading a buffer"; + if (mode == Mode::Vertex) return " (vertex stage)"; + if (mode == Mode::Bda) return " loading through BDA"; + if (mode == Mode::Table) return " reading an image table"; + if (mode == Mode::VertexTable) return " (vertex stage reading an image table)"; + return ""; +} + std::vector Draw(const std::uint32_t* pixelCode, Mode mode, const std::uint32_t* vertexCode = nullptr) { const bool vertexSampling = mode == Mode::Vertex || mode == Mode::VertexTable; - const auto vertex = reinterpret_cast(vertexCode != nullptr ? vertexCode : mode == Mode::VertexTable ? TableVertexCode.data() : mode == Mode::Vertex ? SamplingVertexCode.data() : VertexCode.data()); + const auto vertex = reinterpret_cast(vertexCode != nullptr ? vertexCode : VertexProgram(mode)); const auto pixel = reinterpret_cast(pixelCode); const auto color = reinterpret_cast(ColorMemory.data()); const auto texture = static_cast(reinterpret_cast(TextureMemory.data())); const auto bufferAddress = static_cast(reinterpret_cast(BufferMemory.data() + 1)); const auto storage = static_cast(reinterpret_cast(StorageMemory.data())); - const std::array descriptors{ - static_cast(texture >> 8u), static_cast((texture >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), 3u << 14u, 0xfacu | (9u << 28u), 0u, 0u, 0u, 0u, - 0u, 0u, 0u, 0u, - static_cast(bufferAddress), static_cast((bufferAddress >> 32u) & 0xffffu), static_cast(sizeof(BufferMemory) - sizeof(float)), 0xfacu, - static_cast(storage >> 8u), static_cast((storage >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), 3u << 14u, 0xfacu | (9u << 28u), 0u, 0u, 0u, 0u}; - const auto userWords = mode == Mode::Storage ? 24u : mode == Mode::Buffer || mode == Mode::MovedBuffer ? 16u : mode == Mode::Bda ? 14u : vertexSampling ? 0u : 12u; + const std::array descriptors{static_cast(texture >> 8u), + static_cast((texture >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u, + 0u, + 0u, + 0u, + 0u, + static_cast(bufferAddress), + static_cast((bufferAddress >> 32u) & 0xffffu), + static_cast(sizeof(BufferMemory) - sizeof(float)), + 0xfacu, + static_cast(storage >> 8u), + static_cast((storage >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u}; + const auto userWords = PixelUserWords(mode, vertexSampling); const auto bufferWords = [](const void* pointer, std::uint32_t bytes) { const auto address = static_cast(reinterpret_cast(pointer)); - return std::array{static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, 0xfacu}; + return std::array{static_cast(address), static_cast((address >> 32u) & 0xffffu), + bytes, 0xfacu}; }; const auto other = static_cast(reinterpret_cast(OtherTextureMemory.data())); - const std::array otherImage{static_cast(other >> 8u), static_cast((other >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), 3u << 14u, 0xfacu | (9u << 28u), 0u, 0u, 0u, 0u}; + const std::array otherImage{static_cast(other >> 8u), + static_cast((other >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u}; std::copy(otherImage.begin(), otherImage.end(), TableMemory.begin()); std::copy(descriptors.begin(), descriptors.begin() + 8, TableMemory.begin() + 8); MaterialMemory = {1u, 0u, 0u, 0u}; @@ -123,34 +209,80 @@ std::vector Draw(const std::uint32_t* pixelCode, Mode mode, const std::copy(material.begin(), material.end(), tableWords.begin() + 8); const std::vector> context{ {0x2d5, 0x2000}, - {0x1b6, 0}, {0x207, 0}, {0x200, 0}, {0x203, 0x800}, - {0x2dc, 0xaa00}, {0x2f8, 0}, {0x293, 0}, - {0x80, 0}, {0x8d, 0}, {0x83, 0xffff}, {0x8c, 0xa}, - {0x2f9, 0x2d}, {0x313, 0x6000}, {0x30e, 0xffffffff}, {0x30f, 0xffffffff}, - {0x206, 0x43f}, {0x204, 0x80000}, {0x205, 0x240}, - {0x8e, 0xf}, {0x8f, 0xf}, {0x202, 0xcc0010}, - {0x1c4, 0}, {0x1c5, 9}, {0x1c3, 4}, {0x31c, 0x28028}, - {0x31b, 0}, {0x31d, 0}, {0x3b0, (63u << 14u) | 3u}, - {0x3b8, 0x9000000}, {0x1e0, 0}, - {0xc, 0}, {0xd, 0x40040}, - {0x81, 0x80000000}, {0x82, 0x40040}, - {0x90, 0x80000000}, {0x91, 0x40040}, - {0x94, 0x80000000}, {0x95, 0x40040}, - {0x10f, std::bit_cast(32.0f)}, {0x110, std::bit_cast(32.0f)}, - {0x111, std::bit_cast(-2.0f)}, {0x112, std::bit_cast(2.0f)}, - {0x113, std::bit_cast(1.0f)}, {0x114, 0}, - {0xb4, 0}, {0xb5, std::bit_cast(1.0f)}, - {0x2fe, 0}, {0x302, 0}, {0x306, 0}, {0x30a, 0}, - {0x318, static_cast(color >> 8u)}, {0x390, static_cast(color >> 40u)}, {0x292, 2}, + {0x1b6, 0}, + {0x207, 0}, + {0x200, 0}, + {0x203, 0x800}, + {0x2dc, 0xaa00}, + {0x2f8, 0}, + {0x293, 0}, + {0x80, 0}, + {0x8d, 0}, + {0x83, 0xffff}, + {0x8c, 0xa}, + {0x2f9, 0x2d}, + {0x313, 0x6000}, + {0x30e, 0xffffffff}, + {0x30f, 0xffffffff}, + {0x206, 0x43f}, + {0x204, 0x80000}, + {0x205, 0x240}, + {0x8e, 0xf}, + {0x8f, 0xf}, + {0x202, 0xcc0010}, + {0x1c4, 0}, + {0x1c5, 9}, + {0x1c3, 4}, + {0x31c, 0x28028}, + {0x31b, 0}, + {0x31d, 0}, + {0x3b0, (63u << 14u) | 3u}, + {0x3b8, 0x9000000}, + {0x1e0, 0}, + {0xc, 0}, + {0xd, 0x40040}, + {0x81, 0x80000000}, + {0x82, 0x40040}, + {0x90, 0x80000000}, + {0x91, 0x40040}, + {0x94, 0x80000000}, + {0x95, 0x40040}, + {0x10f, std::bit_cast(32.0f)}, + {0x110, std::bit_cast(32.0f)}, + {0x111, std::bit_cast(-2.0f)}, + {0x112, std::bit_cast(2.0f)}, + {0x113, std::bit_cast(1.0f)}, + {0x114, 0}, + {0xb4, 0}, + {0xb5, std::bit_cast(1.0f)}, + {0x2fe, 0}, + {0x302, 0}, + {0x306, 0}, + {0x30a, 0}, + {0x318, static_cast(color >> 8u)}, + {0x390, static_cast(color >> 40u)}, + {0x292, 2}, }; std::vector> shader{ - {0xc8, static_cast(vertex >> 8u)}, {0xc9, static_cast(vertex >> 40u)}, {0x8b, 1u << 1u}, {0x8c, 0}, - {0x008, static_cast(pixel >> 8u)}, {0x009, static_cast(pixel >> 40u)}, {0x00b, userWords << 1u}, + {0xc8, static_cast(vertex >> 8u)}, + {0xc9, static_cast(vertex >> 40u)}, + {0x8b, 1u << 1u}, + {0x8c, 0}, + {0x008, static_cast(pixel >> 8u)}, + {0x009, static_cast(pixel >> 40u)}, + {0x00b, userWords << 1u}, }; - for (std::uint32_t index = 0; index < userWords; ++index) shader.emplace_back(0x00cu + index, mode == Mode::Table ? tableWords[index] : mode == Mode::Bda && index >= 12u ? static_cast(reinterpret_cast(BufferMemory.data() + 1) >> (index == 12u ? 0u : 32u)) : descriptors[index]); + const auto userWord = [&](std::uint32_t index) -> std::uint32_t { + if (mode == Mode::Table) return tableWords[index]; + if (mode == Mode::Bda && index >= 12u) + return static_cast(reinterpret_cast(BufferMemory.data() + 1) >> (index == 12u ? 0u : 32u)); + return descriptors[index]; + }; + for (std::uint32_t index = 0; index < userWords; ++index) shader.emplace_back(0x00cu + index, userWord(index)); if (vertexSampling) { shader.emplace_back(0x8bu, 12u << 1u); - for (std::uint32_t index = 0; index < 12u; ++index) shader.emplace_back(0x08cu + index, mode == Mode::VertexTable ? tableWords[index] : descriptors[index]); + for (std::uint32_t index = 0; index < 12u; ++index) + shader.emplace_back(0x08cu + index, mode == Mode::VertexTable ? tableWords[index] : descriptors[index]); shader.emplace_back(0x00bu, 0u); } std::vector commands; @@ -179,6 +311,26 @@ std::vector Draw(const std::uint32_t* pixelCode, Mode mode, const return commands; } +std::span PixelProgram(Mode mode, bool buffer, bool vertexSampling) { + switch (mode) { + case Mode::PixelLds: + return LdsPixelCode; + case Mode::Table: + return TablePixelCode; + case Mode::Gds: + return GdsPixelCode; + case Mode::Storage: + return StoragePixelCode; + case Mode::Bda: + return BdaPixelCode; + default: + break; + } + if (buffer) return BufferPixelCode; + if (vertexSampling) return InterpolantPixelCode; + return PixelCode; +} + void DrawSamplesTheTexture(bool heap, Mode mode) { const bool buffer = mode == Mode::Buffer || mode == Mode::Bda || mode == Mode::MovedBuffer; ColorMemory.fill(Kept); @@ -187,12 +339,16 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { BufferMemory[1] = BufferAlpha; BufferMemory[2] = SecondAlpha; BufferMemory[3] = SecondAlpha; - for (std::size_t offset = 0; offset < TextureMemory.size(); offset += Texel.size()) std::memcpy(TextureMemory.data() + offset, Texel.data(), Texel.size()); + for (std::size_t offset = 0; offset < TextureMemory.size(); offset += Texel.size()) + std::memcpy(TextureMemory.data() + offset, Texel.data(), Texel.size()); Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); - for (std::size_t offset = 0; offset < OtherTextureMemory.size(); offset += 4) OtherTextureMemory[offset] = OtherTextureMemory[offset + 1] = OtherTextureMemory[offset + 2] = OtherTextureMemory[offset + 3] = 0x33u; + for (std::size_t offset = 0; offset < OtherTextureMemory.size(); offset += 4) + OtherTextureMemory[offset] = OtherTextureMemory[offset + 1] = OtherTextureMemory[offset + 2] = OtherTextureMemory[offset + 3] = + 0x33u; const bool vertexSampling = mode == Mode::Vertex || mode == Mode::VertexTable; - const auto* code = mode == Mode::PixelLds ? LdsPixelCode.data() : mode == Mode::Table ? TablePixelCode.data() : mode == Mode::Gds ? GdsPixelCode.data() : mode == Mode::Storage ? StoragePixelCode.data() : mode == Mode::Bda ? BdaPixelCode.data() : buffer ? BufferPixelCode.data() : vertexSampling ? InterpolantPixelCode.data() : PixelCode.data(); - const auto bytes = mode == Mode::PixelLds ? sizeof(LdsPixelCode) : mode == Mode::Table ? sizeof(TablePixelCode) : mode == Mode::Gds ? sizeof(GdsPixelCode) : mode == Mode::Storage ? sizeof(StoragePixelCode) : mode == Mode::Bda ? sizeof(BdaPixelCode) : buffer ? sizeof(BufferPixelCode) : vertexSampling ? sizeof(InterpolantPixelCode) : sizeof(PixelCode); + const auto program = PixelProgram(mode, buffer, vertexSampling); + const auto* code = program.data(); + const auto bytes = program.size_bytes(); if (mode == Mode::Vertex) Registered(VertexHeader, SamplingVertexCode.data(), sizeof(SamplingVertexCode), 2); if (mode == Mode::VertexTable) Registered(VertexHeader, TableVertexCode.data(), sizeof(TableVertexCode), 2); Registered(PixelHeader, code, bytes, 1); @@ -207,26 +363,43 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { AgcDriverWaitIdle_nid_postfix(); std::size_t drawn = 0; for (std::size_t offset = 0; offset < ColorMemory.size(); offset += 4) { - if (std::all_of(ColorMemory.begin() + static_cast(offset), ColorMemory.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) continue; + if (std::all_of(ColorMemory.begin() + static_cast(offset), + ColorMemory.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) + continue; for (std::size_t channel = 0; channel < 4; ++channel) { const auto value = static_cast(ColorMemory[offset + channel]); - const unsigned expected = mode == Mode::MovedTexture ? 0x33u : (mode == Mode::Bda || mode == Mode::MovedBuffer) && channel == 3 ? SecondAlphaByte : buffer && channel == 3 ? BufferAlphaByte : Texel[channel]; - Require(value == expected, "pixel " + std::to_string(offset / 4) + " channel " + std::to_string(channel) + " is " + std::to_string(value) + ", expected " + std::to_string(expected) + (mode == Mode::Bda ? " (texture and BDA)" : mode == Mode::MovedBuffer ? " (texture and a buffer moved between two draws)" : mode == Mode::MovedTexture ? " (a texture changed between two draws)" : buffer ? " (texture and buffer)" : mode == Mode::Table ? " (image table)" : " (texture)") + (heap ? " through the heap" : "")); + const unsigned expected = ExpectedChannel(mode, buffer, channel); + Require(value == expected, "pixel " + std::to_string(offset / 4) + " channel " + std::to_string(channel) + " is " + + std::to_string(value) + ", expected " + std::to_string(expected) + DrawnWhat(mode, buffer) + + (heap ? " through the heap" : "")); } ++drawn; } Require(drawn != 0, "the draw covered no pixel"); - if (mode == Mode::Table || mode == Mode::VertexTable) Require(AgcDriver::Graphics::ImageTableBuilds() > tablesBefore, std::string("the table draw's ") + (mode == Mode::Table ? "fragment" : "vertex") + " stage bound no image table"); + if (mode == Mode::Table || mode == Mode::VertexTable) + Require(AgcDriver::Graphics::ImageTableBuilds() > tablesBefore, + std::string("the table draw's ") + (mode == Mode::Table ? "fragment" : "vertex") + " stage bound no image table"); if (mode == Mode::Gds) Require(*gdsCounter != 0u, "the GDS append did not count the drawn lanes"); if (mode == Mode::Storage) { - for (std::size_t channel = 0; channel < 4; ++channel) Require(StorageMemory[channel] == Texel[channel], "storage texel (0, 0) channel " + std::to_string(channel) + " is " + std::to_string(StorageMemory[channel]) + ", expected the sampled " + std::to_string(Texel[channel]) + (heap ? " through the heap" : "")); + for (std::size_t channel = 0; channel < 4; ++channel) + Require(StorageMemory[channel] == Texel[channel], "storage texel (0, 0) channel " + std::to_string(channel) + " is " + + std::to_string(StorageMemory[channel]) + ", expected the sampled " + + std::to_string(Texel[channel]) + (heap ? " through the heap" : "")); } if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) return; const bool descriptorMemory = AgcDriver::Graphics::DescriptorHeapEnabled(); - if (heap && descriptorMemory && (mode == Mode::Vertex || mode == Mode::VertexTable)) Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, "the heap did not take the sampling vertex stage with descriptor memory"); - else if (heap && (mode == Mode::Vertex || mode == Mode::VertexTable)) Require(AgcDriver::DriverDetail::HeapStagesTaken() == takenBefore, "the heap took a vertex stage whose constants are read on the CPU"); - else if (heap) Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, std::string("the heap did not take the fragment stage") + (buffer ? " reading a buffer" : mode == Mode::Vertex ? " (vertex stage)" : mode == Mode::Bda ? " loading through BDA" : mode == Mode::Table ? " reading an image table" : mode == Mode::VertexTable ? " (vertex stage reading an image table)" : "")); - if (heap && descriptorMemory) Require(AgcDriver::Graphics::DataAddressPushes() > pushesBefore, "the heap stages did not read their shader data through pushed addresses"); + if (heap && descriptorMemory && (mode == Mode::Vertex || mode == Mode::VertexTable)) + Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, + "the heap did not take the sampling vertex stage with descriptor memory"); + else if (heap && (mode == Mode::Vertex || mode == Mode::VertexTable)) + Require(AgcDriver::DriverDetail::HeapStagesTaken() == takenBefore, + "the heap took a vertex stage whose constants are read on the CPU"); + else if (heap) + Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, + std::string("the heap did not take the fragment stage") + TakenWhat(mode, buffer)); + if (heap && descriptorMemory) + Require(AgcDriver::Graphics::DataAddressPushes() > pushesBefore, + "the heap stages did not read their shader data through pushed addresses"); } void MixedDrawTakesThePerDrawPath() { @@ -234,7 +407,8 @@ void MixedDrawTakesThePerDrawPath() { using AgcDriver::Graphics::HeapFallbacks; MixedVertexCode = SamplingVertexCode; MixedPixelCode = InterpolantPixelCode; - for (std::size_t offset = 0; offset < TextureMemory.size(); offset += Texel.size()) std::memcpy(TextureMemory.data() + offset, Texel.data(), Texel.size()); + for (std::size_t offset = 0; offset < TextureMemory.size(); offset += Texel.size()) + std::memcpy(TextureMemory.data() + offset, Texel.data(), Texel.size()); Registered(PixelHeader, MixedPixelCode.data(), sizeof(MixedPixelCode), 1); { Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); @@ -256,15 +430,26 @@ void MixedDrawTakesThePerDrawPath() { AgcDriverWaitIdle_nid_postfix(); std::size_t drawn = 0; for (std::size_t offset = 0; offset < ColorMemory.size(); offset += 4) { - if (std::all_of(ColorMemory.begin() + static_cast(offset), ColorMemory.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) continue; - for (std::size_t channel = 0; channel < 4; ++channel) Require(static_cast(ColorMemory[offset + channel]) == Texel[channel], std::string("the ") + draw + " mixed draw: pixel " + std::to_string(offset / 4) + " channel " + std::to_string(channel) + " is " + std::to_string(static_cast(ColorMemory[offset + channel])) + ", expected " + std::to_string(Texel[channel])); + if (std::all_of(ColorMemory.begin() + static_cast(offset), + ColorMemory.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) + continue; + for (std::size_t channel = 0; channel < 4; ++channel) + Require(static_cast(ColorMemory[offset + channel]) == Texel[channel], + std::string("the ") + draw + " mixed draw: pixel " + std::to_string(offset / 4) + " channel " + + std::to_string(channel) + " is " + std::to_string(static_cast(ColorMemory[offset + channel])) + + ", expected " + std::to_string(Texel[channel])); ++drawn; } Require(drawn != 0, std::string("the ") + draw + " mixed draw covered no pixel"); const bool first = std::strcmp(draw, "first") == 0; - if (first) Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, "the heap did not take the vertex stage of the mixed draw"); - Require(HeapFallbacks(HeapFallback::DrawMixedRetry) - retriesBefore == (first ? 1u : 0u), std::string("the ") + draw + " mixed draw retried on the per-draw path " + std::to_string(HeapFallbacks(HeapFallback::DrawMixedRetry) - retriesBefore) + " times, expected " + (first ? "once" : "never")); - Require(HeapFallbacks(HeapFallback::DrawRefusedPair) == refusedBefore, std::string("the ") + draw + " mixed draw stayed mixed after its per-draw retry"); + if (first) + Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, "the heap did not take the vertex stage of the mixed draw"); + Require(HeapFallbacks(HeapFallback::DrawMixedRetry) - retriesBefore == (first ? 1u : 0u), + std::string("the ") + draw + " mixed draw retried on the per-draw path " + + std::to_string(HeapFallbacks(HeapFallback::DrawMixedRetry) - retriesBefore) + " times, expected " + + (first ? "once" : "never")); + Require(HeapFallbacks(HeapFallback::DrawRefusedPair) == refusedBefore, + std::string("the ") + draw + " mixed draw stayed mixed after its per-draw retry"); } AgcDriver::DriverDetail::SetHeapStageUnmapped(std::nullopt); } @@ -284,7 +469,8 @@ int main() { } const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; if (heap && !AgcDriver::Graphics::DescriptorHeapEnabled()) { - std::cout << "skipped, the device lacks VK_EXT_descriptor_heap, or the maintenance5, slot room and push data the GPU heap needs with it, so APS5_GPU_HEAP has no heap to draw through\n"; + std::cout + << "skipped, the device lacks VK_EXT_descriptor_heap, or the maintenance5, slot room and push data the GPU heap needs with it, so APS5_GPU_HEAP has no heap to draw through\n"; return VulkanTestSkipped; } { @@ -304,10 +490,13 @@ int main() { DrawSamplesTheTexture(heap, Mode::MovedTexture); DrawSamplesTheTexture(heap, Mode::PixelLds); DrawSamplesTheTexture(heap, Mode::Texture); - if (heap && AgcDriver::Graphics::DescriptorHeapEnabled() && std::getenv("APS5_HEAP_SLOT_CAP") == nullptr) MixedDrawTakesThePerDrawPath(); - if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) Require(AgcDriver::DriverDetail::HeapRefused(), "a draw found the capped heap full and the heap was not refused"); + if (heap && AgcDriver::Graphics::DescriptorHeapEnabled() && std::getenv("APS5_HEAP_SLOT_CAP") == nullptr) + MixedDrawTakesThePerDrawPath(); + if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) + Require(AgcDriver::DriverDetail::HeapRefused(), "a draw found the capped heap full and the heap was not refused"); AgcDriverShutdown_nid_postfix(); - if (heap && AgcDriver::Graphics::DescriptorHeapEnabled() && std::getenv("APS5_HEAP_SLOT_CAP") == nullptr) Require(AgcDriver::Graphics::EmptyResourceSets() != 0, "no heap draw bound without a per-draw resource set"); + if (heap && AgcDriver::Graphics::DescriptorHeapEnabled() && std::getenv("APS5_HEAP_SLOT_CAP") == nullptr) + Require(AgcDriver::Graphics::EmptyResourceSets() != 0, "no heap draw bound without a per-draw resource set"); std::cout << "A sampled texture reached the drawn pixels" << (heap ? " through the heap" : "") << '\n'; return 0; } catch (const std::exception& error) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp index 4dfb1bb9a642..c241cf1a0abf 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp @@ -23,27 +23,23 @@ alignas(256) std::array Pixels{}; alignas(256) std::array HullUserMemory{}; alignas(256) constexpr std::array LocalCode{ - 0xd5480004, 0x02090502, 0xd5480005, 0x02090102, 0xd5480006, 0x02110902, 0xd5480007, 0x02111102, - 0x7e080d04, 0x7e0a0d05, 0x7e0c0d06, 0x7e0e0d07, 0x10100cff, 0x3f19999a, 0x061010ff, 0xbf666666, - 0x3e1008ff, 0x3e800000, 0xd54b0009, 0x03c5e105, 0x161406a0, 0xd9340000, 0x0000080a, 0xd8340008, - 0x0000070a, 0xd8340010, 0x0000070a, 0xbf8cc07f, 0xbefd2106, + 0xd5480004, 0x02090502, 0xd5480005, 0x02090102, 0xd5480006, 0x02110902, 0xd5480007, 0x02111102, 0x7e080d04, 0x7e0a0d05, + 0x7e0c0d06, 0x7e0e0d07, 0x10100cff, 0x3f19999a, 0x061010ff, 0xbf666666, 0x3e1008ff, 0x3e800000, 0xd54b0009, 0x03c5e105, + 0x161406a0, 0xd9340000, 0x0000080a, 0xd8340008, 0x0000070a, 0xd8340010, 0x0000070a, 0xbf8cc07f, 0xbefd2106, }; alignas(256) constexpr std::array HullCode{ - 0xd7650000, 0x000100c1, 0xd7660000, 0x000200c1, 0xbf8a0000, 0x7da206f9, 0x81060000, 0xd5480014, - 0x02151101, 0x362402ff, 0x000000ff, 0x160028a0, 0xd5430015, 0x040224ff, 0x00000060, 0xdbfc0000, - 0x02000015, 0x162c2890, 0xd5430016, 0x045a24ff, 0x00000030, 0xbf8cc07f, 0xe0781000, 0x02020216, - 0x7da82881, 0xbe94047e, 0xb06a0060, 0x162602f9, 0x0086066a, 0xd8d80008, 0x06000013, 0xd8dc1008, - 0x07000013, 0xbf8cc07f, 0x7e300306, 0x7e320306, 0x7e340306, 0x7e360306, 0x34142484, 0xbefe0414, - 0xe0781000, 0x0403180a, 0x4a162481, 0x16161690, 0x4c1616ff, 0x00008000, 0xe0741000, 0x0202070b, - 0xbf810000, + 0xd7650000, 0x000100c1, 0xd7660000, 0x000200c1, 0xbf8a0000, 0x7da206f9, 0x81060000, 0xd5480014, 0x02151101, 0x362402ff, + 0x000000ff, 0x160028a0, 0xd5430015, 0x040224ff, 0x00000060, 0xdbfc0000, 0x02000015, 0x162c2890, 0xd5430016, 0x045a24ff, + 0x00000030, 0xbf8cc07f, 0xe0781000, 0x02020216, 0x7da82881, 0xbe94047e, 0xb06a0060, 0x162602f9, 0x0086066a, 0xd8d80008, + 0x06000013, 0xd8dc1008, 0x07000013, 0xbf8cc07f, 0x7e300306, 0x7e320306, 0x7e340306, 0x7e360306, 0x34142484, 0xbefe0414, + 0xe0781000, 0x0403180a, 0x4a162481, 0x16161690, 0x4c1616ff, 0x00008000, 0xe0741000, 0x0202070b, 0xbf810000, }; alignas(256) constexpr std::array DomainCode{ - 0xf8000941, 0x00000000, 0x34020e84, 0x16020283, 0xe0341000, 0x04030a01, 0xe0341010, 0x04030c01, - 0xe0341020, 0x04030e01, 0xbf8c3f70, 0x08040af2, 0x08040d02, 0x10201505, 0x3e201906, 0x3e201d02, - 0x10221705, 0x3e221b06, 0x3e221f02, 0xd5510012, 0x040a0d05, 0x102424ff, 0x40400000, 0x7e260280, - 0x7e2802f2, 0xf80008cf, 0x14131110, 0xf800020f, 0x14131214, 0xbf810000, + 0xf8000941, 0x00000000, 0x34020e84, 0x16020283, 0xe0341000, 0x04030a01, 0xe0341010, 0x04030c01, 0xe0341020, 0x04030e01, + 0xbf8c3f70, 0x08040af2, 0x08040d02, 0x10201505, 0x3e201906, 0x3e201d02, 0x10221705, 0x3e221b06, 0x3e221f02, 0xd5510012, + 0x040a0d05, 0x102424ff, 0x40400000, 0x7e260280, 0x7e2802f2, 0xf80008cf, 0x14131110, 0xf800020f, 0x14131214, 0xbf810000, }; alignas(256) constexpr std::array PixelCode{ @@ -57,9 +53,8 @@ constexpr std::uint16_t Corner(std::uint32_t patch, std::uint32_t x, std::uint32 } alignas(256) constexpr std::array Indices{ - Corner(0, 0, 0), Corner(0, 2, 0), Corner(0, 1, 2), - Corner(1, 0, 0), Corner(1, 2, 0), Corner(1, 1, 2), - Corner(2, 0, 0), Corner(2, 2, 0), Corner(2, 1, 2), + Corner(0, 0, 0), Corner(0, 2, 0), Corner(0, 1, 2), Corner(1, 0, 0), Corner(1, 2, 0), + Corner(1, 1, 2), Corner(2, 0, 0), Corner(2, 2, 0), Corner(2, 1, 2), }; struct Header { @@ -98,52 +93,97 @@ std::uint32_t Hi(const void* address) { std::vector Commands() { const auto color = reinterpret_cast(Pixels.data()); const auto users = reinterpret_cast(HullUserMemory.data()); - const std::vector> context{ - {0x2d5, 0x0200210du}, {0x2d6, 128u | (3u << 8u) | (3u << 14u)}, {0x2db, 1u | (2u << 2u) | (2u << 5u)}, - {0x286, std::bit_cast(64.0f)}, {0x287, std::bit_cast(1.0f)}, - {0x1b6, 1}, {0x191, 0x400}, {0x1b3, 0}, {0x1b4, 0}, - {0x260, 0}, {0x207, 0}, {0x200, 0}, {0x203, 0x800}, - {0x2dc, 0xaa00}, {0x2f8, 0}, {0x292, 2}, {0x293, 0}, - {0x80, 0}, {0x8d, 0}, {0x83, 0xffff}, {0x8c, 0xa}, - {0x2f9, 0x2d}, {0x313, 0x6000}, {0x30e, 0xffffffff}, {0x30f, 0xffffffff}, - {0x206, 0x43f}, {0x204, 0x80000}, {0x205, 0x240}, - {0x8e, 0xf}, {0x8f, 0xf}, {0x202, 0xcc0010}, - {0x1c4, 0}, {0x1c5, 9}, {0x1c3, 4}, {0x31c, 0x28028}, - {0x31b, 0}, {0x31d, 0}, {0x3b0, ((Width - 1u) << 14u) | (Height - 1u)}, - {0x3b8, 0x9000000}, {0x1e0, 0}, {0xc, 0}, {0xd, (Height << 16u) | Width}, - {0x81, 0x80000000}, {0x82, (Height << 16u) | Width}, - {0x90, 0x80000000}, {0x91, (Height << 16u) | Width}, - {0x94, 0x80000000}, {0x95, (Height << 16u) | Width}, - {0x318, static_cast(color >> 8u)}, {0x390, static_cast(color >> 40u)}, - {0x10f, std::bit_cast(Width / 2.0f)}, {0x110, std::bit_cast(Width / 2.0f)}, - {0x111, std::bit_cast(-(Height / 2.0f))}, {0x112, std::bit_cast(Height / 2.0f)}, - {0x113, std::bit_cast(1.0f)}, {0x114, 0}, - {0xb4, 0}, {0xb5, std::bit_cast(1.0f)} - }; - const std::vector> shaders{ - {0x148, Lo(LocalCode.data())}, {0x149, Hi(LocalCode.data())}, - {0x108, Lo(HullCode.data())}, {0x109, Hi(HullCode.data())}, - {0x102, static_cast(users)}, {0x103, static_cast(users >> 32u)}, {0x10b, 0}, - {0xc8, Lo(DomainCode.data())}, {0xc9, Hi(DomainCode.data())}, {0x8b, 0}, - {0x8, Lo(PixelCode.data())}, {0x9, Hi(PixelCode.data())}, {0xb, 0} - }; + const std::vector> context{{0x2d5, 0x0200210du}, + {0x2d6, 128u | (3u << 8u) | (3u << 14u)}, + {0x2db, 1u | (2u << 2u) | (2u << 5u)}, + {0x286, std::bit_cast(64.0f)}, + {0x287, std::bit_cast(1.0f)}, + {0x1b6, 1}, + {0x191, 0x400}, + {0x1b3, 0}, + {0x1b4, 0}, + {0x260, 0}, + {0x207, 0}, + {0x200, 0}, + {0x203, 0x800}, + {0x2dc, 0xaa00}, + {0x2f8, 0}, + {0x292, 2}, + {0x293, 0}, + {0x80, 0}, + {0x8d, 0}, + {0x83, 0xffff}, + {0x8c, 0xa}, + {0x2f9, 0x2d}, + {0x313, 0x6000}, + {0x30e, 0xffffffff}, + {0x30f, 0xffffffff}, + {0x206, 0x43f}, + {0x204, 0x80000}, + {0x205, 0x240}, + {0x8e, 0xf}, + {0x8f, 0xf}, + {0x202, 0xcc0010}, + {0x1c4, 0}, + {0x1c5, 9}, + {0x1c3, 4}, + {0x31c, 0x28028}, + {0x31b, 0}, + {0x31d, 0}, + {0x3b0, ((Width - 1u) << 14u) | (Height - 1u)}, + {0x3b8, 0x9000000}, + {0x1e0, 0}, + {0xc, 0}, + {0xd, (Height << 16u) | Width}, + {0x81, 0x80000000}, + {0x82, (Height << 16u) | Width}, + {0x90, 0x80000000}, + {0x91, (Height << 16u) | Width}, + {0x94, 0x80000000}, + {0x95, (Height << 16u) | Width}, + {0x318, static_cast(color >> 8u)}, + {0x390, static_cast(color >> 40u)}, + {0x10f, std::bit_cast(Width / 2.0f)}, + {0x110, std::bit_cast(Width / 2.0f)}, + {0x111, std::bit_cast(-(Height / 2.0f))}, + {0x112, std::bit_cast(Height / 2.0f)}, + {0x113, std::bit_cast(1.0f)}, + {0x114, 0}, + {0xb4, 0}, + {0xb5, std::bit_cast(1.0f)}}; + const std::vector> shaders{{0x148, Lo(LocalCode.data())}, + {0x149, Hi(LocalCode.data())}, + {0x108, Lo(HullCode.data())}, + {0x109, Hi(HullCode.data())}, + {0x102, static_cast(users)}, + {0x103, static_cast(users >> 32u)}, + {0x10b, 0}, + {0xc8, Lo(DomainCode.data())}, + {0xc9, Hi(DomainCode.data())}, + {0x8b, 0}, + {0x8, Lo(PixelCode.data())}, + {0x9, Hi(PixelCode.data())}, + {0xb, 0}}; std::vector commands; Write(commands, 0x79, 0x242, 9); for (const auto& [offset, value] : context) Write(commands, 0x69, offset, value); for (const auto& [offset, value] : shaders) Write(commands, 0x76, offset, value); commands.insert(commands.end(), {0xc0002a00u, 0u}); const auto address = reinterpret_cast(Indices.data()); - commands.insert(commands.end(), {0xc0042700u, static_cast(Indices.size()), static_cast(address), static_cast(address >> 32u), static_cast(Indices.size()), 0u}); + commands.insert(commands.end(), {0xc0042700u, static_cast(Indices.size()), static_cast(address), + static_cast(address >> 32u), static_cast(Indices.size()), 0u}); return commands; } std::array PixelAt(std::uint32_t x, std::uint32_t y) { const auto offset = (static_cast(y) * Width + x) * 4u; - return {std::to_integer(Pixels[offset]), std::to_integer(Pixels[offset + 1]), std::to_integer(Pixels[offset + 2]), std::to_integer(Pixels[offset + 3])}; + return {std::to_integer(Pixels[offset]), std::to_integer(Pixels[offset + 1]), + std::to_integer(Pixels[offset + 2]), std::to_integer(Pixels[offset + 3])}; } std::string PixelText(const std::array& pixel) { - return "(" + std::to_string(pixel[0]) + ", " + std::to_string(pixel[1]) + ", " + std::to_string(pixel[2]) + ", " + std::to_string(pixel[3]) + ")"; + return "(" + std::to_string(pixel[0]) + ", " + std::to_string(pixel[1]) + ", " + std::to_string(pixel[2]) + ", " + + std::to_string(pixel[3]) + ")"; } std::uint32_t Column(std::uint32_t patch, float offset) { @@ -160,7 +200,8 @@ std::uint32_t CoveredPixels(std::uint32_t patch, bool interior) { for (std::uint32_t x = Column(patch, 0.0f); x <= Column(patch, 0.5f) && x < Width; ++x) { const auto pixel = PixelAt(x, y); if (pixel == Background) continue; - Require(pixel[0] == 255 && pixel[2] == 0 && pixel[3] == 255, "patch " + std::to_string(patch) + " pixel (" + std::to_string(x) + ", " + std::to_string(y) + ") is " + PixelText(pixel)); + Require(pixel[0] == 255 && pixel[2] == 0 && pixel[3] == 255, "patch " + std::to_string(patch) + " pixel (" + std::to_string(x) + + ", " + std::to_string(y) + ") is " + PixelText(pixel)); if (!interior || pixel[1] > 32) ++count; } } @@ -177,11 +218,14 @@ void SubmittedPatches() { Require(sceAgcDriverSubmitDcb(&packet) == 0, "tessellation submission failed"); AgcDriverWaitIdle_nid_postfix(); const auto center = Row(-0.5f + 1.0f / 3.0f); - Require(CoveredPixels(0, false) > 100 && CoveredPixels(0, true) == 0, "the level-1 patch was not drawn as one flat triangle, centre " + PixelText(PixelAt(Column(0, 0.25f), center))); + Require(CoveredPixels(0, false) > 100 && CoveredPixels(0, true) == 0, + "the level-1 patch was not drawn as one flat triangle, centre " + PixelText(PixelAt(Column(0, 0.25f), center))); Require(CoveredPixels(1, false) == 0, "the patch with level 0 was not culled"); - Require(CoveredPixels(2, false) > 100 && PixelAt(Column(2, 0.25f), center)[1] > 32, "the level-5 patch has no interior domain points at its centre, " + PixelText(PixelAt(Column(2, 0.25f), center))); + Require(CoveredPixels(2, false) > 100 && PixelAt(Column(2, 0.25f), center)[1] > 32, + "the level-5 patch has no interior domain points at its centre, " + PixelText(PixelAt(Column(2, 0.25f), center))); Require(PixelAt(0, 0) == Background && PixelAt(Width - 1, Height - 1) == Background, "the corners changed"); - Require(!AgcDriver::Graphics::DescriptorHeapEnabled() || AgcDriver::Graphics::DataAddressPushes() > pushes, "the submitted tessellation draw did not take the descriptor heap"); + Require(!AgcDriver::Graphics::DescriptorHeapEnabled() || AgcDriver::Graphics::DataAddressPushes() > pushes, + "the submitted tessellation draw did not take the descriptor heap"); } } From 58490b5f4489d81edb6ad813aea393aa71cae0e6 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 24 Oct 2026 19:21:49 +0530 Subject: [PATCH 036/269] fix(agc): resolve a cached heap stage's image table from the draw's own program A draw-resource-cache hit reuses a build whose stages may belong to another program with the same bindings. writeHeapTableMap found its table by the build's program pointer: a different program skipped the map refresh, and a new program at a freed one's address matched and read the freed program's image table binding (Resident Evil Village PPSA01556 crashed on its atomic flags). The table is now found by its stage, and the image table binding comes from this draw's program, the last ImageTable or ImageStorageTable binding as the build picks it. The build's program and binding pointers are cleared once the build finishes, so no table keeps a pointer into a program it does not own. The test builds a heap set, destroys its program and refreshes the set for an equal-content program, once at another address and once at the destroyed program's address with its freed binding memory overwritten. Without the fix the first leaves the table map unset and the second crashes. Co-authored-by: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- .../Graphics/src/ShaderResources.cpp | 17 +- .../tests/execution/HeapTableStageReuse.cpp | 233 ++++++++++++++++++ 2 files changed, 246 insertions(+), 4 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 1b34c08c6b16..a377b2822d5e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -5498,6 +5498,10 @@ void ShaderResources::finishImageTables() { faults.push_back({IrStage(table.stage), table.program->imageTableShader, table.poison, table.messages}); ranges.insert(ranges.end(), table.program->imageTableRanges.begin(), table.program->imageTableRanges.end()); } + for (auto& table : tableStages) { + table.program = nullptr; + table.images = nullptr; + } if (bda == nullptr) return; bda->SetImageTables(std::move(faults), std::move(ranges)); } @@ -6105,13 +6109,18 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ namespace TableAbi = ShaderRecompiler::ImageTableAbi; heapTableMapSet[stageIndex] = false; const auto table = std::find_if(tableStages.begin(), tableStages.end(), - [&](const TableStage& candidate) { return candidate.program == shader.program && candidate.heap; }); + [&](const TableStage& candidate) { return candidate.stage == shader.stage && candidate.heap; }); if (table == tableStages.end() || table->mapAllocation == noElement) return; + const ShaderRecompiler::DescriptorBinding* images = nullptr; + for (const auto& binding : shader.program->bindings) { + if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable) + images = &binding; + } auto& heap = BindlessHeap::For(context); struct MapStorage {}; auto& map = HostThreadLocal, MapStorage>(); map.assign(table->map.begin(), table->map.end()); - const auto elements = table->images != nullptr ? static_cast(table->images->count) : std::size_t{0}; + const auto elements = images != nullptr ? static_cast(images->count) : std::size_t{0}; const auto base = static_cast(map.size()); map[TableAbi::HeaderElementBase] = base; const auto sampledAbsent = heap.AbsentSlot(Abi::FirstImageBinding, heapPlaceholderView(Abi::FirstImageBinding)); @@ -6156,8 +6165,8 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ map.push_back(*slot); } const auto atomicElement = [&](std::size_t element, bool wide) { - if (table->images == nullptr) return false; - const auto& flags = wide ? table->images->imageAtomic64 : table->images->imageAtomic; + if (images == nullptr) return false; + const auto& flags = wide ? images->imageAtomic64 : images->imageAtomic; return element < flags.size() && flags[element]; }; const auto anyAtomic = [&](bool wide) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp new file mode 100644 index 000000000000..e82efe809341 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp @@ -0,0 +1,233 @@ +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "Recompiler.hpp" +#include "RuntimeAbi.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver { + +struct VulkanDeviceTestAccess { + static Graphics::Context ContextOf(const VulkanDevice& device) { return device.graphicsContext(); } +}; + +} + +namespace { + +using AgcDriver::Graphics::CompiledShader; +using AgcDriver::Graphics::Require; +using AgcDriver::Graphics::ShaderResources; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Lanes = 64; +constexpr std::uint32_t Textures = 4; +constexpr std::uint32_t Stride = 32; +constexpr std::size_t SurfaceBytes = 256; +constexpr std::uint32_t Format8888UNorm = 56; +constexpr std::uint32_t Type2D = 9; +constexpr std::size_t SrtOffset = 4096; +constexpr std::size_t InputOffset = 8192; +constexpr std::size_t OutputOffset = 12288; +constexpr std::size_t HeapOffset = 65536; +constexpr std::size_t BlockBytes = (HeapOffset + std::size_t{Textures} * Stride + 65535u) & ~std::size_t{65535}; +constexpr std::size_t SurfaceBlockBytes = (std::size_t{Textures} * SurfaceBytes + 65535u) & ~std::size_t{65535}; + +constexpr std::array Code{ + 0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, + 0x34080082u, 0x7e200500u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0xbf8cc07fu, + 0xe0301000u, 0x80030504u, 0xf09c0f08u, 0x00450000u, 0xbf8c3f70u, 0x4a000105u, + 0xe0701000u, 0x80070004u, 0xbf810000u, 0u, 0u}; + +class GuestBlock { +public: + GuestBlock(std::size_t bytes, bool gpu) { +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(bytes, 65536)); + if (block != nullptr) GuestArena::GuestArenaCommit_nid_postfix(block, bytes, PAGE_READWRITE, bytes); +#else + constexpr std::uintptr_t alignment = 65536; + void* mapped = mmap(nullptr, bytes + alignment, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (mapped != MAP_FAILED) { + const auto begin = reinterpret_cast(mapped); + const auto aligned = (begin + alignment - 1) & ~(alignment - 1); + if (aligned != begin) munmap(mapped, aligned - begin); + if (aligned + bytes != begin + bytes + alignment) munmap(reinterpret_cast(aligned + bytes), begin + alignment - aligned); + block = reinterpret_cast(aligned); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, bytes); + } +#endif + Require(block != nullptr, "heap table stage reuse: cannot allocate a guest block"); + std::memset(block, 0, bytes); + GuestAllocations::Mutation().Add(block, bytes, true, true, gpu); + AgcDriver::GuestMemory::CollectWritesUncached(reinterpret_cast(block), bytes); + } + + GuestBlock(const GuestBlock&) = delete; + GuestBlock& operator=(const GuestBlock&) = delete; + + std::uint64_t At(std::size_t offset) const { return reinterpret_cast(block + offset); } + std::uint8_t* Bytes(std::size_t offset) const { return block + offset; } + std::uint32_t* Words(std::size_t offset) const { return reinterpret_cast(block + offset); } + +private: + std::uint8_t* block = nullptr; +}; + +std::array BufferDescriptor(std::uint64_t address, std::uint32_t stride, std::uint32_t records) { + return {static_cast(address), static_cast((address >> 32u) & 0xffffu) | (stride << 16u), records, stride == 0u ? 0x31016facu : 0x01016facu}; +} + +void Prepare(const GuestBlock& block, const GuestBlock& surfaces) { + std::memcpy(block.Words(0), Code.data(), sizeof(Code)); + for (std::uint32_t texture = 0; texture < Textures; ++texture) { + const auto offset = static_cast(texture) * SurfaceBytes; + std::memset(surfaces.Bytes(offset), static_cast(texture & 0xffu), SurfaceBytes); + const auto surface = surfaces.At(offset); + const std::array words{static_cast(surface >> 8u), static_cast((surface >> 40u) & 0xffu) | (Format8888UNorm << 20u) | (3u << 30u), 1u | (7u << 14u), 0xfacu | (Type2D << 28u), 0u, 0u, 0u, 0u}; + std::memcpy(block.Words(HeapOffset + static_cast(texture) * Stride), words.data(), sizeof(words)); + } + auto* srt = block.Words(SrtOffset); + const auto heap = BufferDescriptor(block.At(HeapOffset), Stride, Textures); + const auto input = BufferDescriptor(block.At(InputOffset), 0u, Lanes * 4u); + const auto output = BufferDescriptor(block.At(OutputOffset), 0u, Lanes * 4u); + std::copy(heap.begin(), heap.end(), srt); + std::copy(input.begin(), input.end(), srt + 8); + std::copy(output.begin(), output.end(), srt + 12); + AgcDriver::GuestMemory::CollectWritesUncached(block.At(0), BlockBytes); + AgcDriver::GuestMemory::CollectWritesUncached(surfaces.At(0), SurfaceBlockBytes); +} + +ShaderRecompiler::RecompileResult Compile(const AgcDriver::VulkanDevice& device, const GuestBlock& block) { + const auto srt = block.At(SrtOffset); + const std::array userData{static_cast(srt), static_cast(srt >> 32u)}; + const std::span code(block.Words(0), Code.size()); + const std::array memory{{ + {block.At(0), std::as_bytes(code)}, + {srt, std::as_bytes(std::span(block.Words(SrtOffset), 64))}, + {block.At(HeapOffset), std::as_bytes(std::span(block.Words(HeapOffset), static_cast(Textures) * Stride / 4u))}, + }}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Lanes, 1, 1}, 0u, {false, false, false}, false, 1}; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, block.At(0), code, 0, {}}, + {Lanes, 0, userData, compute, std::nullopt, std::nullopt, memory}, + device.ComputeTarget(Lanes), + {0, 0, 0, 128} + }; + return ShaderRecompiler::Recompile(request); +} + +void RequireHeapTable(const ShaderRecompiler::RecompileResult& result) { + const auto has = [&](ShaderRecompiler::DescriptorRole role) { + return std::any_of(result.bindings.begin(), result.bindings.end(), [&](const auto& binding) { return binding.role == role; }); + }; + Require(result.gpuResolvedImages && result.dataAddressPush, "heap table stage reuse: the program is not in the heap's GPU-resolved form"); + Require(has(ShaderRecompiler::DescriptorRole::ImageTable) && has(ShaderRecompiler::DescriptorRole::ImageTableMap), "heap table stage reuse: the program does not bind an image table and its map"); +} + +std::uint32_t TableMapRoot(const ShaderResources& resources, const CompiledShader& shader) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + std::array bytes{}; + resources.PatchDataAddresses(bytes, std::span(&shader, 1), nullptr); + std::uint32_t value = 0; + std::memcpy(&value, bytes.data() + (Abi::RootDword + Abi::RootStageDword(Abi::Stage::Main, Abi::RootStageField::TableMap)) * sizeof(std::uint32_t), sizeof(value)); + return value; +} + +void RefreshAfterOriginalDestroyed(const AgcDriver::VulkanDevice& device, const GuestBlock& block, bool sameAddress) { + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + const char* what = sameAddress ? "an equal-content program at the destroyed program's address" : "an equal-content program at another address"; + std::optional slot; + slot.emplace(Compile(device, block)); + RequireHeapTable(*slot); + const auto* original = &*slot; + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + AgcDriver::Graphics::BindlessHeap::SpanMark lead; + static_cast(AgcDriver::Graphics::BindlessHeap::For(context).Allocate(64, lead)); + const CompiledShader built{ShaderStage::Compute, original, 0}; + auto resources = std::make_shared(context, built); + Require(resources->HeapStage(), "heap table stage reuse: the set was not built on the heap"); + const auto builtMap = TableMapRoot(*resources, built); + Require(builtMap != 0u, "heap table stage reuse: the build left the table map unset"); + const auto bindingBytes = slot->bindings.capacity() * sizeof(ShaderRecompiler::DescriptorBinding); + std::optional other; + std::vector> squatters; + if (sameAddress) { + slot.reset(); + for (int i = 0; i < 16; ++i) { + squatters.push_back(std::make_unique(bindingBytes)); + std::memset(squatters.back().get(), 0xff, bindingBytes); + } + slot.emplace(Compile(device, block)); + Require(&*slot == original, "heap table stage reuse: the reused slot moved"); + } else { + other.emplace(Compile(device, block)); + slot.reset(); + } + const auto& current = sameAddress ? *slot : *other; + RequireHeapTable(current); + const CompiledShader shader{ShaderStage::Compute, ¤t, 0}; + resources->RefreshHeapStage(std::span(&shader, 1)); + const auto refreshed = TableMapRoot(*resources, shader); + Require(refreshed != 0u, std::string("heap table stage reuse: refreshing for ") + what + " left the table map unset"); + Require(refreshed == builtMap, std::string("heap table stage reuse: refreshing for ") + what + " wrote a table map that differs from the build's"); + std::printf("the heap table map refreshed for %s\n", what); +} + +} + +int main() { +#ifdef _WIN32 + _putenv_s("APS5_GPU_HEAP", "1"); + _putenv_s("APS5_VERIFY_GPU_HEAP", "1"); +#else + setenv("APS5_GPU_HEAP", "1", 1); + setenv("APS5_VERIFY_GPU_HEAP", "1", 1); +#endif + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) { + std::cout << "skipped, the device lacks VK_EXT_descriptor_heap, or the maintenance5, slot room and push data the GPU heap needs with it\n"; + return VulkanTestSkipped; + } + GuestBlock block(BlockBytes, true); + GuestBlock surfaces(SurfaceBlockBytes, false); + Prepare(block, surfaces); + RefreshAfterOriginalDestroyed(*device, block, false); + RefreshAfterOriginalDestroyed(*device, block, true); + std::puts("heap table stage reuse tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} From 5f01a66199860d8e66ebec86c270173571d0037e Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 24 Oct 2026 19:21:49 +0530 Subject: [PATCH 037/269] test(agc): give the compute heap sample's variants the Windows libc PATH agc_driver_heap_compute_sample_heap and its pipelined variant could not load libc on Windows (0xc0000135); the draw heap variants already prepend libc's directory to PATH. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index c76c07a80650..6f8c00ac6fe4 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -3141,10 +3141,16 @@ if(BUILD_TESTING) if(TARGET agc_driver_heap_compute_sample_tests) add_test(NAME agc_driver_heap_compute_sample_heap_pipelined COMMAND agc_driver_heap_compute_sample_tests) set_tests_properties(agc_driver_heap_compute_sample_heap_pipelined PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_PIPELINE_DISPATCH=1;APS5_PIPELINED_DRAWS=32" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_heap_compute_sample_heap_pipelined PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() endif() if(TARGET agc_driver_heap_compute_sample_tests) add_test(NAME agc_driver_heap_compute_sample_heap COMMAND agc_driver_heap_compute_sample_tests) set_tests_properties(agc_driver_heap_compute_sample_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_heap_compute_sample_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() endif() if(TARGET agc_driver_pipeline_journal_tests) add_test(NAME agc_driver_pipeline_journal_gpu_heap COMMAND agc_driver_pipeline_journal_tests --gpu-heap) From 3005414edfc088830f0a4350683f1ce690e70c23 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 24 Oct 2026 19:21:49 +0530 Subject: [PATCH 038/269] test(agc): skip the heap compute sample when the requested heap cannot run The sample took its expected mode from DescriptorHeapEnabled(), so with APS5_GPU_HEAP set on a device without the heap it passed by testing the plain path. It now takes the request from APS5_GPU_HEAP and exits 77 with a reason when the heap is requested but unavailable, as the draw sample does; on a capable device the heap assertions stay. Co-Authored-By: Claude Opus 5.5 --- .../libSceAgcDriver/tests/execution/HeapComputeSample.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp index 74676d1af8e0..6629ced8ac89 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp @@ -188,7 +188,12 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; } - const bool heap = AgcDriver::Graphics::DescriptorHeapEnabled(); + const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; + if (heap && !AgcDriver::Graphics::DescriptorHeapEnabled()) { + std::cout + << "skipped, the device lacks VK_EXT_descriptor_heap, or the maintenance5, slot room and push data the GPU heap needs with it, so APS5_GPU_HEAP has no heap to dispatch through\n"; + return VulkanTestSkipped; + } Fill(TextureMemory, Texel); Fill(OtherTextureMemory, OtherTexel); Registered(SampleHeader, SampleCode.data(), sizeof(SampleCode)); From 1607542d6629f697ba5a4875d6720096135bf304 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 24 Oct 2026 21:13:57 +0530 Subject: [PATCH 039/269] fix(agc): keep the heap's swept storage in HostThreadLocal On Windows a module thread_local's destructor runs after emulated TLS has already freed the object (prx_thread_local_destructors). Co-Authored-By: Claude Opus 5.5 --- .../libSceAgcDriver/Graphics/src/BindlessHeap.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 4cbb7a8943e0..8bd9fde37be5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -5,6 +5,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/HostThreadLocal.hpp" #include "RuntimeAbi.hpp" #include "SpirvBackend/SpirvAnalysis.hpp" #include @@ -169,12 +170,16 @@ BindlessHeap::~BindlessHeap() = default; namespace { -thread_local std::vector> sweptStorage; +struct SweptStorageTag {}; + +std::vector>& sweptStorage() { + return HostThreadLocal>, SweptStorageTag>(); +} struct SweptStorageRelease { ~SweptStorageRelease() { - auto released = std::move(sweptStorage); - sweptStorage.clear(); + auto released = std::move(sweptStorage()); + sweptStorage().clear(); } }; @@ -347,7 +352,7 @@ void BindlessHeap::sweepLocked(std::vector>& dropped) { auto& owner = kindOwners[slot]; if (owner.storage != nullptr) { if (owner.storage.use_count() > 1) continue; - sweptStorage.push_back(std::move(owner.storage)); + sweptStorage().push_back(std::move(owner.storage)); } else { const bool heldElsewhere = owner.texture == nullptr || owner.texture.use_count() > static_cast(owner.texture->HeapHolds()); From eb9d6589665ab4d03b5d0b6598f5d57ce5a6e02d Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 25 Oct 2026 01:52:35 +0530 Subject: [PATCH 040/269] fix(agc): share the GPU heap's image slots between binding kinds Every image binding kind had its own range of 4096 heap slots, so a title that keeps more than about 3000 textures of one kind alive refused the heap for good while the other ranges stayed almost empty. Every image binding now maps onto one range of 57 * 4096 slots that the kinds share, the same heap size as before. Slot k stays reserved for kind k's absent descriptor. Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/PresentationPass.cpp | 1 - .../Graphics/include/BindlessHeap.hpp | 26 ++-- .../Graphics/src/BindlessHeap.cpp | 130 ++++++++---------- .../Graphics/src/ShaderResources.cpp | 4 +- .../Graphics/src/TextureDetiler.cpp | 7 +- .../tests/BindlessHeapSlots.cpp | 27 ++-- core/shader/recompiler/RuntimeAbi.hpp | 2 +- core/shader/recompiler/ShaderDiskCache.hpp | 2 +- .../src/SpirvMemory/SpirvDescriptors.cpp | 7 +- docs/dev/ARCHITECTURE.md | 2 +- 10 files changed, 98 insertions(+), 110 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp index 901af9230200..729b4205d1b4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp @@ -259,7 +259,6 @@ const PresentationPass::Target& PresentationPass::target(VkFormat format, VkImag mappings[0].bindingCount = 1; mappings[0].resourceMask = VK_SPIRV_RESOURCE_TYPE_COMBINED_SAMPLED_IMAGE_BIT_EXT; mappings[0].source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; - mappings[0].sourceData.pushIndex.heapOffset = static_cast(bindless.ImageHeapOffset(PresentHeapKind)); mappings[0].sourceData.pushIndex.pushOffset = offsetof(HeapPush, slot); mappings[0].sourceData.pushIndex.heapIndexStride = static_cast(bindless.ImageHeapStride()); mappings[0].sourceData.pushIndex.heapArrayStride = static_cast(bindless.ImageHeapStride()); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 63fe11727f81..4742501af41c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace AgcDriver::Graphics { @@ -33,7 +34,6 @@ class BindlessHeap { static bool Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties); bool DescriptorHeapMode() const { return resourceHeap != nullptr; } - VkDeviceSize ImageHeapOffset(std::uint32_t kind) const; VkDeviceSize ImageHeapStride() const { return imageHeapStride; } VkDeviceSize SamplerHeapStride() const { return samplerHeapStride; } void BindDescriptorHeaps(VkCommandBuffer commands) const; @@ -49,7 +49,7 @@ class BindlessHeap { std::optional StorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view); std::optional ViewSlot(std::uint32_t kind, const void* owner, VkImageView view); void ReleaseViewSlots(const void* owner); - std::uint32_t SlotGeneration(std::uint32_t kind, std::uint32_t slot) const; + std::uint32_t SlotGeneration(std::uint32_t slot) const; const Texture* SlotTexture(std::uint32_t kind, std::uint32_t slot) const; std::optional SamplerSlot(const std::shared_ptr& sampler); std::uint32_t SamplerGeneration(std::uint32_t slot) const; @@ -127,34 +127,34 @@ class BindlessHeap { } }; std::unordered_map textureSlots; - std::unordered_map>> viewSlots; - std::vector nextTextureSlot; + std::unordered_map> viewSlots; + std::uint32_t nextTextureSlot = 0; struct SlotOwner { std::shared_ptr texture; std::shared_ptr storage; TextureKey key{}; std::uint32_t generation = 0; }; - std::vector> owners; - std::vector> freeSlots; + std::vector owners; + std::vector freeSlots; std::uint32_t slotCap = 0; std::uint64_t slotRequests = 0; void sweepLocked(std::vector>& dropped); - std::optional takeSlotLocked(std::uint32_t kind); - std::optional takeOrSweepLocked(std::uint32_t kind, std::vector>& dropped); + std::optional takeSlotLocked(); + std::optional takeOrSweepLocked(std::vector>& dropped); SlotOwner& claimSlotLocked(const TextureKey& key, std::uint32_t slot); - void freeSlotLocked(std::uint32_t kind, std::uint32_t slot); - const SlotOwner* ownerLocked(std::uint32_t kind, std::uint32_t slot) const; + void freeSlotLocked(std::uint32_t slot); + const SlotOwner* ownerLocked(std::uint32_t slot) const; std::unordered_map samplerSlots; - std::unordered_map absentSlots; + std::unordered_set absentSlots; std::vector> heldSamplers; std::vector samplerGenerations; std::vector freeSamplerSlots; void sweepSamplersLocked(std::vector>& dropped); - void noteTakenLocked(std::uint32_t kind, std::vector>& dropped); + void noteTakenLocked(std::vector>& dropped); void noteSamplerTakenLocked(std::vector>& dropped); std::uint32_t imageMargin() const; - std::size_t unusedLocked(std::uint32_t kind) const; + std::size_t unusedLocked() const; bool roomLocked() const; Counts counts; }; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 8bd9fde37be5..518739fdde4e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -108,11 +108,10 @@ VkDeviceSize alignUp(VkDeviceSize value, VkDeviceSize alignment) { } HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { - constexpr auto imageKinds = static_cast(BindlessHeap::SamplerKind); HeapSizes sizes; sizes.imageStride = alignUp(properties.imageDescriptorSize, properties.imageDescriptorAlignment); sizes.samplerStride = alignUp(properties.samplerDescriptorSize, properties.samplerDescriptorAlignment); - const auto imageBytes = imageKinds * Abi::GpuImageHeapSlots * sizes.imageStride; + const auto imageBytes = static_cast(Abi::GpuImageHeapSlots) * sizes.imageStride; sizes.pixelLdsOffset = alignUp(imageBytes, properties.bufferDescriptorAlignment); sizes.resourceUsed = alignUp(sizes.pixelLdsOffset + properties.bufferDescriptorSize, properties.resourceHeapAlignment); sizes.samplerUsed = alignUp(static_cast(Abi::GpuSamplerHeapSlots) * sizes.samplerStride, properties.samplerHeapAlignment); @@ -155,14 +154,12 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { ring = std::make_unique(context, RingBytes, ringUsage); } ringAlignment = static_cast(std::max(context.limits.minStorageBufferOffsetAlignment, 16)); - nextTextureSlot.assign(static_cast(Abi::Binding::Samplers), 0u); ringChunks.resize(RingBytes / RingChunkBytes); - owners.resize(static_cast(Abi::Binding::Samplers)); - freeSlots.resize(static_cast(Abi::Binding::Samplers)); + nextTextureSlot = SamplerKind; slotCap = Abi::GpuImageHeapSlots; if (const char* cap = std::getenv("APS5_HEAP_SLOT_CAP")) { const auto requested = static_cast(std::strtoul(cap, nullptr, 10)); - if (requested != 0u) slotCap = std::min(requested, Abi::GpuImageHeapSlots); + if (requested != 0u) slotCap = SamplerKind + std::min(requested, Abi::GpuImageHeapSlots - SamplerKind); } } @@ -247,13 +244,13 @@ std::optional BindlessHeap::TextureSlot(std::uint32_t kind, const const TextureKey key{kind, texture.get(), view, layout}; if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; if (++slotRequests % 1024u == 0u) NoteSweepDue(); - const auto slot = takeOrSweepLocked(kind, dropped); + const auto slot = takeOrSweepLocked(dropped); if (!slot) return std::nullopt; writeImageSlot(kind, *slot, view, layout); auto& owner = claimSlotLocked(key, *slot); owner.texture = texture; texture->AddHeapHold(); - noteTakenLocked(kind, dropped); + noteTakenLocked(dropped); return slot; } @@ -266,7 +263,7 @@ std::optional BindlessHeap::StorageSlot(std::uint32_t kind, std:: const TextureKey key{kind, owner.get(), view, VK_IMAGE_LAYOUT_GENERAL}; if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; if (++slotRequests % 1024u == 0u) NoteSweepDue(); - const auto slot = takeOrSweepLocked(kind, dropped); + const auto slot = takeOrSweepLocked(dropped); if (!slot) return std::nullopt; writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); claimSlotLocked(key, *slot).storage = std::move(owner); @@ -281,11 +278,11 @@ std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const vo std::lock_guard lock(mutex); const TextureKey key{kind, owner, view, VK_IMAGE_LAYOUT_GENERAL}; if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; - const auto slot = takeOrSweepLocked(kind, dropped); + const auto slot = takeOrSweepLocked(dropped); if (!slot) return std::nullopt; writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); claimSlotLocked(key, *slot); - viewSlots[owner].emplace_back(kind, *slot); + viewSlots[owner].push_back(*slot); return slot; } @@ -293,16 +290,16 @@ void BindlessHeap::ReleaseViewSlots(const void* owner) { std::lock_guard lock(mutex); const auto found = viewSlots.find(owner); if (found == viewSlots.end()) return; - for (const auto& [kind, slot] : found->second) freeSlotLocked(kind, slot); + for (const auto slot : found->second) freeSlotLocked(slot); slotSerial.fetch_add(1, std::memory_order_release); viewSlots.erase(found); } -std::optional BindlessHeap::takeOrSweepLocked(std::uint32_t kind, std::vector>& dropped) { - auto slot = takeSlotLocked(kind); +std::optional BindlessHeap::takeOrSweepLocked(std::vector>& dropped) { + auto slot = takeSlotLocked(); if (!slot) { sweepLocked(dropped); - slot = takeSlotLocked(kind); + slot = takeSlotLocked(); } if (!slot) ++counts.full; return slot; @@ -310,58 +307,52 @@ std::optional BindlessHeap::takeOrSweepLocked(std::uint32_t kind, BindlessHeap::SlotOwner& BindlessHeap::claimSlotLocked(const TextureKey& key, std::uint32_t slot) { textureSlots.emplace(key, slot); - auto& kindOwners = owners[key.kind]; - if (kindOwners.size() <= slot) kindOwners.resize(slot + 1u); - kindOwners[slot].key = key; + if (owners.size() <= slot) owners.resize(slot + 1u); + owners[slot].key = key; ++counts.textures; - return kindOwners[slot]; + return owners[slot]; } -void BindlessHeap::freeSlotLocked(std::uint32_t kind, std::uint32_t slot) { - auto& owner = owners[kind][slot]; +void BindlessHeap::freeSlotLocked(std::uint32_t slot) { + auto& owner = owners[slot]; textureSlots.erase(owner.key); owner.key = {}; ++owner.generation; - freeSlots[kind].push_back(slot); + freeSlots.push_back(slot); ++counts.slotsFreed; } -const BindlessHeap::SlotOwner* BindlessHeap::ownerLocked(std::uint32_t kind, std::uint32_t slot) const { - return kind < owners.size() && slot < owners[kind].size() ? &owners[kind][slot] : nullptr; +const BindlessHeap::SlotOwner* BindlessHeap::ownerLocked(std::uint32_t slot) const { + return slot < owners.size() ? &owners[slot] : nullptr; } -std::optional BindlessHeap::takeSlotLocked(std::uint32_t kind) { - auto& free = freeSlots[kind]; - if (!free.empty()) { - const auto slot = free.back(); - free.pop_back(); +std::optional BindlessHeap::takeSlotLocked() { + if (!freeSlots.empty()) { + const auto slot = freeSlots.back(); + freeSlots.pop_back(); ++counts.slotsReused; return slot; } - auto& next = nextTextureSlot[kind]; - if (next >= slotCap) return std::nullopt; - return next++; + if (nextTextureSlot >= slotCap) return std::nullopt; + return nextTextureSlot++; } void BindlessHeap::sweepLocked(std::vector>& dropped) { ++counts.sweeps; const auto firstDropped = dropped.size(); - for (std::uint32_t kind = 0; kind < owners.size(); ++kind) { - auto& kindOwners = owners[kind]; - for (std::uint32_t slot = 0; slot < kindOwners.size(); ++slot) { - auto& owner = kindOwners[slot]; - if (owner.storage != nullptr) { - if (owner.storage.use_count() > 1) continue; - sweptStorage().push_back(std::move(owner.storage)); - } else { - const bool heldElsewhere = - owner.texture == nullptr || owner.texture.use_count() > static_cast(owner.texture->HeapHolds()); - if (heldElsewhere) continue; - dropped.push_back(std::move(owner.texture)); - } - freeSlotLocked(kind, slot); - slotSerial.fetch_add(1, std::memory_order_release); + for (std::uint32_t slot = SamplerKind; slot < owners.size(); ++slot) { + auto& owner = owners[slot]; + if (owner.storage != nullptr) { + if (owner.storage.use_count() > 1) continue; + sweptStorage().push_back(std::move(owner.storage)); + } else { + const bool heldElsewhere = + owner.texture == nullptr || owner.texture.use_count() > static_cast(owner.texture->HeapHolds()); + if (heldElsewhere) continue; + dropped.push_back(std::move(owner.texture)); } + freeSlotLocked(slot); + slotSerial.fetch_add(1, std::memory_order_release); } for (auto index = firstDropped; index < dropped.size(); ++index) dropped[index]->DropHeapHold(); } @@ -425,27 +416,24 @@ void BindlessHeap::SweepIfDue() { } std::uint32_t BindlessHeap::imageMargin() const { - return std::max(1u, std::min(ImageSlotMargin, slotCap / 4u)); + return std::max(1u, std::min(ImageSlotMargin, (slotCap - SamplerKind) / 4u)); } -std::size_t BindlessHeap::unusedLocked(std::uint32_t kind) const { - const auto next = nextTextureSlot[kind]; - return (next < slotCap ? slotCap - next : 0u) + freeSlots[kind].size(); +std::size_t BindlessHeap::unusedLocked() const { + return (nextTextureSlot < slotCap ? slotCap - nextTextureSlot : 0u) + freeSlots.size(); } bool BindlessHeap::roomLocked() const { - for (std::uint32_t kind = Abi::FirstImageBinding; kind < Abi::FirstStorageImageBinding; ++kind) { - if (unusedLocked(kind) < 2u * static_cast(imageMargin())) return false; - } + if (unusedLocked() < 2u * static_cast(imageMargin())) return false; return Abi::GpuSamplerHeapSlots - heldSamplers.size() + freeSamplerSlots.size() >= 2u * SamplerSlotMargin; } -void BindlessHeap::noteTakenLocked(std::uint32_t kind, std::vector>& dropped) { +void BindlessHeap::noteTakenLocked(std::vector>& dropped) { if (nearlyFull.load(std::memory_order_relaxed)) return; const auto margin = imageMargin(); - if (unusedLocked(kind) >= margin) return; + if (unusedLocked() >= margin) return; sweepLocked(dropped); - if (unusedLocked(kind) < margin) noteNearlyFull("image", margin); + if (unusedLocked() < margin) noteNearlyFull("image", margin); } void BindlessHeap::noteSamplerTakenLocked(std::vector>& dropped) { @@ -468,7 +456,7 @@ bool BindlessHeap::GenerationsCurrent(std::span std::size_t generation = 0; for (std::uint32_t kind = 0; kind < slots.size(); ++kind) { for (const auto slot : slots[kind]) { - const auto* owner = ownerLocked(kind, slot); + const auto* owner = ownerLocked(slot); const auto current = owner != nullptr ? owner->generation : 0u; if (generation >= slotGenerations.size() || current != slotGenerations[generation++]) return false; } @@ -482,27 +470,25 @@ bool BindlessHeap::GenerationsCurrent(std::span return true; } -std::uint32_t BindlessHeap::SlotGeneration(std::uint32_t kind, std::uint32_t slot) const { +std::uint32_t BindlessHeap::SlotGeneration(std::uint32_t slot) const { std::lock_guard lock(mutex); - const auto* owner = ownerLocked(kind, slot); + const auto* owner = ownerLocked(slot); return owner != nullptr ? owner->generation : 0u; } const Texture* BindlessHeap::SlotTexture(std::uint32_t kind, std::uint32_t slot) const { std::lock_guard lock(mutex); - const auto* owner = ownerLocked(kind, slot); - return owner != nullptr ? owner->texture.get() : nullptr; + const auto* owner = ownerLocked(slot); + return owner != nullptr && owner->key.kind == kind ? owner->texture.get() : nullptr; } std::uint32_t BindlessHeap::AbsentSlot(std::uint32_t kind, VkImageView view) { if (kind < Abi::FirstImageBinding || kind >= SamplerKind) throw std::runtime_error("AGC bindless heap: invalid absent slot request"); std::lock_guard lock(mutex); - if (const auto found = absentSlots.find(kind); found != absentSlots.end()) return found->second; - const auto slot = takeSlotLocked(kind); - if (!slot) throw std::runtime_error("AGC bindless heap: the image heap is full"); - writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); - absentSlots.emplace(kind, *slot); - return *slot; + if (absentSlots.contains(kind)) return kind; + writeImageSlot(kind, kind, view, VK_IMAGE_LAYOUT_GENERAL); + absentSlots.insert(kind); + return kind; } std::optional BindlessHeap::SamplerSlot(const std::shared_ptr& sampler) { @@ -606,10 +592,6 @@ void BindlessHeap::enterChunk(std::vector& chunks, std::size_t index, std ++chunk.entries; } -VkDeviceSize BindlessHeap::ImageHeapOffset(std::uint32_t kind) const { - return static_cast(kind) * Abi::GpuImageHeapSlots * imageHeapStride; -} - void BindlessHeap::writeSamplerSlot(std::uint32_t slot, VkSampler sampler) { auto record = FindSampler(sampler); Require(record.has_value(), "a GPU heap sampler has no recorded create info"); @@ -621,7 +603,7 @@ void BindlessHeap::writeSamplerSlot(std::uint32_t slot, VkSampler sampler) { } void BindlessHeap::writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImageView view, VkImageLayout layout) { - const auto offset = ImageHeapOffset(kind) + static_cast(slot) * imageHeapStride; + const auto offset = static_cast(slot) * imageHeapStride; Require(offset + imageHeapStride <= resourceHeapUsed, "a GPU heap image slot lies outside the resource heap"); auto* target = resourceHeap->Bytes().data() + offset; if (view == VK_NULL_HANDLE) { @@ -788,7 +770,7 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, if (kind == SamplerKind) mappings.push_back( heapMapping(Abi::FragmentDescriptorSet, binding, VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT, 0, samplerHeapStride)); - else mappings.push_back(heapMapping(Abi::FragmentDescriptorSet, binding, imageResources, ImageHeapOffset(kind), imageHeapStride)); + else mappings.push_back(heapMapping(Abi::FragmentDescriptorSet, binding, imageResources, 0, imageHeapStride)); } if (use.workgroupMemory) mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset)); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index a377b2822d5e..968954c383a9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6264,7 +6264,7 @@ bool ShaderResources::heapSlotsCurrent(const BindlessHeap& heap, const HeapStage std::size_t generation = 0; for (std::uint32_t kind = 0; kind < state.slots.size(); ++kind) { for (const auto slot : state.slots[kind]) { - if (generation >= state.slotGenerations.size() || heap.SlotGeneration(kind, slot) != state.slotGenerations[generation++]) + if (generation >= state.slotGenerations.size() || heap.SlotGeneration(slot) != state.slotGenerations[generation++]) return false; } } @@ -6328,7 +6328,7 @@ void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, V void ShaderResources::noteHeapSlotGenerations(const BindlessHeap& heap, HeapStageState& state) { state.slotGenerations.clear(); for (std::uint32_t kind = 0; kind < state.slots.size(); ++kind) { - for (const auto slot : state.slots[kind]) state.slotGenerations.push_back(heap.SlotGeneration(kind, slot)); + for (const auto slot : state.slots[kind]) state.slotGenerations.push_back(heap.SlotGeneration(slot)); } state.samplerGenerations.clear(); for (const auto slot : state.samplerSlots) state.samplerGenerations.push_back(heap.SamplerGeneration(slot)); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index b2b7c740eb5c..f482d540e05b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -86,14 +86,13 @@ VkDescriptorSetAndBindingMappingEXT PushAddressMapping(std::uint32_t binding, st return mapping; } -VkDescriptorSetAndBindingMappingEXT PushIndexMapping(const BindlessHeap& heap, std::uint32_t binding, std::uint32_t kind, std::uint32_t offset) { +VkDescriptorSetAndBindingMappingEXT PushIndexMapping(const BindlessHeap& heap, std::uint32_t binding, std::uint32_t offset) { VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; mapping.descriptorSet = 0; mapping.firstBinding = binding; mapping.bindingCount = 1; mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; - mapping.sourceData.pushIndex.heapOffset = static_cast(heap.ImageHeapOffset(kind)); mapping.sourceData.pushIndex.pushOffset = offset; mapping.sourceData.pushIndex.heapIndexStride = static_cast(heap.ImageHeapStride()); mapping.sourceData.pushIndex.heapArrayStride = static_cast(heap.ImageHeapStride()); @@ -284,7 +283,7 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem Require(image && !addressed, "only the image detiler runs on the descriptor heap"); const auto& bindless = BindlessHeap::For(context); mappings[0] = PushAddressMapping(0, offsetof(HeapImagePush, tiled)); - mappings[1] = PushIndexMapping(bindless, 1, DetileHeapKind, offsetof(HeapImagePush, slot)); + mappings[1] = PushIndexMapping(bindless, 1, offsetof(HeapImagePush, slot)); mappingInfo.mappingCount = static_cast(mappings.size()); mappingInfo.pMappings = mappings.data(); createInfo.stage.pNext = &mappingInfo; @@ -497,7 +496,7 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask } if (created == VK_SUCCESS && addressedPipelineLayout != VK_NULL_HANDLE && DescriptorHeapEnabled() && BindlessHeap::For(context).DescriptorHeapMode()) { const auto& bindless = BindlessHeap::For(context); - const std::array mappings{PushAddressMapping(0, offsetof(HeapCmaskPush, cmask)), PushAddressMapping(1, offsetof(HeapCmaskPush, errors)), PushIndexMapping(bindless, 2, DetileHeapKind, offsetof(HeapCmaskPush, slot))}; + const std::array mappings{PushAddressMapping(0, offsetof(HeapCmaskPush, cmask)), PushAddressMapping(1, offsetof(HeapCmaskPush, errors)), PushIndexMapping(bindless, 2, offsetof(HeapCmaskPush, slot))}; VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; mappingInfo.mappingCount = static_cast(mappings.size()); mappingInfo.pMappings = mappings.data(); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 1c55a37fb6ec..212e14dc28e2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -38,30 +38,33 @@ void textureSlots(const Context& context, VkImageView view) { const auto slot = heap.TextureSlot(kind, first, view, VK_IMAGE_LAYOUT_GENERAL); require(slot.has_value(), "the first texture takes a slot"); require(heap.SlotTexture(kind, *slot) == first.get(), "the slot holds the first texture"); - const auto generation = heap.SlotGeneration(kind, *slot); + const auto generation = heap.SlotGeneration(*slot); auto second = fakeTexture(1); require(!heap.TextureSlot(kind, second, view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a held slot is not reused"); first.reset(); const auto reused = heap.TextureSlot(kind, second, view, VK_IMAGE_LAYOUT_GENERAL); require(reused.has_value() && *reused == *slot, "the released texture's slot is reused"); - require(heap.SlotGeneration(kind, *slot) != generation, "a freed slot moves its generation"); + require(heap.SlotGeneration(*slot) != generation, "a freed slot moves its generation"); require(heap.SlotTexture(kind, *slot) == second.get(), "the reused slot holds the second texture"); const auto counts = heap.Statistics(); require(counts.slotsFreed == 1u && counts.slotsReused == 1u, "one slot freed and reused"); auto shared = fakeTexture(2); const auto otherKind = kind + 1u; - const auto firstShared = heap.TextureSlot(kind, shared, view, VK_IMAGE_LAYOUT_GENERAL); - require(!firstShared.has_value(), "the capped kind has no slot left for a third texture"); - const auto sharedSlot = heap.TextureSlot(otherKind, shared, view, VK_IMAGE_LAYOUT_GENERAL); - require(sharedSlot.has_value() && shared->HeapHolds() == 1u, "a texture placed by the heap counts one heap hold"); + require(!heap.TextureSlot(otherKind, shared, view, VK_IMAGE_LAYOUT_GENERAL).has_value(), + "another kind finds the capped heap's only slot held"); second.reset(); + const auto sharedSlot = heap.TextureSlot(otherKind, shared, view, VK_IMAGE_LAYOUT_GENERAL); + require(sharedSlot.has_value() && *sharedSlot == *slot, "another kind takes the slot the first kind's texture left"); + require(shared->HeapHolds() == 1u, "a texture placed by the heap counts one heap hold"); + require(heap.SlotTexture(kind, *slot) == nullptr && heap.SlotTexture(otherKind, *slot) == shared.get(), + "the slot holds the other kind's texture"); shared.reset(); const auto freedBefore = heap.Statistics().slotsFreed; auto third = fakeTexture(0); require(heap.TextureSlot(kind, third, view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture held only by the heap is swept"); - require(heap.Statistics().slotsFreed == freedBefore + 2u, "one sweep frees every slot whose texture only the heap holds"); + require(heap.Statistics().slotsFreed == freedBefore + 1u, "the sweep frees the slot whose texture only the heap holds"); } void samplerSlots(const Context& context) { @@ -89,10 +92,10 @@ void viewSlots(const Context& context, VkImageView view) { const int first = 0, second = 0; const auto slot = heap.ViewSlot(kind, &first, view); require(slot.has_value() && heap.ViewSlot(kind, &first, view) == slot, "a view keeps its slot"); - require(!heap.ViewSlot(kind, &second, view).has_value(), "a full kind refuses another owner's view"); - const auto generation = heap.SlotGeneration(kind, *slot); + require(!heap.ViewSlot(kind, &second, view).has_value(), "a full heap refuses another owner's view"); + const auto generation = heap.SlotGeneration(*slot); heap.ReleaseViewSlots(&first); - require(heap.SlotGeneration(kind, *slot) != generation, "a released view slot moves its generation"); + require(heap.SlotGeneration(*slot) != generation, "a released view slot moves its generation"); require(heap.ViewSlot(kind, &second, view) == slot, "a released view slot is reused"); heap.ReleaseViewSlots(&second); } @@ -108,9 +111,9 @@ void sweptOwnerReentry(const Context& context, VkImageView view) { delete static_cast(pointer); }); }; - require(heap.StorageSlot(kind, owner(), view).has_value(), "the first storage owner takes the kind's only slot"); + require(heap.StorageSlot(kind, owner(), view).has_value(), "the first storage owner takes the heap's only slot"); require(heap.StorageSlot(kind, owner(), view).has_value() && released == 1, - "a full kind sweeps an owner whose release calls back into the heap"); + "a full heap sweeps an owner whose release calls back into the heap"); BindlessHeap::NoteSweepDue(); BindlessHeap::SweepIfDue(); require(released == 2, "a due sweep releases an owner that calls back into the heap"); diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index ff0ced78a505..08794791fced 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -49,7 +49,7 @@ inline constexpr std::uint32_t BindlessTableSlots = 16u; inline constexpr std::uint32_t StorageMipSlots = 16u; inline constexpr std::uint32_t StorageHeapCapacity = 64u; inline constexpr std::uint32_t SamplerHeapCapacity = 64u; -inline constexpr std::uint32_t GpuImageHeapSlots = 4096u; +inline constexpr std::uint32_t GpuImageHeapSlots = static_cast(Binding::Samplers) * 4096u; inline constexpr std::uint32_t GpuSamplerHeapSlots = 2048u; inline constexpr std::uint32_t GpuDataSet = 2u; inline constexpr std::uint32_t GpuGdsSet = 4u; diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index 8eba383469b2..af6bba7ff747 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -13,7 +13,7 @@ namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 48; +inline constexpr std::uint32_t FormatVersion = 49; enum class LoadStatus { Loaded, diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp index 7ccb74b08e7e..29e2be72d652 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp @@ -92,7 +92,12 @@ std::uint32_t tableHeapSlot(SpirvEmitterState& state, std::uint32_t part, std::u const auto count = tableMapWord(state, ConstantU32(state, ImageTableAbi::HeaderElementCount)); const auto partBase = part == 0u ? base : Binary(state, spv::OpIAdd, u32, base, Binary(state, spv::OpIMul, u32, count, ConstantU32(state, part))); const auto slot = tableMapWord(state, Binary(state, spv::OpIAdd, u32, partBase, element)); - const auto clamped = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), slot, ConstantU32(state, slots)), slot, ConstantU32(state, 0u)); + const auto fallback = part == 0u ? RuntimeAbi::FirstImageBinding + : part == 1u ? RuntimeAbi::FirstStorageImageBinding + : part == 3u ? RuntimeAbi::FirstAtomicImageBinding + : part == 4u ? RuntimeAbi::FirstAtomic64ImageBinding + : 0u; + const auto clamped = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), slot, ConstantU32(state, slots)), slot, ConstantU32(state, fallback)); DecorateTableNonUniform(state, clamped); return clamped; } diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index d66c2da8b2e6..8a07e122c260 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -131,7 +131,7 @@ flowchart LR - Queue 0's packet worker decodes, captures and prepares a draw and hands its recording (`Graphics::Draw` under the GPU lock) to a committer thread in [`DrawPipeline.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp), so the next packet is decoded while the previous draw is recorded. Each queued item carries the guest ranges it will write (`DrawWriteRanges`: written buffers and storage images, color targets with their DCC and CMASK, depth and stencil). A later packet that reads or writes one of those ranges, or that the pipeline can't order, drains it first; labels, submission ends, buffer fills and (with `APS5_PIPELINE_DMA=1`) DMA packets are queued as items instead. With `APS5_PIPELINE_DISPATCH=1` (off by default), a `DISPATCH_DIRECT` whose dispatch-cache entry hits with a recipe is queued as an item too, carrying the dispatch's written buffers and storage images (`DispatchWriteRanges`); the capture and the cache lookup stay on the worker and the recipe is recorded on the committer. A dispatch still drains when its lookup misses, when what it reads overlaps a write still pending, when the hit is verified against data or when its writes cannot be ranged (bindless access, GDS, fault buffer). An indirect draw resolved on the CPU (its records read by the worker) drains only when its records or its count overlap a queued write; the records it draws inline drain first, and its last drawn record is queued like a direct draw (`APS5_NO_PIPELINED_INDIRECT=1` drains at every indirect draw). An exception thrown by a commit is rethrown on the worker at its next enqueue or drain, as an inline draw error would be. On by default; `APS5_PIPELINED_DRAWS=0` records every draw inline, and `APS5_EXACT_DRAW_WRITES=0` widens the color and depth ranges to estimates. - A dispatch's resource build runs stage A (binding plan, buffers, descriptor set) without the GPU lock and stage B (image lookups) under it. Between them `VulkanDevice::presync` waits, still without the lock, for recorded work that writes a surface stage B would read on the CPU and for recorded work that writes the DCC keys of an image the dispatch binds (`ShaderResources::PresyncSurfaces`), so the locked `WaitForKeyWriters` finds nothing pending to synchronize with. A key range is waited for only when recorded work writes it, the key-store memo does not give its value (`DccKeyWritersPending`, without the mutex) and the pending stores do not give it either (`DccKeyWriterNeedsSync`, under the mutex, the same test `WaitForKeyWriters` makes before it synchronizes). Stage A's own key scan runs before that wait, and stage B compares it with the keys it reads under the lock as before. `APS5_NO_DCC_PRESYNC=1` leaves the key ranges out; `APS5_NO_PRESYNC=1` disables the whole pre-sync. - `APS5_DRAW_PIPELINE=1` (off by default, meant with `APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1`) takes more of a draw off the worker. A `DrawFinisher` thread runs the second half of a direct pipelined draw (stage materialization, the draw cache insert and the hand-off to the committer) while the worker reads the next packets; the worker drains it before the next draw's cache lookup, before packets other than register writes and draws, and before guest reads, and finishes in place a draw whose stages may write memory (`ProgramWritesMemory`) or write through the BDA page table. The committer skips the fragment-output validation and storage-image layer scans whose inputs match its last commit (`CommitTrims`), and a resource or storage image proved current keeps its proof for the rest of the collect epoch until `GuestMemory::BreakProofs` (a CPU write, a write-back, a recorded write) moves `ProofSerial`. Color metadata passes go through the pipeline with their write ranges (`PipelinedColorMetadataPassWrites`) instead of draining it. A data-only hit whose shape entry belongs to an older draw replaces that entry in place at the second sight of the same read user words. On Linux the main image's pages get a page table entry, and capture pages are pooled across threads. `APS5_VERIFY_DRAW_PIPELINE=1` runs a full check next to 1 in 64 reused proofs and prints `[epoch-proofs]` counts. -- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 4096 image slots per binding kind and 2048 sampler slots, per-draw shader data and flattened SRT in a ring the shaders reach by address) instead of per-draw descriptor sets. Without the extension, or when the device's heaps cannot hold those slots, every stage takes the per-draw path. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; a stage stays GPU-mode only if its compiled module maps onto the heap and every stage of its draw is GPU-mode too; otherwise it is rebuilt on the per-draw path. A draw whose stages come out mixed is rebuilt once with what the first pass learned, and a stage pair that is still mixed takes the per-draw path from then on. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the heap ring and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap is recompiled on the per-dispatch path. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the heap ring per draw with its address in two more pushed dwords. Tables with image atomics index the heap too. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers by device address (`addressedBuffers`: four shader data words per buffer, 64-bit address and byte size, after the slot words) instead of storage buffer descriptors; a draw whose buffers are snapshotted gets its own copy of the words with the snapshot addresses. +- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 233472 image slots that every image binding kind shares, the first 57 holding each kind's absent descriptor, and 2048 sampler slots, per-draw shader data and flattened SRT in a ring the shaders reach by address) instead of per-draw descriptor sets. Without the extension, or when the device's heaps cannot hold those slots, every stage takes the per-draw path. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; a stage stays GPU-mode only if its compiled module maps onto the heap and every stage of its draw is GPU-mode too; otherwise it is rebuilt on the per-draw path. A draw whose stages come out mixed is rebuilt once with what the first pass learned, and a stage pair that is still mixed takes the per-draw path from then on. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the heap ring and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap is recompiled on the per-dispatch path. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the heap ring per draw with its address in two more pushed dwords. Tables with image atomics index the heap too. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers by device address (`addressedBuffers`: four shader data words per buffer, 64-bit address and byte size, after the slot words) instead of storage buffer descriptors; a draw whose buffers are snapshotted gets its own copy of the words with the snapshot addresses. - The shader registry maps a code address to every header registered for that code, in registration order. Static, graphics and rectangle ABI resolution pick the header at the bound address (or one equal to it, `SameHeader`, which also takes a hull header fused by `sceAgcFuseShaderHalves` (type 3) as the registered back half (type 7) it copies, the fused registers aside; graphics ABI resolution then uses the fused header's shader registers); draws and dispatches pick the program by the stage's binary type (`RegisteredProgram`), and a front entry matching both type 2 and type 4 throws. Within a type the last registration wins; re-registering an identical earlier header makes its snapshot current again without preparing it again, and changed code drops the older headers. - The snapshot is published as pending. `SourceHandleFor`, `InvocationFor` and `ShaderPreparationTransaction::Edit` / `Read` wait for the pending job before reading `PreparedShaders`, and rethrow its failure. `APS5_SYNC_SHADER_PREPARE=1` prepares on the registering thread instead. - `APS5_LAZY_SHADER_PREPARE=1` retains registration validation and decoding but discards the temporary plan without queueing preparation. The snapshot is deferred, not pending; draws and dispatches prepare and cache it on first use. A compute or pixel stage's explicit ABI resolution (`ResolveShaderAbi`) plans the stage with the ABI's state, records the ABI and leaves its preparation to the shader's first use, which prepares it with that state (`PreparedShaders::deferredAbis`), so a shader that never draws or dispatches stays unprepared; a graphics-stage ABI is still prepared when it is resolved. This opt-in mode takes precedence over synchronous registration preparation and trades background CPU/memory use for possible first-use stalls; disk caches and shader output are unchanged. From 5645b5be5b6c98026ca5d2e43b1da20046f3c134 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 25 Oct 2026 03:12:42 +0530 Subject: [PATCH 041/269] fix(agc): refuse the GPU heap when storage and view slots fill the shared pool StorageSlot and ViewSlot take their slots from the pool TextureSlot uses but never checked the margin, so retained storage or view owners could fill it while the heap stayed taken and the next heap draw found no slot. Every slot consumer now checks the margin before it claims its slot. A refused heap sweeps again every 64 presents and after released views, so it comes back once the owners are gone even when nothing else asks for a sweep. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 8 +++ .../Graphics/src/BindlessHeap.cpp | 10 ++- .../tests/BindlessHeapSlots.cpp | 66 ++++++++++++++++++- docs/dev/ENVIRONMENT.md | 2 +- 4 files changed, 81 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 6f8c00ac6fe4..ca547d4f17e1 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -3120,6 +3120,14 @@ if(BUILD_TESTING) if(WIN32) set_tests_properties(agc_driver_heap_slots_comes_back PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + foreach(agcHeapSlotsMode IN ITEMS storage-comes-back mixed-comes-back views-come-back) + string(REPLACE "-" "_" agcHeapSlotsName "${agcHeapSlotsMode}") + add_test(NAME agc_driver_heap_slots_${agcHeapSlotsName} COMMAND agc_driver_heap_slots_tests ${agcHeapSlotsMode}) + set_tests_properties(agc_driver_heap_slots_${agcHeapSlotsName} PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_heap_slots_${agcHeapSlotsName} PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() + endforeach() if(TARGET agc_driver_heap_draw_sample_tests) add_test(NAME agc_driver_heap_draw_sample_full_heap COMMAND agc_driver_heap_draw_sample_tests) set_tests_properties(agc_driver_heap_draw_sample_full_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_HEAP_SLOT_CAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 518739fdde4e..874c49deb976 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -265,6 +265,7 @@ std::optional BindlessHeap::StorageSlot(std::uint32_t kind, std:: if (++slotRequests % 1024u == 0u) NoteSweepDue(); const auto slot = takeOrSweepLocked(dropped); if (!slot) return std::nullopt; + noteTakenLocked(dropped); writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); claimSlotLocked(key, *slot).storage = std::move(owner); return slot; @@ -280,6 +281,7 @@ std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const vo if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; const auto slot = takeOrSweepLocked(dropped); if (!slot) return std::nullopt; + noteTakenLocked(dropped); writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); claimSlotLocked(key, *slot); viewSlots[owner].push_back(*slot); @@ -293,6 +295,7 @@ void BindlessHeap::ReleaseViewSlots(const void* owner) { for (const auto slot : found->second) freeSlotLocked(slot); slotSerial.fetch_add(1, std::memory_order_release); viewSlots.erase(found); + if (NearlyFull()) NoteSweepDue(); } std::optional BindlessHeap::takeOrSweepLocked(std::vector>& dropped) { @@ -390,6 +393,8 @@ bool BindlessHeap::NearlyFull() { namespace { std::atomic sweepDue{false}; +std::atomic refusedSweepChecks{0}; +constexpr std::uint32_t RefusedSweepInterval = 64u; } @@ -398,7 +403,10 @@ void BindlessHeap::NoteSweepDue() { } void BindlessHeap::SweepIfDue() { - if (!sweepDue.load(std::memory_order_relaxed) || !sweepDue.exchange(false, std::memory_order_relaxed)) return; + const bool due = sweepDue.load(std::memory_order_relaxed) && sweepDue.exchange(false, std::memory_order_relaxed); + const bool retry = !due && nearlyFull.load(std::memory_order_relaxed) && + refusedSweepChecks.fetch_add(1, std::memory_order_relaxed) % RefusedSweepInterval == RefusedSweepInterval - 1u; + if (!due && !retry) return; std::vector> dropped; SweptStorageRelease swept; std::vector> droppedSamplers; diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 212e14dc28e2..b0bcfae1ec4c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -178,8 +178,62 @@ void heapComesBack(const Context& context, VkImageView view) { BindlessHeap::Release(context.device); } +void storageComesBack(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + std::vector> owners; + for (std::size_t index = 0; index < 7u; ++index) { + owners.push_back(std::make_shared(0)); + require(heap.StorageSlot(Abi::FirstStorageImageBinding, owners.back(), view).has_value(), + "a storage owner takes one of the eight capped slots"); + } + require(BindlessHeap::NearlyFull(), "storage owners that leave one free slot of eight refuse the heap"); + BindlessHeap::NoteSweepDue(); + BindlessHeap::SweepIfDue(); + require(BindlessHeap::NearlyFull(), "a sweep while every storage owner is held leaves the heap refused"); + owners.clear(); + for (std::uint32_t check = 0; check < 64u && BindlessHeap::NearlyFull(); ++check) BindlessHeap::SweepIfDue(); + require(!BindlessHeap::NearlyFull(), "a refused heap sweeps again by itself and takes the heap back once the storage owners are gone"); + BindlessHeap::Release(context.device); +} + +void mixedComesBack(const Context& context, VkImageView sampledView, VkImageView storageView) { + auto& heap = BindlessHeap::For(context); + std::vector> textures; + for (std::size_t index = 0; index < 4u; ++index) { + textures.push_back(fakeTexture(index)); + require(heap.TextureSlot(Abi::FirstImageBinding, textures.back(), sampledView, VK_IMAGE_LAYOUT_GENERAL).has_value(), + "a texture takes one of the eight capped slots"); + } + require(!BindlessHeap::NearlyFull(), "four textures in eight capped slots leave the heap taken"); + std::vector> owners; + for (std::size_t index = 0; index < 3u; ++index) { + owners.push_back(std::make_shared(0)); + require(heap.StorageSlot(Abi::FirstStorageImageBinding, owners.back(), storageView).has_value(), + "a storage owner takes one of the slots the textures left"); + } + require(BindlessHeap::NearlyFull(), "storage owners that take the slots the textures left refuse the heap"); + owners.clear(); + BindlessHeap::NoteSweepDue(); + BindlessHeap::SweepIfDue(); + require(!BindlessHeap::NearlyFull(), "a sweep after the storage owners are gone takes the heap again while the textures stay"); + BindlessHeap::Release(context.device); +} + +void viewsComeBack(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + const auto kind = Abi::FirstStorageImageBinding + 27u; + std::array owners{}; + for (auto& owner : owners) require(heap.ViewSlot(kind, &owner, view).has_value(), "a view takes one of the eight capped slots"); + require(BindlessHeap::NearlyFull(), "views that leave one free slot of eight refuse the heap"); + for (auto& owner : owners) heap.ReleaseViewSlots(&owner); + BindlessHeap::SweepIfDue(); + require(!BindlessHeap::NearlyFull(), "releasing the views schedules the sweep that takes the heap again"); + BindlessHeap::Release(context.device); +} + int main(int argc, char** argv) { - const bool comesBack = argc > 1 && std::string(argv[1]) == "comes-back"; + const std::string mode = argc > 1 ? argv[1] : ""; + const bool comesBack = !mode.empty(); try { #ifdef _WIN32 _putenv_s("APS5_GPU_HEAP", "1"); @@ -207,11 +261,17 @@ int main(int argc, char** argv) { { const auto context = device->GraphicsContext(); const PlaceholderImages placeholders(context); - heapComesBack(context, placeholders.View(Abi::FirstImageBinding)); + const auto sampled = placeholders.View(Abi::FirstImageBinding); + const auto storage = placeholders.View(Abi::FirstStorageImageBinding); + if (mode == "comes-back") heapComesBack(context, sampled); + else if (mode == "storage-comes-back") storageComesBack(context, storage); + else if (mode == "mixed-comes-back") mixedComesBack(context, sampled, storage); + else if (mode == "views-come-back") viewsComeBack(context, storage); + else throw std::runtime_error("unknown mode " + mode); device->WaitIdle(); } device.reset(); - std::cout << "the refused heap comes back after a sweep\n"; + std::cout << "the refused heap comes back after a sweep (" << mode << ")\n"; return 0; } { diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 4d46c7e0b63f..18384e0492b3 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -165,7 +165,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_GROUP_CAPTURE_ALL_QUEUES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp` | | resolves group-ahead capture on queue 0 as well | | `APS5_HANDOFF_SPIN_US` | integer | `core/libs/prx/libSceAgcDriver/Execution/include/HandoffSpin.hpp` | | microseconds a thread spins for a handed-off draw's work or for the GPU mutex before blocking, clamped to 0..10000; unset spins 150 us when the process has more than 8 usable processors and not at all otherwise | | `APS5_HEAP_MIRROR_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 24576 | budget in MiB for the heap mirrors held for registered allocations | -| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 4096 | number of image slots per binding kind the GPU heap uses; 0 keeps the default | +| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 233415 | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | | `APS5_HOOK_LOCKED_WAIT` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | keeps the flush hook's pending-write wait under the GpuMutex | From 493d5fa57526fb078a489d6a22ce410e2a5c4cd2 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 25 Oct 2026 07:53:29 +0530 Subject: [PATCH 042/269] fix(agc): put libc on PATH for the Windows GPU heap test variants --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index ca547d4f17e1..689f4aba88c3 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -3163,14 +3163,23 @@ if(BUILD_TESTING) if(TARGET agc_driver_pipeline_journal_tests) add_test(NAME agc_driver_pipeline_journal_gpu_heap COMMAND agc_driver_pipeline_journal_tests --gpu-heap) set_tests_properties(agc_driver_pipeline_journal_gpu_heap PROPERTIES ENVIRONMENT "APS5_GPU_HEAP=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_pipeline_journal_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() endif() if(TARGET agc_driver_dispatch_move_tests) add_test(NAME agc_driver_dispatch_move_gpu_heap COMMAND agc_driver_dispatch_move_tests) set_tests_properties(agc_driver_dispatch_move_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_dispatch_move_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() endif() if(TARGET agc_driver_bindless_images_tests) add_test(NAME agc_driver_bindless_images_heap COMMAND agc_driver_bindless_images_tests) set_tests_properties(agc_driver_bindless_images_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1" SKIP_RETURN_CODE 77) + if(WIN32) + set_tests_properties(agc_driver_bindless_images_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() endif() set_tests_properties(agc_driver_draw_cache_reuse_off PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_GPL=1" SKIP_RETURN_CODE 77) add_test(NAME agc_driver_draw_cache_reuse_verify COMMAND agc_driver_draw_cache_reuse_tests) From 3b0df6a5d104a728a7b0f31a2ab4be6cf569cc27 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 25 Oct 2026 19:39:06 +0530 Subject: [PATCH 043/269] fix(shader): keep the GPU heap's stage templates in one byte budget across shaders Co-Authored-By: Claude Opus 5.5 --- .../Graphics/src/BindlessHeap.cpp | 6 +- core/shader/recompiler/CMakeLists.txt | 1 + core/shader/recompiler/Recompiler.cpp | 97 ++++++++++++++++++- core/shader/recompiler/Recompiler.hpp | 7 ++ docs/dev/ENVIRONMENT.md | 1 + 5 files changed, 108 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 874c49deb976..1d325b815b54 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -6,6 +6,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libc/include/HostThreadLocal.hpp" +#include "Recompiler.hpp" #include "RuntimeAbi.hpp" #include "SpirvBackend/SpirvAnalysis.hpp" #include @@ -894,13 +895,14 @@ void reportHeapStatistics() { const auto spansWritten = takeCount(spansWrittenWindow); const auto spansKept = takeCount(spansKeptWindow); const auto spansExpired = takeCount(spansExpiredWindow); + const auto templates = ShaderRecompiler::HeapTemplateCounts(); std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired\n", + "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired; templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(spansExpired)); + printed(spansWritten), printed(spansKept), printed(spansExpired), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index d0ba5adf8410..2e6f1061b438 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -247,6 +247,7 @@ function(add_shader_recompiler target runtimeTarget) BuildBarycentricTessellationShaders HeapFragmentEligible CompleteHeapDataWords + HeapTemplateCounts BuildPreparedShaderKey BuildRectListShaders CaptureResources diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index af31eba4adee..15b9b462a8d2 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -14,6 +14,7 @@ #include "SpirvBackend/SpirvSpecialization.hpp" #include "RdnaDecoder/RdnaDescriptorFormat.hpp" #include "ShaderDiskCache.hpp" +#include #include #include #include @@ -392,6 +393,8 @@ struct HeapTemplate { std::vector buffers; std::vector images; std::vector samplers; + std::uint64_t bytes = 0; + std::uint64_t used = 0; }; struct SourceEntry : std::enable_shared_from_this { @@ -418,6 +421,90 @@ struct SourceEntry : std::enable_shared_from_this { namespace { +struct HeapTemplateStore { + struct Queued { + std::weak_ptr source; + std::uint64_t key; + std::uint64_t bytes; + std::uint64_t queuedAt; + }; + std::mutex mutex; + std::deque queue; + std::uint64_t bytes = 0; + std::atomic clock{0}; + std::atomic entries{0}; + std::atomic evicted{0}; +}; + +HeapTemplateStore& HeapTemplates() { + static auto* store = new HeapTemplateStore(); + return *store; +} + +std::uint64_t HeapTemplateBudget() { + static const std::uint64_t budget = [] { + const char* value = std::getenv("APS5_HEAP_TEMPLATE_MIB"); + const auto mib = value != nullptr ? std::strtoull(value, nullptr, 10) : 256ull; + return std::max(mib, 1u) << 20u; + }(); + return budget; +} + +template +std::uint64_t VectorBytes(const TVector& values) { + return static_cast(values.capacity()) * sizeof(typename TVector::value_type); +} + +std::uint64_t HeapTemplateBytes(const HeapTemplate& entry) { + const auto& result = *entry.result; + std::uint64_t bytes = sizeof(RecompileResult) + sizeof(HeapTemplate) + VectorBytes(result.bindings) + VectorBytes(result.pushConstants) + VectorBytes(result.specialization) + VectorBytes(result.vertexAttributes) + VectorBytes(result.heapUserWords) + VectorBytes(result.shaderDataUserWords); + for (const auto& binding : result.bindings) bytes += VectorBytes(binding.guestDescriptor); + return bytes + VectorBytes(entry.buffers) + VectorBytes(entry.images) + VectorBytes(entry.samplers); +} + +void QueueHeapTemplate(const std::shared_ptr& source, std::uint64_t key, std::uint64_t bytes) { + auto& store = HeapTemplates(); + std::lock_guard lock(store.mutex); + store.queue.push_back({source, key, bytes, store.clock.load(std::memory_order_relaxed)}); + store.bytes += bytes; + store.entries.fetch_add(1, std::memory_order_relaxed); + const auto budget = HeapTemplateBudget(); + const auto visits = store.queue.size() * 2u; + for (std::size_t visited = 0; store.bytes > budget && !store.queue.empty() && visited < visits; ++visited) { + auto oldest = std::move(store.queue.front()); + store.queue.pop_front(); + auto owner = oldest.source.lock(); + bool requeue = false; + bool held = false; + if (owner != nullptr) { + std::lock_guard sourceLock(owner->mutex); + if (const auto found = owner->heapTemplates.find(oldest.key); found != owner->heapTemplates.end() && found->second.bytes == oldest.bytes) { + held = true; + if (found->second.used > oldest.queuedAt) requeue = true; + else owner->heapTemplates.erase(found); + } + } + if (requeue) { + oldest.queuedAt = store.clock.load(std::memory_order_relaxed); + store.queue.push_back(std::move(oldest)); + continue; + } + store.bytes -= oldest.bytes; + store.entries.fetch_sub(1, std::memory_order_relaxed); + if (held) store.evicted.fetch_add(1, std::memory_order_relaxed); + } +} + +} + +HeapTemplateCacheCounts HeapTemplateCounts() { + auto& store = HeapTemplates(); + std::lock_guard lock(store.mutex); + return {store.entries.load(std::memory_order_relaxed), store.bytes, store.evicted.exchange(0, std::memory_order_relaxed)}; +} + +namespace { + class PrimedSharedMutex : public std::shared_mutex { public: PrimedSharedMutex() { @@ -2018,6 +2105,7 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap std::lock_guard lock(source.mutex); const auto found = source.heapTemplates.find(key); if (found != source.heapTemplates.end()) { + found->second.used = HeapTemplates().clock.fetch_add(1, std::memory_order_relaxed) + 1u; const auto shared = found->second; useAttributes(shared.result); useBindings(shared); @@ -2032,11 +2120,16 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap static std::atomic templateIds{0}; built->heapTemplateId = templateIds.fetch_add(1, std::memory_order_relaxed) + 1u; HeapTemplate shared{std::move(built), std::move(usedPlan), perDrawBindings ? snapshot.buffers : std::vector{}, perDrawBindings ? snapshot.images : std::vector{}, perDrawBindings ? snapshot.samplers : std::vector{}}; + shared.bytes = HeapTemplateBytes(shared); + shared.used = HeapTemplates().clock.fetch_add(1, std::memory_order_relaxed) + 1u; + bool inserted = false; { std::lock_guard lock(source.mutex); - if (source.heapTemplates.size() >= 4096) source.heapTemplates.clear(); - shared = source.heapTemplates.emplace(key, shared).first->second; + auto [at, added] = source.heapTemplates.emplace(key, shared); + inserted = added; + shared = at->second; } + if (inserted) QueueHeapTemplate(source.shared_from_this(), key, shared.bytes); useAttributes(shared.result); useBindings(shared); CompleteHeapDataWords(*shared.result, words); diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index efb5ffe9f38d..85059232abc2 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -443,6 +443,13 @@ struct GraphicsCompileContext { struct VertexAttribute; +struct HeapTemplateCacheCounts { + std::uint64_t entries = 0; + std::uint64_t bytes = 0; + std::uint64_t evicted = 0; +}; +HeapTemplateCacheCounts HeapTemplateCounts(); + struct HeapStageWords { std::vector userData; std::vector flattenedSrt; diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index e3c692b2ec00..2f8195b0ddb1 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -167,6 +167,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_GROUP_CAPTURE_ALL_QUEUES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp` | | resolves group-ahead capture on queue 0 as well | | `APS5_HANDOFF_SPIN_US` | integer | `core/libs/prx/libSceAgcDriver/Execution/include/HandoffSpin.hpp` | | microseconds a thread spins for a handed-off draw's work or for the GPU mutex before blocking, clamped to 0..10000; unset spins 150 us when the process has more than 8 usable processors and not at all otherwise | | `APS5_HEAP_MIRROR_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 24576 | budget in MiB for the heap mirrors held for registered allocations | +| `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first | | `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 233415 | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | From 82c57145d5433694cbafa998793d457b19d073ae Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 25 Oct 2026 20:26:10 +0530 Subject: [PATCH 044/269] fix(shader): charge everything a heap template owns and evict the least recently used Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 8 ++ core/shader/recompiler/HeapTemplateBudget.hpp | 114 +++++++++++++++ core/shader/recompiler/Recompiler.cpp | 130 +++++++++--------- .../tests/HeapTemplateBudgetTests.cpp | 77 +++++++++++ 4 files changed, 261 insertions(+), 68 deletions(-) create mode 100644 core/shader/recompiler/HeapTemplateBudget.hpp create mode 100644 core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 813ad77f6e22..44f809634b17 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -115,6 +115,14 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/ControlFlow/include) add_test(NAME request_serializer COMMAND request_serializer_tests) set_tests_properties(request_serializer PROPERTIES TIMEOUT 20) + add_test_executable(heap_template_budget_tests + ${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp) + target_include_directories(heap_template_budget_tests PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/core/libs + ${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler + ${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/ControlFlow/include) + add_test(NAME heap_template_budget COMMAND heap_template_budget_tests) + set_tests_properties(heap_template_budget PROPERTIES TIMEOUT 20) find_package(Python3 QUIET COMPONENTS Interpreter) add_test_executable(shader_ir_use_rewrite_tests core/shader/recompiler/IntermediateRepresentation/tests/UseRewrite.cpp diff --git a/core/shader/recompiler/HeapTemplateBudget.hpp b/core/shader/recompiler/HeapTemplateBudget.hpp new file mode 100644 index 000000000000..6885e9d28c21 --- /dev/null +++ b/core/shader/recompiler/HeapTemplateBudget.hpp @@ -0,0 +1,114 @@ +#pragma once + +#include "Recompiler.hpp" + +#include +#include +#include +#include +#include +#include + +namespace ShaderRecompiler { + +template +[[nodiscard]] std::uint64_t OwnedBytes(const std::vector& values) { + return static_cast(values.capacity()) * sizeof(TValue); +} + +[[nodiscard]] inline std::uint64_t OwnedBytes(const std::vector& values) { + return (static_cast(values.capacity()) + 7u) / 8u; +} + +[[nodiscard]] inline std::uint64_t OwnedBytes(const DescriptorBinding& binding) { + return OwnedBytes(binding.guestDescriptor) + OwnedBytes(binding.samplerDepthCompare) + OwnedBytes(binding.imageWritten) + OwnedBytes(binding.imageDepthCompare) + OwnedBytes(binding.imageAtomic) + OwnedBytes(binding.imageAtomic64) + + OwnedBytes(binding.imageShapes) + OwnedBytes(binding.bufferAtomic) + OwnedBytes(binding.bufferWritten) + OwnedBytes(binding.samplerUnnormalized) + OwnedBytes(binding.samplerIntegerBorder) + + OwnedBytes(binding.samplerCoordinatesIgnored) + OwnedBytes(binding.imageUnnormalized) + OwnedBytes(binding.imageUnnormalizedBaseLevel) + OwnedBytes(binding.imageSamplers) + OwnedBytes(binding.bufferRead) + + OwnedBytes(binding.bufferExtent); +} + +// The bytes a heap template's result owns. Its SPIR-V module is shared with the variant it was +// materialized from, so it is not charged. +[[nodiscard]] inline std::uint64_t OwnedBytes(const RecompileResult& result) { + std::uint64_t bytes = sizeof(RecompileResult) + OwnedBytes(result.vertexInputPatches) + OwnedBytes(result.runtimeImageResources) + OwnedBytes(result.vertexInputs) + OwnedBytes(result.parameterExports) + + OwnedBytes(result.fragmentParameters) + OwnedBytes(result.stencilReferences) + OwnedBytes(result.specialization) + OwnedBytes(result.heapSlotWords) + OwnedBytes(result.bindings) + + OwnedBytes(result.pushConstants) + OwnedBytes(result.vertexAttributes) + OwnedBytes(result.imageTablePoison) + OwnedBytes(result.imageTableRanges) + OwnedBytes(result.imageTableReadRanges) + + OwnedBytes(result.heapUserWords) + OwnedBytes(result.shaderDataUserWords); + if (result.meshBarycentrics.has_value()) bytes += OwnedBytes(result.meshBarycentrics->parameters); + for (const auto& binding : result.bindings) bytes += OwnedBytes(binding); + for (const auto& ranges : result.imageTableReadRanges) bytes += OwnedBytes(ranges); + return bytes; +} + +// Least recently used order of the heap templates of every shader, under one byte budget. A +// template is named by its owner (the shader it belongs to), its key in that shader's map, and +// the id of the template built for that key, so a touch or an eviction never reaches a later +// template that took the same owner and key. +class HeapTemplateLru { +public: + struct Name { + std::uint64_t owner = 0; + std::uint64_t key = 0; + std::uint64_t id = 0; + }; + + struct Evicted { + Name name; + std::weak_ptr owner; + }; + + explicit HeapTemplateLru(std::uint64_t budget) : budget(budget) {} + + // Adds a template as the most recently used, and returns the templates evicted to bring the + // total back under the budget, least recently used first. + [[nodiscard]] std::vector Insert(const Name& name, std::uint64_t bytes, std::weak_ptr owner = {}) { + std::vector evicted; + if (const auto found = index.find(Slot{name.owner, name.key}); found != index.end()) { + total -= found->second->bytes; + order.erase(found->second); + index.erase(found); + } + order.push_back({name, bytes, std::move(owner)}); + index.emplace(Slot{name.owner, name.key}, std::prev(order.end())); + total += bytes; + while (total > budget && !order.empty()) { + auto oldest = std::move(order.front()); + index.erase(Slot{oldest.name.owner, oldest.name.key}); + order.pop_front(); + total -= oldest.bytes; + evicted.push_back({oldest.name, std::move(oldest.owner)}); + } + return evicted; + } + + void Touch(const Name& name) { + const auto found = index.find(Slot{name.owner, name.key}); + if (found == index.end() || found->second->name.id != name.id) return; + order.splice(order.end(), order, found->second); + } + + [[nodiscard]] std::uint64_t Entries() const { return order.size(); } + [[nodiscard]] std::uint64_t Bytes() const { return total; } + +private: + struct Entry { + Name name; + std::uint64_t bytes = 0; + std::weak_ptr owner; + }; + struct Slot { + std::uint64_t owner = 0; + std::uint64_t key = 0; + bool operator==(const Slot&) const = default; + }; + struct SlotHash { + std::size_t operator()(const Slot& slot) const { return std::hash{}(slot.owner * 0x9e3779b97f4a7c15ull ^ slot.key); } + }; + + std::uint64_t budget = 0; + std::uint64_t total = 0; + std::list order; + std::unordered_map::iterator, SlotHash> index; +}; + +} diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 15b9b462a8d2..bda199c58492 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -1,4 +1,5 @@ #include "Recompiler.hpp" +#include "HeapTemplateBudget.hpp" #include "StencilReplay.hpp" #include #include @@ -382,6 +383,11 @@ constexpr std::size_t ResultMemoSets = 64; constexpr std::size_t ResultMemoWays = 4; using ResultMemoTable = std::array; +std::uint64_t NextSourceId() { + static std::atomic ids{0}; + return ids.fetch_add(1, std::memory_order_relaxed) + 1u; +} + struct UsedBindingPlan { std::shared_ptr owner; const DescriptorBindingPlan* plan = nullptr; @@ -394,11 +400,11 @@ struct HeapTemplate { std::vector images; std::vector samplers; std::uint64_t bytes = 0; - std::uint64_t used = 0; }; struct SourceEntry : std::enable_shared_from_this { std::mutex mutex; + const std::uint64_t id = NextSourceId(); // The code the entry was built for: the key carries only a hash of it, so a candidate entry is // accepted only when its code matches word for word. Owned here because the request's span // points into a registration the driver may replace while the entry lives on. @@ -421,19 +427,19 @@ struct SourceEntry : std::enable_shared_from_this { namespace { +std::uint64_t HeapTemplateBudget() { + static const std::uint64_t budget = [] { + const char* value = std::getenv("APS5_HEAP_TEMPLATE_MIB"); + const auto mib = value != nullptr ? std::strtoull(value, nullptr, 10) : 256ull; + return std::max(mib, 1u) << 20u; + }(); + return budget; +} + struct HeapTemplateStore { - struct Queued { - std::weak_ptr source; - std::uint64_t key; - std::uint64_t bytes; - std::uint64_t queuedAt; - }; std::mutex mutex; - std::deque queue; - std::uint64_t bytes = 0; - std::atomic clock{0}; - std::atomic entries{0}; - std::atomic evicted{0}; + HeapTemplateLru order{HeapTemplateBudget()}; + std::uint64_t evicted = 0; }; HeapTemplateStore& HeapTemplates() { @@ -441,58 +447,40 @@ HeapTemplateStore& HeapTemplates() { return *store; } -std::uint64_t HeapTemplateBudget() { - static const std::uint64_t budget = [] { - const char* value = std::getenv("APS5_HEAP_TEMPLATE_MIB"); - const auto mib = value != nullptr ? std::strtoull(value, nullptr, 10) : 256ull; - return std::max(mib, 1u) << 20u; - }(); - return budget; +std::uint64_t HeapTemplateBytes(const HeapTemplate& entry) { + return sizeof(HeapTemplate) + OwnedBytes(*entry.result) + OwnedBytes(entry.buffers) + OwnedBytes(entry.images) + OwnedBytes(entry.samplers); } -template -std::uint64_t VectorBytes(const TVector& values) { - return static_cast(values.capacity()) * sizeof(typename TVector::value_type); +HeapTemplateLru::Name HeapTemplateName(const SourceEntry& source, std::uint64_t key, const HeapTemplate& entry) { + return {source.id, key, entry.result->heapTemplateId}; } -std::uint64_t HeapTemplateBytes(const HeapTemplate& entry) { - const auto& result = *entry.result; - std::uint64_t bytes = sizeof(RecompileResult) + sizeof(HeapTemplate) + VectorBytes(result.bindings) + VectorBytes(result.pushConstants) + VectorBytes(result.specialization) + VectorBytes(result.vertexAttributes) + VectorBytes(result.heapUserWords) + VectorBytes(result.shaderDataUserWords); - for (const auto& binding : result.bindings) bytes += VectorBytes(binding.guestDescriptor); - return bytes + VectorBytes(entry.buffers) + VectorBytes(entry.images) + VectorBytes(entry.samplers); +void KeepHeapTemplate(const std::shared_ptr& source, std::uint64_t key, const HeapTemplate& entry) { + auto& store = HeapTemplates(); + std::vector evicted; + { + std::lock_guard lock(store.mutex); + evicted = store.order.Insert(HeapTemplateName(*source, key, entry), entry.bytes, source); + } + std::uint64_t erased = 0; + for (const auto& gone : evicted) { + const auto owner = std::static_pointer_cast(gone.owner.lock()); + if (owner == nullptr) continue; + std::lock_guard lock(owner->mutex); + const auto found = owner->heapTemplates.find(gone.name.key); + if (found == owner->heapTemplates.end() || found->second.result->heapTemplateId != gone.name.id) continue; + owner->heapTemplates.erase(found); + ++erased; + } + if (erased == 0) return; + std::lock_guard lock(store.mutex); + store.evicted += erased; } -void QueueHeapTemplate(const std::shared_ptr& source, std::uint64_t key, std::uint64_t bytes) { +void TouchHeapTemplate(const HeapTemplateLru::Name& name) { auto& store = HeapTemplates(); std::lock_guard lock(store.mutex); - store.queue.push_back({source, key, bytes, store.clock.load(std::memory_order_relaxed)}); - store.bytes += bytes; - store.entries.fetch_add(1, std::memory_order_relaxed); - const auto budget = HeapTemplateBudget(); - const auto visits = store.queue.size() * 2u; - for (std::size_t visited = 0; store.bytes > budget && !store.queue.empty() && visited < visits; ++visited) { - auto oldest = std::move(store.queue.front()); - store.queue.pop_front(); - auto owner = oldest.source.lock(); - bool requeue = false; - bool held = false; - if (owner != nullptr) { - std::lock_guard sourceLock(owner->mutex); - if (const auto found = owner->heapTemplates.find(oldest.key); found != owner->heapTemplates.end() && found->second.bytes == oldest.bytes) { - held = true; - if (found->second.used > oldest.queuedAt) requeue = true; - else owner->heapTemplates.erase(found); - } - } - if (requeue) { - oldest.queuedAt = store.clock.load(std::memory_order_relaxed); - store.queue.push_back(std::move(oldest)); - continue; - } - store.bytes -= oldest.bytes; - store.entries.fetch_sub(1, std::memory_order_relaxed); - if (held) store.evicted.fetch_add(1, std::memory_order_relaxed); - } + store.order.Touch(name); } } @@ -500,7 +488,7 @@ void QueueHeapTemplate(const std::shared_ptr& source, std::uint64_t HeapTemplateCacheCounts HeapTemplateCounts() { auto& store = HeapTemplates(); std::lock_guard lock(store.mutex); - return {store.entries.load(std::memory_order_relaxed), store.bytes, store.evicted.exchange(0, std::memory_order_relaxed)}; + return {store.order.Entries(), store.order.Bytes(), std::exchange(store.evicted, 0)}; } namespace { @@ -2102,15 +2090,21 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap if (std::all_of(words.bindings.begin(), words.bindings.end(), [](const std::vector& descriptor) { return descriptor.empty(); })) words.bindings.clear(); }; { - std::lock_guard lock(source.mutex); - const auto found = source.heapTemplates.find(key); - if (found != source.heapTemplates.end()) { - found->second.used = HeapTemplates().clock.fetch_add(1, std::memory_order_relaxed) + 1u; - const auto shared = found->second; - useAttributes(shared.result); - useBindings(shared); - CompleteHeapDataWords(*shared.result, words); - return shared.result; + std::shared_ptr hit; + { + std::lock_guard lock(source.mutex); + const auto found = source.heapTemplates.find(key); + if (found != source.heapTemplates.end()) { + const auto shared = found->second; + useAttributes(shared.result); + useBindings(shared); + CompleteHeapDataWords(*shared.result, words); + hit = shared.result; + } + } + if (hit != nullptr) { + TouchHeapTemplate({source.id, key, hit->heapTemplateId}); + return hit; } } UsedBindingPlan usedPlan; @@ -2121,7 +2115,6 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap built->heapTemplateId = templateIds.fetch_add(1, std::memory_order_relaxed) + 1u; HeapTemplate shared{std::move(built), std::move(usedPlan), perDrawBindings ? snapshot.buffers : std::vector{}, perDrawBindings ? snapshot.images : std::vector{}, perDrawBindings ? snapshot.samplers : std::vector{}}; shared.bytes = HeapTemplateBytes(shared); - shared.used = HeapTemplates().clock.fetch_add(1, std::memory_order_relaxed) + 1u; bool inserted = false; { std::lock_guard lock(source.mutex); @@ -2129,7 +2122,8 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap inserted = added; shared = at->second; } - if (inserted) QueueHeapTemplate(source.shared_from_this(), key, shared.bytes); + if (inserted) KeepHeapTemplate(source.shared_from_this(), key, shared); + else TouchHeapTemplate(HeapTemplateName(source, key, shared)); useAttributes(shared.result); useBindings(shared); CompleteHeapDataWords(*shared.result, words); diff --git a/core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp b/core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp new file mode 100644 index 000000000000..93b380a42883 --- /dev/null +++ b/core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp @@ -0,0 +1,77 @@ +#include "HeapTemplateBudget.hpp" + +#include +#include +#include +#include +#include + +namespace { + +using ShaderRecompiler::HeapTemplateLru; + +void Require(bool condition, const std::string& what) { + if (!condition) throw std::runtime_error(what); +} + +std::string Names(const std::vector& evicted) { + std::string names; + for (const auto& gone : evicted) names += " " + std::to_string(gone.name.owner) + ":" + std::to_string(gone.name.key); + return names.empty() ? " none" : names; +} + +void LeastRecentlyUsedAcrossShaders() { + HeapTemplateLru order(200); + const HeapTemplateLru::Name a{1, 7, 1}, b{2, 7, 2}, c{3, 7, 3}; + Require(order.Insert(a, 100).empty() && order.Insert(b, 100).empty(), "two templates that fit the budget evicted one"); + order.Touch(a); + order.Touch(b); + const auto evicted = order.Insert(c, 100); + Require(evicted.size() == 1 && evicted[0].name.owner == a.owner && evicted[0].name.id == a.id, "insert A, insert B, touch A, touch B, insert C evicted" + Names(evicted) + " instead of A, the least recently used"); + Require(order.Entries() == 2 && order.Bytes() == 200, "the budget does not hold B and C after A was evicted"); + order.Touch(b); + const auto next = order.Insert({4, 7, 4}, 100); + Require(next.size() == 1 && next[0].name.owner == c.owner, "after touching B, the next insert evicted" + Names(next) + " instead of C"); +} + +void StaleTouchAndReplacedTemplate() { + HeapTemplateLru order(200); + Require(order.Insert({1, 5, 1}, 100).empty() && order.Insert({2, 5, 2}, 100).empty(), "two templates that fit the budget evicted one"); + order.Touch({1, 5, 9}); + const auto evicted = order.Insert({3, 5, 3}, 100); + Require(evicted.size() == 1 && evicted[0].name.owner == 1, "a touch naming a template id that is not kept moved the kept template, evicted" + Names(evicted)); + Require(order.Insert({2, 5, 4}, 150).size() == 1 && order.Bytes() == 150 && order.Entries() == 1, "a template replacing the one kept under the same shader and key was charged on top of it"); +} + +void ChargesOwnedArrays() { + ShaderRecompiler::RecompileResult result; + const auto empty = ShaderRecompiler::OwnedBytes(result); + result.imageTableReadRanges.resize(64); + for (auto& ranges : result.imageTableReadRanges) ranges.resize(1024); + const auto readRanges = std::uint64_t{64} * 1024u * sizeof(std::pair); + Require(ShaderRecompiler::OwnedBytes(result) >= empty + readRanges, "a template whose image table read ranges hold " + std::to_string(readRanges) + " bytes was charged " + std::to_string(ShaderRecompiler::OwnedBytes(result) - empty)); + const auto withRanges = ShaderRecompiler::OwnedBytes(result); + result.heapSlotWords.resize(4096); + result.imageTableRanges.resize(4096); + result.imageTablePoison.resize(1024); + const auto arrays = ShaderRecompiler::OwnedBytes(result.heapSlotWords) + ShaderRecompiler::OwnedBytes(result.imageTableRanges) + ShaderRecompiler::OwnedBytes(result.imageTablePoison); + Require(ShaderRecompiler::OwnedBytes(result) >= withRanges + arrays, "a template's heap slot words, image table ranges and poison were not charged"); + result.bindings.resize(8); + for (auto& binding : result.bindings) binding.guestDescriptor.resize(4096); + Require(ShaderRecompiler::OwnedBytes(result) >= withRanges + arrays + 8u * 4096u * sizeof(std::uint32_t), "the guest descriptor words of a template's bindings were not charged"); +} + +} + +int main() { + try { + LeastRecentlyUsedAcrossShaders(); + StaleTouchAndReplacedTemplate(); + ChargesOwnedArrays(); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } + std::cout << "heap template budget tests passed\n"; + return 0; +} From 1a59442db830f7712dc17619b69983bb1b2fc469 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 26 Oct 2026 02:33:28 +0530 Subject: [PATCH 045/269] fix(agc): send dispatches to the per-dispatch path when the heap runs short of image slots Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 7 +++++++ .../src/Driver/Dispatch/Dispatch.cpp | 3 ++- .../tests/execution/HeapComputeSample.cpp | 19 +++++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 52f8ecb2e9a4..ea5df900a005 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -3203,6 +3203,13 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_heap_compute_sample_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endif() + if(TARGET agc_driver_heap_compute_sample_tests) + add_test(NAME agc_driver_heap_compute_sample_full_heap COMMAND agc_driver_heap_compute_sample_tests) + set_tests_properties(agc_driver_heap_compute_sample_full_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_HEAP_SLOT_CAP=4" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_heap_compute_sample_full_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + endif() + endif() if(TARGET agc_driver_pipeline_journal_tests) add_test(NAME agc_driver_pipeline_journal_gpu_heap COMMAND agc_driver_pipeline_journal_tests --gpu-heap) set_tests_properties(agc_driver_pipeline_journal_gpu_heap PROPERTIES ENVIRONMENT "APS5_GPU_HEAP=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index b93bad149fe4..66a5a0f1dee1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -171,7 +171,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, {0, 0, 0, threadGroup != std::array{} ? 0u : 128u} }; constexpr std::size_t computeHeapKey = std::size_t{1} << 61u; - if (request.target.gpuResolvedImages && HeapFragmentKnown(&snapshot, codeOffset | computeHeapKey) == std::optional(false)) request.target.gpuResolvedImages = false; + if (request.target.gpuResolvedImages && (HeapRefused() || HeapFragmentKnown(&snapshot, codeOffset | computeHeapKey) == std::optional(false))) request.target.gpuResolvedImages = false; static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; static double captureMs = 0, keyMs = 0, recompileMs = 0, deviceMs = 0; static std::uint64_t cacheHits = 0; @@ -281,6 +281,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, } mix(reinterpret_cast(registeredShader.get())); + mix(request.target.gpuResolvedImages); if (fromAhead && key != ahead.key) { fromAhead = false; ++groupStats.keyMismatches; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp index 6629ced8ac89..598ec18ba216 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp @@ -37,6 +37,8 @@ alignas(256) constexpr std::array LdsSampleCode{ alignas(256) std::array TextureMemory{}; alignas(256) std::array OtherTextureMemory{}; alignas(4096) std::array, 4> Outputs{}; +constexpr std::size_t FullHeapTextures = 16; +alignas(256) std::array, FullHeapTextures> ManyTextures{}; struct Header { Shader shader{}; @@ -128,6 +130,16 @@ void DriverSample(bool heap) { if (heap) Require(AgcDriver::Graphics::HeapComputeStages() > before, "the heap did not take the sampling compute stage"); } +void FullHeapSample() { + Outputs[0].fill(-1.0f); + std::vector words; + for (std::size_t index = 0; index < FullHeapTextures; ++index) Sample(words, ManyTextures[index].data(), Outputs[0].data() + 4u * index); + Submit(words); + for (std::size_t index = 0; index < FullHeapTextures; ++index) + RequireSampled(Outputs[0].data() + 4u * index, Texel, "texture " + std::to_string(index) + " of a heap with too few image slots", true); + Require(AgcDriver::Graphics::BindlessHeap::NearlyFull(), "the capped heap never ran short of image slots"); +} + ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const void* image, float* output, std::span code = SampleCode, std::uint32_t ldsDwords = 0u) { std::vector userData; @@ -196,7 +208,14 @@ int main() { } Fill(TextureMemory, Texel); Fill(OtherTextureMemory, OtherTexel); + for (auto& texture : ManyTextures) Fill(texture, Texel); Registered(SampleHeader, SampleCode.data(), sizeof(SampleCode)); + if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) { + FullHeapSample(); + AgcDriverShutdown_nid_postfix(); + std::cout << "compute stages sampled every texture after the heap ran short of image slots\n"; + return 0; + } DriverSample(heap); AgcDriverShutdown_nid_postfix(); { From 10f9d8f54bd791b82ec255b0f145d24b4dd22d63 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 26 Oct 2026 03:22:14 +0530 Subject: [PATCH 046/269] fix(agc): release storage images that hold several heap slots once the heap alone holds them Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 2 +- .../Graphics/include/BindlessHeap.hpp | 5 ++ .../Graphics/src/BindlessHeap.cpp | 79 +++++++++++++++++-- .../Graphics/src/ShaderResources.cpp | 1 + .../tests/BindlessHeapSlots.cpp | 39 +++++++++ 5 files changed, 119 insertions(+), 7 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index ea5df900a005..aec81f5e818d 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -3163,7 +3163,7 @@ if(BUILD_TESTING) if(WIN32) set_tests_properties(agc_driver_heap_slots_comes_back PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() - foreach(agcHeapSlotsMode IN ITEMS storage-comes-back mixed-comes-back views-come-back) + foreach(agcHeapSlotsMode IN ITEMS storage-comes-back storage-views-come-back mixed-comes-back views-come-back) string(REPLACE "-" "_" agcHeapSlotsName "${agcHeapSlotsMode}") add_test(NAME agc_driver_heap_slots_${agcHeapSlotsName} COMMAND agc_driver_heap_slots_tests ${agcHeapSlotsMode}) set_tests_properties(agc_driver_heap_slots_${agcHeapSlotsName} PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 4742501af41c..b9528cbc9508 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -59,6 +59,7 @@ class BindlessHeap { std::uint32_t AbsentSlot(std::uint32_t kind, VkImageView view); static bool NearlyFull(); static void NoteSweepDue(); + static void NoteStorageEvicted(const void* owner); static void SweepIfDue(); struct DataSpan { @@ -128,6 +129,7 @@ class BindlessHeap { }; std::unordered_map textureSlots; std::unordered_map> viewSlots; + std::unordered_map> storageSlots; std::uint32_t nextTextureSlot = 0; struct SlotOwner { std::shared_ptr texture; @@ -140,6 +142,9 @@ class BindlessHeap { std::uint32_t slotCap = 0; std::uint64_t slotRequests = 0; void sweepLocked(std::vector>& dropped); + bool heldOnlyHereLocked(const void* owner, long uses) const; + void releaseStorageLocked(std::span owners, std::vector& kept); + void dropStorageLocked(const void* image, std::uint32_t slot); std::optional takeSlotLocked(); std::optional takeOrSweepLocked(std::vector>& dropped); SlotOwner& claimSlotLocked(const TextureKey& key, std::uint32_t slot); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 1d325b815b54..dcc16333d304 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -269,6 +269,7 @@ std::optional BindlessHeap::StorageSlot(std::uint32_t kind, std:: noteTakenLocked(dropped); writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); claimSlotLocked(key, *slot).storage = std::move(owner); + storageSlots[key.texture].push_back(*slot); return slot; } @@ -319,6 +320,11 @@ BindlessHeap::SlotOwner& BindlessHeap::claimSlotLocked(const TextureKey& key, st void BindlessHeap::freeSlotLocked(std::uint32_t slot) { auto& owner = owners[slot]; + if (const auto found = storageSlots.find(owner.key.texture); found != storageSlots.end()) { + auto& slots = found->second; + if (const auto at = std::find(slots.begin(), slots.end(), slot); at != slots.end()) slots.erase(at); + if (slots.empty()) storageSlots.erase(found); + } textureSlots.erase(owner.key); owner.key = {}; ++owner.generation; @@ -347,8 +353,9 @@ void BindlessHeap::sweepLocked(std::vector>& dropped) { for (std::uint32_t slot = SamplerKind; slot < owners.size(); ++slot) { auto& owner = owners[slot]; if (owner.storage != nullptr) { - if (owner.storage.use_count() > 1) continue; - sweptStorage().push_back(std::move(owner.storage)); + if (!heldOnlyHereLocked(owner.key.texture, owner.storage.use_count())) continue; + dropStorageLocked(owner.key.texture, slot); + continue; } else { const bool heldElsewhere = owner.texture == nullptr || owner.texture.use_count() > static_cast(owner.texture->HeapHolds()); @@ -361,6 +368,35 @@ void BindlessHeap::sweepLocked(std::vector>& dropped) { for (auto index = firstDropped; index < dropped.size(); ++index) dropped[index]->DropHeapHold(); } +bool BindlessHeap::heldOnlyHereLocked(const void* owner, long uses) const { + const auto found = storageSlots.find(owner); + const auto slots = found != storageSlots.end() ? static_cast(found->second.size()) : 1l; + return uses <= slots; +} + +void BindlessHeap::releaseStorageLocked(std::span evicted, std::vector& kept) { + for (const auto* image : evicted) { + const auto found = storageSlots.find(image); + if (found == storageSlots.end()) continue; + const auto& first = owners[found->second.front()].storage; + if (first == nullptr || !heldOnlyHereLocked(image, first.use_count())) { + kept.push_back(image); + continue; + } + dropStorageLocked(image, found->second.front()); + } +} + +void BindlessHeap::dropStorageLocked(const void* image, std::uint32_t slot) { + std::vector slots{slot}; + if (const auto found = storageSlots.find(image); found != storageSlots.end()) slots = found->second; + for (const auto held : slots) { + sweptStorage().push_back(std::move(owners[held].storage)); + freeSlotLocked(held); + } + slotSerial.fetch_add(1, std::memory_order_release); +} + void BindlessHeap::sweepSamplersLocked(std::vector>& dropped) { for (std::uint32_t slot = 0; slot < heldSamplers.size(); ++slot) { auto& held = heldSamplers[slot]; @@ -382,7 +418,7 @@ std::atomic nearlyFull{false}; void noteNearlyFull(const char* what, std::uint32_t margin) { if (!nearlyFull.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; draws take the per-draw path from now on\n", margin, what); + std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; draws and dispatches take the per-draw path until a sweep frees twice that many\n", margin, what); } } @@ -394,6 +430,16 @@ bool BindlessHeap::NearlyFull() { namespace { std::atomic sweepDue{false}; + +std::mutex& evictedStorageMutex() { + static auto& mutex = *new std::mutex(); + return mutex; +} + +std::vector& evictedStorage() { + static auto& list = *new std::vector(); + return list; +} std::atomic refusedSweepChecks{0}; constexpr std::uint32_t RefusedSweepInterval = 64u; @@ -403,23 +449,44 @@ void BindlessHeap::NoteSweepDue() { sweepDue.store(true, std::memory_order_relaxed); } +void BindlessHeap::NoteStorageEvicted(const void* owner) { + if (owner == nullptr) return; + std::lock_guard lock(evictedStorageMutex()); + evictedStorage().push_back(owner); +} + void BindlessHeap::SweepIfDue() { + std::vector evicted; + { + std::lock_guard lock(evictedStorageMutex()); + evicted.swap(evictedStorage()); + } const bool due = sweepDue.load(std::memory_order_relaxed) && sweepDue.exchange(false, std::memory_order_relaxed); const bool retry = !due && nearlyFull.load(std::memory_order_relaxed) && refusedSweepChecks.fetch_add(1, std::memory_order_relaxed) % RefusedSweepInterval == RefusedSweepInterval - 1u; - if (!due && !retry) return; + if (!due && !retry && evicted.empty()) return; + std::sort(evicted.begin(), evicted.end()); + evicted.erase(std::unique(evicted.begin(), evicted.end()), evicted.end()); std::vector> dropped; SweptStorageRelease swept; std::vector> droppedSamplers; + std::vector kept; std::lock_guard heapsLock(heapsMutex()); bool room = true; for (auto& [device, heap] : heaps()) { if (heap == nullptr) continue; std::lock_guard lock(heap->mutex); - heap->sweepLocked(dropped); - heap->sweepSamplersLocked(droppedSamplers); + if (due || retry) { + heap->sweepLocked(dropped); + heap->sweepSamplersLocked(droppedSamplers); + } + heap->releaseStorageLocked(evicted, kept); room = room && heap->roomLocked(); } + if (!kept.empty()) { + std::lock_guard lock(evictedStorageMutex()); + evictedStorage().insert(evictedStorage().end(), kept.begin(), kept.end()); + } if (room && nearlyFull.exchange(false, std::memory_order_relaxed)) std::fprintf(stderr, "[gpu-heap] a sweep left twice the margin of slots free; draws take the heap again\n"); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 1fd1a4b2697f..46b8b7489fa7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -1104,6 +1104,7 @@ std::list::iterator findStorageByImage(StorageTextureCache // Evicts an entry: its pending results go to guest memory first (the image may die with the entry). std::shared_ptr evictStorage(StorageTextureCache& cache, std::list::iterator it) { auto texture = it->texture; + if (GpuHeapEnabled()) BindlessHeap::NoteStorageEvicted(texture.get()); it->texture->SetCached(false); noteUncached(it->texture); it->texture->Flush(); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index b0bcfae1ec4c..71074080f750 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -196,6 +196,44 @@ void storageComesBack(const Context& context, VkImageView view) { BindlessHeap::Release(context.device); } +void storageViewsComeBack(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + int released = 0; + const auto owner = [&released] { + return std::shared_ptr(new int(0), [&released](void* pointer) { + ++released; + delete static_cast(pointer); + }); + }; + std::vector> owners; + for (std::size_t index = 0; index < 3u; ++index) { + owners.push_back(owner()); + for (std::uint32_t kind = 0; kind < 2u; ++kind) { + require(heap.StorageSlot(Abi::FirstStorageImageBinding + kind, owners.back(), view).has_value(), + "a storage owner takes one of the eight capped slots for each of its two views"); + } + } + owners.push_back(owner()); + require(heap.StorageSlot(Abi::FirstStorageImageBinding, owners.back(), view).has_value(), "a single-view storage owner takes the seventh slot"); + require(BindlessHeap::NearlyFull(), "storage owners that leave one free slot of eight refuse the heap"); + owners.clear(); + BindlessHeap::NoteSweepDue(); + BindlessHeap::SweepIfDue(); + require(released == 4, "a sweep released " + std::to_string(released) + " of four storage owners the heap alone held, three of them in two slots each"); + require(!BindlessHeap::NearlyFull(), "a sweep after every storage owner is gone takes the heap again"); + + auto evicted = owner(); + for (std::uint32_t kind = 0; kind < 2u; ++kind) require(heap.StorageSlot(Abi::FirstStorageImageBinding + kind, evicted, view).has_value(), "an evicted owner's view takes a slot"); + const auto* image = evicted.get(); + BindlessHeap::NoteStorageEvicted(image); + BindlessHeap::SweepIfDue(); + require(released == 4, "an evicted storage owner still held outside the heap lost its slots"); + evicted.reset(); + BindlessHeap::SweepIfDue(); + require(released == 5, "the present after an evicted storage owner's last outside holder went did not release its two slots"); + BindlessHeap::Release(context.device); +} + void mixedComesBack(const Context& context, VkImageView sampledView, VkImageView storageView) { auto& heap = BindlessHeap::For(context); std::vector> textures; @@ -265,6 +303,7 @@ int main(int argc, char** argv) { const auto storage = placeholders.View(Abi::FirstStorageImageBinding); if (mode == "comes-back") heapComesBack(context, sampled); else if (mode == "storage-comes-back") storageComesBack(context, storage); + else if (mode == "storage-views-come-back") storageViewsComeBack(context, storage); else if (mode == "mixed-comes-back") mixedComesBack(context, sampled, storage); else if (mode == "views-come-back") viewsComeBack(context, storage); else throw std::runtime_error("unknown mode " + mode); From 7d3ea2db74df5c223dc4505e6b1614d3dfcb085c Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 26 Oct 2026 21:57:16 +0530 Subject: [PATCH 047/269] fix(agc): release heap slots of images that left the storage cache The heap released an evicted storage image once, from a list filled at eviction. An image that took a slot after leaving the cache, or that was still in use at eviction, and every sampled view of an evicted image, waited for the full sweep, which rarely runs in steady play. Under storage pressure the heap alone kept gigabytes of evicted images alive and the storage budget fell to its floor. Each present now frees the slots of images that left the storage cache once only the heap holds them: views first, then, after those views are gone, the storage images they kept alive. Images that never entered the cache keep the old behaviour. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 2 + .../Graphics/include/BindlessHeap.hpp | 8 +- .../Graphics/include/Texture.hpp | 7 +- .../Graphics/src/BindlessHeap.cpp | 120 +++++++++++------- .../Graphics/src/ShaderResources.cpp | 3 +- .../tests/BindlessHeapSlots.cpp | 37 +++++- .../tests/execution/SampledCacheBudget.cpp | 56 ++++++++ 7 files changed, 177 insertions(+), 56 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index aec81f5e818d..8c371d0c8f14 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -3056,6 +3056,8 @@ if(BUILD_TESTING) endif() add_test(NAME agc_driver_sampled_cache_budget_memory COMMAND agc_driver_sampled_cache_budget_tests memory) set_tests_properties(agc_driver_sampled_cache_budget_memory PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77) + add_test(NAME agc_driver_sampled_cache_budget_heap_view COMMAND agc_driver_sampled_cache_budget_tests heap-view) + set_tests_properties(agc_driver_sampled_cache_budget_heap_view PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") add_test(NAME agc_driver_sampled_cache_budget_without_storage_image_multisample COMMAND agc_driver_sampled_cache_budget_tests without-storage-image-multisample) set_tests_properties(agc_driver_sampled_cache_budget_without_storage_image_multisample PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30) add_test(NAME agc_sampled_cache_device_selection COMMAND agc_driver_sampled_cache_budget_tests device-selection-cpu) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index b9528cbc9508..ad4d65fd8d84 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -19,6 +19,7 @@ namespace AgcDriver::Graphics { class Buffer; class Recorder; class Sampler; +class StorageTexture; class Texture; class BindlessHeap { @@ -47,6 +48,7 @@ class BindlessHeap { std::optional TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, VkImageLayout layout); std::optional StorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view); + std::optional StorageSlot(std::uint32_t kind, const std::shared_ptr& image, VkImageView view); std::optional ViewSlot(std::uint32_t kind, const void* owner, VkImageView view); void ReleaseViewSlots(const void* owner); std::uint32_t SlotGeneration(std::uint32_t slot) const; @@ -59,7 +61,7 @@ class BindlessHeap { std::uint32_t AbsentSlot(std::uint32_t kind, VkImageView view); static bool NearlyFull(); static void NoteSweepDue(); - static void NoteStorageEvicted(const void* owner); + static void NoteStorageEvicted(); static void SweepIfDue(); struct DataSpan { @@ -134,6 +136,7 @@ class BindlessHeap { struct SlotOwner { std::shared_ptr texture; std::shared_ptr storage; + const StorageTexture* image = nullptr; TextureKey key{}; std::uint32_t generation = 0; }; @@ -143,7 +146,8 @@ class BindlessHeap { std::uint64_t slotRequests = 0; void sweepLocked(std::vector>& dropped); bool heldOnlyHereLocked(const void* owner, long uses) const; - void releaseStorageLocked(std::span owners, std::vector& kept); + std::optional takeStorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view, const StorageTexture* image); + bool releaseUncachedLocked(std::vector>& dropped, bool storagePhase); void dropStorageLocked(const void* image, std::uint32_t slot); std::optional takeSlotLocked(); std::optional takeOrSweepLocked(std::vector>& dropped); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp index 4b7a24ba125d..513ed7a34dee 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp @@ -302,7 +302,11 @@ class StorageTexture : public std::enable_shared_from_this { // Whether the storage cache holds this image (set and cleared by the cache under its mutex, the // clear before the eviction's flush): what a lookup of its surface would return. bool Cached() const { return cached.load(std::memory_order_acquire); } - void SetCached(bool value) { cached.store(value, std::memory_order_release); } + void SetCached(bool value) { + if (value) everCached.store(true, std::memory_order_relaxed); + cached.store(value, std::memory_order_release); + } + bool LeftCache() const { return everCached.load(std::memory_order_relaxed) && !cached.load(std::memory_order_acquire); } // The pending image whose surface starts at `address` and covers at least `bytes` (a mip chain // contains a descriptor of its first mips), if any; the caller decides whether the geometry fits // (Texture::CanCopyFrom, ResidentPresentable). @@ -691,6 +695,7 @@ class StorageTexture : public std::enable_shared_from_this { // no fill may put results into this one (guarded by the live-image registry lock). bool released = false; std::atomic cached{false}; + std::atomic everCached{false}; // The present a consumer last proved the image current at (NoteProved). mutable std::atomic provedPresent{0}; // Hook skips of this image since FlushPending last listed it (AccessKeptByCpu), the read site diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index dcc16333d304..7133fd94a24c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -252,10 +252,19 @@ std::optional BindlessHeap::TextureSlot(std::uint32_t kind, const owner.texture = texture; texture->AddHeapHold(); noteTakenLocked(dropped); + if (const auto& source = texture->SharedStorageSource(); source != nullptr && source->LeftCache()) NoteStorageEvicted(); return slot; } std::optional BindlessHeap::StorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view) { + return takeStorageSlot(kind, std::move(owner), view, nullptr); +} + +std::optional BindlessHeap::StorageSlot(std::uint32_t kind, const std::shared_ptr& image, VkImageView view) { + return takeStorageSlot(kind, image, view, image.get()); +} + +std::optional BindlessHeap::takeStorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view, const StorageTexture* image) { if (!Abi::GpuHeapStorageKind(kind) || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid storage slot request"); std::vector> dropped; @@ -268,8 +277,11 @@ std::optional BindlessHeap::StorageSlot(std::uint32_t kind, std:: if (!slot) return std::nullopt; noteTakenLocked(dropped); writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); - claimSlotLocked(key, *slot).storage = std::move(owner); + auto& claimed = claimSlotLocked(key, *slot); + claimed.storage = std::move(owner); + claimed.image = image; storageSlots[key.texture].push_back(*slot); + if (image != nullptr && image->LeftCache()) NoteStorageEvicted(); return slot; } @@ -326,6 +338,7 @@ void BindlessHeap::freeSlotLocked(std::uint32_t slot) { if (slots.empty()) storageSlots.erase(found); } textureSlots.erase(owner.key); + owner.image = nullptr; owner.key = {}; ++owner.generation; freeSlots.push_back(slot); @@ -374,17 +387,39 @@ bool BindlessHeap::heldOnlyHereLocked(const void* owner, long uses) const { return uses <= slots; } -void BindlessHeap::releaseStorageLocked(std::span evicted, std::vector& kept) { - for (const auto* image : evicted) { - const auto found = storageSlots.find(image); - if (found == storageSlots.end()) continue; - const auto& first = owners[found->second.front()].storage; - if (first == nullptr || !heldOnlyHereLocked(image, first.use_count())) { - kept.push_back(image); +bool BindlessHeap::releaseUncachedLocked(std::vector>& dropped, bool storagePhase) { + bool heldElsewhere = false; + const auto firstDropped = dropped.size(); + std::vector> images; + for (std::uint32_t slot = SamplerKind; slot < owners.size(); ++slot) { + auto& owner = owners[slot]; + if (owner.storage != nullptr) { + if (!storagePhase) continue; + if (owner.image == nullptr || !owner.image->LeftCache()) continue; + const auto found = storageSlots.find(owner.key.texture); + if (found == storageSlots.end() || found->second.front() != slot) continue; + if (!heldOnlyHereLocked(owner.key.texture, owner.storage.use_count())) { + heldElsewhere = true; + continue; + } + images.emplace_back(owner.key.texture, slot); + continue; + } + if (storagePhase || owner.texture == nullptr) continue; + const auto& source = owner.texture->SharedStorageSource(); + if (source == nullptr || !source->LeftCache()) continue; + if (owner.texture.use_count() > static_cast(owner.texture->HeapHolds())) { + heldElsewhere = true; continue; } - dropStorageLocked(image, found->second.front()); + heldElsewhere = true; + dropped.push_back(std::move(owner.texture)); + freeSlotLocked(slot); + slotSerial.fetch_add(1, std::memory_order_release); } + for (auto index = firstDropped; index < dropped.size(); ++index) dropped[index]->DropHeapHold(); + for (const auto& [image, slot] : images) dropStorageLocked(image, slot); + return heldElsewhere; } void BindlessHeap::dropStorageLocked(const void* image, std::uint32_t slot) { @@ -431,15 +466,7 @@ namespace { std::atomic sweepDue{false}; -std::mutex& evictedStorageMutex() { - static auto& mutex = *new std::mutex(); - return mutex; -} - -std::vector& evictedStorage() { - static auto& list = *new std::vector(); - return list; -} +std::atomic uncachedPending{false}; std::atomic refusedSweepChecks{0}; constexpr std::uint32_t RefusedSweepInterval = 64u; @@ -449,44 +476,45 @@ void BindlessHeap::NoteSweepDue() { sweepDue.store(true, std::memory_order_relaxed); } -void BindlessHeap::NoteStorageEvicted(const void* owner) { - if (owner == nullptr) return; - std::lock_guard lock(evictedStorageMutex()); - evictedStorage().push_back(owner); +void BindlessHeap::NoteStorageEvicted() { + uncachedPending.store(true, std::memory_order_relaxed); } void BindlessHeap::SweepIfDue() { - std::vector evicted; - { - std::lock_guard lock(evictedStorageMutex()); - evicted.swap(evictedStorage()); - } + const bool uncached = uncachedPending.load(std::memory_order_relaxed) && uncachedPending.exchange(false, std::memory_order_relaxed); const bool due = sweepDue.load(std::memory_order_relaxed) && sweepDue.exchange(false, std::memory_order_relaxed); const bool retry = !due && nearlyFull.load(std::memory_order_relaxed) && refusedSweepChecks.fetch_add(1, std::memory_order_relaxed) % RefusedSweepInterval == RefusedSweepInterval - 1u; - if (!due && !retry && evicted.empty()) return; - std::sort(evicted.begin(), evicted.end()); - evicted.erase(std::unique(evicted.begin(), evicted.end()), evicted.end()); - std::vector> dropped; - SweptStorageRelease swept; - std::vector> droppedSamplers; - std::vector kept; - std::lock_guard heapsLock(heapsMutex()); + if (!due && !retry && !uncached) return; + bool again = false; bool room = true; - for (auto& [device, heap] : heaps()) { - if (heap == nullptr) continue; - std::lock_guard lock(heap->mutex); - if (due || retry) { - heap->sweepLocked(dropped); - heap->sweepSamplersLocked(droppedSamplers); + { + std::vector> dropped; + SweptStorageRelease swept; + std::vector> droppedSamplers; + std::lock_guard heapsLock(heapsMutex()); + for (auto& [device, heap] : heaps()) { + if (heap == nullptr) continue; + std::lock_guard lock(heap->mutex); + if (due || retry) { + heap->sweepLocked(dropped); + heap->sweepSamplersLocked(droppedSamplers); + } + if (uncached && heap->releaseUncachedLocked(dropped, false)) again = true; } - heap->releaseStorageLocked(evicted, kept); - room = room && heap->roomLocked(); } - if (!kept.empty()) { - std::lock_guard lock(evictedStorageMutex()); - evictedStorage().insert(evictedStorage().end(), kept.begin(), kept.end()); + { + std::vector> none; + SweptStorageRelease swept; + std::lock_guard heapsLock(heapsMutex()); + for (auto& [device, heap] : heaps()) { + if (heap == nullptr) continue; + std::lock_guard lock(heap->mutex); + if (uncached && heap->releaseUncachedLocked(none, true)) again = true; + room = room && heap->roomLocked(); + } } + if (again) NoteStorageEvicted(); if (room && nearlyFull.exchange(false, std::memory_order_relaxed)) std::fprintf(stderr, "[gpu-heap] a sweep left twice the margin of slots free; draws take the heap again\n"); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 46b8b7489fa7..c74b9fe25b00 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -1104,8 +1104,8 @@ std::list::iterator findStorageByImage(StorageTextureCache // Evicts an entry: its pending results go to guest memory first (the image may die with the entry). std::shared_ptr evictStorage(StorageTextureCache& cache, std::list::iterator it) { auto texture = it->texture; - if (GpuHeapEnabled()) BindlessHeap::NoteStorageEvicted(texture.get()); it->texture->SetCached(false); + if (GpuHeapEnabled()) BindlessHeap::NoteStorageEvicted(); noteUncached(it->texture); it->texture->Flush(); cache.bytes -= it->accounted; @@ -1393,6 +1393,7 @@ void ClearCachedTextures(VkDevice device) { } cleared.push_back(it->texture); it->texture->SetCached(false); + if (GpuHeapEnabled()) BindlessHeap::NoteStorageEvicted(); noteUncached(it->texture); storage.bytes -= it->accounted; storage.index.erase(it->key); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 71074080f750..298b85cd5bbc 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -26,6 +26,7 @@ void require(bool condition, const std::string& what) { } alignas(Texture) std::array, 8> fakeTextures{}; +alignas(StorageTexture) std::array, 3> fakeImages{}; std::shared_ptr fakeTexture(std::size_t index) { return std::shared_ptr(reinterpret_cast(fakeTextures[index].data()), [](Texture*) {}); @@ -222,15 +223,39 @@ void storageViewsComeBack(const Context& context, VkImageView view) { require(released == 4, "a sweep released " + std::to_string(released) + " of four storage owners the heap alone held, three of them in two slots each"); require(!BindlessHeap::NearlyFull(), "a sweep after every storage owner is gone takes the heap again"); - auto evicted = owner(); - for (std::uint32_t kind = 0; kind < 2u; ++kind) require(heap.StorageSlot(Abi::FirstStorageImageBinding + kind, evicted, view).has_value(), "an evicted owner's view takes a slot"); - const auto* image = evicted.get(); - BindlessHeap::NoteStorageEvicted(image); + const auto image = [&released](std::size_t index, bool cached) { + auto* pointer = reinterpret_cast(fakeImages[index].data()); + pointer->SetCached(true); + pointer->SetCached(cached); + return std::shared_ptr(pointer, [&released](StorageTexture*) { ++released; }); + }; + auto evicted = image(0, true); + auto cached = image(1, true); + for (std::uint32_t kind = 0; kind < 2u; ++kind) require(heap.StorageSlot(Abi::FirstStorageImageBinding + kind, evicted, view).has_value(), "an evicted image's view takes a slot"); + require(heap.StorageSlot(Abi::FirstStorageImageBinding, cached, view).has_value(), "a cached image takes a slot"); + evicted->SetCached(false); + BindlessHeap::NoteStorageEvicted(); BindlessHeap::SweepIfDue(); - require(released == 4, "an evicted storage owner still held outside the heap lost its slots"); + require(released == 4, "an evicted storage image still held outside the heap lost its slots"); evicted.reset(); + cached.reset(); + BindlessHeap::SweepIfDue(); + require(released == 5, "the present after an evicted storage image's last outside holder went did not release its two slots, or released the cached image the heap alone holds"); + + auto late = image(0, false); + require(heap.StorageSlot(Abi::FirstStorageImageBinding, late, view).has_value(), "an image that left the storage cache before its first slot takes one"); + BindlessHeap::SweepIfDue(); + require(released == 5, "an image that left the cache lost its slot while still held outside the heap"); + late.reset(); + BindlessHeap::SweepIfDue(); + require(released == 6, "an image that took its slot after leaving the storage cache kept it after its last outside holder went"); + + auto outside = std::shared_ptr(reinterpret_cast(fakeImages[2].data()), [&released](StorageTexture*) { ++released; }); + require(heap.StorageSlot(Abi::FirstStorageImageBinding, outside, view).has_value(), "an image made outside the storage cache takes a slot"); + outside.reset(); + BindlessHeap::NoteStorageEvicted(); BindlessHeap::SweepIfDue(); - require(released == 5, "the present after an evicted storage owner's last outside holder went did not release its two slots"); + require(released == 6, "an image the storage cache never held lost its slot without a sweep"); BindlessHeap::Release(context.device); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp index 6cfb07462053..70a72d518f11 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp @@ -1,5 +1,7 @@ #include "prx/libSceAgcDriver/Execution/include/BdaFeatures.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" @@ -534,6 +536,24 @@ void viewTests(const Context& context) { Require(heldView.expired() && heldStorage.expired(), "the evicted image outlived its last caller without a sampled lookup"); } +bool heapViewTests(const Context& context) { + if (!GpuHeapEnabled() || !context.descriptorHeap || context.hostImportAlignment == 0) return false; + Block block(context); + if (HostImportFor(context, block.Surface(0), BlockBytes) == nullptr) return false; + auto view = Sampled(context, block.Surface(0)); + Require(view->ViewsStorageImage(), "a sampled texture in host-imported memory is not a view of its storage image"); + const std::weak_ptr viewed = view; + for (std::size_t surface = 1; surface < Surfaces; ++surface) CachedStorageSurface(context, Resource(block.Surface(surface))); + Require(!view->StorageSource()->Cached(), "the heap view's storage image was not evicted"); + auto& heap = BindlessHeap::For(context); + Require(heap.TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, view, view->View(), view->Layout()).has_value(), "the view of an evicted storage image took no heap slot"); + view.reset(); + Require(!viewed.expired(), "the heap slot did not hold the view of the evicted storage image"); + BindlessHeap::SweepIfDue(); + Require(viewed.expired(), "the present after the heap became the only holder of a view of an evicted storage image kept the view, and with it the image"); + return true; +} + ShaderRecompiler::RecompileResult SampledProgram(std::uint64_t address) { ShaderRecompiler::DescriptorBinding binding{}; binding.kind = ShaderRecompiler::DescriptorKind::SampledImage; @@ -1190,6 +1210,42 @@ int main(int argc, char** argv) { if (!memory) setenv("APS5_TEXTURE_CACHE_MIB", recover ? "16" : "1", 1); setenv("APS5_TEMPLATE_AUDIT_MS", "250", 0); #endif + if (mode == "heap-view") { +#ifdef _WIN32 + _putenv_s("APS5_GPU_HEAP", "1"); +#else + setenv("APS5_GPU_HEAP", "1", 1); +#endif + std::unique_ptr heapDevice; + try { + heapDevice = std::make_unique(); + } catch (const std::exception& error) { + if (std::getenv("ANYPS5_REQUIRE_VULKAN") != nullptr) throw; + std::printf("skipped, no usable Vulkan device: %s\n", error.what()); + return VulkanTestSkipped; + } + if (!heapDevice->GraphicsContext().descriptorHeap) { + std::puts("skipped, the device has no VK_EXT_descriptor_heap"); + return VulkanTestSkipped; + } + bool tested = false; + { + const auto context = heapDevice->GraphicsContext(); + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + tested = heapViewTests(context); + ClearCachedTextures(context.device); + } + heapDevice->WaitIdle(); + } + heapDevice.reset(); + if (!tested) { + std::puts("skipped, host imports unavailable: heap views of evicted storage images not tested"); + return VulkanTestSkipped; + } + std::puts("heap view release tests passed"); + return 0; + } std::unique_ptr device; try { device = std::make_unique(!disableStorageImageMultisample); From 63dcd263e0d80e42c4de61282adae2db5928e4be Mon Sep 17 00:00:00 2001 From: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:58:58 -0700 Subject: [PATCH 048/269] test(agc): put libc on the heap-view sampled cache test's Windows PATH agc_driver_sampled_cache_budget_heap_view runs agc_driver_sampled_cache_budget_tests like its siblings, but it was missing from their if(WIN32) PATH list, so on Windows it exited 0xc0000135 (DLL not found) before main(). --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index fc40d5c94333..b05cc17b1b6a 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -3367,7 +3367,7 @@ if(BUILD_TESTING) add_test(NAME agc_driver_resource_cache_lookup_changed COMMAND agc_driver_sampled_cache_budget_tests resource-lookup-changed) set_tests_properties(agc_driver_resource_cache_storage_admission agc_driver_resource_cache_oversized_storage_admission agc_driver_resource_cache_storage_clear agc_driver_resource_cache_replaced_texture agc_driver_resource_cache_lookup_changed PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30) if(WIN32) - set_tests_properties(agc_driver_sampled_cache_budget_memory agc_driver_sampled_cache_budget_without_storage_image_multisample agc_driver_resource_cache_storage_admission agc_driver_resource_cache_oversized_storage_admission agc_driver_resource_cache_storage_clear agc_driver_resource_cache_replaced_texture agc_driver_resource_cache_lookup_changed PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(agc_driver_sampled_cache_budget_memory agc_driver_sampled_cache_budget_heap_view agc_driver_sampled_cache_budget_without_storage_image_multisample agc_driver_resource_cache_storage_admission agc_driver_resource_cache_oversized_storage_admission agc_driver_resource_cache_storage_clear agc_driver_resource_cache_replaced_texture agc_driver_resource_cache_lookup_changed PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() # The driver draw test again with the draw key off: the draw cache then keys on the decoded vertex From 4aa75cbe08252418f94a49f853c258231779c433 Mon Sep 17 00:00:00 2001 From: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:53:35 +0000 Subject: [PATCH 049/269] refactor(agc): move the heap walk memo into its own header HeapWalkEntry, its constants and HeapWalkMemo move unchanged from HeapStages.cpp's anonymous namespace to HeapWalkMemo.hpp in AgcDriver::DriverDetail, so a unit test can hold a memo of its own. The per-thread memo and every caller stay in HeapStages.cpp. No behaviour change. --- .../include/Driver/Draw/HeapWalkMemo.hpp | 71 +++++++++++++++++++ .../Execution/src/Driver/Draw/HeapStages.cpp | 56 +-------------- 2 files changed, 72 insertions(+), 55 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp new file mode 100644 index 000000000000..fe724a6ba6fb --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp @@ -0,0 +1,71 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_HEAPWALKMEMO_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_HEAPWALKMEMO_HPP + +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::DriverDetail { + +struct HeapWalkEntry { + std::uint64_t variant = 0; + std::uint64_t shaderBase = 0; + std::uint32_t pushOffset = 0; + std::vector userData; + std::vector> ranges; + std::vector values; + std::vector> accessible; + ShaderRecompiler::SrtUserDataUse userDataUse; + std::shared_ptr capture; + std::shared_ptr result; + std::shared_ptr words; +}; + +constexpr std::size_t HeapWalkWays = 4; + +constexpr std::size_t HeapWalkMemoKeys = 16384; + +constexpr std::size_t HeapWalkDrain = 2; + +constexpr std::size_t HeapWalkSeenKeys = 1u << 16; + +struct HeapWalkMemo { + std::unordered_map> current; + std::unordered_map> previous; + std::vector seen = std::vector(HeapWalkSeenKeys, 0); + + bool admit(std::uint64_t key) { + auto& last = seen[(key ^ (key >> 29)) & (HeapWalkSeenKeys - 1u)]; + if (last == key) return true; + last = key; + return false; + } + + std::vector* find(std::uint64_t key) { + if (const auto found = current.find(key); found != current.end()) return &found->second; + const auto old = previous.find(key); + if (old == previous.end()) return nullptr; + auto moved = std::move(old->second); + previous.erase(old); + auto& ways = slot(key); + ways = std::move(moved); + return &ways; + } + + std::vector& slot(std::uint64_t key) { + for (std::size_t drained = 0; drained < HeapWalkDrain && !previous.empty(); ++drained) previous.erase(previous.begin()); + if (current.size() >= HeapWalkMemoKeys && !current.contains(key)) { + previous = std::move(current); + current.clear(); + } + return current[key]; + } +}; + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 9b05e143cbb6..b02b45b2dfb8 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -229,61 +230,6 @@ bool SampleHeapStageVerify() { namespace { -struct HeapWalkEntry { - std::uint64_t variant = 0; - std::uint64_t shaderBase = 0; - std::uint32_t pushOffset = 0; - std::vector userData; - std::vector> ranges; - std::vector values; - std::vector> accessible; - ShaderRecompiler::SrtUserDataUse userDataUse; - std::shared_ptr capture; - std::shared_ptr result; - std::shared_ptr words; -}; - -constexpr std::size_t HeapWalkWays = 4; - -constexpr std::size_t HeapWalkMemoKeys = 16384; - -constexpr std::size_t HeapWalkDrain = 2; - -constexpr std::size_t HeapWalkSeenKeys = 1u << 16; - -struct HeapWalkMemo { - std::unordered_map> current; - std::unordered_map> previous; - std::vector seen = std::vector(HeapWalkSeenKeys, 0); - - bool admit(std::uint64_t key) { - auto& last = seen[(key ^ (key >> 29)) & (HeapWalkSeenKeys - 1u)]; - if (last == key) return true; - last = key; - return false; - } - - std::vector* find(std::uint64_t key) { - if (const auto found = current.find(key); found != current.end()) return &found->second; - const auto old = previous.find(key); - if (old == previous.end()) return nullptr; - auto moved = std::move(old->second); - previous.erase(old); - auto& ways = slot(key); - ways = std::move(moved); - return &ways; - } - - std::vector& slot(std::uint64_t key) { - for (std::size_t drained = 0; drained < HeapWalkDrain && !previous.empty(); ++drained) previous.erase(previous.begin()); - if (current.size() >= HeapWalkMemoKeys && !current.contains(key)) { - previous = std::move(current); - current.clear(); - } - return current[key]; - } -}; - HeapWalkMemo& heapWalkMemo() { struct WalkMemoStorage {}; auto& memo = HostThreadLocal(); From b7ac0d617923b03f45ebf7094836d3a97c5cc90f Mon Sep 17 00:00:00 2001 From: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:57:52 +0000 Subject: [PATCH 050/269] fix(agc): cap the heap walk memo by bytes The heap walk memo was capped at 16,384 keys per generation, not by size. Each entry pins its walk's ranges and values, the resource capture, the materialized result and the stage words, so in Resident Evil Village one thread's memo grew to 7,400 MiB over 10,638 keys without reaching the key cap, and its lookups slowed from 2 to 120 us. Each entry is now charged when it is stored, the way the recompiler's result memo charges its results: its struct, the capacity of its vectors, and the result, capture and words it holds. The charge is credited whenever the entry goes: a fifth way, a drained or replaced previous generation, or a trim. When the memo holds more than its budget, it drops its previous generation, then the oldest stored entries of the current one until it is back under three quarters of the budget, releasing their results. The budget is per thread's memo: APS5_HEAP_WALK_MEMO_MB, 256 MiB by default as for the result memo, and 0 keeps only the key cap. The key cap, the admit rule and the hit path are unchanged. Test: agc_driver_heap_walk_memo. --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 23 +++- .../include/Driver/Draw/HeapWalkMemo.hpp | 34 +++++- .../Execution/src/Driver/Draw/HeapStages.cpp | 109 +++++++++++++++++- .../libSceAgcDriver/tests/HeapWalkMemo.cpp | 97 ++++++++++++++++ docs/dev/ENVIRONMENT.md | 1 + 5 files changed, 258 insertions(+), 6 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index b05cc17b1b6a..d923c3edfd78 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -1633,6 +1633,27 @@ target_link_libraries(agc_driver_heap_slots_tests PRIVATE set_target_properties(agc_driver_heap_slots_tests PROPERTIES CXX_EXTENSIONS OFF) configure_windows_unwind(agc_driver_heap_slots_tests) +add_test_executable(agc_driver_heap_walk_memo_tests EXCLUDE_FROM_ALL + tests/HeapWalkMemo.cpp +) + +target_include_directories(agc_driver_heap_walk_memo_tests PRIVATE + ${LIBS_INCLUDE_DIR} + $ + ${CMAKE_SOURCE_DIR}/core/shader/recompiler + ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} + ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR} +) + +target_link_libraries(agc_driver_heap_walk_memo_tests PRIVATE + libSceAgcDriver + SDL2-static + libc +) + +set_target_properties(agc_driver_heap_walk_memo_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_driver_heap_walk_memo_tests) + set(agcBufferUpdateSource ${CMAKE_CURRENT_SOURCE_DIR}/tests/shaders/BufferUpdate.comp) set(agcBufferUpdateSpv ${agcTestShaderGeneratedRoot}/BufferUpdate.spv) set(agcBufferUpdateHeader ${agcTestShaderGeneratedRoot}/BufferUpdate_spv.h) @@ -2819,7 +2840,7 @@ if(BUILD_TESTING) if(WIN32) set_tests_properties(agc_shader_bindless agc_shader_selected_records_image_limit agc_shader_selected_records_pair_limit agc_shader_selected_records_direct_image_limit agc_shader_selected_records_direct_pair_limit agc_shader_srt_read_patching agc_shader_type_zero_image_materialization agc_shader_frontend_pair agc_shader_frontend_pair_off agc_shader_layout_pair agc_shader_layout_pair_off agc_shader_result_memo_budget agc_shader_result_memo_budget_threads agc_shader_result_memo_budget_masked agc_shader_entry_lane_proof_budget PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() - foreach(agcTest IN ITEMS agc_vertex_input_tests agc_mesh_output_budget_tests agc_shared_write_tests agc_copy_guest_bytes_tests agc_locks_tests agc_driver_tests agc_shader_memory_tests agc_structurizer_tests agc_spirv_module_tests agc_dpp_write_tests agc_masked_select_tests agc_ir_reclaim_tests agc_vector_window_tests agc_constant_bit_test_tests agc_integer_narrowing_tests agc_scalar_select_mask_tests agc_vertex_input_validation_tests agc_vop1_control_decode_tests agc_validate_program_tests agc_pass_hazards_tests agc_barrier_batch_tests agc_shader_disk_cache_tests agc_screenshot_tests agc_shader_device_profile_tests agc_placeholder_images_tests agc_shader_control_flow_tests agc_driver_flip_tests agc_driver_pm4_tests agc_driver_graphics_tests agc_driver_bda_device_tests agc_driver_mesh_tests agc_driver_cmask_fast_clear_tests agc_formatted_buffer_once_tests agc_formatted_buffer_byte_stores_tests ${agcExecutionTests} agc_fma_mix_once_tests agc_f16_single_convert_tests agc_driver_heap_slots_tests) + foreach(agcTest IN ITEMS agc_vertex_input_tests agc_mesh_output_budget_tests agc_shared_write_tests agc_copy_guest_bytes_tests agc_locks_tests agc_driver_tests agc_shader_memory_tests agc_structurizer_tests agc_spirv_module_tests agc_dpp_write_tests agc_masked_select_tests agc_ir_reclaim_tests agc_vector_window_tests agc_constant_bit_test_tests agc_integer_narrowing_tests agc_scalar_select_mask_tests agc_vertex_input_validation_tests agc_vop1_control_decode_tests agc_validate_program_tests agc_pass_hazards_tests agc_barrier_batch_tests agc_shader_disk_cache_tests agc_screenshot_tests agc_shader_device_profile_tests agc_placeholder_images_tests agc_shader_control_flow_tests agc_driver_flip_tests agc_driver_pm4_tests agc_driver_graphics_tests agc_driver_bda_device_tests agc_driver_mesh_tests agc_driver_cmask_fast_clear_tests agc_formatted_buffer_once_tests agc_formatted_buffer_byte_stores_tests ${agcExecutionTests} agc_fma_mix_once_tests agc_f16_single_convert_tests agc_driver_heap_slots_tests agc_driver_heap_walk_memo_tests) if(agcTest STREQUAL "agc_driver_constant_store_tests" OR agcTest STREQUAL "agc_driver_flat_apertures_tests" OR agcTest STREQUAL "agc_driver_pipeline_optimized_readback_tests" OR agcTest STREQUAL "agc_driver_rcp_hardware_tests") continue() endif() diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp index fe724a6ba6fb..6c0b2b2e222e 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp @@ -23,6 +23,8 @@ struct HeapWalkEntry { std::shared_ptr capture; std::shared_ptr result; std::shared_ptr words; + std::uint64_t bytes = 0; + std::uint64_t stored = 0; }; constexpr std::size_t HeapWalkWays = 4; @@ -33,10 +35,17 @@ constexpr std::size_t HeapWalkDrain = 2; constexpr std::size_t HeapWalkSeenKeys = 1u << 16; +std::uint64_t HeapWalkEntryBytes(const HeapWalkEntry& entry); + +std::uint64_t HeapWalkMemoBudget(); + struct HeapWalkMemo { std::unordered_map> current; std::unordered_map> previous; std::vector seen = std::vector(HeapWalkSeenKeys, 0); + std::uint64_t heldBytes = 0; + std::uint64_t stores = 0; + std::uint64_t budget = HeapWalkMemoBudget(); bool admit(std::uint64_t key) { auto& last = seen[(key ^ (key >> 29)) & (HeapWalkSeenKeys - 1u)]; @@ -57,13 +66,36 @@ struct HeapWalkMemo { } std::vector& slot(std::uint64_t key) { - for (std::size_t drained = 0; drained < HeapWalkDrain && !previous.empty(); ++drained) previous.erase(previous.begin()); + for (std::size_t drained = 0; drained < HeapWalkDrain && !previous.empty(); ++drained) { + release(previous.begin()->second); + previous.erase(previous.begin()); + } if (current.size() >= HeapWalkMemoKeys && !current.contains(key)) { + for (const auto& [old, ways] : previous) release(ways); previous = std::move(current); current.clear(); } return current[key]; } + + void remember(std::uint64_t key, HeapWalkEntry entry) { + auto& ways = slot(key); + if (ways.size() >= HeapWalkWays) { + heldBytes -= ways.back().bytes; + ways.pop_back(); + } + entry.bytes = HeapWalkEntryBytes(entry); + entry.stored = ++stores; + heldBytes += entry.bytes; + ways.insert(ways.begin(), std::move(entry)); + if (budget != 0 && heldBytes > budget) trim(); + } + + void release(const std::vector& ways) { + for (const auto& entry : ways) heldBytes -= entry.bytes; + } + + void trim(); }; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index b02b45b2dfb8..8304b9854b3c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -230,6 +230,109 @@ bool SampleHeapStageVerify() { namespace { +template +std::uint64_t vectorBytes(const std::vector& values) { + return static_cast(values.capacity()) * sizeof(TValue); +} + +std::uint64_t vectorBytes(const std::vector& values) { + return static_cast(values.capacity() + 7u) / 8u; +} + +template +std::uint64_t sharedBytes(const ShaderRecompiler::SharedValues& values) { + return static_cast(values.size()) * sizeof(TValue); +} + +std::uint64_t descriptorBindingBytes(const ShaderRecompiler::DescriptorBinding& binding) { + return vectorBytes(binding.guestDescriptor) + vectorBytes(binding.samplerDepthCompare) + vectorBytes(binding.imageWritten) + + vectorBytes(binding.imageDepthCompare) + vectorBytes(binding.imageAtomic) + vectorBytes(binding.imageAtomic64) + + vectorBytes(binding.imageShapes) + vectorBytes(binding.bufferAtomic) + vectorBytes(binding.bufferWritten) + + vectorBytes(binding.samplerUnnormalized) + vectorBytes(binding.samplerIntegerBorder) + vectorBytes(binding.samplerCoordinatesIgnored) + + vectorBytes(binding.imageUnnormalized) + vectorBytes(binding.imageUnnormalizedBaseLevel) + vectorBytes(binding.imageSamplers) + + vectorBytes(binding.bufferRead) + vectorBytes(binding.bufferExtent); +} + +std::uint64_t resultBytes(const ShaderRecompiler::RecompileResult& result) { + auto bytes = sizeof(ShaderRecompiler::RecompileResult) + vectorBytes(result.vertexInputPatches) + vectorBytes(result.runtimeImageResources) + + vectorBytes(result.vertexInputs) + vectorBytes(result.parameterExports) + vectorBytes(result.fragmentParameters) + + vectorBytes(result.stencilReferences) + vectorBytes(result.specialization) + vectorBytes(result.heapSlotWords) + + vectorBytes(result.bindings) + vectorBytes(result.pushConstants) + vectorBytes(result.vertexAttributes) + + vectorBytes(result.imageTablePoison) + vectorBytes(result.imageTableRanges) + vectorBytes(result.imageTableReadRanges) + + vectorBytes(result.heapUserWords) + vectorBytes(result.shaderDataUserWords); + if (result.meshBarycentrics.has_value()) bytes += vectorBytes(result.meshBarycentrics->parameters); + for (const auto& binding : result.bindings) bytes += descriptorBindingBytes(binding); + for (const auto& ranges : result.imageTableReadRanges) bytes += vectorBytes(ranges); + return bytes; +} + +std::uint64_t captureBytes(const ShaderRecompiler::ResourceCapture& capture) { + const auto& snapshot = capture.snapshot; + auto bytes = sizeof(ShaderRecompiler::ResourceCapture) + vectorBytes(snapshot.buffers) + vectorBytes(snapshot.images) + + vectorBytes(snapshot.samplers) + vectorBytes(snapshot.flattenedSrt) + vectorBytes(snapshot.userData) + + vectorBytes(snapshot.srtPoison) + vectorBytes(snapshot.tables.tables) + vectorBytes(snapshot.tables.ranges) + + vectorBytes(capture.readTrace.leaves) + vectorBytes(capture.readTrace.otherReads) + vectorBytes(capture.userDataUse.reads); + for (const auto& column : snapshot.tables.tables) + bytes += sharedBytes(column.codes) + sharedBytes(column.words) + sharedBytes(column.readRanges); + return bytes; +} + +std::uint64_t wordsBytes(const ShaderRecompiler::HeapStageWords& words) { + auto bytes = sizeof(ShaderRecompiler::HeapStageWords) + vectorBytes(words.userData) + vectorBytes(words.flattenedSrt) + + vectorBytes(words.vertexAttributes) + vectorBytes(words.bindings); + for (const auto& binding : words.bindings) bytes += vectorBytes(binding); + return bytes; +} + +} + +std::uint64_t HeapWalkEntryBytes(const HeapWalkEntry& entry) { + auto bytes = sizeof(HeapWalkEntry) + vectorBytes(entry.userData) + vectorBytes(entry.ranges) + vectorBytes(entry.values) + + vectorBytes(entry.accessible) + vectorBytes(entry.userDataUse.reads); + if (entry.capture != nullptr) bytes += captureBytes(*entry.capture); + if (entry.result != nullptr) bytes += resultBytes(*entry.result); + if (entry.words != nullptr) bytes += wordsBytes(*entry.words); + return bytes; +} + +std::uint64_t HeapWalkMemoBudget() { + static const std::uint64_t budget = [] { + const char* value = std::getenv("APS5_HEAP_WALK_MEMO_MB"); + const std::uint64_t megabytes = value == nullptr || *value == '\0' ? 256u : std::strtoull(value, nullptr, 10); + return megabytes << 20u; + }(); + return budget; +} + +void HeapWalkMemo::trim() { + for (const auto& [key, ways] : previous) release(ways); + previous.clear(); + if (heldBytes <= budget) return; + std::vector> stamps; + for (const auto& [key, ways] : current) { + for (const auto& entry : ways) stamps.emplace_back(entry.stored, entry.bytes); + } + std::sort(stamps.begin(), stamps.end()); + const auto excess = heldBytes - budget / 4u * 3u; + std::uint64_t freed = 0; + std::uint64_t threshold = 0; + for (const auto& [stored, bytes] : stamps) { + threshold = stored; + freed += bytes; + if (freed >= excess) break; + } + for (auto it = current.begin(); it != current.end();) { + std::erase_if(it->second, [&](const HeapWalkEntry& entry) { + if (entry.stored > threshold) return false; + heldBytes -= entry.bytes; + return true; + }); + it = it->second.empty() ? current.erase(it) : std::next(it); + } +} + +namespace { + HeapWalkMemo& heapWalkMemo() { struct WalkMemoStorage {}; auto& memo = HostThreadLocal(); @@ -344,10 +447,7 @@ void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderI const std::vector& values, const AddressRanges& accessible, const std::shared_ptr& capture, const std::shared_ptr& result, const ShaderRecompiler::HeapStageWords& words) { - auto& ways = heapWalkMemo().slot(memoKey); - if (ways.size() >= HeapWalkWays) ways.pop_back(); - ways.emplace(ways.begin()); - auto& entry = ways.front(); + HeapWalkEntry entry; entry.variant = invocation.VariantId(); entry.pushOffset = invocation.Request().layout.pushConstantOffsetBytes; entry.shaderBase = shaderBase; @@ -359,6 +459,7 @@ void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderI entry.capture = capture; entry.result = result; entry.words = std::make_shared(words); + heapWalkMemo().remember(memoKey, std::move(entry)); } } diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp new file mode 100644 index 000000000000..87a1aebadd69 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp @@ -0,0 +1,97 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::DriverDetail::HeapWalkEntry; +using AgcDriver::DriverDetail::HeapWalkEntryBytes; +using AgcDriver::DriverDetail::HeapWalkMemo; +using AgcDriver::DriverDetail::HeapWalkMemoKeys; + +void require(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +HeapWalkEntry sizedEntry(std::size_t words, std::shared_ptr result = nullptr) { + HeapWalkEntry entry; + entry.values.resize(words); + entry.values.shrink_to_fit(); + entry.result = std::move(result); + return entry; +} + +std::uint64_t heldBytes(const HeapWalkMemo& memo) { + std::uint64_t bytes = 0; + for (const auto* generation : {&memo.current, &memo.previous}) { + for (const auto& [key, ways] : *generation) { + for (const auto& entry : ways) bytes += HeapWalkEntryBytes(entry); + } + } + return bytes; +} + +void requireWithinBudget(const HeapWalkMemo& memo, const std::string& where) { + const auto held = heldBytes(memo); + require(held == memo.heldBytes, where + ": the heap walk memo charged " + std::to_string(memo.heldBytes) + " bytes for the " + std::to_string(held) + " it holds"); + require(held <= memo.budget, where + ": the heap walk memo holds " + std::to_string(held) + " bytes, over its budget of " + std::to_string(memo.budget)); +} + +void oldestEntriesDroppedTests() { + constexpr std::size_t words = 4096; + require(HeapWalkEntryBytes(sizedEntry(words)) == sizeof(HeapWalkEntry) + words * sizeof(std::uint32_t), "a heap walk entry is not charged its struct and the capacity of its vectors"); + const auto entryBytes = HeapWalkEntryBytes(sizedEntry(words, std::make_shared())); + HeapWalkMemo memo; + memo.budget = 16 * entryBytes; + constexpr std::uint64_t keys = 64; + std::vector> results; + for (std::uint64_t key = 1; key <= keys; ++key) { + auto result = std::make_shared(); + results.push_back(result); + memo.remember(key, sizedEntry(words, std::move(result))); + requireWithinBudget(memo, "after key " + std::to_string(key)); + } + require(memo.find(1) == nullptr && memo.find(keys / 2) == nullptr, "the oldest heap walk entries stayed past the budget"); + require(results.front().expired() && results[keys / 2 - 1].expired(), "a heap walk entry the budget dropped still holds its result"); + const auto* newest = memo.find(keys); + require(newest != nullptr && newest->size() == 1 && newest->front().values.size() == words, "the newest heap walk entry is not findable under the budget"); + require(!results.back().expired(), "the newest heap walk entry lost its result"); + std::cout << "the heap walk memo keeps " << memo.current.size() << " of " << keys << " entries within its budget of " << memo.budget << " bytes\n"; +} + +void previousGenerationDroppedFirstTests() { + const auto tinyBytes = HeapWalkEntryBytes(sizedEntry(1)); + constexpr std::size_t largeWords = std::size_t{2} << 20u; + const auto largeBytes = HeapWalkEntryBytes(sizedEntry(largeWords)); + HeapWalkMemo memo; + memo.budget = largeBytes + 64 * tinyBytes; + require((HeapWalkMemoKeys + 1) * tinyBytes < memo.budget, "the generation fixture does not fit its budget"); + for (std::uint64_t key = 1; key <= HeapWalkMemoKeys + 1; ++key) memo.remember(key, sizedEntry(1)); + require(memo.previous.size() == HeapWalkMemoKeys && memo.current.size() == 1, "the heap walk memo did not start a generation at its key cap"); + requireWithinBudget(memo, "after the generation swap"); + memo.remember(HeapWalkMemoKeys + 2, sizedEntry(largeWords)); + requireWithinBudget(memo, "after the large entry"); + require(memo.previous.empty(), "the heap walk memo kept its previous generation over the budget"); + require(memo.find(HeapWalkMemoKeys + 1) != nullptr && memo.find(HeapWalkMemoKeys + 2) != nullptr, "the heap walk memo dropped current entries while its previous generation could go"); + std::cout << "the heap walk memo drops its previous generation before its current entries\n"; +} + +} + +int main() { + try { + oldestEntriesDroppedTests(); + previousGenerationDroppedFirstTests(); + std::cout << "heap walk memo budget tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "heap walk memo budget tests failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 45c538bdc83d..faff1878e6c9 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -180,6 +180,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_HANDOFF_SPIN_US` | integer | `core/libs/prx/libSceAgcDriver/Execution/include/HandoffSpin.hpp` | | microseconds a thread spins for a handed-off draw's work or for the GPU mutex before blocking, clamped to 0..10000; unset spins 150 us when the process has more than 8 usable processors and not at all otherwise | | `APS5_HEAP_MIRROR_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 24576 | budget in MiB for the heap mirrors held for registered allocations | | `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first | +| `APS5_HEAP_WALK_MEMO_MB` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | 256 | MiB each thread's GPU heap walk memo may hold across both its generations before the previous generation and then the oldest walks are dropped (0 keeps them until the 16,384-key cap rotates them out) | | `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 233415 | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | From 96f38b89a709af7b56f522a333ec3bb09803d19b Mon Sep 17 00:00:00 2001 From: milescoviello Date: Thu, 29 Oct 2026 17:25:34 +0000 Subject: [PATCH 051/269] fix(agc): match a cached draw's stages only in one heap mode The draw cache matches each stage against its own variants, so a hit could pair a GPU-mode vertex variant with a per-draw pixel variant inserted while the heap refused draws. A hit skips the mixed-stage retry, and pipeline creation failed: "a pipeline with GPU-mode stages does not map onto VK_EXT_descriptor_heap". Later stages now take only variants in the first matched stage's mode. Co-Authored-By: Claude Opus 5.5 --- .../libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp index 9b4a3ec2b4ef..6e6a1896344d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp @@ -128,6 +128,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptrstages.size() != programs.size()) miss = DrawMiss::Stages; std::uint32_t cursor = 0; + std::optional heapMode; { const GuestMemory::ReadSiteScope site(GuestMemory::ReadSite::DrawCache); @@ -141,7 +142,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptrpushOffset != cursor || (heapRefused && variant->compiled->gpuResolvedImages)) continue; + if (variant->pushOffset != cursor || (heapRefused && variant->compiled->gpuResolvedImages) || (heapMode && variant->compiled->gpuResolvedImages != *heapMode)) continue; if (programs[i].binary.stage == ShaderRecompiler::ShaderStage::Mesh && !std::equal(variant->meshIndexDescriptor.begin(), variant->meshIndexDescriptor.end(), programs[i].userData.begin() + ShaderRecompiler::MeshIndexBufferUserWord)) { if (!anyLayout) outcome = EntryOutcome::Differing; anyLayout = true; @@ -168,6 +169,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptrcompiled->gpuResolvedImages; ++stageEqual; cursor += static_cast(variant->compiled->pushConstants.size()); break; From fc7f4400ca53d517b0386e3090fcf9acc10edcf5 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 30 Oct 2026 02:36:27 +0530 Subject: [PATCH 052/269] feat(agc): report the heap walk memos' held bytes on the [gpu-heap] cost line Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/Driver/Draw/HeapStages.cpp | 10 +++++-- .../Graphics/include/BindlessHeap.hpp | 2 ++ .../Graphics/src/BindlessHeap.cpp | 27 ++++++++++++++++++- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 8304b9854b3c..d3422d8e1003 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -459,7 +459,10 @@ void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderI entry.capture = capture; entry.result = result; entry.words = std::make_shared(words); - heapWalkMemo().remember(memoKey, std::move(entry)); + auto& memo = heapWalkMemo(); + const auto heldBefore = memo.heldBytes; + memo.remember(memoKey, std::move(entry)); + Graphics::NoteHeapWalkMemoBytes(static_cast(memo.heldBytes) - static_cast(heldBefore)); } } @@ -485,7 +488,10 @@ MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocatio Graphics::HeapCostScope memoCost(Graphics::HeapCost::WalkMemo); if (memoOn) { memoKey = walkMemoKey(invocation, userData, shaderBase); - auto* found = heapWalkMemo().find(memoKey); + auto& memo = heapWalkMemo(); + const auto heldBefore = memo.heldBytes; + auto* found = memo.find(memoKey); + Graphics::NoteHeapWalkMemoBytes(static_cast(memo.heldBytes) - static_cast(heldBefore)); memoKnown = found != nullptr; for (std::size_t way = 0; found != nullptr && way < found->size(); ++way) { const auto& entry = (*found)[way]; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index ad4d65fd8d84..b92ce94ee7b3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -217,6 +217,8 @@ enum class HeapCost : std::uint8_t { Count }; bool HeapCostTimed(); + +void NoteHeapWalkMemoBytes(std::int64_t delta); void NoteHeapCost(HeapCost cost, std::uint64_t nanoseconds); class HeapCostScope { public: diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 7133fd94a24c..aa491b9975bb 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -27,6 +27,27 @@ namespace AgcDriver::Graphics { namespace { +std::atomic& walkMemoHeld() { + static std::atomic held{0}; + return held; +} + +std::atomic& walkMemoPeak() { + static std::atomic peak{0}; + return peak; +} + +} + +void NoteHeapWalkMemoBytes(std::int64_t delta) { + if (delta == 0) return; + const auto now = walkMemoHeld().fetch_add(delta, std::memory_order_relaxed) + delta; + auto peak = walkMemoPeak().load(std::memory_order_relaxed); + while (now > peak && !walkMemoPeak().compare_exchange_weak(peak, now, std::memory_order_relaxed)) {} +} + +namespace { + namespace Abi = ShaderRecompiler::RuntimeAbi; void check(VkResult result, const char* what) { @@ -978,7 +999,11 @@ void reportHeapStatistics() { std::snprintf(cost, sizeof(cost), " %s %llu x %.2f us = %.0f ms", HeapCostNames[i], printed(calls), averageUs, ns / 1e6); costs += cost; } - if (HeapCostTimed()) std::fprintf(stderr, "[gpu-heap] cost (10 s):%s\n", costs.c_str()); + if (HeapCostTimed()) { + const auto held = static_cast(std::max(walkMemoHeld().load(std::memory_order_relaxed), 0)) / 1048576.0; + const auto peak = static_cast(walkMemoPeak().load(std::memory_order_relaxed)) / 1048576.0; + std::fprintf(stderr, "[gpu-heap] cost (10 s):%s; walk memos hold %.1f MiB on all threads (peak %.1f MiB)\n", costs.c_str(), held, peak); + } const auto heapDraws = takeCount(heapRecords[heapRecordIndex(false, true)]); const auto plainDraws = takeCount(heapRecords[heapRecordIndex(false, false)]); const auto heapDispatches = takeCount(heapRecords[heapRecordIndex(true, true)]); From 981351a3916b7a760a76dc2c2dcd95fd6a1aecf0 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 30 Oct 2026 03:01:15 +0530 Subject: [PATCH 053/269] fix(agc): evict the heap walk memo by last use and charge each object it pins once Co-Authored-By: Claude Opus 5.5 --- .../include/Driver/Draw/HeapWalkMemo.hpp | 53 +++++++++++++-- .../Execution/src/Driver/Draw/HeapStages.cpp | 48 +++++++------ .../libSceAgcDriver/tests/HeapWalkMemo.cpp | 68 ++++++++++++++++++- 3 files changed, 145 insertions(+), 24 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp index 6c0b2b2e222e..8f689d25f4a1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp @@ -37,12 +37,21 @@ constexpr std::size_t HeapWalkSeenKeys = 1u << 16; std::uint64_t HeapWalkEntryBytes(const HeapWalkEntry& entry); +std::uint64_t HeapWalkEntryOwnBytes(const HeapWalkEntry& entry); + +std::uint64_t HeapWalkCaptureBytes(const ShaderRecompiler::ResourceCapture& capture); + +std::uint64_t HeapWalkResultBytes(const ShaderRecompiler::RecompileResult& result); + +std::uint64_t HeapWalkWordsBytes(const ShaderRecompiler::HeapStageWords& words); + std::uint64_t HeapWalkMemoBudget(); struct HeapWalkMemo { std::unordered_map> current; std::unordered_map> previous; std::vector seen = std::vector(HeapWalkSeenKeys, 0); + std::unordered_map> pins; std::uint64_t heldBytes = 0; std::uint64_t stores = 0; std::uint64_t budget = HeapWalkMemoBudget(); @@ -81,18 +90,54 @@ struct HeapWalkMemo { void remember(std::uint64_t key, HeapWalkEntry entry) { auto& ways = slot(key); if (ways.size() >= HeapWalkWays) { - heldBytes -= ways.back().bytes; + drop(ways.back()); ways.pop_back(); } - entry.bytes = HeapWalkEntryBytes(entry); + charge(entry); entry.stored = ++stores; - heldBytes += entry.bytes; ways.insert(ways.begin(), std::move(entry)); if (budget != 0 && heldBytes > budget) trim(); } + void touch(HeapWalkEntry& entry) { + entry.stored = ++stores; + } + + template + void pin(const std::shared_ptr& object, TSize size) { + if (object == nullptr) return; + auto& held = pins[object.get()]; + if (held.first++ == 0) { + held.second = size(*object); + heldBytes += held.second; + } + } + + void unpin(const void* object) { + if (object == nullptr) return; + const auto held = pins.find(object); + if (--held->second.first != 0) return; + heldBytes -= held->second.second; + pins.erase(held); + } + + void charge(HeapWalkEntry& entry) { + entry.bytes = HeapWalkEntryOwnBytes(entry); + heldBytes += entry.bytes; + pin(entry.capture, HeapWalkCaptureBytes); + pin(entry.result, HeapWalkResultBytes); + pin(entry.words, HeapWalkWordsBytes); + } + + void drop(const HeapWalkEntry& entry) { + heldBytes -= entry.bytes; + unpin(entry.capture.get()); + unpin(entry.result.get()); + unpin(entry.words.get()); + } + void release(const std::vector& ways) { - for (const auto& entry : ways) heldBytes -= entry.bytes; + for (const auto& entry : ways) drop(entry); } void trim(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index d3422d8e1003..81b500d96641 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -286,9 +286,25 @@ std::uint64_t wordsBytes(const ShaderRecompiler::HeapStageWords& words) { } +std::uint64_t HeapWalkEntryOwnBytes(const HeapWalkEntry& entry) { + return sizeof(HeapWalkEntry) + vectorBytes(entry.userData) + vectorBytes(entry.ranges) + vectorBytes(entry.values) + + vectorBytes(entry.accessible) + vectorBytes(entry.userDataUse.reads); +} + +std::uint64_t HeapWalkCaptureBytes(const ShaderRecompiler::ResourceCapture& capture) { + return captureBytes(capture); +} + +std::uint64_t HeapWalkResultBytes(const ShaderRecompiler::RecompileResult& result) { + return resultBytes(result); +} + +std::uint64_t HeapWalkWordsBytes(const ShaderRecompiler::HeapStageWords& words) { + return wordsBytes(words); +} + std::uint64_t HeapWalkEntryBytes(const HeapWalkEntry& entry) { - auto bytes = sizeof(HeapWalkEntry) + vectorBytes(entry.userData) + vectorBytes(entry.ranges) + vectorBytes(entry.values) + - vectorBytes(entry.accessible) + vectorBytes(entry.userDataUse.reads); + auto bytes = HeapWalkEntryOwnBytes(entry); if (entry.capture != nullptr) bytes += captureBytes(*entry.capture); if (entry.result != nullptr) bytes += resultBytes(*entry.result); if (entry.words != nullptr) bytes += wordsBytes(*entry.words); @@ -310,24 +326,17 @@ void HeapWalkMemo::trim() { if (heldBytes <= budget) return; std::vector> stamps; for (const auto& [key, ways] : current) { - for (const auto& entry : ways) stamps.emplace_back(entry.stored, entry.bytes); + for (const auto& entry : ways) stamps.emplace_back(entry.stored, key); } std::sort(stamps.begin(), stamps.end()); - const auto excess = heldBytes - budget / 4u * 3u; - std::uint64_t freed = 0; - std::uint64_t threshold = 0; - for (const auto& [stored, bytes] : stamps) { - threshold = stored; - freed += bytes; - if (freed >= excess) break; - } - for (auto it = current.begin(); it != current.end();) { - std::erase_if(it->second, [&](const HeapWalkEntry& entry) { - if (entry.stored > threshold) return false; - heldBytes -= entry.bytes; - return true; - }); - it = it->second.empty() ? current.erase(it) : std::next(it); + const auto target = budget / 4u * 3u; + for (const auto& [stored, key] : stamps) { + if (heldBytes <= target) break; + const auto ways = current.find(key); + const auto entry = std::find_if(ways->second.begin(), ways->second.end(), [&](const HeapWalkEntry& way) { return way.stored == stored; }); + drop(*entry); + ways->second.erase(entry); + if (ways->second.empty()) current.erase(ways); } } @@ -494,9 +503,10 @@ MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocatio Graphics::NoteHeapWalkMemoBytes(static_cast(memo.heldBytes) - static_cast(heldBefore)); memoKnown = found != nullptr; for (std::size_t way = 0; found != nullptr && way < found->size(); ++way) { - const auto& entry = (*found)[way]; + auto& entry = (*found)[way]; if (!sameWalkInputs(entry, invocation, userData, shaderBase)) continue; if (!rangesSettled(entry.ranges, before.get(), generation)) break; + memo.touch(entry); guardRanges(entry.ranges); if (sharedWords != nullptr) *sharedWords = entry.words; else *words = *entry.words; diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp index 87a1aebadd69..136b7bb8802c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include namespace { @@ -29,11 +30,18 @@ HeapWalkEntry sizedEntry(std::size_t words, std::shared_ptr pinned; for (const auto* generation : {&memo.current, &memo.previous}) { for (const auto& [key, ways] : *generation) { - for (const auto& entry : ways) bytes += HeapWalkEntryBytes(entry); + for (const auto& entry : ways) { + bytes += AgcDriver::DriverDetail::HeapWalkEntryOwnBytes(entry); + if (entry.capture != nullptr && pinned.insert(entry.capture.get()).second) bytes += AgcDriver::DriverDetail::HeapWalkCaptureBytes(*entry.capture); + if (entry.result != nullptr && pinned.insert(entry.result.get()).second) bytes += AgcDriver::DriverDetail::HeapWalkResultBytes(*entry.result); + if (entry.words != nullptr && pinned.insert(entry.words.get()).second) bytes += AgcDriver::DriverDetail::HeapWalkWordsBytes(*entry.words); + } } } + require(pinned.size() == memo.pins.size(), "the heap walk memo pins " + std::to_string(memo.pins.size()) + " objects for the " + std::to_string(pinned.size()) + " its entries hold"); return bytes; } @@ -82,12 +90,70 @@ void previousGenerationDroppedFirstTests() { std::cout << "the heap walk memo drops its previous generation before its current entries\n"; } +void hitEntriesKeptTests() { + constexpr std::size_t words = 4096; + const auto entryBytes = HeapWalkEntryBytes(sizedEntry(words)); + HeapWalkMemo memo; + memo.budget = 4 * entryBytes; + for (std::uint64_t key = 1; key <= 4; ++key) memo.remember(key, sizedEntry(words)); + auto* hit = memo.find(1); + require(hit != nullptr && hit->size() == 1, "the first heap walk entry is not findable under the budget"); + memo.touch(hit->front()); + memo.remember(5, sizedEntry(words)); + requireWithinBudget(memo, "after the trim"); + require(memo.find(1) != nullptr, "the heap walk memo dropped an entry that was hit after the entries it kept"); + require(memo.find(2) == nullptr, "the heap walk memo kept its least recently used entry past the budget"); + std::cout << "the heap walk memo keeps its recently hit entries\n"; +} + +void promotedHitKeptTests() { + const auto tinyBytes = HeapWalkEntryBytes(sizedEntry(1)); + constexpr std::size_t largeWords = std::size_t{2} << 20u; + const auto largeBytes = HeapWalkEntryBytes(sizedEntry(largeWords)); + HeapWalkMemo memo; + memo.budget = largeBytes + 64 * tinyBytes; + for (std::uint64_t key = 1; key <= HeapWalkMemoKeys + 1; ++key) memo.remember(key, sizedEntry(1)); + auto* promoted = memo.find(1); + require(promoted != nullptr && memo.current.contains(1), "a hit did not move the heap walk entry into the current generation"); + memo.touch(promoted->front()); + memo.remember(HeapWalkMemoKeys + 2, sizedEntry(largeWords)); + requireWithinBudget(memo, "after the large entry"); + require(memo.find(1) != nullptr, "the heap walk memo dropped an entry promoted by a hit with its previous generation"); + std::cout << "the heap walk memo keeps an entry a hit promoted from its previous generation\n"; +} + +void sharedResultsChargedOnceTests() { + constexpr std::size_t resultWords = std::size_t{1} << 16u; + auto result = std::make_shared(); + result->heapUserWords.resize(resultWords); + result->heapUserWords.shrink_to_fit(); + const std::shared_ptr shared = std::move(result); + std::weak_ptr watched = shared; + const auto ownBytes = AgcDriver::DriverDetail::HeapWalkEntryOwnBytes(sizedEntry(1)); + const auto sharedBytes = AgcDriver::DriverDetail::HeapWalkResultBytes(*shared); + HeapWalkMemo memo; + memo.budget = 2 * HeapWalkEntryBytes(sizedEntry(1, shared)); + constexpr std::uint64_t keys = 16; + for (std::uint64_t key = 1; key <= keys; ++key) memo.remember(key, sizedEntry(1, shared)); + require(memo.heldBytes == keys * ownBytes + sharedBytes, "the heap walk memo charged " + std::to_string(memo.heldBytes) + " bytes for " + std::to_string(keys) + " entries that share one result, not " + std::to_string(keys * ownBytes + sharedBytes)); + for (std::uint64_t key = 1; key <= keys; ++key) require(memo.find(key) != nullptr, "the heap walk memo dropped an entry whose shared result it already charged"); + for (std::uint64_t key = keys + 1; key <= keys + 64; ++key) { + memo.remember(key, sizedEntry(1, std::make_shared())); + require(memo.heldBytes <= memo.budget, "after key " + std::to_string(key) + ": the heap walk memo holds " + std::to_string(memo.heldBytes) + " bytes, over its budget of " + std::to_string(memo.budget)); + } + requireWithinBudget(memo, "after the shared result's entries aged out"); + std::cout << "the heap walk memo charges a result its entries share once\n"; +} + } int main() { try { oldestEntriesDroppedTests(); previousGenerationDroppedFirstTests(); + hitEntriesKeptTests(); + promotedHitKeptTests(); + sharedResultsChargedOnceTests(); std::cout << "heap walk memo budget tests passed\n"; return 0; } catch (const std::exception& error) { From 63400e5a4dc6a19e9a888982be8234ed39bcaef7 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 30 Oct 2026 04:04:17 +0530 Subject: [PATCH 054/269] fix(agc): keep the storage texture cache alive through exit like the other device caches Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index ada99b7aba00..423d0c2d3b88 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -1075,7 +1075,7 @@ struct StorageTextureCache { }; StorageTextureCache& StorageTextures() { - static StorageTextureCache cache; + static auto& cache = *new StorageTextureCache(); return cache; } From 60e99e0fcf41a463ef1cf4dbffac0f0595062c45 Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Fri, 30 Oct 2026 05:34:29 +0530 Subject: [PATCH 055/269] fix(agc): check guest buffers for multisample targets when a draw or dispatch binds the descriptor heap Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp | 2 +- .../prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp | 1 + core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp | 4 ++-- .../prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp | 5 +++++ 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 8cd400d5955c..5e1ac3767f4c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -5349,7 +5349,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { context.Resolved(&Graphics::DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->pipeline); Graphics::NoteHeapRecord(true, record.objects->descriptorHeap); if (record.objects->descriptorHeap) { - Graphics::BindlessHeap::For(context).BindDescriptorHeaps(commands); + resources.BindDescriptorHeaps(commands); } else if (record.bindings != nullptr) { Graphics::Require(record.bindings->allocation.set != VK_NULL_HANDLE && !resources.HeapStage(), "dispatch overlay has no descriptor set"); Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, 0, 1, &record.bindings->allocation.set, Graphics::SetBindSite::Dispatch); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index e2ceb632deb0..b277f55895ea 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -199,6 +199,7 @@ class ShaderResources { bool HeapStage() const { return heapStage; } void RefreshHeapStage(std::span shaders); void Bind(VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout) const; + void BindDescriptorHeaps(VkCommandBuffer commands) const; struct DrawBindings { DrawBindings() = default; DrawBindings(const DrawBindings&) = delete; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 5e36b78705c6..ee96b03694b4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -2464,7 +2464,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); NoteHeapRecord(false, record.pipeline->DescriptorHeap()); if (record.pipeline->DescriptorHeap()) { - BindlessHeap::For(context).BindDescriptorHeaps(commands); + resources.BindDescriptorHeaps(commands); NoteEmptyResourceSet(); } else if (drawBindings != nullptr) { Require(!resources.HeapStage(), "a GPU-mode draw needs a VK_EXT_descriptor_heap pipeline"); @@ -3412,7 +3412,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D pipeline->Begin(commands, *framebuffer, state.renderExtent, state); APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); if (pipeline->DescriptorHeap()) { - BindlessHeap::For(context).BindDescriptorHeaps(commands); + resources->BindDescriptorHeaps(commands); NoteEmptyResourceSet(); } else resources->Bind(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->Layout()); if (pixelLdsSubgroup != 0u && !pipeline->DescriptorHeap()) BindPixelFunctionLds(context, commands, pipeline->Layout()); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index c31549c01bdc..79d23895d63f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6024,6 +6024,11 @@ void ShaderResources::requireGuestBuffers(std::span moved) co } } +void ShaderResources::BindDescriptorHeaps(VkCommandBuffer commands) const { + requireGuestBuffers(); + BindlessHeap::For(context).BindDescriptorHeaps(commands); +} + void ShaderResources::Bind(VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout) const { requireGuestBuffers(); if (_set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, bindPoint, layout, 0, 1, &_set, bindPoint == VK_PIPELINE_BIND_POINT_COMPUTE ? SetBindSite::Dispatch : SetBindSite::Draw); From d600dfa9b154c0e8c7c337898d6843df27e46b62 Mon Sep 17 00:00:00 2001 From: milescoviello Date: Fri, 30 Oct 2026 01:08:48 +0000 Subject: [PATCH 056/269] fix(agc): let a memory recovery evict sampled textures the GPU heap still holds The recovery skipped every sampled entry whose use count wasn't 1, and a texture in a heap slot always has a second owner, so with APS5_GPU_HEAP=1 an out-of-memory recovery released no sampled textures and new allocations went to host memory. Entries held only by the cache and the heap are now evicted, count toward the release target, and the heap is swept at once (when this thread doesn't hold the sampled cache) so their memory comes back before the retry. Co-Authored-By: Claude Opus 5.5 --- .../Graphics/src/ShaderResources.cpp | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 36af9597a61a..1355468cde2d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -1431,6 +1431,7 @@ std::uint64_t ReleaseTextureCaches(std::uint64_t bytes, bool newImage) { ~Done() { flag = false; } } done{releasing}; std::uint64_t freed = 0; + std::uint64_t heapHeldBytes = 0; std::size_t sampledEntries = 0; std::size_t storageEntries = 0; std::size_t storageKept = 0; @@ -1443,9 +1444,10 @@ std::uint64_t ReleaseTextureCaches(std::uint64_t bytes, bool newImage) { if ((inherited && (!newImage || sampledCacheReclaimable == 0)) || (!inherited && !lock.try_lock())) { sampledSkipped = true; } else { - for (auto it = cache.entries.end(); it != cache.entries.begin() && freed < bytes;) { + for (auto it = cache.entries.end(); it != cache.entries.begin() && freed + heapHeldBytes < bytes;) { --it; - if (it->texture.use_count() != 1 || (it->source != nullptr && it->source->Dirty())) continue; + const auto heapHolds = static_cast(it->texture->HeapHolds()); + if (it->texture.use_count() != 1 + heapHolds || (it->source != nullptr && it->source->Dirty())) continue; const auto allocated = it->texture->AllocationBytes(); const auto sourceBytes = it->source != nullptr ? it->source->AllocationBytes() : 0u; const std::weak_ptr source = it->source; @@ -1453,12 +1455,20 @@ std::uint64_t ReleaseTextureCaches(std::uint64_t bytes, bool newImage) { eraseTexture(cache, it); ++cache.counts.evicted; ++sampledEntries; - freed += allocated; + if (heapHolds != 0) heapHeldBytes += allocated; + else freed += allocated; if (source.expired()) freed += sourceBytes; it = next; } } } + if (heapHeldBytes != 0) { + BindlessHeap::NoteSweepDue(); + if (sampledCacheHeld == 0) { + BindlessHeap::SweepIfDue(); + freed += heapHeldBytes; + } + } if (freed < bytes) { auto& cache = StorageTextures(); std::unique_lock gpu(GuestMemory::GpuMutex(), std::defer_lock); From 9188f745012c1eaf99dfa87c3d642b866bd89b3a Mon Sep 17 00:00:00 2001 From: milescoviello Date: Fri, 30 Oct 2026 01:08:48 +0000 Subject: [PATCH 057/269] test(agc): a memory recovery frees a heap-held sampled texture and stops at its target Co-Authored-By: Claude Opus 5.5 --- .../tests/execution/SampledCacheBudget.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp index 9a3ed0d12cf9..b090afdc7521 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp @@ -596,6 +596,22 @@ bool heapViewTests(const Context& context) { return true; } +void heapHeldReleaseTests(const Context& context) { + Block block(context); + auto& heap = BindlessHeap::For(context); + std::vector> held; + for (std::size_t surface = 0; surface < 2; ++surface) { + auto texture = Sampled(context, block.Surface(surface)); + Require(heap.TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, texture, texture->View(), texture->Layout()).has_value(), "the cached sampled texture took no heap slot"); + held.push_back(texture); + } + Require(TextureCacheUsage().sampledEntries == 2u, "the two sampled textures were not cached"); + Require(!held[0].expired() && !held[1].expired(), "the cache and the heap slots did not keep the sampled textures"); + const auto released = ReleaseTextureCaches(SurfaceBytes, true); + Require(held[0].expired() != held[1].expired(), "a memory recovery for one texture's bytes did not free exactly one of two textures that only the cache and the GPU heap held"); + Require(released >= SurfaceBytes && TextureCacheUsage().sampledEntries == 1u, "a memory recovery did not count the texture it freed from the cache and the GPU heap, or went past its target"); +} + ShaderRecompiler::RecompileResult SampledProgram(std::uint64_t address) { ShaderRecompiler::DescriptorBinding binding{}; binding.kind = ShaderRecompiler::DescriptorKind::SampledImage; @@ -1360,6 +1376,8 @@ int main(int argc, char** argv) { const auto context = heapDevice->GraphicsContext(); { std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + heapHeldReleaseTests(context); + ClearCachedTextures(context.device); tested = heapViewTests(context); ClearCachedTextures(context.device); } From dee0acadd7c0bcea5b710b0ec7a43dda535b7b6a Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 04:14:04 +0530 Subject: [PATCH 058/269] fix(agc): route heap stages that do not fit or are excluded to per-draw A stage that needs more image slots than the heap holds took the heap and aborted at bind with "the global image heap is full". HeapStageMappable now counts the stage's sampled and storage images and image tables against the heap's capacity and sends a stage that cannot fit to the per-draw path. With APS5_HEAP_SLOT_CAP far below the default, stages that each fit can still exhaust the heap between compile and bind; the debt entry says so. APS5_GPU_HEAP_EXCLUDE keeps the heap on and sends the stages or resource classes it names to the per-draw path, to bisect heap-only differences. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 4 +- .../include/Driver/Draw/HeapStages.hpp | 1 + .../src/Driver/Dispatch/Dispatch.cpp | 2 +- .../Execution/src/Driver/Draw/DrawCapture.cpp | 2 +- .../Execution/src/Driver/Draw/HeapStages.cpp | 74 ++++++++++++++++++- .../src/Driver/Shaders/ShaderRegistry.cpp | 4 +- .../Graphics/include/BindlessHeap.hpp | 1 + .../Graphics/src/BindlessHeap.cpp | 27 +++++-- .../tests/execution/ImageTableCacheBounds.cpp | 4 +- docs/dev/ENVIRONMENT.md | 3 +- docs/dev/debt/libSceAgcDriver.md | 2 +- 11 files changed, 108 insertions(+), 16 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 6deb9ad96618..38ead7724282 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -2811,8 +2811,10 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_image_table_atomics_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) add_test(NAME agc_driver_image_table_vouch_queued_draws COMMAND agc_driver_image_table_cache_bounds_tests --queued-draws) set_tests_properties(agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) + add_test(NAME agc_driver_image_table_cache_bounds_heap_small COMMAND agc_driver_image_table_cache_bounds_tests) + set_tests_properties(agc_driver_image_table_cache_bounds_heap_small PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_HEAP_SLOT_CAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) if(WIN32) - set_tests_properties(agc_shader_table_snapshot_reuse agc_shader_table_snapshot_reuse_unmasked agc_driver_image_table_vouched_lookups agc_driver_image_table_vouch_queued_draws agc_driver_image_table_atomics agc_driver_image_table_atomics_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + set_tests_properties(agc_shader_table_snapshot_reuse agc_shader_table_snapshot_reuse_unmasked agc_driver_image_table_vouched_lookups agc_driver_image_table_vouch_queued_draws agc_driver_image_table_cache_bounds_heap_small agc_driver_image_table_atomics agc_driver_image_table_atomics_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() add_test(NAME agc_shader_type_zero_image_materialization COMMAND agc_shader_memory_tests --type-zero-image-materialization) set_tests_properties(agc_shader_type_zero_image_materialization PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index ac20067074f4..7117fbee2a79 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -16,6 +16,7 @@ namespace AgcDriver::DriverDetail { bool HeapFragmentsEnabled(); bool HeapRefused(); +bool HeapStageExcluded(ShaderRecompiler::ShaderStage stage); bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage); Graphics::HeapStageReason HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index 19e393ba89b7..d9886df5286c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -185,7 +185,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, {0, 0, 0, threadGroup != std::array{} ? 0u : 128u} }; constexpr std::size_t computeHeapKey = std::size_t{1} << 61u; - if (request.target.gpuResolvedImages && (HeapRefused() || HeapFragmentKnown(&snapshot, codeOffset | computeHeapKey) == std::optional(false))) request.target.gpuResolvedImages = false; + if (request.target.gpuResolvedImages && (HeapRefused() || HeapStageExcluded(ShaderRecompiler::ShaderStage::Compute) || HeapFragmentKnown(&snapshot, codeOffset | computeHeapKey) == std::optional(false))) request.target.gpuResolvedImages = false; static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; static double captureMs = 0, keyMs = 0, recompileMs = 0, deviceMs = 0; static std::uint64_t cacheHits = 0; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 383c1023b3c9..3a8c33037818 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -95,7 +95,7 @@ std::shared_ptr Driver::materializeDraw request.layout.pushConstantSizeBytes = std::min(request.layout.pushConstantSizeBytes, ShaderRecompiler::DepthRemapPushOffsetBytes - pushOffset); } const auto waitedBefore = traceCapSync() || profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0; - const bool heapCandidate = heapPartners && (program.binary.stage == Stage::Fragment || HeapPreRasterStage(program.binary.stage)) && HeapFragmentsEnabled(); + const bool heapCandidate = heapPartners && (program.binary.stage == Stage::Fragment || HeapPreRasterStage(program.binary.stage)) && !HeapStageExcluded(program.binary.stage) && HeapFragmentsEnabled(); const auto fragmentOnHeap = [&] { const auto fragment = std::find_if(programs.begin(), programs.end(), [](const DrawProgram& candidate) { return candidate.binary.stage == Stage::Fragment; }); if (fragment == programs.end()) return true; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index dc6dfc2bef1b..409ce5598986 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -12,9 +12,14 @@ #include #include #include +#include #include +#include +#include +#include #include #include +#include namespace AgcDriver::DriverDetail { @@ -172,14 +177,77 @@ void RefuseHeapPair(std::uint64_t pair) { refused.insert(pair); } +namespace { + +struct HeapExclusions { + std::uint32_t stages = 0; + bool tables = false; + bool storage = false; + bool sampled = false; +}; + +const HeapExclusions& heapExclusions() { + static const HeapExclusions exclusions = [] { + using Stage = ShaderRecompiler::ShaderStage; + HeapExclusions result; + const char* value = std::getenv("APS5_GPU_HEAP_EXCLUDE"); + std::string_view list = value != nullptr ? value : ""; + static constexpr std::pair stages[] = {{"compute", Stage::Compute}, {"vertex", Stage::Vertex}, {"hull", Stage::TessellationControl}, {"domain", Stage::TessellationEvaluation}, + {"geometry", Stage::Geometry}, {"pixel", Stage::Fragment}, {"local", Stage::Local}, {"mesh", Stage::Mesh}}; + while (!list.empty()) { + const auto comma = list.find(','); + const auto item = list.substr(0, comma); + bool known = true; + if (item == "tables") { + result.tables = true; + } else if (item == "storage") { + result.storage = true; + } else if (item == "sampled") { + result.sampled = true; + } else { + const auto stage = std::find_if(std::begin(stages), std::end(stages), [&](const auto& entry) { return entry.first == item; }); + known = stage != std::end(stages); + if (known) result.stages |= 1u << static_cast(stage->second); + } + if (!known) throw std::runtime_error("APS5_GPU_HEAP_EXCLUDE: unknown class '" + std::string(item) + "'; use compute, vertex, hull, domain, geometry, pixel, local, mesh, tables, storage or sampled"); + if (comma == std::string_view::npos) break; + list.remove_prefix(comma + 1u); + } + return result; + }(); + return exclusions; +} + +bool heapClassesAllowed(const ShaderRecompiler::RecompileResult& result) { + using Role = ShaderRecompiler::DescriptorRole; + using Kind = ShaderRecompiler::DescriptorKind; + const auto& exclusions = heapExclusions(); + std::uint64_t demand = 0; + for (const auto& binding : result.bindings) { + const bool table = binding.role == Role::ImageTable || binding.role == Role::ImageStorageTable; + const bool image = binding.role == Role::GuestImages && (binding.kind == Kind::SampledImage || binding.kind == Kind::StorageImage); + if (table || image) demand += binding.count; + if (table && exclusions.tables) return false; + if (image && binding.kind == Kind::StorageImage && exclusions.storage) return false; + if (image && binding.kind == Kind::SampledImage && exclusions.sampled) return false; + } + return demand <= Graphics::BindlessHeap::ImageSlotCapacity(); +} + +} + +bool HeapStageExcluded(ShaderRecompiler::ShaderStage stage) { + return (heapExclusions().stages >> static_cast(stage) & 1u) != 0u; +} + bool HeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { struct MappableStorage {}; auto& known = HostThreadLocal, MappableStorage>(); const auto key = result.variantId * 2u + (workgroupAddress ? 1u : 0u); if (const auto found = known.find(key); found != known.end()) return found->second; if (known.size() >= 65536u) known.clear(); - const bool mappable = Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), - workgroupAddress, result.dataAddressPush, result.functionLdsBuffer, result.meshWindowBuffer); + const bool mappable = heapClassesAllowed(result) && + Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), workgroupAddress, result.dataAddressPush, result.functionLdsBuffer, result.meshWindowBuffer); known.emplace(key, mappable); return mappable; } @@ -562,7 +630,7 @@ void SetHeapStageUnmapped(std::optional stage) { } bool HeapDrawStageMappable(const ShaderRecompiler::RecompileResult& result, ShaderRecompiler::ShaderStage stage) { - return unmappedStage.load(std::memory_order_relaxed) != static_cast(stage) && HeapStageMappable(result); + return unmappedStage.load(std::memory_order_relaxed) != static_cast(stage) && !HeapStageExcluded(stage) && HeapStageMappable(result); } std::uint64_t HeapStagesTaken() { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp index cae31d97c5ec..8e3cc5a238d5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp @@ -1392,7 +1392,7 @@ std::vector PrepareRegistered(RegisteredPreparation& pla } }; bool heapPrebuilt = false; - if ((fragment || heapVertex) && HeapFragmentsEnabled()) { + if ((fragment || heapVertex) && !HeapStageExcluded(request.shader.stage) && HeapFragmentsEnabled()) { const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, entries.front().handle); if (invocation && HeapStageEligible(request.shader.stage, invocation->Plan().get(), heapVertex)) { auto heapRequest = request; @@ -1942,7 +1942,7 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod std::vector heap; const auto addHeap = [&](std::size_t index, bool heapVertex) { const auto& stage = prepared[index]; - if (stage.entry.handle == nullptr || !requests[index]) return false; + if (stage.entry.handle == nullptr || !requests[index] || HeapStageExcluded(stage.stage)) return false; const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(*requests[index], stage.entry.handle); if (!invocation || !HeapStageEligible(stage.stage, invocation->Plan().get(), heapVertex)) return false; auto request = *requests[index]; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 2df534908002..cb19412edfd8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -61,6 +61,7 @@ class BindlessHeap { std::span samplerSlots, std::span samplerGenerations) const; std::uint32_t AbsentSlot(std::uint32_t kind, VkImageView view); static bool NearlyFull(); + static std::uint32_t ImageSlotCapacity(); static void NoteSweepDue(); static void NoteStorageEvicted(); static void SweepIfDue(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 8c91851b97d6..95fa25e7752f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -151,6 +152,22 @@ bool BindlessHeap::Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& prope return resourcesFit && samplersFit; } +namespace { + +std::uint32_t configuredSlotCap() { + static const std::uint32_t cap = [] { + std::uint32_t result = Abi::GpuImageHeapSlots; + if (const char* value = std::getenv("APS5_HEAP_SLOT_CAP")) { + const auto requested = static_cast(std::strtoul(value, nullptr, 10)); + if (requested != 0u) result = static_cast(Abi::Binding::Samplers) + std::min(requested, Abi::GpuImageHeapSlots - static_cast(Abi::Binding::Samplers)); + } + return result; + }(); + return cap; +} + +} + BindlessHeap::BindlessHeap(const Context& context) : context(context) { Require(context.descriptorHeap, "the GPU heap needs VK_EXT_descriptor_heap"); const auto& heapProperties = context.descriptorHeapProperties; @@ -181,11 +198,7 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { ringAlignment = static_cast(std::max(context.limits.minStorageBufferOffsetAlignment, 16)); ringChunks.resize(RingBytes / RingChunkBytes); nextTextureSlot = SamplerKind; - slotCap = Abi::GpuImageHeapSlots; - if (const char* cap = std::getenv("APS5_HEAP_SLOT_CAP")) { - const auto requested = static_cast(std::strtoul(cap, nullptr, 10)); - if (requested != 0u) slotCap = SamplerKind + std::min(requested, Abi::GpuImageHeapSlots - SamplerKind); - } + slotCap = configuredSlotCap(); } BindlessHeap::~BindlessHeap() = default; @@ -486,6 +499,10 @@ bool BindlessHeap::NearlyFull() { return nearlyFull.load(std::memory_order_relaxed); } +std::uint32_t BindlessHeap::ImageSlotCapacity() { + return configuredSlotCap() - SamplerKind; +} + namespace { std::atomic sweepDue{false}; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp index 0fd677075f23..89bea8b9d0ea 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp @@ -166,10 +166,12 @@ void TablesChangingPerDispatch(const GuestBlock& block) { Dispatch(block, 0); most = std::max(most, cache.TableElements()); } - if (AgcDriver::Graphics::DescriptorHeapEnabled()) { + const bool tableFitsHeap = AgcDriver::Graphics::BindlessHeap::ImageSlotCapacity() >= Elements + Spare; + if (AgcDriver::Graphics::DescriptorHeapEnabled() && tableFitsHeap) { Require(AgcDriver::Graphics::HeapComputeStages() > heapStages, "image table cache bounds: the dispatches did not take the descriptor heap"); return; } + if (AgcDriver::Graphics::DescriptorHeapEnabled()) Require(AgcDriver::Graphics::HeapComputeStages() == heapStages, "image table cache bounds: a table stage with more images than the heap's slots took the heap"); Require(most >= Elements, "image table cache bounds: no dispatch kept its table in the resource cache"); Require(most <= AgcDriver::Graphics::ResourceCache::TableElementBudget(), "image table cache bounds: tables that changed every dispatch kept " + std::to_string(most) + " table elements in the resource cache, over its budget of " + std::to_string(AgcDriver::Graphics::ResourceCache::TableElementBudget())); } diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 6204cf57faf3..37f07a5584ba 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -175,6 +175,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_GPU_CHECKPOINTS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | attaches device diagnostic checkpoints through VK_NV_device_diagnostic_checkpoints, or buffer markers through VK_AMD_buffer_marker on a device without it | | `APS5_GPU_COPY_MAX_KIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 1024 | size cap in KiB on a descriptor sub-range copied through the GPU path, larger ones staying on the CPU | | `APS5_GPU_HEAP` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | | binds the sampled and storage images and samplers of eligible stages through the device's VK_EXT_descriptor_heap heaps; without the extension it does nothing | +| `APS5_GPU_HEAP_EXCLUDE` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | | comma list of stage classes that take the per-draw path while the GPU heap stays on: stage names (compute, vertex, hull, domain, geometry, pixel, local, mesh), or tables, storage or sampled for stages with image tables, storage images or sampled images | | `APS5_GPU_NO_WRITEBACK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | skips writing GPU results back into guest memory | | `APS5_GPU_WAIT_TIMEOUT_MS` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp` | 1000 | milliseconds a GPU wait may run before a warning is printed | | `APS5_GROUP_CAPTURE_ALL_QUEUES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp` | | resolves group-ahead capture on queue 0 as well | @@ -182,7 +183,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_HEAP_MIRROR_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 24576 | budget in MiB for the heap mirrors held for registered allocations | | `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first | | `APS5_HEAP_WALK_MEMO_MB` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | 256 | MiB each thread's GPU heap walk memo may hold across both its generations before the previous generation and then the oldest walks are dropped (0 keeps them until the 16,384-key cap rotates them out) | -| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 233415 | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default | +| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 233415 | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default; a stage needing more image slots than this takes the per-draw path | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | | `APS5_HOOK_LOCKED_WAIT` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | keeps the flush hook's pending-write wait under the GpuMutex | diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 21b89a86d58b..51f35f0fc46c 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -309,5 +309,5 @@ ### Opt-in draw paths - [Draw finisher](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp) (`APS5_DRAW_PIPELINE`) - opt-in. The Linux main-image page table it adds matches what Windows already does by default. -- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap`. A stage whose module keeps a set 0 binding (storage images of registration modules, GDS, the fault buffer), mesh and tessellation pipelines and compute stages without images take the per-draw path, and so does every other stage of their draw. +- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap`. A stage whose module keeps a set 0 binding (storage images of registration modules, GDS, the fault buffer), mesh and tessellation pipelines and compute stages without images take the per-draw path, and so does every other stage of their draw. A stage that needs more image slots than the heap holds also takes the per-draw path; with `APS5_HEAP_SLOT_CAP` far below the default, stages that each fit can still exhaust the heap between their compile and their bind, because the nearly-full margin scales with the cap. - [Multi-submit count overflow and buffer validation](../../../core/libs/prx/libSceAgcDriver/Submit/src/Dcb.cpp) (libSceAgcDriver) - whether the console driver imposes an architectural submission packet limit or allows null buffer pointers with non-zero sizes in multi-submit arrays is unmeasured; AgcDriver::SubmitMany validates count against 32-bit pointer array bounds overflow and rejects null addresses for non-empty command buffers with a runtime exception. From dfe95cc9692f9e21e42f80a0be6b744476a8767e Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 04:14:04 +0530 Subject: [PATCH 059/269] test(agc): let the depth remap, prepared graphics and lazy ABI tests run with APS5_GPU_HEAP set Co-Authored-By: Claude Opus 5.5 --- .../tests/execution/LazyResolvedAbi.cpp | 8 +++++--- .../tests/execution/PreparedGraphics.cpp | 19 ++++++++++++++++++- .../tests/execution/Tessellation.cpp | 1 + 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp index aad7c87ddb2b..8abbbca43523 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp @@ -2,6 +2,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/ShaderPreparationScope.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "prx/libc/include/GuestArena.hpp" @@ -556,10 +557,11 @@ void LazyResolution(const Layout& layout, const std::filesystem::path& reference Require(unmatched.firstUses - start.firstUses == Drawn && unmatched.own - start.own == Drawn && unmatched.found == start.found, "lazy resolved ABI: draws whose state differs from the resolved ABI did not count as preparing their own artifact (before: " + Uses(start) + "; after: " + Uses(unmatched) + ")"); Require(unmatched.entries > start.entries && unmatched.unmatchedEntries - start.unmatchedEntries == unmatched.entries - start.entries, "lazy resolved ABI: entries prepared for an ABI no draw used do not count as unmatched (before: " + Uses(start) + "; after: " + Uses(unmatched) + ")"); Require(matched.firstUses == unmatched.firstUses + 1 && matched.found == unmatched.found + 1 && matched.own == unmatched.own, "lazy resolved ABI: a draw whose state matches the resolved ABI did not count as finding its artifact (before: " + Uses(unmatched) + "; after: " + Uses(matched) + ")"); - Require(matched.entries > unmatched.entries && matched.unmatchedEntries == unmatched.unmatchedEntries + (matched.entries - unmatched.entries) - 1, "lazy resolved ABI: the entry a matching draw used still counts as unmatched (before: " + Uses(unmatched) + "; after: " + Uses(matched) + ")"); + const std::uint64_t usedVariants = AgcDriver::DriverDetail::HeapFragmentsEnabled() ? 2u : 1u; + Require(matched.entries > unmatched.entries && matched.unmatchedEntries == unmatched.unmatchedEntries + (matched.entries - unmatched.entries) - usedVariants, "lazy resolved ABI: the entry a matching draw used still counts as unmatched (before: " + Uses(unmatched) + "; after: " + Uses(matched) + ")"); for (const auto index : {Matching, Twice, Replaced}) Require(eager.at("drawn " + std::to_string(index)) == eager.at("resolved " + std::to_string(index)), "lazy resolved ABI: shader " + std::to_string(index) + ", drawn with its resolved ABI's state, did not find the ABI's entries with eager preparation"); - for (std::uint32_t index = 0; index < Drawn; ++index) Require(Count(eager.at("drawn " + std::to_string(index))) == Count(eager.at("resolved " + std::to_string(index))) + 1, "lazy resolved ABI: a draw whose state differs from its resolved ABI did not prepare its own entry with eager preparation"); - Require(Count(eager.at("drawn " + std::to_string(Replacement))) == Count(eager.at("registered " + std::to_string(Replacement))) + 1, "lazy resolved ABI: the header registered over a resolved one did not prepare its own entry at its draw with eager preparation"); + for (std::uint32_t index = 0; index < Drawn; ++index) Require(Count(eager.at("drawn " + std::to_string(index))) == Count(eager.at("resolved " + std::to_string(index))) + usedVariants, "lazy resolved ABI: a draw whose state differs from its resolved ABI did not prepare its own entry with eager preparation"); + Require(Count(eager.at("drawn " + std::to_string(Replacement))) == Count(eager.at("registered " + std::to_string(Replacement))) + usedVariants, "lazy resolved ABI: the header registered over a resolved one did not prepare its own entry at its draw with eager preparation"); Require(lazy.at("libraries drawn") == eager.at("libraries drawn"), "lazy resolved ABI: the pipeline libraries built differ from eager preparation (eager " + eager.at("libraries drawn") + "; lazy " + lazy.at("libraries drawn") + ")"); Require(first == expected, "lazy resolved ABI: the shader prepared at its first draw drew other bytes than with eager preparation"); AgcDriverWaitIdle_nid_postfix(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp index 160c69ad9227..ad020980c96b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "VulkanTestDevice.hpp" #include "prx/libSceAgcDriver/Execution/include/ShaderPreparation.hpp" #include "SceShaders.hpp" @@ -564,7 +565,23 @@ void CheckMergedHull(AgcDriver::VulkanDevice& device) { DecodeGraphicsPrograms(stale, unmapped, registry, false, true); Require(stale.programs[1].userData[0] == 0x10u && stale.programs[1].userData[1] == 0u, "a merged hull draw did not pass a user-data address it does not need unchecked"); const auto stages = PrepareGraphicsStages(prepared, device.Target()); - Require(stages.size() == 4u && stages[0].entry.handle != stages[1].entry.handle, "a merged hull program was not prepared as separate local and hull stages"); + for (const bool heapVariant : {false, true}) { + std::vector set; + for (const auto& stage : stages) { + if (stage.heapVariant == heapVariant) set.push_back(&stage); + } + if (heapVariant && set.empty()) { + Require(!HeapFragmentsEnabled(), "the heap prepared no heap variants of the merged hull draw"); + continue; + } + const auto handleOf = [&](ShaderRecompiler::ShaderStage wanted) { + const auto found = std::find_if(set.begin(), set.end(), [&](const auto* stage) { return stage->stage == wanted; }); + return found == set.end() ? nullptr : (*found)->entry.handle.get(); + }; + const auto* local = handleOf(ShaderRecompiler::ShaderStage::Local); + const auto* hull = handleOf(ShaderRecompiler::ShaderStage::TessellationControl); + Require((heapVariant || set.size() == 4u) && local != nullptr && hull != nullptr && local != hull, "a merged hull program was not prepared as separate local and hull stages"); + } for (const auto& stage : stages) stage.snapshot->prepared->entries.push_back(stage.entry); std::vector linked; std::vector memory; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/Tessellation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/Tessellation.cpp index c36ae606a69d..4a54912bac7c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/Tessellation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/Tessellation.cpp @@ -713,6 +713,7 @@ void Draw(AgcDriver::VulkanDevice& device, const Stages& stages, VkCullModeFlags void RequireDepthRangeRemap(AgcDriver::VulkanDevice& device) { auto target = device.Target(); + target.gpuResolvedImages = AgcDriver::Graphics::DescriptorHeapEnabled(); Require(device.graphicsContext().depthClamp, "tessellation depth remap needs depth clamping"); target.depthRangeRemap = true; const auto compile = [&](float z, std::uint32_t mode) { From 19f1c84b0810d9072a675615d640f28ca23502e8 Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 04:28:44 +0530 Subject: [PATCH 060/269] perf(shader): read heap ring and BDA table words through read-only pointers Co-Authored-By: Claude Opus 5.5 --- .../SpirvMemory/SpirvBufferAccess.hpp | 1 + .../SpirvBackend/src/SpirvBdaFault.cpp | 2 +- .../src/SpirvMemory/SpirvBufferAccess.cpp | 20 ++++++++++++++++++- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 5 ++++- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp index 41d3ef400a1e..4e16e3e49770 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp @@ -13,6 +13,7 @@ std::uint32_t EmitShaderDataWordLoad(SpirvEmitterState& state, std::uint32_t ind std::uint32_t EmitRootDword(SpirvEmitterState& state, std::uint32_t field); std::uint32_t EmitStageRootDword(SpirvEmitterState& state, RuntimeAbi::RootStageField field); std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, std::uint32_t field, std::uint32_t index); +std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, std::uint32_t field, std::uint32_t index); std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::RootStageField field, std::uint32_t index); std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index); bool HasFlattenedSrt(const SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp index 60feb78eac5c..04b65b1ad674 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp @@ -13,7 +13,7 @@ std::uint32_t BdaConstant(SpirvEmitterState& state, std::uint64_t value) { } std::uint32_t BdaWord(SpirvEmitterState& state, std::uint32_t variable, std::uint32_t index) { - if (state.bdaAddressed && variable == state.bdaPagetableVariable) return EmitRootAddressWordPointer(state, RuntimeAbi::RootPagetableAddress, index); + if (state.bdaAddressed && variable == state.bdaPagetableVariable) return EmitRootAddressReadOnlyWordPointer(state, RuntimeAbi::RootPagetableAddress, index); if (state.bdaAddressed && variable == state.faultBufferVariable) return EmitRootAddressWordPointer(state, RuntimeAbi::RootFaultAddress, index); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, variable, ConstantU32(state, 0u), index); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 217410f73498..9d45aa193631 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -73,16 +73,34 @@ std::uint32_t wordPointer(SpirvEmitterState& state, std::uint32_t base, std::uin return pointer; } +std::uint32_t readOnlyWordPointer(SpirvEmitterState& state, std::uint32_t base, std::uint32_t index) { + const auto array = state.module.DecoratedType(spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4u}}}, TypeU32(state)); + const auto words = state.module.DecoratedType(spv::OpTypeStruct, + {{spv::OpDecorate, {spv::DecorationBlock}}, + {spv::OpMemberDecorate, {0u, spv::DecorationOffset, 0u}}, + {spv::OpMemberDecorate, {0u, spv::DecorationNonWritable}}}, + array); + const auto block = state.module.AllocateId(); + state.module.AddFunction(spv::OpConvertUToPtr, TypePointer(state, spv::StorageClassPhysicalStorageBuffer, words), block, base); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePhysicalU32Pointer(state), pointer, block, ConstantU32(state, 0u), index); + return pointer; +} + } std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, std::uint32_t field, std::uint32_t index) { return wordPointer(state, rootAddress(state, field), index); } +std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, std::uint32_t field, std::uint32_t index) { + return readOnlyWordPointer(state, rootAddress(state, field), index); +} + std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::RootStageField field, std::uint32_t index) { const auto u64 = TypeScalarU64(state); const auto base = Binary(state, spv::OpIAdd, u64, rootAddress(state, RuntimeAbi::RootRingAddress), Unary(state, spv::OpUConvert, u64, EmitStageRootDword(state, field))); - return wordPointer(state, base, index); + return readOnlyWordPointer(state, base, index); } namespace { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index c8463e43db84..b538a091a3dc 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -530,7 +530,10 @@ void DefineDescriptors(SpirvEmitterState& state) { } break; case DescriptorBindingKind::ShaderData: - if (!layout.UsesDataAddress()) state.shaderDataStorageVariable = Define(StorageBufferBlockType(state), "shader_data"); + if (!layout.UsesDataAddress()) { + state.shaderDataStorageVariable = Define(StorageBufferBlockType(state), "shader_data"); + state.module.AddAnnotation(spv::OpDecorate, state.shaderDataStorageVariable, spv::DecorationNonWritable); + } break; case DescriptorBindingKind::FlattenedSrt: if (layout.UsesDataAddress()) state.flattenedSrtAddressed = true; From 8a590ddf7efcfc0628f5067b60e1d3cf148deb8e Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 04:44:10 +0530 Subject: [PATCH 061/269] perf(shader): load flattened SRT words without a branch per load Co-Authored-By: Claude Opus 5.5 --- .../SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 9d45aa193631..7236141ce00e 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -130,8 +130,12 @@ std::uint32_t EmitShaderDataWordLoad(SpirvEmitterState& state, std::uint32_t ind std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index) { if (state.flattenedSrtAddressed) { - const auto inBounds = Binary(state, spv::OpULessThan, TypeBool(state), index, EmitStageRootDword(state, RuntimeAbi::RootStageField::SrtDwords)); - return EmitValueOrZeroIfCondition(state, inBounds, [&] { return dataAddressLoad(state, RuntimeAbi::RootStageField::FlattenedSrt, index); }); + const auto u32 = TypeU32(state); + const auto dwords = EmitStageRootDword(state, RuntimeAbi::RootStageField::SrtDwords); + const auto inBounds = Binary(state, spv::OpULessThan, TypeBool(state), index, dwords); + const auto last = Select(state, u32, Binary(state, spv::OpIEqual, TypeBool(state), dwords, ConstantU32(state, 0u)), ConstantU32(state, 0u), Binary(state, spv::OpISub, u32, dwords, ConstantU32(state, 1u))); + const auto clamped = Select(state, u32, inBounds, index, last); + return Select(state, u32, inBounds, dataAddressLoad(state, RuntimeAbi::RootStageField::FlattenedSrt, clamped), ConstantU32(state, 0u)); } if (state.flattenedSrtVariable == 0) FailEmit("the flattened SRT descriptor is missing"); const auto pointer = state.module.AllocateId(); From 80ab6162d7ae7aa596a6adb4ed461f21337da23b Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 05:18:55 +0530 Subject: [PATCH 062/269] perf(shader): read heap buffers through read-only pointers when the shader writes no buffer Co-Authored-By: Claude Opus 5.5 --- .../include/SpirvBackend/SpirvEmitterHelpers.hpp | 3 +++ .../include/SpirvBackend/SpirvEmitterState.hpp | 1 + .../src/SpirvMemory/SpirvModuleSetup.cpp | 13 +++++++++---- .../SpirvBackend/src/SpirvMemory/SpirvTypes.cpp | 13 +++++++++++++ .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 13 ++++++++++--- 5 files changed, 36 insertions(+), 7 deletions(-) diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp index 417d457323a4..3ce7a843bf0b 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp @@ -42,6 +42,7 @@ std::uint32_t TypeStorageBufferU8Pointer(SpirvEmitterState& state); std::uint32_t TypeStorageBufferU8ElementPointer(SpirvEmitterState& state); std::uint32_t TypePhysicalU32Pointer(SpirvEmitterState& state); std::uint32_t TypePhysicalBufferPointer(SpirvEmitterState& state, bool wide); +std::uint32_t TypePhysicalReadOnlyBufferPointer(SpirvEmitterState& state, bool wide); std::uint32_t TypePushConstantElementPointer(SpirvEmitterState& state); std::uint32_t TypeU32ArrayPointer(SpirvEmitterState& state, std::uint32_t storageClass, std::uint32_t dwords); std::uint32_t TypeU32ElementPointer(SpirvEmitterState& state, std::uint32_t storageClass); @@ -112,6 +113,8 @@ std::uint32_t EmitBallotLaneActiveBool(SpirvEmitterState& state, std::uint32_t b std::uint32_t EmitSubgroupLaneActiveBool(SpirvEmitterState& state, std::uint32_t lane); std::uint32_t EmitBinaryU32(SpirvEmitterState& state, std::uint32_t opcode, std::uint32_t lhs, std::uint32_t rhs); std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dwordIndex); +bool WritesGuestBuffers(const IrProgram& program); +bool WritesGuestMemory(const IrProgram& program); void EmitMemoryOffsets(SpirvEmitterState& state); void EmitHeapSlotPreload(SpirvEmitterState& state); std::uint32_t LdsDwordCount(const SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index a6155914bde5..14c1769dd060 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -112,6 +112,7 @@ struct SpirvEmitterState { bool registrationModules = false; bool gpuResolvedImages = false; bool addressedBuffers = false; + std::optional guestBuffersWritten; bool fragmentDescriptorSet = false; bool float16DenormPreserve = false; bool robustBufferAccess2 = false; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp index 14b21bb32199..5ab8c2cda761 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp @@ -308,12 +308,12 @@ void PlanMeshWindowBuffer(SpirvEmitterState& state) { state.meshWindowEntryLive = order.empty() ? Slots(slots, true) : liveIn.at(order.front()); } -bool WritesGuestMemory(const IrProgram& program) { +} + +bool WritesGuestBuffers(const IrProgram& program) { const auto& info = program.Info(); - const auto writtenImage = [](const ImageResource& image) { return !image.targetMerge && (image.written || image.atomic || image.atomic64); }; - const auto writtenModes = [&](const std::vector& modes) { return std::ranges::any_of(modes, writtenImage); }; const auto writtenBuffer = [](const BufferResource& buffer) { return buffer.written || buffer.atomic; }; - if (info.bdaWrites || std::ranges::any_of(info.buffers, writtenBuffer) || std::ranges::any_of(info.images, writtenImage) || std::ranges::any_of(info.runtimeImageModes, writtenModes)) return true; + if (info.bdaWrites || std::ranges::any_of(info.buffers, writtenBuffer)) return true; const auto& memory = program.Resources().memoryInfo; for (const auto& block : program.Blocks()) { for (const IrValue* inst : block->Instructions()) { @@ -327,6 +327,11 @@ bool WritesGuestMemory(const IrProgram& program) { return false; } +bool WritesGuestMemory(const IrProgram& program) { + const auto& info = program.Info(); + const auto writtenImage = [](const ImageResource& image) { return !image.targetMerge && (image.written || image.atomic || image.atomic64); }; + const auto writtenModes = [&](const std::vector& modes) { return std::ranges::any_of(modes, writtenImage); }; + return std::ranges::any_of(info.images, writtenImage) || std::ranges::any_of(info.runtimeImageModes, writtenModes) || WritesGuestBuffers(program); } void DefineModule(SpirvEmitterState& state) { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp index 9cd1f5537d43..1a668c9d8a92 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp @@ -17,6 +17,15 @@ std::uint32_t StorageBufferType(SpirvEmitterState& state) { array); } +std::uint32_t ReadOnlyStorageBufferType(SpirvEmitterState& state, std::uint32_t element, std::uint32_t stride) { + const auto array = state.module.DecoratedType(spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, stride}}}, element); + return state.module.DecoratedType(spv::OpTypeStruct, + {{spv::OpDecorate, {spv::DecorationBlock}}, + {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, + {spv::OpMemberDecorate, {0, spv::DecorationNonWritable}}}, + array); +} + std::uint32_t StorageBufferU64Type(SpirvEmitterState& state) { const auto array = state.module.DecoratedType(spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 8u}}}, TypeScalarU64(state)); return state.module.DecoratedType(spv::OpTypeStruct, @@ -137,6 +146,10 @@ std::uint32_t TypeStorageBufferU8ElementPointer(SpirvEmitterState& state) { return TypePointer(state, spv::StorageClassStorageBuffer, TypeU8(state)); } +std::uint32_t TypePhysicalReadOnlyBufferPointer(SpirvEmitterState& state, bool wide) { + return TypePointer(state, spv::StorageClassPhysicalStorageBuffer, wide ? ReadOnlyStorageBufferType(state, TypeScalarU64(state), 8u) : ReadOnlyStorageBufferType(state, TypeU32(state), 4u)); +} + std::uint32_t TypePhysicalBufferPointer(SpirvEmitterState& state, bool wide) { return TypePointer(state, spv::StorageClassPhysicalStorageBuffer, wide ? StorageBufferU64Type(state) : StorageBufferType(state)); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index 5f0bcfd20fff..89738fabe6fb 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -188,7 +188,14 @@ RuntimeAddress address(SpirvValueEmitContext& context, const IrValue& instructio return {AddBdaAddress(context, instruction, resource.base, Unary(state, spv::OpUConvert, TypeScalarU64(state), bytesAddress.guest), false), bytesAddress.inBounds}; } -MemoryResourceAccess directAccess(SpirvValueEmitContext& context, const IrValue& instruction, bool wide = false, bool plainLoad = false) { +bool readOnlyLoad(SpirvValueEmitContext& context, const IrValue& instruction) { + auto& state = context.state; + if (context.Memory(instruction).coherent || (state.requirements.coherentBuffers && state.program.Metadata().invalidatesCaches)) return false; + if (!state.guestBuffersWritten.has_value()) state.guestBuffersWritten = WritesGuestBuffers(state.program); + return !*state.guestBuffersWritten; +} + +MemoryResourceAccess directAccess(SpirvValueEmitContext& context, const IrValue& instruction, bool wide = false, bool plainLoad = false, bool readOnly = false) { auto& state = context.state; const auto& memory = context.Memory(instruction); if (state.addressedBuffers) { @@ -202,7 +209,7 @@ MemoryResourceAccess directAccess(SpirvValueEmitContext& context, const IrValue& access.kind = memory.kind; access.physical = true; access.objectPointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpConvertUToPtr, TypePhysicalBufferPointer(state, wide), access.objectPointer, address); + state.module.AddFunction(spv::OpConvertUToPtr, readOnly ? TypePhysicalReadOnlyBufferPointer(state, wide) : TypePhysicalBufferPointer(state, wide), access.objectPointer, address); access.byteOffset = state.memoryByteOffsets.at(element); access.memoryAccess = memory.coherent ? spv::MemoryAccessVolatileMask : 0u; access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), EmitShaderDataDwordLoad(state, dword + 2u), ConstantU32(state, wide ? 3u : 2u)); @@ -255,7 +262,7 @@ bool addressedCoherent(SpirvValueEmitContext& context, const IrValue& instructio std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruction, std::uint32_t address, std::uint32_t bits, std::uint32_t enable = 0u) { if (context.Memory(instruction).gpuDescriptor) return EmitBdaRead(context, instruction, address, bits); auto& state = context.state; - const auto access = directAccess(context, instruction, false, !context.Memory(instruction).coherent); + const auto access = directAccess(context, instruction, false, !context.Memory(instruction).coherent, readOnlyLoad(context, instruction)); const auto index = directWordIndex(state, access, address); const auto misalignment = baseMisalignment(context, instruction); const auto unaligned = nonzero(state, misalignment); From 1e30fbb31ee236696b2dd96fb1ea936930c2307a Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 05:18:55 +0530 Subject: [PATCH 063/269] perf(shader): load heap buffer words without a branch, clamping out-of-range reads Co-Authored-By: Claude Opus 5.5 --- .../include/SpirvBackend/SpirvEmitterState.hpp | 1 + .../SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp | 1 + .../src/SpirvMemory/SpirvBufferAccess.cpp | 9 +++++++-- .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 12 +++++++++--- 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index 14c1769dd060..c9dfee948ca3 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -72,6 +72,7 @@ struct MemoryResourceAccess { std::uint32_t memoryAccess = 0; std::uint32_t misalignment = 0; bool physical = false; + bool clampedPhysical = false; }; struct SpirvTableImageVariable { diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp index 4e16e3e49770..1120452de905 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp @@ -14,6 +14,7 @@ std::uint32_t EmitRootDword(SpirvEmitterState& state, std::uint32_t field); std::uint32_t EmitStageRootDword(SpirvEmitterState& state, RuntimeAbi::RootStageField field); std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, std::uint32_t field, std::uint32_t index); std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, std::uint32_t field, std::uint32_t index); +std::uint32_t EmitRingAddress(SpirvEmitterState& state); std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::RootStageField field, std::uint32_t index); std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index); bool HasFlattenedSrt(const SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 7236141ce00e..39cf7d6996db 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -97,6 +97,10 @@ std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, std:: return readOnlyWordPointer(state, rootAddress(state, field), index); } +std::uint32_t EmitRingAddress(SpirvEmitterState& state) { + return rootAddress(state, RuntimeAbi::RootRingAddress); +} + std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::RootStageField field, std::uint32_t index) { const auto u64 = TypeScalarU64(state); const auto base = Binary(state, spv::OpIAdd, u64, rootAddress(state, RuntimeAbi::RootRingAddress), Unary(state, spv::OpUConvert, u64, EmitStageRootDword(state, field))); @@ -382,13 +386,14 @@ std::uint32_t LdsStorageDwords(const SpirvEmitterState& state) { bool LoadsSelectable(const SpirvEmitterState& state, const MemoryResourceAccess& access) { if (access.kind == ResourceKind::Scratch) return true; - if (access.kind == ResourceKind::Lds || access.physical) return false; + if (access.physical) return access.clampedPhysical; + if (access.kind == ResourceKind::Lds) return false; return state.robustBufferAccess2; } std::uint32_t GuardedElementIndex(SpirvEmitterState& state, const MemoryResourceAccess& access, std::uint32_t condition, std::uint32_t index) { if (access.kind == ResourceKind::Lds) FailEmit("LDS loads keep their branch and have no guarded element"); - const auto fallback = access.kind == ResourceKind::Scratch ? 0u : 0xfffffffeu; + const auto fallback = access.kind == ResourceKind::Scratch || access.physical ? 0u : 0xfffffffeu; return Select(state, TypeU32(state), condition, index, ConstantU32(state, fallback)); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index 89738fabe6fb..f142ef2000a0 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -3,6 +3,7 @@ #include "SpirvBackend/SpirvBda.hpp" #include "SpirvBackend/SpirvBufferFormat.hpp" #include "SpirvBackend/SpirvMemory/SpirvSubgroup.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include "SpirvBackend/SpirvMemory/SpirvInputOutput.hpp" #include "PipelineSpecialization.hpp" #include "RdnaDecoder/RdnaDescriptorFormat.hpp" @@ -204,15 +205,20 @@ MemoryResourceAccess directAccess(SpirvValueEmitContext& context, const IrValue& const auto u64 = TypeScalarU64(state); const auto low = Unary(state, spv::OpUConvert, u64, EmitShaderDataDwordLoad(state, dword)); const auto high = Binary(state, spv::OpShiftLeftLogical, u64, Unary(state, spv::OpUConvert, u64, EmitShaderDataDwordLoad(state, dword + 1u)), BdaConstant(state, 32u)); - const auto address = Binary(state, spv::OpBitwiseOr, u64, low, high); + auto address = Binary(state, spv::OpBitwiseOr, u64, low, high); MemoryResourceAccess access; access.kind = memory.kind; access.physical = true; + access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), EmitShaderDataDwordLoad(state, dword + 2u), ConstantU32(state, wide ? 3u : 2u)); + if (state.program.Metadata().bindings.UsesDataAddress()) { + const auto empty = Binary(state, spv::OpIEqual, TypeBool(state), access.length, ConstantU32(state, 0u)); + address = Select(state, u64, empty, EmitRingAddress(state), address); + access.clampedPhysical = true; + } access.objectPointer = state.module.AllocateId(); state.module.AddFunction(spv::OpConvertUToPtr, readOnly ? TypePhysicalReadOnlyBufferPointer(state, wide) : TypePhysicalBufferPointer(state, wide), access.objectPointer, address); access.byteOffset = state.memoryByteOffsets.at(element); access.memoryAccess = memory.coherent ? spv::MemoryAccessVolatileMask : 0u; - access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), EmitShaderDataDwordLoad(state, dword + 2u), ConstantU32(state, wide ? 3u : 2u)); return access; } const auto variable = wide ? state.storageBufferU64Variable : plainLoad || state.storageBufferCoherentVariable == 0u ? state.storageBufferVariable : state.storageBufferCoherentVariable; @@ -268,7 +274,7 @@ std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruct const auto unaligned = nonzero(state, misalignment); const auto next = EmitAddU32(state, index, ConstantU32(state, 1u)); const auto last = Select(state, TypeU32(state), unaligned, next, index); - const bool exact = state.exactRobustLoads && LoadsSelectable(state, access); + const bool exact = state.exactRobustLoads && !access.physical && LoadsSelectable(state, access); const auto bounds = exact ? 0u : EmitMemoryElementInBounds(state, access, last); const auto inBounds = exact ? 0u : (enable != 0u ? both(state, enable, bounds) : bounds); const auto load = [&](std::uint32_t word) { From 41f8d1cb9c19f5635b7542db1565c406b7e94068 Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 05:44:40 +0530 Subject: [PATCH 064/269] perf(agc): copy a heap image slot from the view's encoded descriptor instead of encoding it again Co-Authored-By: Claude Opus 5.5 --- .../Graphics/include/BindlessHeap.hpp | 5 ++- .../include/DescriptorHeapObjects.hpp | 6 +++ .../Graphics/src/BindlessHeap.cpp | 33 +++++++++++---- .../Graphics/src/DescriptorHeapObjects.cpp | 41 +++++++++++++++++++ .../tests/BindlessHeapSlots.cpp | 26 ++++++++++++ 5 files changed, 102 insertions(+), 9 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index cb19412edfd8..8d3e909e2fd0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -83,7 +83,7 @@ class BindlessHeap { void Submitted(Recorder& recorder, std::uint64_t serial); struct Counts { - std::uint64_t textures = 0, samplers = 0, full = 0, ringWraps = 0; + std::uint64_t textures = 0, samplers = 0, full = 0, ringWraps = 0, encodes = 0, encodedCopies = 0; std::uint64_t slotsFreed = 0, slotsReused = 0, sweeps = 0, chunkWaits = 0; std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0; }; @@ -102,6 +102,9 @@ class BindlessHeap { VkDeviceSize pixelLdsHeapOffset = 0; VkDeviceSize meshWindowHeapOffset = 0; VkDeviceSize samplerHeapUsed = 0; + PFN_vkWriteResourceDescriptorsEXT writeResourceDescriptors = nullptr; + PFN_vkWriteSamplerDescriptorsEXT writeSamplerDescriptors = nullptr; + std::vector encodeScratch; void writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImageView view, VkImageLayout layout); void writeSamplerSlot(std::uint32_t slot, VkSampler sampler); void writeBufferDescriptor(VkDeviceSize offset, VkDeviceAddress address, VkDeviceSize bytes, const char* what); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp index bbe25790d619..ac2b8a2ff592 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp @@ -3,7 +3,10 @@ #include +#include +#include #include +#include namespace AgcDriver::Graphics { @@ -13,6 +16,7 @@ struct ImageViewRecord { VkImageViewMinLodCreateInfoEXT minLod{VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT}; bool hasUsage = false; bool hasMinLod = false; + std::uint64_t generation = 0; const VkImageViewCreateInfo* Chain(); }; @@ -26,6 +30,8 @@ struct SamplerRecord { PFN_vkVoidFunction DescriptorHeapObjectFunction(VkDevice device, PFN_vkGetDeviceProcAddr deviceProc, const char* name); std::optional FindImageView(VkImageView view); std::optional FindSampler(VkSampler sampler); +bool CopyEncodedImageView(VkImageView view, std::uint32_t key, std::span target); +void KeepEncodedImageView(VkImageView view, std::uint64_t generation, std::uint32_t key, std::span bytes); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 95fa25e7752f..e130c3a2b3f7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -57,6 +57,8 @@ void check(VkResult result, const char* what) { } std::atomic spansWrittenWindow{0}; +std::atomic imageEncodesWindow{0}; +std::atomic imageCopiesWindow{0}; std::atomic spansKeptWindow{0}; std::atomic spansExpiredWindow{0}; std::atomic heapComputeStages{0}; @@ -743,8 +745,8 @@ void BindlessHeap::writeSamplerSlot(std::uint32_t slot, VkSampler sampler) { const auto offset = static_cast(slot) * samplerHeapStride; Require(offset + samplerHeapStride <= samplerHeapUsed, "a GPU heap sampler slot lies outside the sampler heap"); const VkHostAddressRangeEXT target{samplerHeap->Bytes().data() + offset, static_cast(samplerHeapStride)}; - check(context.Function("vkWriteSamplerDescriptorsEXT")(context.device, 1, record->Chain(), &target), - "vkWriteSamplerDescriptorsEXT"); + if (writeSamplerDescriptors == nullptr) writeSamplerDescriptors = context.Function("vkWriteSamplerDescriptorsEXT"); + check(writeSamplerDescriptors(context.device, 1, record->Chain(), &target), "vkWriteSamplerDescriptorsEXT"); } void BindlessHeap::writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImageView view, VkImageLayout layout) { @@ -755,15 +757,28 @@ void BindlessHeap::writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImag std::memset(target, 0, static_cast(imageHeapStride)); return; } + const bool storage = Abi::GpuHeapStorageKind(kind); + const auto key = static_cast(layout) | (storage ? 0x80000000u : 0u); + const auto stride = static_cast(imageHeapStride); + if (CopyEncodedImageView(view, key, std::span(target, stride))) { + ++counts.encodedCopies; + imageCopiesWindow.fetch_add(1, std::memory_order_relaxed); + return; + } auto record = FindImageView(view); Require(record.has_value(), "a GPU heap image view has no recorded create info"); const VkImageDescriptorInfoEXT imageInfo{VK_STRUCTURE_TYPE_IMAGE_DESCRIPTOR_INFO_EXT, nullptr, record->Chain(), layout}; VkResourceDescriptorInfoEXT resource{VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT}; - resource.type = Abi::GpuHeapStorageKind(kind) ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; + resource.type = storage ? VK_DESCRIPTOR_TYPE_STORAGE_IMAGE : VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; resource.data.pImage = &imageInfo; - const VkHostAddressRangeEXT range{target, static_cast(imageHeapStride)}; - check(context.Function("vkWriteResourceDescriptorsEXT")(context.device, 1, &resource, &range), - "vkWriteResourceDescriptorsEXT"); + encodeScratch.resize(stride); + const VkHostAddressRangeEXT range{encodeScratch.data(), stride}; + if (writeResourceDescriptors == nullptr) writeResourceDescriptors = context.Function("vkWriteResourceDescriptorsEXT"); + check(writeResourceDescriptors(context.device, 1, &resource, &range), "vkWriteResourceDescriptorsEXT"); + std::memcpy(target, encodeScratch.data(), stride); + KeepEncodedImageView(view, record->generation, key, encodeScratch); + ++counts.encodes; + imageEncodesWindow.fetch_add(1, std::memory_order_relaxed); } namespace { @@ -1050,14 +1065,16 @@ void reportHeapStatistics() { const auto spansWritten = takeCount(spansWrittenWindow); const auto spansKept = takeCount(spansKeptWindow); const auto spansExpired = takeCount(spansExpiredWindow); + const auto imageEncodes = takeCount(imageEncodesWindow); + const auto imageCopies = takeCount(imageCopiesWindow); const auto templates = ShaderRecompiler::HeapTemplateCounts(); std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired; templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired; image descriptors %llu encoded / %llu copied; templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(spansExpired), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(spansExpired), printed(imageEncodes), printed(imageCopies), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp index 47360a964ae4..c45a8d712b0b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp @@ -4,6 +4,7 @@ #include #include #include +#include namespace AgcDriver::Graphics { @@ -24,6 +25,16 @@ std::unordered_map& views() { return map; } +struct EncodedImageView { + std::uint32_t key = 0; + std::vector bytes; +}; + +std::unordered_map>& encodedViews() { + static auto& map = *new std::unordered_map>(); + return map; +} + std::unordered_map& samplers() { static auto& map = *new std::unordered_map(); return map; @@ -63,8 +74,11 @@ VKAPI_ATTR VkResult VKAPI_CALL createImageView(VkDevice device, const VkImageVie const auto result = realCreateImageView.load(std::memory_order_acquire)(device, info, allocator, view); if (result == VK_SUCCESS) { auto record = recordOf(*info); + static std::atomic generations{0}; + record.generation = generations.fetch_add(1, std::memory_order_relaxed) + 1u; std::lock_guard lock(recordsMutex()); views()[*view] = std::move(record); + encodedViews().erase(*view); } return result; } @@ -73,6 +87,7 @@ VKAPI_ATTR void VKAPI_CALL destroyImageView(VkDevice device, VkImageView view, c { std::lock_guard lock(recordsMutex()); views().erase(view); + encodedViews().erase(view); } realDestroyImageView.load(std::memory_order_acquire)(device, view, allocator); } @@ -149,6 +164,32 @@ PFN_vkVoidFunction DescriptorHeapObjectFunction(VkDevice device, PFN_vkGetDevice return nullptr; } +bool CopyEncodedImageView(VkImageView view, std::uint32_t key, std::span target) { + std::lock_guard lock(recordsMutex()); + const auto found = encodedViews().find(view); + if (found == encodedViews().end()) return false; + for (const auto& encoded : found->second) { + if (encoded.key != key || encoded.bytes.size() != target.size()) continue; + std::memcpy(target.data(), encoded.bytes.data(), target.size()); + return true; + } + return false; +} + +void KeepEncodedImageView(VkImageView view, std::uint64_t generation, std::uint32_t key, std::span bytes) { + std::lock_guard lock(recordsMutex()); + const auto record = views().find(view); + if (record == views().end() || record->second.generation != generation) return; + auto& entries = encodedViews()[view]; + for (auto& encoded : entries) { + if (encoded.key == key) { + encoded.bytes.assign(bytes.begin(), bytes.end()); + return; + } + } + entries.push_back({key, std::vector(bytes.begin(), bytes.end())}); +} + std::optional FindImageView(VkImageView view) { std::lock_guard lock(recordsMutex()); const auto found = views().find(view); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 298b85cd5bbc..1417382e6e55 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" #include "prx/libSceAgcDriver/Graphics/include/PlaceholderImages.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" @@ -101,6 +102,30 @@ void viewSlots(const Context& context, VkImageView view) { heap.ReleaseViewSlots(&second); } +void encodedViews(const Context& context) { + BindlessHeap heap(context); + const auto base = heap.Statistics(); + const auto encodes = [&] { return heap.Statistics().encodes - base.encodes; }; + const auto copies = [&] { return heap.Statistics().encodedCopies - base.encodedCopies; }; + VkImageView destroyed = VK_NULL_HANDLE; + const auto storageKey = static_cast(VK_IMAGE_LAYOUT_GENERAL) | 0x80000000u; + std::vector bytes(static_cast(heap.ImageHeapStride())); + { + const PlaceholderImages placeholders(context); + const auto view = placeholders.View(Abi::FirstStorageImageBinding); + heap.AbsentSlot(Abi::FirstStorageImageBinding + 2u, view); + require(encodes() == 1u && copies() == 0u, "a view's first heap slot encodes its descriptor"); + heap.AbsentSlot(Abi::FirstStorageImageBinding + 3u, view); + require(encodes() == 1u && copies() == 1u, "another slot for the same view copies the encoded descriptor"); + require(CopyEncodedImageView(view, storageKey, bytes), "a live view keeps its encoded descriptor"); + destroyed = view; + } + require(!CopyEncodedImageView(destroyed, storageKey, bytes), "a destroyed view drops its encoded descriptor"); + const PlaceholderImages again(context); + heap.AbsentSlot(Abi::FirstStorageImageBinding + 4u, again.View(Abi::FirstStorageImageBinding)); + require(encodes() == 2u && copies() == 1u, "a destroyed view's encoded descriptor is not copied to a new view"); +} + void sweptOwnerReentry(const Context& context, VkImageView view) { auto& heap = BindlessHeap::For(context); const auto kind = Abi::FirstStorageImageBinding + 1u; @@ -345,6 +370,7 @@ int main(int argc, char** argv) { samplerSlots(context); ringSpans(context); viewSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); + encodedViews(context); sweptOwnerReentry(context, placeholders.View(Abi::FirstStorageImageBinding)); device->WaitIdle(); } From 4ea221b471345f5f8249c9820bc3bc0f5d85b2d0 Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 05:53:02 +0530 Subject: [PATCH 065/269] perf(agc): resolve each Vulkan device function once per device instead of on every call Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/VulkanDevice.cpp | 8 ++- .../Graphics/include/Context.hpp | 52 +++++++++++++++++-- .../tests/execution/DeviceFunctionCache.cpp | 51 ++++++++++++++++++ 3 files changed, 106 insertions(+), 5 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/DeviceFunctionCache.cpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index b7e2bec8234e..3aa7d2b70c93 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -511,6 +511,7 @@ struct VulkanDevice::State { // built once after setup (see graphicsContext); the context's pool reference is dropped before // the pool at teardown. Graphics::DeviceFunctions deviceFunctions; + std::unique_ptr functionCache = std::make_unique(); bool functionsReady = false; Graphics::Context context; bool contextReady = false; @@ -630,12 +631,14 @@ struct VulkanDevice::State { template TFunction DeviceFunction(const char* name) const { + if (const auto cached = functionCache->Find(name, deviceProc); cached != nullptr) return reinterpret_cast(cached); ++Graphics::DeviceProcLookups(); - auto function = reinterpret_cast(deviceProc(device, name)); + const auto function = deviceProc(device, name); if (function == nullptr) { throw std::runtime_error(std::string("Vulkan device function missing: ") + name); } - return function; + functionCache->Keep(name, deviceProc, function); + return reinterpret_cast(function); } void CreateWorkgroupMemoryLayout() { @@ -4266,6 +4269,7 @@ Graphics::Context VulkanDevice::buildContext() const { context.exactRobustLoads = state->exactRobustLoads; context.copiedWriters = state->copiedWriters.get(); context.functions = state->functionsReady ? &state->deviceFunctions : nullptr; + context.functionCache = state->functionsReady ? state->functionCache.get() : nullptr; context.descriptorIndexing = state->descriptorIndexing; context.descriptorIndexingLimits = state->descriptorIndexingProperties; context.imageInt64Atomics = state->imageInt64Atomics; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index eee62c5eed61..17e871601685 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -150,6 +150,46 @@ inline std::uint64_t& DeviceProcLookups() { return count; } +class DeviceFunctionCache { +public: + PFN_vkVoidFunction Find(const char* name, PFN_vkGetDeviceProcAddr proc) const { + for (std::size_t probe = 0, slot = slotOf(name); probe < MaxProbes; ++probe, slot = (slot + 1u) & (Slots - 1u)) { + const auto& entry = entries[slot]; + const auto* stored = entry.name.load(std::memory_order_acquire); + if (stored == nullptr) return nullptr; + if (stored != name) continue; + const auto function = entry.function.load(std::memory_order_acquire); + return function != nullptr && entry.proc.load(std::memory_order_relaxed) == proc ? function : nullptr; + } + return nullptr; + } + + void Keep(const char* name, PFN_vkGetDeviceProcAddr proc, PFN_vkVoidFunction function) { + for (std::size_t probe = 0, slot = slotOf(name); probe < MaxProbes; ++probe, slot = (slot + 1u) & (Slots - 1u)) { + auto& entry = entries[slot]; + const char* expected = nullptr; + if (!entry.name.compare_exchange_strong(expected, name, std::memory_order_acq_rel) && expected != name) continue; + if (expected == name) return; + entry.proc.store(proc, std::memory_order_relaxed); + entry.function.store(function, std::memory_order_release); + return; + } + } + +private: + static constexpr std::size_t Slots = 2048; + static constexpr std::size_t MaxProbes = 32; + struct Entry { + std::atomic name{nullptr}; + std::atomic proc{nullptr}; + std::atomic function{nullptr}; + }; + static std::size_t slotOf(const char* name) { + return static_cast((reinterpret_cast(name) >> 3u) * 0x9e3779b97f4a7c15ull >> 40u) & (Slots - 1u); + } + std::array entries{}; +}; + inline constexpr std::size_t EmptyBufferBytes = 16; struct Context { @@ -232,6 +272,7 @@ struct Context { const std::vector>* copiedWriters = nullptr; // The device's resolved entry points (see DeviceFunctions); null until the device set up. const DeviceFunctions* functions = nullptr; + DeviceFunctionCache* functionCache = nullptr; // VK_EXT_descriptor_indexing with non-uniform sampled/storage image array indexing enabled // (bindless image tables in graphics stages). bool descriptorIndexing = false; @@ -289,13 +330,18 @@ struct Context { template TFunction Function(const char* name) const { Require(deviceProc != nullptr, "missing Vulkan device function resolver"); - ++DeviceProcLookups(); if (descriptorHeap) { if (const auto hooked = DescriptorHeapObjectFunction(device, deviceProc, name); hooked != nullptr) return reinterpret_cast(hooked); } - const auto function = reinterpret_cast(deviceProc(device, name)); + const auto* cache = functions != nullptr ? functionCache : nullptr; + if (cache != nullptr) { + if (const auto cached = cache->Find(name, deviceProc); cached != nullptr) return reinterpret_cast(cached); + } + ++DeviceProcLookups(); + const auto function = deviceProc(device, name); if (function == nullptr) throw std::runtime_error(std::string("AGC graphics: missing Vulkan function: ") + name); - return function; + if (cache != nullptr) functionCache->Keep(name, deviceProc, function); + return reinterpret_cast(function); } // The table's entry point, or a per-call lookup while the table is absent or lacks it. diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DeviceFunctionCache.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DeviceFunctionCache.cpp new file mode 100644 index 000000000000..4df226b5bf5c --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DeviceFunctionCache.cpp @@ -0,0 +1,51 @@ +#include "VulkanTestDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Context.hpp" + +#include +#include + +namespace { + +PFN_vkGetDeviceProcAddr realProc = nullptr; +int countedCalls = 0; + +PFN_vkVoidFunction VKAPI_CALL countingProc(VkDevice device, const char* name) { + ++countedCalls; + return realProc(device, name); +} + +void require(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +constexpr char DispatchName[] = "vkCmdDispatch"; + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + auto context = device->graphicsContext(); + require(context.functions != nullptr && context.functionCache != nullptr, "the device context carries its function cache"); + const auto first = context.Function(DispatchName); + const auto lookups = AgcDriver::Graphics::DeviceProcLookups(); + require(context.Function(DispatchName) == first && AgcDriver::Graphics::DeviceProcLookups() == lookups, + "a repeated lookup is served from the device's cache"); + realProc = context.deviceProc; + context.deviceProc = countingProc; + require(context.Function(DispatchName) == first && countedCalls == 1, "another resolver is not served from the cache"); + context.deviceProc = realProc; + require(context.Function(DispatchName) == first && AgcDriver::Graphics::DeviceProcLookups() == lookups + 1u, + "the device's resolver is still served from the cache"); + context.deviceProc = countingProc; + context.functions = nullptr; + static_cast(context.Function(DispatchName)); + require(countedCalls == 2, "a context without the device's table looks up every time"); + std::printf("device function cache tests passed\n"); + return 0; + } catch (const std::exception& error) { + std::printf("device function cache tests failed: %s\n", error.what()); + return 1; + } +} From fd802c3b427c6338b13190d13a60fd75aee3d2eb Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 06:21:18 +0530 Subject: [PATCH 066/269] fix(agc): keep the GPU heap off on drivers and validation layers older than VK_EXT_descriptor_heap Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/VulkanDevice.cpp | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 3aa7d2b70c93..6870c2212f6f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -134,6 +134,25 @@ DeviceQueuePlan PlanDeviceQueues(std::span famili namespace { +std::optional ActiveValidationLayerVersion(PFN_vkGetInstanceProcAddr instanceProc) { + const auto requested = [](const char* variable) { + const char* value = std::getenv(variable); + return value != nullptr && (std::strstr(value, "validation") != nullptr || std::strchr(value, '*') != nullptr); + }; + if (!requested("VK_INSTANCE_LAYERS") && !requested("VK_LOADER_LAYERS_ENABLE")) return std::nullopt; + const auto enumerate = reinterpret_cast(instanceProc(VK_NULL_HANDLE, "vkEnumerateInstanceLayerProperties")); + if (enumerate == nullptr) return std::nullopt; + std::uint32_t count = 0; + if (enumerate(&count, nullptr) != VK_SUCCESS) return std::nullopt; + std::vector layers(count); + if (enumerate(&count, layers.data()) != VK_SUCCESS) return std::nullopt; + for (const auto& layer : layers) { + if (std::strcmp(layer.layerName, "VK_LAYER_KHRONOS_validation") == 0) return layer.specVersion; + } + return std::nullopt; +} + + void check(VkResult result, const char* operation) { if (result == VK_ERROR_DEVICE_LOST) Graphics::ReportDeviceLost(); if (result != VK_SUCCESS) { @@ -1904,7 +1923,20 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : } } VkPhysicalDeviceDescriptorHeapFeaturesEXT descriptorHeapFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_FEATURES_EXT}; - if (Graphics::GpuHeapEnabled() && hasExtension(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME) && hasExtension(VK_KHR_MAINTENANCE_5_EXTENSION_NAME) && hasExtension(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) && hasExtension(VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME) && hasExtension(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME)) { + const auto deviceApi = state->properties.apiVersion; + bool releasedDescriptorHeap = deviceApi >= VK_MAKE_API_VERSION(0, 1, 4, 340); + if (Graphics::GpuHeapEnabled() && hasExtension(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME) && !releasedDescriptorHeap) + std::fprintf(stderr, "[gpu-heap] the driver reports Vulkan %u.%u.%u, older than 1.4.340 where VK_EXT_descriptor_heap was released, so its descriptor heap is a pre-release revision and the GPU heap stays off\n", + VK_API_VERSION_MAJOR(deviceApi), VK_API_VERSION_MINOR(deviceApi), VK_API_VERSION_PATCH(deviceApi)); + if (Graphics::GpuHeapEnabled() && releasedDescriptorHeap && hasExtension(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME)) { + const auto validationVersion = ActiveValidationLayerVersion(state->instanceProc); + if (validationVersion.has_value() && *validationVersion < VK_MAKE_API_VERSION(0, 1, 4, 363)) { + std::fprintf(stderr, "[gpu-heap] VK_LAYER_KHRONOS_validation %u.%u.%u predates its descriptor heap rules (1.4.363 is the oldest layer that validates heap push data), so the GPU heap stays off\n", + VK_API_VERSION_MAJOR(*validationVersion), VK_API_VERSION_MINOR(*validationVersion), VK_API_VERSION_PATCH(*validationVersion)); + releasedDescriptorHeap = false; + } + } + if (Graphics::GpuHeapEnabled() && releasedDescriptorHeap && hasExtension(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME) && hasExtension(VK_KHR_MAINTENANCE_5_EXTENSION_NAME) && hasExtension(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) && hasExtension(VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME) && hasExtension(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME)) { VkPhysicalDeviceMaintenance5FeaturesKHR heapMaintenance5{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR, &descriptorHeapFeatures}; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &heapMaintenance5}; state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &features); From 039b02099a65cfc9deff1f223b06c419dc416166 Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 06:46:58 +0530 Subject: [PATCH 067/269] fix(shader): drop the heap slot words of bindings a specialized module no longer binds Co-Authored-By: Claude Opus 5.5 --- .../prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp | 8 +++++++- .../Optimization/src/DescriptorBindingBuilder.cpp | 9 ++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index d58d8997bdd6..15d18092c108 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6555,7 +6555,13 @@ void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const Hea for (const auto& word : program.heapSlotWords) { Require(word.dword < patched.size(), "a GPU-mode slot word lies outside the shader data"); if (word.kind == static_cast(Abi::Binding::Samplers)) { - Require(word.element < samplerSlots.size(), "a GPU-mode slot word names a sampler the stage does not bind"); + if (word.element >= samplerSlots.size()) { + char text[256]; + std::snprintf(text, sizeof(text), + "AGC graphics: a GPU-mode slot word names a sampler the stage does not bind (stage %u, element %u, sampler slots %zu, bindings %zu)", + static_cast(shader.stage), word.element, samplerSlots.size(), bindings.size()); + throw std::runtime_error(text); + } patched[word.dword] = samplerSlots[word.element]; continue; } diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index f8ea3c3e2adb..35daeda2fc35 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -583,7 +583,14 @@ DescriptorBindingPlan DescriptorBindingBuilder::Select(const DescriptorBindingPl } selected.imageMetadata = plan.imageMetadata; selected.runtimeState = plan.runtimeState; - selected.heapSlotWords = plan.heapSlotWords; + constexpr auto bindingCount = static_cast(RuntimeAbi::Binding::Count); + std::set droppedKinds; + for (const auto& binding : plan.bindings) droppedKinds.insert(binding.descriptor.binding % bindingCount); + for (const auto& binding : selected.bindings) droppedKinds.erase(binding.descriptor.binding % bindingCount); + selected.heapSlotWords.reserve(plan.heapSlotWords.size()); + for (const auto& word : plan.heapSlotWords) { + if (!droppedKinds.contains(word.kind)) selected.heapSlotWords.push_back(word); + } selected.addressedBuffers = plan.addressedBuffers; selected.addressedData = plan.addressedData; return selected; From 4d15455fdbf61a53e9f689ca3d70a175d109b0fd Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 06:46:58 +0530 Subject: [PATCH 068/269] feat(agc): check heap storage image slots under APS5_VERIFY_GPU_HEAP Co-Authored-By: Claude Opus 5.5 --- .../Graphics/include/BindlessHeap.hpp | 1 + .../Graphics/src/BindlessHeap.cpp | 6 +++++ .../Graphics/src/ShaderResources.cpp | 27 ++++++++++++------- 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 8d3e909e2fd0..9a371f9ba0b4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -54,6 +54,7 @@ class BindlessHeap { void ReleaseViewSlots(const void* owner); std::uint32_t SlotGeneration(std::uint32_t slot) const; const Texture* SlotTexture(std::uint32_t kind, std::uint32_t slot) const; + bool SlotHoldsStorage(std::uint32_t kind, std::uint32_t slot, const void* owner, VkImageView view) const; std::optional SamplerSlot(const std::shared_ptr& sampler); std::uint32_t SamplerGeneration(std::uint32_t slot) const; std::uint64_t SlotSerial() const { return slotSerial.load(std::memory_order_acquire); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index e130c3a2b3f7..a3c4657c37f2 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -629,6 +629,12 @@ const Texture* BindlessHeap::SlotTexture(std::uint32_t kind, std::uint32_t slot) return owner != nullptr && owner->key.kind == kind ? owner->texture.get() : nullptr; } +bool BindlessHeap::SlotHoldsStorage(std::uint32_t kind, std::uint32_t slot, const void* owner, VkImageView view) const { + std::lock_guard lock(mutex); + const auto* held = ownerLocked(slot); + return held != nullptr && held->key == TextureKey{kind, owner, view, VK_IMAGE_LAYOUT_GENERAL}; +} + std::uint32_t BindlessHeap::AbsentSlot(std::uint32_t kind, VkImageView view) { if (kind < Abi::FirstImageBinding || kind >= SamplerKind) throw std::runtime_error("AGC bindless heap: invalid absent slot request"); std::lock_guard lock(mutex); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 15d18092c108..da2a579b6c0b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6506,22 +6506,31 @@ void ShaderResources::noteHeapSlotGenerations(const BindlessHeap& heap, HeapStag void ShaderResources::verifyHeapSlots(const BindlessHeap& heap, const HeapStageState& state, VkShaderStageFlags stageBit) const { constexpr auto bindingCount = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count); - static std::atomic checked{0}, wrong{0}; + static std::atomic checked{0}, wrong{0}, storageChecked{0}, storageWrong{0}; for (const auto& binding : bindings) { - if (!ownsHeapBinding(binding, stageBit) || binding.layout.descriptorType != VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) continue; + if (!ownsHeapBinding(binding, stageBit)) continue; + const bool sampled = binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; + const bool storage = binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + if (!sampled && !storage) continue; const auto kind = binding.layout.binding % bindingCount; for (std::size_t element = 0; element < binding.imageAllocations.size(); ++element) { const auto index = binding.imageAllocations[element]; if (index == std::numeric_limits::max()) continue; - ++checked; - const bool holdsTexture = - element < state.slots[kind].size() && heap.SlotTexture(kind, state.slots[kind][element]) == textures[index].get(); - if (!holdsTexture) ++wrong; + const bool bound = element < state.slots[kind].size(); + if (sampled) { + ++checked; + if (!bound || heap.SlotTexture(kind, state.slots[kind][element]) != textures[index].get()) ++wrong; + continue; + } + if (storageTextures[index] == nullptr) continue; + ++storageChecked; + if (!bound || !heap.SlotHoldsStorage(kind, state.slots[kind][element], storageTextures[index].get(), heapStorageView(index, binding.layout.binding))) ++storageWrong; } } - if (checked.load() % 100000u < 8u) { - std::fprintf(stderr, "[heap-slots] verify: %llu image slots checked, %llu hold another texture\n", - static_cast(checked.load()), static_cast(wrong.load())); + if ((checked.load() + storageChecked.load()) % 100000u < 8u) { + std::fprintf(stderr, "[heap-slots] verify: %llu image slots checked, %llu hold another texture; %llu storage slots checked, %llu hold another image or view\n", + static_cast(checked.load()), static_cast(wrong.load()), + static_cast(storageChecked.load()), static_cast(storageWrong.load())); } } From ec6c2f384f65810a74ffcb255cea3508aaffd794 Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 06:46:58 +0530 Subject: [PATCH 069/269] test(agc): run the storage image tests' compute stages on the GPU heap Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 2 +- .../libSceAgcDriver/tests/execution/DepthStorageDispatch.cpp | 2 +- .../prx/libSceAgcDriver/tests/execution/DepthStorageReuse.cpp | 2 +- .../prx/libSceAgcDriver/tests/execution/ImageCacheBits.cpp | 2 +- .../libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp | 4 ++-- core/libs/prx/libSceAgcDriver/tests/execution/ImageSint8.cpp | 2 +- .../prx/libSceAgcDriver/tests/execution/ImageSrgbLoad.cpp | 2 +- .../tests/execution/ImageStoreArrayThroughVolume.cpp | 2 +- .../libSceAgcDriver/tests/execution/ImageStoreFaceOnCube.cpp | 2 +- .../tests/execution/ImageStoreFloatRounding.cpp | 2 +- .../tests/execution/ImageStoreLineThroughPlane.cpp | 2 +- .../tests/execution/ImageStoreLineThroughPlaneArray.cpp | 2 +- .../prx/libSceAgcDriver/tests/execution/ImageStorePacked.cpp | 2 +- .../prx/libSceAgcDriver/tests/execution/ImageStoreSint.cpp | 2 +- .../tests/execution/ImageStoreUnormRounding.cpp | 2 +- .../tests/execution/ImageStoreVolumeThroughArray.cpp | 2 +- .../prx/libSceAgcDriver/tests/execution/ImageTexelStatus.cpp | 2 +- .../libSceAgcDriver/tests/execution/StorageFlushOrdering.cpp | 2 +- .../libSceAgcDriver/tests/execution/StorageOneSliceAlias.cpp | 2 +- .../prx/libSceAgcDriver/tests/execution/ViewPastLastMip.cpp | 2 +- 20 files changed, 21 insertions(+), 21 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 38ead7724282..0f3fce8f83d7 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -2972,7 +2972,7 @@ if(BUILD_TESTING) set_tests_properties(${agcTestName}_draw_pipeline PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endforeach() - set(agcGpuHeapTests ${agcDrawPipelineTests} agc_driver_rect_list_indirect agc_driver_provoking_vertex agc_driver_pixel_barycentric_emulation agc_driver_bindless_images agc_driver_image_sample_shared_sampler agc_driver_image_sample_border_color agc_driver_image_sample_lod_clamp agc_driver_image_sample_derivatives agc_driver_image_gather_one_dimensional agc_driver_image_load_packed agc_driver_sampled_cache_budget agc_driver_image_atomics agc_driver_image_atomics64 agc_driver_image_atomics_bitwise agc_driver_image_atomics_float agc_driver_gpu_indirect_arguments_misaligned_writer_ahead agc_driver_gpu_indirect_arguments_written_ahead agc_driver_indirect_arguments_written_ahead agc_driver_indirect_thread_dimensions agc_driver_indirect_patched_stage agc_driver_compute_table_calls agc_driver_buffer_atomics agc_driver_buffer_format agc_driver_mesh agc_driver_tessellation agc_driver_mesh_draw_relocation agc_driver_mesh_index_cache agc_driver_mesh_provoking_vertex agc_driver_tessellation_submit agc_driver_fragment_user_data_tail agc_driver_image_table_cache_bounds agc_driver_lds_beyond_device_limit agc_driver_address_passes) + set(agcGpuHeapTests ${agcDrawPipelineTests} agc_driver_rect_list_indirect agc_driver_provoking_vertex agc_driver_pixel_barycentric_emulation agc_driver_bindless_images agc_driver_image_sample_shared_sampler agc_driver_image_sample_border_color agc_driver_image_sample_lod_clamp agc_driver_image_sample_derivatives agc_driver_image_gather_one_dimensional agc_driver_image_load_packed agc_driver_sampled_cache_budget agc_driver_image_atomics agc_driver_image_atomics64 agc_driver_image_atomics_bitwise agc_driver_image_atomics_float agc_driver_gpu_indirect_arguments_misaligned_writer_ahead agc_driver_gpu_indirect_arguments_written_ahead agc_driver_indirect_arguments_written_ahead agc_driver_indirect_thread_dimensions agc_driver_indirect_patched_stage agc_driver_compute_table_calls agc_driver_buffer_atomics agc_driver_buffer_format agc_driver_mesh agc_driver_tessellation agc_driver_mesh_draw_relocation agc_driver_mesh_index_cache agc_driver_mesh_provoking_vertex agc_driver_tessellation_submit agc_driver_fragment_user_data_tail agc_driver_image_table_cache_bounds agc_driver_lds_beyond_device_limit agc_driver_address_passes agc_driver_depth_storage_dispatch agc_driver_image_cache_bits agc_driver_image_converted_unorm agc_driver_image_sint8 agc_driver_image_srgb_load agc_driver_image_store_array_through_volume agc_driver_image_store_face_on_cube agc_driver_image_store_float_rounding agc_driver_image_store_line_through_plane agc_driver_image_store_line_through_plane_array agc_driver_image_store_packed agc_driver_image_store_sint agc_driver_image_store_unorm_rounding agc_driver_image_store_volume_through_array agc_driver_image_texel_status agc_driver_storage_flush_ordering agc_driver_storage_one_slice_alias agc_driver_view_past_last_mip) foreach(agcTestName IN LISTS agcGpuHeapTests) add_test(NAME ${agcTestName}_gpu_heap COMMAND ${agcTestName}_tests) set_tests_properties(${agcTestName}_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageDispatch.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageDispatch.cpp index 4c2e019b69da..e72c76e7006e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageDispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageDispatch.cpp @@ -141,7 +141,7 @@ ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, std:: ShaderRecompiler::RecompileRequest request{ {ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageReuse.cpp index dbd774f671a8..1f44d1771099 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthStorageReuse.cpp @@ -45,7 +45,7 @@ void Read(AgcDriver::VulkanDevice& device, std::uint32_t format, std::uint32_t w const ShaderRecompiler::ShaderComputeStageInfo compute{{32, 1, 1}, 0u, {false, false, false}, false, 1}; ShaderRecompiler::RecompileRequest request{ {ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, - {32, 0, data, compute, std::nullopt, std::nullopt, memory}, device.Target(), {0, 0, 0, 128}, + {32, 0, data, compute, std::nullopt, std::nullopt, memory}, device.ComputeTarget(64), {0, 0, 0, 128}, }; request.useCache = false; const auto shader = ShaderRecompiler::Recompile(request); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageCacheBits.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageCacheBits.cpp index f321df600250..7f60148977e6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageCacheBits.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageCacheBits.cpp @@ -224,7 +224,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::span co ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp index bb50f103fd84..c8496487b6dc 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageConvertedUnorm.cpp @@ -216,7 +216,7 @@ void Run(AgcDriver::VulkanDevice& device, std::span code, c ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; @@ -442,7 +442,7 @@ void CheckConvertedPreparation(AgcDriver::VulkanDevice& device, const std::uint8 ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; auto converted = request; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageSint8.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageSint8.cpp index cb8958107b62..d5ce832ae322 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageSint8.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageSint8.cpp @@ -115,7 +115,7 @@ void Run(AgcDriver::VulkanDevice& device, std::span code, s ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageSrgbLoad.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageSrgbLoad.cpp index eafabe0d7c87..898a73421caf 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageSrgbLoad.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageSrgbLoad.cpp @@ -188,7 +188,7 @@ std::vector Run(AgcDriver::VulkanDevice& device, std::span(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = useCache; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreArrayThroughVolume.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreArrayThroughVolume.cpp index b410321d5cd0..24cafee2007e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreArrayThroughVolume.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreArrayThroughVolume.cpp @@ -126,7 +126,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::size_t ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFaceOnCube.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFaceOnCube.cpp index 148b6e45c74d..d58e1b29b6ff 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFaceOnCube.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFaceOnCube.cpp @@ -140,7 +140,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, const Forma ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp index 20bb6f2a1834..5a1a134d2bc1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp @@ -168,7 +168,7 @@ void Store(AgcDriver::VulkanDevice& device, std::uint8_t* texels, const Format& ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(storeCode.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlane.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlane.cpp index 6f6e1cfb2dbb..0b29350010ca 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlane.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlane.cpp @@ -146,7 +146,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::span(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlaneArray.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlaneArray.cpp index 26d3e4d1ff99..5327471762b9 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlaneArray.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreLineThroughPlaneArray.cpp @@ -138,7 +138,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::span(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStorePacked.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStorePacked.cpp index 427ebc94b078..93262be4318a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStorePacked.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStorePacked.cpp @@ -177,7 +177,7 @@ void Run(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::span(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; const auto result = ShaderRecompiler::Recompile(request); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreSint.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreSint.cpp index 8daddabd90c8..670081b62ca1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreSint.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreSint.cpp @@ -238,7 +238,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::span(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreUnormRounding.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreUnormRounding.cpp index bb6c6f25cf17..ffbcd129b4cb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreUnormRounding.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreUnormRounding.cpp @@ -207,7 +207,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::span(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreVolumeThroughArray.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreVolumeThroughArray.cpp index b82fa4ba0725..acd2e7530f40 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreVolumeThroughArray.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreVolumeThroughArray.cpp @@ -126,7 +126,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::size_t ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTexelStatus.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTexelStatus.cpp index 319faa1a0675..2c333ba4a6f0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTexelStatus.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTexelStatus.cpp @@ -231,7 +231,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::span co ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StorageFlushOrdering.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StorageFlushOrdering.cpp index ec90020045fa..0bc61f38e924 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StorageFlushOrdering.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StorageFlushOrdering.cpp @@ -131,7 +131,7 @@ bool AddressBasedStorePending(std::uint64_t image, bool open) { void Run(AgcDriver::VulkanDevice& device, const GuestBlock& guest, std::size_t offset, bool submit, const char* name) { const auto* words = guest.Words() + offset / 4u; const auto image = guest.Address() + offset; - const auto target = device.Target(); + const auto target = device.ComputeTarget(64); const auto storeImage = Compile(StoreImageCode, ImageUserData(image), target); const auto storeGlobal = Compile(StoreGlobalCode, GlobalUserData(image), target); device.Dispatch(storeImage, 1u, 1u, 1u, {}, reinterpret_cast(StoreImageCode.data())); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StorageOneSliceAlias.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StorageOneSliceAlias.cpp index 78437ac99d4f..cbb2b9b485e3 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StorageOneSliceAlias.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StorageOneSliceAlias.cpp @@ -129,7 +129,7 @@ void Dispatch(AgcDriver::VulkanDevice& device, std::span co ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ViewPastLastMip.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ViewPastLastMip.cpp index ec229885ef14..98c56fec3415 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ViewPastLastMip.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ViewPastLastMip.cpp @@ -64,7 +64,7 @@ void Store(AgcDriver::VulkanDevice& device, const std::uint32_t* texels, std::ui ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; From 1817bbed4b09e8452e4df769995c66fc13598b3f Mon Sep 17 00:00:00 2001 From: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:18:03 +0000 Subject: [PATCH 070/269] fix(agc): make no draw recipe from an address-space reuse build A recorded draw makes a recipe for its draw-cache entry from a reusable template, and the draw-cache hit replays it after proving the template with ProveCurrent. A space-reuse build is marked reusable, so it got a recipe too, but the resource-cache hit proves such a build differently: it retakes the cached address space (RetakeSpace) and checks that the draw's snapshots are served in place by it (SnapshotsServedInPlace). DrawWithRecipe does neither, so the recipe replayed the build after a snapshot inside its space had changed, where the resource-cache hit refuses it and builds anew. Its keepRecordedDraw also released a space the replay never retook, which dropped the build's released reference, so the next resource-cache hit failed RetakeSpace and built anew. recordPreparedDraw now makes no recipe from a build whose SpaceReuse() is set; the draw-cache hit for such a draw runs Draw, whose resource cache hit does both checks. agc_driver_address_draw_space_reuse draws a read-only BDA pixel shader over imported allocations. With APS5_GPU_HEAP=1 (the _heap registration) it checks that: - a draw repeated with unchanged inputs is served by the first draw's build; - a CPU write into the constant it reads is seen by the reused build; - a guest free inside the address space while the build is idle returns at once, and the next draw builds anew; - a draw asked for a recipe gets none, and after a snapshot inside the space changes the next draw builds anew. Without APS5_GPU_HEAP (the default registration) it checks that every repeated draw builds. On the previous commit the recipe case fails: "a draw recipe made from a build whose reuse retakes its address space recorded the draw (read 150) after a snapshot inside that space changed, with 0 builds, where the draw path builds anew". --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 6 + .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 2 +- .../tests/execution/AddressDrawSpaceReuse.cpp | 428 ++++++++++++++++++ 3 files changed, 435 insertions(+), 1 deletion(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 0f3fce8f83d7..985b02ceb17f 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -2438,6 +2438,12 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_address_passes_draw_transitions PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test(NAME agc_driver_address_draw_space_reuse_heap COMMAND agc_driver_address_draw_space_reuse_tests) + set_tests_properties(agc_driver_address_draw_space_reuse_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1" SKIP_RETURN_CODE 77 TIMEOUT 60) + if(WIN32) + set_tests_properties(agc_driver_address_draw_space_reuse_heap PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() set_target_properties(agc_driver_rcp_hardware_tests PROPERTIES EXCLUDE_FROM_ALL OFF) add_test(NAME agc_driver_rcp_hardware_exact COMMAND agc_driver_rcp_hardware_tests) set_tests_properties(agc_driver_rcp_hardware_exact PROPERTIES ENVIRONMENT "APS5_EXACT_RCP=1;ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 60) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 0b6dc916239a..850059a378cf 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -3418,7 +3418,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D // only a template the resource cache serves under this content key (reusable: no lease, // no copied writes, every direct region import- or mirror-served) of a direct draw, so a // hit's proof is the template's ProveCurrent and nothing needs completion work. - if (recipeOut != nullptr && DrawRecipes() && cacheable && !outcome.waited && args == nullptr && resources->Reusable() && resolved.moved.empty() && !multisampled && !pipeline->ReordersSamples()) { + if (recipeOut != nullptr && DrawRecipes() && cacheable && !outcome.waited && args == nullptr && resources->Reusable() && !resources->SpaceReuse() && resolved.moved.empty() && !multisampled && !pipeline->ReordersSamples()) { auto recipe = std::make_shared(); recipe->device = context.device; recipe->templateRef = resources; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp new file mode 100644 index 000000000000..f60f861fd85f --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp @@ -0,0 +1,428 @@ +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Recipe.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::ColorTargetLayout; +using AgcDriver::Graphics::ColorTileMode; +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Width = 64; +constexpr std::uint32_t Height = 64; +constexpr std::size_t BlockBytes = 65536; +constexpr std::size_t VertexCodeOffset = 0; +constexpr std::size_t PixelCodeOffset = 256; +constexpr std::size_t CapturedOffset = 1024; +constexpr std::uint32_t PinWaitMs = 4000; + +constexpr std::array VertexCode{ + 0xe0382000u, 0x80000005u, 0xbf8c3f70u, 0xf80008cfu, 0x03020100u, 0xbf810000u, +}; + +constexpr std::array PixelCode{ + 0x7e000280u, + 0xdc308000u, 0x01000000u, + 0xbf8c3f70u, + 0xf800180fu, 0x01010101u, + 0xbf810000u, +}; + +constexpr std::array, 3> Triangle{{ + {-1.0f, -1.0f, 0.5f, 1.0f}, {3.0f, -1.0f, 0.5f, 1.0f}, {-1.0f, 3.0f, 0.5f, 1.0f} +}}; + +const ColorTargetLayout TargetLayout(Width, Height, ColorTileMode::RenderTarget, 4); + +std::uint64_t AddressOf(const void* data) { + return static_cast(reinterpret_cast(data)); +} + +class Pages { +public: + explicit Pages(std::size_t bytes) : bytes(bytes) { +#ifdef _WIN32 + if (watched) { + data = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(bytes, BlockBytes)); + if (data != nullptr) GuestArena::GuestArenaCommit_nid_postfix(data, bytes, PAGE_READWRITE, bytes); + } else { + data = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + } +#else + if (watched) { + void* mapped = mmap(nullptr, bytes + BlockBytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(mapped != MAP_FAILED, "address draw space reuse: cannot map guest pages"); + const auto begin = reinterpret_cast(mapped); + const auto aligned = (begin + BlockBytes - 1) & ~(static_cast(BlockBytes) - 1); + if (aligned != begin) munmap(mapped, aligned - begin); + if (aligned + bytes != begin + bytes + BlockBytes) munmap(reinterpret_cast(aligned + bytes), begin + BlockBytes - aligned); + data = reinterpret_cast(aligned); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(data, bytes); + } else { + data = static_cast(std::aligned_alloc(BlockBytes, bytes)); + } +#endif + Require(data != nullptr, "address draw space reuse: cannot allocate guest pages"); + std::memset(data, 0, bytes); + } + + ~Pages() { + AgcDriver::Graphics::StorageTexture::FlushPending(Address(), bytes, nullptr, "test release"); + if (registered) GuestAllocations::Mutation().Remove(data); +#ifdef _WIN32 + if (watched) { + GuestArena::GuestArenaReset_nid_postfix(data, bytes); + GuestArena::GuestArenaRelease_nid_postfix(data, bytes); + } else { + VirtualFree(data, 0, MEM_RELEASE); + } +#else + if (watched) { + munmap(data, bytes); + GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(data, bytes); + } else { + std::free(data); + } +#endif + } + + Pages(const Pages&) = delete; + Pages& operator=(const Pages&) = delete; + + void Register(bool writable) { + GuestAllocations::Mutation().Add(data, bytes, true, writable, true); + registered = true; + } + + void Unregister() { + GuestAllocations::Mutation().Remove(data); + registered = false; + } + + std::uint64_t Address(std::size_t offset = 0) const { return AddressOf(data + offset); } + std::uint8_t* Data() { return data; } + +private: + std::size_t bytes; + bool watched = AgcDriver::GuestMemory::WriteWatched(); + std::uint8_t* data = nullptr; + bool registered = false; +}; + +std::uint64_t Builds() { + const auto counters = AgcDriver::Graphics::BdaResources::TableCacheCounters(); + return counters.hits + counters.misses; +} + +float Level(std::uint8_t value) { + return static_cast(value) / 255.0f; +} + +struct Scene { + AgcDriver::VulkanDevice& device; + Pages pixels{TargetLayout.Bytes()}; + Pages vertices{BlockBytes}; + Pages code{BlockBytes}; + Pages constants{BlockBytes}; + Pages spare{BlockBytes}; + std::deque vertexResults; + std::uint32_t vertexPush = 0; + std::deque pixelResults; + std::array shaders{}; + std::vector snapshots; + AgcDriver::Graphics::State state{}; + + explicit Scene(AgcDriver::VulkanDevice& device) : device(device) { + pixels.Register(true); + std::memcpy(vertices.Data(), Triangle.data(), sizeof(Triangle)); + vertices.Register(false); + std::memcpy(code.Data() + VertexCodeOffset, VertexCode.data(), sizeof(VertexCode)); + std::memcpy(code.Data() + PixelCodeOffset, PixelCode.data(), sizeof(PixelCode)); + code.Register(false); + constants.Register(true); + spare.Register(true); + Fetch(vertices, 0); + state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, 64u, 64u, std::nullopt, std::nullopt}; + state.color = {pixels.Address(), {Width, Height}, VK_FORMAT_R8G8B8A8_UNORM, TargetLayout.Bytes(), 0xe4u, ColorTileMode::RenderTarget}; + state.colors = {state.color}; + state.hasColorTarget = true; + state.renderExtent = {Width, Height}; + state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + state.viewport = {0, static_cast(Height), static_cast(Width), -static_cast(Height), 0, 1}; + state.negativeOneToOne = false; + state.scissor = {{0, 0}, {Width, Height}}; + state.cullMode = VK_CULL_MODE_NONE; + state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + state.blend.colorWriteMask = 15; + state.blends = {state.blend}; + state.blendConstants = {}; + Point(constants.Address()); + } + + void Fetch(Pages& source, std::size_t offset) { + const auto address = source.Address(offset); + const std::vector userData{static_cast(address), static_cast((address >> 32u) & 0xffffu) | (16u << 16u), static_cast((BlockBytes - offset) / 16u), 0x01016facu}; + const std::array vertexMemory{{{code.Address(VertexCodeOffset), std::as_bytes(std::span(VertexCode))}}}; + ShaderRecompiler::RecompileRequest vertex{ + {ShaderStage::Vertex, code.Address(VertexCodeOffset), VertexCode, 0, {}}, + {64, 0, userData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, vertexMemory}, + device.Target(), + {0, 0, 0, 64} + }; + vertex.useCache = true; + vertexResults.push_back(ShaderRecompiler::Recompile(vertex)); + if (vertexResults.size() > 8) vertexResults.pop_front(); + vertexPush = static_cast(vertexResults.back().pushConstants.size()); + shaders[0] = {ShaderStage::Vertex, &vertexResults.back(), 0}; + } + + void Point(std::uint64_t slot) { + const auto target = device.Target(); + ShaderRecompiler::ShaderPixelStageInfo pixel{}; + pixel.inputAddr = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionX) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionY); + pixel.posX = true; + pixel.posY = true; + pixel.targetOutputMode[0] = 9; + pixel.targetExportMapping.fill(0xe4u); + const std::vector userData{static_cast(slot), static_cast(slot >> 32u), 0u, 0u}; + const std::array pixelMemory{{{code.Address(PixelCodeOffset), std::as_bytes(std::span(PixelCode))}}}; + ShaderRecompiler::RecompileRequest fragment{ + {ShaderStage::Fragment, code.Address(PixelCodeOffset), PixelCode, 0, {}}, + {64, 0, userData, std::nullopt, pixel, std::nullopt, pixelMemory}, + target, + PixelPushLayout(vertexPush, target) + }; + fragment.useCache = true; + pixelResults.push_back(ShaderRecompiler::Recompile(fragment)); + if (pixelResults.size() > 8) pixelResults.pop_front(); + const auto& pixelResult = pixelResults.back(); + Require(std::any_of(pixelResult.bindings.begin(), pixelResult.bindings.end(), [](const auto& binding) { return binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable; }), "address draw space reuse: the pixel shader does not read guest memory through the BDA table"); + shaders[1] = {ShaderStage::Fragment, &pixelResult, PixelPushOffset(vertexPush, target)}; + snapshots = { + {code.Address(VertexCodeOffset), std::as_bytes(std::span(reinterpret_cast(code.Data() + VertexCodeOffset), VertexCode.size()))}, + {code.Address(PixelCodeOffset), std::as_bytes(std::span(reinterpret_cast(code.Data() + PixelCodeOffset), PixelCode.size()))}, + }; + } + + void Store(Pages& pages, std::size_t offset, std::uint8_t value) { + const auto level = Level(value); + std::memcpy(pages.Data() + offset, &level, sizeof(level)); + } + + void Draw(std::shared_ptr* recipe = nullptr) { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + const AgcDriver::Pm4::DrawParameters draw{0, static_cast(Triangle.size()), 0, 1, 0, false}; + device.Draw(state, draw, shaders, snapshots, recipe); + } + + AgcDriver::RecipeOutcome DrawFromRecipe(const std::shared_ptr& recipe) { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + const AgcDriver::Pm4::DrawParameters draw{0, static_cast(Triangle.size()), 0, 1, 0, false}; + return device.DrawFromRecipe(state, draw, shaders, snapshots, recipe); + } + + void Wait() { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + device.WaitIdle(); + } + + std::uint8_t Color() { + AgcDriver::Graphics::StorageTexture::FlushPending(pixels.Address(), TargetLayout.Bytes(), nullptr, "test read-back"); + Wait(); + std::vector texels(TargetLayout.Bytes()); + AgcDriver::GuestMemory::Read(pixels.Address(), std::as_writable_bytes(std::span(texels)), 1); + const auto first = texels[TargetLayout.Offset(0, 0)]; + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + const auto offset = TargetLayout.Offset(x, y); + for (std::size_t channel = 0; channel < 4; ++channel) Require(texels[offset + channel] == first, "address draw space reuse: the full-screen draw left texels of different values"); + } + } + return first; + } + + std::uint8_t DrawnColor() { + Draw(); + return Color(); + } + + void RequireFreeAtOnce(const std::string& after) { + Wait(); + const auto start = std::chrono::steady_clock::now(); + try { + spare.Unregister(); + } catch (const std::exception& error) { + throw std::runtime_error("address draw space reuse: a free inside the address space " + after + " failed: " + error.what()); + } + const auto waited = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + spare.Register(true); + Require(waited < PinWaitMs / 4.0, "address draw space reuse: a free inside the address space " + after + " waited " + std::to_string(waited) + " ms"); + } +}; + +bool Imported(Scene& scene) { + scene.Store(scene.constants, 0, 255); + const auto color = scene.DrawnColor(); + if (AgcDriver::Graphics::HostImportLiveBytes() == 0) return false; + Require(color == 255, "address draw space reuse: the first draw did not read the guest constant through the BDA table (" + std::to_string(color) + ")"); + return true; +} + +void UnchangedInputs(Scene& scene) { + scene.Store(scene.constants, 0, 200); + Require(scene.DrawnColor() == 200, "address draw space reuse: the draw before the repeat did not read the guest constant"); + const auto before = Builds(); + const auto color = scene.DrawnColor(); + Require(color == 200, "address draw space reuse: the repeated draw read " + std::to_string(color) + " instead of the guest constant 200"); + Require(Builds() == before, "address draw space reuse: a read-only address-based draw repeated with unchanged inputs over an imported allocation built its resources again (" + std::to_string(Builds() - before) + " builds)"); +} + +void CpuWrite(Scene& scene) { + scene.Store(scene.constants, 0, 120); + Require(scene.DrawnColor() == 120, "address draw space reuse: the draw before the CPU write did not read the guest constant"); + scene.Store(scene.constants, 0, 40); + const auto before = Builds(); + const auto color = scene.DrawnColor(); + Require(color == 40, "address draw space reuse: a draw after a CPU write into its constant read " + std::to_string(color) + " instead of the written 40"); + Require(Builds() == before, "address draw space reuse: a CPU write into memory the draw reads in place made it build its resources again (" + std::to_string(Builds() - before) + " builds)"); +} + +void IdleFree(Scene& scene) { + scene.Store(scene.constants, 0, 90); + Require(scene.DrawnColor() == 90, "address draw space reuse: the draw before the free did not read the guest constant"); + const auto before = Builds(); + Require(scene.DrawnColor() == 90 && Builds() == before, "address draw space reuse: the draw before the free was not served by the cached build"); + scene.RequireFreeAtOnce("while the cached build is idle"); + const auto rebuilt = Builds(); + Require(scene.DrawnColor() == 90, "address draw space reuse: the draw after the free did not read the guest constant"); + Require(Builds() == rebuilt + 1, "address draw space reuse: the draw after a free inside its address space did not build its resources again"); +} + +void RecipeAfterSnapshotChange(Scene& scene) { + scene.Store(scene.constants, 0, 150); + const auto plain = scene.snapshots; + std::array captured{}; + std::memcpy(captured.data(), scene.constants.Data() + CapturedOffset, captured.size()); + scene.snapshots.push_back({scene.constants.Address(CapturedOffset), captured}); + std::shared_ptr recipe; + scene.Draw(&recipe); + Require(scene.Color() == 150, "address draw space reuse: the draw asked for a recipe did not read the guest constant"); + scene.constants.Data()[CapturedOffset] ^= 0xffu; + const auto before = Builds(); + if (recipe != nullptr) { + const bool recorded = scene.DrawFromRecipe(recipe) == AgcDriver::RecipeOutcome::Recorded; + const auto color = scene.Color(); + Require(!recorded, "address draw space reuse: a draw recipe made from a build whose reuse retakes its address space recorded the draw (read " + std::to_string(color) + ") after a snapshot inside that space changed, with " + std::to_string(Builds() - before) + " builds, where the draw path builds anew"); + } + const auto color = scene.DrawnColor(); + const auto built = Builds() - before; + scene.constants.Data()[CapturedOffset] ^= 0xffu; + scene.snapshots = plain; + Require(color == 150 && built == 1, "address draw space reuse: the draw after a snapshot inside the address space changed read " + std::to_string(color) + " with " + std::to_string(built) + " builds, expected 150 and a build"); + Require(recipe == nullptr, "address draw space reuse: a draw recipe was made from a build whose reuse must retake its address space and check its snapshots"); +} + +void Disabled(Scene& scene) { + scene.Store(scene.constants, 0, 70); + Require(scene.DrawnColor() == 70, "address draw space reuse: the first draw with the reuse off did not read the guest constant"); + const auto before = Builds(); + Require(scene.DrawnColor() == 70, "address draw space reuse: the repeated draw with the reuse off did not read the guest constant"); + Require(Builds() == before + 1, "address draw space reuse: without APS5_GPU_HEAP a repeated address-based draw did not build its resources again"); +} + +void LimitPinWait() { + if (std::getenv("APS5_PIN_WAIT_MS") != nullptr) return; + const auto wait = std::to_string(PinWaitMs); +#ifdef _WIN32 + _putenv_s("APS5_PIN_WAIT_MS", wait.c_str()); +#else + setenv("APS5_PIN_WAIT_MS", wait.c_str(), 1); +#endif +} + +using Case = void (*)(Scene&); + +struct NamedCase { + const char* name; + Case run; +}; + +constexpr std::array Cases{{ + {"unchanged", UnchangedInputs}, + {"cpu-write", CpuWrite}, + {"idle-free", IdleFree}, + {"recipe-snapshot", RecipeAfterSnapshotChange}, +}}; + +} + +int main(int argc, char** argv) { + try { + const std::string mode = argc > 1 ? argv[1] : ""; + const std::string only = mode == "--case" && argc > 2 ? argv[2] : ""; + Require(mode.empty() || !only.empty(), "usage: [--case ]"); + LimitPinWait(); + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + const bool reuse = !AgcDriver::Graphics::ShaderResources::SpaceReuseDisabled(); + { + Scene scene(*device); + if (!Imported(scene)) { + std::puts("skipped, host imports are unavailable: the cached address space needs one"); + return VulkanTestSkipped; + } + if (!reuse) { + Require(only.empty(), "address draw space reuse: --case needs APS5_GPU_HEAP set"); + Disabled(scene); + } else { + bool ran = false; + for (const auto& entry : Cases) { + if (!only.empty() && only != entry.name) continue; + entry.run(scene); + ran = true; + } + Require(ran, "address draw space reuse: no case is named " + only); + } + scene.Wait(); + } + std::printf("address draw space reuse tests passed%s%s\n", reuse ? "" : " with the reuse off", only.empty() ? "" : (" " + only).c_str()); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} From 270d43a8657b6180025dc994af648cbf8e6bc512 Mon Sep 17 00:00:00 2001 From: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:21:25 +0000 Subject: [PATCH 071/269] fix(agc): give the cached address space back when a hit throws before it is served A resource-cache hit on a space-reuse build retakes the cached address space before it checks the build, and releases it again on the paths that do not serve it (snapshots not served in place, a failed proof, a moved buffer refused). A hit that throws after RetakeSpace and before it is served, as CheckBufferAliases does for a draw whose shader buffer aliases its render target, released nothing: the cached build kept the space, and with it a lease on every allocation in it, so a later guest free inside the space waited APS5_PIN_WAIT_MS and then failed as pinned. The hit now holds the retaken space in a guard that releases it on every exit that does not serve the hit, the throwing ones included, and is dismissed when the build is served. The explicit releases on the refusing paths are folded into it, so each path releases once. agc_driver_address_draw_space_reuse adds a case: after two draws that reuse the build, a draw whose vertex buffer reads the pages it renders to hits the cached build and is refused by CheckBufferAliases; a free inside the address space then has to return at once. On the previous commit it fails: "a free inside the address space after a hit that threw before it was served (AGC graphics: shader buffer aliases the render target) failed: guest allocation 0x...+0x10000 is still pinned by GPU work or an import (waited 4000 ms for the lease (APS5_PIN_WAIT_MS))". A failing case now reports its error and exits without tearing the scene down, whose frees would throw on pinned allocations. --- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 10 ++-- .../tests/execution/AddressDrawSpaceReuse.cpp | 56 +++++++++++++++---- 2 files changed, 48 insertions(+), 18 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 850059a378cf..f6bf8f85d1e9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1909,17 +1909,17 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat if (resolved.cacheable) { resolved.contentKey = DrawResourceKey(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, indexBytes, !trimKey); if (auto cached = SharedResourceCache().Find(resolved.contentKey)) { + const auto releaseSpace = [](ShaderResources* resources) { static_cast(resources->ReleaseSpace()); }; + std::unique_ptr heldSpace(cached->SpaceReuse() ? cached.get() : nullptr, releaseSpace); bool spaceHeld = !cached->SpaceReuse(); - if (!spaceHeld && cached->RetakeSpace()) { - spaceHeld = cached->SnapshotsServedInPlace(snapshots); - if (!spaceHeld) static_cast(cached->ReleaseSpace()); - } + if (!spaceHeld && cached->RetakeSpace()) spaceHeld = cached->SnapshotsServedInPlace(snapshots); const bool valid = spaceHeld && cached->Revalidate(shaders); auto* recorder = Recorder::Active(); std::optional> moved; if (valid && recorder != nullptr) moved = cached->MovedReadOnlyBuffers(shaders, *recorder, &state.color); if (moved.has_value()) { if (trimKey) CheckBufferAliases(shaders, state.color, draw.indexAddress, indexBytes); + static_cast(heldSpace.release()); resolved.resources = std::move(cached); resolved.moved = std::move(*moved); if (resolved.resources->HeapStage()) resolved.resources->RefreshHeapStage(shaders); @@ -1927,10 +1927,8 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat outcome.kind = KindTemplateHit; countCache(&DrawProfile::cacheHits); } else if (valid) { - if (cached->SpaceReuse()) static_cast(cached->ReleaseSpace()); countCache(&DrawProfile::cacheMisses); } else { - if (cached->SpaceReuse()) static_cast(cached->ReleaseSpace()); SharedResourceCache().Remove(resolved.contentKey); countCache(&DrawProfile::cacheInvalidated); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp index f60f861fd85f..99750c523930 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp @@ -159,6 +159,7 @@ struct Scene { Pages code{BlockBytes}; Pages constants{BlockBytes}; Pages spare{BlockBytes}; + Pages alias{BlockBytes}; std::deque vertexResults; std::uint32_t vertexPush = 0; std::deque pixelResults; @@ -175,6 +176,7 @@ struct Scene { code.Register(false); constants.Register(true); spare.Register(true); + alias.Register(true); Fetch(vertices, 0); state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, 64u, 64u, std::nullopt, std::nullopt}; state.color = {pixels.Address(), {Width, Height}, VK_FORMAT_R8G8B8A8_UNORM, TargetLayout.Bytes(), 0xe4u, ColorTileMode::RenderTarget}; @@ -356,6 +358,30 @@ void RecipeAfterSnapshotChange(Scene& scene) { Require(recipe == nullptr, "address draw space reuse: a draw recipe was made from a build whose reuse must retake its address space and check its snapshots"); } +void ThrowingHit(Scene& scene) { + scene.Store(scene.constants, 0, 110); + for (int warm = 0; warm < 2; ++warm) Require(scene.DrawnColor() == 110, "address draw space reuse: the draw before the aliasing draw did not read the guest constant"); + const auto color = scene.state.color; + scene.state.color.address = scene.alias.Address(); + scene.state.colors = {scene.state.color}; + scene.Fetch(scene.alias, 0); + const auto before = Builds(); + std::string refused; + try { + scene.Draw(); + } catch (const std::exception& error) { + refused = error.what(); + } + const auto built = Builds() - before; + scene.state.color = color; + scene.state.colors = {color}; + scene.Fetch(scene.vertices, 0); + Require(!refused.empty(), "address draw space reuse: a draw whose vertex buffer aliases its render target was recorded"); + Require(built == 0, "address draw space reuse: the draw whose vertex buffer aliases its render target built its resources (" + std::to_string(built) + " builds) instead of hitting the cached build"); + scene.RequireFreeAtOnce("after a hit that threw before it was served (" + refused + ")"); + Require(scene.DrawnColor() == 110, "address draw space reuse: the draw after the refused aliasing draw did not read the guest constant"); +} + void Disabled(Scene& scene) { scene.Store(scene.constants, 0, 70); Require(scene.DrawnColor() == 70, "address draw space reuse: the first draw with the reuse off did not read the guest constant"); @@ -381,11 +407,12 @@ struct NamedCase { Case run; }; -constexpr std::array Cases{{ +constexpr std::array Cases{{ {"unchanged", UnchangedInputs}, {"cpu-write", CpuWrite}, {"idle-free", IdleFree}, {"recipe-snapshot", RecipeAfterSnapshotChange}, + {"throwing-hit", ThrowingHit}, }}; } @@ -405,19 +432,24 @@ int main(int argc, char** argv) { std::puts("skipped, host imports are unavailable: the cached address space needs one"); return VulkanTestSkipped; } - if (!reuse) { - Require(only.empty(), "address draw space reuse: --case needs APS5_GPU_HEAP set"); - Disabled(scene); - } else { - bool ran = false; - for (const auto& entry : Cases) { - if (!only.empty() && only != entry.name) continue; - entry.run(scene); - ran = true; + try { + if (!reuse) { + Require(only.empty(), "address draw space reuse: --case needs APS5_GPU_HEAP set"); + Disabled(scene); + } else { + bool ran = false; + for (const auto& entry : Cases) { + if (!only.empty() && only != entry.name) continue; + entry.run(scene); + ran = true; + } + Require(ran, "address draw space reuse: no case is named " + only); } - Require(ran, "address draw space reuse: no case is named " + only); + scene.Wait(); + } catch (const std::exception& error) { + std::cerr << error.what() << std::endl; + std::_Exit(1); } - scene.Wait(); } std::printf("address draw space reuse tests passed%s%s\n", reuse ? "" : " with the reuse off", only.empty() ? "" : (" " + only).c_str()); return 0; From 758d23c805b49db9f506dc04aa717f504d08c357 Mon Sep 17 00:00:00 2001 From: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> Date: Sat, 31 Oct 2026 01:25:59 +0000 Subject: [PATCH 072/269] fix(agc): give the retaken address space back when a draw ends without recording it A served space-reuse hit keeps the retaken address space until keepRecordedDraw hands it to the recorder. Two paths leave it held: - the transition path (APS5_DRAW_TRANSITIONS=1, not lean) builds a hit with moved buffers afresh and drops the template without releasing its space; - a draw that ends after the hit without keepRecordedDraw, such as an indirect draw whose records are all empty (prepareDraw returns false), or a throw in prepareDraw or recordPreparedDraw. The cached build then holds a lease on every allocation in the space, and a later guest free inside it waits APS5_PIN_WAIT_MS and fails as pinned. The transition path now releases the template's space before it builds anew. Draw releases a space still held when the draw ends, into the active recorder, so it lives as long as the work recorded so far. That release runs after keepRecordedDraw has already released the space on every recorded draw, so ReleaseSpace now returns nothing and keeps the released reference when no space is held: before, a second call reset the reference and the next RetakeSpace failed. agc_driver_address_draw_space_reuse adds two cases and an APS5_DRAW_TRANSITIONS=1 registration (_heap_transitions): - a draw whose read-only vertex buffer moved inside the space renders, and a free after it returns at once; - an indirect draw with no records after two reused draws hits the cached build without building, and a free after it returns at once. On the previous commit the second fails in both registrations ("a free inside the address space after an indirect draw without records ended after its resource-cache hit failed: ... still pinned by GPU work or an import (waited 4000 ms for the lease (APS5_PIN_WAIT_MS))"), and the first fails with APS5_DRAW_TRANSITIONS=1 ("... after the transition path built a draw whose vertex buffer moved anew failed: ..."). With the Draw release but without the ReleaseSpace change, a draw repeated with unchanged inputs builds its resources again. --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 6 +++ .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 10 +++++ .../Graphics/src/GuestBufferMemory.cpp | 1 + .../tests/execution/AddressDrawSpaceReuse.cpp | 38 ++++++++++++++++++- 4 files changed, 54 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 985b02ceb17f..7ec6cbfce74e 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -2444,6 +2444,12 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_address_draw_space_reuse_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test(NAME agc_driver_address_draw_space_reuse_heap_transitions COMMAND agc_driver_address_draw_space_reuse_tests) + set_tests_properties(agc_driver_address_draw_space_reuse_heap_transitions PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_DRAW_TRANSITIONS=1" SKIP_RETURN_CODE 77 TIMEOUT 60) + if(WIN32) + set_tests_properties(agc_driver_address_draw_space_reuse_heap_transitions PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() set_target_properties(agc_driver_rcp_hardware_tests PROPERTIES EXCLUDE_FROM_ALL OFF) add_test(NAME agc_driver_rcp_hardware_exact COMMAND agc_driver_rcp_hardware_tests) set_tests_properties(agc_driver_rcp_hardware_exact PROPERTIES ENVIRONMENT "APS5_EXACT_RCP=1;ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 60) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index f6bf8f85d1e9..0aa22b1d625a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -3271,6 +3271,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara Require(std::ranges::any_of(images, [&](const std::pair& image) { return image.first == binding.resident->Image() && image.second; }), "the partial write of a packed color target does not store into the target's resident image"); } if (!lean && !resolved.moved.empty()) { + if (resolved.resources->SpaceReuse()) static_cast(resolved.resources->ReleaseSpace()); resolved.resources = std::make_shared(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, static_cast(indexBytes), snapshots); resolved.moved.clear(); } @@ -3799,6 +3800,15 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters& prepared.recipeOut = recipeOut; prepared.trace = trace; prepared.shape = shape; + const struct HeldSpace { + PreparedDraw& prepared; + ~HeldSpace() { + const auto& resources = prepared.resolved.resources; + if (resources == nullptr || !resources->SpaceReuse()) return; + auto space = resources->ReleaseSpace(); + if (space != nullptr && prepared.recorder != nullptr) prepared.recorder->Keep(std::const_pointer_cast(std::move(space))); + } + } heldSpace{prepared}; if (prepareDraw(context, state, draw, shaders, snapshots, prepared)) recordPreparedDraw(context, state, draw, shaders, prepared); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index a3feea7ed176..2c2f9c18549d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -4934,6 +4934,7 @@ bool GuestBufferMemory::SpaceOnly() const { } std::shared_ptr GuestBufferMemory::ReleaseSpace() { + if (space == nullptr) return {}; releasedSpace = space; return std::move(space); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp index 99750c523930..790568f8e9ee 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp @@ -48,6 +48,9 @@ constexpr std::size_t BlockBytes = 65536; constexpr std::size_t VertexCodeOffset = 0; constexpr std::size_t PixelCodeOffset = 256; constexpr std::size_t CapturedOffset = 1024; +constexpr std::size_t RecordsOffset = 2048; +constexpr std::size_t MovedVerticesOffset = 32768; +constexpr std::uint32_t NoLocation = 0x280u; constexpr std::uint32_t PinWaitMs = 4000; constexpr std::array VertexCode{ @@ -170,6 +173,7 @@ struct Scene { explicit Scene(AgcDriver::VulkanDevice& device) : device(device) { pixels.Register(true); std::memcpy(vertices.Data(), Triangle.data(), sizeof(Triangle)); + std::memcpy(vertices.Data() + MovedVerticesOffset, Triangle.data(), sizeof(Triangle)); vertices.Register(false); std::memcpy(code.Data() + VertexCodeOffset, VertexCode.data(), sizeof(VertexCode)); std::memcpy(code.Data() + PixelCodeOffset, PixelCode.data(), sizeof(PixelCode)); @@ -251,6 +255,13 @@ struct Scene { device.Draw(state, draw, shaders, snapshots, recipe); } + void DrawWithoutRecords() { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + AgcDriver::Pm4::DrawParameters draw{0, 0, 0, 0, 0, false, 0, 0}; + draw.indirect = AgcDriver::Pm4::DrawParameters::IndirectDraw{constants.Address(RecordsOffset), 0x24u, 16u, 16u, 0u, false, 0u, NoLocation, NoLocation, NoLocation, false, 0u}; + device.Draw(state, draw, shaders, snapshots); + } + AgcDriver::RecipeOutcome DrawFromRecipe(const std::shared_ptr& recipe) { std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); const AgcDriver::Pm4::DrawParameters draw{0, static_cast(Triangle.size()), 0, 1, 0, false}; @@ -382,6 +393,29 @@ void ThrowingHit(Scene& scene) { Require(scene.DrawnColor() == 110, "address draw space reuse: the draw after the refused aliasing draw did not read the guest constant"); } +void MovedVertices(Scene& scene) { + scene.Store(scene.constants, 0, 170); + for (int warm = 0; warm < 2; ++warm) Require(scene.DrawnColor() == 170, "address draw space reuse: the draw before the vertex buffer moved did not read the guest constant"); + const auto before = Builds(); + scene.Fetch(scene.vertices, MovedVerticesOffset); + const auto color = scene.DrawnColor(); + scene.Fetch(scene.vertices, 0); + Require(color == 170, "address draw space reuse: the draw after its read-only vertex buffer moved read " + std::to_string(color) + " instead of 170"); + const bool transitions = std::getenv("APS5_DRAW_TRANSITIONS") != nullptr; + Require(transitions || Builds() == before, "address draw space reuse: the draw whose read-only vertex buffer moved inside the space built its resources (" + std::to_string(Builds() - before) + " builds) instead of binding the moved buffer to the cached build"); + scene.RequireFreeAtOnce(transitions ? "after the transition path built a draw whose vertex buffer moved anew" : "after a draw whose vertex buffer moved inside it"); +} + +void NoRecords(Scene& scene) { + scene.Store(scene.constants, 0, 60); + for (int warm = 0; warm < 2; ++warm) Require(scene.DrawnColor() == 60, "address draw space reuse: the draw before the indirect draw did not read the guest constant"); + const auto before = Builds(); + scene.DrawWithoutRecords(); + Require(Builds() == before, "address draw space reuse: the indirect draw without records built its resources (" + std::to_string(Builds() - before) + " builds) instead of hitting the cached build"); + scene.RequireFreeAtOnce("after an indirect draw without records ended after its resource-cache hit"); + Require(scene.DrawnColor() == 60, "address draw space reuse: the draw after the indirect draw did not read the guest constant"); +} + void Disabled(Scene& scene) { scene.Store(scene.constants, 0, 70); Require(scene.DrawnColor() == 70, "address draw space reuse: the first draw with the reuse off did not read the guest constant"); @@ -407,12 +441,14 @@ struct NamedCase { Case run; }; -constexpr std::array Cases{{ +constexpr std::array Cases{{ {"unchanged", UnchangedInputs}, {"cpu-write", CpuWrite}, {"idle-free", IdleFree}, {"recipe-snapshot", RecipeAfterSnapshotChange}, {"throwing-hit", ThrowingHit}, + {"moved-vertices", MovedVertices}, + {"no-records", NoRecords}, }}; } From 229b9883ce74ae9c633a8da1068d5cd5ee83ce5a Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 07:51:18 +0530 Subject: [PATCH 073/269] perf(agc): read GPU heap shader data as a uniform buffer mapped from the resource heap and keep descriptor heaps device-local Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/VulkanDevice.cpp | 6 +- .../Graphics/include/BindlessHeap.hpp | 8 +- .../Graphics/src/BindlessHeap.cpp | 106 ++++++++++++++---- .../Graphics/src/ShaderResources.cpp | 3 +- .../Graphics/src/ShaderValidation.cpp | 6 + .../tests/BindlessHeapSlots.cpp | 4 +- core/shader/recompiler/CacheKey.hpp | 1 + core/shader/recompiler/Recompiler.cpp | 1 + core/shader/recompiler/Recompiler.hpp | 1 + .../include/SpirvBackend/SpirvEmitter.hpp | 1 + .../SpirvBackend/SpirvEmitterState.hpp | 2 + .../SpirvBackend/src/SpirvEmitter.cpp | 1 + .../src/SpirvMemory/SpirvBufferAccess.cpp | 10 ++ .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 5 + docs/dev/ENVIRONMENT.md | 2 + 15 files changed, 131 insertions(+), 26 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 6870c2212f6f..f15896c0c50e 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -537,6 +537,7 @@ struct VulkanDevice::State { std::unique_ptr detiler; bool descriptorHeap = false; VkPhysicalDeviceDescriptorHeapPropertiesEXT descriptorHeapProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_PROPERTIES_EXT}; + std::uint32_t heapDataUniformDwords = 0; std::unique_ptr recorder; // Device-local buffers of a repeated 16-byte fill pattern (FillBuffer), most recently used // last; each is filled once by a doubling chain in device memory. @@ -1947,6 +1948,8 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : if (descriptorHeapFeatures.descriptorHeap == VK_TRUE && heapMaintenance5.maintenance5 == VK_TRUE && Graphics::BindlessHeap::Fits(state->descriptorHeapProperties)) { state->descriptorHeap = true; state->maintenance5 = true; + if (Graphics::BindlessHeap::RingInResourceHeap(state->descriptorHeapProperties, state->properties.limits.minUniformBufferOffsetAlignment)) + state->heapDataUniformDwords = std::min(16384u, state->properties.limits.maxUniformBufferRange / 4u); deviceExtensions.push_back(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME); for (const char* required : {VK_KHR_MAINTENANCE_5_EXTENSION_NAME, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME}) { if (std::find_if(deviceExtensions.begin(), deviceExtensions.end(), [&](const char* name) { return std::strcmp(name, required) == 0; }) == deviceExtensions.end()) deviceExtensions.push_back(required); @@ -4143,6 +4146,7 @@ ShaderRecompiler::SpirvTarget VulkanDevice::Target() const { target.fusedExactArithmetic = state->fusedExactArithmetic; target.float32DenormPreserve = state->float32DenormPreserve; target.descriptorMemory = Graphics::DescriptorHeapEnabled(); + target.heapDataUniformDwords = target.descriptorMemory ? state->heapDataUniformDwords : 0u; return target; } @@ -5364,7 +5368,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { Graphics::Recorder::CountMerged(CommandClass::DispatchLeading); } else { const auto timing = recorder.BeginGpuTiming(CommandClass::DispatchLeading); - Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); + Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); Graphics::Recorder::CountBarriers(CommandClass::DispatchLeading); recorder.EndGpuTiming(timing); ++d.preBarriersRecorded; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 9a371f9ba0b4..7c0038c45c71 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -33,6 +33,7 @@ class BindlessHeap { static BindlessHeap* Existing(const Context& context); static void Release(VkDevice device); static bool Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties); + static bool RingInResourceHeap(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, VkDeviceSize uniformAlignment); bool DescriptorHeapMode() const { return resourceHeap != nullptr; } VkDeviceSize ImageHeapStride() const { return imageHeapStride; } @@ -45,6 +46,7 @@ class BindlessHeap { void WriteMeshWindowBuffer(VkDeviceAddress address, VkDeviceSize bytes); VkDeviceAddress RingAddress() const; VkBuffer RingBuffer() const; + VkDeviceSize RingOffset() const; std::optional TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, VkImageLayout layout); @@ -91,10 +93,15 @@ class BindlessHeap { Counts Statistics() const; static constexpr std::size_t RingBytes = 64u << 20u; + static constexpr std::size_t RingChunkBytes = 2u << 20u; private: Context context; std::unique_ptr ring; + std::byte* ringData = nullptr; + std::size_t ringBytes = RingBytes; + VkDeviceSize ringHeapOffset = 0; + bool ringInHeap = false; std::unique_ptr resourceHeap; std::unique_ptr samplerHeap; VkDeviceSize imageHeapStride = 0; @@ -109,7 +116,6 @@ class BindlessHeap { void writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImageView view, VkImageLayout layout); void writeSamplerSlot(std::uint32_t slot, VkSampler sampler); void writeBufferDescriptor(VkDeviceSize offset, VkDeviceAddress address, VkDeviceSize bytes, const char* what); - static constexpr std::size_t RingChunkBytes = 4u << 20u; struct Chunk { Recorder* recorder = nullptr; std::uint64_t serial = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index a3c4657c37f2..e2bf5a41f7c5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -147,6 +147,31 @@ HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& propertie } +namespace { + +struct ResourceRing { + VkDeviceSize offset = 0; + std::size_t bytes = 0; +}; + +ResourceRing resourceRing(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, VkDeviceSize uniformAlignment) { + static const bool disabled = std::getenv("APS5_NO_HEAP_DATA_UNIFORM") != nullptr; + if (disabled) return {}; + const auto sizes = heapSizes(properties); + const auto offset = alignUp(sizes.resourceUsed + properties.minResourceHeapReservedRange, std::max(uniformAlignment, properties.resourceHeapAlignment)); + if (offset >= properties.maxResourceHeapSize) return {}; + const auto room = static_cast(properties.maxResourceHeapSize - offset) / BindlessHeap::RingChunkBytes * BindlessHeap::RingChunkBytes; + const auto bytes = std::min(room, BindlessHeap::RingBytes); + if (bytes < 2u * BindlessHeap::RingChunkBytes) return {}; + return {offset, bytes}; +} + +} + +bool BindlessHeap::RingInResourceHeap(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, VkDeviceSize uniformAlignment) { + return resourceRing(properties, uniformAlignment).bytes != 0u; +} + bool BindlessHeap::Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { const auto sizes = heapSizes(properties); const bool resourcesFit = sizes.resourceUsed + properties.minResourceHeapReservedRange <= properties.maxResourceHeapSize; @@ -181,24 +206,39 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { meshWindowHeapOffset = sizes.meshWindowOffset; samplerHeapUsed = sizes.samplerUsed; Require(Fits(heapProperties), "the GPU heap's slots exceed the device's descriptor heap sizes"); + static const bool hostDescriptors = std::getenv("APS5_NO_HEAP_DEVICE_DESCRIPTORS") != nullptr; + constexpr VkMemoryPropertyFlags deviceVisible = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + const auto makeBuffer = [&](std::size_t bytes, VkBufferUsageFlags usage, bool deviceLocal) { + if (deviceLocal) { + try { + return std::make_unique(context, bytes, usage, deviceVisible); + } catch (const std::exception&) { + } + } + return std::make_unique(context, bytes, usage); + }; + constexpr VkBufferUsageFlags ringUsage = + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; constexpr VkBufferUsageFlags heapUsage = VK_BUFFER_USAGE_DESCRIPTOR_HEAP_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - resourceHeap = std::make_unique( - context, static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange), heapUsage); - samplerHeap = std::make_unique( - context, static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage); + const auto heapRing = resourceRing(heapProperties, context.limits.minUniformBufferOffsetAlignment); + ringInHeap = heapRing.bytes != 0u; + const auto resourceBytes = ringInHeap ? static_cast(heapRing.offset) + heapRing.bytes + : static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange); + resourceHeap = makeBuffer(resourceBytes, ringInHeap ? heapUsage | ringUsage : heapUsage, ringInHeap || !hostDescriptors); + samplerHeap = makeBuffer(static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage, !hostDescriptors); std::fill(resourceHeap->Bytes().begin(), resourceHeap->Bytes().end(), std::byte{0}); std::fill(samplerHeap->Bytes().begin(), samplerHeap->Bytes().end(), std::byte{0}); - constexpr VkBufferUsageFlags ringUsage = - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - try { - ring = std::make_unique(context, RingBytes, ringUsage, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - } catch (const std::exception&) { - ring = std::make_unique(context, RingBytes, ringUsage); + if (ringInHeap) { + ringHeapOffset = heapRing.offset; + ringBytes = heapRing.bytes; + ringData = resourceHeap->Bytes().data() + ringHeapOffset; + ringAlignment = static_cast(std::max({context.limits.minStorageBufferOffsetAlignment, context.limits.minUniformBufferOffsetAlignment, 16})); + } else { + ring = makeBuffer(RingBytes, ringUsage, true); + ringData = ring->Bytes().data(); + ringAlignment = static_cast(std::max(context.limits.minStorageBufferOffsetAlignment, 16)); } - ringAlignment = static_cast(std::max(context.limits.minStorageBufferOffsetAlignment, 16)); - ringChunks.resize(RingBytes / RingChunkBytes); + ringChunks.resize(ringBytes / RingChunkBytes); nextTextureSlot = SamplerKind; slotCap = configuredSlotCap(); } @@ -695,11 +735,11 @@ bool BindlessHeap::Held(const SpanMark& mark) { } BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) { - const auto bytes = words * sizeof(std::uint32_t); + const auto bytes = ringInHeap ? (words * sizeof(std::uint32_t) + 15u) / 16u * 16u : words * sizeof(std::uint32_t); if (bytes > RingChunkBytes) throw std::runtime_error("AGC bindless heap: per-draw data exceeds a ring chunk"); std::lock_guard lock(mutex); auto offset = (ringCursor + ringAlignment - 1) / ringAlignment * ringAlignment; - if (offset + bytes > RingBytes) { + if (offset + bytes > ringBytes) { offset = 0; ++counts.ringWraps; } @@ -713,7 +753,7 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) for (std::size_t skipped = 0; keptAhead(); ++skipped) { if (skipped == ringChunks.size()) throw std::runtime_error("AGC bindless heap: one batch's shader data exceeds its ring"); offset = (offset / RingChunkBytes + 1u) * RingChunkBytes; - if (offset + bytes > RingBytes) { + if (offset + bytes > ringBytes) { offset = 0; ++counts.ringWraps; } @@ -721,7 +761,7 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) } ringCursor = offset + bytes; for (auto chunk = offset / RingChunkBytes; chunk <= lastChunk(); ++chunk) enterChunk(ringChunks, chunk, ringChunk, "shader data"); - auto* base = reinterpret_cast(ring->Bytes().data() + offset); + auto* base = reinterpret_cast(ringData + offset); ++counts.spansWritten; spansWrittenWindow.fetch_add(1, std::memory_order_relaxed); mark = {static_cast(offset), static_cast(words), ringChunks[offset / RingChunkBytes].entries}; @@ -806,6 +846,7 @@ struct HeapBindingUse { bool faultMemory = false; bool pixelLdsMemory = false; bool meshWindowMemory = false; + std::vector dataUniforms; std::pair refused{~0u, ~0u}; }; @@ -861,6 +902,10 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& use.meshWindowMemory = true; continue; } + if (set == Abi::GpuDataSet && binding % bindingCount == static_cast(Abi::Binding::ShaderData) && binding / bindingCount < Abi::StageCount) { + use.dataUniforms.push_back(binding); + continue; + } const bool heapImageOrSampler = set == Abi::FragmentDescriptorSet && binding >= firstImage && binding <= samplers; if (!heapImageOrSampler) { use.refused = entry; @@ -944,6 +989,21 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, heapMapping(Abi::FragmentDescriptorSet, binding, VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT, 0, samplerHeapStride)); else mappings.push_back(heapMapping(Abi::FragmentDescriptorSet, binding, imageResources, 0, imageHeapStride)); } + if (!use.dataUniforms.empty() && !ringInHeap) { + mappings.clear(); + return false; + } + for (const auto binding : use.dataUniforms) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = Abi::GpuDataSet; + mapping.firstBinding = binding; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_RESOURCE_HEAP_DATA_EXT; + mapping.sourceData.heapData.heapOffset = static_cast(ringHeapOffset); + mapping.sourceData.heapData.pushOffset = rootAddressOffset(Abi::RootStageDword(static_cast(binding / bindingCount), Abi::RootStageField::ShaderData)); + mappings.push_back(mapping); + } if (use.workgroupMemory) mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset)); if (use.gdsBinding != ~0u) @@ -1155,7 +1215,7 @@ void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { heapBinds.fetch_add(1, std::memory_order_relaxed); heapBindWindow.fetch_add(1, std::memory_order_relaxed); VkBindHeapInfoEXT info{VK_STRUCTURE_TYPE_BIND_HEAP_INFO_EXT}; - info.heapRange = {resourceHeap->DeviceAddress(), resourceHeapUsed + context.descriptorHeapProperties.minResourceHeapReservedRange}; + info.heapRange = {resourceHeap->DeviceAddress(), ringInHeap ? ringHeapOffset + ringBytes : resourceHeapUsed + context.descriptorHeapProperties.minResourceHeapReservedRange}; info.reservedRangeOffset = resourceHeapUsed; info.reservedRangeSize = context.descriptorHeapProperties.minResourceHeapReservedRange; context.Function("vkCmdBindResourceHeapEXT")(commands, &info); @@ -1167,11 +1227,15 @@ void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { } VkDeviceAddress BindlessHeap::RingAddress() const { - return ring->DeviceAddress(); + return ringInHeap ? resourceHeap->DeviceAddress() + ringHeapOffset : ring->DeviceAddress(); } VkBuffer BindlessHeap::RingBuffer() const { - return ring->Handle(); + return ringInHeap ? resourceHeap->Handle() : ring->Handle(); +} + +VkDeviceSize BindlessHeap::RingOffset() const { + return ringInHeap ? ringHeapOffset : 0; } void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index da2a579b6c0b..681f63f0c59b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6199,7 +6199,8 @@ std::size_t DataOffsetIndex(std::size_t stage, ShaderRecompiler::RuntimeAbi::Bin std::pair ShaderResources::shaderDataLocation(const CompiledShader& shader, const DrawBindings* rewritten) const { if (!heapStage || shader.program == nullptr || !shader.program->gpuResolvedImages) return {shaderDataBuffer(shader), 0}; const auto& offsets = rewritten != nullptr && rewritten->addressOffsets ? rewritten->heapOffsets : heapOffsets; - return {BindlessHeap::For(context).RingBuffer(), offsets[DataOffsetIndex(HeapStageIndex(shader.stage), ShaderRecompiler::RuntimeAbi::Binding::ShaderData)]}; + const auto& heap = BindlessHeap::For(context); + return {heap.RingBuffer(), heap.RingOffset() + offsets[DataOffsetIndex(HeapStageIndex(shader.stage), ShaderRecompiler::RuntimeAbi::Binding::ShaderData)]}; } void ShaderResources::PatchDataAddresses(std::span bytes, std::span shaders, const DrawBindings* rewritten) const { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index 0ad7fa9e0bcd..06f2e511032f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -612,6 +612,12 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi } else { Require(binding->count != 0u && binding->count <= capacity && count != module.constants.end() && count->second == binding->count, "typed heap array length disagrees with compact binding"); } + } else if (variable.storage == spv::StorageClassUniform) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + Require(shader.dataAddressPush && decoration.set && decoration.binding && *decoration.set == Abi::GpuDataSet && + *decoration.binding % bindingCount == static_cast(Abi::Binding::ShaderData), + "a uniform buffer is only the GPU heap's shader data"); } else { Require(variable.storage == spv::StorageClassStorageBuffer && decoration.set && decoration.binding, "unsupported or unbound shader resource"); const auto key = std::make_pair(*decoration.set, *decoration.binding); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 1417382e6e55..cad3ef158c4d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -152,7 +152,7 @@ void ringSpans(const Context& context) { BindlessHeap::SpanMark first; const auto span = heap.Allocate(16u, first); require(first.offset == span.offset && first.words == 16u && heap.Held(first), "a span written in the open chunk is held"); - constexpr std::size_t chunkWords = (4u << 20u) / sizeof(std::uint32_t); + constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); BindlessHeap::SpanMark filler; static_cast(heap.Allocate(chunkWords - 1024u, filler)); BindlessHeap::SpanMark crossing; @@ -173,7 +173,7 @@ void ringSpans(const Context& context) { while (heap.Statistics().ringWraps == wraps) last = heap.Allocate(chunkWords, fill); return last.offset; }; - require(untilWrap() == (4u << 20u), "the ring skips a chunk a later batch still reads kept spans from"); + require(untilWrap() == AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips a chunk a later batch still reads kept spans from"); require(heap.Held(first), "the skipped chunk's kept span is still held"); require(heap.Statistics().keptChunksSkipped == 1u, "one kept chunk skipped"); heap.Submitted(recorder, 0u); diff --git a/core/shader/recompiler/CacheKey.hpp b/core/shader/recompiler/CacheKey.hpp index ca35ed548589..c9b803dd07b6 100644 --- a/core/shader/recompiler/CacheKey.hpp +++ b/core/shader/recompiler/CacheKey.hpp @@ -360,6 +360,7 @@ class RecompileCacheKey { append(key, value.deviceScopeLdsMemoryBarriers); append(key, value.gpuResolvedImages); append(key, value.descriptorMemory); + append(key, value.heapDataUniformDwords); append(key, value.ldsLockFences); append(key, value.meshWindowBuffer); } diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 1a8d90238047..9a8ce742407c 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -768,6 +768,7 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) targetOptions.waveLdsMemoryBarriers = request.target.waveLdsMemoryBarriers; targetOptions.deviceScopeLdsMemoryBarriers = request.target.deviceScopeLdsMemoryBarriers; targetOptions.gpuResolvedImages = gpuMode; + targetOptions.heapDataUniformDwords = request.target.heapDataUniformDwords; targetOptions.ldsLockFences = request.target.ldsLockFences; targetOptions.meshWindowBuffer = request.target.meshWindowBuffer; diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 46f5011723d6..0833c0fab006 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -351,6 +351,7 @@ struct SpirvTarget { bool deviceScopeLdsMemoryBarriers = false; bool gpuResolvedImages = false; bool descriptorMemory = false; + std::uint32_t heapDataUniformDwords = 0; bool ldsLockFences = false; bool fragmentBarycentricBuiltins = false; bool meshWindowBuffer = false; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp index ffee9ce646eb..6ee08e86ff81 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp @@ -44,6 +44,7 @@ struct SpirvTargetOptions { std::uint32_t pixelFunctionStorageDwords = 4096u; bool deviceScopeLdsMemoryBarriers = false; bool gpuResolvedImages = false; + std::uint32_t heapDataUniformDwords = 0; bool ldsLockFences = false; bool meshWindowBuffer = false; }; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index c9dfee948ca3..8eab6eab3d08 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -112,6 +112,7 @@ struct SpirvEmitterState { std::uint32_t depthRemapClipIndex = 0; bool registrationModules = false; bool gpuResolvedImages = false; + std::uint32_t heapDataUniformDwords = 0; bool addressedBuffers = false; std::optional guestBuffersWritten; bool fragmentDescriptorSet = false; @@ -213,6 +214,7 @@ struct SpirvEmitterState { std::uint32_t gdsLength = 0; std::uint32_t pushConstantVariable = 0; std::uint32_t shaderDataStorageVariable = 0; + std::uint32_t shaderDataUniformVariable = 0; std::unordered_map heapSlotVariables; std::uint32_t flattenedSrtVariable = 0; bool flattenedSrtAddressed = false; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp index df493ab5a2a6..3bfc0981acc6 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp @@ -267,6 +267,7 @@ std::vector SpirvEmitter::Emit(const IrProgram& program, const Sh state.depthRangeRemap = target.depthRangeRemap; state.registrationModules = target.registrationModules; state.gpuResolvedImages = target.gpuResolvedImages; + state.heapDataUniformDwords = target.heapDataUniformDwords; state.fragmentDescriptorSet = target.fragmentDescriptorSet; state.meshBarycentricPixel = target.meshBarycentricPixel; state.meshBarycentricVertex = target.meshBarycentricVertex; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 39cf7d6996db..0dd703bd0ce6 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -110,6 +110,16 @@ std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::Roo namespace { std::uint32_t dataAddressLoad(SpirvEmitterState& state, RuntimeAbi::RootStageField field, std::uint32_t index) { + if (field == RuntimeAbi::RootStageField::ShaderData && state.shaderDataUniformVariable != 0u) { + const auto u32 = TypeU32(state); + const auto vector = Binary(state, spv::OpShiftRightLogical, u32, index, ConstantU32(state, 2u)); + const auto component = Binary(state, spv::OpBitwiseAnd, u32, index, ConstantU32(state, 3u)); + const auto element = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassUniform, u32), element, state.shaderDataUniformVariable, ConstantU32(state, 0u), vector, component); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, u32, value, element); + return value; + } const auto pointer = EmitStageRingWordPointer(state, field, index); const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, spv::MemoryAccessAlignedMask, 4u); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index b538a091a3dc..cc0fe66aaf82 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -533,6 +533,11 @@ void DefineDescriptors(SpirvEmitterState& state) { if (!layout.UsesDataAddress()) { state.shaderDataStorageVariable = Define(StorageBufferBlockType(state), "shader_data"); state.module.AddAnnotation(spv::OpDecorate, state.shaderDataStorageVariable, spv::DecorationNonWritable); + } else if (layout.ShaderDataDwords() != 0u && layout.ShaderDataDwords() <= state.heapDataUniformDwords) { + const auto vectors = (layout.ShaderDataDwords() + 3u) / 4u; + const auto array = state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 16u}}}, TypeU32Vector(state, 4), ConstantU32(state, vectors)); + const auto block = state.module.DecoratedType(spv::OpTypeStruct, {{spv::OpDecorate, {spv::DecorationBlock}}, {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}}, array); + state.shaderDataUniformVariable = Define(block, "shader_data", spv::StorageClassUniform); } break; case DescriptorBindingKind::FlattenedSrt: diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 37f07a5584ba..b0205903b42d 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -622,6 +622,8 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_MIMALLOC` | presence | `core/libs/prx/libkernel/System/src/MimallocMacOs.cpp` | | makes the process allocate through mimalloc instead of the system allocator: on Windows the entry stub (`core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp`) loads `mimalloc.dll`, on macOS libkernel restarts the title with `libmimalloc.dylib` in `DYLD_INSERT_LIBRARIES` | | `APS5_MIMALLOC_RESTARTED` | presence | `core/libs/prx/libkernel/System/src/MimallocMacOs.cpp` | | on macOS, set by libkernel for the restart that loads mimalloc and removed at start-up, so a restart that did not load it is not repeated | | `APS5_NO_DIRECT_MEMORY_SECTION_POOL` | presence | `core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp` | | on Windows, creates a section for every direct-memory allocation and closes it at release instead of reusing released sections that never held guest data | +| `APS5_NO_HEAP_DATA_UNIFORM` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | | keeps the GPU heap's shader-data ring in its own buffer and has GPU-mode stages read their shader data through device-address pointers, instead of placing the ring inside the resource heap and reading it as a uniform buffer mapped from heap data | +| `APS5_NO_HEAP_DEVICE_DESCRIPTORS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | | allocates the GPU heap's resource and sampler heaps in host-visible memory instead of device-local host-visible memory (the resource heap stays device-local while it holds the shader-data ring) | | `APS5_NO_JOB_AFFINITY` | presence | `core/libs/prx/libkernel/Pthread/src/Thread.cpp` | | on Windows, disables pinning of job worker threads | | `APS5_NO_SLEEP_WAKE` | presence | `core/libs/prx/libkernel/Time/SleepWake.cpp` | | keeps every sleep of 1 ms or less in full instead of ending it at a GPU batch, batch completion action or flip completion | | `APS5_NO_TIMER_RESOLUTION` | presence | `core/libs/prx/libkernel/Time/Time.cpp` | | keeps the default 15.6 ms scheduler tick instead of raising it to 0.5 ms on Windows | From eb606888ccc41f7b94bf0f2eccc5bfb7b90d420e Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 09:28:53 +0530 Subject: [PATCH 074/269] fix(agc): bind multisampled storage targets on the GPU heap through their storage view A heap compute stage that stores to a multisampled color target bound the placeholder slot, and the target's storage view was picked from the raw binding number, which on the heap is the stage group's binding (65 + kind): uint stores went through the float view and wrote zeros. Multisampled storage views take a heap view slot (released with the view), the uint storage form is picked from the binding's kind everywhere, and APS5_VERIFY_GPU_HEAP checks multisampled storage slots. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 2 +- .../Graphics/include/ShaderResources.hpp | 1 + .../Graphics/src/MultisampleTarget.cpp | 5 +++ .../Graphics/src/ShaderResources.cpp | 40 +++++++++++++++---- .../execution/SampleMultisampleTarget.cpp | 2 +- 5 files changed, 41 insertions(+), 9 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 7ec6cbfce74e..6d8fa8021856 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -2984,7 +2984,7 @@ if(BUILD_TESTING) set_tests_properties(${agcTestName}_draw_pipeline PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endforeach() - set(agcGpuHeapTests ${agcDrawPipelineTests} agc_driver_rect_list_indirect agc_driver_provoking_vertex agc_driver_pixel_barycentric_emulation agc_driver_bindless_images agc_driver_image_sample_shared_sampler agc_driver_image_sample_border_color agc_driver_image_sample_lod_clamp agc_driver_image_sample_derivatives agc_driver_image_gather_one_dimensional agc_driver_image_load_packed agc_driver_sampled_cache_budget agc_driver_image_atomics agc_driver_image_atomics64 agc_driver_image_atomics_bitwise agc_driver_image_atomics_float agc_driver_gpu_indirect_arguments_misaligned_writer_ahead agc_driver_gpu_indirect_arguments_written_ahead agc_driver_indirect_arguments_written_ahead agc_driver_indirect_thread_dimensions agc_driver_indirect_patched_stage agc_driver_compute_table_calls agc_driver_buffer_atomics agc_driver_buffer_format agc_driver_mesh agc_driver_tessellation agc_driver_mesh_draw_relocation agc_driver_mesh_index_cache agc_driver_mesh_provoking_vertex agc_driver_tessellation_submit agc_driver_fragment_user_data_tail agc_driver_image_table_cache_bounds agc_driver_lds_beyond_device_limit agc_driver_address_passes agc_driver_depth_storage_dispatch agc_driver_image_cache_bits agc_driver_image_converted_unorm agc_driver_image_sint8 agc_driver_image_srgb_load agc_driver_image_store_array_through_volume agc_driver_image_store_face_on_cube agc_driver_image_store_float_rounding agc_driver_image_store_line_through_plane agc_driver_image_store_line_through_plane_array agc_driver_image_store_packed agc_driver_image_store_sint agc_driver_image_store_unorm_rounding agc_driver_image_store_volume_through_array agc_driver_image_texel_status agc_driver_storage_flush_ordering agc_driver_storage_one_slice_alias agc_driver_view_past_last_mip) + set(agcGpuHeapTests ${agcDrawPipelineTests} agc_driver_rect_list_indirect agc_driver_provoking_vertex agc_driver_pixel_barycentric_emulation agc_driver_bindless_images agc_driver_image_sample_shared_sampler agc_driver_image_sample_border_color agc_driver_image_sample_lod_clamp agc_driver_image_sample_derivatives agc_driver_image_gather_one_dimensional agc_driver_image_load_packed agc_driver_sampled_cache_budget agc_driver_image_atomics agc_driver_image_atomics64 agc_driver_image_atomics_bitwise agc_driver_image_atomics_float agc_driver_gpu_indirect_arguments_misaligned_writer_ahead agc_driver_gpu_indirect_arguments_written_ahead agc_driver_indirect_arguments_written_ahead agc_driver_indirect_thread_dimensions agc_driver_indirect_patched_stage agc_driver_compute_table_calls agc_driver_buffer_atomics agc_driver_buffer_format agc_driver_mesh agc_driver_tessellation agc_driver_mesh_draw_relocation agc_driver_mesh_index_cache agc_driver_mesh_provoking_vertex agc_driver_tessellation_submit agc_driver_fragment_user_data_tail agc_driver_image_table_cache_bounds agc_driver_lds_beyond_device_limit agc_driver_address_passes agc_driver_depth_storage_dispatch agc_driver_image_cache_bits agc_driver_image_converted_unorm agc_driver_image_sint8 agc_driver_image_srgb_load agc_driver_image_store_array_through_volume agc_driver_image_store_face_on_cube agc_driver_image_store_float_rounding agc_driver_image_store_line_through_plane agc_driver_image_store_line_through_plane_array agc_driver_image_store_packed agc_driver_image_store_sint agc_driver_image_store_unorm_rounding agc_driver_image_store_volume_through_array agc_driver_image_texel_status agc_driver_storage_flush_ordering agc_driver_storage_one_slice_alias agc_driver_view_past_last_mip agc_driver_sample_multisample_target) foreach(agcTestName IN LISTS agcGpuHeapTests) add_test(NAME ${agcTestName}_gpu_heap COMMAND ${agcTestName}_tests) set_tests_properties(${agcTestName}_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 979545c0aa41..dde3f485d460 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -655,6 +655,7 @@ class ShaderResources { VkImageView heapPlaceholderView(std::uint32_t kind) const; VkImageView heapSampledView(std::size_t index) const; VkImageView heapStorageView(std::size_t index, std::uint32_t binding) const; + VkImageView heapMultisampleStorageView(std::size_t index) const; void appendHeapSlotKey(VkShaderStageFlags stageBit, std::vector& key) const; static bool heapSlotsCurrent(const BindlessHeap& heap, const HeapStageState& state); void takeHeapSlots(BindlessHeap& heap, HeapStageState& state, VkShaderStageFlags stageBit, std::span key); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp index 051b7149dfd2..d40aabeee94c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp @@ -1,5 +1,6 @@ #include #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp" @@ -749,6 +750,10 @@ class MultisampleTarget : public std::enable_shared_from_this for (const auto& [format, resolvePass] : resolvePasses) context.Function("vkDestroyRenderPass")(context.device, resolvePass, nullptr); if (orderView) context.Function("vkDestroyImageView")(context.device, orderView, nullptr); if (twinView) context.Function("vkDestroyImageView")(context.device, twinView, nullptr); + if (auto* heap = BindlessHeap::Existing(context)) { + if (storageView) heap->ReleaseViewSlots(reinterpret_cast(storageView)); + if (uintStorageView) heap->ReleaseViewSlots(reinterpret_cast(uintStorageView)); + } if (storageView) context.Function("vkDestroyImageView")(context.device, storageView, nullptr); if (uintStorageView) context.Function("vkDestroyImageView")(context.device, uintStorageView, nullptr); destroy({image, memory, view}); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 681f63f0c59b..2acd7fdad80f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -50,6 +50,11 @@ namespace AgcDriver::Graphics { namespace { +bool UintStorageBinding(std::uint32_t binding) { + const auto kind = binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count); + return kind >= ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 7u && kind < ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 14u; +} + bool overlap(std::uint64_t first, std::size_t firstSize, std::uint64_t second, std::size_t secondSize) { return first < second + secondSize && second < first + firstSize; } @@ -2623,7 +2628,7 @@ void ShaderResources::buildComplete() { for (auto element = first; element < last; ++element) { const auto index = binding.imageAllocations[element]; if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) images.push_back({samplers[index]->Handle(), VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}); - else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) images.push_back({VK_NULL_HANDLE, storageAtomic64[index] ? storageTextures[index]->Atomic64View(storageMips[index], storageFirstLayer[index]) : storageAtomic[index] ? storageTextures[index]->AtomicView(storageMips[index], storageFirstLayer[index]) : storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index], binding.layout.binding >= ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 7u && binding.layout.binding < ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 14u), VK_IMAGE_LAYOUT_GENERAL}); + else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) images.push_back({VK_NULL_HANDLE, storageAtomic64[index] ? storageTextures[index]->Atomic64View(storageMips[index], storageFirstLayer[index]) : storageAtomic[index] ? storageTextures[index]->AtomicView(storageMips[index], storageFirstLayer[index]) : storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index], UintStorageBinding(binding.layout.binding)), VK_IMAGE_LAYOUT_GENERAL}); else images.push_back({VK_NULL_HANDLE, textureFirstLayer[index] ? textures[index]->FirstLayerView() : textures[index]->View(), textures[index]->Layout()}); } if (recorded) runs.emplace_back(write.dstArrayElement, write.descriptorCount); @@ -2668,7 +2673,7 @@ void ShaderResources::buildComplete() { for (const auto index : binding.imageAllocations) { if (index == std::numeric_limits::max()) images.push_back(absentImage(binding.layout.binding)); else if (storageTextures[index] == nullptr) images.push_back({VK_NULL_HANDLE, multisampleStorageViews[index], VK_IMAGE_LAYOUT_GENERAL}); - else images.push_back({VK_NULL_HANDLE, storageAtomic64[index] ? storageTextures[index]->Atomic64View(storageMips[index], storageFirstLayer[index]) : storageAtomic[index] ? storageTextures[index]->AtomicView(storageMips[index], storageFirstLayer[index]) : storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index], binding.layout.binding >= ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 7u && binding.layout.binding < ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 14u), VK_IMAGE_LAYOUT_GENERAL}); + else images.push_back({VK_NULL_HANDLE, storageAtomic64[index] ? storageTextures[index]->Atomic64View(storageMips[index], storageFirstLayer[index]) : storageAtomic[index] ? storageTextures[index]->AtomicView(storageMips[index], storageFirstLayer[index]) : storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index], UintStorageBinding(binding.layout.binding)), VK_IMAGE_LAYOUT_GENERAL}); } Require(binding.imageAllocations.size() == binding.layout.descriptorCount, "descriptor allocations disagree with compact binding"); break; @@ -5232,7 +5237,7 @@ void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBind Require(!(element < binding.imageAtomic.size() && binding.imageAtomic[element]) && !(element < binding.imageAtomic64.size() && binding.imageAtomic64[element]), "storage image atomics on a multisampled texture are not implemented"); storageTextures.push_back(nullptr); multisampleStorageViews.resize(storageTextures.size(), VK_NULL_HANDLE); - const bool uintStorage = binding.binding >= ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 7u && binding.binding < ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 14u; + const bool uintStorage = UintStorageBinding(binding.binding); multisampleStorageViews.back() = MultisampleTargetStorageView(context, resource, uintStorage); multisampleSources.push_back(resource.baseAddress); storageMips.push_back(0); @@ -6391,13 +6396,15 @@ VkImageView ShaderResources::heapSampledView(std::size_t index) const { return texture->View(); } +VkImageView ShaderResources::heapMultisampleStorageView(std::size_t index) const { + return index < multisampleStorageViews.size() ? multisampleStorageViews[index] : VK_NULL_HANDLE; +} + VkImageView ShaderResources::heapStorageView(std::size_t index, std::uint32_t binding) const { const auto& texture = storageTextures[index]; if (storageAtomic64[index]) return texture->Atomic64View(storageMips[index], storageFirstLayer[index]); if (storageAtomic[index]) return texture->AtomicView(storageMips[index], storageFirstLayer[index]); - const auto kind = binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count); - const bool uintStorage = kind >= ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 7u && kind < ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 14u; - return texture->StorageView(storageMips[index], storageFirstLayer[index], uintStorage); + return texture->StorageView(storageMips[index], storageFirstLayer[index], UintStorageBinding(binding)); } void ShaderResources::appendHeapSlotKey(VkShaderStageFlags stageBit, std::vector& key) const { @@ -6417,6 +6424,11 @@ void ShaderResources::appendHeapSlotKey(VkShaderStageFlags stageBit, std::vector } } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { for (const auto index : binding.imageAllocations) { + if (index != absent && storageTextures[index] == nullptr && heapMultisampleStorageView(index) != VK_NULL_HANDLE) { + key.insert(key.end(), {0u, reinterpret_cast(heapMultisampleStorageView(index)), + static_cast(VK_IMAGE_LAYOUT_GENERAL)}); + continue; + } if (index == absent || storageTextures[index] == nullptr) { key.push_back(0u); continue; @@ -6474,6 +6486,14 @@ void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, V } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { auto& kindSlots = state.slots[kind]; for (const auto index : binding.imageAllocations) { + if (index != absent && storageTextures[index] == nullptr && heapMultisampleStorageView(index) != VK_NULL_HANDLE) { + const auto view = reinterpret_cast(key[cursor + 1]); + cursor += 3; + const auto slot = heap.ViewSlot(kind, reinterpret_cast(view), view); + Require(slot.has_value(), "the global storage image heap is full"); + kindSlots.push_back(*slot); + continue; + } if (index == absent || storageTextures[index] == nullptr) { ++cursor; kindSlots.push_back(heap.AbsentSlot(kind, heapPlaceholderView(kind))); @@ -6523,7 +6543,13 @@ void ShaderResources::verifyHeapSlots(const BindlessHeap& heap, const HeapStageS if (!bound || heap.SlotTexture(kind, state.slots[kind][element]) != textures[index].get()) ++wrong; continue; } - if (storageTextures[index] == nullptr) continue; + if (storageTextures[index] == nullptr) { + const auto view = heapMultisampleStorageView(index); + if (view == VK_NULL_HANDLE) continue; + ++storageChecked; + if (!bound || !heap.SlotHoldsStorage(kind, state.slots[kind][element], reinterpret_cast(view), view)) ++storageWrong; + continue; + } ++storageChecked; if (!bound || !heap.SlotHoldsStorage(kind, state.slots[kind][element], storageTextures[index].get(), heapStorageView(index, binding.layout.binding))) ++storageWrong; } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp index 97d9c16dd988..aaf3b550f8c4 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp @@ -402,7 +402,7 @@ ShaderRecompiler::RecompileResult CompileProgram(AgcDriver::VulkanDevice& device ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {32, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + device.ComputeTarget(64), {0, 0, 0, 128} }; request.useCache = false; From 95e1f337425f3b935c95c2f9aa61c5751af5f679 Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 09:39:34 +0530 Subject: [PATCH 075/269] fix(agc): give heap image tables a uint storage column for raw uint stores Table storage elements written through a uint mode (16-bit float and SINT formats stored as raw bits) indexed the table map's one storage column, whose slots hold the float storage view, so their stores wrote zeros. The heap table map gains a fifth column with each storage element's uint view, which uint storage table variables index. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 4 +- .../Graphics/include/Texture.hpp | 1 + .../Graphics/src/ShaderResources.cpp | 24 +++++++++++- .../libSceAgcDriver/Graphics/src/Texture.cpp | 7 ++++ .../tests/execution/ImageTableCacheBounds.cpp | 38 +++++++++++++++++++ .../src/SpirvMemory/SpirvDescriptors.cpp | 14 ++++++- 6 files changed, 83 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 6d8fa8021856..f8f3367f13c7 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -2821,12 +2821,14 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_image_table_atomics PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) add_test(NAME agc_driver_image_table_atomics_gpu_heap COMMAND agc_driver_image_table_cache_bounds_tests --atomic-table) set_tests_properties(agc_driver_image_table_atomics_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) + add_test(NAME agc_driver_image_table_store_gpu_heap COMMAND agc_driver_image_table_cache_bounds_tests --store-table) + set_tests_properties(agc_driver_image_table_store_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) add_test(NAME agc_driver_image_table_vouch_queued_draws COMMAND agc_driver_image_table_cache_bounds_tests --queued-draws) set_tests_properties(agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) add_test(NAME agc_driver_image_table_cache_bounds_heap_small COMMAND agc_driver_image_table_cache_bounds_tests) set_tests_properties(agc_driver_image_table_cache_bounds_heap_small PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_HEAP_SLOT_CAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) if(WIN32) - set_tests_properties(agc_shader_table_snapshot_reuse agc_shader_table_snapshot_reuse_unmasked agc_driver_image_table_vouched_lookups agc_driver_image_table_vouch_queued_draws agc_driver_image_table_cache_bounds_heap_small agc_driver_image_table_atomics agc_driver_image_table_atomics_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + set_tests_properties(agc_shader_table_snapshot_reuse agc_shader_table_snapshot_reuse_unmasked agc_driver_image_table_vouched_lookups agc_driver_image_table_vouch_queued_draws agc_driver_image_table_cache_bounds_heap_small agc_driver_image_table_atomics agc_driver_image_table_atomics_gpu_heap agc_driver_image_table_store_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() add_test(NAME agc_shader_type_zero_image_materialization COMMAND agc_shader_memory_tests --type-zero-image-materialization) set_tests_properties(agc_shader_type_zero_image_materialization PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp index 1c69bddd5dc2..6018473d641d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp @@ -192,6 +192,7 @@ class StorageTexture : public std::enable_shared_from_this { VkImageView View(std::uint32_t mip); VkImageView FirstLayerView(std::uint32_t mip); VkImageView StorageView(std::uint32_t mip, bool firstLayer, bool uintStorage = false); + VkImageView UintStorageViewOrDefault(std::uint32_t mip, bool firstLayer); VkImageView ElementView(); VkImageView AtomicView(std::uint32_t mip, bool firstLayer); VkImageView Atomic64View(std::uint32_t mip, bool firstLayer); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 2acd7fdad80f..a4eac73d4524 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6349,9 +6349,11 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ } return false; }; + const auto samplerSpan = std::max(elements, map[TableAbi::HeaderSamplerCount]); + Require(table->tableSamplers.size() <= samplerSpan, "an image table map has more table samplers than its header counts"); + const auto extraBase = base + 2u * elements + samplerSpan; if (anyAtomic(false) || anyAtomic(true)) { - Require(table->tableSamplers.size() <= elements, "an image table with atomics has more table samplers than elements"); - map.resize(base + 3u * elements, fallbackSampler); + map.resize(extraBase, fallbackSampler); for (const bool wide : {false, true}) { const auto kind = wide ? Abi::FirstAtomic64ImageBinding : Abi::FirstAtomicImageBinding; const auto absent = heap.AbsentSlot(kind, heapPlaceholderView(kind)); @@ -6370,6 +6372,24 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ } } } + const bool storageTable = std::ranges::any_of(shader.program->bindings, [](const ShaderRecompiler::DescriptorBinding& binding) { + return binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable; + }); + if (storageTable) { + map.resize(extraBase + 2u * elements, fallbackSampler); + const auto kind = Abi::FirstStorageImageBinding + 7u; + const auto absent = heap.AbsentSlot(kind, heapPlaceholderView(kind)); + for (std::size_t element = 0; element < elements; ++element) { + const auto index = element < table->elementStorage.size() ? table->elementStorage[element] : noElement; + if (index == noElement || storageTextures[index] == nullptr) { + map.push_back(absent); + continue; + } + const auto slot = heap.StorageSlot(kind, storageTextures[index], storageTextures[index]->UintStorageViewOrDefault(storageMips[index], storageFirstLayer[index])); + Require(slot.has_value(), "the global storage image heap is full"); + map.push_back(*slot); + } + } if (map.size() == base) map.push_back(sampledAbsent); heapTableMaps[stageIndex] = heapSpan(heapStages[stageIndex].map, map); heapTableMapSet[stageIndex] = true; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index 5caa230c7f6b..3b89252af76a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -2072,6 +2072,13 @@ VkImageView StorageTexture::StorageView(std::uint32_t mip, bool firstLayer, bool return created; } +VkImageView StorageTexture::UintStorageViewOrDefault(std::uint32_t mip, bool firstLayer) { + const auto uintFormat = UintStorageViewFormat(storageFormat); + const bool available = PackedStorageViewFormat(storageFormat) == VK_FORMAT_UNDEFINED && uintFormat != VK_FORMAT_UNDEFINED && + StorageFormatOrUndefined(context, uintFormat) == uintFormat; + return StorageView(mip, firstLayer, available); +} + VkImageView StorageTexture::ElementView() { if (elementView != VK_NULL_HANDLE) return elementView; if (descriptor.dimension != TextureDimension::k2D || geometry.imageLayers != 1) return VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp index 89bea8b9d0ea..b3374d1a5660 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp @@ -73,6 +73,10 @@ constexpr std::uint32_t AtomicWidth = 64; constexpr std::size_t AtomicKernelOffset = 1024; constexpr std::size_t AtomicSurfaceBytes = AtomicWidth * 4u; constexpr std::uint32_t AtomicElement = 5; +constexpr std::uint32_t Format16x4Float = 71; +constexpr std::size_t StoreSurfaceBytes = AtomicWidth * 8u; +constexpr std::uint64_t StoredTexel = 0x3c00ull | 0x3800ull << 16u | 0x4000ull << 32u | 0xbc00ull << 48u; +constexpr std::array StoreTableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x2c240086u, 0x4a222485u, 0x7e200511u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0x7e020280u, 0x7e0402f2u, 0x7e0602f0u, 0x7e0802f4u, 0x7e0a02f3u, 0xbf8c3f70u, 0xf0200f08u, 0x00050200u, 0xbf810000u}; constexpr std::array AtomicTableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x2c240086u, 0x4a222485u, 0x7e200511u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0x7e020280u, 0x7e040281u, 0x34060082u, 0xbf8c3f70u, 0xf0442108u, 0x00050200u, 0xbf8c3f70u, 0xe0701000u, 0x80070203u, 0xbf8c3f70u, 0xbf810000u}; constexpr std::array TableCode{0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x7e200500u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0xf09c0f08u, 0x00450000u, 0xe0700000u, 0x80070000u, 0xbf810000u}; @@ -400,6 +404,35 @@ void AtomicTable(const GuestBlock& block) { std::puts("image table atomics passed"); } +void StoreTable(const GuestBlock& block) { + std::memcpy(block.Bytes(AtomicKernelOffset), StoreTableCode.data(), sizeof(StoreTableCode)); + for (std::uint32_t record = 0; record < AtomicRecords; ++record) { + const auto surface = TexturesOffset + static_cast(record) * StoreSurfaceBytes; + std::memset(block.Bytes(surface), 0, StoreSurfaceBytes); + const auto address = block.At(surface); + const std::array words{static_cast(address >> 8u), static_cast((address >> 40u) & 0xffu) | (Format16x4Float << 20u) | (((AtomicWidth - 1u) & 3u) << 30u), (AtomicWidth - 1u) >> 2u, 0xfacu | (Type2D << 28u), 0u, 0u, 0u, 0u}; + std::memcpy(block.Bytes(HeapOffset + static_cast(record) * Stride), words.data(), sizeof(words)); + } + auto* srt = reinterpret_cast(block.Bytes(SrtOffset)); + std::fill(srt, srt + SrtBytes / 4u, 0u); + const auto heap = V(block.At(HeapOffset), Stride, AtomicRecords); + const auto output = V(block.At(OutputOffset), 0u, 4096u); + std::copy(heap.begin(), heap.end(), srt); + std::copy(output.begin(), output.end(), srt + 12); + const auto heapStages = AgcDriver::Graphics::HeapComputeStages(); + Dispatch(block, 0, AtomicKernelOffset); + std::array texels{}; + AgcDriver::GuestMemory::Read(block.At(TexturesOffset + static_cast(AtomicElement) * StoreSurfaceBytes), std::as_writable_bytes(std::span(texels))); + for (std::uint32_t texel = 0; texel < AtomicWidth; ++texel) { + char text[160]; + std::snprintf(text, sizeof(text), "image table store: texel %u of a 16_16_16_16_FLOAT table element holds 0x%016llx, expected 0x%016llx", texel, + static_cast(texels[texel]), static_cast(StoredTexel)); + Require(texels[texel] == StoredTexel, text); + } + if (AgcDriver::Graphics::DescriptorHeapEnabled()) Require(AgcDriver::Graphics::HeapComputeStages() > heapStages, "image table store: the dispatch did not take the descriptor heap"); + std::puts("image table store passed"); +} + struct QueuedDraw { std::atomic release{false}; @@ -540,6 +573,11 @@ int main(int argc, char** argv) { AgcDriverShutdown_nid_postfix(); return 0; } + if (argc == 2 && std::string(argv[1]) == "--store-table") { + StoreTable(block); + AgcDriverShutdown_nid_postfix(); + return 0; + } if (argc == 2 && std::string(argv[1]) == "--atomic-table") { AtomicTable(block); AgcDriverShutdown_nid_postfix(); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp index 82e6ebf36bdf..c11411e61288 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp @@ -90,12 +90,21 @@ std::uint32_t tableHeapSlot(SpirvEmitterState& state, std::uint32_t part, std::u const auto u32 = TypeU32(state); const auto base = tableMapWord(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)); const auto count = tableMapWord(state, ConstantU32(state, ImageTableAbi::HeaderElementCount)); - const auto partBase = part == 0u ? base : Binary(state, spv::OpIAdd, u32, base, Binary(state, spv::OpIMul, u32, count, ConstantU32(state, part))); + std::uint32_t partBase = base; + if (part != 0u && part < 3u) { + partBase = Binary(state, spv::OpIAdd, u32, base, Binary(state, spv::OpIMul, u32, count, ConstantU32(state, part))); + } else if (part >= 3u) { + const auto samplers = tableMapWord(state, ConstantU32(state, ImageTableAbi::HeaderSamplerCount)); + const auto samplerSpan = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), count, samplers), samplers, count); + const auto extra = Binary(state, spv::OpIMul, u32, count, ConstantU32(state, part - 1u)); + partBase = Binary(state, spv::OpIAdd, u32, Binary(state, spv::OpIAdd, u32, base, samplerSpan), extra); + } const auto slot = tableMapWord(state, Binary(state, spv::OpIAdd, u32, partBase, element)); const auto fallback = part == 0u ? RuntimeAbi::FirstImageBinding : part == 1u ? RuntimeAbi::FirstStorageImageBinding : part == 3u ? RuntimeAbi::FirstAtomicImageBinding : part == 4u ? RuntimeAbi::FirstAtomic64ImageBinding + : part == 5u ? RuntimeAbi::FirstStorageImageBinding + 7u : 0u; const auto clamped = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), slot, ConstantU32(state, slots)), slot, ConstantU32(state, fallback)); DecorateTableNonUniform(state, clamped); @@ -109,7 +118,8 @@ std::uint32_t TableStorageImagePointer(SpirvEmitterState& state, DescriptorBindi if (found == state.tableImageVariables.end() || !state.tableAccess.active) ExitDescriptorBindingFailure(state, kind, resource, "image storage table array was not emitted for the mode"); const auto pointer = state.module.AllocateId(); const auto value = static_cast(kind); - const auto part = RuntimeAbi::AtomicImageKind(value) ? 3u : RuntimeAbi::Atomic64ImageKind(value) ? 4u : 1u; + const bool uintStorage = value >= RuntimeAbi::FirstStorageImageBinding + 7u && value < RuntimeAbi::FirstStorageImageBinding + 14u; + const auto part = RuntimeAbi::AtomicImageKind(value) ? 3u : RuntimeAbi::Atomic64ImageKind(value) ? 4u : uintStorage ? 5u : 1u; state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, part, state.tableAccess.element, RuntimeAbi::GpuImageHeapSlots) : state.tableAccess.element); DecorateTableNonUniform(state, pointer); return pointer; From 28c310dc06e54df69b59bc902b65b963d4cd74e4 Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 10:52:52 +0530 Subject: [PATCH 076/269] fix(shader): keep zeroing out-of-range GPU heap address loads main omits the final zero select for read-only and volatile buffer loads, relying on robust buffer access to return zero for the out-of-range fallback index. Heap stages read guest buffers through device addresses, whose out-of-range fallback loads word 0 of the buffer, so those loads returned data (agc_driver_buffer_descriptor_runtime with APS5_GPU_HEAP=1). Address loads keep the select. Co-Authored-By: Claude Opus 5.5 --- core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index 49a5bc6f954c..16834811c748 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -320,7 +320,8 @@ std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruct const auto low = Binary(state, spv::OpShiftRightLogical, TypeU32(state), load(lowIndex), shift); const auto high = EmitValueOrZero(state, unaligned, Binary(state, spv::OpShiftLeftLogical, TypeU32(state), load(highIndex), highShift)); const auto value = combine(low, high); - return (access.memoryAccess & spv::MemoryAccessVolatileMask) != 0u || (state.requirements.readOnlyStorage && access.memoryAccess == 0u) ? value : EmitValueOrZero(state, inBounds, value); + const bool robustZero = !access.physical && ((access.memoryAccess & spv::MemoryAccessVolatileMask) != 0u || (state.requirements.readOnlyStorage && access.memoryAccess == 0u)); + return robustZero ? value : EmitValueOrZero(state, inBounds, value); } std::uint32_t byteBuffers(SpirvEmitterState& state) { From 68c1327a6a083e3f7602cde5577b576e7e56313e Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 10:52:52 +0530 Subject: [PATCH 077/269] test(agc): skip the image table store test without the GPU heap Per-dispatch image tables still bind every storage element through its float view, so the store test fails without the heap; it now skips there and the gap is recorded in the driver's debt file. Co-Authored-By: Claude Opus 5.5 --- .../tests/execution/ImageTableCacheBounds.cpp | 11 ++++++++--- docs/dev/debt/libSceAgcDriver.md | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp index b3374d1a5660..b9808d38c1a9 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp @@ -404,7 +404,7 @@ void AtomicTable(const GuestBlock& block) { std::puts("image table atomics passed"); } -void StoreTable(const GuestBlock& block) { +bool StoreTable(const GuestBlock& block) { std::memcpy(block.Bytes(AtomicKernelOffset), StoreTableCode.data(), sizeof(StoreTableCode)); for (std::uint32_t record = 0; record < AtomicRecords; ++record) { const auto surface = TexturesOffset + static_cast(record) * StoreSurfaceBytes; @@ -421,6 +421,10 @@ void StoreTable(const GuestBlock& block) { std::copy(output.begin(), output.end(), srt + 12); const auto heapStages = AgcDriver::Graphics::HeapComputeStages(); Dispatch(block, 0, AtomicKernelOffset); + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) { + std::puts("image table store skipped: per-dispatch image tables have no uint storage view (docs/dev/debt/libSceAgcDriver.md)"); + return false; + } std::array texels{}; AgcDriver::GuestMemory::Read(block.At(TexturesOffset + static_cast(AtomicElement) * StoreSurfaceBytes), std::as_writable_bytes(std::span(texels))); for (std::uint32_t texel = 0; texel < AtomicWidth; ++texel) { @@ -431,6 +435,7 @@ void StoreTable(const GuestBlock& block) { } if (AgcDriver::Graphics::DescriptorHeapEnabled()) Require(AgcDriver::Graphics::HeapComputeStages() > heapStages, "image table store: the dispatch did not take the descriptor heap"); std::puts("image table store passed"); + return true; } struct QueuedDraw { @@ -574,9 +579,9 @@ int main(int argc, char** argv) { return 0; } if (argc == 2 && std::string(argv[1]) == "--store-table") { - StoreTable(block); + const bool ran = StoreTable(block); AgcDriverShutdown_nid_postfix(); - return 0; + return ran ? 0 : VulkanTestSkipped; } if (argc == 2 && std::string(argv[1]) == "--atomic-table") { AtomicTable(block); diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 5c173972fa94..c171f59db96d 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -288,6 +288,7 @@ - [Table S#](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) DISABLE_CUBE_WRAP faults on selection without `VK_EXT_non_seamless_cube_map`: no runtime dimension check, including valid non-cube direct/table T#s. Unselected entries do not fault; with the feature this bit alone is accepted. Table T#/direct S# faults only for cubes needing the missing feature. - An [image table](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) whose record range overlaps a buffer or storage image written by its own dispatch faults (`table written by its dispatch`) when any entry is selected, even if the write misses the selected record. A selected column's range is its record and the bytes of the record before the descriptor. - An [image table](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) T# whose surface has no mapped byte faults when selected instead of becoming a zero texture as a direct T# does; what the console returns for it is not measured. +- A per-dispatch [image table](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) binds every storage element through its float storage view, so a table store through a uint mode (16-bit float and SINT formats written as raw bits) writes zero. The GPU heap gives tables a uint storage column; `agc_driver_image_table_store_gpu_heap` covers it and skips without the heap. - [User-data callees](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp) (libSceAgcDriver) - a compute shader's `s_swappc_b64` whose source pair is a user-data pair, or a copy of one made with `s_mov_b32` or `s_mov_b64` in the same block, calls the code at the address that user data holds. At dispatch the callee is read from guest memory up to its `s_setpc_b64` on the link pair, one copy of it is appended per call after the caller's last instruction, and the call is rewritten to `s_call_b64` to that copy. The words after the caller's last instruction are dropped from the recompiled code; in the shaders seen they are metadata or constants the caller reads relative to its program counter, and those reads go to the captured guest code, which linking does not change. A caller that jumps through a table among those words, which the control flow analysis reads from the recompiled code, throws. A copy runs at another program counter than the callee, so a callee that reads its program counter, makes a call, ends the program, jumps through another pair, returns before code it branches to, spans more than 64 KiB or is not readable throws. Callees are read again whenever a dispatch misses the dispatch cache; a dispatch that hits it reuses the linked program, so a title that rewrote a callee in place at the same address would keep running the old code. - [Table callees](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp) (libSceAgcDriver) - a compute shader's `s_swappc_b64` whose source pair is two consecutive dwords of an `s_buffer_load_dword*`, or a copy of them made with `s_mov_b32` or `s_mov_b64` in the same block (a conditional branch forward past the call between them is crossed), calls one of the targets that buffer holds when the load's buffer descriptor comes from an `s_load_dwordx4`, or a 4-dword-aligned slice of an `s_load_dwordx8` or `s_load_dwordx16`, without SOFFSET from a user-data pointer, or from a pointer pair that two `s_mov_b32` of a literal or inline constant set, and the load's SOFFSET from an `s_lshl_b32` by 2 to 24 bits. The descriptor load may be in an earlier block, such as before a per-lane loop around the call, when it is the only write of the descriptor registers that reaches the buffer load on every path back from it, and no `s_call_b64` or statically resolved call lies on those paths; the paths may run through any `s_swappc_b64` that is not resolved statically, the table call itself included, whose callee is assumed to keep the descriptor registers. The chain compares the target each iteration actually loads, so a callee that changes them can only make a later target miss the chain and fault as an unlinked call. Paths follow fall-through, direct branches and the `s_setpc_b64` jumps whose target the control flow analysis resolves. A path that reaches, before a write of the descriptor registers, the program's first instruction, the entry of an in-program function (an `s_call_b64` target, whose callers are not followed), or an instruction that nothing modelled jumps or falls into fails the search. At dispatch the descriptor and the buffer are read from guest memory, and every non-zero 64-bit value at the loaded offset plus a multiple of the shift's stride, below the descriptor's size (stride times num_records, or num_records bytes with stride 0), is read as a user-data callee and appended once per call. The call becomes a branch to a chain that compares the source pair with each target (`s_cmp_lg_u32` with a literal and `s_cbranch_scc1` per dword) and `s_call_b64`s the copy that matches; no match runs the original `s_swappc_b64` as an unlinked call. There is one chain for each value SCC has at the call, and the chain sets SCC back to that value (`s_cmp_eq_u32 0, 0` or `s_cmp_lg_u32 0, 0`) before the callee or the unlinked call runs. Each copy follows its own compares and call, so no branch spans more than one copy. A later call's branch to its chain and its return cross earlier calls' copies through a pair of `s_branch` relays before the first of those copies and after each one, so they don't span more than one copy either. The searched range is the descriptor's whole size, which covers the range the load can reach whether it is checked in bytes or in strides; which one the PS5 uses for `s_buffer_load` was not measured. More than 64 distinct targets, a buffer above 64 MiB, or a call more than 0x7fff dwords before the end of the program and its user-data callees throws. As with user-data callees, the buffer is read again only when a dispatch misses the dispatch cache, so a target a title adds to the buffer later is an unlinked call when a cached program runs. - [AGC FS table](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp) (libSceAgcDriver) - the driver maps 2 MiB at 0xF_E0000000 when it is created and fills the table that libSceAgc keeps at 0xF_E0040000 (six 16-byte V# slots, slot 0 describing eight 16-byte records) the way PS5 13.60 libSceAgcDriver and libSceAgc do, but every record points at one AnyPS5 routine that only returns (`s_setpc_b64` on the link pair). Sony's routines, which order work before a title's `ds_ordered_count`, are not modeled. From 9263a4bdce848bbe17dc0f104f71af9ccf4d893e Mon Sep 17 00:00:00 2001 From: Raghav314 Date: Sat, 31 Oct 2026 10:56:26 +0530 Subject: [PATCH 078/269] fix(agc): gate the GPU heap on the descriptor heap extension's revision, not the driver's Vulkan version Drivers ship the released VK_EXT_descriptor_heap (revision 1) while reporting an older Vulkan version (NVIDIA 595.99.02 reports 1.4.329), and every heap test passes on them. The heap now needs revision 1 or newer; the validation layer gate stays. Co-Authored-By: Claude Opus 5.5 --- .../prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index d5f7d13ba0a8..0cd1b94c2d2c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -1977,11 +1977,11 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : } } VkPhysicalDeviceDescriptorHeapFeaturesEXT descriptorHeapFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_FEATURES_EXT}; - const auto deviceApi = state->properties.apiVersion; - bool releasedDescriptorHeap = deviceApi >= VK_MAKE_API_VERSION(0, 1, 4, 340); - if (Graphics::GpuHeapEnabled() && hasExtension(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME) && !releasedDescriptorHeap) - std::fprintf(stderr, "[gpu-heap] the driver reports Vulkan %u.%u.%u, older than 1.4.340 where VK_EXT_descriptor_heap was released, so its descriptor heap is a pre-release revision and the GPU heap stays off\n", - VK_API_VERSION_MAJOR(deviceApi), VK_API_VERSION_MINOR(deviceApi), VK_API_VERSION_PATCH(deviceApi)); + const auto heapExtension = std::find_if(availableExtensions.begin(), availableExtensions.end(), [](const auto& item) { return std::strcmp(item.extensionName, VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME) == 0; }); + bool releasedDescriptorHeap = heapExtension != availableExtensions.end() && heapExtension->specVersion >= VK_EXT_DESCRIPTOR_HEAP_SPEC_VERSION; + if (Graphics::GpuHeapEnabled() && heapExtension != availableExtensions.end() && !releasedDescriptorHeap) + std::fprintf(stderr, "[gpu-heap] the driver's VK_EXT_descriptor_heap is revision %u, older than the released revision %u, so the GPU heap stays off\n", + heapExtension->specVersion, static_cast(VK_EXT_DESCRIPTOR_HEAP_SPEC_VERSION)); if (Graphics::GpuHeapEnabled() && releasedDescriptorHeap && hasExtension(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME)) { const auto validationVersion = ActiveValidationLayerVersion(state->instanceProc); if (validationVersion.has_value() && *validationVersion < VK_MAKE_API_VERSION(0, 1, 4, 363)) { From aa86660b4c2b29677fc5ab1bd5bb63c1ee54ca8b Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 31 Oct 2026 17:41:34 +0530 Subject: [PATCH 079/269] fix(agc): free retired depth surfaces that only GPU heap slots sample A retired single-sample depth surface stayed alive while any of its sampled views had another holder. A GPU heap slot is such a holder, and the heap frees a slot only once the heap is its view's only holder, which the surface's own view map prevents. With the GPU heap on, every retired depth surface a title had sampled stayed alive for good. releaseRetired now ignores holds that heap slots account for. The views own their image (as multisample ones already did), so a slot keeps sampling a valid image until the next sweep, which release() requests. The stencil copy's views own its image the same way. --- .../Graphics/src/DepthSurface.cpp | 27 ++++++++++++++----- .../tests/DepthSurfaceReuse.cpp | 15 +++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp index 73d166e5f6b0..f95bcad036c9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" @@ -315,7 +316,7 @@ class DepthSurface { allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); memory = AllocateImageMemory(context, allocation, requirements.memoryTypeBits, "vkAllocateMemory depth target"); Check(context.Function("vkBindImageMemory")(context.device, image, memory, 0), "vkBindImageMemory depth"); - if (target.samples != 1u) owned = std::make_shared(this->context, image, memory); + owned = std::make_shared(this->context, image, memory); VkImageViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; viewInfo.image = image; viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; @@ -534,8 +535,14 @@ class DepthSurface { return std::any_of(textures.begin(), textures.end(), held) || std::any_of(stencilCopy.textures.begin(), stencilCopy.textures.end(), held); } - bool SampledElsewhere() const { - return std::any_of(textures.begin(), textures.end(), [](const auto& entry) { return entry.second.use_count() > 1; }); + bool SampledOutsideHeap() const { + const auto outside = [](const auto& entry) { return entry.second != nullptr && entry.second.use_count() > 1 + static_cast(entry.second->HeapHolds()); }; + return std::any_of(textures.begin(), textures.end(), outside) || std::any_of(stencilCopy.textures.begin(), stencilCopy.textures.end(), outside); + } + + bool SampledByHeap() const { + const auto heap = [](const auto& entry) { return entry.second != nullptr && entry.second->HeapHolds() != 0u; }; + return std::any_of(textures.begin(), textures.end(), heap) || std::any_of(stencilCopy.textures.begin(), stencilCopy.textures.end(), heap); } void NoteHostWrite() { @@ -1059,6 +1066,7 @@ class DepthSurface { struct StencilCopy { VkImage image = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; + std::shared_ptr owner; std::unique_ptr staging; std::map, std::shared_ptr> textures; std::uint64_t written = 0; @@ -1163,6 +1171,7 @@ class DepthSurface { allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); stencilCopy.memory = AllocateImageMemory(context, allocation, requirements.memoryTypeBits, "vkAllocateMemory stencil copy"); Check(context.Function("vkBindImageMemory")(context.device, stencilCopy.image, stencilCopy.memory, 0), "vkBindImageMemory stencil copy"); + stencilCopy.owner = std::make_shared(context, stencilCopy.image, stencilCopy.memory); stencilCopy.staging = std::make_unique(context, static_cast(target.extent.width) * target.extent.height, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); } catch (...) { releaseStencilCopy(); @@ -1175,7 +1184,7 @@ class DepthSurface { } auto& texture = stencilCopy.textures[key]; if (texture == nullptr) { - texture = std::make_shared(context, stencilCopy.image, VK_FORMAT_R8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT, components, viewType); + texture = std::make_shared(context, stencilCopy.image, VK_FORMAT_R8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT, components, viewType, 0, stencilCopy.owner); texture->MarkRefreshedPerUse(); } return texture; @@ -1217,8 +1226,11 @@ class DepthSurface { void releaseStencilCopy() noexcept { stencilCopy.textures.clear(); stencilCopy.staging.reset(); - if (stencilCopy.image) context.Function("vkDestroyImage")(context.device, stencilCopy.image, nullptr); - if (stencilCopy.memory) context.Function("vkFreeMemory")(context.device, stencilCopy.memory, nullptr); + if (stencilCopy.owner != nullptr) stencilCopy.owner.reset(); + else { + if (stencilCopy.image) context.Function("vkDestroyImage")(context.device, stencilCopy.image, nullptr); + if (stencilCopy.memory) context.Function("vkFreeMemory")(context.device, stencilCopy.memory, nullptr); + } stencilCopy = {}; } @@ -1313,6 +1325,7 @@ class DepthSurface { } void release() noexcept { + if (SampledByHeap()) BindlessHeap::NoteSweepDue(); depthPlane = {}; stencilPlane = {}; releaseStencilCopy(); @@ -1784,7 +1797,7 @@ void releaseRetired(const Context& context) { auto& list = surfaces(); for (auto it = list.begin(); it != list.end();) { const auto& surface = **it; - if (!surface.retired || surface.context.device != context.device || surface.target.samples != 1u || surface.SampledElsewhere()) { + if (!surface.retired || surface.context.device != context.device || surface.target.samples != 1u || surface.SampledOutsideHeap()) { ++it; continue; } diff --git a/core/libs/prx/libSceAgcDriver/tests/DepthSurfaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/DepthSurfaceReuse.cpp index 47bf9f8ca45b..56e332b4c93f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/DepthSurfaceReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/DepthSurfaceReuse.cpp @@ -440,6 +440,21 @@ void TestRetiredSurfaceRelease(const Context& context) { DepthSurfaceView(context, {sampled + 0x200000u, 0, extent, VK_FORMAT_D32_SFLOAT, 1.0f, 0}); Require(destroyed(sampledImage), "a retired depth surface must free its image once its sampled view is released"); + constexpr std::uint64_t heapHeld = 0x9a000000; + DepthSurfaceView(context, {heapHeld, 0, extent, VK_FORMAT_D32_SFLOAT, 1.0f, 0}); + const auto heapImage = lastImage; + auto slotView = lookup(context, {heapHeld, FormatR32Float, 256, 256}); + Require(slotView != nullptr, "an R32F view of a D32 surface's own extent must sample its depth plane"); + slotView->AddHeapHold(); + RetireDepthSurfaces(context.device, heapHeld, bytes); + const auto heapReleased = DepthSurfacesReleased(); + DepthSurfaceView(context, {heapHeld + 0x100000u, 0, extent, VK_FORMAT_D32_SFLOAT, 1.0f, 0}); + Require(DepthSurfacesReleased() > heapReleased, "a retired depth surface whose sampled view only GPU heap slots hold must be freed"); + Require(!destroyed(heapImage), "a GPU heap slot's sampled view must keep the freed surface's depth image"); + slotView->DropHeapHold(); + slotView.reset(); + Require(destroyed(heapImage), "dropping the heap slot's view must free the depth image"); + constexpr std::uint64_t kept = 0x9c000000; DepthSurfaceView(context, {kept, 0, extent, VK_FORMAT_D32_SFLOAT, 1.0f, 0}); const auto keptImage = lastImage; From 653edfefa188dcb5f2cd053258b26307472a7f9b Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 31 Oct 2026 18:38:18 +0530 Subject: [PATCH 080/269] fix(agc): GPU heap slots hold no reference to what they name A heap slot held a shared reference to its texture, storage image or sampler, and the heap freed slots by sweeping for owners it alone held. Every way an owner can leave its caches then needed its own rule (images in several slots, images that left the storage cache, retired depth surfaces), and the ones missed stayed resident: under memory pressure evicted storage images waited for the next present, the storage budget counted them as memory outside the caches, and the cache shrank to its floor while they stayed alive. A slot now names its owner by address only, as view slots already did. Textures, storage images and samplers free their slots when they are destroyed. That is safe because every batch that reads a slot keeps the slot's owner alive through its draw's or dispatch's resources, the same guarantee the per-draw path relies on for its descriptor sets, so a slot is never reused while a batch can read it. The sweeps, heap holds and the present-time sweep go; a heap refused for lack of free slots comes back when released slots leave twice the margin free. agc_driver_storage_cache_budget_heap_slots runs the storage budget test with every stored image bound to a heap storage slot; evicted images must be freed at once and give their slots back. --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 14 +- .../Execution/src/PresentationPass.cpp | 2 +- .../Execution/src/VulkanDevice.cpp | 1 - .../Graphics/include/BindlessHeap.hpp | 35 +- .../Graphics/include/Sampler.hpp | 3 + .../Graphics/include/Texture.hpp | 6 +- .../Graphics/src/BindlessHeap.cpp | 310 ++++-------------- .../Graphics/src/DepthSurface.cpp | 15 +- .../Graphics/src/MultisampleTarget.cpp | 4 +- .../libSceAgcDriver/Graphics/src/Sampler.cpp | 4 + .../Graphics/src/ShaderResources.cpp | 22 +- .../libSceAgcDriver/Graphics/src/Texture.cpp | 5 +- .../tests/BindlessHeapSlots.cpp | 195 +++++------ .../tests/DepthSurfaceReuse.cpp | 15 - .../tests/execution/SampledCacheBudget.cpp | 16 +- .../tests/execution/StorageCacheBudget.cpp | 59 +++- docs/dev/ARCHITECTURE.md | 2 +- 17 files changed, 263 insertions(+), 445 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index a3d0f7234e71..191f243823fb 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -3507,6 +3507,18 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_storage_cache_retained_batch PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test(NAME agc_driver_storage_cache_budget_heap_slots COMMAND agc_driver_storage_cache_budget_tests --heap-slots) + set_tests_properties(agc_driver_storage_cache_budget_heap_slots PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_storage_cache_budget_heap_slots PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() + add_test(NAME agc_driver_storage_cache_retained_batch_heap_slots COMMAND agc_driver_storage_cache_budget_tests --retained-batch-heap-slots) + set_tests_properties(agc_driver_storage_cache_retained_batch_heap_slots PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_storage_cache_retained_batch_heap_slots PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test(NAME agc_driver_sampled_cache_budget_memory COMMAND agc_driver_sampled_cache_budget_tests memory) set_tests_properties(agc_driver_sampled_cache_budget_memory PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77) add_test(NAME agc_driver_sampled_cache_budget_heap_view COMMAND agc_driver_sampled_cache_budget_tests heap-view) @@ -3619,7 +3631,7 @@ if(BUILD_TESTING) if(WIN32) set_tests_properties(agc_driver_heap_slots_comes_back PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() - foreach(agcHeapSlotsMode IN ITEMS storage-comes-back storage-views-come-back mixed-comes-back views-come-back) + foreach(agcHeapSlotsMode IN ITEMS storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back) string(REPLACE "-" "_" agcHeapSlotsName "${agcHeapSlotsMode}") add_test(NAME agc_driver_heap_slots_${agcHeapSlotsName} COMMAND agc_driver_heap_slots_tests ${agcHeapSlotsMode}) set_tests_properties(agc_driver_heap_slots_${agcHeapSlotsName} PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp index e7ac92f42e86..dbe9f8619982 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp @@ -141,7 +141,7 @@ void PresentationPass::Release(std::size_t index) noexcept { } slot.transient.clear(); if (slot.source && heap) { - if (auto* bindless = Graphics::BindlessHeap::Existing(context)) bindless->ReleaseViewSlots(&slot); + if (auto* bindless = Graphics::BindlessHeap::Existing(context)) bindless->ReleaseImageSlots(&slot); } if (slot.source) context.Function("vkDestroyImageView")(context.device, slot.source, nullptr); slot.source = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index e2803c4ee7f2..06176919bae6 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -3843,7 +3843,6 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu APS5_LOG_OUT_DEBUG("Presentation command buffer begin commands=%p image=%p", reinterpret_cast(commands), reinterpret_cast(state->images[index])); using CommandClass = Graphics::Recorder::CommandClass; Graphics::Recorder::CountPresent(); - if (Graphics::GpuHeapEnabled()) Graphics::BindlessHeap::SweepIfDue(); if (Graphics::Recorder::GpuTimingEnabled()) { if (slot.queries == VK_NULL_HANDLE) { VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 7c0038c45c71..a7aeaaa93bdf 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -50,10 +50,11 @@ class BindlessHeap { std::optional TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, VkImageLayout layout); - std::optional StorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view); + std::optional StorageSlot(std::uint32_t kind, const void* owner, VkImageView view); std::optional StorageSlot(std::uint32_t kind, const std::shared_ptr& image, VkImageView view); std::optional ViewSlot(std::uint32_t kind, const void* owner, VkImageView view); - void ReleaseViewSlots(const void* owner); + void ReleaseImageSlots(const void* owner); + void ReleaseSamplerSlot(const Sampler* sampler); std::uint32_t SlotGeneration(std::uint32_t slot) const; const Texture* SlotTexture(std::uint32_t kind, std::uint32_t slot) const; bool SlotHoldsStorage(std::uint32_t kind, std::uint32_t slot, const void* owner, VkImageView view) const; @@ -65,9 +66,6 @@ class BindlessHeap { std::uint32_t AbsentSlot(std::uint32_t kind, VkImageView view); static bool NearlyFull(); static std::uint32_t ImageSlotCapacity(); - static void NoteSweepDue(); - static void NoteStorageEvicted(); - static void SweepIfDue(); struct DataSpan { std::uint32_t offset = 0; @@ -87,7 +85,7 @@ class BindlessHeap { struct Counts { std::uint64_t textures = 0, samplers = 0, full = 0, ringWraps = 0, encodes = 0, encodedCopies = 0; - std::uint64_t slotsFreed = 0, slotsReused = 0, sweeps = 0, chunkWaits = 0; + std::uint64_t slotsFreed = 0, slotsReused = 0, chunkWaits = 0; std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0; }; Counts Statistics() const; @@ -144,38 +142,31 @@ class BindlessHeap { } }; std::unordered_map textureSlots; - std::unordered_map> viewSlots; - std::unordered_map> storageSlots; + std::unordered_map> ownerSlots; std::uint32_t nextTextureSlot = 0; struct SlotOwner { - std::shared_ptr texture; - std::shared_ptr storage; - const StorageTexture* image = nullptr; + const Texture* texture = nullptr; TextureKey key{}; std::uint32_t generation = 0; }; std::vector owners; std::vector freeSlots; std::uint32_t slotCap = 0; - std::uint64_t slotRequests = 0; - void sweepLocked(std::vector>& dropped); - bool heldOnlyHereLocked(const void* owner, long uses) const; - std::optional takeStorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view, const StorageTexture* image); - bool releaseUncachedLocked(std::vector>& dropped, bool storagePhase); - void dropStorageLocked(const void* image, std::uint32_t slot); + std::optional ownedSlot(std::uint32_t kind, const void* owner, VkImageView view); std::optional takeSlotLocked(); - std::optional takeOrSweepLocked(std::vector>& dropped); SlotOwner& claimSlotLocked(const TextureKey& key, std::uint32_t slot); void freeSlotLocked(std::uint32_t slot); const SlotOwner* ownerLocked(std::uint32_t slot) const; std::unordered_map samplerSlots; std::unordered_set absentSlots; - std::vector> heldSamplers; + std::vector heldSamplers; std::vector samplerGenerations; std::vector freeSamplerSlots; - void sweepSamplersLocked(std::vector>& dropped); - void noteTakenLocked(std::vector>& dropped); - void noteSamplerTakenLocked(std::vector>& dropped); + bool refused = false; + void noteRefusedLocked(const char* what, std::uint32_t margin); + void noteTakenLocked(); + void noteSamplerTakenLocked(); + void noteReleasedLocked(); std::uint32_t imageMargin() const; std::size_t unusedLocked() const; bool roomLocked() const; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp index f494ce1a422f..daabdbd4c6ca 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp @@ -5,6 +5,7 @@ #include "prx/libSceAgcDriver/Graphics/include/GuestSamplerResource.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" #include +#include #include #include #include @@ -32,11 +33,13 @@ class Sampler { cacheKey = key; keyed = true; } + void MarkHeapSlotted() { heapSlotted.store(true, std::memory_order_release); } private: void release() noexcept; Context context; + std::atomic heapSlotted{false}; bool forcesDegamma = false; VkSampler sampler = VK_NULL_HANDLE; bool requiresFilterMinmax = false; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp index fa8a0df9abb1..42bd920e7bef 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp @@ -121,12 +121,10 @@ class Texture { void MarkRefreshedPerUse() { perUseCopy = PerUseCopy::RemadePerUse; } bool Released() const { return released.load(std::memory_order_acquire); } void MarkReleased() { released.store(true, std::memory_order_release); } - std::uint32_t HeapHolds() const { return heapHolds.load(std::memory_order_relaxed); } - void AddHeapHold() { heapHolds.fetch_add(1, std::memory_order_relaxed); } - void DropHeapHold() { heapHolds.fetch_sub(1, std::memory_order_relaxed); } + void MarkHeapSlotted() { heapSlotted.store(true, std::memory_order_release); } private: - std::atomic heapHolds{0}; + std::atomic heapSlotted{false}; void release() noexcept; bool refreshBlockCopy(); bool refreshSrgbExpand(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index e2bf5a41f7c5..e15b19f05d29 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -5,7 +5,6 @@ #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" -#include "prx/libc/include/HostThreadLocal.hpp" #include "Recompiler.hpp" #include "RuntimeAbi.hpp" #include "SpirvBackend/SpirvAnalysis.hpp" @@ -243,22 +242,19 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { slotCap = configuredSlotCap(); } -BindlessHeap::~BindlessHeap() = default; - namespace { -struct SweptStorageTag {}; +constexpr std::uint32_t ImageSlotMargin = 1024u; +constexpr std::uint32_t SamplerSlotMargin = Abi::GpuSamplerHeapSlots / 4u; +std::atomic refusedHeaps{0}; -std::vector>& sweptStorage() { - return HostThreadLocal>, SweptStorageTag>(); } -struct SweptStorageRelease { - ~SweptStorageRelease() { - auto released = std::move(sweptStorage()); - sweptStorage().clear(); - } -}; +BindlessHeap::~BindlessHeap() { + if (refused) refusedHeaps.fetch_sub(1, std::memory_order_relaxed); +} + +namespace { std::mutex& heapsMutex() { static auto& mutex = *new std::mutex(); @@ -318,91 +314,74 @@ std::optional BindlessHeap::TextureSlot(std::uint32_t kind, const const bool sampledKind = kind >= Abi::FirstImageBinding && kind < Abi::FirstStorageImageBinding; if (!sampledKind || texture == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid texture slot request"); - std::vector> dropped; - SweptStorageRelease swept; std::lock_guard lock(mutex); const TextureKey key{kind, texture.get(), view, layout}; if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; - if (++slotRequests % 1024u == 0u) NoteSweepDue(); - const auto slot = takeOrSweepLocked(dropped); + const auto slot = takeSlotLocked(); if (!slot) return std::nullopt; writeImageSlot(kind, *slot, view, layout); - auto& owner = claimSlotLocked(key, *slot); - owner.texture = texture; - texture->AddHeapHold(); - noteTakenLocked(dropped); - if (const auto& source = texture->SharedStorageSource(); source != nullptr && source->LeftCache()) NoteStorageEvicted(); + claimSlotLocked(key, *slot).texture = texture.get(); + texture->MarkHeapSlotted(); + noteTakenLocked(); return slot; } -std::optional BindlessHeap::StorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view) { - return takeStorageSlot(kind, std::move(owner), view, nullptr); -} - std::optional BindlessHeap::StorageSlot(std::uint32_t kind, const std::shared_ptr& image, VkImageView view) { - return takeStorageSlot(kind, image, view, image.get()); + return StorageSlot(kind, static_cast(image.get()), view); } -std::optional BindlessHeap::takeStorageSlot(std::uint32_t kind, std::shared_ptr owner, VkImageView view, const StorageTexture* image) { +std::optional BindlessHeap::StorageSlot(std::uint32_t kind, const void* owner, VkImageView view) { if (!Abi::GpuHeapStorageKind(kind) || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid storage slot request"); - std::vector> dropped; - SweptStorageRelease swept; - std::lock_guard lock(mutex); - const TextureKey key{kind, owner.get(), view, VK_IMAGE_LAYOUT_GENERAL}; - if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; - if (++slotRequests % 1024u == 0u) NoteSweepDue(); - const auto slot = takeOrSweepLocked(dropped); - if (!slot) return std::nullopt; - noteTakenLocked(dropped); - writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); - auto& claimed = claimSlotLocked(key, *slot); - claimed.storage = std::move(owner); - claimed.image = image; - storageSlots[key.texture].push_back(*slot); - if (image != nullptr && image->LeftCache()) NoteStorageEvicted(); - return slot; + return ownedSlot(kind, owner, view); } std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const void* owner, VkImageView view) { const bool imageKind = kind >= Abi::FirstImageBinding && kind < SamplerKind; if (!imageKind || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid view slot request"); - std::vector> dropped; - SweptStorageRelease swept; + return ownedSlot(kind, owner, view); +} + +std::optional BindlessHeap::ownedSlot(std::uint32_t kind, const void* owner, VkImageView view) { std::lock_guard lock(mutex); const TextureKey key{kind, owner, view, VK_IMAGE_LAYOUT_GENERAL}; if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; - const auto slot = takeOrSweepLocked(dropped); + const auto slot = takeSlotLocked(); if (!slot) return std::nullopt; - noteTakenLocked(dropped); writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); claimSlotLocked(key, *slot); - viewSlots[owner].push_back(*slot); + noteTakenLocked(); return slot; } -void BindlessHeap::ReleaseViewSlots(const void* owner) { +void BindlessHeap::ReleaseImageSlots(const void* owner) { std::lock_guard lock(mutex); - const auto found = viewSlots.find(owner); - if (found == viewSlots.end()) return; - for (const auto slot : found->second) freeSlotLocked(slot); + const auto found = ownerSlots.find(owner); + if (found == ownerSlots.end()) return; + const auto slots = std::move(found->second); + ownerSlots.erase(found); + for (const auto slot : slots) freeSlotLocked(slot); slotSerial.fetch_add(1, std::memory_order_release); - viewSlots.erase(found); - if (NearlyFull()) NoteSweepDue(); + noteReleasedLocked(); } -std::optional BindlessHeap::takeOrSweepLocked(std::vector>& dropped) { - auto slot = takeSlotLocked(); - if (!slot) { - sweepLocked(dropped); - slot = takeSlotLocked(); - } - if (!slot) ++counts.full; - return slot; +void BindlessHeap::ReleaseSamplerSlot(const Sampler* sampler) { + std::lock_guard lock(mutex); + const auto found = samplerSlots.find(sampler); + if (found == samplerSlots.end()) return; + const auto slot = found->second; + samplerSlots.erase(found); + heldSamplers[slot] = nullptr; + ++samplerGenerations[slot]; + slotSerial.fetch_add(1, std::memory_order_release); + freeSamplerSlots.push_back(slot); + ++counts.slotsFreed; + noteReleasedLocked(); } BindlessHeap::SlotOwner& BindlessHeap::claimSlotLocked(const TextureKey& key, std::uint32_t slot) { textureSlots.emplace(key, slot); + ownerSlots[key.texture].push_back(slot); if (owners.size() <= slot) owners.resize(slot + 1u); owners[slot].key = key; ++counts.textures; @@ -411,13 +390,8 @@ BindlessHeap::SlotOwner& BindlessHeap::claimSlotLocked(const TextureKey& key, st void BindlessHeap::freeSlotLocked(std::uint32_t slot) { auto& owner = owners[slot]; - if (const auto found = storageSlots.find(owner.key.texture); found != storageSlots.end()) { - auto& slots = found->second; - if (const auto at = std::find(slots.begin(), slots.end(), slot); at != slots.end()) slots.erase(at); - if (slots.empty()) storageSlots.erase(found); - } textureSlots.erase(owner.key); - owner.image = nullptr; + owner.texture = nullptr; owner.key = {}; ++owner.generation; freeSlots.push_back(slot); @@ -435,173 +409,21 @@ std::optional BindlessHeap::takeSlotLocked() { ++counts.slotsReused; return slot; } - if (nextTextureSlot >= slotCap) return std::nullopt; - return nextTextureSlot++; -} - -void BindlessHeap::sweepLocked(std::vector>& dropped) { - ++counts.sweeps; - const auto firstDropped = dropped.size(); - for (std::uint32_t slot = SamplerKind; slot < owners.size(); ++slot) { - auto& owner = owners[slot]; - if (owner.storage != nullptr) { - if (!heldOnlyHereLocked(owner.key.texture, owner.storage.use_count())) continue; - dropStorageLocked(owner.key.texture, slot); - continue; - } else { - const bool heldElsewhere = - owner.texture == nullptr || owner.texture.use_count() > static_cast(owner.texture->HeapHolds()); - if (heldElsewhere) continue; - dropped.push_back(std::move(owner.texture)); - } - freeSlotLocked(slot); - slotSerial.fetch_add(1, std::memory_order_release); - } - for (auto index = firstDropped; index < dropped.size(); ++index) dropped[index]->DropHeapHold(); -} - -bool BindlessHeap::heldOnlyHereLocked(const void* owner, long uses) const { - const auto found = storageSlots.find(owner); - const auto slots = found != storageSlots.end() ? static_cast(found->second.size()) : 1l; - return uses <= slots; -} - -bool BindlessHeap::releaseUncachedLocked(std::vector>& dropped, bool storagePhase) { - bool heldElsewhere = false; - const auto firstDropped = dropped.size(); - std::vector> images; - for (std::uint32_t slot = SamplerKind; slot < owners.size(); ++slot) { - auto& owner = owners[slot]; - if (owner.storage != nullptr) { - if (!storagePhase) continue; - if (owner.image == nullptr || !owner.image->LeftCache()) continue; - const auto found = storageSlots.find(owner.key.texture); - if (found == storageSlots.end() || found->second.front() != slot) continue; - if (!heldOnlyHereLocked(owner.key.texture, owner.storage.use_count())) { - heldElsewhere = true; - continue; - } - images.emplace_back(owner.key.texture, slot); - continue; - } - if (storagePhase || owner.texture == nullptr) continue; - const auto& source = owner.texture->SharedStorageSource(); - if (source == nullptr || !source->LeftCache()) continue; - if (owner.texture.use_count() > static_cast(owner.texture->HeapHolds())) { - heldElsewhere = true; - continue; - } - heldElsewhere = true; - dropped.push_back(std::move(owner.texture)); - freeSlotLocked(slot); - slotSerial.fetch_add(1, std::memory_order_release); - } - for (auto index = firstDropped; index < dropped.size(); ++index) dropped[index]->DropHeapHold(); - for (const auto& [image, slot] : images) dropStorageLocked(image, slot); - return heldElsewhere; -} - -void BindlessHeap::dropStorageLocked(const void* image, std::uint32_t slot) { - std::vector slots{slot}; - if (const auto found = storageSlots.find(image); found != storageSlots.end()) slots = found->second; - for (const auto held : slots) { - sweptStorage().push_back(std::move(owners[held].storage)); - freeSlotLocked(held); - } - slotSerial.fetch_add(1, std::memory_order_release); -} - -void BindlessHeap::sweepSamplersLocked(std::vector>& dropped) { - for (std::uint32_t slot = 0; slot < heldSamplers.size(); ++slot) { - auto& held = heldSamplers[slot]; - if (held == nullptr || held.use_count() != 1) continue; - samplerSlots.erase(held.get()); - dropped.push_back(std::move(held)); - ++samplerGenerations[slot]; - slotSerial.fetch_add(1, std::memory_order_release); - freeSamplerSlots.push_back(slot); - ++counts.slotsFreed; + if (nextTextureSlot >= slotCap) { + ++counts.full; + return std::nullopt; } -} - -namespace { - -constexpr std::uint32_t ImageSlotMargin = 1024u; -constexpr std::uint32_t SamplerSlotMargin = Abi::GpuSamplerHeapSlots / 4u; -std::atomic nearlyFull{false}; - -void noteNearlyFull(const char* what, std::uint32_t margin) { - if (!nearlyFull.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; draws and dispatches take the per-draw path until a sweep frees twice that many\n", margin, what); -} - + return nextTextureSlot++; } bool BindlessHeap::NearlyFull() { - return nearlyFull.load(std::memory_order_relaxed); + return refusedHeaps.load(std::memory_order_relaxed) != 0u; } std::uint32_t BindlessHeap::ImageSlotCapacity() { return configuredSlotCap() - SamplerKind; } -namespace { - -std::atomic sweepDue{false}; - -std::atomic uncachedPending{false}; -std::atomic refusedSweepChecks{0}; -constexpr std::uint32_t RefusedSweepInterval = 64u; - -} - -void BindlessHeap::NoteSweepDue() { - sweepDue.store(true, std::memory_order_relaxed); -} - -void BindlessHeap::NoteStorageEvicted() { - uncachedPending.store(true, std::memory_order_relaxed); -} - -void BindlessHeap::SweepIfDue() { - const bool uncached = uncachedPending.load(std::memory_order_relaxed) && uncachedPending.exchange(false, std::memory_order_relaxed); - const bool due = sweepDue.load(std::memory_order_relaxed) && sweepDue.exchange(false, std::memory_order_relaxed); - const bool retry = !due && nearlyFull.load(std::memory_order_relaxed) && - refusedSweepChecks.fetch_add(1, std::memory_order_relaxed) % RefusedSweepInterval == RefusedSweepInterval - 1u; - if (!due && !retry && !uncached) return; - bool again = false; - bool room = true; - { - std::vector> dropped; - SweptStorageRelease swept; - std::vector> droppedSamplers; - std::lock_guard heapsLock(heapsMutex()); - for (auto& [device, heap] : heaps()) { - if (heap == nullptr) continue; - std::lock_guard lock(heap->mutex); - if (due || retry) { - heap->sweepLocked(dropped); - heap->sweepSamplersLocked(droppedSamplers); - } - if (uncached && heap->releaseUncachedLocked(dropped, false)) again = true; - } - } - { - std::vector> none; - SweptStorageRelease swept; - std::lock_guard heapsLock(heapsMutex()); - for (auto& [device, heap] : heaps()) { - if (heap == nullptr) continue; - std::lock_guard lock(heap->mutex); - if (uncached && heap->releaseUncachedLocked(none, true)) again = true; - room = room && heap->roomLocked(); - } - } - if (again) NoteStorageEvicted(); - if (room && nearlyFull.exchange(false, std::memory_order_relaxed)) - std::fprintf(stderr, "[gpu-heap] a sweep left twice the margin of slots free; draws take the heap again\n"); -} - std::uint32_t BindlessHeap::imageMargin() const { return std::max(1u, std::min(ImageSlotMargin, (slotCap - SamplerKind) / 4u)); } @@ -615,20 +437,27 @@ bool BindlessHeap::roomLocked() const { return Abi::GpuSamplerHeapSlots - heldSamplers.size() + freeSamplerSlots.size() >= 2u * SamplerSlotMargin; } -void BindlessHeap::noteTakenLocked(std::vector>& dropped) { - if (nearlyFull.load(std::memory_order_relaxed)) return; +void BindlessHeap::noteRefusedLocked(const char* what, std::uint32_t margin) { + if (refused) return; + refused = true; + refusedHeaps.fetch_add(1, std::memory_order_relaxed); + std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; draws and dispatches take the per-draw path until released slots leave twice that many free\n", margin, what); +} + +void BindlessHeap::noteTakenLocked() { const auto margin = imageMargin(); - if (unusedLocked() >= margin) return; - sweepLocked(dropped); - if (unusedLocked() < margin) noteNearlyFull("image", margin); + if (!refused && unusedLocked() < margin) noteRefusedLocked("image", margin); +} + +void BindlessHeap::noteSamplerTakenLocked() { + if (!refused && Abi::GpuSamplerHeapSlots - heldSamplers.size() + freeSamplerSlots.size() < SamplerSlotMargin) noteRefusedLocked("sampler", SamplerSlotMargin); } -void BindlessHeap::noteSamplerTakenLocked(std::vector>& dropped) { - if (nearlyFull.load(std::memory_order_relaxed)) return; - const auto unused = [&] { return Abi::GpuSamplerHeapSlots - heldSamplers.size() + freeSamplerSlots.size(); }; - if (unused() >= SamplerSlotMargin) return; - sweepSamplersLocked(dropped); - if (unused() < SamplerSlotMargin) noteNearlyFull("sampler", SamplerSlotMargin); +void BindlessHeap::noteReleasedLocked() { + if (!refused || !roomLocked()) return; + refused = false; + refusedHeaps.fetch_sub(1, std::memory_order_relaxed); + std::fprintf(stderr, "[gpu-heap] released slots left twice the margin free; draws take the heap again\n"); } std::uint32_t BindlessHeap::SamplerGeneration(std::uint32_t slot) const { @@ -666,7 +495,7 @@ std::uint32_t BindlessHeap::SlotGeneration(std::uint32_t slot) const { const Texture* BindlessHeap::SlotTexture(std::uint32_t kind, std::uint32_t slot) const { std::lock_guard lock(mutex); const auto* owner = ownerLocked(slot); - return owner != nullptr && owner->key.kind == kind ? owner->texture.get() : nullptr; + return owner != nullptr && owner->key.kind == kind ? owner->texture : nullptr; } bool BindlessHeap::SlotHoldsStorage(std::uint32_t kind, std::uint32_t slot, const void* owner, VkImageView view) const { @@ -686,10 +515,8 @@ std::uint32_t BindlessHeap::AbsentSlot(std::uint32_t kind, VkImageView view) { std::optional BindlessHeap::SamplerSlot(const std::shared_ptr& sampler) { if (sampler == nullptr) throw std::runtime_error("AGC bindless heap: invalid sampler slot request"); - std::vector> dropped; std::lock_guard lock(mutex); if (const auto found = samplerSlots.find(sampler.get()); found != samplerSlots.end()) return found->second; - if (freeSamplerSlots.empty()) sweepSamplersLocked(dropped); std::uint32_t slot = 0; if (!freeSamplerSlots.empty()) { slot = freeSamplerSlots.back(); @@ -705,9 +532,10 @@ std::optional BindlessHeap::SamplerSlot(const std::shared_ptrHandle()); samplerSlots.emplace(sampler.get(), slot); - heldSamplers[slot] = sampler; + heldSamplers[slot] = sampler.get(); + sampler->MarkHeapSlotted(); ++counts.samplers; - noteSamplerTakenLocked(dropped); + noteSamplerTakenLocked(); return slot; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp index f95bcad036c9..1a31fe45d87a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp @@ -1,5 +1,4 @@ #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" -#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" @@ -535,14 +534,9 @@ class DepthSurface { return std::any_of(textures.begin(), textures.end(), held) || std::any_of(stencilCopy.textures.begin(), stencilCopy.textures.end(), held); } - bool SampledOutsideHeap() const { - const auto outside = [](const auto& entry) { return entry.second != nullptr && entry.second.use_count() > 1 + static_cast(entry.second->HeapHolds()); }; - return std::any_of(textures.begin(), textures.end(), outside) || std::any_of(stencilCopy.textures.begin(), stencilCopy.textures.end(), outside); - } - - bool SampledByHeap() const { - const auto heap = [](const auto& entry) { return entry.second != nullptr && entry.second->HeapHolds() != 0u; }; - return std::any_of(textures.begin(), textures.end(), heap) || std::any_of(stencilCopy.textures.begin(), stencilCopy.textures.end(), heap); + bool SampledElsewhere() const { + const auto held = [](const auto& entry) { return entry.second.use_count() > 1; }; + return std::any_of(textures.begin(), textures.end(), held) || std::any_of(stencilCopy.textures.begin(), stencilCopy.textures.end(), held); } void NoteHostWrite() { @@ -1325,7 +1319,6 @@ class DepthSurface { } void release() noexcept { - if (SampledByHeap()) BindlessHeap::NoteSweepDue(); depthPlane = {}; stencilPlane = {}; releaseStencilCopy(); @@ -1797,7 +1790,7 @@ void releaseRetired(const Context& context) { auto& list = surfaces(); for (auto it = list.begin(); it != list.end();) { const auto& surface = **it; - if (!surface.retired || surface.context.device != context.device || surface.target.samples != 1u || surface.SampledOutsideHeap()) { + if (!surface.retired || surface.context.device != context.device || surface.target.samples != 1u || surface.SampledElsewhere()) { ++it; continue; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp index 857885016a03..1ca9709273f2 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp @@ -757,8 +757,8 @@ class MultisampleTarget : public std::enable_shared_from_this if (orderView) context.Function("vkDestroyImageView")(context.device, orderView, nullptr); if (twinView) context.Function("vkDestroyImageView")(context.device, twinView, nullptr); if (auto* heap = BindlessHeap::Existing(context)) { - if (storageView) heap->ReleaseViewSlots(reinterpret_cast(storageView)); - if (uintStorageView) heap->ReleaseViewSlots(reinterpret_cast(uintStorageView)); + if (storageView) heap->ReleaseImageSlots(reinterpret_cast(storageView)); + if (uintStorageView) heap->ReleaseImageSlots(reinterpret_cast(uintStorageView)); } if (storageView) context.Function("vkDestroyImageView")(context.device, storageView, nullptr); if (uintStorageView) context.Function("vkDestroyImageView")(context.device, uintStorageView, nullptr); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp index 3b0160e00544..dc1cac5fd13d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp" #include #include @@ -55,6 +56,9 @@ namespace AgcDriver::Graphics { } void Sampler::release() noexcept { + if (heapSlotted.exchange(false, std::memory_order_acq_rel)) { + if (auto* heap = BindlessHeap::Existing(context)) heap->ReleaseSamplerSlot(this); + } if (sampler) context.Function("vkDestroySampler")(context.device, sampler, nullptr); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 4d39e39d4cd8..02ed51780595 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -232,7 +232,6 @@ std::list::iterator findTexture(TextureCache& cache, const Textur } void eraseTexture(TextureCache& cache, std::list::iterator it) { - if (it->texture != nullptr && it->texture->HeapHolds() != 0u) BindlessHeap::NoteSweepDue(); cache.bytes -= it->accounted; if (it->source != nullptr) { for (auto [view, last] = cache.views.equal_range(it->source.get()); view != last; ++view) { @@ -325,8 +324,7 @@ bool admitTexture(TextureCache& cache, const TextureKey& key, std::uint64_t inco ++cache.counts.uncached; return false; } - const auto heapHolds = back->texture != nullptr ? back->texture->HeapHolds() : 0u; - const bool keep = back->accounted == 0 || (!over && back->texture.use_count() > 1 + static_cast(heapHolds)); + const bool keep = back->accounted == 0 || (!over && back->texture.use_count() > 1); if (keep && cache.passed < cache.entries.size()) { cache.entries.splice(cache.entries.begin(), cache.entries, back); ++cache.passed; @@ -1153,7 +1151,6 @@ std::list::iterator findStorageByImage(StorageTextureCache std::shared_ptr evictStorage(StorageTextureCache& cache, std::list::iterator it) { auto texture = it->texture; it->texture->SetCached(false); - if (GpuHeapEnabled()) BindlessHeap::NoteStorageEvicted(); noteUncached(it->texture); it->texture->Flush(); cache.bytes -= it->accounted; @@ -1446,7 +1443,6 @@ void ClearCachedTextures(VkDevice device) { } cleared.push_back(it->texture); it->texture->SetCached(false); - if (GpuHeapEnabled()) BindlessHeap::NoteStorageEvicted(); noteUncached(it->texture); storage.bytes -= it->accounted; storage.index.erase(it->key); @@ -1475,7 +1471,6 @@ std::uint64_t ReleaseTextureCaches(std::uint64_t bytes, bool newImage) { ~Done() { flag = false; } } done{releasing}; std::uint64_t freed = 0; - std::uint64_t heapHeldBytes = 0; std::size_t sampledEntries = 0; std::size_t storageEntries = 0; std::size_t storageKept = 0; @@ -1488,10 +1483,9 @@ std::uint64_t ReleaseTextureCaches(std::uint64_t bytes, bool newImage) { if ((inherited && (!newImage || sampledCacheReclaimable == 0)) || (!inherited && !lock.try_lock())) { sampledSkipped = true; } else { - for (auto it = cache.entries.end(); it != cache.entries.begin() && freed + heapHeldBytes < bytes;) { + for (auto it = cache.entries.end(); it != cache.entries.begin() && freed < bytes;) { --it; - const auto heapHolds = static_cast(it->texture->HeapHolds()); - if (it->texture.use_count() != 1 + heapHolds || (it->source != nullptr && it->source->Dirty())) continue; + if (it->texture.use_count() != 1 || (it->source != nullptr && it->source->Dirty())) continue; const auto allocated = it->texture->AllocationBytes(); const auto sourceBytes = it->source != nullptr ? it->source->AllocationBytes() : 0u; const std::weak_ptr source = it->source; @@ -1499,20 +1493,12 @@ std::uint64_t ReleaseTextureCaches(std::uint64_t bytes, bool newImage) { eraseTexture(cache, it); ++cache.counts.evicted; ++sampledEntries; - if (heapHolds != 0) heapHeldBytes += allocated; - else freed += allocated; + freed += allocated; if (source.expired()) freed += sourceBytes; it = next; } } } - if (heapHeldBytes != 0) { - BindlessHeap::NoteSweepDue(); - if (sampledCacheHeld == 0) { - BindlessHeap::SweepIfDue(); - freed += heapHeldBytes; - } - } if (freed < bytes) { auto& cache = StorageTextures(); std::unique_lock gpu(GuestMemory::GpuMutex(), std::defer_lock); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index 470ae32c9b36..fceece3a5edf 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -1235,6 +1235,9 @@ VkImageView Texture::BaseLevelView() const { } void Texture::release() noexcept { + if (heapSlotted.exchange(false, std::memory_order_acq_rel)) { + if (auto* heap = BindlessHeap::Existing(context)) heap->ReleaseImageSlots(this); + } upload.reset(); if (view) context.Function("vkDestroyImageView")(context.device, view, nullptr); view = VK_NULL_HANDLE; @@ -6568,7 +6571,7 @@ StorageTexture::~StorageTexture() { } void StorageTexture::release() noexcept { - if (auto* heap = BindlessHeap::Existing(context)) heap->ReleaseViewSlots(this); + if (auto* heap = BindlessHeap::Existing(context)) heap->ReleaseImageSlots(this); for (const auto& [mip, extra] : extraViews) context.Function("vkDestroyImageView")(context.device, extra, nullptr); extraViews.clear(); for (const auto& [mip, extra] : firstLayerViews) context.Function("vkDestroyImageView")(context.device, extra, nullptr); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index cad3ef158c4d..7bc5b0518382 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -27,7 +27,6 @@ void require(bool condition, const std::string& what) { } alignas(Texture) std::array, 8> fakeTextures{}; -alignas(StorageTexture) std::array, 3> fakeImages{}; std::shared_ptr fakeTexture(std::size_t index) { return std::shared_ptr(reinterpret_cast(fakeTextures[index].data()), [](Texture*) {}); @@ -39,53 +38,54 @@ void textureSlots(const Context& context, VkImageView view) { auto first = fakeTexture(0); const auto slot = heap.TextureSlot(kind, first, view, VK_IMAGE_LAYOUT_GENERAL); require(slot.has_value(), "the first texture takes a slot"); - require(heap.SlotTexture(kind, *slot) == first.get(), "the slot holds the first texture"); + require(heap.SlotTexture(kind, *slot) == first.get(), "the slot names the first texture"); + require(first.use_count() == 1, "a heap slot holds a reference to its texture"); const auto generation = heap.SlotGeneration(*slot); auto second = fakeTexture(1); - require(!heap.TextureSlot(kind, second, view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a held slot is not reused"); - first.reset(); + require(!heap.TextureSlot(kind, second, view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "the slot of a live texture is not reused"); + heap.ReleaseImageSlots(first.get()); const auto reused = heap.TextureSlot(kind, second, view, VK_IMAGE_LAYOUT_GENERAL); require(reused.has_value() && *reused == *slot, "the released texture's slot is reused"); require(heap.SlotGeneration(*slot) != generation, "a freed slot moves its generation"); - require(heap.SlotTexture(kind, *slot) == second.get(), "the reused slot holds the second texture"); + require(heap.SlotTexture(kind, *slot) == second.get(), "the reused slot names the second texture"); const auto counts = heap.Statistics(); require(counts.slotsFreed == 1u && counts.slotsReused == 1u, "one slot freed and reused"); auto shared = fakeTexture(2); const auto otherKind = kind + 1u; require(!heap.TextureSlot(otherKind, shared, view, VK_IMAGE_LAYOUT_GENERAL).has_value(), - "another kind finds the capped heap's only slot held"); - second.reset(); + "another kind finds the capped heap's only slot taken"); + heap.ReleaseImageSlots(second.get()); const auto sharedSlot = heap.TextureSlot(otherKind, shared, view, VK_IMAGE_LAYOUT_GENERAL); require(sharedSlot.has_value() && *sharedSlot == *slot, "another kind takes the slot the first kind's texture left"); - require(shared->HeapHolds() == 1u, "a texture placed by the heap counts one heap hold"); require(heap.SlotTexture(kind, *slot) == nullptr && heap.SlotTexture(otherKind, *slot) == shared.get(), - "the slot holds the other kind's texture"); - shared.reset(); + "the slot names the other kind's texture"); const auto freedBefore = heap.Statistics().slotsFreed; - auto third = fakeTexture(0); - require(heap.TextureSlot(kind, third, view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture held only by the heap is swept"); - require(heap.Statistics().slotsFreed == freedBefore + 1u, "the sweep frees the slot whose texture only the heap holds"); + heap.ReleaseImageSlots(shared.get()); + heap.ReleaseImageSlots(shared.get()); + require(heap.Statistics().slotsFreed == freedBefore + 1u, "a texture's release frees its slot once"); } void samplerSlots(const Context& context) { - BindlessHeap heap(context); + auto& heap = BindlessHeap::For(context); auto cache = std::make_unique(); const std::array firstWords{0u, 0u, 0u, 0u}; const std::array secondWords{0u, 0u, 0x00100000u, 0u}; auto first = cache->Get(context, firstWords, false); + const auto uses = first.use_count(); const auto slot = heap.SamplerSlot(first); require(slot.has_value(), "the first sampler takes a slot"); + require(first.use_count() == uses, "a heap slot holds a reference to its sampler"); const auto generation = heap.SamplerGeneration(*slot); require(first->CacheKey() != nullptr, "a cached sampler carries its key"); first.reset(); cache.reset(); + require(heap.SamplerGeneration(*slot) != generation, "a destroyed sampler did not release its slot"); cache = std::make_unique(); auto second = cache->Get(context, secondWords, false); const auto reused = heap.SamplerSlot(second); - require(reused.has_value() && *reused == *slot, "the released sampler's slot is reused"); - require(heap.SamplerGeneration(*slot) != generation, "a freed sampler slot moves its generation"); + require(reused.has_value() && *reused == *slot, "the destroyed sampler's slot is reused"); } void viewSlots(const Context& context, VkImageView view) { @@ -96,10 +96,10 @@ void viewSlots(const Context& context, VkImageView view) { require(slot.has_value() && heap.ViewSlot(kind, &first, view) == slot, "a view keeps its slot"); require(!heap.ViewSlot(kind, &second, view).has_value(), "a full heap refuses another owner's view"); const auto generation = heap.SlotGeneration(*slot); - heap.ReleaseViewSlots(&first); + heap.ReleaseImageSlots(&first); require(heap.SlotGeneration(*slot) != generation, "a released view slot moves its generation"); require(heap.ViewSlot(kind, &second, view) == slot, "a released view slot is reused"); - heap.ReleaseViewSlots(&second); + heap.ReleaseImageSlots(&second); } void encodedViews(const Context& context) { @@ -126,23 +126,17 @@ void encodedViews(const Context& context) { require(encodes() == 2u && copies() == 1u, "a destroyed view's encoded descriptor is not copied to a new view"); } -void sweptOwnerReentry(const Context& context, VkImageView view) { - auto& heap = BindlessHeap::For(context); - const auto kind = Abi::FirstStorageImageBinding + 1u; - int released = 0; - const auto owner = [&] { - return std::shared_ptr(new int(0), [&context, &released](void* pointer) { - if (auto* existing = BindlessHeap::Existing(context)) existing->ReleaseViewSlots(pointer); - ++released; - delete static_cast(pointer); - }); - }; - require(heap.StorageSlot(kind, owner(), view).has_value(), "the first storage owner takes the heap's only slot"); - require(heap.StorageSlot(kind, owner(), view).has_value() && released == 1, - "a full heap sweeps an owner whose release calls back into the heap"); - BindlessHeap::NoteSweepDue(); - BindlessHeap::SweepIfDue(); - require(released == 2, "a due sweep releases an owner that calls back into the heap"); +void ownerSlots(const Context& context, VkImageView view) { + BindlessHeap heap(context); + const int image = 0, other = 0; + const auto slot = heap.StorageSlot(Abi::FirstStorageImageBinding, &image, view); + require(slot.has_value(), "a storage owner takes the capped heap's only slot"); + require(!heap.StorageSlot(Abi::FirstStorageImageBinding + 1u, &image, view).has_value(), "the owner's second view finds the heap full"); + heap.ReleaseImageSlots(&other); + require(!heap.StorageSlot(Abi::FirstStorageImageBinding, &other, view).has_value(), "another owner's release freed this owner's slot"); + heap.ReleaseImageSlots(&image); + require(heap.StorageSlot(Abi::FirstStorageImageBinding, &other, view) == slot, "a storage owner's release frees its slot"); + heap.ReleaseImageSlots(&other); } void ringSpans(const Context& context) { @@ -192,95 +186,46 @@ void heapComesBack(const Context& context, VkImageView view) { "a texture takes one of the eight capped slots"); } require(BindlessHeap::NearlyFull(), "one free slot of eight refuses the heap"); - BindlessHeap::SweepIfDue(); - require(BindlessHeap::NearlyFull(), "a sweep that is not due leaves the heap refused"); - BindlessHeap::NoteSweepDue(); - BindlessHeap::SweepIfDue(); - require(BindlessHeap::NearlyFull(), "a sweep that frees nothing leaves the heap refused"); - held.clear(); - BindlessHeap::NoteSweepDue(); - BindlessHeap::SweepIfDue(); - require(!BindlessHeap::NearlyFull(), "a sweep that frees the slots of textures only the heap held takes the heap again"); + for (std::size_t index = 0; index < 2u; ++index) heap.ReleaseImageSlots(held[index].get()); + require(BindlessHeap::NearlyFull(), "three free slots of eight leave the heap refused"); + heap.ReleaseImageSlots(held[2].get()); + require(!BindlessHeap::NearlyFull(), "a release that leaves twice the margin free takes the heap again"); + for (std::size_t index = 3; index < held.size(); ++index) heap.ReleaseImageSlots(held[index].get()); BindlessHeap::Release(context.device); } void storageComesBack(const Context& context, VkImageView view) { auto& heap = BindlessHeap::For(context); - std::vector> owners; - for (std::size_t index = 0; index < 7u; ++index) { - owners.push_back(std::make_shared(0)); - require(heap.StorageSlot(Abi::FirstStorageImageBinding, owners.back(), view).has_value(), + std::array owners{}; + for (auto& owner : owners) { + require(heap.StorageSlot(Abi::FirstStorageImageBinding, &owner, view).has_value(), "a storage owner takes one of the eight capped slots"); } require(BindlessHeap::NearlyFull(), "storage owners that leave one free slot of eight refuse the heap"); - BindlessHeap::NoteSweepDue(); - BindlessHeap::SweepIfDue(); - require(BindlessHeap::NearlyFull(), "a sweep while every storage owner is held leaves the heap refused"); - owners.clear(); - for (std::uint32_t check = 0; check < 64u && BindlessHeap::NearlyFull(); ++check) BindlessHeap::SweepIfDue(); - require(!BindlessHeap::NearlyFull(), "a refused heap sweeps again by itself and takes the heap back once the storage owners are gone"); + for (auto& owner : owners) heap.ReleaseImageSlots(&owner); + require(!BindlessHeap::NearlyFull(), "releasing the storage owners takes the heap again"); BindlessHeap::Release(context.device); } void storageViewsComeBack(const Context& context, VkImageView view) { auto& heap = BindlessHeap::For(context); - int released = 0; - const auto owner = [&released] { - return std::shared_ptr(new int(0), [&released](void* pointer) { - ++released; - delete static_cast(pointer); - }); - }; - std::vector> owners; + std::array owners{}; for (std::size_t index = 0; index < 3u; ++index) { - owners.push_back(owner()); for (std::uint32_t kind = 0; kind < 2u; ++kind) { - require(heap.StorageSlot(Abi::FirstStorageImageBinding + kind, owners.back(), view).has_value(), + require(heap.StorageSlot(Abi::FirstStorageImageBinding + kind, &owners[index], view).has_value(), "a storage owner takes one of the eight capped slots for each of its two views"); } } - owners.push_back(owner()); - require(heap.StorageSlot(Abi::FirstStorageImageBinding, owners.back(), view).has_value(), "a single-view storage owner takes the seventh slot"); + require(heap.StorageSlot(Abi::FirstStorageImageBinding, &owners[3], view).has_value(), "a single-view storage owner takes the seventh slot"); require(BindlessHeap::NearlyFull(), "storage owners that leave one free slot of eight refuse the heap"); - owners.clear(); - BindlessHeap::NoteSweepDue(); - BindlessHeap::SweepIfDue(); - require(released == 4, "a sweep released " + std::to_string(released) + " of four storage owners the heap alone held, three of them in two slots each"); - require(!BindlessHeap::NearlyFull(), "a sweep after every storage owner is gone takes the heap again"); - - const auto image = [&released](std::size_t index, bool cached) { - auto* pointer = reinterpret_cast(fakeImages[index].data()); - pointer->SetCached(true); - pointer->SetCached(cached); - return std::shared_ptr(pointer, [&released](StorageTexture*) { ++released; }); - }; - auto evicted = image(0, true); - auto cached = image(1, true); - for (std::uint32_t kind = 0; kind < 2u; ++kind) require(heap.StorageSlot(Abi::FirstStorageImageBinding + kind, evicted, view).has_value(), "an evicted image's view takes a slot"); - require(heap.StorageSlot(Abi::FirstStorageImageBinding, cached, view).has_value(), "a cached image takes a slot"); - evicted->SetCached(false); - BindlessHeap::NoteStorageEvicted(); - BindlessHeap::SweepIfDue(); - require(released == 4, "an evicted storage image still held outside the heap lost its slots"); - evicted.reset(); - cached.reset(); - BindlessHeap::SweepIfDue(); - require(released == 5, "the present after an evicted storage image's last outside holder went did not release its two slots, or released the cached image the heap alone holds"); - - auto late = image(0, false); - require(heap.StorageSlot(Abi::FirstStorageImageBinding, late, view).has_value(), "an image that left the storage cache before its first slot takes one"); - BindlessHeap::SweepIfDue(); - require(released == 5, "an image that left the cache lost its slot while still held outside the heap"); - late.reset(); - BindlessHeap::SweepIfDue(); - require(released == 6, "an image that took its slot after leaving the storage cache kept it after its last outside holder went"); - - auto outside = std::shared_ptr(reinterpret_cast(fakeImages[2].data()), [&released](StorageTexture*) { ++released; }); - require(heap.StorageSlot(Abi::FirstStorageImageBinding, outside, view).has_value(), "an image made outside the storage cache takes a slot"); - outside.reset(); - BindlessHeap::NoteStorageEvicted(); - BindlessHeap::SweepIfDue(); - require(released == 6, "an image the storage cache never held lost its slot without a sweep"); + const auto freed = heap.Statistics().slotsFreed; + heap.ReleaseImageSlots(&owners[0]); + require(heap.Statistics().slotsFreed == freed + 2u, "a storage owner's release freed " + std::to_string(heap.Statistics().slotsFreed - freed) + " of its two slots"); + require(BindlessHeap::NearlyFull(), "three free slots of eight leave the heap refused"); + heap.ReleaseImageSlots(&owners[1]); + require(!BindlessHeap::NearlyFull(), "releasing a second two-view owner takes the heap again"); + heap.ReleaseImageSlots(&owners[2]); + heap.ReleaseImageSlots(&owners[3]); BindlessHeap::Release(context.device); } @@ -293,17 +238,15 @@ void mixedComesBack(const Context& context, VkImageView sampledView, VkImageView "a texture takes one of the eight capped slots"); } require(!BindlessHeap::NearlyFull(), "four textures in eight capped slots leave the heap taken"); - std::vector> owners; - for (std::size_t index = 0; index < 3u; ++index) { - owners.push_back(std::make_shared(0)); - require(heap.StorageSlot(Abi::FirstStorageImageBinding, owners.back(), storageView).has_value(), + std::array owners{}; + for (auto& owner : owners) { + require(heap.StorageSlot(Abi::FirstStorageImageBinding, &owner, storageView).has_value(), "a storage owner takes one of the slots the textures left"); } require(BindlessHeap::NearlyFull(), "storage owners that take the slots the textures left refuse the heap"); - owners.clear(); - BindlessHeap::NoteSweepDue(); - BindlessHeap::SweepIfDue(); - require(!BindlessHeap::NearlyFull(), "a sweep after the storage owners are gone takes the heap again while the textures stay"); + for (auto& owner : owners) heap.ReleaseImageSlots(&owner); + require(!BindlessHeap::NearlyFull(), "releasing the storage owners takes the heap again while the textures stay"); + for (const auto& texture : textures) heap.ReleaseImageSlots(texture.get()); BindlessHeap::Release(context.device); } @@ -313,12 +256,27 @@ void viewsComeBack(const Context& context, VkImageView view) { std::array owners{}; for (auto& owner : owners) require(heap.ViewSlot(kind, &owner, view).has_value(), "a view takes one of the eight capped slots"); require(BindlessHeap::NearlyFull(), "views that leave one free slot of eight refuse the heap"); - for (auto& owner : owners) heap.ReleaseViewSlots(&owner); - BindlessHeap::SweepIfDue(); - require(!BindlessHeap::NearlyFull(), "releasing the views schedules the sweep that takes the heap again"); + for (auto& owner : owners) heap.ReleaseImageSlots(&owner); + require(!BindlessHeap::NearlyFull(), "releasing the views takes the heap again"); BindlessHeap::Release(context.device); } +void twoHeapsComeBack(const Context& context, VkImageView view) { + auto first = std::make_unique(context); + auto second = std::make_unique(context); + std::array firstOwners{}, secondOwners{}; + for (auto& owner : firstOwners) require(first->ViewSlot(Abi::FirstStorageImageBinding, &owner, view).has_value(), "a view takes one of the first heap's eight capped slots"); + for (auto& owner : secondOwners) require(second->ViewSlot(Abi::FirstStorageImageBinding, &owner, view).has_value(), "a view takes one of the second heap's eight capped slots"); + require(BindlessHeap::NearlyFull(), "two nearly full heaps refuse the heap"); + for (auto& owner : secondOwners) second->ReleaseImageSlots(&owner); + require(BindlessHeap::NearlyFull(), "room in the second heap took the heap back while the first stays nearly full"); + second.reset(); + require(BindlessHeap::NearlyFull(), "destroying the second heap took the heap back while the first stays nearly full"); + for (auto& owner : firstOwners) first->ReleaseImageSlots(&owner); + require(!BindlessHeap::NearlyFull(), "room in the last refused heap did not take the heap back"); + first.reset(); +} + int main(int argc, char** argv) { const std::string mode = argc > 1 ? argv[1] : ""; const bool comesBack = !mode.empty(); @@ -356,11 +314,12 @@ int main(int argc, char** argv) { else if (mode == "storage-views-come-back") storageViewsComeBack(context, storage); else if (mode == "mixed-comes-back") mixedComesBack(context, sampled, storage); else if (mode == "views-come-back") viewsComeBack(context, storage); + else if (mode == "two-heaps-come-back") twoHeapsComeBack(context, storage); else throw std::runtime_error("unknown mode " + mode); device->WaitIdle(); } device.reset(); - std::cout << "the refused heap comes back after a sweep (" << mode << ")\n"; + std::cout << "the refused heap comes back once released slots leave room (" << mode << ")\n"; return 0; } { @@ -371,7 +330,7 @@ int main(int argc, char** argv) { ringSpans(context); viewSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); encodedViews(context); - sweptOwnerReentry(context, placeholders.View(Abi::FirstStorageImageBinding)); + ownerSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); device->WaitIdle(); } device.reset(); diff --git a/core/libs/prx/libSceAgcDriver/tests/DepthSurfaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/DepthSurfaceReuse.cpp index 56e332b4c93f..47bf9f8ca45b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/DepthSurfaceReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/DepthSurfaceReuse.cpp @@ -440,21 +440,6 @@ void TestRetiredSurfaceRelease(const Context& context) { DepthSurfaceView(context, {sampled + 0x200000u, 0, extent, VK_FORMAT_D32_SFLOAT, 1.0f, 0}); Require(destroyed(sampledImage), "a retired depth surface must free its image once its sampled view is released"); - constexpr std::uint64_t heapHeld = 0x9a000000; - DepthSurfaceView(context, {heapHeld, 0, extent, VK_FORMAT_D32_SFLOAT, 1.0f, 0}); - const auto heapImage = lastImage; - auto slotView = lookup(context, {heapHeld, FormatR32Float, 256, 256}); - Require(slotView != nullptr, "an R32F view of a D32 surface's own extent must sample its depth plane"); - slotView->AddHeapHold(); - RetireDepthSurfaces(context.device, heapHeld, bytes); - const auto heapReleased = DepthSurfacesReleased(); - DepthSurfaceView(context, {heapHeld + 0x100000u, 0, extent, VK_FORMAT_D32_SFLOAT, 1.0f, 0}); - Require(DepthSurfacesReleased() > heapReleased, "a retired depth surface whose sampled view only GPU heap slots hold must be freed"); - Require(!destroyed(heapImage), "a GPU heap slot's sampled view must keep the freed surface's depth image"); - slotView->DropHeapHold(); - slotView.reset(); - Require(destroyed(heapImage), "dropping the heap slot's view must free the depth image"); - constexpr std::uint64_t kept = 0x9c000000; DepthSurfaceView(context, {kept, 0, extent, VK_FORMAT_D32_SFLOAT, 1.0f, 0}); const auto keptImage = lastImage; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp index fdac964374f7..a5e76fcb6989 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp @@ -596,11 +596,11 @@ bool heapViewTests(const Context& context) { for (std::size_t surface = 1; surface < Surfaces; ++surface) CachedStorageSurface(context, Resource(block.Surface(surface))); Require(!view->StorageSource()->Cached(), "the heap view's storage image was not evicted"); auto& heap = BindlessHeap::For(context); - Require(heap.TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, view, view->View(), view->Layout()).has_value(), "the view of an evicted storage image took no heap slot"); + const auto slot = heap.TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, view, view->View(), view->Layout()); + Require(slot.has_value(), "the view of an evicted storage image took no heap slot"); view.reset(); - Require(!viewed.expired(), "the heap slot did not hold the view of the evicted storage image"); - BindlessHeap::SweepIfDue(); - Require(viewed.expired(), "the present after the heap became the only holder of a view of an evicted storage image kept the view, and with it the image"); + Require(viewed.expired(), "a heap slot kept the view of an evicted storage image, and with it the image"); + Require(heap.SlotTexture(ShaderRecompiler::RuntimeAbi::FirstImageBinding, *slot) == nullptr, "a destroyed view kept its heap slot"); return true; } @@ -608,16 +608,22 @@ void heapHeldReleaseTests(const Context& context) { Block block(context); auto& heap = BindlessHeap::For(context); std::vector> held; + std::vector slots; for (std::size_t surface = 0; surface < 2; ++surface) { auto texture = Sampled(context, block.Surface(surface)); - Require(heap.TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, texture, texture->View(), texture->Layout()).has_value(), "the cached sampled texture took no heap slot"); + const auto slot = heap.TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, texture, texture->View(), texture->Layout()); + Require(slot.has_value(), "the cached sampled texture took no heap slot"); held.push_back(texture); + slots.push_back(*slot); } Require(TextureCacheUsage().sampledEntries == 2u, "the two sampled textures were not cached"); Require(!held[0].expired() && !held[1].expired(), "the cache and the heap slots did not keep the sampled textures"); const auto released = ReleaseTextureCaches(SurfaceBytes, true); Require(held[0].expired() != held[1].expired(), "a memory recovery for one texture's bytes did not free exactly one of two textures that only the cache and the GPU heap held"); Require(released >= SurfaceBytes && TextureCacheUsage().sampledEntries == 1u, "a memory recovery did not count the texture it freed from the cache and the GPU heap, or went past its target"); + const auto gone = held[0].expired() ? 0u : 1u; + Require(heap.SlotTexture(ShaderRecompiler::RuntimeAbi::FirstImageBinding, slots[gone]) == nullptr, "the texture a memory recovery freed kept its heap slot"); + Require(heap.SlotTexture(ShaderRecompiler::RuntimeAbi::FirstImageBinding, slots[1u - gone]) == held[1u - gone].lock().get(), "the texture a memory recovery kept lost its heap slot"); } ShaderRecompiler::RecompileResult SampledProgram(std::uint64_t address) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp index 87090fa580e1..47f154043556 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "prx/libc/include/GuestAllocations.hpp" @@ -11,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -74,14 +76,38 @@ void Record(AgcDriver::VulkanDevice& device, std::uint64_t address) { device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); } +bool heapSlots = false; + +struct HeapSlotted { + std::uint32_t slot = 0; + std::uint32_t generation = 0; +}; +std::map heapSlotsByAddress; + +std::shared_ptr heapSlotted(AgcDriver::VulkanDevice& device, std::uint64_t address, std::shared_ptr image) { + if (!heapSlots || image == nullptr) return image; + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + auto& heap = AgcDriver::Graphics::BindlessHeap::For(device.GraphicsContext()); + const auto slot = heap.StorageSlot(ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding, image, image->StorageView(0, false)); + Require(slot.has_value(), "the stored image took no GPU heap storage slot"); + heapSlotsByAddress.try_emplace(address, HeapSlotted{*slot, heap.SlotGeneration(*slot)}); + return image; +} + +bool heapSlotFreed(AgcDriver::VulkanDevice& device, std::uint64_t address) { + const auto found = heapSlotsByAddress.find(address); + Require(found != heapSlotsByAddress.end(), "no GPU heap slot was recorded for the surface"); + return AgcDriver::Graphics::BindlessHeap::For(device.GraphicsContext()).SlotGeneration(found->second.slot) != found->second.generation; +} + std::shared_ptr Store(AgcDriver::VulkanDevice& device, std::uint64_t base, std::uint32_t surface, bool flush = true) { const auto address = base + surface * Stride; Record(device, address); device.WaitIdle(); - if (!flush) return StorageTexture::FindLive(address, SurfaceBytes); + if (!flush) return heapSlotted(device, address, StorageTexture::FindLive(address, SurfaceBytes)); StorageTexture::FlushPending(address, static_cast(SurfaceBytes), nullptr, "test"); device.WaitIdle(); - return StorageTexture::FindLive(address, SurfaceBytes); + return heapSlotted(device, address, StorageTexture::FindLive(address, SurfaceBytes)); } int RetainedBatch() { @@ -94,6 +120,10 @@ int RetainedBatch() { #endif const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; + if (heapSlots && !device->GraphicsContext().descriptorHeap) { + std::puts("skipped, the device has no VK_EXT_descriptor_heap"); + return VulkanTestSkipped; + } std::vector storage((SurfaceBytes + MaxSurfaces * Stride + Stride) / 4u, 0u); auto* texels = reinterpret_cast((reinterpret_cast(storage.data()) + Stride - 1u) & ~std::uintptr_t{Stride - 1u}); const auto base = static_cast(reinterpret_cast(texels)); @@ -110,8 +140,9 @@ int RetainedBatch() { }; try { Record(*device, base); - auto retained = StorageTexture::FindLive(base, SurfaceBytes); + auto retained = heapSlotted(*device, base, StorageTexture::FindLive(base, SurfaceBytes)); Require(retained != nullptr, "surface 0 has no cached storage image"); + const std::weak_ptr weak = retained; const auto retainedBytes = retained->BudgetBytes(); auto* recorder = Recorder::Active(); Require(recorder != nullptr && recorder->Recording(), "the surface dispatch was not left in an open batch"); @@ -122,6 +153,11 @@ int RetainedBatch() { for (std::uint32_t surface = 1; surface <= capacity; ++surface) Record(*device, base + surface * Stride); Require(StorageTexture::FindLive(base, SurfaceBytes) == nullptr, "surface 0 remained cached after the storage budget was exceeded"); Require(recorder->OpenKeptBytes() >= beforeEviction + retainedBytes, "an evicted storage image held by a batch without a shared resource-cache entry was not charged to that batch"); + if (heapSlots) { + Require(!weak.expired() && !heapSlotFreed(*device, base), "an evicted storage image lost its GPU heap slot while its open batch still read it"); + device->WaitIdle(); + Require(weak.expired() && heapSlotFreed(*device, base), "an evicted storage image kept its GPU heap slot after the batch that held it finished"); + } } catch (...) { release(); throw; @@ -134,7 +170,14 @@ int RetainedBatch() { int main(int argc, char** argv) { try { - if (argc == 2 && std::string(argv[1]) == "--retained-batch") return RetainedBatch(); + const std::string mode = argc == 2 ? argv[1] : ""; + heapSlots = mode == "--heap-slots" || mode == "--retained-batch-heap-slots"; +#ifdef _WIN32 + if (heapSlots) Require(_putenv_s("APS5_GPU_HEAP", "1") == 0, "cannot enable the GPU heap"); +#else + if (heapSlots) Require(setenv("APS5_GPU_HEAP", "1", 1) == 0, "cannot enable the GPU heap"); +#endif + if (mode == "--retained-batch" || mode == "--retained-batch-heap-slots") return RetainedBatch(); #ifdef _WIN32 Require(_putenv_s("APS5_TEXTURE_CACHE_MIB", "32") == 0, "cannot set the test cache budget"); #else @@ -142,6 +185,10 @@ int main(int argc, char** argv) { #endif const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; + if (heapSlots && !device->GraphicsContext().descriptorHeap) { + std::puts("skipped, the device has no VK_EXT_descriptor_heap"); + return VulkanTestSkipped; + } const auto budget = TestBudget; std::vector storage((SurfaceBytes + MaxSurfaces * Stride + Stride) / 4u, 0u); auto* texels = reinterpret_cast((reinterpret_cast(storage.data()) + Stride - 1u) & ~std::uintptr_t{Stride - 1u}); @@ -179,6 +226,10 @@ int main(int argc, char** argv) { const auto capacity = static_cast(budget / held); Require(capacity + 2u <= MaxSurfaces, "the eviction set exceeds the test storage"); for (std::uint32_t surface = reused; surface < capacity + 2u; ++surface) images[surface] = Store(*device, base, surface); + for (std::uint32_t surface = 0; heapSlots && surface < capacity + 2u; ++surface) { + const bool evicted = surface < 2u; + Require(heapSlotFreed(*device, base + surface * Stride) == evicted, "surface " + std::to_string(surface) + (evicted ? " was evicted but kept its GPU heap slot" : " is cached but lost its GPU heap slot")); + } for (std::uint32_t surface = 0; surface < capacity + 2u; ++surface) { const bool cached = StorageTexture::FindLive(base + surface * Stride, SurfaceBytes) != nullptr; Require(cached == (surface >= 2u), "surface " + std::to_string(surface) + (cached ? " is still cached" : " was evicted") + " after " + std::to_string(capacity + 2u) + " surfaces under a budget of " + std::to_string(capacity) + " of them"); diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 6b8cbb0a010c..0c6dc3a828c1 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -143,7 +143,7 @@ flowchart LR - Queue 0's packet worker decodes, captures and prepares a draw and hands its recording (`Graphics::Draw` under the GPU lock) to a committer thread in [`DrawPipeline.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp), so the next packet is decoded while the previous draw is recorded. Each queued item carries the guest ranges it will write (`DrawWriteRanges`: written buffers and storage images, color targets with their DCC and CMASK, depth and stencil). A later packet that reads or writes one of those ranges, or that the pipeline can't order, drains it first; labels, submission ends, buffer fills and DMA packets are queued as items instead. With `APS5_PIPELINE_DISPATCH=1` (off by default), a `DISPATCH_DIRECT` whose dispatch-cache entry hits with a recipe is queued as an item too, carrying the dispatch's written buffers and storage images (`DispatchWriteRanges`); the capture and the cache lookup stay on the worker and the recipe is recorded on the committer. A dispatch still drains when its lookup misses, when what it reads overlaps a write still pending, when the hit is verified against data or when its writes cannot be ranged (bindless access, GDS, fault buffer). An indirect draw resolved on the CPU (its records read by the worker) drains only when its records or its count overlap a queued write; the records it draws inline drain first, and its last drawn record is queued like a direct draw (`APS5_NO_PIPELINED_INDIRECT=1` drains at every indirect draw). An exception thrown by a commit is rethrown on the worker at its next enqueue or drain, as an inline draw error would be. On by default; `APS5_PIPELINED_DRAWS=0` records every draw inline, and `APS5_EXACT_DRAW_WRITES=0` widens the color and depth ranges to estimates. - A dispatch's resource build runs stage A (binding plan, buffers, descriptor set) without the GPU lock and stage B (image lookups) under it. Between them `VulkanDevice::presync` waits, still without the lock, for recorded work that writes a surface stage B would read on the CPU and for recorded work that writes the DCC keys of an image the dispatch binds (`ShaderResources::PresyncSurfaces`), so the locked `WaitForKeyWriters` finds nothing pending to synchronize with. A key range is waited for only when recorded work writes it, the key-store memo does not give its value (`DccKeyWritersPending`, without the mutex) and the pending stores do not give it either (`DccKeyWriterNeedsSync`, under the mutex, the same test `WaitForKeyWriters` makes before it synchronizes). Stage A's own key scan runs before that wait, and stage B compares it with the keys it reads under the lock as before. `APS5_NO_DCC_PRESYNC=1` leaves the key ranges out; `APS5_NO_PRESYNC=1` disables the whole pre-sync. - `APS5_DRAW_PIPELINE` (any value turns it on, even `0`; off by default, meant with `APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1`) takes more of a draw off the worker. A `DrawFinisher` thread runs the second half of a direct pipelined draw (stage materialization, the draw cache insert and the hand-off to the committer) while the worker reads the next packets; the worker drains it before the next draw's cache lookup, before packets other than register writes and draws, and before guest reads, and finishes in place a draw whose stages may write memory (`ProgramWritesMemory`) or write through the BDA page table. The committer skips the fragment-output validation and storage-image layer scans whose inputs match its last commit (`CommitTrims`), and a resource or storage image proved current keeps its proof for the rest of the collect epoch until `GuestMemory::BreakProofs` (a CPU write, a write-back, a recorded write) moves `ProofSerial`. Color metadata passes go through the pipeline with their write ranges (`PipelinedColorMetadataPassWrites`) instead of draining it. A data-only hit whose shape entry belongs to an older draw replaces that entry in place at the second sight of the same read user words. On Linux the main image's pages get a page table entry, and capture pages are pooled across threads. `APS5_VERIFY_DRAW_PIPELINE=1` runs a full check next to 1 in 64 reused proofs and prints `[epoch-proofs]` counts. -- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 233472 image slots that every image binding kind shares, the first 57 holding each kind's absent descriptor, and 2048 sampler slots, per-draw shader data and flattened SRT in a ring the shaders reach by address) instead of per-draw descriptor sets. Without the extension, or when the device's heaps cannot hold those slots, every stage takes the per-draw path. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; a stage stays GPU-mode only if its compiled module maps onto the heap and every stage of its draw is GPU-mode too; otherwise it is rebuilt on the per-draw path. A draw whose stages come out mixed is rebuilt once with what the first pass learned, and a stage pair that is still mixed takes the per-draw path from then on. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the heap ring and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap is recompiled on the per-dispatch path. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the heap ring per draw with its address in two more pushed dwords. Tables with image atomics index the heap too. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers by device address (`addressedBuffers`: four shader data words per buffer, 64-bit address and byte size, after the slot words) instead of storage buffer descriptors; a draw whose buffers are snapshotted gets its own copy of the words with the snapshot addresses. +- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 233472 image slots that every image binding kind shares, the first 57 holding each kind's absent descriptor, and 2048 sampler slots, per-draw shader data and flattened SRT in a ring the shaders reach by address) instead of per-draw descriptor sets. Without the extension, or when the device's heaps cannot hold those slots, every stage takes the per-draw path. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; a stage stays GPU-mode only if its compiled module maps onto the heap and every stage of its draw is GPU-mode too; otherwise it is rebuilt on the per-draw path. A draw whose stages come out mixed is rebuilt once with what the first pass learned, and a stage pair that is still mixed takes the per-draw path from then on. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A heap slot holds no reference to its texture, storage image, view or sampler: the owner frees its slots when it is destroyed, and every batch that reads a slot keeps the owner alive through its draw's or dispatch's resources, so a slot is never reused while a batch can still read it. With fewer free image or sampler slots than the margin, stages take the per-draw path until released slots leave twice the margin free. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the heap ring and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap is recompiled on the per-dispatch path. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the heap ring per draw with its address in two more pushed dwords. Tables with image atomics index the heap too. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers by device address (`addressedBuffers`: four shader data words per buffer, 64-bit address and byte size, after the slot words) instead of storage buffer descriptors; a draw whose buffers are snapshotted gets its own copy of the words with the snapshot addresses. - The shader registry maps a code address to every header registered for that code, in registration order. Static, graphics and rectangle ABI resolution pick the header at the bound address (or one equal to it, `SameHeader`, which also takes a hull header fused by `sceAgcFuseShaderHalves` (type 3) as the registered back half (type 7) it copies, the fused registers aside; graphics ABI resolution then uses the fused header's shader registers); draws and dispatches pick the program by the stage's binary type (`RegisteredProgram`), and a front entry matching both type 2 and type 4 throws. Within a type the last registration wins; re-registering an identical earlier header makes its snapshot current again without preparing it again, and changed code drops the older headers. - The snapshot is published as pending. `SourceHandleFor`, `InvocationFor` and `ShaderPreparationTransaction::Edit` / `Read` wait for the pending job before reading `PreparedShaders`, and rethrow its failure. `APS5_SYNC_SHADER_PREPARE=1` prepares on the registering thread instead. - `APS5_LAZY_SHADER_PREPARE=1` retains registration validation and decoding but discards the temporary plan without queueing preparation. The snapshot is deferred, not pending; draws and dispatches prepare and cache it on first use. A compute or pixel stage's explicit ABI resolution (`ResolveShaderAbi`) plans the stage with the ABI's state, records the ABI and leaves its preparation to the shader's first use, which prepares it with that state (`PreparedShaders::deferredAbis`), so a shader that never draws or dispatches stays unprepared; a graphics-stage ABI is still prepared when it is resolved. This opt-in mode takes precedence over synchronous registration preparation and trades background CPU/memory use for possible first-use stalls; disk caches and shader output are unchanged. From 4243e9c4f10e18dc51936c46a9114f4765e4e808 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 31 Oct 2026 19:35:53 +0530 Subject: [PATCH 081/269] refactor(agc): tidy the GPU heap core Remove dead heap API and counters, name magic numbers, share the image slot path, and mix the slot key hash so a view used as its own owner no longer collides. --- .../Execution/src/Driver/Draw/HeapStages.cpp | 182 ++++++++------ .../Execution/src/VulkanDevice.cpp | 2 +- .../Graphics/include/BindlessHeap.hpp | 45 ++-- .../Graphics/include/ShaderResources.hpp | 1 - .../Graphics/src/BindlessHeap.cpp | 225 ++++++++---------- .../Graphics/src/ShaderResources.cpp | 125 +++------- .../tests/BindlessHeapSlots.cpp | 14 +- .../tests/execution/SampledCacheBudget.cpp | 4 +- .../tests/execution/StorageCacheBudget.cpp | 2 +- core/shader/recompiler/RuntimeAbi.hpp | 1 + .../src/SpirvMemory/SpirvDescriptors.cpp | 4 +- 11 files changed, 280 insertions(+), 325 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 409ce5598986..a306f3d9d220 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -25,6 +25,11 @@ namespace AgcDriver::DriverDetail { namespace { +constexpr std::size_t ThreadCacheLimit = 65536u; +constexpr std::uint64_t WalkPageBytes = 0x1000u; +constexpr std::uint64_t WordBytes = sizeof(std::uint32_t); +constexpr std::uint64_t DefaultWalkMemoMiB = 256u; + std::atomic& heapStages() { static std::atomic count{0}; return count; @@ -60,11 +65,6 @@ const char* resultDifference(const ShaderRecompiler::RecompileResult& left, cons return nullptr; } -bool sameResult(const ShaderRecompiler::RecompileResult& left, const ShaderRecompiler::RecompileResult& right) { - std::size_t index = 0; - return resultDifference(left, right, index) == nullptr; -} - void reportHeapMismatch(const char* check, const char* what, const ShaderRecompiler::RecompileResult& result, std::size_t index) { static std::atomic printed{0}; if (printed.fetch_add(1, std::memory_order_relaxed) >= 64u) return; @@ -173,7 +173,7 @@ bool HeapPairRefused(std::uint64_t pair) { void RefuseHeapPair(std::uint64_t pair) { auto& refused = refusedPairs(); - if (refused.size() >= 65536u) refused.clear(); + if (refused.size() >= ThreadCacheLimit) refused.clear(); refused.insert(pair); } @@ -186,30 +186,46 @@ struct HeapExclusions { bool sampled = false; }; +using ExcludableStage = std::pair; + +constexpr ExcludableStage ExcludableStages[] = { + {"compute", ShaderRecompiler::ShaderStage::Compute}, + {"vertex", ShaderRecompiler::ShaderStage::Vertex}, + {"hull", ShaderRecompiler::ShaderStage::TessellationControl}, + {"domain", ShaderRecompiler::ShaderStage::TessellationEvaluation}, + {"geometry", ShaderRecompiler::ShaderStage::Geometry}, + {"pixel", ShaderRecompiler::ShaderStage::Fragment}, + {"local", ShaderRecompiler::ShaderStage::Local}, + {"mesh", ShaderRecompiler::ShaderStage::Mesh}}; + +bool applyExclusion(HeapExclusions& exclusions, std::string_view item) { + if (item == "tables") { + exclusions.tables = true; + return true; + } + if (item == "storage") { + exclusions.storage = true; + return true; + } + if (item == "sampled") { + exclusions.sampled = true; + return true; + } + const auto stage = std::find_if(std::begin(ExcludableStages), std::end(ExcludableStages), [&](const auto& entry) { return entry.first == item; }); + if (stage == std::end(ExcludableStages)) return false; + exclusions.stages |= 1u << static_cast(stage->second); + return true; +} + const HeapExclusions& heapExclusions() { static const HeapExclusions exclusions = [] { - using Stage = ShaderRecompiler::ShaderStage; HeapExclusions result; const char* value = std::getenv("APS5_GPU_HEAP_EXCLUDE"); std::string_view list = value != nullptr ? value : ""; - static constexpr std::pair stages[] = {{"compute", Stage::Compute}, {"vertex", Stage::Vertex}, {"hull", Stage::TessellationControl}, {"domain", Stage::TessellationEvaluation}, - {"geometry", Stage::Geometry}, {"pixel", Stage::Fragment}, {"local", Stage::Local}, {"mesh", Stage::Mesh}}; while (!list.empty()) { const auto comma = list.find(','); const auto item = list.substr(0, comma); - bool known = true; - if (item == "tables") { - result.tables = true; - } else if (item == "storage") { - result.storage = true; - } else if (item == "sampled") { - result.sampled = true; - } else { - const auto stage = std::find_if(std::begin(stages), std::end(stages), [&](const auto& entry) { return entry.first == item; }); - known = stage != std::end(stages); - if (known) result.stages |= 1u << static_cast(stage->second); - } - if (!known) throw std::runtime_error("APS5_GPU_HEAP_EXCLUDE: unknown class '" + std::string(item) + "'; use compute, vertex, hull, domain, geometry, pixel, local, mesh, tables, storage or sampled"); + if (!applyExclusion(result, item)) throw std::runtime_error("APS5_GPU_HEAP_EXCLUDE: unknown class '" + std::string(item) + "'; use compute, vertex, hull, domain, geometry, pixel, local, mesh, tables, storage or sampled"); if (comma == std::string_view::npos) break; list.remove_prefix(comma + 1u); } @@ -245,7 +261,7 @@ bool HeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool wor auto& known = HostThreadLocal, MappableStorage>(); const auto key = result.variantId * 2u + (workgroupAddress ? 1u : 0u); if (const auto found = known.find(key); found != known.end()) return found->second; - if (known.size() >= 65536u) known.clear(); + if (known.size() >= ThreadCacheLimit) known.clear(); const bool mappable = heapClassesAllowed(result) && Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), workgroupAddress, result.dataAddressPush, result.functionLdsBuffer, result.meshWindowBuffer); known.emplace(key, mappable); @@ -321,7 +337,9 @@ std::uint64_t descriptorBindingBytes(const ShaderRecompiler::DescriptorBinding& vectorBytes(binding.bufferRead) + vectorBytes(binding.bufferExtent); } -std::uint64_t resultBytes(const ShaderRecompiler::RecompileResult& result) { +} + +std::uint64_t HeapWalkResultBytes(const ShaderRecompiler::RecompileResult& result) { auto bytes = sizeof(ShaderRecompiler::RecompileResult) + vectorBytes(result.vertexInputPatches) + vectorBytes(result.runtimeImageResources) + vectorBytes(result.vertexInputs) + vectorBytes(result.parameterExports) + vectorBytes(result.fragmentParameters) + vectorBytes(result.stencilReferences) + vectorBytes(result.specialization) + vectorBytes(result.heapSlotWords) + @@ -334,7 +352,7 @@ std::uint64_t resultBytes(const ShaderRecompiler::RecompileResult& result) { return bytes; } -std::uint64_t captureBytes(const ShaderRecompiler::ResourceCapture& capture) { +std::uint64_t HeapWalkCaptureBytes(const ShaderRecompiler::ResourceCapture& capture) { const auto& snapshot = capture.snapshot; auto bytes = sizeof(ShaderRecompiler::ResourceCapture) + vectorBytes(snapshot.buffers) + vectorBytes(snapshot.images) + vectorBytes(snapshot.samplers) + vectorBytes(snapshot.flattenedSrt) + vectorBytes(snapshot.userData) + @@ -345,44 +363,30 @@ std::uint64_t captureBytes(const ShaderRecompiler::ResourceCapture& capture) { return bytes; } -std::uint64_t wordsBytes(const ShaderRecompiler::HeapStageWords& words) { +std::uint64_t HeapWalkWordsBytes(const ShaderRecompiler::HeapStageWords& words) { auto bytes = sizeof(ShaderRecompiler::HeapStageWords) + vectorBytes(words.userData) + vectorBytes(words.flattenedSrt) + vectorBytes(words.vertexAttributes) + vectorBytes(words.bindings); for (const auto& binding : words.bindings) bytes += vectorBytes(binding); return bytes; } -} - std::uint64_t HeapWalkEntryOwnBytes(const HeapWalkEntry& entry) { return sizeof(HeapWalkEntry) + vectorBytes(entry.userData) + vectorBytes(entry.ranges) + vectorBytes(entry.values) + vectorBytes(entry.accessible) + vectorBytes(entry.userDataUse.reads); } -std::uint64_t HeapWalkCaptureBytes(const ShaderRecompiler::ResourceCapture& capture) { - return captureBytes(capture); -} - -std::uint64_t HeapWalkResultBytes(const ShaderRecompiler::RecompileResult& result) { - return resultBytes(result); -} - -std::uint64_t HeapWalkWordsBytes(const ShaderRecompiler::HeapStageWords& words) { - return wordsBytes(words); -} - std::uint64_t HeapWalkEntryBytes(const HeapWalkEntry& entry) { auto bytes = HeapWalkEntryOwnBytes(entry); - if (entry.capture != nullptr) bytes += captureBytes(*entry.capture); - if (entry.result != nullptr) bytes += resultBytes(*entry.result); - if (entry.words != nullptr) bytes += wordsBytes(*entry.words); + if (entry.capture != nullptr) bytes += HeapWalkCaptureBytes(*entry.capture); + if (entry.result != nullptr) bytes += HeapWalkResultBytes(*entry.result); + if (entry.words != nullptr) bytes += HeapWalkWordsBytes(*entry.words); return bytes; } std::uint64_t HeapWalkMemoBudget() { static const std::uint64_t budget = [] { const char* value = std::getenv("APS5_HEAP_WALK_MEMO_MB"); - const std::uint64_t megabytes = value == nullptr || *value == '\0' ? 256u : std::strtoull(value, nullptr, 10); + const std::uint64_t megabytes = value == nullptr || *value == '\0' ? DefaultWalkMemoMiB : std::strtoull(value, nullptr, 10); return megabytes << 20u; }(); return budget; @@ -438,10 +442,10 @@ struct WalkReads { bool readWalkWord(void* context, std::uint64_t address, std::uint32_t* value) { auto& reads = *static_cast(context); - const auto page = address & ~std::uint64_t{0xfff}; - const bool crossesPage = (address & 0xfffu) > 0x1000u - sizeof(*value); + const auto page = address & ~(WalkPageBytes - 1u); + const bool crossesPage = (address & (WalkPageBytes - 1u)) > WalkPageBytes - sizeof(*value); if (page != reads.page || crossesPage) { - if (GuestMemory::Accessible(reinterpret_cast(page), 0x1000u)) reads.page = page; + if (GuestMemory::Accessible(reinterpret_cast(page), WalkPageBytes)) reads.page = page; else if (!GuestMemory::Accessible(reinterpret_cast(address), sizeof(*value))) { reads.failed = true; return false; @@ -465,10 +469,10 @@ void coalesceWords(std::vector& words, AddressRanges& ranges) { ranges.clear(); for (const auto address : words) { if (!ranges.empty() && address <= ranges.back().second) { - ranges.back().second = std::max(ranges.back().second, address + 4u); + ranges.back().second = std::max(ranges.back().second, address + WordBytes); continue; } - ranges.emplace_back(address, address + 4u); + ranges.emplace_back(address, address + WordBytes); } } @@ -476,7 +480,7 @@ void copyRangeValues(const AddressRanges& ranges, std::vector& va values.clear(); for (const auto& [begin, end] : ranges) { const auto offset = values.size(); - values.resize(offset + static_cast((end - begin) / 4u)); + values.resize(offset + static_cast((end - begin) / WordBytes)); std::memcpy(values.data() + offset, reinterpret_cast(begin), static_cast(end - begin)); } } @@ -508,7 +512,7 @@ bool sameWalkInputs(const HeapWalkEntry& entry, const ShaderRecompiler::Prepared if (!sameStage || !std::equal(entry.userData.begin(), entry.userData.end(), userData.begin(), userData.end())) return false; std::size_t cursor = 0; for (const auto& [begin, end] : entry.ranges) { - const auto count = static_cast((end - begin) / 4u); + const auto count = static_cast((end - begin) / WordBytes); if (GuestMemory::CompareMapped(begin, std::as_bytes(std::span(entry.values.data() + cursor, count))) != GuestMemory::Compare::Equal) return false; cursor += count; @@ -519,6 +523,10 @@ bool sameWalkInputs(const HeapWalkEntry& entry, const ShaderRecompiler::Prepared return true; } +void noteMemoBytes(const HeapWalkMemo& memo, std::uint64_t heldBefore) { + Graphics::NoteHeapWalkMemoBytes(static_cast(memo.heldBytes) - static_cast(heldBefore)); +} + void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase, const AddressRanges& ranges, const std::vector& values, const AddressRanges& accessible, @@ -539,7 +547,47 @@ void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderI auto& memo = heapWalkMemo(); const auto heldBefore = memo.heldBytes; memo.remember(memoKey, std::move(entry)); - Graphics::NoteHeapWalkMemoBytes(static_cast(memo.heldBytes) - static_cast(heldBefore)); + noteMemoBytes(memo, heldBefore); +} + +std::shared_ptr +adoptWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, + std::uint64_t shaderBase, const Graphics::Recorder::WriteRanges* before, std::uint64_t generation, + ShaderRecompiler::HeapStageWords* words, std::shared_ptr* sharedWords, + HeapStageReads* stageReads, bool& memoKnown) { + auto& memo = heapWalkMemo(); + const auto heldBefore = memo.heldBytes; + auto* found = memo.find(memoKey); + noteMemoBytes(memo, heldBefore); + memoKnown = found != nullptr; + for (std::size_t way = 0; found != nullptr && way < found->size(); ++way) { + auto& entry = (*found)[way]; + if (!sameWalkInputs(entry, invocation, userData, shaderBase)) continue; + if (!rangesSettled(entry.ranges, before, generation)) break; + memo.touch(entry); + guardRanges(entry.ranges); + if (sharedWords != nullptr) *sharedWords = entry.words; + else *words = *entry.words; + if (stageReads != nullptr) *stageReads = {entry.ranges, entry.values, entry.userDataUse, entry.capture, true}; + auto result = entry.result; + if (way != 0) + std::rotate(found->begin(), found->begin() + static_cast(way), + found->begin() + static_cast(way) + 1); + return result; + } + return nullptr; +} + +std::shared_ptr +captureWalk(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase, + WalkReads& reads) { + ShaderRecompiler::SrtRuntime runtime; + runtime.userData = userData; + runtime.shaderBase = shaderBase; + runtime.userContext = &reads; + runtime.readMemory = readWalkWord; + runtime.accessible = walkAccessible; + return invocation.Capture(runtime); } } @@ -565,37 +613,13 @@ MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocatio Graphics::HeapCostScope memoCost(Graphics::HeapCost::WalkMemo); if (memoOn) { memoKey = walkMemoKey(invocation, userData, shaderBase); - auto& memo = heapWalkMemo(); - const auto heldBefore = memo.heldBytes; - auto* found = memo.find(memoKey); - Graphics::NoteHeapWalkMemoBytes(static_cast(memo.heldBytes) - static_cast(heldBefore)); - memoKnown = found != nullptr; - for (std::size_t way = 0; found != nullptr && way < found->size(); ++way) { - auto& entry = (*found)[way]; - if (!sameWalkInputs(entry, invocation, userData, shaderBase)) continue; - if (!rangesSettled(entry.ranges, before.get(), generation)) break; - memo.touch(entry); - guardRanges(entry.ranges); - if (sharedWords != nullptr) *sharedWords = entry.words; - else *words = *entry.words; - if (stageReads != nullptr) *stageReads = {entry.ranges, entry.values, entry.userDataUse, entry.capture, true}; - auto result = entry.result; - if (way != 0) - std::rotate(found->begin(), found->begin() + static_cast(way), - found->begin() + static_cast(way) + 1); - return result; - } + if (auto adopted = adoptWalk(memoKey, invocation, userData, shaderBase, before.get(), generation, words, sharedWords, stageReads, memoKnown)) + return adopted; } memoCost.Stop(); Graphics::HeapCostScope walkCost(Graphics::HeapCost::Walk); - ShaderRecompiler::SrtRuntime runtime; - runtime.userData = userData; - runtime.shaderBase = shaderBase; - runtime.userContext = &reads; - runtime.readMemory = readWalkWord; - runtime.accessible = walkAccessible; - auto capture = invocation.Capture(runtime); + auto capture = captureWalk(invocation, userData, shaderBase, reads); coalesceWords(reads.words, ranges); auto& values = HostThreadLocal, ValuesStorage>(); if ((memoOn || stageReads != nullptr) && !reads.failed) copyRangeValues(ranges, values); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 06176919bae6..41014c144d2a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -4166,7 +4166,7 @@ bool VulkanDevice::PresentsOnOwnQueue() const { ShaderRecompiler::SpirvTarget VulkanDevice::ComputeTarget(std::uint32_t waveSize) const { auto target = Target(); if (waveSize == 32u && state->computeWave32) target.subgroupSize = 32u; - target.gpuResolvedImages = Graphics::HeapComputeEnabled(); + target.gpuResolvedImages = Graphics::DescriptorHeapEnabled(); return target; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index a7aeaaa93bdf..47caf2ee21d1 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -37,7 +37,6 @@ class BindlessHeap { bool DescriptorHeapMode() const { return resourceHeap != nullptr; } VkDeviceSize ImageHeapStride() const { return imageHeapStride; } - VkDeviceSize SamplerHeapStride() const { return samplerHeapStride; } void BindDescriptorHeaps(VkCommandBuffer commands) const; bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset = ~0u, bool rootGds = false, bool rootFault = false, @@ -48,10 +47,8 @@ class BindlessHeap { VkBuffer RingBuffer() const; VkDeviceSize RingOffset() const; - std::optional TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, - VkImageLayout layout); + std::optional TextureSlot(std::uint32_t kind, Texture* texture, VkImageView view, VkImageLayout layout); std::optional StorageSlot(std::uint32_t kind, const void* owner, VkImageView view); - std::optional StorageSlot(std::uint32_t kind, const std::shared_ptr& image, VkImageView view); std::optional ViewSlot(std::uint32_t kind, const void* owner, VkImageView view); void ReleaseImageSlots(const void* owner); void ReleaseSamplerSlot(const Sampler* sampler); @@ -84,8 +81,8 @@ class BindlessHeap { void Submitted(Recorder& recorder, std::uint64_t serial); struct Counts { - std::uint64_t textures = 0, samplers = 0, full = 0, ringWraps = 0, encodes = 0, encodedCopies = 0; - std::uint64_t slotsFreed = 0, slotsReused = 0, chunkWaits = 0; + std::uint64_t ringWraps = 0, encodes = 0, encodedCopies = 0; + std::uint64_t slotsFreed = 0, slotsReused = 0; std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0; }; Counts Statistics() const; @@ -122,44 +119,49 @@ class BindlessHeap { }; std::vector ringChunks; std::size_t ringChunk = ~std::size_t{0}; - void enterChunk(std::vector& chunks, std::size_t index, std::size_t& current, const char* what); + void enterRingChunk(std::size_t index); + std::size_t wrapRingOffset(std::size_t offset, std::size_t bytes); std::size_t ringCursor = 0; std::uint32_t ringAlignment = 256; mutable std::mutex mutex; std::atomic slotSerial{1}; - struct TextureKey { + struct ImageSlotKey { std::uint32_t kind; - const void* texture; + const void* owner; VkImageView view; VkImageLayout layout; - bool operator==(const TextureKey&) const = default; + bool operator==(const ImageSlotKey&) const = default; }; - struct TextureKeyHash { - std::size_t operator()(const TextureKey& key) const { - const auto texture = std::hash{}(key.texture); - const auto view = std::hash{}(reinterpret_cast(key.view)); - return texture ^ view ^ (static_cast(key.kind) << 48u) ^ (static_cast(key.layout) << 40u); + struct ImageSlotKeyHash { + std::size_t operator()(const ImageSlotKey& key) const { + constexpr std::size_t HashSalt = 0x9e3779b97f4a7c15ull; + std::size_t seed = 0; + const auto mix = [&seed](std::size_t value) { seed ^= value + HashSalt + (seed << 6u) + (seed >> 2u); }; + mix(key.kind); + mix(static_cast(key.layout)); + mix(std::hash{}(key.owner)); + mix(std::hash{}(reinterpret_cast(key.view))); + return seed; } }; - std::unordered_map textureSlots; + std::unordered_map imageSlots; std::unordered_map> ownerSlots; - std::uint32_t nextTextureSlot = 0; + std::uint32_t nextImageSlot = 0; struct SlotOwner { const Texture* texture = nullptr; - TextureKey key{}; + ImageSlotKey key{}; std::uint32_t generation = 0; }; std::vector owners; std::vector freeSlots; std::uint32_t slotCap = 0; - std::optional ownedSlot(std::uint32_t kind, const void* owner, VkImageView view); + std::optional imageSlot(std::uint32_t kind, const void* owner, VkImageView view, VkImageLayout layout, Texture* texture); std::optional takeSlotLocked(); - SlotOwner& claimSlotLocked(const TextureKey& key, std::uint32_t slot); + SlotOwner& claimSlotLocked(const ImageSlotKey& key, std::uint32_t slot); void freeSlotLocked(std::uint32_t slot); const SlotOwner* ownerLocked(std::uint32_t slot) const; std::unordered_map samplerSlots; std::unordered_set absentSlots; - std::vector heldSamplers; std::vector samplerGenerations; std::vector freeSamplerSlots; bool refused = false; @@ -176,7 +178,6 @@ class BindlessHeap { bool GpuHeapEnabled(); void SetDescriptorHeapDevice(bool available); bool DescriptorHeapEnabled(); -bool HeapComputeEnabled(); bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds = false, bool meshWindow = false); void NoteHeapComputeStage(); std::uint64_t HeapComputeStages(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index a74b49452de6..97831656f24c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -658,7 +658,6 @@ class ShaderResources { VkImageView heapStorageView(std::size_t index, std::uint32_t binding) const; VkImageView heapMultisampleStorageView(std::size_t index) const; void appendHeapSlotKey(VkShaderStageFlags stageBit, std::vector& key) const; - static bool heapSlotsCurrent(const BindlessHeap& heap, const HeapStageState& state); void takeHeapSlots(BindlessHeap& heap, HeapStageState& state, VkShaderStageFlags stageBit, std::span key); static void noteHeapSlotGenerations(const BindlessHeap& heap, HeapStageState& state); void verifyHeapSlots(const BindlessHeap& heap, const HeapStageState& state, VkShaderStageFlags stageBit) const; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index e15b19f05d29..12ed91165d3d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -11,17 +11,18 @@ #include #include #include +#include #include #include #include #include -#include #include #include #include #include #include #include +#include namespace AgcDriver::Graphics { @@ -50,9 +51,27 @@ namespace { namespace Abi = ShaderRecompiler::RuntimeAbi; -void check(VkResult result, const char* what) { - if (result != VK_SUCCESS) - throw std::runtime_error(std::string("AGC bindless heap: ") + what + " failed: " + std::to_string(static_cast(result))); +constexpr std::size_t RingSpanAlignment = 16u; + +bool pipelineStats() { + static const bool enabled = std::getenv("APS5_PIPELINE_STATS") != nullptr; + return enabled; +} + +bool isSampledKind(std::uint32_t kind) { + return kind >= Abi::FirstImageBinding && kind < Abi::FirstStorageImageBinding; +} + +bool isImageKind(std::uint32_t kind) { + return kind >= Abi::FirstImageBinding && kind < BindlessHeap::SamplerKind; +} + +std::size_t chunkOf(std::size_t offset) { + return offset / BindlessHeap::RingChunkBytes; +} + +std::size_t lastChunkOf(std::size_t offset, std::size_t bytes) { + return chunkOf(offset + std::max(bytes, 1u) - 1u); } std::atomic spansWrittenWindow{0}; @@ -113,10 +132,6 @@ bool DescriptorHeapEnabled() { return GpuHeapEnabled() && descriptorHeapDevice.load(std::memory_order_relaxed); } -bool HeapComputeEnabled() { - return DescriptorHeapEnabled(); -} - namespace { struct HeapSizes { @@ -231,14 +246,14 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { ringHeapOffset = heapRing.offset; ringBytes = heapRing.bytes; ringData = resourceHeap->Bytes().data() + ringHeapOffset; - ringAlignment = static_cast(std::max({context.limits.minStorageBufferOffsetAlignment, context.limits.minUniformBufferOffsetAlignment, 16})); + ringAlignment = static_cast(std::max({context.limits.minStorageBufferOffsetAlignment, context.limits.minUniformBufferOffsetAlignment, RingSpanAlignment})); } else { ring = makeBuffer(RingBytes, ringUsage, true); ringData = ring->Bytes().data(); - ringAlignment = static_cast(std::max(context.limits.minStorageBufferOffsetAlignment, 16)); + ringAlignment = static_cast(std::max(context.limits.minStorageBufferOffsetAlignment, RingSpanAlignment)); } ringChunks.resize(ringBytes / RingChunkBytes); - nextTextureSlot = SamplerKind; + nextImageSlot = SamplerKind; slotCap = configuredSlotCap(); } @@ -309,47 +324,30 @@ BindlessHeap* BindlessHeap::Existing(const Context& context) { return found == heaps().end() ? nullptr : found->second.get(); } -std::optional BindlessHeap::TextureSlot(std::uint32_t kind, const std::shared_ptr& texture, VkImageView view, - VkImageLayout layout) { - const bool sampledKind = kind >= Abi::FirstImageBinding && kind < Abi::FirstStorageImageBinding; - if (!sampledKind || texture == nullptr || view == VK_NULL_HANDLE) - throw std::runtime_error("AGC bindless heap: invalid texture slot request"); - std::lock_guard lock(mutex); - const TextureKey key{kind, texture.get(), view, layout}; - if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; - const auto slot = takeSlotLocked(); - if (!slot) return std::nullopt; - writeImageSlot(kind, *slot, view, layout); - claimSlotLocked(key, *slot).texture = texture.get(); - texture->MarkHeapSlotted(); - noteTakenLocked(); - return slot; -} - -std::optional BindlessHeap::StorageSlot(std::uint32_t kind, const std::shared_ptr& image, VkImageView view) { - return StorageSlot(kind, static_cast(image.get()), view); +std::optional BindlessHeap::TextureSlot(std::uint32_t kind, Texture* texture, VkImageView view, VkImageLayout layout) { + Require(isSampledKind(kind) && texture != nullptr && view != VK_NULL_HANDLE, "bindless heap: invalid texture slot request"); + return imageSlot(kind, texture, view, layout, texture); } std::optional BindlessHeap::StorageSlot(std::uint32_t kind, const void* owner, VkImageView view) { - if (!Abi::GpuHeapStorageKind(kind) || owner == nullptr || view == VK_NULL_HANDLE) - throw std::runtime_error("AGC bindless heap: invalid storage slot request"); - return ownedSlot(kind, owner, view); + Require(Abi::GpuHeapStorageKind(kind) && owner != nullptr && view != VK_NULL_HANDLE, "bindless heap: invalid storage slot request"); + return imageSlot(kind, owner, view, VK_IMAGE_LAYOUT_GENERAL, nullptr); } std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const void* owner, VkImageView view) { - const bool imageKind = kind >= Abi::FirstImageBinding && kind < SamplerKind; - if (!imageKind || owner == nullptr || view == VK_NULL_HANDLE) throw std::runtime_error("AGC bindless heap: invalid view slot request"); - return ownedSlot(kind, owner, view); + Require(isImageKind(kind) && owner != nullptr && view != VK_NULL_HANDLE, "bindless heap: invalid view slot request"); + return imageSlot(kind, owner, view, VK_IMAGE_LAYOUT_GENERAL, nullptr); } -std::optional BindlessHeap::ownedSlot(std::uint32_t kind, const void* owner, VkImageView view) { +std::optional BindlessHeap::imageSlot(std::uint32_t kind, const void* owner, VkImageView view, VkImageLayout layout, Texture* texture) { std::lock_guard lock(mutex); - const TextureKey key{kind, owner, view, VK_IMAGE_LAYOUT_GENERAL}; - if (const auto found = textureSlots.find(key); found != textureSlots.end()) return found->second; + const ImageSlotKey key{kind, owner, view, layout}; + if (const auto found = imageSlots.find(key); found != imageSlots.end()) return found->second; const auto slot = takeSlotLocked(); if (!slot) return std::nullopt; - writeImageSlot(kind, *slot, view, VK_IMAGE_LAYOUT_GENERAL); - claimSlotLocked(key, *slot); + writeImageSlot(kind, *slot, view, layout); + claimSlotLocked(key, *slot).texture = texture; + if (texture != nullptr) texture->MarkHeapSlotted(); noteTakenLocked(); return slot; } @@ -371,7 +369,6 @@ void BindlessHeap::ReleaseSamplerSlot(const Sampler* sampler) { if (found == samplerSlots.end()) return; const auto slot = found->second; samplerSlots.erase(found); - heldSamplers[slot] = nullptr; ++samplerGenerations[slot]; slotSerial.fetch_add(1, std::memory_order_release); freeSamplerSlots.push_back(slot); @@ -379,18 +376,17 @@ void BindlessHeap::ReleaseSamplerSlot(const Sampler* sampler) { noteReleasedLocked(); } -BindlessHeap::SlotOwner& BindlessHeap::claimSlotLocked(const TextureKey& key, std::uint32_t slot) { - textureSlots.emplace(key, slot); - ownerSlots[key.texture].push_back(slot); +BindlessHeap::SlotOwner& BindlessHeap::claimSlotLocked(const ImageSlotKey& key, std::uint32_t slot) { + imageSlots.emplace(key, slot); + ownerSlots[key.owner].push_back(slot); if (owners.size() <= slot) owners.resize(slot + 1u); owners[slot].key = key; - ++counts.textures; return owners[slot]; } void BindlessHeap::freeSlotLocked(std::uint32_t slot) { auto& owner = owners[slot]; - textureSlots.erase(owner.key); + imageSlots.erase(owner.key); owner.texture = nullptr; owner.key = {}; ++owner.generation; @@ -409,11 +405,8 @@ std::optional BindlessHeap::takeSlotLocked() { ++counts.slotsReused; return slot; } - if (nextTextureSlot >= slotCap) { - ++counts.full; - return std::nullopt; - } - return nextTextureSlot++; + if (nextImageSlot >= slotCap) return std::nullopt; + return nextImageSlot++; } bool BindlessHeap::NearlyFull() { @@ -429,12 +422,12 @@ std::uint32_t BindlessHeap::imageMargin() const { } std::size_t BindlessHeap::unusedLocked() const { - return (nextTextureSlot < slotCap ? slotCap - nextTextureSlot : 0u) + freeSlots.size(); + return (nextImageSlot < slotCap ? slotCap - nextImageSlot : 0u) + freeSlots.size(); } bool BindlessHeap::roomLocked() const { if (unusedLocked() < 2u * static_cast(imageMargin())) return false; - return Abi::GpuSamplerHeapSlots - heldSamplers.size() + freeSamplerSlots.size() >= 2u * SamplerSlotMargin; + return Abi::GpuSamplerHeapSlots - samplerGenerations.size() + freeSamplerSlots.size() >= 2u * SamplerSlotMargin; } void BindlessHeap::noteRefusedLocked(const char* what, std::uint32_t margin) { @@ -450,7 +443,7 @@ void BindlessHeap::noteTakenLocked() { } void BindlessHeap::noteSamplerTakenLocked() { - if (!refused && Abi::GpuSamplerHeapSlots - heldSamplers.size() + freeSamplerSlots.size() < SamplerSlotMargin) noteRefusedLocked("sampler", SamplerSlotMargin); + if (!refused && Abi::GpuSamplerHeapSlots - samplerGenerations.size() + freeSamplerSlots.size() < SamplerSlotMargin) noteRefusedLocked("sampler", SamplerSlotMargin); } void BindlessHeap::noteReleasedLocked() { @@ -501,11 +494,11 @@ const Texture* BindlessHeap::SlotTexture(std::uint32_t kind, std::uint32_t slot) bool BindlessHeap::SlotHoldsStorage(std::uint32_t kind, std::uint32_t slot, const void* owner, VkImageView view) const { std::lock_guard lock(mutex); const auto* held = ownerLocked(slot); - return held != nullptr && held->key == TextureKey{kind, owner, view, VK_IMAGE_LAYOUT_GENERAL}; + return held != nullptr && held->key == ImageSlotKey{kind, owner, view, VK_IMAGE_LAYOUT_GENERAL}; } std::uint32_t BindlessHeap::AbsentSlot(std::uint32_t kind, VkImageView view) { - if (kind < Abi::FirstImageBinding || kind >= SamplerKind) throw std::runtime_error("AGC bindless heap: invalid absent slot request"); + Require(isImageKind(kind), "bindless heap: invalid absent slot request"); std::lock_guard lock(mutex); if (absentSlots.contains(kind)) return kind; writeImageSlot(kind, kind, view, VK_IMAGE_LAYOUT_GENERAL); @@ -514,7 +507,7 @@ std::uint32_t BindlessHeap::AbsentSlot(std::uint32_t kind, VkImageView view) { } std::optional BindlessHeap::SamplerSlot(const std::shared_ptr& sampler) { - if (sampler == nullptr) throw std::runtime_error("AGC bindless heap: invalid sampler slot request"); + Require(sampler != nullptr, "bindless heap: invalid sampler slot request"); std::lock_guard lock(mutex); if (const auto found = samplerSlots.find(sampler.get()); found != samplerSlots.end()) return found->second; std::uint32_t slot = 0; @@ -522,19 +515,15 @@ std::optional BindlessHeap::SamplerSlot(const std::shared_ptr(heldSamplers.size()); - heldSamplers.emplace_back(); + } else if (samplerGenerations.size() < Abi::GpuSamplerHeapSlots) { + slot = static_cast(samplerGenerations.size()); samplerGenerations.push_back(0u); } else { - ++counts.full; return std::nullopt; } writeSamplerSlot(slot, sampler->Handle()); samplerSlots.emplace(sampler.get(), slot); - heldSamplers[slot] = sampler.get(); sampler->MarkHeapSlotted(); - ++counts.samplers; noteSamplerTakenLocked(); return slot; } @@ -546,9 +535,8 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words) { bool BindlessHeap::Held(const SpanMark& mark) { if (mark.entry == 0u || mark.words == 0u) return false; - const auto first = mark.offset / RingChunkBytes; - const auto last = (mark.offset + static_cast(mark.words) * sizeof(std::uint32_t) - 1u) / RingChunkBytes; - if (first != last) return false; + const auto first = chunkOf(mark.offset); + if (first != lastChunkOf(mark.offset, static_cast(mark.words) * sizeof(std::uint32_t))) return false; std::lock_guard lock(mutex); auto& chunk = ringChunks[first]; if (chunk.entries != mark.entry) { @@ -563,49 +551,44 @@ bool BindlessHeap::Held(const SpanMark& mark) { } BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) { - const auto bytes = ringInHeap ? (words * sizeof(std::uint32_t) + 15u) / 16u * 16u : words * sizeof(std::uint32_t); + const auto bytes = ringInHeap ? alignUp(words * sizeof(std::uint32_t), RingSpanAlignment) : words * sizeof(std::uint32_t); if (bytes > RingChunkBytes) throw std::runtime_error("AGC bindless heap: per-draw data exceeds a ring chunk"); std::lock_guard lock(mutex); - auto offset = (ringCursor + ringAlignment - 1) / ringAlignment * ringAlignment; - if (offset + bytes > ringBytes) { - offset = 0; - ++counts.ringWraps; - } - const auto lastChunk = [&] { return (offset + std::max(bytes, 1u) - 1u) / RingChunkBytes; }; + auto offset = wrapRingOffset(alignUp(ringCursor, ringAlignment), bytes); const auto keptAhead = [&] { - for (auto chunk = offset / RingChunkBytes; chunk <= lastChunk(); ++chunk) { + for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) { if (chunk != ringChunk && ringChunks[chunk].open) return true; } return false; }; for (std::size_t skipped = 0; keptAhead(); ++skipped) { if (skipped == ringChunks.size()) throw std::runtime_error("AGC bindless heap: one batch's shader data exceeds its ring"); - offset = (offset / RingChunkBytes + 1u) * RingChunkBytes; - if (offset + bytes > ringBytes) { - offset = 0; - ++counts.ringWraps; - } + offset = wrapRingOffset((chunkOf(offset) + 1u) * RingChunkBytes, bytes); ++counts.keptChunksSkipped; } ringCursor = offset + bytes; - for (auto chunk = offset / RingChunkBytes; chunk <= lastChunk(); ++chunk) enterChunk(ringChunks, chunk, ringChunk, "shader data"); + for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) enterRingChunk(chunk); auto* base = reinterpret_cast(ringData + offset); ++counts.spansWritten; spansWrittenWindow.fetch_add(1, std::memory_order_relaxed); - mark = {static_cast(offset), static_cast(words), ringChunks[offset / RingChunkBytes].entries}; + mark = {static_cast(offset), static_cast(words), ringChunks[chunkOf(offset)].entries}; return {static_cast(offset), std::span(base, words)}; } -void BindlessHeap::enterChunk(std::vector& chunks, std::size_t index, std::size_t& current, const char* what) { - if (index == current) return; - current = index; - auto& chunk = chunks[index]; - if (chunk.open) throw std::runtime_error(std::string("AGC bindless heap: one batch's ") + what + " exceeds its ring"); +std::size_t BindlessHeap::wrapRingOffset(std::size_t offset, std::size_t bytes) { + if (offset + bytes <= ringBytes) return offset; + ++counts.ringWraps; + return 0; +} + +void BindlessHeap::enterRingChunk(std::size_t index) { + if (index == ringChunk) return; + ringChunk = index; + auto& chunk = ringChunks[index]; + if (chunk.open) throw std::runtime_error("AGC bindless heap: one batch's shader data exceeds its ring"); if (chunk.serial != 0u) { - ++counts.chunkWaits; if (!chunk.recorder->HasTimeline()) - throw std::runtime_error(std::string("AGC bindless heap: the ") + what + - " ring needs the recorder timeline to wait for a batch"); + throw std::runtime_error("AGC bindless heap: the shader data ring needs the recorder timeline to wait for a batch"); chunk.recorder->WaitSerial(chunk.serial); chunk.serial = 0u; } @@ -620,7 +603,7 @@ void BindlessHeap::writeSamplerSlot(std::uint32_t slot, VkSampler sampler) { Require(offset + samplerHeapStride <= samplerHeapUsed, "a GPU heap sampler slot lies outside the sampler heap"); const VkHostAddressRangeEXT target{samplerHeap->Bytes().data() + offset, static_cast(samplerHeapStride)}; if (writeSamplerDescriptors == nullptr) writeSamplerDescriptors = context.Function("vkWriteSamplerDescriptorsEXT"); - check(writeSamplerDescriptors(context.device, 1, record->Chain(), &target), "vkWriteSamplerDescriptorsEXT"); + Check(writeSamplerDescriptors(context.device, 1, record->Chain(), &target), "vkWriteSamplerDescriptorsEXT"); } void BindlessHeap::writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImageView view, VkImageLayout layout) { @@ -648,7 +631,7 @@ void BindlessHeap::writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImag encodeScratch.resize(stride); const VkHostAddressRangeEXT range{encodeScratch.data(), stride}; if (writeResourceDescriptors == nullptr) writeResourceDescriptors = context.Function("vkWriteResourceDescriptorsEXT"); - check(writeResourceDescriptors(context.device, 1, &resource, &range), "vkWriteResourceDescriptorsEXT"); + Check(writeResourceDescriptors(context.device, 1, &resource, &range), "vkWriteResourceDescriptorsEXT"); std::memcpy(target, encodeScratch.data(), stride); KeepEncodedImageView(view, record->generation, key, encodeScratch); ++counts.encodes; @@ -681,19 +664,17 @@ struct HeapBindingUse { using SetAndBinding = std::pair; std::optional> decoratedVariables(std::span spirv) { - constexpr std::uint32_t opDecorate = 71u; - constexpr std::uint32_t decorationBinding = 33u; - constexpr std::uint32_t decorationSet = 34u; - constexpr std::size_t headerWords = 5u; - if (spirv.size() < headerWords) return std::nullopt; + constexpr std::size_t HeaderWords = 5u; + constexpr std::uint32_t DecorateWords = 4u; + if (spirv.size() < HeaderWords) return std::nullopt; std::unordered_map decorated; - for (std::size_t at = headerWords; at < spirv.size();) { + for (std::size_t at = HeaderWords; at < spirv.size();) { const auto count = spirv[at] >> 16u; if (count == 0u || at + count > spirv.size()) return std::nullopt; - if ((spirv[at] & 0xffffu) == opDecorate && count >= 4u) { + if ((spirv[at] & 0xffffu) == static_cast(spv::OpDecorate) && count >= DecorateWords) { auto& entry = decorated.try_emplace(spirv[at + 1u], SetAndBinding{~0u, ~0u}).first->second; - if (spirv[at + 2u] == decorationSet) entry.first = spirv[at + 3u]; - if (spirv[at + 2u] == decorationBinding) entry.second = spirv[at + 3u]; + if (spirv[at + 2u] == static_cast(spv::DecorationDescriptorSet)) entry.first = spirv[at + 3u]; + if (spirv[at + 2u] == static_cast(spv::DecorationBinding)) entry.second = spirv[at + 3u]; } at += count; } @@ -774,19 +755,30 @@ constexpr std::uint32_t rootAddressOffset(std::uint32_t rootField) { return (Abi::RootDword + rootField) * sizeof(std::uint32_t); } +VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, VkDeviceSize heapOffset) { + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = Abi::GpuDataSet; + mapping.firstBinding = binding; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_RESOURCE_HEAP_DATA_EXT; + mapping.sourceData.heapData.heapOffset = static_cast(heapOffset); + mapping.sourceData.heapData.pushOffset = rootAddressOffset(Abi::RootStageDword(static_cast(binding / bindingCount), Abi::RootStageField::ShaderData)); + return mapping; +} + } bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds, bool meshWindow) { HeapBindingUse use; const bool mappable = heapBindings(spirv, {.workgroupAddress = workgroupAddress, .gdsAddress = gdsAddress, .pixelLds = pixelLds, .meshWindow = meshWindow}, use); - static const bool stats = std::getenv("APS5_PIPELINE_STATS") != nullptr; - if (!mappable && stats) { + if (!mappable && pipelineStats()) { static std::mutex causesMutex; static std::map causes; std::lock_guard lock(causesMutex); const auto count = ++causes[use.refused]; - const bool powerOfTwo = (count & (count - 1u)) == 0u; - if (powerOfTwo) { + if (std::has_single_bit(count)) { std::fprintf( stderr, "[gpu-heap] unmappable stage: descriptor set %d binding %d (workgroup address %d, gds address %d); %llu stage variants with this cause\n", @@ -805,6 +797,7 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, const HeapBindingRoots roots{ .workgroupAddress = workgroupAddressOffset != ~0u, .gdsAddress = rootGds, .faultAddress = rootFault, .pixelLds = pixelLds, .meshWindow = meshWindow}; if (!heapBindings(spirv, roots, use)) return false; + if (!use.dataUniforms.empty() && !ringInHeap) return false; constexpr auto bindingCount = static_cast(Abi::Binding::Count); constexpr VkSpirvResourceTypeFlagsEXT imageResources = VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_IMAGE_BIT_EXT | @@ -817,21 +810,7 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, heapMapping(Abi::FragmentDescriptorSet, binding, VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT, 0, samplerHeapStride)); else mappings.push_back(heapMapping(Abi::FragmentDescriptorSet, binding, imageResources, 0, imageHeapStride)); } - if (!use.dataUniforms.empty() && !ringInHeap) { - mappings.clear(); - return false; - } - for (const auto binding : use.dataUniforms) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = Abi::GpuDataSet; - mapping.firstBinding = binding; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_RESOURCE_HEAP_DATA_EXT; - mapping.sourceData.heapData.heapOffset = static_cast(ringHeapOffset); - mapping.sourceData.heapData.pushOffset = rootAddressOffset(Abi::RootStageDword(static_cast(binding / bindingCount), Abi::RootStageField::ShaderData)); - mappings.push_back(mapping); - } + for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, ringHeapOffset)); if (use.workgroupMemory) mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset)); if (use.gdsBinding != ~0u) @@ -920,8 +899,7 @@ constexpr std::array(HeapCost::Count)> Hea "template build", "slots", "stage data", "buffer addresses", "memo insert", "guards"}; void reportHeapStatistics() { - static const bool enabled = std::getenv("APS5_PIPELINE_STATS") != nullptr; - if (!enabled) return; + if (!pipelineStats()) return; static std::atomic calls{0}; if ((calls.fetch_add(1, std::memory_order_relaxed) & 1023u) != 0u) return; static std::mutex reportMutex; @@ -989,8 +967,7 @@ void NoteHeapStageReason(HeapStageReason reason) { } bool HeapCostTimed() { - static const bool timed = std::getenv("APS5_PIPELINE_STATS") != nullptr; - return timed; + return pipelineStats(); } void NoteHeapCost(HeapCost cost, std::uint64_t nanoseconds) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 02ed51780595..95b8631e516e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -50,9 +50,14 @@ namespace AgcDriver::Graphics { namespace { +std::uint32_t takenSlot(std::optional slot, const char* what) { + Require(slot.has_value(), what); + return *slot; +} + bool UintStorageBinding(std::uint32_t binding) { const auto kind = binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count); - return kind >= ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 7u && kind < ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 14u; + return kind >= ShaderRecompiler::RuntimeAbi::FirstUintStorageImageBinding && kind < ShaderRecompiler::RuntimeAbi::FirstAtomicImageBinding; } bool overlap(std::uint64_t first, std::size_t firstSize, std::uint64_t second, std::size_t secondSize) { @@ -6318,38 +6323,25 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ continue; } const auto view = textureFirstLayer[index] ? textures[index]->FirstLayerView() : textures[index]->View(); - const auto slot = heap.TextureSlot(Abi::FirstImageBinding, textures[index], view, textures[index]->Layout()); - Require(slot.has_value(), "the global image heap is full"); - map.push_back(*slot); + map.push_back(takenSlot(heap.TextureSlot(Abi::FirstImageBinding, textures[index].get(), view, textures[index]->Layout()), "the global image heap is full")); } - for (std::size_t element = 0; element < elements; ++element) { - const auto index = element < table->elementStorage.size() ? table->elementStorage[element] : noElement; - if (index == noElement || storageTextures[index] == nullptr) { - map.push_back(storageAbsent); - continue; - } - const auto slot = heap.StorageSlot(Abi::FirstStorageImageBinding, storageTextures[index], - storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index])); - Require(slot.has_value(), "the global storage image heap is full"); - map.push_back(*slot); - } - std::uint32_t fallbackSampler = 0; - for (const auto index : table->tableSamplers) { - if (index == noElement) continue; - const auto slot = heap.SamplerSlot(samplers[index]); - Require(slot.has_value(), "the global sampler heap is full"); - fallbackSampler = *slot; - break; - } - for (const auto index : table->tableSamplers) { - if (index == noElement) { - map.push_back(fallbackSampler); - continue; + const auto appendStorageSlots = [&](std::uint32_t kind, std::uint32_t absent, const char* full, const auto& wanted, const auto& viewOf) { + for (std::size_t element = 0; element < elements; ++element) { + const auto index = element < table->elementStorage.size() ? table->elementStorage[element] : noElement; + if (!wanted(element) || index == noElement || storageTextures[index] == nullptr) { + map.push_back(absent); + continue; + } + map.push_back(takenSlot(heap.StorageSlot(kind, storageTextures[index].get(), viewOf(*storageTextures[index], index)), full)); } - const auto slot = heap.SamplerSlot(samplers[index]); - Require(slot.has_value(), "the global sampler heap is full"); - map.push_back(*slot); - } + }; + appendStorageSlots( + Abi::FirstStorageImageBinding, storageAbsent, "the global storage image heap is full", [](std::size_t) { return true; }, + [&](StorageTexture& image, std::size_t index) { return image.StorageView(storageMips[index], storageFirstLayer[index]); }); + const auto samplerSlotOf = [&](std::size_t index) { return takenSlot(heap.SamplerSlot(samplers[index]), "the global sampler heap is full"); }; + const auto firstSampler = std::find_if(table->tableSamplers.begin(), table->tableSamplers.end(), [&](const auto index) { return index != noElement; }); + const std::uint32_t fallbackSampler = firstSampler != table->tableSamplers.end() ? samplerSlotOf(*firstSampler) : 0u; + for (const auto index : table->tableSamplers) map.push_back(index == noElement ? fallbackSampler : samplerSlotOf(index)); const auto atomicElement = [&](std::size_t element, bool wide) { if (images == nullptr) return false; const auto& flags = wide ? images->imageAtomic64 : images->imageAtomic; @@ -6368,20 +6360,13 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ map.resize(extraBase, fallbackSampler); for (const bool wide : {false, true}) { const auto kind = wide ? Abi::FirstAtomic64ImageBinding : Abi::FirstAtomicImageBinding; - const auto absent = heap.AbsentSlot(kind, heapPlaceholderView(kind)); - for (std::size_t element = 0; element < elements; ++element) { - const auto index = element < table->elementStorage.size() ? table->elementStorage[element] : noElement; - if (!atomicElement(element, wide) || index == noElement || storageTextures[index] == nullptr) { - map.push_back(absent); - continue; - } - auto& image = *storageTextures[index]; - const auto view = wide ? image.Atomic64View(storageMips[index], storageFirstLayer[index]) - : image.AtomicView(storageMips[index], storageFirstLayer[index]); - const auto slot = heap.StorageSlot(kind, storageTextures[index], view); - Require(slot.has_value(), "the global atomic image heap is full"); - map.push_back(*slot); - } + appendStorageSlots( + kind, heap.AbsentSlot(kind, heapPlaceholderView(kind)), "the global atomic image heap is full", + [&](std::size_t element) { return atomicElement(element, wide); }, + [&](StorageTexture& image, std::size_t index) { + return wide ? image.Atomic64View(storageMips[index], storageFirstLayer[index]) + : image.AtomicView(storageMips[index], storageFirstLayer[index]); + }); } } const bool storageTable = std::ranges::any_of(shader.program->bindings, [](const ShaderRecompiler::DescriptorBinding& binding) { @@ -6389,18 +6374,10 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ }); if (storageTable) { map.resize(extraBase + 2u * elements, fallbackSampler); - const auto kind = Abi::FirstStorageImageBinding + 7u; - const auto absent = heap.AbsentSlot(kind, heapPlaceholderView(kind)); - for (std::size_t element = 0; element < elements; ++element) { - const auto index = element < table->elementStorage.size() ? table->elementStorage[element] : noElement; - if (index == noElement || storageTextures[index] == nullptr) { - map.push_back(absent); - continue; - } - const auto slot = heap.StorageSlot(kind, storageTextures[index], storageTextures[index]->UintStorageViewOrDefault(storageMips[index], storageFirstLayer[index])); - Require(slot.has_value(), "the global storage image heap is full"); - map.push_back(*slot); - } + const auto kind = Abi::FirstUintStorageImageBinding; + appendStorageSlots( + kind, heap.AbsentSlot(kind, heapPlaceholderView(kind)), "the global storage image heap is full", [](std::size_t) { return true; }, + [&](StorageTexture& image, std::size_t index) { return image.UintStorageViewOrDefault(storageMips[index], storageFirstLayer[index]); }); } if (map.size() == base) map.push_back(sampledAbsent); heapTableMaps[stageIndex] = heapSpan(heapStages[stageIndex].map, map); @@ -6475,21 +6452,6 @@ void ShaderResources::appendHeapSlotKey(VkShaderStageFlags stageBit, std::vector } } -bool ShaderResources::heapSlotsCurrent(const BindlessHeap& heap, const HeapStageState& state) { - std::size_t generation = 0; - for (std::uint32_t kind = 0; kind < state.slots.size(); ++kind) { - for (const auto slot : state.slots[kind]) { - if (generation >= state.slotGenerations.size() || heap.SlotGeneration(slot) != state.slotGenerations[generation++]) - return false; - } - } - for (std::size_t i = 0; i < state.samplerSlots.size(); ++i) { - if (i >= state.samplerGenerations.size() || heap.SamplerGeneration(state.samplerSlots[i]) != state.samplerGenerations[i]) - return false; - } - return true; -} - void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, VkShaderStageFlags stageBit, std::span key) { namespace Abi = ShaderRecompiler::RuntimeAbi; @@ -6511,9 +6473,7 @@ void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, V } const auto view = reinterpret_cast(key[cursor + 1]); cursor += 3; - const auto slot = heap.TextureSlot(kind, textures[index], view, textures[index]->Layout()); - Require(slot.has_value(), "the global image heap is full"); - kindSlots.push_back(*slot); + kindSlots.push_back(takenSlot(heap.TextureSlot(kind, textures[index].get(), view, textures[index]->Layout()), "the global image heap is full")); } } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { auto& kindSlots = state.slots[kind]; @@ -6521,9 +6481,7 @@ void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, V if (index != absent && storageTextures[index] == nullptr && heapMultisampleStorageView(index) != VK_NULL_HANDLE) { const auto view = reinterpret_cast(key[cursor + 1]); cursor += 3; - const auto slot = heap.ViewSlot(kind, reinterpret_cast(view), view); - Require(slot.has_value(), "the global storage image heap is full"); - kindSlots.push_back(*slot); + kindSlots.push_back(takenSlot(heap.ViewSlot(kind, reinterpret_cast(view), view), "the global storage image heap is full")); continue; } if (index == absent || storageTextures[index] == nullptr) { @@ -6533,16 +6491,12 @@ void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, V } const auto view = reinterpret_cast(key[cursor + 1]); cursor += 3; - const auto slot = heap.StorageSlot(kind, storageTextures[index], view); - Require(slot.has_value(), "the global storage image heap is full"); - kindSlots.push_back(*slot); + kindSlots.push_back(takenSlot(heap.StorageSlot(kind, storageTextures[index].get(), view), "the global storage image heap is full")); } } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { for (const auto index : binding.imageAllocations) { ++cursor; - const auto slot = heap.SamplerSlot(samplers[index]); - Require(slot.has_value(), "the global sampler heap is full"); - state.samplerSlots.push_back(*slot); + state.samplerSlots.push_back(takenSlot(heap.SamplerSlot(samplers[index]), "the global sampler heap is full")); } } } @@ -6662,10 +6616,9 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { bool current = key == stageState.key; const auto slotSerial = heap.SlotSerial(); const bool unmoved = current && EpochProofs() && stageState.slotSerial == slotSerial; - if (!unmoved && current && CommitTrims()) + if (!unmoved && current) current = heap.GenerationsCurrent(stageState.slots, stageState.slotGenerations, stageState.samplerSlots, stageState.samplerGenerations); - else if (!unmoved && current) current = heapSlotsCurrent(heap, stageState); if (!current) { stageState.key = key; takeHeapSlots(heap, stageState, stageBit, key); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 7bc5b0518382..35c23e4404c4 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -36,16 +36,16 @@ void textureSlots(const Context& context, VkImageView view) { BindlessHeap heap(context); const auto kind = Abi::FirstImageBinding; auto first = fakeTexture(0); - const auto slot = heap.TextureSlot(kind, first, view, VK_IMAGE_LAYOUT_GENERAL); + const auto slot = heap.TextureSlot(kind, first.get(), view, VK_IMAGE_LAYOUT_GENERAL); require(slot.has_value(), "the first texture takes a slot"); require(heap.SlotTexture(kind, *slot) == first.get(), "the slot names the first texture"); require(first.use_count() == 1, "a heap slot holds a reference to its texture"); const auto generation = heap.SlotGeneration(*slot); auto second = fakeTexture(1); - require(!heap.TextureSlot(kind, second, view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "the slot of a live texture is not reused"); + require(!heap.TextureSlot(kind, second.get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "the slot of a live texture is not reused"); heap.ReleaseImageSlots(first.get()); - const auto reused = heap.TextureSlot(kind, second, view, VK_IMAGE_LAYOUT_GENERAL); + const auto reused = heap.TextureSlot(kind, second.get(), view, VK_IMAGE_LAYOUT_GENERAL); require(reused.has_value() && *reused == *slot, "the released texture's slot is reused"); require(heap.SlotGeneration(*slot) != generation, "a freed slot moves its generation"); require(heap.SlotTexture(kind, *slot) == second.get(), "the reused slot names the second texture"); @@ -54,10 +54,10 @@ void textureSlots(const Context& context, VkImageView view) { auto shared = fakeTexture(2); const auto otherKind = kind + 1u; - require(!heap.TextureSlot(otherKind, shared, view, VK_IMAGE_LAYOUT_GENERAL).has_value(), + require(!heap.TextureSlot(otherKind, shared.get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "another kind finds the capped heap's only slot taken"); heap.ReleaseImageSlots(second.get()); - const auto sharedSlot = heap.TextureSlot(otherKind, shared, view, VK_IMAGE_LAYOUT_GENERAL); + const auto sharedSlot = heap.TextureSlot(otherKind, shared.get(), view, VK_IMAGE_LAYOUT_GENERAL); require(sharedSlot.has_value() && *sharedSlot == *slot, "another kind takes the slot the first kind's texture left"); require(heap.SlotTexture(kind, *slot) == nullptr && heap.SlotTexture(otherKind, *slot) == shared.get(), "the slot names the other kind's texture"); @@ -182,7 +182,7 @@ void heapComesBack(const Context& context, VkImageView view) { std::vector> held; for (std::size_t index = 0; index < 7u; ++index) { held.push_back(fakeTexture(index)); - require(heap.TextureSlot(kind, held.back(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), + require(heap.TextureSlot(kind, held.back().get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture takes one of the eight capped slots"); } require(BindlessHeap::NearlyFull(), "one free slot of eight refuses the heap"); @@ -234,7 +234,7 @@ void mixedComesBack(const Context& context, VkImageView sampledView, VkImageView std::vector> textures; for (std::size_t index = 0; index < 4u; ++index) { textures.push_back(fakeTexture(index)); - require(heap.TextureSlot(Abi::FirstImageBinding, textures.back(), sampledView, VK_IMAGE_LAYOUT_GENERAL).has_value(), + require(heap.TextureSlot(Abi::FirstImageBinding, textures.back().get(), sampledView, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture takes one of the eight capped slots"); } require(!BindlessHeap::NearlyFull(), "four textures in eight capped slots leave the heap taken"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp index a5e76fcb6989..69d498940cba 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp @@ -596,7 +596,7 @@ bool heapViewTests(const Context& context) { for (std::size_t surface = 1; surface < Surfaces; ++surface) CachedStorageSurface(context, Resource(block.Surface(surface))); Require(!view->StorageSource()->Cached(), "the heap view's storage image was not evicted"); auto& heap = BindlessHeap::For(context); - const auto slot = heap.TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, view, view->View(), view->Layout()); + const auto slot = heap.TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, view.get(), view->View(), view->Layout()); Require(slot.has_value(), "the view of an evicted storage image took no heap slot"); view.reset(); Require(viewed.expired(), "a heap slot kept the view of an evicted storage image, and with it the image"); @@ -611,7 +611,7 @@ void heapHeldReleaseTests(const Context& context) { std::vector slots; for (std::size_t surface = 0; surface < 2; ++surface) { auto texture = Sampled(context, block.Surface(surface)); - const auto slot = heap.TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, texture, texture->View(), texture->Layout()); + const auto slot = heap.TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, texture.get(), texture->View(), texture->Layout()); Require(slot.has_value(), "the cached sampled texture took no heap slot"); held.push_back(texture); slots.push_back(*slot); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp index 47f154043556..bed98baff4b0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp @@ -88,7 +88,7 @@ std::shared_ptr heapSlotted(AgcDriver::VulkanDevice& device, std if (!heapSlots || image == nullptr) return image; std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); auto& heap = AgcDriver::Graphics::BindlessHeap::For(device.GraphicsContext()); - const auto slot = heap.StorageSlot(ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding, image, image->StorageView(0, false)); + const auto slot = heap.StorageSlot(ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding, image.get(), image->StorageView(0, false)); Require(slot.has_value(), "the stored image took no GPU heap storage slot"); heapSlotsByAddress.try_emplace(address, HeapSlotted{*slot, heap.SlotGeneration(*slot)}); return image; diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index 08794791fced..8ecd0502a287 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -19,6 +19,7 @@ inline constexpr std::uint32_t FirstComparisonImageBinding = 22u; inline constexpr std::uint32_t FirstStorageImageBinding = 29u; inline constexpr std::uint32_t ImageBindingCount = 56u; inline constexpr bool GpuHeapStorageKind(std::uint32_t kind) { return kind >= FirstStorageImageBinding && kind < FirstImageBinding + ImageBindingCount; } +inline constexpr std::uint32_t FirstUintStorageImageBinding = FirstStorageImageBinding + 7u; inline constexpr std::uint32_t FirstAtomicImageBinding = FirstStorageImageBinding + 14u; inline constexpr std::uint32_t FirstAtomic64ImageBinding = FirstStorageImageBinding + 21u; inline constexpr bool AtomicImageKind(std::uint32_t kind) { return kind >= FirstAtomicImageBinding && kind < FirstAtomic64ImageBinding; } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp index c11411e61288..40a8542b2403 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp @@ -104,7 +104,7 @@ std::uint32_t tableHeapSlot(SpirvEmitterState& state, std::uint32_t part, std::u : part == 1u ? RuntimeAbi::FirstStorageImageBinding : part == 3u ? RuntimeAbi::FirstAtomicImageBinding : part == 4u ? RuntimeAbi::FirstAtomic64ImageBinding - : part == 5u ? RuntimeAbi::FirstStorageImageBinding + 7u + : part == 5u ? RuntimeAbi::FirstUintStorageImageBinding : 0u; const auto clamped = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), slot, ConstantU32(state, slots)), slot, ConstantU32(state, fallback)); DecorateTableNonUniform(state, clamped); @@ -118,7 +118,7 @@ std::uint32_t TableStorageImagePointer(SpirvEmitterState& state, DescriptorBindi if (found == state.tableImageVariables.end() || !state.tableAccess.active) ExitDescriptorBindingFailure(state, kind, resource, "image storage table array was not emitted for the mode"); const auto pointer = state.module.AllocateId(); const auto value = static_cast(kind); - const bool uintStorage = value >= RuntimeAbi::FirstStorageImageBinding + 7u && value < RuntimeAbi::FirstStorageImageBinding + 14u; + const bool uintStorage = value >= RuntimeAbi::FirstUintStorageImageBinding && value < RuntimeAbi::FirstAtomicImageBinding; const auto part = RuntimeAbi::AtomicImageKind(value) ? 3u : RuntimeAbi::Atomic64ImageKind(value) ? 4u : uintStorage ? 5u : 1u; state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, part, state.tableAccess.element, RuntimeAbi::GpuImageHeapSlots) : state.tableAccess.element); DecorateTableNonUniform(state, pointer); From dd832931744d92911d5cc0aefd19a91ab5825c83 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 31 Oct 2026 19:53:32 +0530 Subject: [PATCH 082/269] refactor(agc): GPU heap slot owners share one base and slot pool Texture, StorageTexture, Sampler, MultisampleTarget and presentation slots derive from HeapSlotOwner, which frees all of an owner's slots with one call and only when the heap gave it some. Image and sampler slots share SlotPool, the statistics read each heap's counts instead of a second set of counters, the heap lookup cache no longer depends on the draw pipeline, and multisample storage views are keyed by their target instead of by the view itself. --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 2 +- .../Execution/include/PresentationPass.hpp | 4 +- .../Execution/src/PresentationPass.cpp | 4 +- .../Graphics/include/BindlessHeap.hpp | 58 ++++-- .../Graphics/include/MultisampleTarget.hpp | 9 +- .../Graphics/include/Sampler.hpp | 5 +- .../Graphics/include/ShaderResources.hpp | 4 +- .../Graphics/include/Texture.hpp | 7 +- .../Graphics/include/TextureDetiler.hpp | 6 +- .../Graphics/src/BindlessHeap.cpp | 178 +++++++++--------- .../Graphics/src/MultisampleTarget.cpp | 14 +- .../libSceAgcDriver/Graphics/src/Sampler.cpp | 4 +- .../Graphics/src/ShaderResources.cpp | 18 +- .../libSceAgcDriver/Graphics/src/Texture.cpp | 6 +- .../Graphics/src/TextureDetiler.cpp | 4 +- .../tests/BindlessHeapSlots.cpp | 112 ++++++++--- .../tests/execution/MultisampleRetirement.cpp | 16 +- 17 files changed, 270 insertions(+), 181 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 191f243823fb..ad03f741f035 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -3631,7 +3631,7 @@ if(BUILD_TESTING) if(WIN32) set_tests_properties(agc_driver_heap_slots_comes_back PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() - foreach(agcHeapSlotsMode IN ITEMS storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back) + foreach(agcHeapSlotsMode IN ITEMS storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release) string(REPLACE "-" "_" agcHeapSlotsName "${agcHeapSlotsMode}") add_test(NAME agc_driver_heap_slots_${agcHeapSlotsName} COMMAND agc_driver_heap_slots_tests ${agcHeapSlotsMode}) set_tests_properties(agc_driver_heap_slots_${agcHeapSlotsName} PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/PresentationPass.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/PresentationPass.hpp index 60684205b75d..954234c6ace3 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/PresentationPass.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/PresentationPass.hpp @@ -3,6 +3,7 @@ #define VK_NO_PROTOTYPES #include +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include #include @@ -45,7 +46,8 @@ class PresentationPass { VkPipeline pipeline = VK_NULL_HANDLE; VkPipeline heapPipeline = VK_NULL_HANDLE; }; - struct Slot { + struct Slot : Graphics::HeapSlotOwner { + using Graphics::HeapSlotOwner::ReleaseHeapSlots; VkDescriptorSet set = VK_NULL_HANDLE; VkImageView source = VK_NULL_HANDLE; std::uint32_t width = 0; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp index dbe9f8619982..de2faec8994a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp @@ -140,9 +140,7 @@ void PresentationPass::Release(std::size_t index) noexcept { if (view) context.Function("vkDestroyImageView")(context.device, view, nullptr); } slot.transient.clear(); - if (slot.source && heap) { - if (auto* bindless = Graphics::BindlessHeap::Existing(context)) bindless->ReleaseImageSlots(&slot); - } + if (slot.source && heap) slot.ReleaseHeapSlots(context); if (slot.source) context.Function("vkDestroyImageView")(context.device, slot.source, nullptr); slot.source = VK_NULL_HANDLE; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 47caf2ee21d1..e75160afa6a7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -18,6 +18,7 @@ namespace AgcDriver::Graphics { class Buffer; class Recorder; +class HeapSlotOwner; class Sampler; class StorageTexture; class Texture; @@ -48,13 +49,12 @@ class BindlessHeap { VkDeviceSize RingOffset() const; std::optional TextureSlot(std::uint32_t kind, Texture* texture, VkImageView view, VkImageLayout layout); - std::optional StorageSlot(std::uint32_t kind, const void* owner, VkImageView view); - std::optional ViewSlot(std::uint32_t kind, const void* owner, VkImageView view); - void ReleaseImageSlots(const void* owner); - void ReleaseSamplerSlot(const Sampler* sampler); + std::optional StorageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view); + std::optional ViewSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view); + void ReleaseSlots(const HeapSlotOwner* owner); std::uint32_t SlotGeneration(std::uint32_t slot) const; const Texture* SlotTexture(std::uint32_t kind, std::uint32_t slot) const; - bool SlotHoldsStorage(std::uint32_t kind, std::uint32_t slot, const void* owner, VkImageView view) const; + bool SlotHoldsStorage(std::uint32_t kind, std::uint32_t slot, const HeapSlotOwner* owner, VkImageView view) const; std::optional SamplerSlot(const std::shared_ptr& sampler); std::uint32_t SamplerGeneration(std::uint32_t slot) const; std::uint64_t SlotSerial() const { return slotSerial.load(std::memory_order_acquire); } @@ -127,7 +127,7 @@ class BindlessHeap { std::atomic slotSerial{1}; struct ImageSlotKey { std::uint32_t kind; - const void* owner; + const HeapSlotOwner* owner; VkImageView view; VkImageLayout layout; bool operator==(const ImageSlotKey&) const = default; @@ -139,42 +139,66 @@ class BindlessHeap { const auto mix = [&seed](std::size_t value) { seed ^= value + HashSalt + (seed << 6u) + (seed >> 2u); }; mix(key.kind); mix(static_cast(key.layout)); - mix(std::hash{}(key.owner)); + mix(std::hash{}(key.owner)); mix(std::hash{}(reinterpret_cast(key.view))); return seed; } }; std::unordered_map imageSlots; - std::unordered_map> ownerSlots; - std::uint32_t nextImageSlot = 0; + std::unordered_map> ownerSlots; + struct SlotPool { + std::uint32_t next = 0; + std::uint32_t limit = 0; + std::vector free; + std::vector generations; + std::optional Take(bool& reused); + void Free(std::uint32_t slot); + std::size_t Unused() const; + std::uint32_t Generation(std::uint32_t slot) const; + }; struct SlotOwner { const Texture* texture = nullptr; ImageSlotKey key{}; - std::uint32_t generation = 0; }; std::vector owners; - std::vector freeSlots; + SlotPool imagePool; + SlotPool samplerPool; std::uint32_t slotCap = 0; - std::optional imageSlot(std::uint32_t kind, const void* owner, VkImageView view, VkImageLayout layout, Texture* texture); - std::optional takeSlotLocked(); + std::optional imageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view, VkImageLayout layout, Texture* texture); SlotOwner& claimSlotLocked(const ImageSlotKey& key, std::uint32_t slot); void freeSlotLocked(std::uint32_t slot); const SlotOwner* ownerLocked(std::uint32_t slot) const; - std::unordered_map samplerSlots; + std::unordered_map samplerSlots; std::unordered_set absentSlots; - std::vector samplerGenerations; - std::vector freeSamplerSlots; bool refused = false; void noteRefusedLocked(const char* what, std::uint32_t margin); void noteTakenLocked(); void noteSamplerTakenLocked(); void noteReleasedLocked(); std::uint32_t imageMargin() const; - std::size_t unusedLocked() const; bool roomLocked() const; Counts counts; }; +class HeapSlotOwner { +public: + HeapSlotOwner(const HeapSlotOwner&) = delete; + HeapSlotOwner& operator=(const HeapSlotOwner&) = delete; + +protected: + HeapSlotOwner() = default; + ~HeapSlotOwner() = default; + void ReleaseHeapSlots(const Context& context) noexcept { + if (heapSlotted.exchange(false, std::memory_order_acq_rel)) { + if (auto* heap = BindlessHeap::Existing(context)) heap->ReleaseSlots(this); + } + } + +private: + friend class BindlessHeap; + mutable std::atomic heapSlotted{false}; +}; + bool GpuHeapEnabled(); void SetDescriptorHeapDevice(bool available); bool DescriptorHeapEnabled(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp index 44c1a862468a..97a9f8a31501 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp @@ -18,6 +18,13 @@ namespace AgcDriver::Graphics { +class HeapSlotOwner; + +struct MultisampleStorage { + VkImageView view = VK_NULL_HANDLE; + const HeapSlotOwner* owner = nullptr; +}; + class StorageTexture; class Texture; struct GuestTextureResource; @@ -75,7 +82,7 @@ VkImageView MultisampleTargetView(const Context& context, const ColorTarget& tar VkImageView MultisampleTargetView(const Context& context, const ColorTarget& target, std::shared_ptr& owner, VkImage* image = nullptr); void KeepMultisampleTarget_nid_no_patch(const std::shared_ptr& owner); void MaterializeMultisampleTargetClear(const Context& context, const ColorTarget& target); -VkImageView MultisampleTargetStorageView(const Context& context, const GuestTextureResource& resource, bool uintStorage = false); +MultisampleStorage MultisampleTargetStorageView(const Context& context, const GuestTextureResource& resource, bool uintStorage = false); bool MultisampleTargetStorable(const Context& context, const ColorTarget& target); void ResolveMultisampleTarget(const Context& context, const ColorTarget& source, StorageTexture& destination, VkImageView destinationView); bool MultisampledColorFillAbsorbs(std::uint64_t address, std::size_t bytes, std::uint32_t pattern); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp index daabdbd4c6ca..a3a21ed58fd9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp @@ -1,6 +1,7 @@ #ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_SAMPLER_HPP #define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_SAMPLER_HPP +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestSamplerResource.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" @@ -14,7 +15,7 @@ namespace AgcDriver::Graphics { -class Sampler { +class Sampler : public HeapSlotOwner { public: Sampler(const Context& context, const GuestSamplerResource& descriptor); ~Sampler(); @@ -33,13 +34,11 @@ class Sampler { cacheKey = key; keyed = true; } - void MarkHeapSlotted() { heapSlotted.store(true, std::memory_order_release); } private: void release() noexcept; Context context; - std::atomic heapSlotted{false}; bool forcesDegamma = false; VkSampler sampler = VK_NULL_HANDLE; bool requiresFilterMinmax = false; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 97831656f24c..f366635d012a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -4,6 +4,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" @@ -657,6 +658,7 @@ class ShaderResources { VkImageView heapSampledView(std::size_t index) const; VkImageView heapStorageView(std::size_t index, std::uint32_t binding) const; VkImageView heapMultisampleStorageView(std::size_t index) const; + const HeapSlotOwner* heapMultisampleStorageOwner(std::size_t index) const; void appendHeapSlotKey(VkShaderStageFlags stageBit, std::vector& key) const; void takeHeapSlots(BindlessHeap& heap, HeapStageState& state, VkShaderStageFlags stageBit, std::span key); static void noteHeapSlotGenerations(const BindlessHeap& heap, HeapStageState& state); @@ -707,7 +709,7 @@ class ShaderResources { std::vector textureBaseLevel; std::vector textureSrgb; std::vector> storageTextures; - std::vector multisampleStorageViews; + std::vector multisampleStorage; std::vector storageMips; std::vector storageKeys; std::vector storageFirstLayer; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp index 42bd920e7bef..4802e7bd0682 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp @@ -1,6 +1,7 @@ #ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_TEXTURE_HPP #define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_TEXTURE_HPP +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestTextureResource.hpp" @@ -57,7 +58,7 @@ struct OwnedImage { std::uint32_t memoryType = 0; }; -class Texture { +class Texture : public HeapSlotOwner { public: Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span snapshot, bool depthCompare = false, const VkClearColorValue* clear = nullptr); Texture(const Context& context, const std::shared_ptr& source, const GuestTextureResource& descriptor, VkComponentMapping components); @@ -121,10 +122,8 @@ class Texture { void MarkRefreshedPerUse() { perUseCopy = PerUseCopy::RemadePerUse; } bool Released() const { return released.load(std::memory_order_acquire); } void MarkReleased() { released.store(true, std::memory_order_release); } - void MarkHeapSlotted() { heapSlotted.store(true, std::memory_order_release); } private: - std::atomic heapSlotted{false}; void release() noexcept; bool refreshBlockCopy(); bool refreshSrgbExpand(); @@ -177,7 +176,7 @@ VkFormat SrgbTwinFormat(const Context& context, VkFormat format); // either at once (WriteBack) or deferred: MarkDirty keeps them on the GPU until something reads that // memory (FlushPending, through the GuestMemory flush hook), the image is refreshed after a CPU write, // or it leaves the cache. Dispatches reusing the image meanwhile skip the round trip entirely. -class StorageTexture : public std::enable_shared_from_this { +class StorageTexture : public std::enable_shared_from_this, public HeapSlotOwner { public: static std::shared_ptr Create(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, std::uint32_t mipLevel); ~StorageTexture(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp index d94680de26cf..a370aba2922d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp @@ -13,6 +13,8 @@ namespace AgcDriver::Graphics { +class HeapSlotOwner; + class Buffer; // The part of a mip one Dispatch moves: only elements whose tiled offset (relative to the mip's @@ -48,12 +50,12 @@ namespace AgcDriver::Graphics { // restricts the move to part of the mip (a partial upload or write-back, StorageTexture), // leaving the other elements of both buffers alone. void Dispatch(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, bool thick = false, const DetileWindow& window = {}); - void DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, const DetileWindow& window = {}, const void* owner = nullptr); + void DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, const DetileWindow& window = {}, const HeapSlotOwner* owner = nullptr); void DispatchRepack(VkCommandBuffer commands, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, std::uint64_t bytes); static VkFormat ImageElementFormat(std::uint32_t elementBytes); // Recycles the descriptor sets of the previous batch; call before recording a new command batch. void BeginBatch(); - void DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write, const void* owner = nullptr); + void DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write, const HeapSlotOwner* owner = nullptr); std::uint32_t CmaskErrors(); void DispatchMultisampleReadback(VkCommandBuffer commands, VkFormat format, VkBuffer destination, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements); void DispatchMultisampleImage(VkCommandBuffer commands, std::uint32_t elementBytes, VkBuffer source, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 12ed91165d3d..6b77f50cba31 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -74,11 +74,6 @@ std::size_t lastChunkOf(std::size_t offset, std::size_t bytes) { return chunkOf(offset + std::max(bytes, 1u) - 1u); } -std::atomic spansWrittenWindow{0}; -std::atomic imageEncodesWindow{0}; -std::atomic imageCopiesWindow{0}; -std::atomic spansKeptWindow{0}; -std::atomic spansExpiredWindow{0}; std::atomic heapComputeStages{0}; std::atomic descriptorHeapDevice{false}; std::atomic imageTableBuilds{0}; @@ -253,8 +248,10 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { ringAlignment = static_cast(std::max(context.limits.minStorageBufferOffsetAlignment, RingSpanAlignment)); } ringChunks.resize(ringBytes / RingChunkBytes); - nextImageSlot = SamplerKind; slotCap = configuredSlotCap(); + imagePool.next = SamplerKind; + imagePool.limit = slotCap; + samplerPool.limit = Abi::GpuSamplerHeapSlots; } namespace { @@ -292,8 +289,7 @@ BindlessHeap& BindlessHeap::For(const Context& context) { std::uint64_t epoch = ~std::uint64_t{0}; }; thread_local Cached cached; - const bool trims = CommitTrims(); - if (trims && cached.heap != nullptr && cached.device == context.device && cached.epoch == heapsEpoch.load(std::memory_order_acquire)) { + if (cached.heap != nullptr && cached.device == context.device && cached.epoch == heapsEpoch.load(std::memory_order_acquire)) { return *cached.heap; } std::lock_guard lock(heapsMutex()); @@ -302,7 +298,7 @@ BindlessHeap& BindlessHeap::For(const Context& context) { heap = std::make_unique(context); heapsEpoch.fetch_add(1, std::memory_order_acq_rel); } - if (trims) cached = {context.device, heap.get(), heapsEpoch.load(std::memory_order_acquire)}; + cached = {context.device, heap.get(), heapsEpoch.load(std::memory_order_acquire)}; return *heap; } @@ -326,56 +322,55 @@ BindlessHeap* BindlessHeap::Existing(const Context& context) { std::optional BindlessHeap::TextureSlot(std::uint32_t kind, Texture* texture, VkImageView view, VkImageLayout layout) { Require(isSampledKind(kind) && texture != nullptr && view != VK_NULL_HANDLE, "bindless heap: invalid texture slot request"); - return imageSlot(kind, texture, view, layout, texture); + const HeapSlotOwner* owner = texture; + return imageSlot(kind, owner, view, layout, texture); } -std::optional BindlessHeap::StorageSlot(std::uint32_t kind, const void* owner, VkImageView view) { +std::optional BindlessHeap::StorageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view) { Require(Abi::GpuHeapStorageKind(kind) && owner != nullptr && view != VK_NULL_HANDLE, "bindless heap: invalid storage slot request"); return imageSlot(kind, owner, view, VK_IMAGE_LAYOUT_GENERAL, nullptr); } -std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const void* owner, VkImageView view) { +std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view) { Require(isImageKind(kind) && owner != nullptr && view != VK_NULL_HANDLE, "bindless heap: invalid view slot request"); return imageSlot(kind, owner, view, VK_IMAGE_LAYOUT_GENERAL, nullptr); } -std::optional BindlessHeap::imageSlot(std::uint32_t kind, const void* owner, VkImageView view, VkImageLayout layout, Texture* texture) { +std::optional BindlessHeap::imageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view, VkImageLayout layout, Texture* texture) { std::lock_guard lock(mutex); const ImageSlotKey key{kind, owner, view, layout}; if (const auto found = imageSlots.find(key); found != imageSlots.end()) return found->second; - const auto slot = takeSlotLocked(); + bool reused = false; + const auto slot = imagePool.Take(reused); if (!slot) return std::nullopt; + if (reused) ++counts.slotsReused; writeImageSlot(kind, *slot, view, layout); claimSlotLocked(key, *slot).texture = texture; - if (texture != nullptr) texture->MarkHeapSlotted(); + owner->heapSlotted.store(true, std::memory_order_release); noteTakenLocked(); return slot; } -void BindlessHeap::ReleaseImageSlots(const void* owner) { +void BindlessHeap::ReleaseSlots(const HeapSlotOwner* owner) { std::lock_guard lock(mutex); - const auto found = ownerSlots.find(owner); - if (found == ownerSlots.end()) return; - const auto slots = std::move(found->second); - ownerSlots.erase(found); - for (const auto slot : slots) freeSlotLocked(slot); + bool released = false; + if (const auto found = ownerSlots.find(owner); found != ownerSlots.end()) { + const auto slots = std::move(found->second); + ownerSlots.erase(found); + for (const auto slot : slots) freeSlotLocked(slot); + released = true; + } + if (const auto found = samplerSlots.find(owner); found != samplerSlots.end()) { + samplerPool.Free(found->second); + samplerSlots.erase(found); + ++counts.slotsFreed; + released = true; + } + if (!released) return; slotSerial.fetch_add(1, std::memory_order_release); noteReleasedLocked(); } -void BindlessHeap::ReleaseSamplerSlot(const Sampler* sampler) { - std::lock_guard lock(mutex); - const auto found = samplerSlots.find(sampler); - if (found == samplerSlots.end()) return; - const auto slot = found->second; - samplerSlots.erase(found); - ++samplerGenerations[slot]; - slotSerial.fetch_add(1, std::memory_order_release); - freeSamplerSlots.push_back(slot); - ++counts.slotsFreed; - noteReleasedLocked(); -} - BindlessHeap::SlotOwner& BindlessHeap::claimSlotLocked(const ImageSlotKey& key, std::uint32_t slot) { imageSlots.emplace(key, slot); ownerSlots[key.owner].push_back(slot); @@ -389,8 +384,7 @@ void BindlessHeap::freeSlotLocked(std::uint32_t slot) { imageSlots.erase(owner.key); owner.texture = nullptr; owner.key = {}; - ++owner.generation; - freeSlots.push_back(slot); + imagePool.Free(slot); ++counts.slotsFreed; } @@ -398,15 +392,31 @@ const BindlessHeap::SlotOwner* BindlessHeap::ownerLocked(std::uint32_t slot) con return slot < owners.size() ? &owners[slot] : nullptr; } -std::optional BindlessHeap::takeSlotLocked() { - if (!freeSlots.empty()) { - const auto slot = freeSlots.back(); - freeSlots.pop_back(); - ++counts.slotsReused; +std::optional BindlessHeap::SlotPool::Take(bool& reused) { + reused = false; + if (!free.empty()) { + const auto slot = free.back(); + free.pop_back(); + reused = true; return slot; } - if (nextImageSlot >= slotCap) return std::nullopt; - return nextImageSlot++; + if (next >= limit) return std::nullopt; + const auto slot = next++; + if (generations.size() <= slot) generations.resize(static_cast(slot) + 1u, 0u); + return slot; +} + +void BindlessHeap::SlotPool::Free(std::uint32_t slot) { + ++generations[slot]; + free.push_back(slot); +} + +std::size_t BindlessHeap::SlotPool::Unused() const { + return (next < limit ? limit - next : 0u) + free.size(); +} + +std::uint32_t BindlessHeap::SlotPool::Generation(std::uint32_t slot) const { + return slot < generations.size() ? generations[slot] : 0u; } bool BindlessHeap::NearlyFull() { @@ -421,13 +431,9 @@ std::uint32_t BindlessHeap::imageMargin() const { return std::max(1u, std::min(ImageSlotMargin, (slotCap - SamplerKind) / 4u)); } -std::size_t BindlessHeap::unusedLocked() const { - return (nextImageSlot < slotCap ? slotCap - nextImageSlot : 0u) + freeSlots.size(); -} - bool BindlessHeap::roomLocked() const { - if (unusedLocked() < 2u * static_cast(imageMargin())) return false; - return Abi::GpuSamplerHeapSlots - samplerGenerations.size() + freeSamplerSlots.size() >= 2u * SamplerSlotMargin; + if (imagePool.Unused() < 2u * static_cast(imageMargin())) return false; + return samplerPool.Unused() >= 2u * SamplerSlotMargin; } void BindlessHeap::noteRefusedLocked(const char* what, std::uint32_t margin) { @@ -439,11 +445,11 @@ void BindlessHeap::noteRefusedLocked(const char* what, std::uint32_t margin) { void BindlessHeap::noteTakenLocked() { const auto margin = imageMargin(); - if (!refused && unusedLocked() < margin) noteRefusedLocked("image", margin); + if (!refused && imagePool.Unused() < margin) noteRefusedLocked("image", margin); } void BindlessHeap::noteSamplerTakenLocked() { - if (!refused && Abi::GpuSamplerHeapSlots - samplerGenerations.size() + freeSamplerSlots.size() < SamplerSlotMargin) noteRefusedLocked("sampler", SamplerSlotMargin); + if (!refused && samplerPool.Unused() < SamplerSlotMargin) noteRefusedLocked("sampler", SamplerSlotMargin); } void BindlessHeap::noteReleasedLocked() { @@ -455,7 +461,7 @@ void BindlessHeap::noteReleasedLocked() { std::uint32_t BindlessHeap::SamplerGeneration(std::uint32_t slot) const { std::lock_guard lock(mutex); - return slot < samplerGenerations.size() ? samplerGenerations[slot] : 0u; + return samplerPool.Generation(slot); } bool BindlessHeap::GenerationsCurrent(std::span> slots, std::span slotGenerations, @@ -465,24 +471,18 @@ bool BindlessHeap::GenerationsCurrent(std::span std::size_t generation = 0; for (std::uint32_t kind = 0; kind < slots.size(); ++kind) { for (const auto slot : slots[kind]) { - const auto* owner = ownerLocked(slot); - const auto current = owner != nullptr ? owner->generation : 0u; - if (generation >= slotGenerations.size() || current != slotGenerations[generation++]) return false; + if (generation >= slotGenerations.size() || imagePool.Generation(slot) != slotGenerations[generation++]) return false; } } - const auto samplerGenerationOf = [&](std::uint32_t slot) { - return slot < this->samplerGenerations.size() ? this->samplerGenerations[slot] : 0u; - }; for (std::size_t i = 0; i < samplerSlots.size(); ++i) { - if (i >= samplerGenerations.size() || samplerGenerationOf(samplerSlots[i]) != samplerGenerations[i]) return false; + if (i >= samplerGenerations.size() || samplerPool.Generation(samplerSlots[i]) != samplerGenerations[i]) return false; } return true; } std::uint32_t BindlessHeap::SlotGeneration(std::uint32_t slot) const { std::lock_guard lock(mutex); - const auto* owner = ownerLocked(slot); - return owner != nullptr ? owner->generation : 0u; + return imagePool.Generation(slot); } const Texture* BindlessHeap::SlotTexture(std::uint32_t kind, std::uint32_t slot) const { @@ -491,7 +491,7 @@ const Texture* BindlessHeap::SlotTexture(std::uint32_t kind, std::uint32_t slot) return owner != nullptr && owner->key.kind == kind ? owner->texture : nullptr; } -bool BindlessHeap::SlotHoldsStorage(std::uint32_t kind, std::uint32_t slot, const void* owner, VkImageView view) const { +bool BindlessHeap::SlotHoldsStorage(std::uint32_t kind, std::uint32_t slot, const HeapSlotOwner* owner, VkImageView view) const { std::lock_guard lock(mutex); const auto* held = ownerLocked(slot); return held != nullptr && held->key == ImageSlotKey{kind, owner, view, VK_IMAGE_LAYOUT_GENERAL}; @@ -509,21 +509,15 @@ std::uint32_t BindlessHeap::AbsentSlot(std::uint32_t kind, VkImageView view) { std::optional BindlessHeap::SamplerSlot(const std::shared_ptr& sampler) { Require(sampler != nullptr, "bindless heap: invalid sampler slot request"); std::lock_guard lock(mutex); - if (const auto found = samplerSlots.find(sampler.get()); found != samplerSlots.end()) return found->second; - std::uint32_t slot = 0; - if (!freeSamplerSlots.empty()) { - slot = freeSamplerSlots.back(); - freeSamplerSlots.pop_back(); - ++counts.slotsReused; - } else if (samplerGenerations.size() < Abi::GpuSamplerHeapSlots) { - slot = static_cast(samplerGenerations.size()); - samplerGenerations.push_back(0u); - } else { - return std::nullopt; - } - writeSamplerSlot(slot, sampler->Handle()); - samplerSlots.emplace(sampler.get(), slot); - sampler->MarkHeapSlotted(); + if (const auto found = samplerSlots.find(static_cast(sampler.get())); found != samplerSlots.end()) return found->second; + bool reused = false; + const auto slot = samplerPool.Take(reused); + if (!slot) return std::nullopt; + if (reused) ++counts.slotsReused; + writeSamplerSlot(*slot, sampler->Handle()); + const HeapSlotOwner* owner = sampler.get(); + samplerSlots.emplace(owner, *slot); + owner->heapSlotted.store(true, std::memory_order_release); noteSamplerTakenLocked(); return slot; } @@ -541,12 +535,10 @@ bool BindlessHeap::Held(const SpanMark& mark) { auto& chunk = ringChunks[first]; if (chunk.entries != mark.entry) { ++counts.spansExpired; - spansExpiredWindow.fetch_add(1, std::memory_order_relaxed); return false; } chunk.open = true; ++counts.spansKept; - spansKeptWindow.fetch_add(1, std::memory_order_relaxed); return true; } @@ -570,7 +562,6 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) enterRingChunk(chunk); auto* base = reinterpret_cast(ringData + offset); ++counts.spansWritten; - spansWrittenWindow.fetch_add(1, std::memory_order_relaxed); mark = {static_cast(offset), static_cast(words), ringChunks[chunkOf(offset)].entries}; return {static_cast(offset), std::span(base, words)}; } @@ -619,7 +610,6 @@ void BindlessHeap::writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImag const auto stride = static_cast(imageHeapStride); if (CopyEncodedImageView(view, key, std::span(target, stride))) { ++counts.encodedCopies; - imageCopiesWindow.fetch_add(1, std::memory_order_relaxed); return; } auto record = FindImageView(view); @@ -635,7 +625,6 @@ void BindlessHeap::writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImag std::memcpy(target, encodeScratch.data(), stride); KeepEncodedImageView(view, record->generation, key, encodeScratch); ++counts.encodes; - imageEncodesWindow.fetch_add(1, std::memory_order_relaxed); } namespace { @@ -934,11 +923,26 @@ void reportHeapStatistics() { const auto commandBuffers = takeCount(commandBuffersBegun); const auto copies = takeCount(cpuBufferCopies); const auto copiedMiB = takeCount(cpuBufferCopyBytes) >> 20u; - const auto spansWritten = takeCount(spansWrittenWindow); - const auto spansKept = takeCount(spansKeptWindow); - const auto spansExpired = takeCount(spansExpiredWindow); - const auto imageEncodes = takeCount(imageEncodesWindow); - const auto imageCopies = takeCount(imageCopiesWindow); + static BindlessHeap::Counts lastTotals; + BindlessHeap::Counts totals; + { + std::lock_guard heapsLock(heapsMutex()); + for (const auto& entry : heaps()) { + const auto counts = entry.second->Statistics(); + totals.spansWritten += counts.spansWritten; + totals.spansKept += counts.spansKept; + totals.spansExpired += counts.spansExpired; + totals.encodes += counts.encodes; + totals.encodedCopies += counts.encodedCopies; + } + } + const auto windowDelta = [](std::uint64_t now, std::uint64_t before) { return now >= before ? now - before : now; }; + const auto spansWritten = windowDelta(totals.spansWritten, lastTotals.spansWritten); + const auto spansKept = windowDelta(totals.spansKept, lastTotals.spansKept); + const auto spansExpired = windowDelta(totals.spansExpired, lastTotals.spansExpired); + const auto imageEncodes = windowDelta(totals.encodes, lastTotals.encodes); + const auto imageCopies = windowDelta(totals.encodedCopies, lastTotals.encodedCopies); + lastTotals = totals; const auto templates = ShaderRecompiler::HeapTemplateCounts(); std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp index 1ca9709273f2..fe5d6e2b77b8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp @@ -149,7 +149,7 @@ struct TargetUse { std::atomic claimed{false}; }; -class MultisampleTarget : public std::enable_shared_from_this { +class MultisampleTarget : public std::enable_shared_from_this, public HeapSlotOwner { public: MultisampleTarget(const Context& context, const ColorTarget& target) : context(context), target(target), cmask(target.cmaskAddress, target.cmaskBytes), colorFill(target) { this->context.bufferPool.reset(); @@ -756,10 +756,7 @@ class MultisampleTarget : public std::enable_shared_from_this for (const auto& [format, resolvePass] : resolvePasses) context.Function("vkDestroyRenderPass")(context.device, resolvePass, nullptr); if (orderView) context.Function("vkDestroyImageView")(context.device, orderView, nullptr); if (twinView) context.Function("vkDestroyImageView")(context.device, twinView, nullptr); - if (auto* heap = BindlessHeap::Existing(context)) { - if (storageView) heap->ReleaseImageSlots(reinterpret_cast(storageView)); - if (uintStorageView) heap->ReleaseImageSlots(reinterpret_cast(uintStorageView)); - } + ReleaseHeapSlots(context); if (storageView) context.Function("vkDestroyImageView")(context.device, storageView, nullptr); if (uintStorageView) context.Function("vkDestroyImageView")(context.device, uintStorageView, nullptr); destroy({image, memory, view}); @@ -1382,7 +1379,7 @@ void MaterializeMultisampleTargetClear(const Context& context, const ColorTarget acquire(context, target); } -VkImageView MultisampleTargetStorageView(const Context& context, const GuestTextureResource& resource, bool uintStorage) { +MultisampleStorage MultisampleTargetStorageView(const Context& context, const GuestTextureResource& resource, bool uintStorage) { std::lock_guard lock(targetsMutex()); discardRetiredTargets(); const auto format = ResolveTextureFormat(resource.format); @@ -1393,13 +1390,14 @@ VkImageView MultisampleTargetStorageView(const Context& context, const GuestText const auto& rendered = target->target; if (sameStorageForm(context, rendered.format, format) && rendered.extent.width == resource.width && rendered.extent.height == resource.height && rendered.samples == resource.samples && rendered.mip == 0) { if (!holdHostOnly(*target)) continue; - return target->Storage(StorageFormatForGuest(context, resource.format), uintStorage); + return {target->Storage(StorageFormatForGuest(context, resource.format), uintStorage), target.get()}; } other = target.get(); } if (other == nullptr) { Require(Recorder::Active() != nullptr, "a multisampled color target is only written by recorded dispatches"); - return createFilled(context, resource, format, "writing", true).Storage(StorageFormatForGuest(context, resource.format), uintStorage); + auto& created = createFilled(context, resource, format, "writing", true); + return {created.Storage(StorageFormatForGuest(context, resource.format), uintStorage), &created}; } char text[320]; std::snprintf(text, sizeof(text), "AGC graphics: storage image access to multisampled color target 0x%llx (%ux%u, %u samples, vk format %d) as a %ux%u texture of %u samples and guest format %u (vk %d) is not implemented", static_cast(resource.baseAddress), other->target.extent.width, other->target.extent.height, other->target.samples, static_cast(other->target.format), resource.width, resource.height, resource.samples, resource.format, static_cast(format)); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp index dc1cac5fd13d..593f1b7c8cb9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp @@ -56,9 +56,7 @@ namespace AgcDriver::Graphics { } void Sampler::release() noexcept { - if (heapSlotted.exchange(false, std::memory_order_acq_rel)) { - if (auto* heap = BindlessHeap::Existing(context)) heap->ReleaseSamplerSlot(this); - } + ReleaseHeapSlots(context); if (sampler) context.Function("vkDestroySampler")(context.device, sampler, nullptr); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 95b8631e516e..97d0b8fe4ae9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -2683,7 +2683,7 @@ void ShaderResources::buildComplete() { write.pImageInfo = images.data() + images.size(); for (const auto index : binding.imageAllocations) { if (index == std::numeric_limits::max()) images.push_back(absentImage(binding.layout.binding)); - else if (storageTextures[index] == nullptr) images.push_back({VK_NULL_HANDLE, multisampleStorageViews[index], VK_IMAGE_LAYOUT_GENERAL}); + else if (storageTextures[index] == nullptr) images.push_back({VK_NULL_HANDLE, multisampleStorage[index].view, VK_IMAGE_LAYOUT_GENERAL}); else images.push_back({VK_NULL_HANDLE, storageAtomic64[index] ? storageTextures[index]->Atomic64View(storageMips[index], storageFirstLayer[index]) : storageAtomic[index] ? storageTextures[index]->AtomicView(storageMips[index], storageFirstLayer[index]) : storageTextures[index]->StorageView(storageMips[index], storageFirstLayer[index], UintStorageBinding(binding.layout.binding)), VK_IMAGE_LAYOUT_GENERAL}); } Require(binding.imageAllocations.size() == binding.layout.descriptorCount, "descriptor allocations disagree with compact binding"); @@ -5248,9 +5248,9 @@ void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBind if (resource.dimension == TextureDimension::k2DMsaa) { Require(!(element < binding.imageAtomic.size() && binding.imageAtomic[element]) && !(element < binding.imageAtomic64.size() && binding.imageAtomic64[element]), "storage image atomics on a multisampled texture are not implemented"); storageTextures.push_back(nullptr); - multisampleStorageViews.resize(storageTextures.size(), VK_NULL_HANDLE); + multisampleStorage.resize(storageTextures.size()); const bool uintStorage = UintStorageBinding(binding.binding); - multisampleStorageViews.back() = MultisampleTargetStorageView(context, resource, uintStorage); + multisampleStorage.back() = MultisampleTargetStorageView(context, resource, uintStorage); multisampleSources.push_back(resource.baseAddress); storageMips.push_back(0); storageKeys.push_back(0); @@ -6406,7 +6406,11 @@ VkImageView ShaderResources::heapSampledView(std::size_t index) const { } VkImageView ShaderResources::heapMultisampleStorageView(std::size_t index) const { - return index < multisampleStorageViews.size() ? multisampleStorageViews[index] : VK_NULL_HANDLE; + return index < multisampleStorage.size() ? multisampleStorage[index].view : VK_NULL_HANDLE; +} + +const HeapSlotOwner* ShaderResources::heapMultisampleStorageOwner(std::size_t index) const { + return index < multisampleStorage.size() ? multisampleStorage[index].owner : nullptr; } VkImageView ShaderResources::heapStorageView(std::size_t index, std::uint32_t binding) const { @@ -6434,7 +6438,7 @@ void ShaderResources::appendHeapSlotKey(VkShaderStageFlags stageBit, std::vector } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { for (const auto index : binding.imageAllocations) { if (index != absent && storageTextures[index] == nullptr && heapMultisampleStorageView(index) != VK_NULL_HANDLE) { - key.insert(key.end(), {0u, reinterpret_cast(heapMultisampleStorageView(index)), + key.insert(key.end(), {reinterpret_cast(heapMultisampleStorageOwner(index)), reinterpret_cast(heapMultisampleStorageView(index)), static_cast(VK_IMAGE_LAYOUT_GENERAL)}); continue; } @@ -6481,7 +6485,7 @@ void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, V if (index != absent && storageTextures[index] == nullptr && heapMultisampleStorageView(index) != VK_NULL_HANDLE) { const auto view = reinterpret_cast(key[cursor + 1]); cursor += 3; - kindSlots.push_back(takenSlot(heap.ViewSlot(kind, reinterpret_cast(view), view), "the global storage image heap is full")); + kindSlots.push_back(takenSlot(heap.ViewSlot(kind, heapMultisampleStorageOwner(index), view), "the global storage image heap is full")); continue; } if (index == absent || storageTextures[index] == nullptr) { @@ -6533,7 +6537,7 @@ void ShaderResources::verifyHeapSlots(const BindlessHeap& heap, const HeapStageS const auto view = heapMultisampleStorageView(index); if (view == VK_NULL_HANDLE) continue; ++storageChecked; - if (!bound || !heap.SlotHoldsStorage(kind, state.slots[kind][element], reinterpret_cast(view), view)) ++storageWrong; + if (!bound || !heap.SlotHoldsStorage(kind, state.slots[kind][element], heapMultisampleStorageOwner(index), view)) ++storageWrong; continue; } ++storageChecked; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index fceece3a5edf..cdf583b6a16f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -1235,9 +1235,7 @@ VkImageView Texture::BaseLevelView() const { } void Texture::release() noexcept { - if (heapSlotted.exchange(false, std::memory_order_acq_rel)) { - if (auto* heap = BindlessHeap::Existing(context)) heap->ReleaseImageSlots(this); - } + ReleaseHeapSlots(context); upload.reset(); if (view) context.Function("vkDestroyImageView")(context.device, view, nullptr); view = VK_NULL_HANDLE; @@ -6571,7 +6569,7 @@ StorageTexture::~StorageTexture() { } void StorageTexture::release() noexcept { - if (auto* heap = BindlessHeap::Existing(context)) heap->ReleaseImageSlots(this); + ReleaseHeapSlots(context); for (const auto& [mip, extra] : extraViews) context.Function("vkDestroyImageView")(context.device, extra, nullptr); extraViews.clear(); for (const auto& [mip, extra] : firstLayerViews) context.Function("vkDestroyImageView")(context.device, extra, nullptr); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index 3e90314fcf01..0e557e1b26a3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -480,7 +480,7 @@ std::uint32_t TextureDetiler::CmaskErrors() { return codes; } -void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write, const void* owner) { +void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write, const HeapSlotOwner* owner) { Require(commands != VK_NULL_HANDLE && cmask != VK_NULL_HANDLE && view != VK_NULL_HANDLE, "a CMASK clear needs a command buffer, the CMASK buffer and the target view"); Require(elementBytes == 1 || elementBytes == 2 || elementBytes == 4 || elementBytes == 8, "a CMASK clear of this element size is not modeled"); Require(cmaskOffset % 4 == 0 && cmaskBytes % 4 == 0 && cmaskBytes != 0, "a CMASK clear needs a word-aligned CMASK"); @@ -587,7 +587,7 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask barrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, anyAccess); } -void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile, std::uint32_t slice, const DetileWindow& window, const void* owner) { +void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile, std::uint32_t slice, const DetileWindow& window, const HeapSlotOwner* owner) { Require(commands != VK_NULL_HANDLE, "texture detiling requires an active command buffer"); Require(window.rangeBegin < window.rangeEnd && window.tiledBase <= window.rangeBegin, "texture detiling window is empty"); Require(tiled != VK_NULL_HANDLE && view != VK_NULL_HANDLE, "texture detiling requires a tiled buffer and an image view"); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 35c23e4404c4..3d67f54fd8f7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -26,6 +26,10 @@ void require(bool condition, const std::string& what) { if (!condition) throw std::runtime_error(what); } +struct FakeOwner : HeapSlotOwner { + FakeOwner() = default; +}; + alignas(Texture) std::array, 8> fakeTextures{}; std::shared_ptr fakeTexture(std::size_t index) { @@ -44,7 +48,7 @@ void textureSlots(const Context& context, VkImageView view) { auto second = fakeTexture(1); require(!heap.TextureSlot(kind, second.get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "the slot of a live texture is not reused"); - heap.ReleaseImageSlots(first.get()); + heap.ReleaseSlots(first.get()); const auto reused = heap.TextureSlot(kind, second.get(), view, VK_IMAGE_LAYOUT_GENERAL); require(reused.has_value() && *reused == *slot, "the released texture's slot is reused"); require(heap.SlotGeneration(*slot) != generation, "a freed slot moves its generation"); @@ -56,14 +60,14 @@ void textureSlots(const Context& context, VkImageView view) { const auto otherKind = kind + 1u; require(!heap.TextureSlot(otherKind, shared.get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "another kind finds the capped heap's only slot taken"); - heap.ReleaseImageSlots(second.get()); + heap.ReleaseSlots(second.get()); const auto sharedSlot = heap.TextureSlot(otherKind, shared.get(), view, VK_IMAGE_LAYOUT_GENERAL); require(sharedSlot.has_value() && *sharedSlot == *slot, "another kind takes the slot the first kind's texture left"); require(heap.SlotTexture(kind, *slot) == nullptr && heap.SlotTexture(otherKind, *slot) == shared.get(), "the slot names the other kind's texture"); const auto freedBefore = heap.Statistics().slotsFreed; - heap.ReleaseImageSlots(shared.get()); - heap.ReleaseImageSlots(shared.get()); + heap.ReleaseSlots(shared.get()); + heap.ReleaseSlots(shared.get()); require(heap.Statistics().slotsFreed == freedBefore + 1u, "a texture's release frees its slot once"); } @@ -91,15 +95,15 @@ void samplerSlots(const Context& context) { void viewSlots(const Context& context, VkImageView view) { auto& heap = BindlessHeap::For(context); const auto kind = Abi::FirstStorageImageBinding + 27u; - const int first = 0, second = 0; + FakeOwner first, second; const auto slot = heap.ViewSlot(kind, &first, view); require(slot.has_value() && heap.ViewSlot(kind, &first, view) == slot, "a view keeps its slot"); require(!heap.ViewSlot(kind, &second, view).has_value(), "a full heap refuses another owner's view"); const auto generation = heap.SlotGeneration(*slot); - heap.ReleaseImageSlots(&first); + heap.ReleaseSlots(&first); require(heap.SlotGeneration(*slot) != generation, "a released view slot moves its generation"); require(heap.ViewSlot(kind, &second, view) == slot, "a released view slot is reused"); - heap.ReleaseImageSlots(&second); + heap.ReleaseSlots(&second); } void encodedViews(const Context& context) { @@ -128,15 +132,63 @@ void encodedViews(const Context& context) { void ownerSlots(const Context& context, VkImageView view) { BindlessHeap heap(context); - const int image = 0, other = 0; + FakeOwner image, other; const auto slot = heap.StorageSlot(Abi::FirstStorageImageBinding, &image, view); require(slot.has_value(), "a storage owner takes the capped heap's only slot"); require(!heap.StorageSlot(Abi::FirstStorageImageBinding + 1u, &image, view).has_value(), "the owner's second view finds the heap full"); - heap.ReleaseImageSlots(&other); + heap.ReleaseSlots(&other); require(!heap.StorageSlot(Abi::FirstStorageImageBinding, &other, view).has_value(), "another owner's release freed this owner's slot"); - heap.ReleaseImageSlots(&image); + heap.ReleaseSlots(&image); require(heap.StorageSlot(Abi::FirstStorageImageBinding, &other, view) == slot, "a storage owner's release frees its slot"); - heap.ReleaseImageSlots(&other); + heap.ReleaseSlots(&other); +} + +void ownerViewsRelease(const Context& context, VkImageView view) { + BindlessHeap heap(context); + FakeOwner owner; + const auto firstKind = Abi::FirstStorageImageBinding, secondKind = Abi::FirstStorageImageBinding + 1u; + const auto first = heap.StorageSlot(firstKind, &owner, view); + const auto second = heap.ViewSlot(secondKind, &owner, view); + require(first.has_value() && second.has_value() && *first != *second, "one owner takes a slot for each of its two views"); + const auto before = heap.Statistics(); + const auto serial = heap.SlotSerial(); + require(heap.StorageSlot(firstKind, &owner, view) == first && heap.ViewSlot(secondKind, &owner, view) == second, "a lookup hit returns the owner's existing slots"); + const auto hit = heap.Statistics(); + require(hit.slotsFreed == before.slotsFreed && hit.slotsReused == before.slotsReused && hit.encodes == before.encodes && hit.encodedCopies == before.encodedCopies, + "a lookup hit changed the counts"); + require(heap.SlotSerial() == serial, "a lookup hit moved the slot serial"); + const auto firstGeneration = heap.SlotGeneration(*first), secondGeneration = heap.SlotGeneration(*second); + heap.ReleaseSlots(&owner); + const auto released = heap.Statistics(); + require(released.slotsFreed == before.slotsFreed + 2u, "one release freed " + std::to_string(released.slotsFreed - before.slotsFreed) + " of the owner's two slots"); + require(heap.SlotGeneration(*first) != firstGeneration && heap.SlotGeneration(*second) != secondGeneration, "the release moved both slots' generations"); + require(heap.SlotSerial() != serial, "a release moved the slot serial"); + const auto releasedSerial = heap.SlotSerial(); + const auto releasedGenerations = std::array{heap.SlotGeneration(*first), heap.SlotGeneration(*second)}; + heap.ReleaseSlots(&owner); + require(heap.Statistics().slotsFreed == released.slotsFreed, "a second release of the same owner freed slots"); + require(heap.SlotSerial() == releasedSerial, "a second release moved the slot serial"); + require(heap.SlotGeneration(*first) == releasedGenerations[0] && heap.SlotGeneration(*second) == releasedGenerations[1], "a second release moved a generation"); +} + +struct SharedOwner : std::enable_shared_from_this, HeapSlotOwner { + explicit SharedOwner(const Context& context) : context(context) {} + ~SharedOwner() { ReleaseHeapSlots(context); } + Context context; +}; + +void sharedOwnerRelease(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + auto owner = std::make_shared(context); + const HeapSlotOwner* base = owner.get(); + require(static_cast(base) != static_cast(owner.get()), "the slot owner base does not sit behind another base"); + const auto slot = heap.StorageSlot(Abi::FirstStorageImageBinding, owner.get(), view); + require(slot.has_value(), "an owner behind another base takes a slot"); + const auto generation = heap.SlotGeneration(*slot); + const auto freed = heap.Statistics().slotsFreed; + owner.reset(); + require(heap.SlotGeneration(*slot) != generation && heap.Statistics().slotsFreed == freed + 1u, + "destroying an owner behind another base did not free its slot"); } void ringSpans(const Context& context) { @@ -186,30 +238,30 @@ void heapComesBack(const Context& context, VkImageView view) { "a texture takes one of the eight capped slots"); } require(BindlessHeap::NearlyFull(), "one free slot of eight refuses the heap"); - for (std::size_t index = 0; index < 2u; ++index) heap.ReleaseImageSlots(held[index].get()); + for (std::size_t index = 0; index < 2u; ++index) heap.ReleaseSlots(held[index].get()); require(BindlessHeap::NearlyFull(), "three free slots of eight leave the heap refused"); - heap.ReleaseImageSlots(held[2].get()); + heap.ReleaseSlots(held[2].get()); require(!BindlessHeap::NearlyFull(), "a release that leaves twice the margin free takes the heap again"); - for (std::size_t index = 3; index < held.size(); ++index) heap.ReleaseImageSlots(held[index].get()); + for (std::size_t index = 3; index < held.size(); ++index) heap.ReleaseSlots(held[index].get()); BindlessHeap::Release(context.device); } void storageComesBack(const Context& context, VkImageView view) { auto& heap = BindlessHeap::For(context); - std::array owners{}; + std::array owners{}; for (auto& owner : owners) { require(heap.StorageSlot(Abi::FirstStorageImageBinding, &owner, view).has_value(), "a storage owner takes one of the eight capped slots"); } require(BindlessHeap::NearlyFull(), "storage owners that leave one free slot of eight refuse the heap"); - for (auto& owner : owners) heap.ReleaseImageSlots(&owner); + for (auto& owner : owners) heap.ReleaseSlots(&owner); require(!BindlessHeap::NearlyFull(), "releasing the storage owners takes the heap again"); BindlessHeap::Release(context.device); } void storageViewsComeBack(const Context& context, VkImageView view) { auto& heap = BindlessHeap::For(context); - std::array owners{}; + std::array owners{}; for (std::size_t index = 0; index < 3u; ++index) { for (std::uint32_t kind = 0; kind < 2u; ++kind) { require(heap.StorageSlot(Abi::FirstStorageImageBinding + kind, &owners[index], view).has_value(), @@ -219,13 +271,13 @@ void storageViewsComeBack(const Context& context, VkImageView view) { require(heap.StorageSlot(Abi::FirstStorageImageBinding, &owners[3], view).has_value(), "a single-view storage owner takes the seventh slot"); require(BindlessHeap::NearlyFull(), "storage owners that leave one free slot of eight refuse the heap"); const auto freed = heap.Statistics().slotsFreed; - heap.ReleaseImageSlots(&owners[0]); + heap.ReleaseSlots(&owners[0]); require(heap.Statistics().slotsFreed == freed + 2u, "a storage owner's release freed " + std::to_string(heap.Statistics().slotsFreed - freed) + " of its two slots"); require(BindlessHeap::NearlyFull(), "three free slots of eight leave the heap refused"); - heap.ReleaseImageSlots(&owners[1]); + heap.ReleaseSlots(&owners[1]); require(!BindlessHeap::NearlyFull(), "releasing a second two-view owner takes the heap again"); - heap.ReleaseImageSlots(&owners[2]); - heap.ReleaseImageSlots(&owners[3]); + heap.ReleaseSlots(&owners[2]); + heap.ReleaseSlots(&owners[3]); BindlessHeap::Release(context.device); } @@ -238,25 +290,25 @@ void mixedComesBack(const Context& context, VkImageView sampledView, VkImageView "a texture takes one of the eight capped slots"); } require(!BindlessHeap::NearlyFull(), "four textures in eight capped slots leave the heap taken"); - std::array owners{}; + std::array owners{}; for (auto& owner : owners) { require(heap.StorageSlot(Abi::FirstStorageImageBinding, &owner, storageView).has_value(), "a storage owner takes one of the slots the textures left"); } require(BindlessHeap::NearlyFull(), "storage owners that take the slots the textures left refuse the heap"); - for (auto& owner : owners) heap.ReleaseImageSlots(&owner); + for (auto& owner : owners) heap.ReleaseSlots(&owner); require(!BindlessHeap::NearlyFull(), "releasing the storage owners takes the heap again while the textures stay"); - for (const auto& texture : textures) heap.ReleaseImageSlots(texture.get()); + for (const auto& texture : textures) heap.ReleaseSlots(texture.get()); BindlessHeap::Release(context.device); } void viewsComeBack(const Context& context, VkImageView view) { auto& heap = BindlessHeap::For(context); const auto kind = Abi::FirstStorageImageBinding + 27u; - std::array owners{}; + std::array owners{}; for (auto& owner : owners) require(heap.ViewSlot(kind, &owner, view).has_value(), "a view takes one of the eight capped slots"); require(BindlessHeap::NearlyFull(), "views that leave one free slot of eight refuse the heap"); - for (auto& owner : owners) heap.ReleaseImageSlots(&owner); + for (auto& owner : owners) heap.ReleaseSlots(&owner); require(!BindlessHeap::NearlyFull(), "releasing the views takes the heap again"); BindlessHeap::Release(context.device); } @@ -264,15 +316,15 @@ void viewsComeBack(const Context& context, VkImageView view) { void twoHeapsComeBack(const Context& context, VkImageView view) { auto first = std::make_unique(context); auto second = std::make_unique(context); - std::array firstOwners{}, secondOwners{}; + std::array firstOwners{}, secondOwners{}; for (auto& owner : firstOwners) require(first->ViewSlot(Abi::FirstStorageImageBinding, &owner, view).has_value(), "a view takes one of the first heap's eight capped slots"); for (auto& owner : secondOwners) require(second->ViewSlot(Abi::FirstStorageImageBinding, &owner, view).has_value(), "a view takes one of the second heap's eight capped slots"); require(BindlessHeap::NearlyFull(), "two nearly full heaps refuse the heap"); - for (auto& owner : secondOwners) second->ReleaseImageSlots(&owner); + for (auto& owner : secondOwners) second->ReleaseSlots(&owner); require(BindlessHeap::NearlyFull(), "room in the second heap took the heap back while the first stays nearly full"); second.reset(); require(BindlessHeap::NearlyFull(), "destroying the second heap took the heap back while the first stays nearly full"); - for (auto& owner : firstOwners) first->ReleaseImageSlots(&owner); + for (auto& owner : firstOwners) first->ReleaseSlots(&owner); require(!BindlessHeap::NearlyFull(), "room in the last refused heap did not take the heap back"); first.reset(); } @@ -315,6 +367,8 @@ int main(int argc, char** argv) { else if (mode == "mixed-comes-back") mixedComesBack(context, sampled, storage); else if (mode == "views-come-back") viewsComeBack(context, storage); else if (mode == "two-heaps-come-back") twoHeapsComeBack(context, storage); + else if (mode == "owner-views-release") ownerViewsRelease(context, storage); + else if (mode == "shared-owner-release") sharedOwnerRelease(context, storage); else throw std::runtime_error("unknown mode " + mode); device->WaitIdle(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp index b39f34eb6fbd..3fbf87df0e83 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp @@ -488,7 +488,7 @@ class Run { { std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); const auto keptBefore = context.recorder->OpenKeptBytes(); - storageView = MultisampleTargetStorageView(context, resource); + storageView = MultisampleTargetStorageView(context, resource).view; promoted = ImageFor(storageView, &promotedImage); Require(promoted.generation != old.generation && Alive(oldImage, old), "MSAA storage promotion did not retain its source image"); Require(ImageFor(sampledView).generation == old.generation, "MSAA storage promotion destroyed a held sampled view"); @@ -496,7 +496,7 @@ class Run { totalBytes = AllocationBytesOf(old) + AllocationBytesOf(promoted); const auto kept = context.recorder->OpenKeptBytes(); Require(kept == keptBefore + totalBytes, "MSAA storage promotion did not account for exactly both allocations"); - Require(MultisampleTargetStorageView(context, resource) == storageView, "a repeated MSAA storage lookup changed its view"); + Require(MultisampleTargetStorageView(context, resource).view == storageView, "a repeated MSAA storage lookup changed its view"); Require(context.recorder->OpenKeptBytes() == kept, "a repeated MSAA storage lookup double-counts its allocations"); } Sync(); @@ -506,10 +506,10 @@ class Run { Require(held->View() == sampledView, "a held sampled MSAA alias changed after promotion completion"); held.reset(); const auto keptBefore = context.recorder->OpenKeptBytes(); - Require(MultisampleTargetStorageView(context, resource) == storageView, "a later MSAA storage lookup changed its promoted image"); + Require(MultisampleTargetStorageView(context, resource).view == storageView, "a later MSAA storage lookup changed its promoted image"); const auto kept = context.recorder->OpenKeptBytes(); Require(kept == keptBefore + totalBytes, "an already-storable MSAA target is missing allocations from the new batch budget"); - Require(MultisampleTargetStorageView(context, resource) == storageView, "a repeated promoted MSAA lookup changed its view"); + Require(MultisampleTargetStorageView(context, resource).view == storageView, "a repeated promoted MSAA lookup changed its view"); Require(context.recorder->OpenKeptBytes() == kept, "an already-storable MSAA target double-counts its allocations in one batch"); } block.Unmap(); @@ -549,7 +549,7 @@ class Run { Sync(); { std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); - promoted = ImageFor(MultisampleTargetStorageView(context, resource), &promotedImage); + promoted = ImageFor(MultisampleTargetStorageView(context, resource).view, &promotedImage); Require(bornStorable == (promoted.generation == rendered.generation), bornStorable ? "a born-storable MSAA target was promoted to a new image" : "MSAA storage promotion kept the rendered image"); const auto promotedTwin = MultisampleTargetView(context, twin); ImageFor(promotedTwin, &promotedTwinImage); @@ -573,13 +573,13 @@ class Run { { std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex()); MultisampleTargetView(context, target); - storageView = MultisampleTargetStorageView(context, resource); + storageView = MultisampleTargetStorageView(context, resource).view; Require(storageView != VK_NULL_HANDLE, "a UNORM storage access to a multisampled sRGB target has no view"); - Require(MultisampleTargetStorageView(context, resource) == storageView, "a repeated UNORM storage access to a multisampled sRGB target changed its view"); + Require(MultisampleTargetStorageView(context, resource).view == storageView, "a repeated UNORM storage access to a multisampled sRGB target changed its view"); resource.format = 60; bool refused = false; try { - MultisampleTargetStorageView(context, resource); + MultisampleTargetStorageView(context, resource).view; } catch (const std::exception&) { refused = true; } From 31f5d0e8dd0a27b2b16ef8d51f6b30a890996fd8 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 31 Oct 2026 20:13:28 +0530 Subject: [PATCH 083/269] fix(agc): recheck a space-reuse hit's BDA table against new multisample targets A cached build keeps the BDA page table it was built with, filtered by the multisample-target guard generation of that moment. A new resident multisample target bumps only that generation, so a space-reuse hit kept binding a table that still mapped the target's guest memory. The build now keeps the generation its table was filtered at; a hit whose generation moved reruns ExcludeMultisampleTargetRanges over the build's space ranges and keeps the hit only when the result matches its table. Ported from #13858 (a142526a55). Co-authored-by: Yunus Shaikh <75296019+EagleBearerYS@users.noreply.github.com> --- .../Graphics/include/BdaResources.hpp | 3 + .../Graphics/include/ShaderResources.hpp | 1 + .../Graphics/src/BdaResources.cpp | 17 +++++ .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 2 +- .../Graphics/src/ShaderResources.cpp | 6 ++ .../tests/execution/AddressDrawSpaceReuse.cpp | 74 ++++++++++++++++++- 6 files changed, 101 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BdaResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BdaResources.hpp index 2a796be04636..f6c1b36e076c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BdaResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BdaResources.hpp @@ -4,6 +4,7 @@ #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "Recompiler.hpp" #include +#include #include #include #include @@ -17,6 +18,7 @@ class BdaResources { explicit BdaResources(const Context& context); BdaResources(const Context& context, const GuestBufferMemory& memory); VkDescriptorBufferInfo Table() const; + bool TableGuardCurrent(VkDevice device, std::span ranges); VkDescriptorBufferInfo Fault() const; void CheckFault() const; struct ImageTableFaults { @@ -60,6 +62,7 @@ class BdaResources { std::shared_ptr table; std::unique_ptr fault; std::size_t tableBytes = 0; + std::uint64_t tableGuardSerial = 0; std::vector imageTables; std::vector> imageTableRanges; std::vector srtGuards; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index f366635d012a..bb70a7423bb8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -259,6 +259,7 @@ class ShaderResources { static bool SpaceReuseDisabled(); bool BdaReadOnly() const { return usesBda && bdaReadOnly; } bool RetakeSpace() { return guestMemory.RetakeSpace(); } + bool AddressTableGuardCurrent(); bool SnapshotsServedInPlace(std::span snapshots) const { return guestMemory.SnapshotsServedInPlace(snapshots); } std::shared_ptr ReleaseSpace() { return guestMemory.ReleaseSpace(); } bool UsesAddressTable() const { return usesBda; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp index eb4622ac8164..6073ce796d00 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp @@ -132,6 +132,7 @@ BdaResources::BdaResources(const Context& context, const GuestBufferMemory& memo if (std::find(it->spaceKeys.begin(), it->spaceKeys.end(), key) == it->spaceKeys.end()) continue; if (auto shared = it->buffer.lock(); shared != nullptr) { tableBytes = shared->Bytes().size(); + tableGuardSerial = guardSerial; ++cache.hits; ++cache.classes.spaceTables; table = std::move(shared); @@ -143,6 +144,7 @@ BdaResources::BdaResources(const Context& context, const GuestBufferMemory& memo } } auto filtered = ExcludeMultisampleTargetRanges(context.device, addressRanges, guardSerial); + tableGuardSerial = guardSerial; const auto& ranges = filtered.has_value() ? *filtered : addressRanges; Require(ranges.size() <= std::numeric_limits::max(), "BDA table range count overflow"); Require(ranges.size() <= (std::numeric_limits::max() - sizeof(ShaderRecompiler::BdaAbi::Header)) / sizeof(ShaderRecompiler::BdaAbi::Range), "BDA table size overflow"); @@ -228,6 +230,21 @@ VkDescriptorBufferInfo BdaResources::Table() const { return {table->Handle(), 0, tableBytes}; } +bool BdaResources::TableGuardCurrent(VkDevice device, std::span ranges) { + if (table == nullptr || tableGuardSerial == MultisampleTargetRangeGeneration()) return true; + auto generation = tableGuardSerial; + const auto filtered = ExcludeMultisampleTargetRanges(device, ranges, generation); + const auto expected = filtered.has_value() ? std::span(*filtered) : ranges; + const auto bytes = table->Bytes().first(tableBytes); + ShaderRecompiler::BdaAbi::Header header{}; + if (bytes.size() < sizeof(header)) return false; + std::memcpy(&header, bytes.data(), sizeof(header)); + if (header.count != expected.size() || (bytes.size() - sizeof(header)) / sizeof(ShaderRecompiler::BdaAbi::Range) < expected.size()) return false; + if (!expected.empty() && std::memcmp(bytes.data() + sizeof(header), expected.data(), expected.size() * sizeof(ShaderRecompiler::BdaAbi::Range)) != 0) return false; + tableGuardSerial = generation; + return true; +} + VkDescriptorBufferInfo BdaResources::Fault() const { return {fault->Handle(), 0, ShaderRecompiler::BdaAbi::FaultBufferBytes}; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 435055ddbb13..da32eec2bc78 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1918,7 +1918,7 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat const auto releaseSpace = [](ShaderResources* resources) { static_cast(resources->ReleaseSpace()); }; std::unique_ptr heldSpace(cached->SpaceReuse() ? cached.get() : nullptr, releaseSpace); bool spaceHeld = !cached->SpaceReuse(); - if (!spaceHeld && cached->RetakeSpace()) spaceHeld = cached->SnapshotsServedInPlace(snapshots); + if (!spaceHeld && cached->RetakeSpace()) spaceHeld = cached->AddressTableGuardCurrent() && cached->SnapshotsServedInPlace(snapshots); const bool valid = spaceHeld && cached->Revalidate(shaders); auto* recorder = Recorder::Active(); std::optional> moved; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 97d0b8fe4ae9..e0132fb267d9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -2837,6 +2837,12 @@ bool ShaderResources::NeverReusable(std::span shaders) { }); } +bool ShaderResources::AddressTableGuardCurrent() { + if (bda == nullptr) return true; + if (const auto cached = guestMemory.CachedAddressTable(); cached.has_value()) return bda->TableGuardCurrent(context.device, *cached->ranges); + return bda->TableGuardCurrent(context.device, guestMemory.AddressRanges()); +} + bool ShaderResources::SpaceReuseDisabled() { return !GpuHeapEnabled(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp index 790568f8e9ee..0a391c2bb722 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp @@ -5,6 +5,7 @@ #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libc/include/GuestAllocations.hpp" @@ -416,6 +417,75 @@ void NoRecords(Scene& scene) { Require(scene.DrawnColor() == 60, "address draw space reuse: the draw after the indirect draw did not read the guest constant"); } +constexpr std::size_t MultisampleTargetOffset = 32768; + +bool MultisampleTargetsAvailable(Scene& scene) { + const auto context = scene.device.GraphicsContext(); + if (AgcDriver::GuestMemory::WriteWatched() && (context.limits.framebufferColorSampleCounts & VK_SAMPLE_COUNT_4_BIT) != 0) return true; + Require(std::getenv("ANYPS5_REQUIRE_VULKAN") == nullptr, "address draw space reuse: the multisample target cases require write tracking and 4x color targets"); + std::puts("skipped, the multisample target cases require write tracking and 4x color targets"); + return false; +} + +void PlaceMultisampleTarget(Scene& scene, std::uint64_t address) { + const auto context = scene.device.GraphicsContext(); + AgcDriver::Graphics::ColorTarget target{}; + target.address = address; + target.surfaceAddress = address; + target.extent = {Width, Height}; + target.surfaceExtent = target.extent; + target.format = VK_FORMAT_R8G8B8A8_UNORM; + target.tileMode = ColorTileMode::RenderTarget; + target.elementBytes = 4; + target.bytes = TargetLayout.Bytes(); + target.samples = 4; + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + Require(AgcDriver::Graphics::MultisampleTargetView(context, target) != VK_NULL_HANDLE, "address draw space reuse: the multisample target has no view"); + scene.device.SubmitRecorded(true); + scene.device.WaitIdle(); +} + +void RetireMultisampleTargets(Scene& scene) { + const auto context = scene.device.GraphicsContext(); + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + scene.device.WaitIdle(); + AgcDriver::Graphics::ClearMultisampleTargets(context.device); +} + +std::uint8_t DrawnAfterTarget(Scene& scene, std::uint64_t address) { + PlaceMultisampleTarget(scene, address); + std::uint8_t color = 0; + try { + color = scene.DrawnColor(); + } catch (...) { + RetireMultisampleTargets(scene); + throw; + } + RetireMultisampleTargets(scene); + return color; +} + +void MultisampleTargetInside(Scene& scene) { + if (!MultisampleTargetsAvailable(scene)) return; + scene.Store(scene.constants, 0, 130); + Require(scene.DrawnColor() == 130 && scene.DrawnColor() == 130, "address draw space reuse: the draws before the multisample target did not read the guest constant"); + const auto built = Builds(); + const auto color = DrawnAfterTarget(scene, scene.constants.Address(MultisampleTargetOffset)); + Require(Builds() == built + 1, "address draw space reuse: a draw after a resident multisample target appeared inside its address space made " + std::to_string(Builds() - built) + " builds instead of 1"); + Require(color == 130, "address draw space reuse: the build after a resident multisample target appeared inside its address space read " + std::to_string(color) + " instead of 130"); +} + +void MultisampleTargetOutside(Scene& scene) { + if (!MultisampleTargetsAvailable(scene)) return; + scene.Store(scene.constants, 0, 160); + Require(scene.DrawnColor() == 160 && scene.DrawnColor() == 160, "address draw space reuse: the draws before the multisample target did not read the guest constant"); + Pages outside{BlockBytes}; + const auto built = Builds(); + const auto color = DrawnAfterTarget(scene, outside.Address()); + Require(color == 160, "address draw space reuse: the draw after a resident multisample target appeared outside its space read " + std::to_string(color) + " instead of 160"); + Require(Builds() == built, "address draw space reuse: a draw after a resident multisample target appeared outside its space made " + std::to_string(Builds() - built) + " builds instead of reusing its cached one"); +} + void Disabled(Scene& scene) { scene.Store(scene.constants, 0, 70); Require(scene.DrawnColor() == 70, "address draw space reuse: the first draw with the reuse off did not read the guest constant"); @@ -441,7 +511,7 @@ struct NamedCase { Case run; }; -constexpr std::array Cases{{ +constexpr std::array Cases{{ {"unchanged", UnchangedInputs}, {"cpu-write", CpuWrite}, {"idle-free", IdleFree}, @@ -449,6 +519,8 @@ constexpr std::array Cases{{ {"throwing-hit", ThrowingHit}, {"moved-vertices", MovedVertices}, {"no-records", NoRecords}, + {"multisample-target-inside", MultisampleTargetInside}, + {"multisample-target-outside", MultisampleTargetOutside}, }}; } From 675e23803dfecb8dabfdba032ce7456a60a7456d Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 31 Oct 2026 20:51:43 +0530 Subject: [PATCH 084/269] refactor(agc): tidy the heap draw and dispatch paths Remove dead draw-pipeline write queries and the duplicate GraphicsContext accessor, extract the direct-heap capture without a goto, share the user-data mask, keep one ring template per cached variant, split the draw stage retry into named helpers, bundle materializeDrawStage's per-draw state, name the heap fragment key classes and descriptor-heap constants, and copy a dispatch's push block only when it is patched. The patched-stage re-materialize now passes the heap-pair refusal like the other two materializeDrawStage calls; it used the defaulted heapPartners = true. --- .../include/Driver/Dispatch/DispatchCache.hpp | 5 +- .../include/Driver/Draw/DrawCache.hpp | 2 + .../include/Driver/Draw/DrawPipeline.hpp | 2 - .../include/Driver/Draw/HeapStages.hpp | 23 +- .../Execution/include/Driver/Driver.hpp | 32 ++- .../Execution/include/VulkanDevice.hpp | 2 +- .../src/Driver/Dispatch/Dispatch.cpp | 6 +- .../src/Driver/Dispatch/VariantValidation.cpp | 2 +- .../Execution/src/Driver/Draw/Draw.cpp | 94 ++++--- .../Execution/src/Driver/Draw/DrawCapture.cpp | 265 +++++++++--------- .../src/Driver/Draw/DrawPipeline.cpp | 18 -- .../src/Driver/Draw/DrawRelocate.cpp | 5 +- .../Execution/src/Driver/Draw/HeapStages.cpp | 45 ++- .../Execution/src/VulkanDevice.cpp | 69 +++-- .../tests/BindlessHeapSlots.cpp | 6 +- .../tests/PresentationPass.cpp | 2 +- .../tests/execution/AddressDrawSpaceReuse.cpp | 6 +- .../tests/execution/SampledCacheBudget.cpp | 4 +- .../tests/execution/StorageCacheBudget.cpp | 8 +- 19 files changed, 333 insertions(+), 263 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp index 8f6056605040..b5891813b69a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp @@ -52,10 +52,7 @@ struct DispatchVariant { std::vector> shaderDataPatches; std::uint64_t userDataMask = ~std::uint64_t{0}; std::shared_ptr vertexInfo; - bool ring = false; - std::shared_ptr> ringAttributes; - std::shared_ptr> ringFlat; - std::shared_ptr>> ringBindings; + std::shared_ptr ringTemplate; std::shared_ptr memory; std::vector captured; diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp index d6316cdbd3f9..6b890d466e0b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp @@ -135,6 +135,8 @@ struct StageCapture { bool ring = false; std::shared_ptr heapWords; std::shared_ptr> heapReadWords; + + bool Cacheable() const { return !direct || ring; } }; struct RelocatableUserWord { diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp index 0f67789f75bd..f2bc4960a534 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp @@ -61,7 +61,6 @@ class DrawPipeline { static bool MetadataPassesPipelined(); static void CountPipelinedMetadataPass(); static std::uint64_t PipelinedMetadataPasses(); - void QueuedWrites(std::vector& out); private: struct Item { Commit commit; @@ -127,7 +126,6 @@ class DrawFinisher { LabelLookup PendingLabel(std::uint64_t address, std::size_t bytes, std::uint64_t& value); bool PendingOverlapsAny(std::span ranges); bool PendingKey(std::uint64_t key, std::uint64_t shape); - void PendingWrites(std::vector& out); enum class DrainSite : std::uint32_t { Lookup, Reads, Packet, Kept, Count }; static void NoteDrain(DrainSite site, bool drained); static std::string DrainText(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index 7117fbee2a79..852c7bc11724 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -21,6 +21,17 @@ bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage); Graphics::HeapStageReason HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex); bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex); +enum class HeapKeyClass { Draw, Compute, HeapVertex }; + +constexpr std::size_t HeapFragmentKey(std::size_t codeOffset, HeapKeyClass keyClass) { + switch (keyClass) { + case HeapKeyClass::Compute: return codeOffset | std::size_t{1} << 61u; + case HeapKeyClass::HeapVertex: return codeOffset | std::size_t{1} << 62u; + case HeapKeyClass::Draw: break; + } + return codeOffset; +} + std::optional HeapFragmentKnown(const void* snapshot, std::size_t codeOffset); void NoteHeapFragment(const void* snapshot, std::size_t codeOffset, bool eligible); bool HeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress = false); @@ -50,10 +61,14 @@ struct HeapStageReads { bool complete = false; }; -std::shared_ptr -MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, - std::uint64_t shaderBase, ShaderRecompiler::HeapStageWords* words = nullptr, - std::shared_ptr* sharedWords = nullptr, HeapStageReads* stageReads = nullptr); +struct HeapStageMaterialized { + std::shared_ptr result; + std::shared_ptr words; + HeapStageReads reads; +}; + +HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, + std::uint64_t shaderBase); void NoteHeapDirect(); void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const ShaderRecompiler::RecompileResult& expected, const ShaderRecompiler::ResourceCapture* expectedCapture = nullptr); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp index d44820bbed8e..c29d70f2b170 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp @@ -57,6 +57,33 @@ inline std::uint32_t ThreadDimensionGroups(std::uint32_t threads, std::uint32_t struct DrawTail; +struct DrawStageContext { + const QueueState& queue; + const Submission& submission; + std::size_t packetOffset; + std::uint64_t traceToken; + const std::vector& programs; + const Graphics::State& graphics; + const ShaderRecompiler::ShaderPixelStageInfo& pixel; + const std::vector>& vertexInfos; + std::vector& memory; + const std::vector& linked; + const std::shared_ptr& localDevice; + ShaderMemory& shaderMemory; + std::vector& stageCaptures; + std::vector& recompiled; + const bool& drawHit; + const std::vector>& matched; + const std::vector>& matchedRegions; + bool profile; + std::uint64_t dumpTarget; + std::uint64_t dumpSlot1; + std::uint64_t& captures; + DrawPhaseTiming& phaseTiming; + std::array& phaseMs; + const std::optional& meshBarycentrics; +}; + class Driver { public: static Driver& Get(); @@ -206,7 +233,10 @@ class Driver { std::shared_ptr decodeDraw(const QueueState& queue, const Submission& submission, const Graphics::Context& context); void resolveDrawDecode(const QueueState& queue, const Submission& submission, const Graphics::Context& context, std::shared_ptr& decode, bool registerKey, std::uint64_t drawKey, bool profile); void lookupDraw(const Submission& submission, const std::shared_ptr& localDevice, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector& programs, const std::vector& roles, const std::vector>& vertexInfos, bool useDrawEntries, bool registerKey, bool profile, std::uint64_t& drawKey, std::shared_ptr& entry, std::vector>& matched, std::vector>& matchedRegions, bool& drawHit, bool& verifyHit, DrawPhaseTiming& phaseTiming, std::array& phaseMs, const std::shared_ptr& dataEntry, DrawDataCandidates& dataCandidates, std::vector& stageData); - std::shared_ptr materializeDrawStage(std::size_t i, std::uint32_t pushOffset, const QueueState& queue, const Submission& submission, std::size_t packetOffset, std::uint64_t traceToken, const std::vector& programs, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector>& vertexInfos, std::vector& memory, const std::vector& linked, const Pm4::DrawParameters& drawParameters, const std::shared_ptr& localDevice, ShaderMemory& shaderMemory, std::vector& stageCaptures, std::vector& recompiled, bool drawHit, const std::vector>& matched, const std::vector>& matchedRegions, bool profile, std::uint64_t dumpTarget, std::uint64_t dumpSlot1, std::uint64_t& captures, DrawPhaseTiming& phaseTiming, std::array& phaseMs, std::string& rejected, const std::optional& meshBarycentrics, bool heapPartners = true); + enum class HeapDirect { Declined, Unmapped, Taken }; + std::shared_ptr materializeDrawStage(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters, bool heapPartners); + HeapDirect materializeHeapDirect(const DrawStageContext& context, std::size_t i, const ShaderRecompiler::PreparedShaderInvocation& invocation, const ShaderRecompiler::RecompileRequest& request, PerformanceTimer& timing); + static std::runtime_error stageFailure(const DrawProgram& program, const ShaderRecompiler::RecompileRequest& request, const std::exception& error, std::span regions); static void recordStageDataPositions(DispatchVariant& variant, const ShaderRecompiler::ResourceCapture& capture, const std::vector& decodeReads); void cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawParameters& drawParameters, const std::optional& indirectCpu, const std::vector& programs, const std::vector& stageCaptures, const std::vector>& vertexInfos, const std::vector>& decodeReads, bool verifyHit, const std::vector>& matched, const std::vector& stageData, std::vector>& fresh, std::uint64_t drawKey, bool registerKey, const std::shared_ptr& decode, DrawPhaseTiming& phaseTiming, const std::vector& reused, const std::shared_ptr& entry, std::uint64_t shapeKey, bool shapeNeedsEntry = false); static bool drawPrecheck(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp index ab0428636fee..4eb80e805010 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp @@ -371,7 +371,7 @@ class VulkanDevice { IndirectDrawSupport DrawIndirectSupport() const; void EnqueueDraw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots = {}); bool PrebuildGraphicsLibraries(const Graphics::ShaderStages& stages, std::span shaders); - Graphics::Context GraphicsContext() const { return graphicsContext(); } + const Graphics::Context& contextRef(std::optional& scratch) const; public: // The device's Graphics::Context: a copy of the one built at setup (its instance functions diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index ee393713b9eb..7c4f37b1d660 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -189,8 +189,8 @@ void Driver::dispatch(QueueState& queue, std::span packet, localDevice->ComputeTarget((packet[4] & 0x8000u) != 0 ? 32u : 64u), {0, 0, 0, threadGroup != std::array{} ? 0u : 128u} }; - constexpr std::size_t computeHeapKey = std::size_t{1} << 61u; - if (request.target.gpuResolvedImages && (HeapRefused() || HeapStageExcluded(ShaderRecompiler::ShaderStage::Compute) || HeapFragmentKnown(&snapshot, codeOffset | computeHeapKey) == std::optional(false))) request.target.gpuResolvedImages = false; + const std::size_t computeHeapKey = HeapFragmentKey(codeOffset, HeapKeyClass::Compute); + if (request.target.gpuResolvedImages && (HeapRefused() || HeapStageExcluded(ShaderRecompiler::ShaderStage::Compute) || HeapFragmentKnown(&snapshot, computeHeapKey) == std::optional(false))) request.target.gpuResolvedImages = false; static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; static double captureMs = 0, keyMs = 0, recompileMs = 0, deviceMs = 0; static std::uint64_t cacheHits = 0; @@ -401,7 +401,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, compiledResult = invocation.Materialize(*capture); if (compiledResult->gpuResolvedImages && !HeapStageMappable(*compiledResult, compiledResult->workgroupMemoryDwords != 0)) { Graphics::NoteHeapFallback(Graphics::HeapFallback::DispatchUnmapped); - NoteHeapFragment(&snapshot, codeOffset | computeHeapKey, false); + NoteHeapFragment(&snapshot, computeHeapKey, false); request.target.gpuResolvedImages = false; invocation = InvocationFor(snapshot, codeOffset, request); capture = shaderMemory->Capture(invocation); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp index 87495ad34df0..ee91c8402656 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp @@ -21,7 +21,7 @@ void Driver::appendEntryRegions(const DispatchVariant& variant, std::vector Driver::patchDataWords(const DispatchVariant& variant, const std::vector& words) { - if (variant.ringFlat != nullptr) return variant.compiled; + if (variant.ringTemplate != nullptr && !variant.ringTemplate->flattenedSrt.empty()) return variant.compiled; auto patched = std::make_shared(*variant.compiled); auto& descriptor = patched->bindings[variant.flatBinding].guestDescriptor; for (std::size_t k = 0; k < variant.dataPositions.size(); ++k) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 43e47f8e2c9f..1ae18eae8f3c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -202,6 +203,42 @@ void noteFinisherHandOff(bool handed) { namespace { +bool MixesHeapAndGuestStages(std::span stages, std::span programResults) { + const auto guest = [&](const Graphics::CompiledShader& stage) { return std::ranges::find(programResults, stage.program) != programResults.end(); }; + return std::ranges::any_of(stages, [](const Graphics::CompiledShader& stage) { return stage.program->gpuResolvedImages; }) && std::ranges::any_of(stages, [&](const Graphics::CompiledShader& stage) { return guest(stage) && !stage.program->gpuResolvedImages; }); +} + +class DrawStageCheckpoint { +public: + DrawStageCheckpoint(std::vector& stages, std::vector>& compiledStages, std::uint32_t& pushCursorBytes, Pm4::DrawParameters& drawParameters, ShaderRecompiler::ShaderPixelStageInfo& pixel, bool keepCopies) + : stages(stages), compiledStages(compiledStages), pushCursorBytes(pushCursorBytes), drawParameters(drawParameters), pixel(pixel), stagesBefore(stages.size()), compiledBefore(compiledStages.size()), pushBefore(pushCursorBytes), + parametersBefore(keepCopies ? std::optional(drawParameters) : std::nullopt), pixelBefore(keepCopies ? std::optional(pixel) : std::nullopt) {} + + void Restore() { + stages.resize(stagesBefore); + compiledStages.resize(compiledBefore); + pushCursorBytes = pushBefore; + drawParameters = *parametersBefore; + pixel = *pixelBefore; + } + +private: + std::vector& stages; + std::vector>& compiledStages; + std::uint32_t& pushCursorBytes; + Pm4::DrawParameters& drawParameters; + ShaderRecompiler::ShaderPixelStageInfo& pixel; + std::size_t stagesBefore; + std::size_t compiledBefore; + std::uint32_t pushBefore; + std::optional parametersBefore; + std::optional pixelBefore; +}; + +} + +namespace { + enum class HeldReason : std::size_t { Known, NoDecode, Size, NullVertex, NullFragment, NullOther, Bda, Buffer, Storage, Count }; std::array, static_cast(HeldReason::Count)> heldReasons{}; @@ -886,17 +923,18 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { require(index < user.size(), "a ring vertex template reads a user word the draw does not have"); words->userData.push_back(user[index]); } - if (variant.ringAttributes != nullptr) words->vertexAttributes = *variant.ringAttributes; - if (variant.ringFlat != nullptr) { - words->flattenedSrt = *variant.ringFlat; + const auto& ringTemplate = *variant.ringTemplate; + words->vertexAttributes = ringTemplate.vertexAttributes; + if (!ringTemplate.flattenedSrt.empty()) { + words->flattenedSrt = ringTemplate.flattenedSrt; if (&variant == matched[i].get() && stageData[i].compiled != nullptr) { for (std::size_t k = 0; k < variant.dataPositions.size(); ++k) { if (variant.dataSlots[k] < words->flattenedSrt.size()) words->flattenedSrt[variant.dataSlots[k]] = stageData[i].words[variant.dataPositions[k]]; } } } - if (variant.ringBindings != nullptr) { - words->bindings = *variant.ringBindings; + if (!ringTemplate.bindings.empty()) { + words->bindings = ringTemplate.bindings; require(words->bindings.size() == variant.compiled->bindings.size(), "a ring vertex hit's bindings differ in number from its template"); for (std::size_t index = 0; index < words->bindings.size(); ++index) { const auto role = variant.compiled->bindings[index].role; @@ -924,7 +962,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { std::vector words; freshRuns(i, runs, words); const auto& compiled = *stageCaptures[i].compiled; - if (kept.ring) VerifyRingWords(*kept.compiled, *buildRingWords(i, kept), *stageCaptures[i].compiled, stageCaptures[i].heapWords.get()); + if (kept.ringTemplate != nullptr) VerifyRingWords(*kept.compiled, *buildRingWords(i, kept), *stageCaptures[i].compiled, stageCaptures[i].heapWords.get()); const char* what = runs != kept.runs ? "runs" : words != kept.words ? "words" : vertexInfos[i].has_value() != (kept.vertexInfo != nullptr) || (vertexInfos[i] && !sameVertexInfo(*vertexInfos[i], *kept.vertexInfo)) ? "vertex stage info" : compiled.variantId != kept.compiled->variantId ? "variant" : compiled.pushConstants != kept.compiled->pushConstants ? "push constants" : nullptr; ++dataVerified; if (what == nullptr) return; @@ -949,7 +987,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { throw std::runtime_error(message); }; const auto ringWords = [&](std::size_t i) { - if (!matched[i]->ring) return; + if (matched[i]->ringTemplate == nullptr) return; stageCaptures[i].heapWords = buildRingWords(i, *matched[i]); stageCaptures[i].direct = true; stageCaptures[i].ring = true; @@ -964,6 +1002,10 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { for (const auto& program : programs) heapPair = (heapPair ^ reinterpret_cast(program.snapshot.get()) ^ (static_cast(program.codeOffset) << 1u)) * 0x100000001b3ull; const bool heapPairRefused = heapCheck && HeapPairRefused(heapPair); bool heapRetry = false; + const DrawStageContext stageContext{queue, submission, packetOffset, trace.token, programs, graphics, pixel, vertexInfos, memory, linked, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, meshBarycentrics}; + const auto candidateForStage = [&](std::size_t i, bool afterHeap) { + return std::find_if(dataCandidates[i].begin(), dataCandidates[i].end(), [&](const auto& kept) { return kept.first->pushOffset == pushCursorBytes && (!afterHeap || kept.first->compiled->gpuResolvedImages); }); + }; const auto runStages = [&]() -> std::optional { for (std::size_t i = 0; i < programs.size(); ++i) { if (roles[i] == Role::GeometryBack) continue; @@ -982,7 +1024,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { matched[i] = nullptr; matchedRegions[i].clear(); } - const auto candidate = reused[i] ? dataCandidates[i].end() : std::find_if(dataCandidates[i].begin(), dataCandidates[i].end(), [&](const auto& kept) { return kept.first->pushOffset == pushCursorBytes && (!afterHeap || kept.first->compiled->gpuResolvedImages); }); + const auto candidate = reused[i] ? dataCandidates[i].end() : candidateForStage(i, afterHeap); if (reused[i]) { programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); @@ -1003,10 +1045,10 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { break; } } - compiledStages.push_back(materializeDrawStage(i, pushCursorBytes, queue, submission, packetOffset, trace.token, programs, graphics, pixel, vertexInfos, memory, linked, drawParameters, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics, !heapPairRefused)); + compiledStages.push_back(materializeDrawStage(stageContext, i, pushCursorBytes, drawParameters, !heapPairRefused)); if (!rejected.empty()) return DrawVerdict::Rejected; programResults[i] = compiledStages.back().get(); - if (verifyHit && matched[i] != nullptr && matched[i]->ring) VerifyRingWords(*matched[i]->compiled, *buildRingWords(i, *matched[i]), *programResults[i], stageCaptures[i].heapWords.get()); + if (verifyHit && matched[i] != nullptr && matched[i]->ringTemplate != nullptr) VerifyRingWords(*matched[i]->compiled, *buildRingWords(i, *matched[i]), *programResults[i], stageCaptures[i].heapWords.get()); if (candidate != dataCandidates[i].end()) verifyDataStage(i, *candidate->first); if (stageData[i].compiled != nullptr && verifyDrawDataHits()) verifyStageData(i); } @@ -1033,32 +1075,16 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { } return std::nullopt; }; - const auto mixedHeap = [&] { - const auto guest = [&](const Graphics::CompiledShader& stage) { return std::ranges::find(programResults, stage.program) != programResults.end(); }; - return std::ranges::any_of(stages, [](const Graphics::CompiledShader& stage) { return stage.program->gpuResolvedImages; }) && std::ranges::any_of(stages, [&](const Graphics::CompiledShader& stage) { return guest(stage) && !stage.program->gpuResolvedImages; }); - }; - const auto stagesBefore = stages.size(); - const auto compiledBefore = compiledStages.size(); - const auto pushBefore = pushCursorBytes; - const auto parametersBefore = heapCheck ? std::optional(drawParameters) : std::nullopt; - const auto pixelBefore = heapCheck ? std::optional(pixel) : std::nullopt; + DrawStageCheckpoint checkpoint(stages, compiledStages, pushCursorBytes, drawParameters, pixel, heapCheck); if (const auto verdict = runStages()) return *verdict; - for (std::uint32_t retry = 0; heapCheck && mixedHeap(); ++retry) { + for (std::uint32_t retry = 0; heapCheck && MixesHeapAndGuestStages(stages, programResults); ++retry) { require(retry < 2u, "a draw mixes GPU-mode and per-draw stages after taking the per-draw path"); Graphics::NoteHeapFallback(retry == 0u ? Graphics::HeapFallback::DrawMixedRetry : Graphics::HeapFallback::DrawRefusedPair); if (retry == 1u) RefuseHeapPair(heapPair); - for (std::size_t i = 0; i < programs.size(); ++i) { - if (reused[i] && programResults[i] != nullptr && !programResults[i]->gpuResolvedImages) { - Graphics::NoteHeapFallback(Graphics::HeapFallback::DrawMixedReused); - break; - } - } + const auto reusedGuest = [&](std::size_t i) { return reused[i] && programResults[i] != nullptr && !programResults[i]->gpuResolvedImages; }; + if (std::ranges::any_of(std::views::iota(std::size_t{0}, programs.size()), reusedGuest)) Graphics::NoteHeapFallback(Graphics::HeapFallback::DrawMixedReused); heapRetry = retry == 0u; - stages.resize(stagesBefore); - compiledStages.resize(compiledBefore); - pushCursorBytes = pushBefore; - drawParameters = *parametersBefore; - pixel = *pixelBefore; + checkpoint.Restore(); std::fill(programResults.begin(), programResults.end(), nullptr); for (std::size_t i = 0; i < programs.size(); ++i) { if (!reused[i]) stageCaptures[i] = {}; @@ -1089,7 +1115,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { }; for (std::size_t i = 0; i < programs.size(); ++i) { const auto& capture = stageCaptures[i]; - if (reused[i] || capture.compiled == nullptr || (capture.direct && !capture.ring) || !CacheableResult(*capture.compiled)) continue; + if (reused[i] || capture.compiled == nullptr || !capture.Cacheable() || !CacheableResult(*capture.compiled)) continue; stored = true; const auto& words = programs[i].userData; for (std::size_t w = 0; w < words.size(); ++w) { @@ -1161,7 +1187,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { if (programResults[0]->meshBarycentrics != meshBarycentrics) { const auto pushBytes = programResults[0]->pushConstants.size(); const auto exports = programResults[0]->parameterExports; - compiledStages.push_back(materializeDrawStage(0, pushOffsets[0], queue, submission, packetOffset, traceToken, programs, graphics, pixel, vertexInfos, memory, linked, drawParameters, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics, !heapPairRefused)); + compiledStages.push_back(materializeDrawStage(stageContext, 0, pushOffsets[0], drawParameters, !heapPairRefused)); if (!rejected.empty()) return DrawVerdict::Rejected; programResults[0] = compiledStages.back().get(); stages[0].program = programResults[0]; @@ -1281,7 +1307,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { auto& result = results[resultIndex[programIndex]]; const auto pushBytes = result.pushConstants.size(); decodeVertexInfo(programIndex); - result = *materializeDrawStage(programIndex, pushOffsets[programIndex], queue, submission, packetOffset, trace.token, programs, graphics, pixel, vertexInfos, memory, linked, programs[programIndex].binary.stage == Stage::TessellationControl || programs[programIndex].binary.stage == Stage::TessellationEvaluation ? direct : drawParameters, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics); + result = *materializeDrawStage(stageContext, programIndex, pushOffsets[programIndex], programs[programIndex].binary.stage == Stage::TessellationControl || programs[programIndex].binary.stage == Stage::TessellationEvaluation ? direct : drawParameters, !heapPairRefused); if (!rejected.empty()) return DrawVerdict::Rejected; require(result.pushConstants.size() == pushBytes, "patched program changed its push constant layout"); for (auto& stage : stages) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 91b6ea29aa0c..bf3dfe06b166 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -48,6 +48,19 @@ void TraceMaterializationFailure(std::uint64_t token, const Submission& submissi } } +std::uint64_t UserDataMask(const DrawProgram& program, const std::optional& vertexInfo, std::uint64_t walked, const ShaderRecompiler::RecompileResult& compiled) { + std::uint64_t mask = walked | compiled.userDataRegisterReads; + const auto& tail = program.snapshot->userDataTailRegister; + if (tail && *tail >= program.firstUserSgpr) { + const auto index = *tail - program.firstUserSgpr; + mask |= index + 1u < 64u ? std::uint64_t{3} << index : ~std::uint64_t{0}; + } + if (vertexInfo) { + for (const auto reg : {static_cast(vertexInfo->fetchAttribReg), static_cast(vertexInfo->fetchBufferReg)}) mask |= reg + 1u < 64u ? std::uint64_t{3} << reg : ~std::uint64_t{0}; + } + return mask; +} + void TraceShaderRequestFailure(std::uint64_t token, const Submission& submission, std::size_t packetOffset, const DrawProgram& program, const std::exception_ptr& failure) noexcept { if (token == 0) return; try { @@ -71,46 +84,103 @@ void TraceShaderRequestFailure(std::uint64_t token, const Submission& submission } -std::shared_ptr Driver::materializeDrawStage(std::size_t i, std::uint32_t pushOffset, const QueueState& queue, const Submission& submission, std::size_t packetOffset, std::uint64_t traceToken, const std::vector& programs, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector>& vertexInfos, std::vector& memory, const std::vector& linked, const Pm4::DrawParameters& drawParameters, const std::shared_ptr& localDevice, ShaderMemory& shaderMemory, std::vector& stageCaptures, std::vector& recompiled, bool drawHit, const std::vector>& matched, const std::vector>& matchedRegions, bool profile, std::uint64_t dumpTarget, std::uint64_t dumpSlot1, std::uint64_t& captures, DrawPhaseTiming& phaseTiming, std::array& phaseMs, std::string& rejected, const std::optional& meshBarycentrics, bool heapPartners) try { +Driver::HeapDirect Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t i, const ShaderRecompiler::PreparedShaderInvocation& invocation, const ShaderRecompiler::RecompileRequest& request, PerformanceTimer& timing) { + const auto& program = context.programs[i]; + auto& stageCapture = context.stageCaptures[i]; + HeapStageMaterialized materialized; + Graphics::HeapCostScope callCost(Graphics::HeapCost::HeapStageCall); + try { + materialized = MaterializeHeapStage(invocation, program.userData, program.binary.codeAddress); + } catch (const std::exception& error) { + throw stageFailure(program, request, error, request.context.memory); + } + callCost.Stop(); + Graphics::HeapCostScope finishCost(Graphics::HeapCost::StageFinish); + if (materialized.result == nullptr) return HeapDirect::Declined; + if (!HeapDrawStageMappable(*materialized.result, program.binary.stage)) return HeapDirect::Unmapped; + NoteHeapDirect(); + stageCapture.compiled = std::move(materialized.result); + stageCapture.heapWords = stageCapture.compiled->heapTemplateId != 0 ? std::const_pointer_cast(std::move(materialized.words)) : nullptr; + if (SampleHeapStageVerify()) { + const auto fullCapture = context.shaderMemory.Capture(invocation); + const auto expected = invocation.Materialize(*fullCapture); + static_cast(context.shaderMemory.TakeRecentRegions()); + NoteHeapDirectVerify(stageCapture.heapWords != nullptr ? *PatchedHeapResult(*stageCapture.compiled, *stageCapture.heapWords) : *stageCapture.compiled, *expected, fullCapture.get()); + } + stageCapture.regions.clear(); + stageCapture.direct = true; + auto& reads = materialized.reads; + if (reads.complete) { + auto owned = std::make_shared>(std::move(reads.values)); + std::size_t cursor = 0; + for (const auto& [begin, end] : reads.ranges) { + const auto count = static_cast((end - begin) / sizeof(std::uint32_t)); + stageCapture.regions.push_back({begin, std::as_bytes(std::span(owned->data() + cursor, count))}); + cursor += count; + } + stageCapture.heapReadWords = std::move(owned); + stageCapture.userDataUse = reads.userDataUse; + stageCapture.capture = std::move(reads.capture); + stageCapture.userDataMask = UserDataMask(program, context.vertexInfos[i], reads.userDataUse.asValue | reads.userDataUse.asBase, *stageCapture.compiled); + stageCapture.ring = true; + } + context.recompiled[i] = true; + timing.Mark("heap_direct"); + context.phaseTiming.Phase(DrawRowRecompile); + return HeapDirect::Taken; +} + +std::runtime_error Driver::stageFailure(const DrawProgram& program, const ShaderRecompiler::RecompileRequest& request, const std::exception& error, std::span regions) { + static const bool dumpShaders = std::getenv("APS5_DUMP_SHADERS") != nullptr; + std::string dump; + if (dumpShaders) { + try { + auto failed = request; + failed.context.memory = regions; + dump = dumpRequest(program.binary.codeAddress, failed, "_failed"); + } catch (...) {} + } + std::ostringstream where; + where << "shader 0x" << std::hex << program.binary.codeAddress << " stage " << std::dec << static_cast(program.binary.stage); + if (!dump.empty()) where << " (" << dump << ")"; + where << ": "; + return std::runtime_error(where.str() + error.what()); +} + +std::shared_ptr Driver::materializeDrawStage(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters, bool heapPartners) try { PerformanceTimer timing("Shader.DrawStage"); using Stage = ShaderRecompiler::ShaderStage; - phaseTiming.Phase(DrawRowVectors); - const auto& program = programs[i]; - const auto tailMask = [&]() -> std::uint64_t { - const auto& tail = program.snapshot->userDataTailRegister; - if (!tail || *tail < program.firstUserSgpr) return 0; - const auto index = *tail - program.firstUserSgpr; - return index + 1u < 64u ? std::uint64_t{3} << index : ~std::uint64_t{0}; - }; + context.phaseTiming.Phase(DrawRowVectors); + const auto& program = context.programs[i]; Graphics::HeapCostScope prepareCost(Graphics::HeapCost::StagePrepare); - const auto waveSize = Graphics::StageWaveSize(graphics.stages, program.binary.stage); + const auto waveSize = Graphics::StageWaveSize(context.graphics.stages, program.binary.stage); ShaderRecompiler::RecompileRequest request{ program.binary, - {waveSize, program.firstUserSgpr, program.userData, std::nullopt, program.binary.stage == Stage::Fragment ? std::optional(pixel) : std::nullopt, vertexInfos[i], memory, RegisteredFloatMode(*program.snapshot)}, - localDevice->Target(), - {0, 0, pushOffset, Graphics::StagePushLimit(graphics.stages, pushOffset, graphics.depthRemap.mode != 0u) - pushOffset % Graphics::PipelinePushSlotBytes}, - ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, linked, Graphics::StageMeshConfiguration(graphics.stages, program.binary.stage), graphics.stages.tessellation, {drawParameters.indexAddress, drawParameters.indexCount, drawParameters.indexSize, drawParameters.instanceCount}, program.binary.stage == Stage::Mesh ? meshBarycentrics : std::nullopt} + {waveSize, program.firstUserSgpr, program.userData, std::nullopt, program.binary.stage == Stage::Fragment ? std::optional(context.pixel) : std::nullopt, context.vertexInfos[i], context.memory, RegisteredFloatMode(*program.snapshot)}, + context.localDevice->Target(), + {0, 0, pushOffset, Graphics::StagePushLimit(context.graphics.stages, pushOffset, context.graphics.depthRemap.mode != 0u) - pushOffset % Graphics::PipelinePushSlotBytes}, + ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, context.linked, Graphics::StageMeshConfiguration(context.graphics.stages, program.binary.stage), context.graphics.stages.tessellation, {drawParameters.indexAddress, drawParameters.indexCount, drawParameters.indexSize, drawParameters.instanceCount}, program.binary.stage == Stage::Mesh ? context.meshBarycentrics : std::nullopt} }; - if (graphics.depthRemap.mode != 0u && pushOffset < Graphics::PipelinePushSlotBytes) { + if (context.graphics.depthRemap.mode != 0u && pushOffset < Graphics::PipelinePushSlotBytes) { request.layout.pushConstantSizeBytes = std::min(request.layout.pushConstantSizeBytes, ShaderRecompiler::DepthRemapPushOffsetBytes - pushOffset); } - const auto waitedBefore = traceCapSync() || profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0; + const auto waitedBefore = traceCapSync() || context.profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0; const bool heapCandidate = heapPartners && (program.binary.stage == Stage::Fragment || HeapPreRasterStage(program.binary.stage)) && !HeapStageExcluded(program.binary.stage) && HeapFragmentsEnabled(); const auto fragmentOnHeap = [&] { - const auto fragment = std::find_if(programs.begin(), programs.end(), [](const DrawProgram& candidate) { return candidate.binary.stage == Stage::Fragment; }); - if (fragment == programs.end()) return true; + const auto fragment = std::find_if(context.programs.begin(), context.programs.end(), [](const DrawProgram& candidate) { return candidate.binary.stage == Stage::Fragment; }); + if (fragment == context.programs.end()) return true; const auto known = HeapFragmentKnown(fragment->snapshot.get(), fragment->codeOffset); return known.has_value() ? *known : PreparedHeapStage(*fragment->snapshot, fragment->codeOffset); }; const bool heapVertex = request.target.descriptorMemory && HeapPreRasterStage(program.binary.stage) && fragmentOnHeap(); - const auto heapKey = program.codeOffset | (heapVertex ? std::size_t{1} << 62u : std::size_t{0}); + const auto heapKey = HeapFragmentKey(program.codeOffset, heapVertex ? HeapKeyClass::HeapVertex : HeapKeyClass::Draw); const auto heapKnown = heapCandidate ? HeapFragmentKnown(program.snapshot.get(), heapKey) : std::nullopt; if (heapKnown.value_or(false)) request.target.gpuResolvedImages = true; const auto invocationFor = [&] { try { return InvocationFor(*program.snapshot, program.codeOffset, request); } catch (...) { - TraceShaderRequestFailure(traceToken, submission, packetOffset, program, std::current_exception()); + TraceShaderRequestFailure(context.traceToken, context.submission, context.packetOffset, program, std::current_exception()); throw; } }; @@ -138,133 +208,73 @@ std::shared_ptr Driver::materializeDraw Graphics::NoteHeapStageReason(stageReason); prepareCost.Stop(); timing.Mark("prepared_invocation"); - auto& stageCapture = stageCaptures[i]; + auto& stageCapture = context.stageCaptures[i]; stageCapture.direct = false; stageCapture.ring = false; stageCapture.heapReadWords.reset(); stageCapture.capture.reset(); stageCapture.forgetSerial = GuestMemory::ForgetSerial(); stageCapture.pushOffset = pushOffset; - const auto named = [&](const std::exception& error, std::span regions) { - static const bool dumpShaders = std::getenv("APS5_DUMP_SHADERS") != nullptr; - std::string dump; - if (dumpShaders) { - try { - auto failed = request; - failed.context.memory = regions; - dump = dumpRequest(program.binary.codeAddress, failed, "_failed"); - } catch (...) {} - } - std::ostringstream where; - where << "shader 0x" << std::hex << program.binary.codeAddress << " stage " << std::dec << static_cast(program.binary.stage); - if (!dump.empty()) where << " (" << dump << ")"; - where << ": "; - return std::runtime_error(where.str() + error.what()); - }; const auto unmapped = [&] { Graphics::NoteHeapFallback(Graphics::HeapFallback::DrawUnmapped); NoteHeapFragment(program.snapshot.get(), heapKey, false); - return materializeDrawStage(i, pushOffset, queue, submission, packetOffset, traceToken, programs, graphics, pixel, vertexInfos, memory, linked, drawParameters, localDevice, shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, rejected, meshBarycentrics, heapPartners); + return materializeDrawStage(context, i, pushOffset, drawParameters, heapPartners); }; if (request.target.gpuResolvedImages) { - auto words = std::make_shared(); - std::shared_ptr reusedWords; - HeapStageReads reads; - decltype(MaterializeHeapStage(invocation, program.userData, program.binary.codeAddress, words.get(), &reusedWords, &reads)) direct; - Graphics::HeapCostScope callCost(Graphics::HeapCost::HeapStageCall); - try { - direct = MaterializeHeapStage(invocation, program.userData, program.binary.codeAddress, words.get(), &reusedWords, &reads); - } catch (const std::exception& error) { - throw named(error, request.context.memory); - } - callCost.Stop(); - Graphics::HeapCostScope finishCost(Graphics::HeapCost::StageFinish); - if (direct == nullptr) goto heapCapture; - if (!HeapDrawStageMappable(*direct, program.binary.stage)) return unmapped(); - NoteHeapDirect(); - stageCapture.compiled = std::move(direct); - if (reusedWords != nullptr) words = std::const_pointer_cast(std::move(reusedWords)); - stageCapture.heapWords = stageCapture.compiled->heapTemplateId != 0 ? std::move(words) : nullptr; - if (SampleHeapStageVerify()) { - const auto fullCapture = shaderMemory.Capture(invocation); - const auto expected = invocation.Materialize(*fullCapture); - static_cast(shaderMemory.TakeRecentRegions()); - NoteHeapDirectVerify(stageCapture.heapWords != nullptr ? *PatchedHeapResult(*stageCapture.compiled, *stageCapture.heapWords) : *stageCapture.compiled, *expected, fullCapture.get()); + switch (materializeHeapDirect(context, i, invocation, request, timing)) { + case HeapDirect::Taken: return stageCapture.compiled; + case HeapDirect::Unmapped: return unmapped(); + case HeapDirect::Declined: break; } - stageCapture.regions.clear(); - stageCapture.direct = true; - if (reads.complete) { - auto owned = std::make_shared>(std::move(reads.values)); - std::size_t cursor = 0; - for (const auto& [begin, end] : reads.ranges) { - const auto count = static_cast((end - begin) / sizeof(std::uint32_t)); - stageCapture.regions.push_back({begin, std::as_bytes(std::span(owned->data() + cursor, count))}); - cursor += count; - } - stageCapture.heapReadWords = std::move(owned); - stageCapture.userDataUse = reads.userDataUse; - stageCapture.capture = std::move(reads.capture); - auto mask = reads.userDataUse.asValue | reads.userDataUse.asBase | stageCapture.compiled->userDataRegisterReads | tailMask(); - if (vertexInfos[i]) { - for (const auto reg : {static_cast(vertexInfos[i]->fetchAttribReg), static_cast(vertexInfos[i]->fetchBufferReg)}) mask |= reg + 1u < 64u ? std::uint64_t{3} << reg : ~std::uint64_t{0}; - } - stageCapture.userDataMask = mask; - stageCapture.ring = true; - } - recompiled[i] = true; - timing.Mark("heap_direct"); - phaseTiming.Phase(DrawRowRecompile); - return stageCapture.compiled; } -heapCapture: const auto capture = [&] { const SampledReadScope sampling(evidenceReads); try { - return CaptureInvocation(shaderMemory, *program.snapshot, program.codeOffset, request, invocation); + return CaptureInvocation(context.shaderMemory, *program.snapshot, program.codeOffset, request, invocation); } catch (const std::exception& error) { - throw named(error, shaderMemory.Regions()); + throw stageFailure(program, request, error, context.shaderMemory.Regions()); } }(); - stageCapture.regions = shaderMemory.TakeRecentRegions(); - stageCapture.supplied = shaderMemory.SuppliedBlocks(); + stageCapture.regions = context.shaderMemory.TakeRecentRegions(); + stageCapture.supplied = context.shaderMemory.SuppliedBlocks(); stageCapture.userDataUse = capture->userDataUse; - recompiled[i] = true; - memory = shaderMemory.Regions(); + context.recompiled[i] = true; + context.memory = context.shaderMemory.Regions(); - for (std::size_t j = 0; j < programs.size(); ++j) { - if (matched[j] != nullptr && !recompiled[j] && (drawHit || j < i)) memory.insert(memory.end(), matchedRegions[j].begin(), matchedRegions[j].end()); + for (std::size_t j = 0; j < context.programs.size(); ++j) { + if (context.matched[j] != nullptr && !context.recompiled[j] && (context.drawHit || j < i)) context.memory.insert(context.memory.end(), context.matchedRegions[j].begin(), context.matchedRegions[j].end()); } - request.context.memory = memory; - if (traceCapSync()) traceCapture("draw-capture", program.binary.codeAddress, submission.queue, memory, Graphics::Recorder::ThreadWaitedMs() - waitedBefore); - if (profile) { - ++captures; - phaseTiming.Phase(DrawRowCapture); + request.context.memory = context.memory; + if (traceCapSync()) traceCapture("draw-capture", program.binary.codeAddress, context.submission.queue, context.memory, Graphics::Recorder::ThreadWaitedMs() - waitedBefore); + if (context.profile) { + ++context.captures; + context.phaseTiming.Phase(DrawRowCapture); - const auto waited = std::min(Graphics::Recorder::ThreadWaitedMs() - waitedBefore, phaseMs[DrawRowCapture]); - phaseMs[DrawRowCapture] -= waited; - phaseMs[DrawRowCaptureHookWaits] += waited; + const auto waited = std::min(Graphics::Recorder::ThreadWaitedMs() - waitedBefore, context.phaseMs[DrawRowCapture]); + context.phaseMs[DrawRowCapture] -= waited; + context.phaseMs[DrawRowCaptureHookWaits] += waited; } - if (dumpTarget != 0) { + if (context.dumpTarget != 0) { - const auto slot0 = (static_cast(readRegister(queue.context, 0x390)) << 40u) | (static_cast(readRegister(queue.context, 0x318)) << 8u); - if ((graphics.hasColorTarget && graphics.color.address == dumpTarget) || slot0 == dumpTarget || program.binary.codeAddress == dumpTarget) static_cast(dumpRequest(program.binary.codeAddress, request)); + const auto slot0 = (static_cast(readRegister(context.queue.context, 0x390)) << 40u) | (static_cast(readRegister(context.queue.context, 0x318)) << 8u); + if ((context.graphics.hasColorTarget && context.graphics.color.address == context.dumpTarget) || slot0 == context.dumpTarget || program.binary.codeAddress == context.dumpTarget) static_cast(dumpRequest(program.binary.codeAddress, request)); } - if (dumpSlot1 != 0) { - const auto value = [&](std::uint32_t offset) -> std::uint64_t { const auto it = queue.context.find(offset); return it == queue.context.end() ? 0u : it->second; }; + if (context.dumpSlot1 != 0) { + const auto value = [&](std::uint32_t offset) -> std::uint64_t { const auto it = context.queue.context.find(offset); return it == context.queue.context.end() ? 0u : it->second; }; const auto slot1 = (value(0x391) << 40u) | (value(0x327) << 8u); - if (slot1 == dumpSlot1) { + if (slot1 == context.dumpSlot1) { static_cast(dumpRequest(program.binary.codeAddress, request)); if (std::FILE* file = std::fopen("draw_slot1.regs", "w")) { - for (const auto& [offset, value] : queue.context) std::fprintf(file, "context %x %08x\n", offset, value); - for (const auto& [offset, value] : queue.userConfig) std::fprintf(file, "uconfig %x %08x\n", offset, value); - for (const auto& [offset, value] : queue.shader) std::fprintf(file, "shader %x %08x\n", offset, value); + for (const auto& [offset, value] : context.queue.context) std::fprintf(file, "context %x %08x\n", offset, value); + for (const auto& [offset, value] : context.queue.userConfig) std::fprintf(file, "uconfig %x %08x\n", offset, value); + for (const auto& [offset, value] : context.queue.shader) std::fprintf(file, "shader %x %08x\n", offset, value); std::fclose(file); } } } - phaseTiming.Phase(DrawRowCapture); + context.phaseTiming.Phase(DrawRowCapture); timing.Mark("capture_resources"); stageCapture.heapWords.reset(); @@ -282,34 +292,30 @@ std::shared_ptr Driver::materializeDraw try { stageCapture.compiled = invocation.Materialize(*capture); } catch (const std::exception& error) { - TraceMaterializationFailure(traceToken, submission, packetOffset, i, "capture-or-materialize", std::current_exception()); - throw named(error, request.context.memory); + TraceMaterializationFailure(context.traceToken, context.submission, context.packetOffset, i, "capture-or-materialize", std::current_exception()); + throw stageFailure(program, request, error, request.context.memory); } } if (stageCapture.compiled->gpuResolvedImages && !HeapDrawStageMappable(*stageCapture.compiled, program.binary.stage)) return unmapped(); stageCapture.capture = capture; timing.Mark("materialize"); const auto walked = capture->userDataUse.asValue | capture->userDataUse.asBase; - auto mask = walked == 0 ? ~std::uint64_t{0} : walked | stageCapture.compiled->userDataRegisterReads | tailMask(); - if (vertexInfos[i]) { - for (const auto reg : {static_cast(vertexInfos[i]->fetchAttribReg), static_cast(vertexInfos[i]->fetchBufferReg)}) { - mask |= reg + 1u < 64u ? std::uint64_t{3} << reg : ~std::uint64_t{0}; - } - } - stageCapture.userDataMask = mask; - phaseTiming.Phase(DrawRowRecompile); + stageCapture.userDataMask = walked == 0 ? ~std::uint64_t{0} : UserDataMask(program, context.vertexInfos[i], walked, *stageCapture.compiled); + context.phaseTiming.Phase(DrawRowRecompile); return stageCapture.compiled; } catch (const std::exception& error) { if (!SkipRefusedDraws()) throw; - throw RefusedDraw(programs[i].binary.codeAddress, error.what()); + throw RefusedDraw(context.programs[i].binary.codeAddress, error.what()); } + + void Driver::recordStageDataPositions(DispatchVariant& variant, const ShaderRecompiler::ResourceCapture& capture, const std::vector& decodeReads) { const auto& compiled = *variant.compiled; for (std::size_t b = 0; b < compiled.bindings.size(); ++b) { if (compiled.bindings[b].role != ShaderRecompiler::DescriptorRole::FlattenedSrt) continue; variant.flatBinding = static_cast(b); - static_cast(DataWordPositions(variant.runs, capture.readTrace.leaves, capture.readTrace.otherReads, variant.words, variant.ringFlat != nullptr ? *variant.ringFlat : compiled.bindings[b].guestDescriptor, variant.dataPositions, variant.dataSlots)); + static_cast(DataWordPositions(variant.runs, capture.readTrace.leaves, capture.readTrace.otherReads, variant.words, variant.ringTemplate != nullptr && !variant.ringTemplate->flattenedSrt.empty() ? variant.ringTemplate->flattenedSrt : compiled.bindings[b].guestDescriptor, variant.dataPositions, variant.dataSlots)); break; } if (variant.dataPositions.empty() || decodeReads.empty()) return; @@ -348,7 +354,7 @@ void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawP fresh[i] = matched[i]; continue; } - if (stageCapture.compiled == nullptr || (stageCapture.direct && !stageCapture.ring) || !CacheableResult(*stageCapture.compiled)) continue; + if (stageCapture.compiled == nullptr || !stageCapture.Cacheable() || !CacheableResult(*stageCapture.compiled)) continue; auto variant = std::make_shared(); variant->compiled = stageCapture.compiled; if (programs[i].binary.stage == ShaderRecompiler::ShaderStage::Mesh) { @@ -359,10 +365,11 @@ void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawP variant->pushOffset = stageCapture.pushOffset; variant->userDataMask = stageCapture.userDataMask; if (stageCapture.ring && stageCapture.heapWords != nullptr) { - variant->ring = true; - variant->ringAttributes = std::make_shared>(stageCapture.heapWords->vertexAttributes); - if (!stageCapture.heapWords->flattenedSrt.empty()) variant->ringFlat = std::make_shared>(stageCapture.heapWords->flattenedSrt); - if (!stageCapture.heapWords->bindings.empty()) variant->ringBindings = std::make_shared>>(stageCapture.heapWords->bindings); + auto ringTemplate = std::make_shared(); + ringTemplate->vertexAttributes = stageCapture.heapWords->vertexAttributes; + ringTemplate->flattenedSrt = stageCapture.heapWords->flattenedSrt; + ringTemplate->bindings = stageCapture.heapWords->bindings; + variant->ringTemplate = std::move(ringTemplate); } if (vertexInfos[i]) variant->vertexInfo = std::make_shared(*vertexInfos[i]); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp index 3c0a88b0f95a..9734c9bdf8ad 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp @@ -117,15 +117,6 @@ bool DrawFinisher::PendingKey(std::uint64_t key, std::uint64_t shape) { return std::any_of(pending.begin(), pending.end(), [&](const Pending& held) { return held.key == key || (shape != 0 && held.shape == shape); }); } -void DrawFinisher::PendingWrites(std::vector& out) { - if (!Busy() || !finisherProducer) return; - std::lock_guard lock(mutex); - for (const auto& held : pending) { - if (held.unknown) out.emplace_back(0, std::numeric_limits::max()); - else out.insert(out.end(), held.writes.begin(), held.writes.end()); - } -} - namespace { std::array, static_cast(DrawFinisher::DrainSite::Count)> finisherDrains{}, finisherSkips{}; } @@ -522,15 +513,6 @@ std::optional DrawPipeline::PendingLabel(std::uint64_t address, s return std::nullopt; } -void DrawPipeline::QueuedWrites(std::vector& out) { - if (DrawFinisher::Overlap()) DrawFinisher::Get().PendingWrites(out); - std::lock_guard lock(mutex); - for (const auto& item : items) { - out.insert(out.end(), item.writes.begin(), item.writes.end()); - if (item.labelAddress != 0 && !item.labelBytes.empty()) out.emplace_back(item.labelAddress, item.labelAddress + item.labelBytes.size()); - } -} - void DrawPipeline::countWrites(const std::vector& writes, bool added) { for (const auto& range : writes) { const auto found = std::find_if(queuedWrites.begin(), queuedWrites.end(), [&](const auto& entry) { return entry.first == range; }); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp index 1f18fad45f52..50a32e557d8b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp @@ -324,10 +324,7 @@ void Driver::relocateDrawEntry(const QueueState& queue, std::uint64_t alias, std copy->flatBinding = variant->flatBinding; copy->pushOffset = variant->pushOffset; copy->vertexInfo = variant->vertexInfo; - copy->ring = variant->ring; - copy->ringAttributes = variant->ringAttributes; - copy->ringFlat = variant->ringFlat; - copy->ringBindings = variant->ringBindings; + copy->ringTemplate = variant->ringTemplate; for (const auto& move : moves) { if (move.program != i) continue; const auto delta = AlignedWord(move.to) - AlignedWord(move.from); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index a306f3d9d220..30d70b77b9a9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -550,11 +550,9 @@ void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderI noteMemoBytes(memo, heldBefore); } -std::shared_ptr -adoptWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, - std::uint64_t shaderBase, const Graphics::Recorder::WriteRanges* before, std::uint64_t generation, - ShaderRecompiler::HeapStageWords* words, std::shared_ptr* sharedWords, - HeapStageReads* stageReads, bool& memoKnown) { +bool adoptWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, + std::uint64_t shaderBase, const Graphics::Recorder::WriteRanges* before, std::uint64_t generation, + HeapStageMaterialized& adopted, bool& memoKnown) { auto& memo = heapWalkMemo(); const auto heldBefore = memo.heldBytes; auto* found = memo.find(memoKey); @@ -566,16 +564,15 @@ adoptWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderInvocatio if (!rangesSettled(entry.ranges, before, generation)) break; memo.touch(entry); guardRanges(entry.ranges); - if (sharedWords != nullptr) *sharedWords = entry.words; - else *words = *entry.words; - if (stageReads != nullptr) *stageReads = {entry.ranges, entry.values, entry.userDataUse, entry.capture, true}; - auto result = entry.result; + adopted.words = entry.words; + adopted.reads = {entry.ranges, entry.values, entry.userDataUse, entry.capture, true}; + adopted.result = entry.result; if (way != 0) std::rotate(found->begin(), found->begin() + static_cast(way), found->begin() + static_cast(way) + 1); - return result; + return true; } - return nullptr; + return false; } std::shared_ptr @@ -592,10 +589,8 @@ captureWalk(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::s } -std::shared_ptr -MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, - std::uint64_t shaderBase, ShaderRecompiler::HeapStageWords* words, - std::shared_ptr* sharedWords, HeapStageReads* stageReads) { +HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, + std::uint64_t shaderBase) { struct ReadsStorage {}; struct RangesStorage {}; struct ValuesStorage {}; @@ -606,14 +601,15 @@ MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocatio const auto before = Graphics::Recorder::PendingWriteSnapshot(); snapshotCost.Stop(); const auto generation = GuestMemory::TrackerGeneration(); - const bool memoOn = words != nullptr && !invocation.Request().context.vertex.has_value(); + const bool memoOn = !invocation.Request().context.vertex.has_value(); std::uint64_t memoKey = 0; bool memoKnown = false; Graphics::HeapCostScope memoCost(Graphics::HeapCost::WalkMemo); if (memoOn) { memoKey = walkMemoKey(invocation, userData, shaderBase); - if (auto adopted = adoptWalk(memoKey, invocation, userData, shaderBase, before.get(), generation, words, sharedWords, stageReads, memoKnown)) + HeapStageMaterialized adopted; + if (adoptWalk(memoKey, invocation, userData, shaderBase, before.get(), generation, adopted, memoKnown)) return adopted; } memoCost.Stop(); @@ -622,25 +618,28 @@ MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocatio auto capture = captureWalk(invocation, userData, shaderBase, reads); coalesceWords(reads.words, ranges); auto& values = HostThreadLocal, ValuesStorage>(); - if ((memoOn || stageReads != nullptr) && !reads.failed) copyRangeValues(ranges, values); + if (!reads.failed) copyRangeValues(ranges, values); const bool settled = rangesSettled(ranges, before.get(), generation); walkCost.Stop(); - if (!settled) return nullptr; + if (!settled) return {}; Graphics::HeapCostScope guardCost(Graphics::HeapCost::Guards); guardRanges(ranges); guardCost.Stop(); Graphics::HeapCostScope materializeCost(Graphics::HeapCost::Materialize); - std::shared_ptr result; - if (words != nullptr) result = invocation.MaterializeHeap(*capture, *words); + auto words = std::make_shared(); + auto result = invocation.MaterializeHeap(*capture, *words); if (result == nullptr) result = invocation.Materialize(*capture); materializeCost.Stop(); const bool complete = !reads.failed && result != nullptr; - if (stageReads != nullptr && complete) *stageReads = {ranges, values, capture->userDataUse, capture, true}; + HeapStageMaterialized materialized; + if (complete) materialized.reads = {ranges, values, capture->userDataUse, capture, true}; Graphics::HeapCostScope insertCost(Graphics::HeapCost::MemoInsert); if (memoOn && complete && (memoKnown || heapWalkMemo().admit(memoKey))) rememberWalk(memoKey, invocation, userData, shaderBase, ranges, values, reads.accessible, capture, result, *words); - return result; + materialized.result = std::move(result); + materialized.words = std::move(words); + return materialized; } namespace { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 41014c144d2a..76de7ebf4071 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -157,6 +157,27 @@ std::optional ActiveValidationLayerVersion(PFN_vkGetInstanceProcA return std::nullopt; } +constexpr std::uint32_t MinHeapValidationLayerVersion = VK_MAKE_API_VERSION(0, 1, 4, 363); +constexpr std::uint32_t HeapDataUniformDwordCap = 16384u; + +bool DescriptorHeapAvailable(const std::vector& availableExtensions, PFN_vkGetInstanceProcAddr instanceProc) { + if (!Graphics::GpuHeapEnabled()) return false; + const auto heapExtension = std::find_if(availableExtensions.begin(), availableExtensions.end(), [](const auto& item) { return std::strcmp(item.extensionName, VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME) == 0; }); + if (heapExtension == availableExtensions.end()) return false; + if (heapExtension->specVersion < VK_EXT_DESCRIPTOR_HEAP_SPEC_VERSION) { + std::fprintf(stderr, "[gpu-heap] the driver's VK_EXT_descriptor_heap is revision %u, older than the released revision %u, so the GPU heap stays off\n", + heapExtension->specVersion, static_cast(VK_EXT_DESCRIPTOR_HEAP_SPEC_VERSION)); + return false; + } + const auto validationVersion = ActiveValidationLayerVersion(instanceProc); + if (validationVersion.has_value() && *validationVersion < MinHeapValidationLayerVersion) { + std::fprintf(stderr, "[gpu-heap] VK_LAYER_KHRONOS_validation %u.%u.%u predates its descriptor heap rules (1.4.363 is the oldest layer that validates heap push data), so the GPU heap stays off\n", + VK_API_VERSION_MAJOR(*validationVersion), VK_API_VERSION_MINOR(*validationVersion), VK_API_VERSION_PATCH(*validationVersion)); + return false; + } + return true; +} + void check(VkResult result, const char* operation) { if (result == VK_ERROR_DEVICE_LOST) Graphics::ReportDeviceLost(); @@ -1968,20 +1989,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : } } VkPhysicalDeviceDescriptorHeapFeaturesEXT descriptorHeapFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_FEATURES_EXT}; - const auto heapExtension = std::find_if(availableExtensions.begin(), availableExtensions.end(), [](const auto& item) { return std::strcmp(item.extensionName, VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME) == 0; }); - bool releasedDescriptorHeap = heapExtension != availableExtensions.end() && heapExtension->specVersion >= VK_EXT_DESCRIPTOR_HEAP_SPEC_VERSION; - if (Graphics::GpuHeapEnabled() && heapExtension != availableExtensions.end() && !releasedDescriptorHeap) - std::fprintf(stderr, "[gpu-heap] the driver's VK_EXT_descriptor_heap is revision %u, older than the released revision %u, so the GPU heap stays off\n", - heapExtension->specVersion, static_cast(VK_EXT_DESCRIPTOR_HEAP_SPEC_VERSION)); - if (Graphics::GpuHeapEnabled() && releasedDescriptorHeap && hasExtension(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME)) { - const auto validationVersion = ActiveValidationLayerVersion(state->instanceProc); - if (validationVersion.has_value() && *validationVersion < VK_MAKE_API_VERSION(0, 1, 4, 363)) { - std::fprintf(stderr, "[gpu-heap] VK_LAYER_KHRONOS_validation %u.%u.%u predates its descriptor heap rules (1.4.363 is the oldest layer that validates heap push data), so the GPU heap stays off\n", - VK_API_VERSION_MAJOR(*validationVersion), VK_API_VERSION_MINOR(*validationVersion), VK_API_VERSION_PATCH(*validationVersion)); - releasedDescriptorHeap = false; - } - } - if (Graphics::GpuHeapEnabled() && releasedDescriptorHeap && hasExtension(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME) && hasExtension(VK_KHR_MAINTENANCE_5_EXTENSION_NAME) && hasExtension(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) && hasExtension(VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME) && hasExtension(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME)) { + if (DescriptorHeapAvailable(availableExtensions, state->instanceProc) && hasExtension(VK_KHR_MAINTENANCE_5_EXTENSION_NAME) && hasExtension(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) && hasExtension(VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME) && hasExtension(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME)) { VkPhysicalDeviceMaintenance5FeaturesKHR heapMaintenance5{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR, &descriptorHeapFeatures}; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &heapMaintenance5}; state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &features); @@ -1993,7 +2001,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : state->descriptorHeap = true; state->maintenance5 = true; if (Graphics::BindlessHeap::RingInResourceHeap(state->descriptorHeapProperties, state->properties.limits.minUniformBufferOffsetAlignment)) - state->heapDataUniformDwords = std::min(16384u, state->properties.limits.maxUniformBufferRange / 4u); + state->heapDataUniformDwords = std::min(HeapDataUniformDwordCap, state->properties.limits.maxUniformBufferRange / 4u); deviceExtensions.push_back(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME); for (const char* required : {VK_KHR_MAINTENANCE_5_EXTENSION_NAME, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME}) { if (std::find_if(deviceExtensions.begin(), deviceExtensions.end(), [&](const char* name) { return std::strcmp(name, required) == 0; }) == deviceExtensions.end()) deviceExtensions.push_back(required); @@ -4301,10 +4309,15 @@ bool VulkanDevice::GraphicsPipelineLibraries() const { return state->graphicsPipelineLibrary; } -Graphics::Context VulkanDevice::graphicsContext() const { +const Graphics::Context& VulkanDevice::contextRef(std::optional& scratch) const { static const bool noCache = std::getenv("APS5_NO_CONTEXT_CACHE") != nullptr; if (state->contextReady && !noCache) return state->context; - return buildContext(); + return scratch.emplace(buildContext()); +} + +Graphics::Context VulkanDevice::graphicsContext() const { + std::optional scratch; + return contextRef(scratch); } Graphics::Context VulkanDevice::buildContext() const { @@ -4432,9 +4445,8 @@ VulkanDevice::IndirectDrawSupport VulkanDevice::DrawIndirectSupport() const { } std::optional VulkanDevice::KnownDrawRejection(const Graphics::State& graphics, std::span shaders) const { - static const bool noCache = std::getenv("APS5_NO_CONTEXT_CACHE") != nullptr; - if (state->contextReady && !noCache) return Graphics::KnownValidationFailure(state->context, shaders, graphics); - return Graphics::KnownValidationFailure(buildContext(), shaders, graphics); + std::optional scratch; + return Graphics::KnownValidationFailure(contextRef(scratch), shaders, graphics); } void VulkanDevice::ColorMetadataPass(const Graphics::ColorMetadataPass& pass) { @@ -5491,14 +5503,19 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { recorder.Keep(std::move(memory)); } if (record.pushStages != 0) { - auto pushed = *record.pushBytes; - resources.PatchDataAddresses(pushed, std::span(record.shader, 1), record.bindings.get()); + std::array patchedBytes; + const std::byte* pushed = record.pushBytes->data(); + if (resources.HeapStage() || record.objects->descriptorHeap) { + patchedBytes = *record.pushBytes; + resources.PatchDataAddresses(patchedBytes, std::span(record.shader, 1), record.bindings.get()); + pushed = patchedBytes.data(); + } if (record.objects->descriptorHeap) { - std::memcpy(pushed.data() + Graphics::ComputePushConstantBytes, &workgroupAddress, sizeof(workgroupAddress)); - const VkPushDataInfoEXT push{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {pushed.data(), pushed.size()}}; + std::memcpy(patchedBytes.data() + Graphics::ComputePushConstantBytes, &workgroupAddress, sizeof(workgroupAddress)); + const VkPushDataInfoEXT push{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {patchedBytes.data(), patchedBytes.size()}}; context.Function("vkCmdPushDataEXT")(commands, &push); } else { - Graphics::CmdPushConstants(context, commands, record.objects->layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, Graphics::ComputePushConstantBytes, pushed.data()); + Graphics::CmdPushConstants(context, commands, record.objects->layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, Graphics::ComputePushConstantBytes, pushed); } } const auto gpuTiming = recorder.BeginGpuTiming(record.programAddress != 0 ? record.programAddress : record.shader->program->variantId); @@ -5638,7 +5655,7 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons objects->descriptorHeap = heapDevice && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(spirv, heapMappings, workgroupAddressOffset, shader.dataAddressPush); require(!gpuMode || objects->descriptorHeap, "a GPU-mode compute stage does not map onto VK_EXT_descriptor_heap"); const auto createPipelines = state->DeviceFunction("vkCreateComputePipelines"); - if (objects->descriptorHeap) CreateComputeHeapPipeline(state->device, createPipelines, context.pipelineCache, objects->module, computePipelineFlags(), stageFlags, specialization.Info(), subgroupSize, heapMappings, &objects->pipeline, context.pipelineCacheSynchronization); + if (objects->descriptorHeap) CreateComputeHeapPipeline(state->device, createPipelines, context.pipelineCache, objects->module, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, heapMappings, &objects->pipeline, context.pipelineCacheSynchronization); else CreateComputePipeline(state->device, createPipelines, context.pipelineCache, objects->module, objects->layout, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, &objects->pipeline, context.pipelineCacheSynchronization); objects->destroyModule(objects->device, objects->module, nullptr); objects->module = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 3d67f54fd8f7..9797ebdafd9e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -346,7 +346,7 @@ int main(int argc, char** argv) { std::printf("skipped, no usable Vulkan device: %s\n", error.what()); return VulkanTestSkipped; } - if (!device->GraphicsContext().descriptorHeap) { + if (!device->graphicsContext().descriptorHeap) { std::printf("skipped, the device has no VK_EXT_descriptor_heap\n"); return VulkanTestSkipped; } @@ -357,7 +357,7 @@ int main(int argc, char** argv) { #endif if (comesBack) { { - const auto context = device->GraphicsContext(); + const auto context = device->graphicsContext(); const PlaceholderImages placeholders(context); const auto sampled = placeholders.View(Abi::FirstImageBinding); const auto storage = placeholders.View(Abi::FirstStorageImageBinding); @@ -377,7 +377,7 @@ int main(int argc, char** argv) { return 0; } { - const auto context = device->GraphicsContext(); + const auto context = device->graphicsContext(); const PlaceholderImages placeholders(context); textureSlots(context, placeholders.View(Abi::FirstImageBinding)); samplerSlots(context); diff --git a/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp index 472fb3cb5f04..723d1f722926 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp @@ -834,7 +834,7 @@ int main() { std::printf("skipped, the device has no descriptor heap\n"); return VulkanTestSkipped; } - const auto context = heapDevice->GraphicsContext(); + const auto context = heapDevice->graphicsContext(); Require(BindlessHeap::For(context).DescriptorHeapMode(), "the test device did not open the descriptor heap"); residentPresentTests(context); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp index 0a391c2bb722..c837ff204562 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp @@ -420,7 +420,7 @@ void NoRecords(Scene& scene) { constexpr std::size_t MultisampleTargetOffset = 32768; bool MultisampleTargetsAvailable(Scene& scene) { - const auto context = scene.device.GraphicsContext(); + const auto context = scene.device.graphicsContext(); if (AgcDriver::GuestMemory::WriteWatched() && (context.limits.framebufferColorSampleCounts & VK_SAMPLE_COUNT_4_BIT) != 0) return true; Require(std::getenv("ANYPS5_REQUIRE_VULKAN") == nullptr, "address draw space reuse: the multisample target cases require write tracking and 4x color targets"); std::puts("skipped, the multisample target cases require write tracking and 4x color targets"); @@ -428,7 +428,7 @@ bool MultisampleTargetsAvailable(Scene& scene) { } void PlaceMultisampleTarget(Scene& scene, std::uint64_t address) { - const auto context = scene.device.GraphicsContext(); + const auto context = scene.device.graphicsContext(); AgcDriver::Graphics::ColorTarget target{}; target.address = address; target.surfaceAddress = address; @@ -446,7 +446,7 @@ void PlaceMultisampleTarget(Scene& scene, std::uint64_t address) { } void RetireMultisampleTargets(Scene& scene) { - const auto context = scene.device.GraphicsContext(); + const auto context = scene.device.graphicsContext(); std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); scene.device.WaitIdle(); AgcDriver::Graphics::ClearMultisampleTargets(context.device); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp index 69d498940cba..6d2ca20ecc93 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp @@ -1381,13 +1381,13 @@ int main(int argc, char** argv) { std::printf("skipped, no usable Vulkan device: %s\n", error.what()); return VulkanTestSkipped; } - if (!heapDevice->GraphicsContext().descriptorHeap) { + if (!heapDevice->graphicsContext().descriptorHeap) { std::puts("skipped, the device has no VK_EXT_descriptor_heap"); return VulkanTestSkipped; } bool tested = false; { - const auto context = heapDevice->GraphicsContext(); + const auto context = heapDevice->graphicsContext(); { std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); heapHeldReleaseTests(context); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp index bed98baff4b0..8ad29aead3cf 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp @@ -87,7 +87,7 @@ std::map heapSlotsByAddress; std::shared_ptr heapSlotted(AgcDriver::VulkanDevice& device, std::uint64_t address, std::shared_ptr image) { if (!heapSlots || image == nullptr) return image; std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); - auto& heap = AgcDriver::Graphics::BindlessHeap::For(device.GraphicsContext()); + auto& heap = AgcDriver::Graphics::BindlessHeap::For(device.graphicsContext()); const auto slot = heap.StorageSlot(ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding, image.get(), image->StorageView(0, false)); Require(slot.has_value(), "the stored image took no GPU heap storage slot"); heapSlotsByAddress.try_emplace(address, HeapSlotted{*slot, heap.SlotGeneration(*slot)}); @@ -97,7 +97,7 @@ std::shared_ptr heapSlotted(AgcDriver::VulkanDevice& device, std bool heapSlotFreed(AgcDriver::VulkanDevice& device, std::uint64_t address) { const auto found = heapSlotsByAddress.find(address); Require(found != heapSlotsByAddress.end(), "no GPU heap slot was recorded for the surface"); - return AgcDriver::Graphics::BindlessHeap::For(device.GraphicsContext()).SlotGeneration(found->second.slot) != found->second.generation; + return AgcDriver::Graphics::BindlessHeap::For(device.graphicsContext()).SlotGeneration(found->second.slot) != found->second.generation; } std::shared_ptr Store(AgcDriver::VulkanDevice& device, std::uint64_t base, std::uint32_t surface, bool flush = true) { @@ -120,7 +120,7 @@ int RetainedBatch() { #endif const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; - if (heapSlots && !device->GraphicsContext().descriptorHeap) { + if (heapSlots && !device->graphicsContext().descriptorHeap) { std::puts("skipped, the device has no VK_EXT_descriptor_heap"); return VulkanTestSkipped; } @@ -185,7 +185,7 @@ int main(int argc, char** argv) { #endif const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; - if (heapSlots && !device->GraphicsContext().descriptorHeap) { + if (heapSlots && !device->graphicsContext().descriptorHeap) { std::puts("skipped, the device has no VK_EXT_descriptor_heap"); return VulkanTestSkipped; } From 37878533aa61cdb93364fef796283282491520f1 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 31 Oct 2026 21:04:47 +0530 Subject: [PATCH 085/269] refactor(agc): tidy the heap resource, pipeline and descriptor paths Remove the dead storage-texture cache flag, share one buffer device-address query, read owned buffers' cached addresses, look the device function cache up before the descriptor-heap hooks, count bind and record statistics only when they are reported, classify heap bindings without goto, name the heap shader checks and pipeline-library key tags, share the descriptor-heap pipeline flags, keep encoded image views in their view record, and add APS5_NO_SPACE_REUSE to turn space reuse off on its own. --- .../Execution/src/PresentationPass.cpp | 3 +- .../Execution/src/VulkanDevice.cpp | 8 +- .../Graphics/include/Context.hpp | 13 +- .../Graphics/include/PipelineLibrary.hpp | 3 +- .../Graphics/include/Resources.hpp | 2 + .../Graphics/include/Sampler.hpp | 11 +- .../Graphics/include/ShaderResources.hpp | 3 +- .../Graphics/include/Shaders.hpp | 15 ++ .../Graphics/include/Texture.hpp | 7 +- .../Graphics/src/BindlessHeap.cpp | 3 +- .../Graphics/src/BufferAddress.cpp | 8 +- .../Graphics/src/DescriptorHeapObjects.cpp | 67 ++++---- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 24 +-- .../Graphics/src/GuestBufferMemory.cpp | 34 ++-- .../libSceAgcDriver/Graphics/src/Pipeline.cpp | 37 ++--- .../Graphics/src/PipelineLibrary.cpp | 16 +- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 10 +- .../Graphics/src/ResidentMirror.cpp | 3 +- .../Graphics/src/Resources.cpp | 11 +- .../Graphics/src/ShaderAddressResources.cpp | 4 +- .../Graphics/src/ShaderResources.cpp | 154 ++++++++++-------- .../Graphics/src/ShaderValidation.cpp | 2 +- .../Graphics/src/TextureDetiler.cpp | 9 +- docs/dev/ENVIRONMENT.md | 1 + 24 files changed, 239 insertions(+), 209 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp index de2faec8994a..d1107261563b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp @@ -282,8 +282,7 @@ const PresentationPass::Target& PresentationPass::target(VkFormat format, VkImag mappingInfo.mappingCount = static_cast(mappings.size()); mappingInfo.pMappings = mappings.data(); stages[1].pNext = &mappingInfo; - VkPipelineCreateFlags2CreateInfoKHR heapFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR}; - heapFlags.flags = VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT; + auto heapFlags = Graphics::DescriptorHeapFlags(); pipelineInfo.pNext = &heapFlags; pipelineInfo.layout = VK_NULL_HANDLE; Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.heapPipeline), "vkCreateGraphicsPipelines presentation pass heap"); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 76de7ebf4071..2b896282cbd8 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -262,8 +262,7 @@ const char* ComputePipelineDumpDirectory() { return std::getenv("APS5_DUMP_COMPU #endif void CreateComputeHeapPipeline(VkDevice device, PFN_vkCreateComputePipelines create, VkPipelineCache cache, VkShaderModule module, VkPipelineCreateFlags flags, VkPipelineShaderStageCreateFlags stageFlags, const VkSpecializationInfo* specialization, std::uint32_t subgroupSize, std::span mappings, VkPipeline* pipeline, Graphics::PipelineCacheSynchronization* synchronization) { - VkPipelineCreateFlags2CreateInfoKHR flags2{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR}; - flags2.flags = static_cast(flags) | VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT; + auto flags2 = Graphics::DescriptorHeapFlags(static_cast(flags)); VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, &flags2}; info.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; info.stage.flags = stageFlags; @@ -761,10 +760,7 @@ struct VulkanDevice::State { write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &described; DeviceFunction("vkUpdateDescriptorSets")(device, 1, &write, 0, nullptr); - if (context.descriptorHeap) { - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, memory->buffer->Handle()}; - memory->address = DeviceFunction("vkGetBufferDeviceAddressKHR")(device, &addressInfo); - } + if (context.descriptorHeap) memory->address = Graphics::BufferDeviceAddress(context, memory->buffer->Handle()); workgroupMemory = std::move(memory); return workgroupMemory; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index e9fcc727fa22..d354c23f52e9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -192,6 +192,10 @@ class DeviceFunctionCache { inline constexpr std::size_t EmptyBufferBytes = 16; +inline VkPipelineCreateFlags2CreateInfoKHR DescriptorHeapFlags(VkPipelineCreateFlags2KHR flags = 0, const void* next = nullptr) { + return {VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR, next, flags | VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT}; +} + struct Context { VkDevice device; VkPhysicalDevice physical; @@ -330,13 +334,16 @@ struct Context { template TFunction Function(const char* name) const { Require(deviceProc != nullptr, "missing Vulkan device function resolver"); - if (descriptorHeap) { - if (const auto hooked = DescriptorHeapObjectFunction(device, deviceProc, name); hooked != nullptr) return reinterpret_cast(hooked); - } const auto* cache = functions != nullptr ? functionCache : nullptr; if (cache != nullptr) { if (const auto cached = cache->Find(name, deviceProc); cached != nullptr) return reinterpret_cast(cached); } + if (descriptorHeap) { + if (const auto hooked = DescriptorHeapObjectFunction(device, deviceProc, name); hooked != nullptr) { + if (cache != nullptr) functionCache->Keep(name, deviceProc, hooked); + return reinterpret_cast(hooked); + } + } ++DeviceProcLookups(); const auto function = deviceProc(device, name); if (function == nullptr) throw std::runtime_error(std::string("AGC graphics: missing Vulkan function: ") + name); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp index c398c01818e8..18ff01097e70 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp @@ -42,8 +42,7 @@ struct OptimizedPipeline { void Schedule(); }; -bool DescriptorHeapPipelineInfo(const VkGraphicsPipelineCreateInfo& info); -VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPipelineCreateInfo& info, const VkPipelineRenderingCreateInfoKHR& rendering, const VkPipelineLayoutCreateInfo& layout, const PipelineLibraryKeys& keys, std::shared_ptr* optimized = nullptr, bool partsOnly = false, std::span modules = {}); +VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPipelineCreateInfo& info, const VkPipelineRenderingCreateInfoKHR& rendering, const VkPipelineLayoutCreateInfo& layout, const PipelineLibraryKeys& keys, bool descriptorHeap, std::shared_ptr* optimized = nullptr, bool partsOnly = false, std::span modules = {}); void WaitForOptimizedPipelines(VkDevice device); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Resources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Resources.hpp index 674cff0c47d0..2e4741f0ca85 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Resources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Resources.hpp @@ -6,6 +6,8 @@ namespace AgcDriver::Graphics { +VkDeviceAddress BufferDeviceAddress(const Context& context, VkBuffer buffer); + class Buffer { public: Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp index a3a21ed58fd9..34b4f5d95518 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace AgcDriver::Graphics { @@ -29,11 +30,8 @@ class Sampler : public HeapSlotOwner { bool RequiresNonSeamlessCube() const; static void Validate(const Context& context, const GuestSamplerResource& descriptor); static bool ReadsOpaqueBlackBorder(const GuestSamplerResource& descriptor); - const std::array* CacheKey() const { return keyed ? &cacheKey : nullptr; } - void SetCacheKey(const std::array& key) { - cacheKey = key; - keyed = true; - } + const std::array* CacheKey() const { return cacheKey ? &*cacheKey : nullptr; } + void SetCacheKey(const std::array& key) { cacheKey = key; } private: void release() noexcept; @@ -44,8 +42,7 @@ class Sampler : public HeapSlotOwner { bool requiresFilterMinmax = false; bool opaqueBlackBorder = false; bool requiresNonSeamlessCube = false; - std::array cacheKey{}; - bool keyed = false; + std::optional> cacheKey; }; // One VkSampler per distinct S# (its 4 words plus the shader's depth-compare use and the diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index bb70a7423bb8..fb7d17f2c921 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -547,7 +547,8 @@ class ShaderResources { void forgetDeferredInputs(); void release() noexcept; void prepareAddressBindings(std::span shaders, std::span snapshots); - VkDescriptorBufferInfo descriptor(Allocation& allocation); + VkDescriptorBufferInfo descriptor(Allocation& allocation) { return descriptor(allocation, allocation.adjustment); } + VkDescriptorBufferInfo descriptor(const Allocation& allocation, std::uint32_t& adjustment) const; VkDescriptorBufferInfo wholeDwordRange(VkDescriptorBufferInfo info) const; void noteReusable(); void reportDescriptorCaches() const; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp index d575cd5c21a6..085aeb40fffe 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp @@ -3,6 +3,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include "Recompiler.hpp" +#include #include #include #include @@ -13,6 +14,12 @@ inline constexpr std::uint32_t PipelinePushConstantBytes = 256; inline constexpr std::uint32_t PipelinePushSlotBytes = 128; inline constexpr std::uint32_t ComputePushConstantBytes = 128; +inline constexpr std::uint32_t HeapLayoutKeyTag = 0x48454150u; +inline constexpr std::uint32_t DataSetKeyTag = 0x44415441u; +inline constexpr std::uint32_t MainSetBit = 1u; +inline constexpr std::uint32_t HeapSetBit = 2u; +inline constexpr std::uint32_t DataSetBit = 4u; + inline std::uint32_t PushBlockBytes(bool libraries) { return libraries ? PipelinePushConstantBytes : PipelinePushSlotBytes; } @@ -40,6 +47,14 @@ struct CompiledShader { const ShaderRecompiler::HeapStageWords* heap = nullptr; }; +inline bool HeapShader(const CompiledShader& shader) { + return shader.program != nullptr && shader.program->gpuResolvedImages; +} + +inline bool AnyHeapShader(std::span shaders) { + return std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return HeapShader(shader); }); +} + inline const std::vector& DrawGuestWords(const ShaderRecompiler::RecompileResult& program, const ShaderRecompiler::HeapStageWords* heap, const ShaderRecompiler::DescriptorBinding& binding) { if (heap == nullptr || heap->bindings.empty()) return binding.guestDescriptor; const auto index = static_cast(&binding - program.bindings.data()); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp index 4802e7bd0682..7c163899751a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp @@ -302,11 +302,7 @@ class StorageTexture : public std::enable_shared_from_this, publ // Whether the storage cache holds this image (set and cleared by the cache under its mutex, the // clear before the eviction's flush): what a lookup of its surface would return. bool Cached() const { return cached.load(std::memory_order_acquire); } - void SetCached(bool value) { - if (value) everCached.store(true, std::memory_order_relaxed); - cached.store(value, std::memory_order_release); - } - bool LeftCache() const { return everCached.load(std::memory_order_relaxed) && !cached.load(std::memory_order_acquire); } + void SetCached(bool value) { cached.store(value, std::memory_order_release); } // The pending image whose surface starts at `address` and covers at least `bytes` (a mip chain // contains a descriptor of its first mips), if any; the caller decides whether the geometry fits // (Texture::CanCopyFrom, ResidentPresentable). @@ -701,7 +697,6 @@ class StorageTexture : public std::enable_shared_from_this, publ // no fill may put results into this one (guarded by the live-image registry lock). bool released = false; std::atomic cached{false}; - std::atomic everCached{false}; // The present a consumer last proved the image current at (NoteProved). mutable std::atomic provedPresent{0}; // Hook skips of this image since FlushPending last listed it (AccessKeptByCpu), the read site diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 6b77f50cba31..657fdb5da0cf 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -962,6 +962,7 @@ void forgetHeapBinding(VkCommandBuffer commands) { } void NoteHeapRecord(bool compute, bool heap) { + if (!pipelineStats()) return; heapRecords[heapRecordIndex(compute, heap)].fetch_add(1, std::memory_order_relaxed); reportHeapStatistics(); } @@ -1007,7 +1008,7 @@ void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkP std::uint32_t firstSet, std::uint32_t setCount, const VkDescriptorSet* sets, SetBindSite site) { context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, bindPoint, layout, firstSet, setCount, sets, 0, nullptr); - setBinds[static_cast(site)].fetch_add(1, std::memory_order_relaxed); + if (pipelineStats()) setBinds[static_cast(site)].fetch_add(1, std::memory_order_relaxed); forgetHeapBinding(commands); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferAddress.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferAddress.cpp index 857cce2cc2f8..f788d9722265 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferAddress.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferAddress.cpp @@ -7,10 +7,14 @@ VkDeviceAddress Buffer::DeviceAddress() const { return deviceAddress; } +VkDeviceAddress BufferDeviceAddress(const Context& context, VkBuffer buffer) { + const VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer}; + return context.Function("vkGetBufferDeviceAddressKHR")(context.device, &info); +} + void Buffer::initializeAddress(VkBufferUsageFlags usage) { if ((usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) == 0) return; - const VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer}; - deviceAddress = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &info); + deviceAddress = BufferDeviceAddress(context, buffer); Require(deviceAddress != 0, "vkGetBufferDeviceAddressKHR returned a null address"); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp index c45a8d712b0b..fd62cf8ec388 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" +#include #include #include #include @@ -20,18 +21,18 @@ std::mutex& recordsMutex() { return mutex; } -std::unordered_map& views() { - static auto& map = *new std::unordered_map(); - return map; -} - struct EncodedImageView { std::uint32_t key = 0; std::vector bytes; }; -std::unordered_map>& encodedViews() { - static auto& map = *new std::unordered_map>(); +struct ViewEntry { + ImageViewRecord record; + std::vector encoded; +}; + +std::unordered_map& views() { + static auto& map = *new std::unordered_map(); return map; } @@ -77,8 +78,7 @@ VKAPI_ATTR VkResult VKAPI_CALL createImageView(VkDevice device, const VkImageVie static std::atomic generations{0}; record.generation = generations.fetch_add(1, std::memory_order_relaxed) + 1u; std::lock_guard lock(recordsMutex()); - views()[*view] = std::move(record); - encodedViews().erase(*view); + views()[*view] = ViewEntry{std::move(record), {}}; } return result; } @@ -87,7 +87,6 @@ VKAPI_ATTR void VKAPI_CALL destroyImageView(VkDevice device, VkImageView view, c { std::lock_guard lock(recordsMutex()); views().erase(view); - encodedViews().erase(view); } realDestroyImageView.load(std::memory_order_acquire)(device, view, allocator); } @@ -119,6 +118,24 @@ bool resolve(std::atomic& real, VkDevice device, PFN_vkGetDeviceProcA return true; } +struct ObjectHook { + const char* name; + bool (*resolveReal)(VkDevice, PFN_vkGetDeviceProcAddr, const char*); + PFN_vkVoidFunction hook; +}; + +template & Real> +bool resolveRealFunction(VkDevice device, PFN_vkGetDeviceProcAddr deviceProc, const char* name) { + return resolve(Real, device, deviceProc, name); +} + +const std::array ObjectHooks{{ + {"vkCreateImageView", &resolveRealFunction, reinterpret_cast(&createImageView)}, + {"vkDestroyImageView", &resolveRealFunction, reinterpret_cast(&destroyImageView)}, + {"vkCreateSampler", &resolveRealFunction, reinterpret_cast(&createSampler)}, + {"vkDestroySampler", &resolveRealFunction, reinterpret_cast(&destroySampler)}, +}}; + } const VkImageViewCreateInfo* ImageViewRecord::Chain() { @@ -145,30 +162,18 @@ const VkSamplerCreateInfo* SamplerRecord::Chain() { PFN_vkVoidFunction DescriptorHeapObjectFunction(VkDevice device, PFN_vkGetDeviceProcAddr deviceProc, const char* name) { if (device == VK_NULL_HANDLE) return nullptr; - if (std::strcmp(name, "vkCreateImageView") == 0) { - if (!resolve(realCreateImageView, device, deviceProc, name)) return nullptr; - return reinterpret_cast(&createImageView); - } - if (std::strcmp(name, "vkDestroyImageView") == 0) { - if (!resolve(realDestroyImageView, device, deviceProc, name)) return nullptr; - return reinterpret_cast(&destroyImageView); - } - if (std::strcmp(name, "vkCreateSampler") == 0) { - if (!resolve(realCreateSampler, device, deviceProc, name)) return nullptr; - return reinterpret_cast(&createSampler); - } - if (std::strcmp(name, "vkDestroySampler") == 0) { - if (!resolve(realDestroySampler, device, deviceProc, name)) return nullptr; - return reinterpret_cast(&destroySampler); + for (const auto& entry : ObjectHooks) { + if (std::strcmp(name, entry.name) != 0) continue; + return entry.resolveReal(device, deviceProc, name) ? entry.hook : nullptr; } return nullptr; } bool CopyEncodedImageView(VkImageView view, std::uint32_t key, std::span target) { std::lock_guard lock(recordsMutex()); - const auto found = encodedViews().find(view); - if (found == encodedViews().end()) return false; - for (const auto& encoded : found->second) { + const auto found = views().find(view); + if (found == views().end()) return false; + for (const auto& encoded : found->second.encoded) { if (encoded.key != key || encoded.bytes.size() != target.size()) continue; std::memcpy(target.data(), encoded.bytes.data(), target.size()); return true; @@ -179,8 +184,8 @@ bool CopyEncodedImageView(VkImageView view, std::uint32_t key, std::span bytes) { std::lock_guard lock(recordsMutex()); const auto record = views().find(view); - if (record == views().end() || record->second.generation != generation) return; - auto& entries = encodedViews()[view]; + if (record == views().end() || record->second.record.generation != generation) return; + auto& entries = record->second.encoded; for (auto& encoded : entries) { if (encoded.key == key) { encoded.bytes.assign(bytes.begin(), bytes.end()); @@ -194,7 +199,7 @@ std::optional FindImageView(VkImageView view) { std::lock_guard lock(recordsMutex()); const auto found = views().find(view); if (found == views().end()) return std::nullopt; - return found->second; + return found->second.record; } std::optional FindSampler(VkSampler sampler) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index da32eec2bc78..9104eb4079b0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -197,8 +197,7 @@ void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, s Check(context.Function("vkBindBufferMemory")(context.device, pool.buffer, pool.memory, 0), "vkBindBufferMemory pixel function LDS"); pool.bytes = bytes; if (addressed) { - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, pool.buffer}; - pool.address = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + pool.address = BufferDeviceAddress(context, pool.buffer); } Check(context.Function("vkMapMemory")(context.device, pool.memory, 0, 16, 0, reinterpret_cast(&pool.header)), "vkMapMemory pixel function LDS"); pool.header[0] = 0u; @@ -297,8 +296,7 @@ void PrepareMeshWindow(const Context& context) { Check(context.Function("vkBindBufferMemory")(context.device, pool.buffer, pool.memory, 0), "vkBindBufferMemory mesh window"); pool.bytes = bytes; if (addressed) { - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, pool.buffer}; - pool.address = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + pool.address = BufferDeviceAddress(context, pool.buffer); } const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u}; VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; @@ -2609,8 +2607,9 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam record.pipeline->Begin(commands, *record.framebuffer, state.renderExtent, state); } APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); - NoteHeapRecord(false, record.pipeline->DescriptorHeap()); - if (record.pipeline->DescriptorHeap()) { + const bool heapPipeline = record.pipeline->DescriptorHeap(); + NoteHeapRecord(false, heapPipeline); + if (heapPipeline) { resources.BindDescriptorHeaps(commands); NoteEmptyResourceSet(); } else if (drawBindings != nullptr) { @@ -2623,8 +2622,8 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam Require(!resources.HeapStage(), "a GPU-mode draw needs a VK_EXT_descriptor_heap pipeline"); resources.Bind(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout()); } - if (!record.pipeline->DescriptorHeap() && std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; })) BindPixelFunctionLds(context, commands, record.pipeline->Layout()); - if (!record.pipeline->DescriptorHeap() && UsesMeshWindow(shaders)) BindMeshWindow(context, commands, record.pipeline->Layout()); + if (!heapPipeline && std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; })) BindPixelFunctionLds(context, commands, record.pipeline->Layout()); + if (!heapPipeline && UsesMeshWindow(shaders)) BindMeshWindow(context, commands, record.pipeline->Layout()); APS5_LOG_CHARS_OUT_DEBUG("Resources bound"); pushDrawConstants(*record.pipeline, commands, state, draw, shaders, resources, record.pushBytes, record.pushStages, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty(), drawBindings.get()); APS5_LOG_CHARS_OUT_DEBUG("Push constants recorded"); @@ -2964,7 +2963,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara } if (state.quadList || StripPatches(state, shaders)) recipeOut = nullptr; if (context.recorder != nullptr) context.recorder->BoundKeptBytes(); - if (std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->gpuResolvedImages; })) recipeOut = nullptr; + if (AnyHeapShader(shaders)) recipeOut = nullptr; auto& timing = prepared.timing.emplace("Graphics.Draw"); // APS5_PROFILE_DRAW prints the time of each phase of the draw (microseconds) and the [draws] totals. static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; @@ -3562,12 +3561,13 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D APS5_LOG_OUT_DEBUG("Beginning pipeline renderExtent=%ux%u", state.renderExtent.width, state.renderExtent.height); pipeline->Begin(commands, *framebuffer, state.renderExtent, state); APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); - if (pipeline->DescriptorHeap()) { + const bool heapPipeline = pipeline->DescriptorHeap(); + if (heapPipeline) { resources->BindDescriptorHeaps(commands); NoteEmptyResourceSet(); } else resources->Bind(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->Layout()); - if (pixelLdsSubgroup != 0u && !pipeline->DescriptorHeap()) BindPixelFunctionLds(context, commands, pipeline->Layout()); - if (!pipeline->DescriptorHeap() && UsesMeshWindow(shaders)) BindMeshWindow(context, commands, pipeline->Layout()); + if (pixelLdsSubgroup != 0u && !heapPipeline) BindPixelFunctionLds(context, commands, pipeline->Layout()); + if (!heapPipeline && UsesMeshWindow(shaders)) BindMeshWindow(context, commands, pipeline->Layout()); APS5_LOG_CHARS_OUT_DEBUG("Resources bound"); pushDrawConstants(*pipeline, commands, state, draw, shaders, *resources, nullptr, 0, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty()); APS5_LOG_CHARS_OUT_DEBUG("Push constants recorded"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index c02924f8f49d..1768f2c187db 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -574,8 +574,7 @@ const char* bindImport(const Context& context, HostImport& entry, VkExternalMemo allocated = true; entry.memoryType = allocation.memoryTypeIndex; if (const auto result = context.Function("vkBindBufferMemory")(context.device, entry.buffer, entry.memory, 0); result != VK_SUCCESS) return failed("vkBindBufferMemory", result); - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, entry.buffer}; - entry.address = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + entry.address = BufferDeviceAddress(context, entry.buffer); if (entry.address == 0) return failed("vkGetBufferDeviceAddressKHR", VK_ERROR_UNKNOWN); return nullptr; } @@ -772,10 +771,9 @@ const char* createChunkedDmaBufImport(const Context& context, HostImport& entry, failure = result; return "vkBindBufferMemory"; } - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer}; entry.buffer = buffer; entry.memory = VK_NULL_HANDLE; - entry.address = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + entry.address = BufferDeviceAddress(context, buffer); entry.chunk = std::move(chunk); entry.dmaBuf = true; return nullptr; @@ -864,8 +862,7 @@ bool createSparseDmaBufImport(const Context& context, HostImport& entry, int fil context.Function("vkDestroyFence")(context.device, fence, nullptr); if (bound != VK_SUCCESS) fail("vkQueueBindSparse", bound); if (waited != VK_SUCCESS) fail("vkWaitForFences", waited); - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer}; - const auto address = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + const auto address = BufferDeviceAddress(context, buffer); if (address == 0) fail("vkGetBufferDeviceAddressKHR", VK_ERROR_UNKNOWN); entry.buffer = buffer; entry.memory = VK_NULL_HANDLE; @@ -3105,6 +3102,13 @@ std::vector> refreshHeapRuns(const GuestBu return checked; } +void refreshWritableMirrors(const GuestBufferMemory::AddressSpace& space, std::vector& blocks) { + for (const auto index : space.writableMirrors) { + const auto& region = space.base[index]; + if (prepareRefresh(*region.mirror, region.begin, region.end - region.begin)) appendBlocks(blocks, *region.mirror, region.begin, region.end - region.begin); + } +} + bool heapMirrorWatched(ImageMirror& mirror) { const auto serial = GuestMemory::UnwatchSerial(); if (mirror.watchedSerial.load(std::memory_order_relaxed) == serial) return true; @@ -4449,10 +4453,7 @@ void GuestBufferMemory::AcquireRegistered() { // before any of them is dereferenced. served = true; mirrored = space->mirrored; - for (const auto index : space->writableMirrors) { - const auto& region = space->base[index]; - if (prepareRefresh(*region.mirror, region.begin, region.end - region.begin)) appendBlocks(blocks, *region.mirror, region.begin, region.end - region.begin); - } + refreshWritableMirrors(*space, blocks); lap(timing.mirrorsUs, at); } } @@ -4947,10 +4948,6 @@ std::shared_ptr GuestBufferMemory::ReleaseSpace() { namespace { -bool epochMirrors() { - return DrawPipelineEnabled(); -} - void noteEpochMirrors(bool reused, const GuestBufferMemory::AddressSpace& space) { static std::atomic reuses{0}, refreshes{0}, compared{0}, differing{0}; static const bool verify = std::getenv("APS5_VERIFY_DRAW_PIPELINE") != nullptr; @@ -5004,15 +5001,12 @@ bool GuestBufferMemory::RetakeSpace() { std::vector blocks; const auto epoch = GuestMemory::CollectEpoch(); const auto proof = GuestMemory::ProofSerial(); - const bool reuse = epochMirrors() && epoch != 0 && space->refreshedEpoch.load(std::memory_order_relaxed) == epoch && space->refreshedProof.load(std::memory_order_relaxed) == proof; + const bool reuse = DrawPipelineEnabled() && epoch != 0 && space->refreshedEpoch.load(std::memory_order_relaxed) == epoch && space->refreshedProof.load(std::memory_order_relaxed) == proof; if (reuse) { noteEpochMirrors(true, *space); } else { - for (const auto index : space->writableMirrors) { - const auto& region = space->base[index]; - if (prepareRefresh(*region.mirror, region.begin, region.end - region.begin)) appendBlocks(blocks, *region.mirror, region.begin, region.end - region.begin); - } - if (epochMirrors()) noteEpochMirrors(false, *space); + refreshWritableMirrors(*space, blocks); + if (DrawPipelineEnabled()) noteEpochMirrors(false, *space); } const auto checked = refreshHeapRuns(*space, blocks); compareBlocks(blocks); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index 6c8909957ef5..f32421dcde58 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -343,10 +343,10 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& appendKey(key, shader.pushConstantOffset); if (resources.split) { auto& sets = shader.stage == Stage::Fragment ? keys.fragmentSets : keys.preRasterizationSets; - if (shader.program->gpuResolvedImages) { - sets |= 2u; + if (HeapShader(shader)) { + sets |= HeapSetBit; for (const auto& binding : shader.program->bindings) { - if (binding.descriptorSet == 0u) sets |= 1u; + if (binding.descriptorSet == 0u) sets |= MainSetBit; } } else { for (const auto& binding : shader.program->bindings) { @@ -356,14 +356,14 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& } } } - if (resources.split && std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program->gpuResolvedImages; })) { - keys.preRasterizationSets |= 2u; - keys.fragmentSets |= 2u; + if (resources.split && AnyHeapShader(shaders)) { + keys.preRasterizationSets |= HeapSetBit; + keys.fragmentSets |= HeapSetBit; } if (resources.split) { const auto unused = 3u & ~(keys.preRasterizationSets | keys.fragmentSets); - keys.preRasterizationSets |= unused & 1u; - keys.fragmentSets |= unused & 2u; + keys.preRasterizationSets |= unused & MainSetBit; + keys.fragmentSets |= unused & HeapSetBit; } for (const auto& binding : input.bindings) { appendKey(keys.vertexInput, binding.binding); @@ -440,15 +440,15 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& appendKey(key, ~0u); appendKey(key, sets); appendKey(key, pushStagesOf(context)); - if ((sets & 1u) != 0u) { + if ((sets & MainSetBit) != 0u) { appendKey(key, resources.mainKey.size()); for (const auto word : resources.mainKey) appendKey(key, word); } - if ((sets & 2u) != 0u) { + if ((sets & HeapSetBit) != 0u) { appendKey(key, resources.fragmentKey.size()); for (const auto word : resources.fragmentKey) appendKey(key, word); } - if ((sets & 4u) != 0u) appendKey(key, 0x44415441u); + if ((sets & DataSetBit) != 0u) appendKey(key, DataSetKeyTag); }; splitKey(keys.layout, 3u); splitKey(keys.preRasterizationLayout, keys.preRasterizationSets); @@ -514,16 +514,16 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput specializations.reserve(shaders.size()); std::vector> heapMappings(shaders.size()); std::vector heapMappingInfos(shaders.size(), VkShaderDescriptorSetAndBindingMappingInfoEXT{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}); - if (context.descriptorHeap && DescriptorHeapEnabled() && std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program->gpuResolvedImages; })) { + if (context.descriptorHeap && DescriptorHeapEnabled() && AnyHeapShader(shaders)) { auto& heap = BindlessHeap::For(context); const bool rooted = std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program->dataAddressPush; }); descriptorHeap = std::all_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { const auto index = static_cast(&shader - shaders.data()); - const bool generatedFault = !shader.program->gpuResolvedImages && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const auto& binding) { return binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer; }); + const bool generatedFault = !HeapShader(shader) && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const auto& binding) { return binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer; }); return heap.DescriptorHeapMappings(std::span(shader.program->spirv.data(), shader.program->spirv.size()), heapMappings[index], ~0u, shader.program->dataAddressPush, generatedFault && rooted, shader.program->functionLdsBuffer, shader.program->meshWindowBuffer); }); } - Require(descriptorHeap || std::none_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program->gpuResolvedImages; }), "a pipeline with GPU-mode stages does not map onto VK_EXT_descriptor_heap"); + Require(descriptorHeap || !AnyHeapShader(shaders), "a pipeline with GPU-mode stages does not map onto VK_EXT_descriptor_heap"); const VkPipelineShaderStageRequiredSubgroupSizeCreateInfoEXT meshSubgroup{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO_EXT, nullptr, 32u}; for (std::uint32_t i = 0; i < shaders.size(); ++i) { const auto& shader = *shaders[i].program; @@ -756,10 +756,9 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput pipelineInfo.layout = layout; pipelineInfo.renderPass = renderPass; if (dynamicRendering) pipelineInfo.pNext = &rendering; - VkPipelineCreateFlags2CreateInfoKHR heapFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR}; + VkPipelineCreateFlags2CreateInfoKHR heapFlags{}; if (descriptorHeap) { - heapFlags.flags = static_cast(pipelineInfo.flags) | VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT; - heapFlags.pNext = pipelineInfo.pNext; + heapFlags = DescriptorHeapFlags(static_cast(pipelineInfo.flags), pipelineInfo.pNext); pipelineInfo.pNext = &heapFlags; pipelineInfo.flags = 0; pipelineInfo.layout = VK_NULL_HANDLE; @@ -771,14 +770,14 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput return; } if (prebuilding) { - static_cast(LinkPipelineFromLibraries(context, pipelineInfo, rendering, layoutInfo, keys, &optimized, true, _modules)); + static_cast(LinkPipelineFromLibraries(context, pipelineInfo, rendering, layoutInfo, keys, descriptorHeap, &optimized, true, _modules)); for (const auto module : _modules) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); _modules.clear(); prebuilt = true; return; } const VkPipelineCache pipelineCache = state.stages.tessellation && !context.tessellationPipelineCache ? VK_NULL_HANDLE : context.pipelineCache; - if (libraries) pipeline = LinkPipelineFromLibraries(context, pipelineInfo, rendering, layoutInfo, keys, &optimized, false, _modules); + if (libraries) pipeline = LinkPipelineFromLibraries(context, pipelineInfo, rendering, layoutInfo, keys, descriptorHeap, &optimized, false, _modules); else { auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateGraphicsPipelines")(context.device, pipelineCache, 1, &pipelineInfo, nullptr, &pipeline), "vkCreateGraphicsPipelines"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineLibrary.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineLibrary.cpp index 88a6fbae84b6..01d6ae5a7db7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineLibrary.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineLibrary.cpp @@ -112,14 +112,7 @@ std::span PipelineLibraryDynamicStates() { return dynamicStates; } -bool DescriptorHeapPipelineInfo(const VkGraphicsPipelineCreateInfo& info) { - for (auto* next = static_cast(info.pNext); next != nullptr; next = next->pNext) { - if (next->sType == VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR) return (reinterpret_cast(next)->flags & VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT) != 0; - } - return false; -} - -VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPipelineCreateInfo& info, const VkPipelineRenderingCreateInfoKHR& rendering, const VkPipelineLayoutCreateInfo& layout, const PipelineLibraryKeys& keys, std::shared_ptr* optimized, bool partsOnly, std::span modules) { +VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPipelineCreateInfo& info, const VkPipelineRenderingCreateInfoKHR& rendering, const VkPipelineLayoutCreateInfo& layout, const PipelineLibraryKeys& keys, bool descriptorHeap, std::shared_ptr* optimized, bool partsOnly, std::span modules) { Require(info.renderPass == VK_NULL_HANDLE && info.pDynamicState != nullptr, "pipeline library parts need dynamic rendering and the library dynamic states"); const bool split = (layout.flags & VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT) != 0; Require(!split || ((layout.setLayoutCount == 2u || layout.setLayoutCount == 3u) && layout.pSetLayouts != nullptr && ((keys.preRasterizationSets | keys.fragmentSets) & ~((1u << layout.setLayoutCount) - 1u)) == 0u), "split pipeline library layout requires two or three descriptor set slots and a valid mask"); @@ -156,7 +149,6 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip Check(context.Function("vkCreatePipelineLayout")(context.device, &info, nullptr, &handle), "vkCreatePipelineLayout library"); return device.layouts.emplace(key, handle).first->second; }; - const bool descriptorHeap = DescriptorHeapPipelineInfo(info); const std::array memoryMarker{std::byte{descriptorHeap ? std::uint8_t{2} : std::uint8_t{0}}}; const Key memoryKey(memoryMarker.begin(), memoryMarker.end()); const auto fullLayout = descriptorHeap ? VkPipelineLayout{VK_NULL_HANDLE} : layoutFor(Combined(keys.layout, memoryKey), std::nullopt); @@ -208,7 +200,7 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip library.flags = flags[part]; VkGraphicsPipelineCreateInfo create{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &library}; create.flags = optimize ? VK_PIPELINE_CREATE_LIBRARY_BIT_KHR | VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT : VK_PIPELINE_CREATE_LIBRARY_BIT_KHR; - VkPipelineCreateFlags2CreateInfoKHR partFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR, &library, static_cast(create.flags) | VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT}; + auto partFlags = DescriptorHeapFlags(static_cast(create.flags), &library); create.pDynamicState = info.pDynamicState; create.layout = partLayouts[part]; switch (flags[part]) { @@ -289,7 +281,7 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip VkGraphicsPipelineCreateInfo create{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &linked}; create.flags = 0; create.layout = info.layout; - VkPipelineCreateFlags2CreateInfoKHR linkFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR, &linked, VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT}; + auto linkFlags = DescriptorHeapFlags(0, &linked); if (descriptorHeap) { create.pNext = &linkFlags; create.flags = 0; @@ -325,7 +317,7 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip VkGraphicsPipelineCreateInfo create{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &linked}; create.flags = VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT; create.layout = libraryLayout; - VkPipelineCreateFlags2CreateInfoKHR relinkFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR, &linked, static_cast(VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT) | VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT}; + auto relinkFlags = DescriptorHeapFlags(static_cast(VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT), &linked); if (descriptorHeap) { create.pNext = &relinkFlags; create.flags = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 0664bb82452c..867d9f58382d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -2456,15 +2456,14 @@ void Recorder::dispatchDumps(VkCommandBuffer commands, std::uint32_t firstDump, std::uint32_t phase; } parameters{sampleCounter->DeviceAddress(), sampleCounter->DeviceAddress() + DumpListOffset, firstDump, dumps, firstSegment, lastSegment, 0u}; static_assert(sizeof(parameters) == SampleDumpPushBytes); - const auto push = [&](VkCommandBuffer target, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, std::uint32_t size, const void* values) { CmdPushConstants(context, target, layout, stages, offset, size, values); }; const auto dispatch = function(cmdDispatch, "vkCmdDispatch"); - push(commands, dumpLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleDumpPushBytes, ¶meters); + CmdPushConstants(context, commands, dumpLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleDumpPushBytes, ¶meters); dispatch(commands, 1, 1, 1); if (dumps == 0) return; const auto publish = [&](std::uint32_t phase) { recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); parameters.phase = phase; - push(commands, dumpLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleDumpPushBytes, ¶meters); + CmdPushConstants(context, commands, dumpLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleDumpPushBytes, ¶meters); dispatch(commands, 1, 1, 1); }; publish(1u); @@ -2507,7 +2506,6 @@ void Recorder::foldSamples(Batch& batch, VkDeviceAddress target) { const auto commands = batch.commands; const auto copy = function(cmdCopyQueryPoolResults, "vkCmdCopyQueryPoolResults"); const auto bind = function(cmdBindPipeline, "vkCmdBindPipeline"); - const auto push = [&](VkCommandBuffer target, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, std::uint32_t size, const void* values) { CmdPushConstants(context, target, layout, stages, offset, size, values); }; const auto dispatch = function(cmdDispatch, "vkCmdDispatch"); std::size_t done = 0; do { @@ -2529,13 +2527,13 @@ void Recorder::foldSamples(Batch& batch, VkDeviceAddress target) { std::uint32_t store; } parameters{sampleCounter->DeviceAddress(), target, count, last && target != 0 ? 1u : 0u}; static_assert(sizeof(parameters) == SampleCounterPushBytes); - push(commands, sampleLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleCounterPushBytes, ¶meters); + CmdPushConstants(context, commands, sampleLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleCounterPushBytes, ¶meters); dispatch(commands, 1, 1, 1); if (parameters.store == 1u) { const auto publish = [&](std::uint32_t store) { recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); parameters.store = store; - push(commands, sampleLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleCounterPushBytes, ¶meters); + CmdPushConstants(context, commands, sampleLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleCounterPushBytes, ¶meters); dispatch(commands, 1, 1, 1); }; publish(3u); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ResidentMirror.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ResidentMirror.cpp index 3913660efc5f..72a0f41a4eec 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ResidentMirror.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ResidentMirror.cpp @@ -408,8 +408,7 @@ ResidentBuffer::ResidentBuffer(const Context& context, std::uint64_t base, std:: index = last; } submit(binds); - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer}; - address = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + address = BufferDeviceAddress(context, buffer); if (address == 0) fail("vkGetBufferDeviceAddressKHR of a resident heap mirror", VK_ERROR_UNKNOWN); } catch (...) { release(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp index 1f28a6cd857b..2b905203ab40 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp @@ -48,11 +48,15 @@ VkBuffer BindExactBuffer(const Context& context, std::size_t size, VkBufferUsage return buffer; } +VkBufferUsageFlags UsageWithoutUnsupportedAddress(const Context& context, VkBufferUsageFlags requested, VkBufferUsageFlags pooled) { + if (!context.bufferDeviceAddress && (requested & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) == 0) return pooled & ~static_cast(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); + return pooled; } -Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties) : context(context), size(size), capacity(BufferPool::Capacity(size)), usage(BufferPool::Usage(usage, properties)), properties(properties) { +} + +Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties) : context(context), size(size), capacity(BufferPool::Capacity(size)), usage(UsageWithoutUnsupportedAddress(context, usage, BufferPool::Usage(usage, properties))), properties(properties) { Require(size != 0, "zero-sized GPU buffer"); - if (!context.bufferDeviceAddress && (usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) == 0) this->usage &= ~static_cast(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); const bool addressable = (this->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0; Require(!addressable || context.bufferDeviceAddress, "buffer device address is not enabled"); cache = GetBufferPool(context); @@ -170,9 +174,8 @@ void Buffer::Invalidate() { Check(context.Function("vkInvalidateMappedMemoryRanges")(context.device, 1, &range), "vkInvalidateMappedMemoryRanges"); } -DeviceBuffer::DeviceBuffer(const Context& context, std::size_t size, VkBufferUsageFlags usage) : context(context), size(size), capacity(BufferPool::Capacity(size)), usage(BufferPool::Usage(usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { +DeviceBuffer::DeviceBuffer(const Context& context, std::size_t size, VkBufferUsageFlags usage) : context(context), size(size), capacity(BufferPool::Capacity(size)), usage(UsageWithoutUnsupportedAddress(context, usage, BufferPool::Usage(usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT))) { Require(size != 0, "zero-sized device buffer"); - if (!context.bufferDeviceAddress && (usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) == 0) this->usage &= ~static_cast(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); cache = GetBufferPool(context); if (const auto allocation = cache->Take(size, this->usage, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { buffer = allocation->buffer; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp index 6f69cb75df70..511ba6ce40ed 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp @@ -38,8 +38,8 @@ void ShaderResources::prepareAddressBindings(std::span sha } } -VkDescriptorBufferInfo ShaderResources::descriptor(Allocation& allocation) { - if (allocation.guest) return wholeDwordRange(guestMemory.Descriptor(allocation.address, allocation.size, allocation.adjustment)); +VkDescriptorBufferInfo ShaderResources::descriptor(const Allocation& allocation, std::uint32_t& adjustment) const { + if (allocation.guest) return wholeDwordRange(guestMemory.Descriptor(allocation.address, allocation.size, adjustment)); if (allocation.role == ShaderRecompiler::DescriptorRole::GuestBuffers) { Require(context.emptyBuffer != VK_NULL_HANDLE, "no placeholder buffer for a null V#"); return {context.emptyBuffer, 0, allocation.size}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index e0132fb267d9..12833912a0e3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -2061,6 +2062,28 @@ void ValidateRuntimeResources(const CompiledShader& shader, std::span shaders, const ColorTarget* target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::size_t indexBytes) { @@ -2097,7 +2120,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons Require(stageStorageBuffers <= limits.maxPerStageDescriptorUpdateAfterBindStorageBuffers && stageResources <= limits.maxPerStageUpdateAfterBindResources, "shader descriptors exceed per-stage limits"); updateAfterBind = true; }; - const bool heapShader = shader.program->gpuResolvedImages; + const bool heapShader = HeapShader(shader); if (heapShader) { Require(DescriptorHeapEnabled(), "a GPU-mode stage needs VK_EXT_descriptor_heap (APS5_GPU_HEAP)"); heapStage = true; @@ -2151,27 +2174,24 @@ void ShaderResources::buildPrepare(std::span shaders, cons bindings.back().heap = true; continue; } - if (binding.role == ShaderRecompiler::DescriptorRole::GuestImages && binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) goto perDrawBinding; - if (binding.role == ShaderRecompiler::DescriptorRole::GuestImages || binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers) { + const auto heapClass = ClassifyHeapBinding(binding); + if (heapClass == HeapBindingClass::Unsupported) Require(false, std::string("a GPU-mode fragment stage has an unsupported ") + roleName(binding.role) + " binding"); + if (heapClass == HeapBindingClass::SharedImage) { Require(binding.kind == ShaderRecompiler::DescriptorKind::SampledImage || binding.kind == ShaderRecompiler::DescriptorKind::Sampler, "a GPU-mode stage binds sampled images and samplers only"); addImageBinding(binding, DrawGuestWords(shader, binding), flags); bindings.back().heap = true; continue; } - if (binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable || binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer || binding.role == ShaderRecompiler::DescriptorRole::Gds) goto perDrawBinding; - if (binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers) { - goto perDrawBinding; + if (heapClass == HeapBindingClass::ShaderData) { + Require(binding.count == 1 && !DrawGuestWords(shader, binding).empty(), "invalid GPU-mode shader data binding"); + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, DrawGuestWords(shader, binding)); + Binding item{{binding.binding, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, flags, nullptr}, {}, {}}; + item.heap = true; + item.role = binding.role; + bindings.push_back(std::move(item)); + continue; } - Require(binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt, std::string("a GPU-mode fragment stage has an unsupported ") + roleName(binding.role) + " binding"); - Require(binding.count == 1 && !DrawGuestWords(shader, binding).empty(), "invalid GPU-mode shader data binding"); - if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, DrawGuestWords(shader, binding)); - Binding item{{binding.binding, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, flags, nullptr}, {}, {}}; - item.heap = true; - item.role = binding.role; - bindings.push_back(std::move(item)); - continue; } - perDrawBinding: const bool addressRole = binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable || binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer; const bool bufferRole = addressRole || binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers || binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt || binding.role == ShaderRecompiler::DescriptorRole::Gds; const bool imageRole = binding.role == ShaderRecompiler::DescriptorRole::GuestImages || binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers; @@ -2302,7 +2322,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons const auto heapDataBytes = [&](std::int64_t ring) -> std::uint64_t { const auto stage = HeapRingStage(ring); for (const auto& shader : shaders) { - if (HeapStageIndex(shader.stage) != stage || shader.program == nullptr || !shader.program->gpuResolvedImages) continue; + if (HeapStageIndex(shader.stage) != stage || !HeapShader(shader)) continue; for (const auto& binding : shader.program->bindings) { if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) return binding.guestDescriptor.size() * sizeof(std::uint32_t); } @@ -2371,7 +2391,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons }; if (heapStage) { Require(splitSets && descriptions[1].empty(), "a GPU-mode fragment stage needs split sets and no per-draw fragment bindings"); - fragmentLayoutKey = {0x48454150u}; + fragmentLayoutKey = {HeapLayoutKeyTag}; } _layout = createLayout(layoutKey, descriptions[0], layoutBindingFlags, ownsLayout); if (splitSets && !heapStage) { @@ -2457,8 +2477,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons bool SplitsSets(const Context& context, std::span shaders) { const auto fragmentSet = [](const CompiledShader& shader) { return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const auto& binding) { return binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet; }); }; const auto fragmentStage = [](const CompiledShader& shader) { return shader.stage == ShaderRecompiler::ShaderStage::Fragment; }; - const auto heapStage = [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->gpuResolvedImages; }; - return std::any_of(shaders.begin(), shaders.end(), fragmentSet) || std::any_of(shaders.begin(), shaders.end(), heapStage) || (context.graphicsPipelineLibrary && std::any_of(shaders.begin(), shaders.end(), fragmentStage)); + return std::any_of(shaders.begin(), shaders.end(), fragmentSet) || AnyHeapShader(shaders) || (context.graphicsPipelineLibrary && std::any_of(shaders.begin(), shaders.end(), fragmentStage)); } DescribedSetLayouts DescribeSetLayouts(const Context& context, std::span shaders) { @@ -2472,12 +2491,11 @@ DescribedSetLayouts DescribeSetLayouts(const Context& context, std::spangpuResolvedImages; }; - const bool heapStage = std::any_of(shaders.begin(), shaders.end(), heapShader); + const bool heapStage = AnyHeapShader(shaders); for (const auto& shader : shaders) { Require(shader.program != nullptr, "missing compiled shader"); const VkShaderStageFlags flags = VulkanStage(shader.stage); - const bool gpuMode = heapShader(shader); + const bool gpuMode = HeapShader(shader); std::uint64_t stageStorageBuffers = 0; std::uint64_t stageResources = 0; const bool addressedStage = gpuMode && shader.program->dataAddressPush; @@ -2500,8 +2518,8 @@ DescribedSetLayouts DescribeSetLayouts(const Context& context, std::spanLayout(result.mainKey, descriptions[0], updateAfterBind, bindingFlags[0]); if (heapStage) { Require(split && descriptions[1].empty(), "a GPU-mode stage needs split sets and no per-draw fragment bindings"); - result.fragmentKey = {0x48454150u}; + result.fragmentKey = {HeapLayoutKeyTag}; return result; } if (split) result.layouts.fragment = context.descriptorCache->Layout(result.fragmentKey, descriptions[1], updateAfterBind, bindingFlags[1]); @@ -2844,7 +2862,8 @@ bool ShaderResources::AddressTableGuardCurrent() { } bool ShaderResources::SpaceReuseDisabled() { - return !GpuHeapEnabled(); + static const bool disabled = std::getenv("APS5_NO_SPACE_REUSE") != nullptr; + return disabled || !GpuHeapEnabled(); } // APS5_PROFILE_DRAW: the per-device descriptor caches' counters, every 10 s. @@ -2871,7 +2890,7 @@ void VisitContentKey(const CompiledShader& shader, bool dataWords, bool movableB visit(static_cast(program.PipelineVariantId() >> 32u)); if (shader.heap != nullptr && program.heapTemplateId != 0) { visit(0u); - visit(0x48454150u); + visit(HeapLayoutKeyTag); visit(static_cast(program.heapTemplateId)); visit(static_cast(program.heapTemplateId >> 32u)); for (const auto& binding : program.bindings) { @@ -4889,7 +4908,7 @@ VkBuffer ShaderResources::shaderDataBuffer(const CompiledShader& shader) const { } void ShaderResources::forgetShaderDataWords(const CompiledShader& shader) { - if (shader.program != nullptr && shader.program->gpuResolvedImages) { + if (HeapShader(shader)) { auto& stageState = heapStages[HeapStageIndex(shader.stage)]; stageState.data.mark.entry = 0; stageState.data.words.clear(); @@ -5356,7 +5375,7 @@ ShaderResources::TableStage& ShaderResources::tableStage(const CompiledShader& s table.program = shader.program; table.poison = shader.program->imageTablePoison; table.messages.assign(table.poison.size(), nullptr); - table.heap = shader.program->gpuResolvedImages && shader.program->dataAddressPush; + table.heap = HeapShader(shader) && shader.program->dataAddressPush; return table; } @@ -5846,7 +5865,7 @@ std::optional> ShaderResources::MovedR if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE && !heapStage) || (usesBda && !spaceReuse)) return moved; for (const auto& shader : shaders) { if (shader.program == nullptr) return std::nullopt; - const bool heapShader = shader.program->gpuResolvedImages; + const bool heapShader = HeapShader(shader); for (const auto& binding : shader.program->bindings) { if (heapShader && (DataRole(binding.role) || binding.role == ShaderRecompiler::DescriptorRole::GuestImages || binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers)) continue; if (DataRole(binding.role)) { @@ -6184,32 +6203,37 @@ PipelineSetLayouts ShaderResources::SetLayouts() const { void ShaderResources::RefreshHeapStage(std::span shaders) { for (const auto& shader : shaders) { - if (shader.program != nullptr && shader.program->gpuResolvedImages) writeHeapStage(shader); + if (HeapShader(shader)) writeHeapStage(shader); } } void ShaderResources::writeBufferAddresses(std::span words, std::uint32_t dataStage, const std::vector* overrides) const { - thread_local VkDevice addressDevice = VK_NULL_HANDLE; - thread_local PFN_vkGetBufferDeviceAddressKHR bufferAddress = nullptr; - if (addressDevice != context.device || bufferAddress == nullptr) { - bufferAddress = context.Function("vkGetBufferDeviceAddressKHR"); - addressDevice = context.device; - } for (const auto& binding : bindings) { if (!binding.addressed || binding.dataStage != dataStage) continue; for (std::size_t element = 0; element < binding.allocations.size(); ++element) { const auto index = binding.allocations[element]; - auto info = overrides != nullptr && (*overrides)[index].buffer != VK_NULL_HANDLE ? (*overrides)[index] : const_cast(this)->descriptor(const_cast(allocations[index])); - if (info.buffer == VK_NULL_HANDLE) info = {context.emptyBuffer, 0, EmptyBufferBytes}; - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, info.buffer}; - const auto base = bufferAddress(context.device, &addressInfo); - Require(base != 0, "an addressed buffer has no device address"); - const auto address = base + info.offset; + const auto& allocation = allocations[index]; + const bool overridden = overrides != nullptr && (*overrides)[index].buffer != VK_NULL_HANDLE; + const bool owned = !overridden && !allocation.guest && allocation.buffer != nullptr && allocation.role != ShaderRecompiler::DescriptorRole::GuestBuffers && allocation.role != ShaderRecompiler::DescriptorRole::BdaPagetable && allocation.role != ShaderRecompiler::DescriptorRole::FaultBuffer; + VkDeviceAddress address = 0; + VkDeviceSize range = 0; + if (owned) { + address = allocation.buffer->DeviceAddress(); + range = allocation.size; + } else { + auto adjustment = allocation.adjustment; + auto info = overridden ? (*overrides)[index] : descriptor(allocation, adjustment); + if (info.buffer == VK_NULL_HANDLE) info = {context.emptyBuffer, 0, EmptyBufferBytes}; + const auto base = BufferDeviceAddress(context, info.buffer); + Require(base != 0, "an addressed buffer has no device address"); + address = base + info.offset; + range = info.range; + } const auto at = static_cast(binding.addressDword) + element * 4u; Require(at + 3u < words.size(), "buffer address words lie outside the shader data"); words[at] = static_cast(address); words[at + 1u] = static_cast(address >> 32u); - words[at + 2u] = static_cast(std::min(info.range, 0xffffffffu)); + words[at + 2u] = static_cast(std::min(range, 0xffffffffu)); words[at + 3u] = 0u; } } @@ -6225,7 +6249,7 @@ std::size_t DataOffsetIndex(std::size_t stage, ShaderRecompiler::RuntimeAbi::Bin } std::pair ShaderResources::shaderDataLocation(const CompiledShader& shader, const DrawBindings* rewritten) const { - if (!heapStage || shader.program == nullptr || !shader.program->gpuResolvedImages) return {shaderDataBuffer(shader), 0}; + if (!heapStage || !HeapShader(shader)) return {shaderDataBuffer(shader), 0}; const auto& offsets = rewritten != nullptr && rewritten->addressOffsets ? rewritten->heapOffsets : heapOffsets; const auto& heap = BindlessHeap::For(context); return {heap.RingBuffer(), heap.RingOffset() + offsets[DataOffsetIndex(HeapStageIndex(shader.stage), ShaderRecompiler::RuntimeAbi::Binding::ShaderData)]}; @@ -6245,10 +6269,8 @@ void ShaderResources::PatchDataAddresses(std::span("vkGetBufferDeviceAddressKHR"); const auto of = [&](const VkDescriptorBufferInfo& info) { - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, info.buffer}; - const auto base = address(context.device, &addressInfo); + const auto base = BufferDeviceAddress(context, info.buffer); Require(base != 0, "a BDA buffer has no device address"); return base + info.offset; }; @@ -6283,10 +6305,10 @@ void ShaderResources::PatchDataAddresses(std::span::max()) { const auto* overrides = rewritten != nullptr && rewritten->addressOffsets ? &rewritten->addressOverrides : nullptr; - auto info = overrides != nullptr && (*overrides)[gdsAllocation].buffer != VK_NULL_HANDLE ? (*overrides)[gdsAllocation] : const_cast(this)->descriptor(const_cast(allocations[gdsAllocation])); + auto adjustment = allocations[gdsAllocation].adjustment; + const auto info = overrides != nullptr && (*overrides)[gdsAllocation].buffer != VK_NULL_HANDLE ? (*overrides)[gdsAllocation] : descriptor(allocations[gdsAllocation], adjustment); Require(info.buffer != VK_NULL_HANDLE, "the GDS buffer is missing"); - const VkBufferDeviceAddressInfo addressInfo{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, info.buffer}; - const auto base = context.Function("vkGetBufferDeviceAddressKHR")(context.device, &addressInfo); + const auto base = BufferDeviceAddress(context, info.buffer); Require(base != 0, "the GDS buffer has no device address"); split(Abi::RootGdsAddress, base + info.offset); } @@ -6557,6 +6579,19 @@ void ShaderResources::verifyHeapSlots(const BindlessHeap& heap, const HeapStageS } } +namespace { + +[[noreturn]] void ThrowHeapSlotMismatch(const char* format, ...) { + char text[320]; + va_list arguments; + va_start(arguments, format); + std::vsnprintf(text, sizeof(text), format, arguments); + va_end(arguments); + throw std::runtime_error(text); +} + +} + void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const HeapStageState& stageState, std::vector& patched, bool current) const { namespace Abi = ShaderRecompiler::RuntimeAbi; @@ -6573,14 +6608,11 @@ void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const Hea auto& first = patched[offset + offsetof(Abi::ResourceMetadata, firstElement) / 4u]; if (kind < Abi::FirstImageBinding) continue; if (!(kind < slots.size() && first < slots[kind].size())) { - char text[320]; - std::snprintf( - text, sizeof(text), + ThrowHeapSlotMismatch( "AGC graphics: GPU-mode image metadata names an element the stage does not bind (stage %u, image %u of %u, kind %u, first %u, slots of the kind %zu, flags 0x%x, element count %u, bindings %zu, stage state reused %d)", static_cast(shader.stage), image, program.runtimeImageCount, kind, first, kind < slots.size() ? slots[kind].size() : std::size_t{0}, patched[offset + offsetof(Abi::ResourceMetadata, flags) / 4u], patched[offset + offsetof(Abi::ResourceMetadata, elementCount) / 4u], bindings.size(), current ? 1 : 0); - throw std::runtime_error(text); } first = slots[kind][first]; } @@ -6588,23 +6620,17 @@ void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const Hea Require(word.dword < patched.size(), "a GPU-mode slot word lies outside the shader data"); if (word.kind == static_cast(Abi::Binding::Samplers)) { if (word.element >= samplerSlots.size()) { - char text[256]; - std::snprintf(text, sizeof(text), - "AGC graphics: a GPU-mode slot word names a sampler the stage does not bind (stage %u, element %u, sampler slots %zu, bindings %zu)", - static_cast(shader.stage), word.element, samplerSlots.size(), bindings.size()); - throw std::runtime_error(text); + ThrowHeapSlotMismatch("AGC graphics: a GPU-mode slot word names a sampler the stage does not bind (stage %u, element %u, sampler slots %zu, bindings %zu)", + static_cast(shader.stage), word.element, samplerSlots.size(), bindings.size()); } patched[word.dword] = samplerSlots[word.element]; continue; } if (!(word.kind < slots.size() && word.element < slots[word.kind].size())) { - char text[256]; - std::snprintf( - text, sizeof(text), + ThrowHeapSlotMismatch( "AGC graphics: a GPU-mode slot word names an image the stage does not bind (stage %u, kind %u, element %u, slots of the kind %zu, bindings %zu)", static_cast(shader.stage), word.kind, word.element, word.kind < slots.size() ? slots[word.kind].size() : std::size_t{0}, bindings.size()); - throw std::runtime_error(text); } patched[word.dword] = slots[word.kind][word.element]; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index cb85939b5e4d..be60c6d18224 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -733,7 +733,7 @@ std::set ValidateShaders(std::span shaders, const auto expected = state.rectList || patches ? (i == 0 ? Stage::Vertex : tessStages[i]) : tessellation ? tessStages[i] : geometry && i == 1 ? Stage::Geometry : i == shaders.size() - 1 ? Stage::Fragment : state.stages.path == ShaderPath::Geometry ? Stage::Mesh : Stage::Vertex; Require(shaders[i].program != nullptr, "missing compiled shader"); Require(shaders[i].stage == expected, "graphics stage order disagrees"); - for (const auto& binding : shaders[i].program->bindings) Require(binding.descriptorSet == ShaderRecompiler::RuntimeAbi::DescriptorSet || (shaders[i].program->dataAddressPush && binding.role == ShaderRecompiler::DescriptorRole::Gds && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::GpuGdsSet) || ((shaders[i].stage == ShaderRecompiler::ShaderStage::Fragment || shaders[i].program->gpuResolvedImages) && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet), "graphics resource uses a descriptor set other than its stage's"); + for (const auto& binding : shaders[i].program->bindings) Require(binding.descriptorSet == ShaderRecompiler::RuntimeAbi::DescriptorSet || (shaders[i].program->dataAddressPush && binding.role == ShaderRecompiler::DescriptorRole::Gds && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::GpuGdsSet) || ((shaders[i].stage == ShaderRecompiler::ShaderStage::Fragment || HeapShader(shaders[i])) && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet), "graphics resource uses a descriptor set other than its stage's"); const auto current = Inspect(shaders[i], state, subgroup, fragmentShaderBarycentric, descriptorIndexing, imageInt64Atomics, geometryShader, sampleRateShading, bufferInt64Atomics, shaderClipDistance, shaderCullDistance, viewportIndexLayer, runtimeDescriptorArray, demoteToHelperInvocation, shaderTerminateInvocation, primitiveLocations); if (i != 0) { for (const auto& [location, signature] : current.inputs) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index 0e557e1b26a3..6e6e7ea43f2a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -224,8 +224,7 @@ VkFormat TextureDetiler::ImageElementFormat(std::uint32_t elementBytes) { VkDeviceAddress TextureDetiler::bufferAddress(VkBuffer buffer) const { if (addressedPipelineLayout == VK_NULL_HANDLE || !BufferPool::ForceAddresses()) return 0; - const VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer}; - return context.Function("vkGetBufferDeviceAddressKHR")(context.device, &info); + return BufferDeviceAddress(context, buffer); } VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, bool addressed, bool heap) { @@ -289,7 +288,7 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem createInfo.layout = addressed ? addressedPipelineLayout : image ? imagePipelineLayout : pipelineLayout; std::array mappings{}; VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; - VkPipelineCreateFlags2CreateInfoKHR heapFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR}; + auto heapFlags = DescriptorHeapFlags(); if (heap) { Require(image && !addressed, "only the image detiler runs on the descriptor heap"); const auto& bindless = BindlessHeap::For(context); @@ -298,7 +297,6 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem mappingInfo.mappingCount = static_cast(mappings.size()); mappingInfo.pMappings = mappings.data(); createInfo.stage.pNext = &mappingInfo; - heapFlags.flags = VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT; createInfo.pNext = &heapFlags; createInfo.layout = VK_NULL_HANDLE; } @@ -521,8 +519,7 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; mappingInfo.mappingCount = static_cast(mappings.size()); mappingInfo.pMappings = mappings.data(); - VkPipelineCreateFlags2CreateInfoKHR heapFlags{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR}; - heapFlags.flags = VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT; + auto heapFlags = DescriptorHeapFlags(); auto heapInfo = pipelineInfo; heapInfo.pNext = &heapFlags; heapInfo.stage.pNext = &mappingInfo; diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index d8c33795e553..e2b99f01228e 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -344,6 +344,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_SITE_SAMPLING` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WriteEvidence.cpp` | | disables per-site sampling of write evidence | | `APS5_NO_SNAPSHOT_CHECK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | skips the live compare that proves a captured snapshot still equals the guest bytes | | `APS5_NO_SORTED_SNAPSHOT_LOOKUP` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | scans the snapshot's regions in AddSnapshot instead of searching them | +| `APS5_NO_SPACE_REUSE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | turns off the reuse of a read-only address-space draw's resources across draws (a held address space, and the read-only BDA shaders' exemption from never being reused); already off without APS5_GPU_HEAP | | `APS5_NO_SPACE_STAMP_ONCE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | stamps every direct import of a cached address space on each hit instead of once per space | | `APS5_NO_SPARSE_HEAP_MIRROR` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | disables sparse heap mirrors, mirroring only whole heap ranges | | `APS5_NO_STAGE_A_IMAGES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | leaves every image element to the stage-B full lookup instead of a stage-A record | From 866bd70c7083ce7f7f19b8738db9105cf6f0c77a Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 1 Nov 2026 01:32:30 +0530 Subject: [PATCH 086/269] refactor(shader): tidy the GPU heap recompiler paths Drop the second encode/decode of userDataRegisterReads in the disk cache, remove always-true heap conditions, share heap templates by pointer and build their words outside the source lock, name the heap parts, storage-kind stride and slot word sizes, share the root stage table with the driver, and replace positional bool parameters with named option structs. --- .../Graphics/include/ShaderResources.hpp | 9 +- .../Graphics/src/ShaderResources.cpp | 2 +- core/shader/recompiler/CMakeLists.txt | 2 + core/shader/recompiler/CacheKey.hpp | 1 - core/shader/recompiler/Deserialize.cpp | 2 +- .../include/Optimization/BindingAllocator.hpp | 9 +- .../Optimization/src/BindingAllocator.cpp | 9 +- .../src/DescriptorBindingBuilder.cpp | 40 ++- core/shader/recompiler/Recompiler.cpp | 256 ++++++++++-------- core/shader/recompiler/RuntimeAbi.hpp | 38 ++- core/shader/recompiler/ShaderDiskCache.cpp | 2 - .../SpirvMemory/SpirvBufferAccess.hpp | 1 - .../SpirvBackend/src/SpirvBdaLookup.cpp | 1 - .../src/SpirvMemory/SpirvBufferAccess.cpp | 12 +- .../src/SpirvMemory/SpirvDescriptors.cpp | 48 ++-- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 11 +- .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 2 +- 17 files changed, 263 insertions(+), 182 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index fb7d17f2c921..d25247d67c02 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -73,13 +73,8 @@ std::shared_ptr RepeatStorageSurface(const Context& context, con bool PendingStorageOverlaps(std::uint64_t address, std::size_t bytes, const StorageTexture* except); inline std::size_t HeapStageIndex(ShaderRecompiler::ShaderStage stage) { - namespace Abi = ShaderRecompiler::RuntimeAbi; - switch (stage) { - case ShaderRecompiler::ShaderStage::Fragment: return static_cast(Abi::Stage::Fragment); - case ShaderRecompiler::ShaderStage::TessellationControl: return static_cast(Abi::Stage::TessellationControl); - case ShaderRecompiler::ShaderStage::TessellationEvaluation: return static_cast(Abi::Stage::TessellationEvaluation); - default: return static_cast(Abi::Stage::Main); - } + using ShaderRecompiler::ShaderStage; + return static_cast(ShaderRecompiler::RuntimeAbi::StageGroup(stage == ShaderStage::Fragment, stage == ShaderStage::TessellationControl, stage == ShaderStage::TessellationEvaluation)); } struct PipelineSetLayouts { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 12833912a0e3..36b1bae4a39f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -58,7 +58,7 @@ std::uint32_t takenSlot(std::optional slot, const char* what) { bool UintStorageBinding(std::uint32_t binding) { const auto kind = binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count); - return kind >= ShaderRecompiler::RuntimeAbi::FirstUintStorageImageBinding && kind < ShaderRecompiler::RuntimeAbi::FirstAtomicImageBinding; + return ShaderRecompiler::RuntimeAbi::UintStorageImageKind(kind); } bool overlap(std::uint64_t first, std::size_t firstSize, std::uint64_t second, std::size_t secondSize) { diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index f78e0c788303..6d6d3e624210 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -242,6 +242,8 @@ function(add_shader_recompiler target runtimeTarget) set(shaderCacheReviewedNames BdaAbi::RangesOrdered RuntimeAbi::GpuHeapStorageKind + RuntimeAbi::StageGroup + RuntimeAbi::UintStorageImageKind StorageElementPointer FirstAtomicStorageImageBinding BuildBarycentricGeometryShader diff --git a/core/shader/recompiler/CacheKey.hpp b/core/shader/recompiler/CacheKey.hpp index e8423099ff19..46890406b8d5 100644 --- a/core/shader/recompiler/CacheKey.hpp +++ b/core/shader/recompiler/CacheKey.hpp @@ -6,7 +6,6 @@ #include "prx/libc/include/HostThreadLocal.hpp" #include #include -#include #include #include #include diff --git a/core/shader/recompiler/Deserialize.cpp b/core/shader/recompiler/Deserialize.cpp index 5bc2aec69619..4a6ada3e769a 100644 --- a/core/shader/recompiler/Deserialize.cpp +++ b/core/shader/recompiler/Deserialize.cpp @@ -227,7 +227,7 @@ int main(int argc, char** argv) { std::cout << "ShaderInfoCollector::Collect OK\n"; BindingAllocator bindingAllocator; - const auto bindings = bindingAllocator.Allocate(program, request.layout, request.target.registrationModules); + const auto bindings = bindingAllocator.Allocate(program, request.layout, {.registrationModules = request.target.registrationModules}); std::cout << "BindingAllocator::Allocate OK, bindings=" << bindings.bindings.size() << "\n"; std::cout << "ALL STAGES OK\n"; diff --git a/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp b/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp index 0b402bdff22c..0710b88619b9 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp @@ -22,9 +22,16 @@ struct BindingAllocationResult : CompiledBindingLayout { std::vector shaderDataUserWords; }; +struct AllocationOptions { + bool registrationModules = false; + bool stencilReplay = false; + bool gpuResolvedImages = false; + bool descriptorMemory = false; +}; + class BindingAllocator { public: - [[nodiscard]] BindingAllocationResult Allocate(IrProgram& program, const BindingLayout& layout, bool registrationModules = false, bool stencilReplay = false, bool gpuResolvedImages = false, bool descriptorMemory = false) const; + [[nodiscard]] BindingAllocationResult Allocate(IrProgram& program, const BindingLayout& layout, const AllocationOptions& options = {}) const; [[nodiscard]] const IrDescriptorBinding& FindBinding(const IrBindingLayout& layout, DescriptorBindingKind kind) const; }; diff --git a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp index 81fbcc7ce3f0..7222b420070c 100644 --- a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp +++ b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp @@ -68,7 +68,8 @@ bool usesGds(const IrProgram& program) { } -BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const BindingLayout& layout, bool registrationModules, bool stencilReplay, bool gpuResolvedImages, bool descriptorMemory) const { +BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const BindingLayout& layout, const AllocationOptions& options) const { + const auto [registrationModules, stencilReplay, gpuResolvedImages, descriptorMemory] = options; IrProgramMetadata& metadata = program.Metadata(); if (!metadata.shaderInfoComplete || metadata.bindingLayoutComplete) { fail(metadata.shaderInfoComplete ? "shader binding layout failed: binding layout already allocated" @@ -114,7 +115,7 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin next.runtimeStateDwords = (attributes + RuntimeAbi::VertexSelectorsPerDword - 1u) / RuntimeAbi::VertexSelectorsPerDword; } if (gpuResolvedImages) { - next.samplerSlotDwords = static_cast(info.samplers.size()) * 2u; + next.samplerSlotDwords = static_cast(info.samplers.size()) * RuntimeAbi::SamplerSlotWords; next.gpuResolvedImages = true; } const auto pushSize = layout.pushConstantSizeBytes / 4u; @@ -160,13 +161,13 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin } } - next.heapStorageImages = gpuResolvedImages && descriptorMemory && next.gpuResolvedImages; + next.heapStorageImages = gpuResolvedImages && descriptorMemory; if (gpuResolvedImages && !registrationModules) { for (const auto& descriptor : next.descriptors) { if (next.HeapImageKind(descriptor.kind)) next.imageSlotDwords += static_cast(descriptor.resources.size()); } } - if (descriptorMemory && next.gpuResolvedImages) next.bufferAddressDwords = static_cast(info.buffers.size()) * 4u; + if (descriptorMemory && gpuResolvedImages) next.bufferAddressDwords = static_cast(info.buffers.size()) * RuntimeAbi::BufferAddressWords; std::vector samplers; for (std::uint32_t i = 0; i < info.samplers.size(); i++) { diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index 35daeda2fc35..d092d02f66a3 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -415,6 +415,14 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l plan.bindings.reserve(layout.descriptors.size()); const bool slotWords = layout.gpuResolvedImages && !registrationModules; std::uint32_t imageSlotBase = layout.ImageSlotDword(); + const auto descriptorSetFor = [&](DescriptorBindingKind kind) { + if (kind == DescriptorBindingKind::Gds && layout.UsesDataAddress()) return RuntimeAbi::GpuGdsSet; + if (layout.gpuResolvedImages) { + const bool heapSetBinding = layout.HeapImageKind(kind) || kind == DescriptorBindingKind::Samplers || kind == DescriptorBindingKind::ShaderData || kind == DescriptorBindingKind::FlattenedSrt; + return heapSetBinding ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet; + } + return fragmentDescriptorSet && stage == IrShaderStage::Pixel ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet; + }; for (const auto& logical : layout.descriptors) { const bool imageHeap = ImageBindingResourceClass(logical.kind) != ImageResourceClass::None; const bool samplerHeap = logical.kind == DescriptorBindingKind::Samplers; @@ -455,9 +463,8 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l PreparedDescriptorBinding entry{}; auto& physical = entry.descriptor; const bool heapImage = layout.HeapImageKind(compact.kind); - const bool heapSetBinding = heapImage || samplerHeap || compact.kind == DescriptorBindingKind::ShaderData || compact.kind == DescriptorBindingKind::FlattenedSrt; const bool sharedHeapArray = layout.gpuResolvedImages && (heapImage || samplerHeap); - physical.descriptorSet = compact.kind == DescriptorBindingKind::Gds && layout.UsesDataAddress() ? RuntimeAbi::GpuGdsSet : layout.gpuResolvedImages ? (heapSetBinding ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet) : fragmentDescriptorSet && stage == IrShaderStage::Pixel ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet; + physical.descriptorSet = descriptorSetFor(compact.kind); physical.binding = NativeBinding(sharedHeapArray ? IrShaderStage::Pixel : stage, compact.kind); physical.count = compact.resources.empty() ? 1u : static_cast(compact.resources.size()); physical.kind = PhysicalKindFor(compact.kind); @@ -556,22 +563,39 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l return plan; } +namespace { + +bool IsAddressedRole(const DescriptorBindingPlan& plan, DescriptorRole role) { + switch (role) { + case DescriptorRole::GuestBuffers: return plan.addressedBuffers; + case DescriptorRole::ShaderData: + case DescriptorRole::FlattenedSrt: + case DescriptorRole::BdaPagetable: + case DescriptorRole::FaultBuffer: + case DescriptorRole::ImageTable: + case DescriptorRole::ImageStorageTable: + case DescriptorRole::SamplerTable: + case DescriptorRole::ImageTableMap: return plan.addressedData; + default: return false; + } +} + +} + DescriptorBindingPlan DescriptorBindingBuilder::Select(const DescriptorBindingPlan& plan, std::span bindings) const { DescriptorBindingPlan selected; std::set remaining(bindings.begin(), bindings.end()); selected.bindings.reserve(remaining.size()); for (const auto& binding : plan.bindings) { - const bool addressed = (plan.addressedBuffers && binding.descriptor.role == DescriptorRole::GuestBuffers) || (plan.addressedData && (binding.descriptor.role == DescriptorRole::ShaderData || binding.descriptor.role == DescriptorRole::FlattenedSrt || binding.descriptor.role == DescriptorRole::BdaPagetable || binding.descriptor.role == DescriptorRole::FaultBuffer || binding.descriptor.role == DescriptorRole::ImageTable || binding.descriptor.role == DescriptorRole::ImageStorageTable || binding.descriptor.role == DescriptorRole::SamplerTable || binding.descriptor.role == DescriptorRole::ImageTableMap)); + const bool addressed = IsAddressedRole(plan, binding.descriptor.role); if (remaining.erase(binding.descriptor.binding) == 0u && !addressed) continue; selected.storageData |= binding.descriptor.role == DescriptorRole::ShaderData; selected.bindings.push_back(binding); } if (plan.addressedData) { - remaining.erase(NativeBinding(IrShaderStage::Pixel, static_cast(RuntimeAbi::FirstImageBinding))); - remaining.erase(NativeBinding(IrShaderStage::Pixel, static_cast(RuntimeAbi::FirstStorageImageBinding))); - remaining.erase(NativeBinding(IrShaderStage::Pixel, static_cast(RuntimeAbi::FirstAtomicImageBinding))); - remaining.erase(NativeBinding(IrShaderStage::Pixel, static_cast(RuntimeAbi::FirstAtomic64ImageBinding))); - remaining.erase(NativeBinding(IrShaderStage::Pixel, DescriptorBindingKind::Samplers)); + for (const auto kind : {RuntimeAbi::FirstImageBinding, RuntimeAbi::FirstStorageImageBinding, RuntimeAbi::FirstAtomicImageBinding, RuntimeAbi::FirstAtomic64ImageBinding, static_cast(DescriptorBindingKind::Samplers)}) { + remaining.erase(NativeBinding(IrShaderStage::Pixel, static_cast(kind))); + } } if (!remaining.empty()) fail("specialized module bindings disagree with the prepared plan"); const bool hasSamplers = std::any_of(selected.bindings.begin(), selected.bindings.end(), [](const auto& binding) { return binding.descriptor.role == DescriptorRole::GuestSamplers; }); diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index dbb02c89ca85..9bd1401ee9d9 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -15,7 +15,6 @@ #include "SpirvBackend/SpirvSpecialization.hpp" #include "RdnaDecoder/RdnaDescriptorFormat.hpp" #include "ShaderDiskCache.hpp" -#include #include #include #include @@ -401,9 +400,18 @@ constexpr std::size_t ResultMemoSets = 64; constexpr std::size_t ResultMemoWays = 4; using ResultMemoTable = std::array; +std::uint64_t NextId(std::atomic& counter) { + return counter.fetch_add(1, std::memory_order_relaxed) + 1u; +} + std::uint64_t NextSourceId() { static std::atomic ids{0}; - return ids.fetch_add(1, std::memory_order_relaxed) + 1u; + return NextId(ids); +} + +std::uint64_t NextTemplateId() { + static std::atomic ids{0}; + return NextId(ids); } struct UsedBindingPlan { @@ -439,7 +447,7 @@ struct SourceEntry : std::enable_shared_from_this { std::vector emissionFailures; std::unique_ptr memo; std::unique_ptr maskedMemo; - std::unordered_map heapTemplates; + std::unordered_map> heapTemplates; }; namespace { @@ -485,7 +493,7 @@ void KeepHeapTemplate(const std::shared_ptr& source, std::uint64_t if (owner == nullptr) continue; std::lock_guard lock(owner->mutex); const auto found = owner->heapTemplates.find(gone.name.key); - if (found == owner->heapTemplates.end() || found->second.result->heapTemplateId != gone.name.id) continue; + if (found == owner->heapTemplates.end() || found->second->result->heapTemplateId != gone.name.id) continue; owner->heapTemplates.erase(found); ++erased; } @@ -664,7 +672,7 @@ std::array partialThreads(const RecompileRequest& request) { std::uint64_t nextVariantId() { static std::atomic variants{0}; - return variants.fetch_add(1, std::memory_order_relaxed) + 1; + return NextId(variants); } template @@ -707,9 +715,8 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) bool registration = request.target.registrationModules && (request.shader.stage == ShaderStage::Vertex || request.shader.stage == ShaderStage::Fragment); program.Metadata().bindingLayoutComplete = false; const bool stencilReplay = request.shader.stage == ShaderStage::Fragment && std::ranges::any_of(program.Info().outputs, [](const StageOutput& output) { return output.kind == StageOutputKind::StencilRef; }) && std::ranges::find(request.target.supportedCapabilities, static_cast(spv::CapabilityStencilExportEXT)) == request.target.supportedCapabilities.end(); - const bool gpuResolved = request.target.gpuResolvedImages; - auto bindings = bindingAllocator.Allocate(program, request.layout, registration, stencilReplay, gpuResolved, request.target.descriptorMemory); - const bool gpuMode = gpuResolved && bindings.layout.gpuResolvedImages; + AllocationOptions allocation {.registrationModules = registration, .stencilReplay = stencilReplay, .gpuResolvedImages = request.target.gpuResolvedImages, .descriptorMemory = request.target.descriptorMemory}; + auto bindings = bindingAllocator.Allocate(program, request.layout, allocation); SpirvTargetOptions targetOptions {}; targetOptions.vulkanVersion = request.target.vulkanVersion; @@ -768,7 +775,7 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) } targetOptions.waveLdsMemoryBarriers = request.target.waveLdsMemoryBarriers; targetOptions.deviceScopeLdsMemoryBarriers = request.target.deviceScopeLdsMemoryBarriers; - targetOptions.gpuResolvedImages = gpuMode; + targetOptions.gpuResolvedImages = allocation.gpuResolvedImages; targetOptions.heapDataUniformDwords = request.target.heapDataUniformDwords; targetOptions.ldsLockFences = request.target.ldsLockFences; targetOptions.meshWindowBuffer = request.target.meshWindowBuffer; @@ -787,8 +794,8 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) if (registration && result.spirv.size() > request.target.registrationWordLimit) { registration = false; program.Metadata().bindingLayoutComplete = false; - bindings = bindingAllocator.Allocate(program, request.layout, false, stencilReplay, gpuResolved, request.target.descriptorMemory); - targetOptions.gpuResolvedImages = gpuResolved && bindings.layout.gpuResolvedImages; + allocation.registrationModules = false; + bindings = bindingAllocator.Allocate(program, request.layout, allocation); targetOptions.registrationModules = false; result.spirv = spirvEmitter.Emit(program, inputInfo, bindings, targetOptions, &emitted); } @@ -803,7 +810,7 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) result.gpuResolvedImages = targetOptions.gpuResolvedImages; result.samplerSlotDword = result.gpuResolvedImages ? bindings.layout.SamplerSlotDword() : 0u; result.bufferAddressDword = bindings.layout.bufferAddressDwords != 0u ? bindings.layout.BufferAddressDword() : 0u; - result.bufferAddressCount = bindings.layout.bufferAddressDwords / 4u; + result.bufferAddressCount = bindings.layout.bufferAddressDwords / RuntimeAbi::BufferAddressWords; result.dataAddressPush = bindings.layout.UsesDataAddress(); result.bdaStores = emitted.bdaStores; @@ -890,6 +897,14 @@ struct SpecializedSpirv { SharedSpirv spirv; }; +bool StencilInPush(const CompiledShaderArtifact& artifact, const IrBindingLayout& layout) { + return !artifact.stencilReferences.empty() && !layout.UsesDataAddress(); +} + +bool UsesRootOrPush(const IrBindingLayout& layout) { + return layout.UsesPushData() || layout.UsesDataAddress(); +} + std::vector specializeWords(const CompiledShaderArtifact& artifact, std::span classes, std::span constants, const SpirvTarget& target) { auto source = SpecializeVertexInputTypes(artifact, classes); std::map supplied; @@ -1270,7 +1285,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil auto& moduleKey = HostThreadLocal, LocalModuleKeyStorage>(); moduleKey.clear(); if (variant.bindings.layout.UsesPushData()) moduleKey.push_back(request.layout.pushConstantOffsetBytes / 4u); - if (!artifact.stencilReferences.empty() && !variant.bindings.layout.UsesDataAddress()) moduleKey.push_back(request.layout.pushConstantOffsetBytes / 4u + artifact.stencilReferenceDword); + if (StencilInPush(artifact, variant.bindings.layout)) moduleKey.push_back(request.layout.pushConstantOffsetBytes / 4u + artifact.stencilReferenceDword); if (request.context.pixel) { for (const auto packing : request.context.pixel->targetExportPacking) moduleKey.push_back(static_cast(packing)); moduleKey.push_back(request.context.pixel->dualSourceBlend ? 1u : 0u); @@ -1319,7 +1334,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil if (artifact.registrationModule) runtimeSelectors.at(input.location / RuntimeAbi::VertexSelectorsPerDword) |= (selectors & 0xfffu) << (input.location % RuntimeAbi::VertexSelectorsPerDword * 16u); } } - if (!plan->bindings.specialization.empty() || variant.bindings.layout.UsesPushData() || variant.bindings.layout.UsesDataAddress() || !artifact.vertexInputPatches.empty() || request.context.pixel || depthRemap) { + if (!plan->bindings.specialization.empty() || UsesRootOrPush(variant.bindings.layout) || !artifact.vertexInputPatches.empty() || request.context.pixel || depthRemap) { { std::shared_lock lock(plan->mutex); if (const auto found = plan->modules.find(moduleKey); found != plan->modules.end()) entry = found->second; @@ -1333,7 +1348,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil auto constants = plan->bindings.specialization; std::size_t index = 0; if (variant.bindings.layout.UsesPushData()) constants.push_back({PipelineSpecialization::PushDataOffset, moduleKey[index++]}); - if (!artifact.stencilReferences.empty() && !variant.bindings.layout.UsesDataAddress()) constants.push_back({PipelineSpecialization::StencilReferenceOffset, moduleKey[index++]}); + if (StencilInPush(artifact, variant.bindings.layout)) constants.push_back({PipelineSpecialization::StencilReferenceOffset, moduleKey[index++]}); if (request.context.pixel) { for (std::uint32_t target = 0; target < request.context.pixel->targetExportPacking.size(); ++target) constants.push_back({PipelineSpecialization::ExportPackingBase + target, moduleKey[index++]}); constants.push_back({PipelineSpecialization::DualSourceBlend, moduleKey[index++]}); @@ -1360,7 +1375,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil const auto prepare = [&] { auto specialized = specialize(); const auto& module = specialized.module; - if ((variant.bindings.layout.UsesPushData() || variant.bindings.layout.UsesDataAddress()) && !module->pushData) throw std::runtime_error("specialization removed the prepared push constant interface"); + if (UsesRootOrPush(variant.bindings.layout) && !module->pushData) throw std::runtime_error("specialization removed the prepared push constant interface"); auto selected = DescriptorBindingBuilder{}.Select(plan->bindings, module->bindings); entry->bindings = std::move(selected); entry->module = module; @@ -1398,7 +1413,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil for (std::uint32_t component = 0; component < PipelineSpecialization::WorkgroupOffsetWords; ++component) result.specialization.push_back({PipelineSpecialization::WorkgroupOffsetBase + component, 0u}); } result.heapSlotWords = bindingPlan->heapSlotWords; - if (!artifact.stencilReferences.empty() && !variant.bindings.layout.UsesDataAddress()) { + if (StencilInPush(artifact, variant.bindings.layout)) { if (artifact.stencilReferenceDword * sizeof(std::uint32_t) != result.pushConstants.size() || result.pushConstants.size() + sizeof(std::uint32_t) > request.layout.pushConstantSizeBytes) throw std::runtime_error("stencil replay push constant lies outside the stage range"); result.pushConstants.resize(result.pushConstants.size() + sizeof(std::uint32_t)); } @@ -1806,7 +1821,13 @@ void reportResultMemo() { // Everything materializeResult reads besides the variant: the snapshot (the descriptor words, the // flattened SRT, the user data, the uniform fill) and, for the vertex family, the V# table the // attributes are resolved from. -std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapshot& snapshot, bool masked = false, bool perDrawData = true, bool descriptors = true) { +struct SnapshotHashScope { + bool masked = false; + bool perDrawData = true; + bool descriptors = true; +}; + +std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapshot& snapshot, SnapshotHashScope scope = {}) { std::uint64_t hash = 0xcbf29ce484222325ull; const auto mix = [&](std::uint64_t value) { hash ^= value; @@ -1824,8 +1845,8 @@ std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapsh for (std::uint32_t i = 0; i < value.dwordCount && i < value.dwords.size(); ++i) mix(value.dwords[i]); } }; - if (descriptors) { - if (masked) { + if (scope.descriptors) { + if (scope.masked) { mix(snapshot.buffers.size()); for (const auto& value : snapshot.buffers) { mix(value.dwordCount); @@ -1841,10 +1862,10 @@ std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapsh mixDescriptors(snapshot.images); mixDescriptors(snapshot.samplers); } - if (masked) { + if (scope.masked) { mix(snapshot.flattenedSrt.size()); mix(snapshot.userData.size()); - } else if (perDrawData) { + } else if (scope.perDrawData) { mixWords(snapshot.flattenedSrt); mixWords(snapshot.userData); } @@ -1904,7 +1925,7 @@ std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapsh const auto count = std::min(vertex.resourcesNum, ShaderVertexStageInfo::MaxResources); mix(count); for (std::uint32_t i = 0; i < count; ++i) { - if (perDrawData) { + if (scope.perDrawData) { for (const auto field : vertex.resources[i].fields) mix(field); } else { mix(vertex.resources[i].fields[3]); @@ -1923,7 +1944,7 @@ std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapsh std::shared_ptr materializePreparedMemoized(SourceEntry& source, const std::shared_ptr& variant, const RecompileRequest& request, const ResourceSnapshot& snapshot, bool cacheHit, bool* memoHit) { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; const auto variantId = variant->artifact.variantId; - const auto hash = snapshotHash(request, snapshot, false); + const auto hash = snapshotHash(request, snapshot); const auto index = (variantId * 0x9e3779b97f4a7c15ull) ^ hash; auto& counters = resultMemoCounters(); { @@ -1941,7 +1962,7 @@ std::shared_ptr materializePreparedMemoized(SourceEntry& } } const bool masking = MaskedResultMemo(); - const auto maskedHash = masking ? snapshotHash(request, snapshot, true) : 0u; + const auto maskedHash = masking ? snapshotHash(request, snapshot, {.masked = true}) : 0u; const auto maskedIndex = (variantId * 0x9e3779b97f4a7c15ull) ^ maskedHash; std::shared_ptr donor; std::shared_ptr donorPatch; @@ -2151,8 +2172,10 @@ bool MatchesPreparedShader(const RecompileRequest& request, const SourceHandle& const auto words = prepared.ShaderDataDwords(); const bool usesPush = !prepared.gpuResolvedImages && prepared.runtimeImageCount == 0u && words != 0u && words <= layout.pushConstantSizeBytes / 4u; if (prepared.UsesPushData() != usesPush) return false; - if (!handle.artifact->artifact.stencilReferences.empty() && prepared.UsesDataAddress() && prepared.stencilReferenceDword != RuntimeAbi::RootDword + RuntimeAbi::RootStencilReference) return false; - if (!handle.artifact->artifact.stencilReferences.empty() && !prepared.UsesDataAddress() && (prepared.stencilReferenceDword >= layout.pushConstantSizeBytes / 4u || prepared.stencilReferenceDword != (usesPush ? words : 0u))) return false; + if (!handle.artifact->artifact.stencilReferences.empty()) { + const bool misplaced = prepared.UsesDataAddress() ? prepared.stencilReferenceDword != RuntimeAbi::RootDword + RuntimeAbi::RootStencilReference : prepared.stencilReferenceDword >= layout.pushConstantSizeBytes / 4u || prepared.stencilReferenceDword != (usesPush ? words : 0u); + if (misplaced) return false; + } if (!std::ranges::equal(key, handle.staticKey) || handle.source->code.size() != request.shader.code.size()) return false; return handle.source->code.data() == request.shader.code.data() || std::ranges::equal(handle.source->code, request.shader.code); } @@ -2193,6 +2216,79 @@ std::shared_ptr PreparedShaderInvocation::Capture(const S return capture; } +namespace { + +bool AllEmpty(const std::vector>& words) { + return std::all_of(words.begin(), words.end(), [](const std::vector& descriptor) { return descriptor.empty(); }); +} + +std::uint64_t HeapTemplateKey(const RecompileRequest& request, const CompiledVariant& variant, const ResourceSnapshot& snapshot, bool perDrawBindings) { + std::uint64_t key = snapshotHash(request, snapshot, {.perDrawData = false, .descriptors = !perDrawBindings}) ^ variant.artifact.variantId * 0x9e3779b97f4a7c15ull; + if (perDrawBindings) { + visitBindingPlanKey(variant, snapshot, request.context.pixel ? std::span(request.context.pixel->targetExportMapping) : std::span{}, [&](std::uint64_t word) { key = (key ^ word) * 0x100000001b3ull; }); + } + return key; +} + +void HeapVertexAttributes(const RecompileRequest& request, const RecompileResult& result, HeapStageWords& words) { + words.vertexAttributes.clear(); + if (!request.context.vertex) return; + const auto& vertex = *request.context.vertex; + words.vertexAttributes = result.vertexAttributes; + for (auto& attribute : words.vertexAttributes) { + if (attribute.location >= vertex.resourcesNum || attribute.location >= vertex.resources.size()) throw std::runtime_error("ShaderRecompiler: vertex attribute outside the draw's vertex resources"); + attribute.resource = vertex.resources[attribute.location]; + if (vertex.fetchEmbedded) attribute.fetchIndex = vertex.resourcesDst[attribute.location].fetchIndex; + } +} + +void HeapBindingWords(const RecompileRequest& request, const CompiledVariant& variant, const ResourceSnapshot& snapshot, const HeapTemplate& shared, HeapStageWords& words) { + const auto& layout = variant.bindings.layout; + if (shared.plan.plan == nullptr) throw std::runtime_error("ShaderRecompiler: a heap template has no binding plan"); + const bool sameBuffers = snapshot.buffers == shared.buffers; + const bool sameImages = snapshot.images == shared.images && snapshot.samplers == shared.samplers; + if (sameBuffers && sameImages) return; + const auto count = shared.result->bindings.size(); + if (shared.plan.plan->bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap template's binding plan differs from its bindings"); + if (sameImages) { + words.bindings.assign(count, {}); + for (std::size_t index = 0; index < count; ++index) { + const auto& entry = shared.plan.plan->bindings[index]; + if (entry.descriptor.role != DescriptorRole::GuestBuffers) continue; + auto& descriptor = words.bindings[index]; + descriptor.reserve(entry.resources.size() * 4u); + for (const auto resource : entry.resources) { + if (resource >= snapshot.buffers.size() || snapshot.buffers[resource].dwordCount != 4u) throw std::runtime_error("ShaderRecompiler: a heap stage's guest buffer descriptor is out of range"); + descriptor.insert(descriptor.end(), snapshot.buffers[resource].dwords.begin(), snapshot.buffers[resource].dwords.begin() + 4); + } + if (descriptor == shared.result->bindings[index].guestDescriptor) descriptor.clear(); + } + if (AllEmpty(words.bindings)) words.bindings.clear(); + return; + } + const auto tables = ResourceMaterializer::ResolveImageTables(variant.info.info, snapshot, variant.artifact.variantId); + BindingAllocationResult bindings; + DescriptorBindingBuilder{}.Populate(bindings, variant.bindings, *shared.plan.plan, variant.info.userDataBase, snapshot, partialThreads(request), &tables); + if (bindings.bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw bindings differ from its template"); + words.bindings.reserve(count); + for (auto& binding : bindings.bindings) words.bindings.push_back(std::move(binding.guestDescriptor)); + if (variant.artifact.registrationModule && request.shader.stage != ShaderStage::Fragment && layout.runtimeStateDwords != 0u) { + const auto first = layout.RuntimeStateDword() + RuntimeAbi::StateVertexSelectors; + for (std::size_t index = 0; index < words.bindings.size(); ++index) { + if (shared.result->bindings[index].role != DescriptorRole::ShaderData) continue; + const auto& kept = shared.result->bindings[index].guestDescriptor; + if (first + layout.runtimeStateDwords > kept.size() || first + layout.runtimeStateDwords > words.bindings[index].size()) throw std::runtime_error("ShaderRecompiler: vertex selector state lies outside a heap stage's shader data"); + std::copy_n(kept.begin() + first, layout.runtimeStateDwords, words.bindings[index].begin() + first); + } + } + for (std::size_t index = 0; index < count; ++index) { + if (words.bindings[index] == shared.result->bindings[index].guestDescriptor) words.bindings[index].clear(); + } + if (AllEmpty(words.bindings)) words.bindings.clear(); +} + +} + std::shared_ptr PreparedShaderInvocation::MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words) const { if (capture.source != handle->source || capture.plan != handle->source->plan) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); const auto& variant = handle->artifact; @@ -2211,91 +2307,31 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap const bool tables = std::ranges::any_of(layout.descriptors, [](const IrDescriptorBinding& descriptor) { return descriptor.kind == DescriptorBindingKind::ImageTable || descriptor.kind == DescriptorBindingKind::SamplerTable || descriptor.kind == DescriptorBindingKind::ImageTableMap; }); const bool perDrawBindings = (request.shader.stage == ShaderStage::Fragment || request.shader.stage == ShaderStage::Vertex) && !tables; auto& source = *handle->source; - std::uint64_t key = snapshotHash(request, snapshot, false, false, !perDrawBindings) ^ variant->artifact.variantId * 0x9e3779b97f4a7c15ull; - if (perDrawBindings) { - visitBindingPlanKey(*variant, snapshot, request.context.pixel ? std::span(request.context.pixel->targetExportMapping) : std::span{}, [&](std::uint64_t word) { key = (key ^ word) * 0x100000001b3ull; }); - } - const auto useAttributes = [&](const std::shared_ptr& result) { - words.vertexAttributes.clear(); - if (!request.context.vertex) return; - const auto& vertex = *request.context.vertex; - words.vertexAttributes = result->vertexAttributes; - for (auto& attribute : words.vertexAttributes) { - if (attribute.location >= vertex.resourcesNum || attribute.location >= vertex.resources.size()) throw std::runtime_error("ShaderRecompiler: vertex attribute outside the draw's vertex resources"); - attribute.resource = vertex.resources[attribute.location]; - if (vertex.fetchEmbedded) attribute.fetchIndex = vertex.resourcesDst[attribute.location].fetchIndex; - } - }; - const auto useBindings = [&](const HeapTemplate& shared) { - if (!perDrawBindings) return; - if (shared.plan.plan == nullptr) throw std::runtime_error("ShaderRecompiler: a heap template has no binding plan"); - const bool sameBuffers = snapshot.buffers == shared.buffers; - const bool sameImages = snapshot.images == shared.images && snapshot.samplers == shared.samplers; - if (sameBuffers && sameImages) return; - const auto count = shared.result->bindings.size(); - if (shared.plan.plan->bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap template's binding plan differs from its bindings"); - if (sameImages) { - words.bindings.assign(count, {}); - for (std::size_t index = 0; index < count; ++index) { - const auto& entry = shared.plan.plan->bindings[index]; - if (entry.descriptor.role != DescriptorRole::GuestBuffers) continue; - auto& descriptor = words.bindings[index]; - descriptor.reserve(entry.resources.size() * 4u); - for (const auto resource : entry.resources) { - if (resource >= snapshot.buffers.size() || snapshot.buffers[resource].dwordCount != 4u) throw std::runtime_error("ShaderRecompiler: a heap stage's guest buffer descriptor is out of range"); - descriptor.insert(descriptor.end(), snapshot.buffers[resource].dwords.begin(), snapshot.buffers[resource].dwords.begin() + 4); - } - if (descriptor == shared.result->bindings[index].guestDescriptor) descriptor.clear(); - } - if (std::all_of(words.bindings.begin(), words.bindings.end(), [](const std::vector& descriptor) { return descriptor.empty(); })) words.bindings.clear(); - return; - } - const auto tables = ResourceMaterializer::ResolveImageTables(variant->info.info, snapshot, variant->artifact.variantId); - BindingAllocationResult bindings; - DescriptorBindingBuilder{}.Populate(bindings, variant->bindings, *shared.plan.plan, variant->info.userDataBase, snapshot, partialThreads(request), &tables); - if (bindings.bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw bindings differ from its template"); - words.bindings.reserve(count); - for (auto& binding : bindings.bindings) words.bindings.push_back(std::move(binding.guestDescriptor)); - if (variant->artifact.registrationModule && request.shader.stage != ShaderStage::Fragment && layout.runtimeStateDwords != 0u) { - const auto first = layout.RuntimeStateDword() + RuntimeAbi::StateVertexSelectors; - for (std::size_t index = 0; index < words.bindings.size(); ++index) { - if (shared.result->bindings[index].role != DescriptorRole::ShaderData) continue; - const auto& kept = shared.result->bindings[index].guestDescriptor; - if (first + layout.runtimeStateDwords > kept.size() || first + layout.runtimeStateDwords > words.bindings[index].size()) throw std::runtime_error("ShaderRecompiler: vertex selector state lies outside a heap stage's shader data"); - std::copy_n(kept.begin() + first, layout.runtimeStateDwords, words.bindings[index].begin() + first); - } - } - for (std::size_t index = 0; index < count; ++index) { - if (words.bindings[index] == shared.result->bindings[index].guestDescriptor) words.bindings[index].clear(); - } - if (std::all_of(words.bindings.begin(), words.bindings.end(), [](const std::vector& descriptor) { return descriptor.empty(); })) words.bindings.clear(); + const std::uint64_t key = HeapTemplateKey(request, *variant, snapshot, perDrawBindings); + const auto complete = [&](const std::shared_ptr& shared) { + HeapVertexAttributes(request, *shared->result, words); + if (perDrawBindings) HeapBindingWords(request, *variant, snapshot, *shared, words); + CompleteHeapDataWords(*shared->result, words); }; + std::shared_ptr hit; { - std::shared_ptr hit; - { - std::lock_guard lock(source.mutex); - const auto found = source.heapTemplates.find(key); - if (found != source.heapTemplates.end()) { - const auto shared = found->second; - useAttributes(shared.result); - useBindings(shared); - CompleteHeapDataWords(*shared.result, words); - hit = shared.result; - } - } - if (hit != nullptr) { - TouchHeapTemplate({source.id, key, hit->heapTemplateId}); - return hit; - } + std::lock_guard lock(source.mutex); + const auto found = source.heapTemplates.find(key); + if (found != source.heapTemplates.end()) hit = found->second; + } + if (hit != nullptr) { + complete(hit); + TouchHeapTemplate({source.id, key, hit->result->heapTemplateId}); + return hit->result; } UsedBindingPlan usedPlan; auto built = std::make_shared(materializeResult(*variant, request, snapshot, false, &usedPlan)); built->cacheHit = true; for (const auto reg : layout.userDataRegisters) built->heapUserWords.push_back(reg - userDataBase); - static std::atomic templateIds{0}; - built->heapTemplateId = templateIds.fetch_add(1, std::memory_order_relaxed) + 1u; - HeapTemplate shared{std::move(built), std::move(usedPlan), perDrawBindings ? snapshot.buffers : std::vector{}, perDrawBindings ? snapshot.images : std::vector{}, perDrawBindings ? snapshot.samplers : std::vector{}}; - shared.bytes = HeapTemplateBytes(shared); + built->heapTemplateId = NextTemplateId(); + auto created = std::make_shared(HeapTemplate{std::move(built), std::move(usedPlan), perDrawBindings ? snapshot.buffers : std::vector{}, perDrawBindings ? snapshot.images : std::vector{}, perDrawBindings ? snapshot.samplers : std::vector{}}); + created->bytes = HeapTemplateBytes(*created); + std::shared_ptr shared = std::move(created); bool inserted = false; { std::lock_guard lock(source.mutex); @@ -2303,12 +2339,10 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap inserted = added; shared = at->second; } - if (inserted) KeepHeapTemplate(source.shared_from_this(), key, shared); - else TouchHeapTemplate(HeapTemplateName(source, key, shared)); - useAttributes(shared.result); - useBindings(shared); - CompleteHeapDataWords(*shared.result, words); - return shared.result; + if (inserted) KeepHeapTemplate(source.shared_from_this(), key, *shared); + else TouchHeapTemplate(HeapTemplateName(source, key, *shared)); + complete(shared); + return shared->result; } std::shared_ptr PreparedShaderInvocation::Materialize(const ResourceCapture& capture) const { diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index 8ecd0502a287..43acb484c2f9 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -19,11 +19,36 @@ inline constexpr std::uint32_t FirstComparisonImageBinding = 22u; inline constexpr std::uint32_t FirstStorageImageBinding = 29u; inline constexpr std::uint32_t ImageBindingCount = 56u; inline constexpr bool GpuHeapStorageKind(std::uint32_t kind) { return kind >= FirstStorageImageBinding && kind < FirstImageBinding + ImageBindingCount; } -inline constexpr std::uint32_t FirstUintStorageImageBinding = FirstStorageImageBinding + 7u; -inline constexpr std::uint32_t FirstAtomicImageBinding = FirstStorageImageBinding + 14u; -inline constexpr std::uint32_t FirstAtomic64ImageBinding = FirstStorageImageBinding + 21u; +inline constexpr std::uint32_t StorageKindStride = 7u; +inline constexpr std::uint32_t FirstUintStorageImageBinding = FirstStorageImageBinding + StorageKindStride; +inline constexpr std::uint32_t FirstAtomicImageBinding = FirstStorageImageBinding + 2u * StorageKindStride; +inline constexpr std::uint32_t FirstAtomic64ImageBinding = FirstStorageImageBinding + 3u * StorageKindStride; +inline constexpr std::uint32_t SamplerSlotWords = 2u; +inline constexpr std::uint32_t BufferAddressWords = 4u; inline constexpr bool AtomicImageKind(std::uint32_t kind) { return kind >= FirstAtomicImageBinding && kind < FirstAtomic64ImageBinding; } inline constexpr bool Atomic64ImageKind(std::uint32_t kind) { return kind >= FirstAtomic64ImageBinding && kind < FirstImageBinding + ImageBindingCount; } +inline constexpr bool UintStorageImageKind(std::uint32_t kind) { return kind >= FirstUintStorageImageBinding && kind < FirstAtomicImageBinding; } + +enum class HeapPart : std::uint32_t { Sampled, Storage, Sampler, Atomic, Atomic64, UintStorage }; + +inline constexpr HeapPart StorageHeapPart(std::uint32_t kind) { + if (AtomicImageKind(kind)) return HeapPart::Atomic; + if (Atomic64ImageKind(kind)) return HeapPart::Atomic64; + if (UintStorageImageKind(kind)) return HeapPart::UintStorage; + return HeapPart::Storage; +} + +inline constexpr std::uint32_t HeapPartFirstBinding(HeapPart part) { + switch (part) { + case HeapPart::Sampled: return FirstImageBinding; + case HeapPart::Storage: return FirstStorageImageBinding; + case HeapPart::Atomic: return FirstAtomicImageBinding; + case HeapPart::Atomic64: return FirstAtomic64ImageBinding; + case HeapPart::UintStorage: return FirstUintStorageImageBinding; + case HeapPart::Sampler: break; + } + return 0u; +} enum class Binding : std::uint32_t { Buffers = 0u, @@ -42,6 +67,13 @@ enum class Binding : std::uint32_t { enum class Stage : std::uint32_t { Main, Fragment, TessellationControl, TessellationEvaluation }; +inline constexpr Stage StageGroup(bool fragment, bool tessellationControl, bool tessellationEvaluation) { + if (fragment) return Stage::Fragment; + if (tessellationControl) return Stage::TessellationControl; + if (tessellationEvaluation) return Stage::TessellationEvaluation; + return Stage::Main; +} + inline constexpr std::uint32_t UserDataCapacity = 128u; inline constexpr std::uint32_t BufferCapacity = 128u; inline constexpr std::uint32_t ImageCapacity = 256u; diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index 6b5768b8c62b..372911d0f59a 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -697,7 +697,6 @@ void encodeInvocation(Writer& writer, const ShaderInvocation& invocation) { }); writer.Value(invocation.imageTableShader); writer.Value(invocation.imageTableFaults); - writer.Value(invocation.userDataRegisterReads); } void decodeInvocation(Reader& reader, ShaderInvocation& invocation) { @@ -744,7 +743,6 @@ void decodeInvocation(Reader& reader, ShaderInvocation& invocation) { }); reader.Value(invocation.imageTableShader); reader.Value(invocation.imageTableFaults); - reader.Value(invocation.userDataRegisterReads); } void encodeLayout(Writer& writer, const IrBindingLayout& layout) { diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp index 1120452de905..1c70beac0361 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp @@ -19,7 +19,6 @@ std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::Roo std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index); bool HasFlattenedSrt(const SpirvEmitterState& state); void EmitMemoryOffsets(SpirvEmitterState& state); -void EmitHeapSlotPreload(SpirvEmitterState& state); std::uint32_t LoadHeapSlotWord(SpirvEmitterState& state, std::uint32_t dword); std::uint32_t LdsDwordCount(const SpirvEmitterState& state); bool LdsInDeviceMemory(const SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp index 7f94dadba526..eb1d96d1967f 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp @@ -2,7 +2,6 @@ #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" #include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" -#include #include #include #include diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 0dd703bd0ce6..1b297f86402c 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -33,15 +33,6 @@ std::uint32_t EmitBinaryU32(SpirvEmitterState& state, std::uint32_t opcode, std: return result; } -RuntimeAbi::Stage RootStage(const SpirvEmitterState& state) { - switch (state.program.Resources().stage) { - case IrShaderStage::Pixel: return RuntimeAbi::Stage::Fragment; - case IrShaderStage::TessellationControl: return RuntimeAbi::Stage::TessellationControl; - case IrShaderStage::TessellationEvaluation: return RuntimeAbi::Stage::TessellationEvaluation; - default: return RuntimeAbi::Stage::Main; - } -} - std::uint32_t EmitRootDword(SpirvEmitterState& state, std::uint32_t field) { if (!state.program.Metadata().bindings.UsesDataAddress()) FailEmit("the root is read only by stages that take their data through it"); const auto u32 = TypeU32(state); @@ -53,7 +44,8 @@ std::uint32_t EmitRootDword(SpirvEmitterState& state, std::uint32_t field) { } std::uint32_t EmitStageRootDword(SpirvEmitterState& state, RuntimeAbi::RootStageField field) { - return EmitRootDword(state, RuntimeAbi::RootStageDword(RootStage(state), field)); + const auto stage = state.program.Resources().stage; + return EmitRootDword(state, RuntimeAbi::RootStageDword(RuntimeAbi::StageGroup(stage == IrShaderStage::Pixel, stage == IrShaderStage::TessellationControl, stage == IrShaderStage::TessellationEvaluation), field)); } namespace { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp index 40a8542b2403..bf8c1d32f2f2 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp @@ -86,26 +86,23 @@ std::uint32_t tableMapWord(SpirvEmitterState& state, std::uint32_t index) { return value; } -std::uint32_t tableHeapSlot(SpirvEmitterState& state, std::uint32_t part, std::uint32_t element, std::uint32_t slots) { +std::uint32_t tableHeapSlot(SpirvEmitterState& state, RuntimeAbi::HeapPart part, std::uint32_t element, std::uint32_t slots) { + using RuntimeAbi::HeapPart; + const auto partIndex = static_cast(part); const auto u32 = TypeU32(state); const auto base = tableMapWord(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)); const auto count = tableMapWord(state, ConstantU32(state, ImageTableAbi::HeaderElementCount)); std::uint32_t partBase = base; - if (part != 0u && part < 3u) { - partBase = Binary(state, spv::OpIAdd, u32, base, Binary(state, spv::OpIMul, u32, count, ConstantU32(state, part))); - } else if (part >= 3u) { + if (part == HeapPart::Storage || part == HeapPart::Sampler) { + partBase = Binary(state, spv::OpIAdd, u32, base, Binary(state, spv::OpIMul, u32, count, ConstantU32(state, partIndex))); + } else if (part >= HeapPart::Atomic) { const auto samplers = tableMapWord(state, ConstantU32(state, ImageTableAbi::HeaderSamplerCount)); const auto samplerSpan = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), count, samplers), samplers, count); - const auto extra = Binary(state, spv::OpIMul, u32, count, ConstantU32(state, part - 1u)); + const auto extra = Binary(state, spv::OpIMul, u32, count, ConstantU32(state, partIndex - 1u)); partBase = Binary(state, spv::OpIAdd, u32, Binary(state, spv::OpIAdd, u32, base, samplerSpan), extra); } const auto slot = tableMapWord(state, Binary(state, spv::OpIAdd, u32, partBase, element)); - const auto fallback = part == 0u ? RuntimeAbi::FirstImageBinding - : part == 1u ? RuntimeAbi::FirstStorageImageBinding - : part == 3u ? RuntimeAbi::FirstAtomicImageBinding - : part == 4u ? RuntimeAbi::FirstAtomic64ImageBinding - : part == 5u ? RuntimeAbi::FirstUintStorageImageBinding - : 0u; + const auto fallback = RuntimeAbi::HeapPartFirstBinding(part); const auto clamped = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), slot, ConstantU32(state, slots)), slot, ConstantU32(state, fallback)); DecorateTableNonUniform(state, clamped); return clamped; @@ -118,8 +115,7 @@ std::uint32_t TableStorageImagePointer(SpirvEmitterState& state, DescriptorBindi if (found == state.tableImageVariables.end() || !state.tableAccess.active) ExitDescriptorBindingFailure(state, kind, resource, "image storage table array was not emitted for the mode"); const auto pointer = state.module.AllocateId(); const auto value = static_cast(kind); - const bool uintStorage = value >= RuntimeAbi::FirstUintStorageImageBinding && value < RuntimeAbi::FirstAtomicImageBinding; - const auto part = RuntimeAbi::AtomicImageKind(value) ? 3u : RuntimeAbi::Atomic64ImageKind(value) ? 4u : uintStorage ? 5u : 1u; + const auto part = RuntimeAbi::StorageHeapPart(value); state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, part, state.tableAccess.element, RuntimeAbi::GpuImageHeapSlots) : state.tableAccess.element); DecorateTableNonUniform(state, pointer); return pointer; @@ -190,18 +186,24 @@ std::uint32_t ImageViewSizeType(SpirvEmitterState& state, RdnaImageDimension dim } } +namespace { + +void RequireDynamicIndexing(SpirvEmitterState& state, std::uint32_t capability, DescriptorBindingKind kind, std::uint32_t resource, const char* reason) { + const auto supported = std::find(state.supportedCapabilities.begin(), state.supportedCapabilities.end(), capability) != state.supportedCapabilities.end(); + if (!supported) ExitDescriptorBindingFailure(state, kind, resource, reason); + state.module.EmitCapability(capability); +} + +} + std::uint32_t HeapImageSlot(SpirvEmitterState& state, DescriptorBindingKind kind, std::uint32_t resource) { - const auto supported = std::find(state.supportedCapabilities.begin(), state.supportedCapabilities.end(), spv::CapabilitySampledImageArrayDynamicIndexing) != state.supportedCapabilities.end(); - if (!supported) ExitDescriptorBindingFailure(state, kind, resource, "the image heap needs image array dynamic indexing, which the device lacks"); - state.module.EmitCapability(spv::CapabilitySampledImageArrayDynamicIndexing); + RequireDynamicIndexing(state, spv::CapabilitySampledImageArrayDynamicIndexing, kind, resource, "the image heap needs image array dynamic indexing, which the device lacks"); const auto dword = state.program.Metadata().bindings.ImageMetadataDword() + resource * static_cast(sizeof(RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t)) + static_cast(offsetof(RuntimeAbi::ResourceMetadata, firstElement) / sizeof(std::uint32_t)); return LoadHeapSlotWord(state, dword); } std::uint32_t HeapImageSlotWord(SpirvEmitterState& state, DescriptorBindingKind kind, std::uint32_t resource, std::uint32_t arrayIndex) { - const auto supported = std::find(state.supportedCapabilities.begin(), state.supportedCapabilities.end(), spv::CapabilitySampledImageArrayDynamicIndexing) != state.supportedCapabilities.end(); - if (!supported) ExitDescriptorBindingFailure(state, kind, resource, "the image heap needs image array dynamic indexing, which the device lacks"); - state.module.EmitCapability(spv::CapabilitySampledImageArrayDynamicIndexing); + RequireDynamicIndexing(state, spv::CapabilitySampledImageArrayDynamicIndexing, kind, resource, "the image heap needs image array dynamic indexing, which the device lacks"); const auto& layout = state.program.Metadata().bindings; auto dword = layout.ImageSlotDword(); for (const auto& descriptor : layout.descriptors) { @@ -216,9 +218,7 @@ std::uint32_t HeapImageSlotWord(SpirvEmitterState& state, DescriptorBindingKind std::uint32_t StorageElementPointer(SpirvEmitterState& state, std::uint32_t pointerType, std::uint32_t variable, std::uint32_t arrayIndex, DescriptorBindingKind kind, std::uint32_t resource) { if (!state.gpuResolvedImages || !state.program.Metadata().bindings.HeapImageKind(kind)) return DescriptorElementPointer(state, pointerType, variable, arrayIndex, kind, resource, "storage image descriptor array was not emitted"); if (variable == 0) ExitDescriptorBindingFailure(state, kind, resource, "storage image heap array was not emitted"); - const auto supported = std::find(state.supportedCapabilities.begin(), state.supportedCapabilities.end(), spv::CapabilityStorageImageArrayDynamicIndexing) != state.supportedCapabilities.end(); - if (!supported) ExitDescriptorBindingFailure(state, kind, resource, "the storage image heap needs storage image array dynamic indexing, which the device lacks"); - state.module.EmitCapability(spv::CapabilityStorageImageArrayDynamicIndexing); + RequireDynamicIndexing(state, spv::CapabilityStorageImageArrayDynamicIndexing, kind, resource, "the storage image heap needs storage image array dynamic indexing, which the device lacks"); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, variable, state.registrationModules ? HeapImageSlot(state, kind, resource) : HeapImageSlotWord(state, kind, resource, arrayIndex)); return pointer; @@ -236,7 +236,7 @@ std::uint32_t LoadSampledImageDescriptor(SpirvEmitterState& state, std::uint32_t const auto found = std::find_if(state.tableImageVariables.begin(), state.tableImageVariables.end(), [&](const SpirvTableImageVariable& variable) { return variable.kind == kind; }); if (found == state.tableImageVariables.end() || !state.tableAccess.active) ExitDescriptorBindingFailure(state, kind, resource, "image table array was not emitted for the mode"); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, 0u, state.tableAccess.element, RuntimeAbi::GpuImageHeapSlots) : state.tableAccess.element); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, RuntimeAbi::HeapPart::Sampled, state.tableAccess.element, RuntimeAbi::GpuImageHeapSlots) : state.tableAccess.element); if (!state.tableAccess.uniform) DecorateTableNonUniform(state, pointer); const auto image = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, imageType, image, pointer); @@ -272,7 +272,7 @@ std::uint32_t LoadSamplerDescriptor(SpirvEmitterState& state, std::uint32_t samp const auto variant = image != nullptr && image->depthCompare ? 2u : 0u; const auto element = Binary(state, spv::OpIAdd, TypeU32(state), state.tableAccess.samplerElement, ConstantU32(state, variant + (point ? 1u : 0u))); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.tableSamplerVariable, state.tableHeap ? tableHeapSlot(state, 2u, element, RuntimeAbi::GpuSamplerHeapSlots) : element); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.tableSamplerVariable, state.tableHeap ? tableHeapSlot(state, RuntimeAbi::HeapPart::Sampler, element, RuntimeAbi::GpuSamplerHeapSlots) : element); DecorateTableNonUniform(state, pointer); const auto loaded = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, samplerType, loaded, pointer); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index cc0fe66aaf82..94a6ce5a2a35 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -475,20 +475,18 @@ void DefineDescriptors(SpirvEmitterState& state) { state.module.AddName(state.pushConstantVariable, "vsharp"); } for (const IrDescriptorBinding& binding : layout.descriptors) { + const bool gpuHeap = state.gpuResolvedImages && (binding.kind == DescriptorBindingKind::Samplers || layout.HeapImageKind(binding.kind)); const auto Define = [&](std::uint32_t type, const char* name, std::uint32_t storage = spv::StorageClassStorageBuffer) { const auto variable = state.module.DefineGlobalVariable(TypePointer(state, storage, type), storage); state.module.AddName(variable, name); const bool gpuData = state.gpuResolvedImages && (binding.kind == DescriptorBindingKind::ShaderData || binding.kind == DescriptorBindingKind::FlattenedSrt); - const bool gpuHeap = binding.kind == DescriptorBindingKind::Samplers || layout.HeapImageKind(binding.kind); - const bool sharedHeap = state.gpuResolvedImages && gpuHeap; - const bool fragmentSet = sharedHeap || (!state.gpuResolvedImages && state.fragmentDescriptorSet && stage == IrShaderStage::Pixel); + const bool fragmentSet = gpuHeap || (!state.gpuResolvedImages && state.fragmentDescriptorSet && stage == IrShaderStage::Pixel); state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, binding.kind == DescriptorBindingKind::Gds && layout.UsesDataAddress() ? RuntimeAbi::GpuGdsSet : gpuData ? RuntimeAbi::GpuDataSet : fragmentSet ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, NativeBinding(sharedHeap ? IrShaderStage::Pixel : stage, binding.kind)); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, NativeBinding(gpuHeap ? IrShaderStage::Pixel : stage, binding.kind)); return variable; }; const auto ArrayType = [&](std::uint32_t type) { const bool heap = binding.kind == DescriptorBindingKind::Samplers || ImageBindingResourceClass(binding.kind) != ImageResourceClass::None; - const bool gpuHeap = state.gpuResolvedImages && (binding.kind == DescriptorBindingKind::Samplers || layout.HeapImageKind(binding.kind)); const auto count = gpuHeap ? (binding.kind == DescriptorBindingKind::Samplers ? RuntimeAbi::GpuSamplerHeapSlots : RuntimeAbi::GpuImageHeapSlots) : static_cast(binding.resources.size()); const auto length = heap && !gpuHeap && !state.registrationModules ? state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::HeapCountBase + static_cast(binding.kind), count) : ConstantU32(state, count); return state.module.Type(spv::OpTypeArray, type, length); @@ -570,7 +568,8 @@ void DefineDescriptors(SpirvEmitterState& state) { const auto name = "table_images_" + std::to_string(static_cast(kind)); if (state.tableHeap) { const auto value = static_cast(kind); - const auto heapKind = binding.kind != DescriptorBindingKind::ImageStorageTable ? RuntimeAbi::FirstImageBinding : RuntimeAbi::AtomicImageKind(value) ? RuntimeAbi::FirstAtomicImageBinding : RuntimeAbi::Atomic64ImageKind(value) ? RuntimeAbi::FirstAtomic64ImageBinding : RuntimeAbi::FirstStorageImageBinding; + const auto part = RuntimeAbi::StorageHeapPart(value); + const auto heapKind = binding.kind != DescriptorBindingKind::ImageStorageTable ? RuntimeAbi::FirstImageBinding : part == RuntimeAbi::HeapPart::Atomic || part == RuntimeAbi::HeapPart::Atomic64 ? RuntimeAbi::HeapPartFirstBinding(part) : RuntimeAbi::FirstStorageImageBinding; const auto type = state.module.Type(spv::OpTypeArray, ImageType(state, mode), ConstantU32(state, RuntimeAbi::GpuImageHeapSlots)); const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniformConstant, type), spv::StorageClassUniformConstant); state.module.AddName(variable, name.c_str()); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index 16834811c748..a51f59e46988 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -201,7 +201,7 @@ MemoryResourceAccess directAccess(SpirvValueEmitContext& context, const IrValue& const auto& memory = context.Memory(instruction); if (state.addressedBuffers) { const auto element = ResourceForDescriptor(state, DescriptorBindingKind::Buffers, memory.resource); - const auto dword = state.program.Metadata().bindings.BufferAddressDword() + element * 4u; + const auto dword = state.program.Metadata().bindings.BufferAddressDword() + element * RuntimeAbi::BufferAddressWords; const auto u64 = TypeScalarU64(state); const auto low = Unary(state, spv::OpUConvert, u64, EmitShaderDataDwordLoad(state, dword)); const auto high = Binary(state, spv::OpShiftLeftLogical, u64, Unary(state, spv::OpUConvert, u64, EmitShaderDataDwordLoad(state, dword + 1u)), BdaConstant(state, 32u)); From 11ef9c57b11c1a80db24f1cfa847fef2da0b0fb6 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 1 Nov 2026 02:02:03 +0530 Subject: [PATCH 087/269] fix(agc): let one draw's shader data span several heap ring chunks A draw whose shader data exceeded one 2 MiB ring chunk threw 'per-draw data exceeds a ring chunk' (Death Stranding 2 reaches 2.4 MiB per compute dispatch). A span may now cover several chunks and stays held while none of them has been written over: each chunk records the ring entry at which it was last entered, and a span is held only while every chunk it covers was entered no later than the span itself. Only data larger than half the ring is refused. --- .../Graphics/include/BindlessHeap.hpp | 3 +- .../Graphics/src/BindlessHeap.cpp | 19 ++++----- .../tests/BindlessHeapSlots.cpp | 39 ++++++++++++++++++- 3 files changed, 49 insertions(+), 12 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index e75160afa6a7..a6ce8c74c272 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -115,9 +115,10 @@ class BindlessHeap { Recorder* recorder = nullptr; std::uint64_t serial = 0; bool open = false; - std::uint64_t entries = 0; + std::uint64_t entered = 0; }; std::vector ringChunks; + std::uint64_t ringEntries = 0; std::size_t ringChunk = ~std::size_t{0}; void enterRingChunk(std::size_t index); std::size_t wrapRingOffset(std::size_t offset, std::size_t bytes); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 657fdb5da0cf..b725e8ce108d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -530,21 +530,22 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words) { bool BindlessHeap::Held(const SpanMark& mark) { if (mark.entry == 0u || mark.words == 0u) return false; const auto first = chunkOf(mark.offset); - if (first != lastChunkOf(mark.offset, static_cast(mark.words) * sizeof(std::uint32_t))) return false; + const auto last = lastChunkOf(mark.offset, static_cast(mark.words) * sizeof(std::uint32_t)); std::lock_guard lock(mutex); - auto& chunk = ringChunks[first]; - if (chunk.entries != mark.entry) { - ++counts.spansExpired; - return false; + for (auto chunk = first; chunk <= last; ++chunk) { + if (ringChunks[chunk].entered > mark.entry) { + ++counts.spansExpired; + return false; + } } - chunk.open = true; + for (auto chunk = first; chunk <= last; ++chunk) ringChunks[chunk].open = true; ++counts.spansKept; return true; } BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) { const auto bytes = ringInHeap ? alignUp(words * sizeof(std::uint32_t), RingSpanAlignment) : words * sizeof(std::uint32_t); - if (bytes > RingChunkBytes) throw std::runtime_error("AGC bindless heap: per-draw data exceeds a ring chunk"); + if (bytes > ringBytes / 2u) throw std::runtime_error("AGC bindless heap: per-draw data exceeds half the shader data ring"); std::lock_guard lock(mutex); auto offset = wrapRingOffset(alignUp(ringCursor, ringAlignment), bytes); const auto keptAhead = [&] { @@ -562,7 +563,7 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) enterRingChunk(chunk); auto* base = reinterpret_cast(ringData + offset); ++counts.spansWritten; - mark = {static_cast(offset), static_cast(words), ringChunks[chunkOf(offset)].entries}; + mark = {static_cast(offset), static_cast(words), ringEntries}; return {static_cast(offset), std::span(base, words)}; } @@ -584,7 +585,7 @@ void BindlessHeap::enterRingChunk(std::size_t index) { chunk.serial = 0u; } chunk.open = true; - ++chunk.entries; + chunk.entered = ++ringEntries; } void BindlessHeap::writeSamplerSlot(std::uint32_t slot, VkSampler sampler) { diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 9797ebdafd9e..7ad1ce722bbd 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -203,10 +203,10 @@ void ringSpans(const Context& context) { static_cast(heap.Allocate(chunkWords - 1024u, filler)); BindlessHeap::SpanMark crossing; static_cast(heap.Allocate(4096u, crossing)); - require(!heap.Held(crossing), "a span over two chunks is never kept"); + require(heap.Held(crossing), "a span over two chunks is kept"); require(heap.Held(first), "a span stays held while its batch keeps the chunk open"); const auto counts = heap.Statistics(); - require(counts.spansWritten == 3u && counts.spansKept == 2u, "three spans written and two kept"); + require(counts.spansWritten == 3u && counts.spansKept == 3u, "three spans written and kept"); BindlessHeap::SpanMark third; static_cast(heap.Allocate(chunkWords, third)); Recorder recorder(context); @@ -226,6 +226,40 @@ void ringSpans(const Context& context) { require(untilWrap() == 0u && !heap.Held(first) && heap.Statistics().spansExpired == 1u, "a span the ring wrote over has expired"); } +void ringLargeSpans(const Context& context) { + BindlessHeap heap(context); + constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); + constexpr std::size_t largeWords = chunkWords * 2u + 1024u; + BindlessHeap::SpanMark pin; + static_cast(heap.Allocate(16u, pin)); + BindlessHeap::SpanMark large; + const auto span = heap.Allocate(largeWords, large); + require(span.words.size() == largeWords && heap.Held(large), "a span over three chunks is written and held"); + Recorder recorder(context); + BindlessHeap::SpanMark fill; + const auto untilWrap = [&](const BindlessHeap::SpanMark& kept) { + const auto wraps = heap.Statistics().ringWraps; + BindlessHeap::DataSpan last{}; + while (heap.Statistics().ringWraps == wraps) { + heap.Submitted(recorder, 0u); + require(heap.Held(kept), "a kept span stays held while later batches fill the ring"); + last = heap.Allocate(chunkWords, fill); + } + return last.offset; + }; + require(untilWrap(large) == 3u * AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips every chunk a kept large span covers"); + require(untilWrap(pin) == AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips only the pinned first chunk"); + require(!heap.Held(large), "a large span expires once the ring writes over one of its later chunks"); + require(heap.Held(pin), "the pinned span outlives the large span"); + bool refused = false; + try { + static_cast(heap.Allocate(AgcDriver::Graphics::BindlessHeap::RingBytes / sizeof(std::uint32_t) / 2u + 1u)); + } catch (const std::runtime_error&) { + refused = true; + } + require(refused, "a span over half the ring is refused"); +} + } void heapComesBack(const Context& context, VkImageView view) { @@ -382,6 +416,7 @@ int main(int argc, char** argv) { textureSlots(context, placeholders.View(Abi::FirstImageBinding)); samplerSlots(context); ringSpans(context); + ringLargeSpans(context); viewSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); encodedViews(context); ownerSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); From dfd8a5eff99b430f283ba242fec61f8e7e9ceea7 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 1 Nov 2026 02:10:31 +0530 Subject: [PATCH 088/269] fix(agc): never wrap a heap ring span onto the current chunk behind its cursor After a wrap, the kept-chunk skip loop treated the current chunk as free, so with every other chunk kept a span could land at the start of the current chunk and write over shader data the open batch had already written, without marking that chunk entered. The current chunk now counts as taken when the new span starts behind the ring cursor; a ring with no room left refuses the span as before. --- .../Graphics/include/BindlessHeap.hpp | 1 + .../Graphics/src/BindlessHeap.cpp | 2 +- .../tests/BindlessHeapSlots.cpp | 26 +++++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index a6ce8c74c272..7956a2134293 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -86,6 +86,7 @@ class BindlessHeap { std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0; }; Counts Statistics() const; + std::size_t RingChunkCount() const { return ringChunks.size(); } static constexpr std::size_t RingBytes = 64u << 20u; static constexpr std::size_t RingChunkBytes = 2u << 20u; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index b725e8ce108d..e3b7c8e4c7ab 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -550,7 +550,7 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) auto offset = wrapRingOffset(alignUp(ringCursor, ringAlignment), bytes); const auto keptAhead = [&] { for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) { - if (chunk != ringChunk && ringChunks[chunk].open) return true; + if (chunk == ringChunk ? offset < ringCursor : ringChunks[chunk].open) return true; } return false; }; diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 7ad1ce722bbd..0c3be4226d8a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -228,6 +228,7 @@ void ringSpans(const Context& context) { void ringLargeSpans(const Context& context) { BindlessHeap heap(context); + if (heap.RingChunkCount() < 5u) return; constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); constexpr std::size_t largeWords = chunkWords * 2u + 1024u; BindlessHeap::SpanMark pin; @@ -260,6 +261,30 @@ void ringLargeSpans(const Context& context) { require(refused, "a span over half the ring is refused"); } +void ringCurrentChunk(const Context& context) { + BindlessHeap heap(context); + constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); + Recorder recorder(context); + std::vector pins(heap.RingChunkCount() - 1u); + for (auto& pin : pins) { + static_cast(heap.Allocate(chunkWords, pin)); + heap.Submitted(recorder, 0u); + for (const auto& kept : pins) { + if (kept.entry != 0u) require(heap.Held(kept), "every pinned chunk stays held"); + } + } + BindlessHeap::SpanMark live; + static_cast(heap.Allocate(16u, live)); + bool refused = false; + try { + static_cast(heap.Allocate(chunkWords)); + } catch (const std::runtime_error&) { + refused = true; + } + require(refused, "a span never wraps onto the current chunk behind data this batch already wrote"); + require(heap.Held(live), "the current chunk's span is still held"); +} + } void heapComesBack(const Context& context, VkImageView view) { @@ -417,6 +442,7 @@ int main(int argc, char** argv) { samplerSlots(context); ringSpans(context); ringLargeSpans(context); + ringCurrentChunk(context); viewSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); encodedViews(context); ownerSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); From f2449f6ec25d5c1f7e61839e34f02daa12223293 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 1 Nov 2026 05:52:41 +0530 Subject: [PATCH 089/269] test(agc): create the GPU heap before the memory accounting baseline With APS5_GPU_HEAP=1 the first pixel-function LDS preparation created the GPU heap, adding the heap's own buffers to the counted allocations, and the heap's context copy kept the test's buffer pool alive past its reset. The test now creates the heap before installing its pool and taking its baseline, so it holds in both modes. --- .../prx/libSceAgcDriver/tests/execution/MemoryAccounting.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MemoryAccounting.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MemoryAccounting.cpp index 23b07da10799..4444184ad7da 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MemoryAccounting.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MemoryAccounting.cpp @@ -4,6 +4,7 @@ #include "prx/libSceAgcDriver/Execution/include/PqToSdr.hpp" #include "prx/libSceAgcDriver/Graphics/include/DeferredDestruction.hpp" #include "prx/libSceAgcDriver/Execution/include/PresentationScaler.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp" @@ -159,6 +160,7 @@ int main() { auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; auto context = device->graphicsContext(); + if (context.descriptorHeap) static_cast(BindlessHeap::For(context)); context.bufferPool = std::make_shared(context); drain(context); const auto baseline = MemoryAccounting::Read(context.device).allocations.size(); From fc0cf9360fbcdae8530ace8ba382b10841a2191e Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 1 Nov 2026 07:04:13 +0530 Subject: [PATCH 090/269] refactor(agc): keep the heap walk memo's internals private HeapWalkMemo's slot, pin, charge, drop, release and trim helpers are private, remember() stamps entries through touch(), and slot() and trim() share one retirePrevious(). --- .../include/Driver/Draw/HeapWalkMemo.hpp | 34 +++++++++++-------- .../Execution/src/Driver/Draw/HeapStages.cpp | 3 +- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp index 8f689d25f4a1..da1ea6b54f6a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp @@ -74,19 +74,6 @@ struct HeapWalkMemo { return &ways; } - std::vector& slot(std::uint64_t key) { - for (std::size_t drained = 0; drained < HeapWalkDrain && !previous.empty(); ++drained) { - release(previous.begin()->second); - previous.erase(previous.begin()); - } - if (current.size() >= HeapWalkMemoKeys && !current.contains(key)) { - for (const auto& [old, ways] : previous) release(ways); - previous = std::move(current); - current.clear(); - } - return current[key]; - } - void remember(std::uint64_t key, HeapWalkEntry entry) { auto& ways = slot(key); if (ways.size() >= HeapWalkWays) { @@ -94,7 +81,7 @@ struct HeapWalkMemo { ways.pop_back(); } charge(entry); - entry.stored = ++stores; + touch(entry); ways.insert(ways.begin(), std::move(entry)); if (budget != 0 && heldBytes > budget) trim(); } @@ -103,6 +90,20 @@ struct HeapWalkMemo { entry.stored = ++stores; } +private: + std::vector& slot(std::uint64_t key) { + for (std::size_t drained = 0; drained < HeapWalkDrain && !previous.empty(); ++drained) { + release(previous.begin()->second); + previous.erase(previous.begin()); + } + if (current.size() >= HeapWalkMemoKeys && !current.contains(key)) { + retirePrevious(); + previous = std::move(current); + current.clear(); + } + return current[key]; + } + template void pin(const std::shared_ptr& object, TSize size) { if (object == nullptr) return; @@ -140,6 +141,11 @@ struct HeapWalkMemo { for (const auto& entry : ways) drop(entry); } + void retirePrevious() { + for (const auto& [key, ways] : previous) release(ways); + previous.clear(); + } + void trim(); }; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 30d70b77b9a9..14fb2c93467d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -393,8 +393,7 @@ std::uint64_t HeapWalkMemoBudget() { } void HeapWalkMemo::trim() { - for (const auto& [key, ways] : previous) release(ways); - previous.clear(); + retirePrevious(); if (heldBytes <= budget) return; std::vector> stamps; for (const auto& [key, ways] : current) { From 1cd3c3bdee5a370e72b7e904877bccc3f03abfb4 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 1 Nov 2026 07:06:06 +0530 Subject: [PATCH 091/269] feat(agc): replay shader requests against a GPU heap target agc_shader_replay --gpu-heap sets the target fields the device sets with APS5_GPU_HEAP=1 (GPU-resolved images, descriptor memory and the 16384-dword heap data uniform), so captured requests can be recompiled in heap mode. --- core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp b/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp index 5f1baac6280b..6aa5676114a9 100644 --- a/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp +++ b/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp @@ -51,6 +51,7 @@ bool g_robust2 = false; bool g_waveLdsMemoryBarriers = false; bool g_deviceScopeLdsMemoryBarriers = false; bool g_ldsLockFences = false; +bool g_gpuHeap = false; bool g_code = false; bool Replay(const char* path) { @@ -60,6 +61,11 @@ bool Replay(const char* path) { if (g_waveLdsMemoryBarriers) request.request.target.waveLdsMemoryBarriers = true; if (g_deviceScopeLdsMemoryBarriers) request.request.target.deviceScopeLdsMemoryBarriers = true; if (g_ldsLockFences) request.request.target.ldsLockFences = true; + if (g_gpuHeap) { + request.request.target.gpuResolvedImages = true; + request.request.target.descriptorMemory = true; + request.request.target.heapDataUniformDwords = 16384u; + } std::printf("%s: %zu code words, %zu user data, %zu memory regions, wave%u\n", path, request.request.shader.code.size(), request.request.context.userData.size(), request.request.context.memory.size(), request.request.context.waveSize); if (request.request.context.compute.has_value()) { const auto& compute = *request.request.context.compute; @@ -189,7 +195,7 @@ bool Replay(const char* path) { int main(int argc, char** argv) { if (argc < 2) { - std::fprintf(stderr, "usage: agc_shader_replay [--dis] [--asm] [--cfg] [--mem] [--spv] [--prepare] [--materialize] [--code] [--maintenance8] [--robust2] [--wave-lds-memory-barriers] [--device-scope-lds-memory-barriers] [--lds-lock-fences] ...\n the driver writes shader_
.req files when APS5_DUMP_SHADERS is set; shader_
.prepare.req holds a request whose preparation failed before any resource capture, so replay it with --prepare\n"); + std::fprintf(stderr, "usage: agc_shader_replay [--dis] [--asm] [--cfg] [--mem] [--spv] [--prepare] [--materialize] [--code] [--maintenance8] [--robust2] [--wave-lds-memory-barriers] [--device-scope-lds-memory-barriers] [--lds-lock-fences] [--gpu-heap] ...\n the driver writes shader_
.req files when APS5_DUMP_SHADERS is set; shader_
.prepare.req holds a request whose preparation failed before any resource capture, so replay it with --prepare\n"); return 2; } int failures = 0; @@ -214,6 +220,10 @@ int main(int argc, char** argv) { g_maintenance8 = true; continue; } + if (std::string(argv[i]) == "--gpu-heap") { + g_gpuHeap = true; + continue; + } if (std::string(argv[i]) == "--robust2") { g_robust2 = true; continue; From 0f4b636d0419a3b11a0f84476a32e4a416075346 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 1 Nov 2026 07:29:02 +0530 Subject: [PATCH 092/269] refactor(shader): share the GPU heap emitter helpers One 64-bit address composer, aligned word loads, the image first-element dword, shared descriptor set and binding numbers, one heap array definition that creates its slot-count constant before the element type, derived table-heap and BDA state flags, the read-only storage buffer type and the table map load. Emitted SPIR-V is byte-identical: 945 captured game shaders in plain and GPU heap mode and the image-table test shaders. --- .../IrMetadata/DescriptorBinding.hpp | 3 ++ .../IntermediateRepresentation/IrProgram.hpp | 3 ++ .../src/IrProgram.cpp | 18 ++++++++ .../src/DescriptorBindingBuilder.cpp | 14 +----- .../SpirvBackend/SpirvEmitterHelpers.hpp | 1 + .../SpirvBackend/SpirvEmitterState.hpp | 6 +-- .../SpirvMemory/SpirvBufferAccess.hpp | 4 ++ .../SpirvBackend/src/SpirvBdaFault.cpp | 8 ++-- .../SpirvBackend/src/SpirvBdaLookup.cpp | 4 +- .../SpirvBackend/src/SpirvEmitter.cpp | 12 ++++++ .../SpirvBackend/src/SpirvImageEmitter.cpp | 13 +++--- .../src/SpirvMemory/SpirvBufferAccess.cpp | 34 ++++++++------- .../src/SpirvMemory/SpirvDescriptors.cpp | 19 +++----- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 43 +++++++++---------- .../src/SpirvMemory/SpirvTypes.cpp | 18 ++++---- .../SpirvBackend/src/SpirvModuleEmitter.cpp | 8 ++-- .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 4 +- 17 files changed, 118 insertions(+), 94 deletions(-) diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp index b15dfa3d3a46..0911b62c97f7 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp @@ -60,6 +60,9 @@ struct IrBindingLayout { [[nodiscard]] std::uint32_t ImageMetadataDword() const { return DispatchThreadLimitDword() + (dispatchThreadLimit ? 3u : 0u); } + [[nodiscard]] std::uint32_t ImageFirstElementDword(std::uint32_t image) const { + return ImageMetadataDword() + image * (sizeof(RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t)) + offsetof(RuntimeAbi::ResourceMetadata, firstElement) / sizeof(std::uint32_t); + } [[nodiscard]] std::uint32_t RuntimeStateDword() const { return ImageMetadataDword() + runtimeImageCount * (sizeof(RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t)); } diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrProgram.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrProgram.hpp index bb66d00d95c4..a25479ebada3 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrProgram.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrProgram.hpp @@ -58,6 +58,9 @@ IrValue* ResolveInvariantPhi(const IrResourcePlan& program, IrValue* value); bool IsAddressResourceKind(ResourceKind kind); PositionExportComponent DecodePositionExportComponent(std::uint32_t control, std::uint32_t positionIndex, std::uint32_t component); std::uint32_t NativeBinding(IrShaderStage stage, DescriptorBindingKind kind); +bool SharedHeapArray(const IrBindingLayout& layout, DescriptorBindingKind kind, bool gpuResolved); +std::uint32_t DescriptorBindingNumber(const IrBindingLayout& layout, DescriptorBindingKind kind, IrShaderStage stage, bool gpuResolved); +std::uint32_t DescriptorSetNumber(const IrBindingLayout& layout, DescriptorBindingKind kind, IrShaderStage stage, bool gpuResolved, bool fragmentDescriptorSet, bool plan); ImageResourceClass ImageBindingResourceClass(DescriptorBindingKind kind); std::uint32_t ImageBindingIndex(DescriptorBindingKind kind); DescriptorBindingKind DescriptorBindingForImage(const ImageResource& image); diff --git a/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp b/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp index 34a251932ba1..1708aa0bf401 100644 --- a/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp +++ b/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp @@ -907,6 +907,24 @@ std::uint32_t NativeBinding(IrShaderStage stage, DescriptorBindingKind kind) { return RuntimeAbi::BindingNumber(static_cast(group), kind); } +bool SharedHeapArray(const IrBindingLayout& layout, DescriptorBindingKind kind, bool gpuResolved) { + return gpuResolved && (kind == DescriptorBindingKind::Samplers || layout.HeapImageKind(kind)); +} + +std::uint32_t DescriptorBindingNumber(const IrBindingLayout& layout, DescriptorBindingKind kind, IrShaderStage stage, bool gpuResolved) { + return NativeBinding(SharedHeapArray(layout, kind, gpuResolved) ? IrShaderStage::Pixel : stage, kind); +} + +std::uint32_t DescriptorSetNumber(const IrBindingLayout& layout, DescriptorBindingKind kind, IrShaderStage stage, bool gpuResolved, bool fragmentDescriptorSet, bool plan) { + if (kind == DescriptorBindingKind::Gds && layout.UsesDataAddress()) return RuntimeAbi::GpuGdsSet; + if (gpuResolved) { + if (SharedHeapArray(layout, kind, true)) return RuntimeAbi::FragmentDescriptorSet; + if (kind == DescriptorBindingKind::ShaderData || kind == DescriptorBindingKind::FlattenedSrt) return plan ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::GpuDataSet; + return RuntimeAbi::DescriptorSet; + } + return fragmentDescriptorSet && stage == IrShaderStage::Pixel ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet; +} + ImageResourceClass ImageBindingResourceClass(DescriptorBindingKind kind) { const auto value = static_cast(kind); if (value >= FirstImageBinding && value < FirstStorageImageBinding) { diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index 51308b954a49..f73abbdf8b3e 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -425,14 +425,6 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l plan.bindings.reserve(layout.descriptors.size()); const bool slotWords = layout.gpuResolvedImages && !registrationModules; std::uint32_t imageSlotBase = layout.ImageSlotDword(); - const auto descriptorSetFor = [&](DescriptorBindingKind kind) { - if (kind == DescriptorBindingKind::Gds && layout.UsesDataAddress()) return RuntimeAbi::GpuGdsSet; - if (layout.gpuResolvedImages) { - const bool heapSetBinding = layout.HeapImageKind(kind) || kind == DescriptorBindingKind::Samplers || kind == DescriptorBindingKind::ShaderData || kind == DescriptorBindingKind::FlattenedSrt; - return heapSetBinding ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet; - } - return fragmentDescriptorSet && stage == IrShaderStage::Pixel ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet; - }; for (const auto& logical : layout.descriptors) { const bool imageHeap = ImageBindingResourceClass(logical.kind) != ImageResourceClass::None; const bool samplerHeap = logical.kind == DescriptorBindingKind::Samplers; @@ -472,10 +464,8 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l if ((imageHeap || samplerHeap) && compact.resources.empty()) continue; PreparedDescriptorBinding entry{}; auto& physical = entry.descriptor; - const bool heapImage = layout.HeapImageKind(compact.kind); - const bool sharedHeapArray = layout.gpuResolvedImages && (heapImage || samplerHeap); - physical.descriptorSet = descriptorSetFor(compact.kind); - physical.binding = NativeBinding(sharedHeapArray ? IrShaderStage::Pixel : stage, compact.kind); + physical.descriptorSet = DescriptorSetNumber(layout, compact.kind, stage, layout.gpuResolvedImages, fragmentDescriptorSet, true); + physical.binding = DescriptorBindingNumber(layout, compact.kind, stage, layout.gpuResolvedImages); physical.count = compact.resources.empty() ? 1u : static_cast(compact.resources.size()); physical.kind = PhysicalKindFor(compact.kind); physical.role = RoleFor(compact.kind); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp index dbcfe577f92b..32e9076cd8a4 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp @@ -42,6 +42,7 @@ std::uint32_t TypeStorageBufferU8Pointer(SpirvEmitterState& state); std::uint32_t TypeStorageBufferU8ElementPointer(SpirvEmitterState& state); std::uint32_t TypePhysicalU32Pointer(SpirvEmitterState& state); std::uint32_t TypePhysicalBufferPointer(SpirvEmitterState& state, bool wide); +std::uint32_t ReadOnlyStorageBufferType(SpirvEmitterState& state, std::uint32_t element, std::uint32_t stride); std::uint32_t TypePhysicalReadOnlyBufferPointer(SpirvEmitterState& state, bool wide); std::uint32_t TypePushConstantElementPointer(SpirvEmitterState& state); std::uint32_t TypeU32ArrayPointer(SpirvEmitterState& state, std::uint32_t storageClass, std::uint32_t dwords); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index 7dafa33356c3..33e96153abfc 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -93,6 +93,9 @@ struct SpirvEmitterState { const ImageResource* runtimeImage = nullptr; SpirvTableAccess tableAccess; SpirvEmitterState(const IrProgram& program, const ShaderStageInputInfo& inputInfo); + [[nodiscard]] bool BdaAddressed() const; + [[nodiscard]] bool TableMapAddressed() const; + [[nodiscard]] bool TableHeap() const; SpirvModule module; const IrProgram& program; @@ -223,9 +226,6 @@ struct SpirvEmitterState { std::unordered_map heapSlotVariables; std::uint32_t flattenedSrtVariable = 0; bool flattenedSrtAddressed = false; - bool bdaAddressed = false; - bool tableMapAddressed = false; - bool tableHeap = false; std::uint32_t ldsVariable = 0; std::uint32_t ldsBufferVariable = 0; std::uint32_t ldsBufferU64Variable = 0; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp index 1c70beac0361..b5d015a73697 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp @@ -4,12 +4,15 @@ #include "SpirvBackend/SpirvEmitterState.hpp" #include "IntermediateRepresentation/IrProgram.hpp" #include +#include namespace ShaderRecompiler { std::uint32_t EmitBinaryU32(SpirvEmitterState& state, std::uint32_t opcode, std::uint32_t lhs, std::uint32_t rhs); std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dwordIndex); std::uint32_t EmitShaderDataWordLoad(SpirvEmitterState& state, std::uint32_t index); +std::uint32_t ComposeAddress64(SpirvEmitterState& state, const std::function& loadLow, const std::function& loadHigh); +std::uint32_t EmitAlignedLoadU32(SpirvEmitterState& state, std::uint32_t pointer); std::uint32_t EmitRootDword(SpirvEmitterState& state, std::uint32_t field); std::uint32_t EmitStageRootDword(SpirvEmitterState& state, RuntimeAbi::RootStageField field); std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, std::uint32_t field, std::uint32_t index); @@ -19,6 +22,7 @@ std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::Roo std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index); bool HasFlattenedSrt(const SpirvEmitterState& state); void EmitMemoryOffsets(SpirvEmitterState& state); +std::uint32_t LoadTableMap(SpirvEmitterState& state, std::uint32_t index); std::uint32_t LoadHeapSlotWord(SpirvEmitterState& state, std::uint32_t dword); std::uint32_t LdsDwordCount(const SpirvEmitterState& state); bool LdsInDeviceMemory(const SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp index 04b65b1ad674..b4570bef9264 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp @@ -13,8 +13,8 @@ std::uint32_t BdaConstant(SpirvEmitterState& state, std::uint64_t value) { } std::uint32_t BdaWord(SpirvEmitterState& state, std::uint32_t variable, std::uint32_t index) { - if (state.bdaAddressed && variable == state.bdaPagetableVariable) return EmitRootAddressReadOnlyWordPointer(state, RuntimeAbi::RootPagetableAddress, index); - if (state.bdaAddressed && variable == state.faultBufferVariable) return EmitRootAddressWordPointer(state, RuntimeAbi::RootFaultAddress, index); + if (state.BdaAddressed() && variable == state.bdaPagetableVariable) return EmitRootAddressReadOnlyWordPointer(state, RuntimeAbi::RootPagetableAddress, index); + if (state.BdaAddressed() && variable == state.faultBufferVariable) return EmitRootAddressWordPointer(state, RuntimeAbi::RootFaultAddress, index); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, variable, ConstantU32(state, 0u), index); return pointer; @@ -22,7 +22,7 @@ std::uint32_t BdaWord(SpirvEmitterState& state, std::uint32_t variable, std::uin std::uint32_t BdaLoadWord(SpirvEmitterState& state, std::uint32_t index) { const auto value = state.module.AllocateId(); - if (state.bdaAddressed) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, BdaWord(state, state.bdaPagetableVariable, index), spv::MemoryAccessAlignedMask, 4u); + if (state.BdaAddressed()) state.module.AddFunction(spv::OpLoad, TypeU32(state), value, BdaWord(state, state.bdaPagetableVariable, index), spv::MemoryAccessAlignedMask, 4u); else state.module.AddFunction(spv::OpLoad, TypeU32(state), value, BdaWord(state, state.bdaPagetableVariable, index)); return value; } @@ -64,7 +64,7 @@ void DefineBdaFaultFunction(SpirvEmitterState& state) { const auto won = Binary(state, spv::OpIEqual, TypeBool(state), previous, ConstantU32(state, 0u)); EmitIfCondition(state, won, [&] { const auto store = [&](std::uint32_t index, std::uint32_t value) { - if (state.bdaAddressed) state.module.AddFunction(spv::OpStore, BdaWord(state, state.faultBufferVariable, ConstantU32(state, index)), value, spv::MemoryAccessAlignedMask, 4u); + if (state.BdaAddressed()) state.module.AddFunction(spv::OpStore, BdaWord(state, state.faultBufferVariable, ConstantU32(state, index)), value, spv::MemoryAccessAlignedMask, 4u); else state.module.AddFunction(spv::OpStore, BdaWord(state, state.faultBufferVariable, ConstantU32(state, index)), value); }; store(1, reason); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp index eb1d96d1967f..68f7b42b2497 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp @@ -65,8 +65,8 @@ std::uint32_t DefineBdaLookup(SpirvEmitterState& state, const char* name, bool r } leaveIf(binary(spv::OpINotEqual, boolean, reason, constant(0u)), reason); }; - auto length = state.bdaAddressed ? EmitRootDword(state, RuntimeAbi::RootPagetableDwords) : state.module.AllocateId(); - if (!state.bdaAddressed) state.module.AddFunction(spv::OpArrayLength, u32, length, state.bdaPagetableVariable, 0u); + auto length = state.BdaAddressed() ? EmitRootDword(state, RuntimeAbi::RootPagetableDwords) : state.module.AllocateId(); + if (!state.BdaAddressed()) state.module.AddFunction(spv::OpArrayLength, u32, length, state.bdaPagetableVariable, 0u); fail(binary(spv::OpULessThan, boolean, length, constant(4)), BdaAbi::FaultReason::InvalidTable); const auto count = BdaLoadWord(state, constant(1)); const auto available = binary(spv::OpISub, u32, length, constant(4)); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp index 3bfc0981acc6..9edaaa2b9158 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp @@ -79,6 +79,18 @@ std::uint32_t WaveLdsScope(const IrProgram& program, const ShaderWorkgroupInputI SpirvEmitterState::SpirvEmitterState(const IrProgram& program, const ShaderStageInputInfo& inputInfo) : module(program.Resources().stage == IrShaderStage::Mesh ? 0x00010400u : 0x00010300u), program(program), inputInfo(inputInfo), requirements(AnalyzeProgramRequirements(program)) { } +bool SpirvEmitterState::BdaAddressed() const { + return (bdaPagetableVariable != 0 || faultBufferVariable != 0) && program.Metadata().bindings.UsesDataAddress(); +} + +bool SpirvEmitterState::TableMapAddressed() const { + return tableMapVariable != 0 && program.Metadata().bindings.UsesDataAddress(); +} + +bool SpirvEmitterState::TableHeap() const { + return gpuResolvedImages && program.Metadata().bindings.UsesDataAddress(); +} + SpirvValueEmitContext::SpirvValueEmitContext(SpirvEmitterState& state) : state(state) { } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp index ec0dbd666e89..eefd21e39cb6 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp @@ -1753,8 +1753,10 @@ ScalarBufferDword EmitScalarBufferDword(SpirvEmitterState& state, std::uint32_t return dword; } +} + std::uint32_t LoadTableMap(SpirvEmitterState& state, std::uint32_t index) { - if (state.tableMapAddressed) { + if (state.TableMapAddressed()) { const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, TypeU32(state), value, EmitStageRingWordPointer(state, RuntimeAbi::RootStageField::TableMap, index), spv::MemoryAccessAlignedMask, 4u); return value; @@ -1766,6 +1768,8 @@ std::uint32_t LoadTableMap(SpirvEmitterState& state, std::uint32_t index) { return value; } +namespace { + std::uint32_t TableMapAt(SpirvEmitterState& state, std::uint32_t base, std::uint32_t offset) { return LoadTableMap(state, offset == 0u ? base : Binary(state, spv::OpIAdd, TypeU32(state), base, ConstantU32(state, offset))); } @@ -1901,8 +1905,8 @@ TableAccessResult EmitTableAccess(SpirvValueEmitContext& ctx, const IrValue& ins result.valid = both(checked, negate(driverRejected)); result.flags = flags; live = selected; - state.tableAccess.element = state.tableHeap ? Select(state, u32, checked, element, ConstantU32(state, 0u)) : Binary(state, spv::OpIAdd, u32, LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)), element); - state.tableAccess.heap = state.tableHeap; + state.tableAccess.element = state.TableHeap() ? Select(state, u32, checked, element, ConstantU32(state, 0u)) : Binary(state, spv::OpIAdd, u32, LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)), element); + state.tableAccess.heap = state.TableHeap(); const auto& sources = state.program.Resources().descriptorSources; state.tableAccess.uniform = base.source < sources.size() && sources[base.source].tableColumn.has_value() && sources[base.source].tableColumn->selected; if (!state.tableAccess.uniform) DecorateTableNonUniform(state, state.tableAccess.element); @@ -2326,8 +2330,7 @@ void EmitImageBvhIntersectRay(SpirvValueEmitContext& ctx, const IrValue& inst) { for (std::uint32_t i = 0; i < 4u; ++i) { const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpConvertUToPtr, TypePhysicalU32Pointer(state), pointer, op(spv::OpIAdd, u64, physical, BdaConstant(state, (first + i) * 4u))); - values[i] = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, u32, values[i], pointer, spv::MemoryAccessAlignedMask, 4u); + values[i] = EmitAlignedLoadU32(state, pointer); } return compose(values); }); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 1b297f86402c..d8b999662cd9 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -5,6 +5,7 @@ #include "SpirvBackend/SpirvMemory/SpirvDescriptors.hpp" #include "SpirvBackend/SpirvBda.hpp" #include +#include #include #include #include @@ -33,6 +34,12 @@ std::uint32_t EmitBinaryU32(SpirvEmitterState& state, std::uint32_t opcode, std: return result; } +std::uint32_t EmitAlignedLoadU32(SpirvEmitterState& state, std::uint32_t pointer) { + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, spv::MemoryAccessAlignedMask, 4u); + return value; +} + std::uint32_t EmitRootDword(SpirvEmitterState& state, std::uint32_t field) { if (!state.program.Metadata().bindings.UsesDataAddress()) FailEmit("the root is read only by stages that take their data through it"); const auto u32 = TypeU32(state); @@ -48,13 +55,17 @@ std::uint32_t EmitStageRootDword(SpirvEmitterState& state, RuntimeAbi::RootStage return EmitRootDword(state, RuntimeAbi::RootStageDword(RuntimeAbi::StageGroup(stage == IrShaderStage::Pixel, stage == IrShaderStage::TessellationControl, stage == IrShaderStage::TessellationEvaluation), field)); } +std::uint32_t ComposeAddress64(SpirvEmitterState& state, const std::function& loadLow, const std::function& loadHigh) { + const auto u64 = TypeScalarU64(state); + const auto low = Unary(state, spv::OpUConvert, u64, loadLow()); + const auto high = Binary(state, spv::OpShiftLeftLogical, u64, Unary(state, spv::OpUConvert, u64, loadHigh()), BdaConstant(state, 32u)); + return Binary(state, spv::OpBitwiseOr, u64, low, high); +} + namespace { std::uint32_t rootAddress(SpirvEmitterState& state, std::uint32_t field) { - const auto u64 = TypeScalarU64(state); - const auto low = Unary(state, spv::OpUConvert, u64, EmitRootDword(state, field)); - const auto high = Binary(state, spv::OpShiftLeftLogical, u64, Unary(state, spv::OpUConvert, u64, EmitRootDword(state, field + 1u)), BdaConstant(state, 32u)); - return Binary(state, spv::OpBitwiseOr, u64, low, high); + return ComposeAddress64(state, [&] { return EmitRootDword(state, field); }, [&] { return EmitRootDword(state, field + 1u); }); } std::uint32_t wordPointer(SpirvEmitterState& state, std::uint32_t base, std::uint32_t index) { @@ -66,12 +77,7 @@ std::uint32_t wordPointer(SpirvEmitterState& state, std::uint32_t base, std::uin } std::uint32_t readOnlyWordPointer(SpirvEmitterState& state, std::uint32_t base, std::uint32_t index) { - const auto array = state.module.DecoratedType(spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4u}}}, TypeU32(state)); - const auto words = state.module.DecoratedType(spv::OpTypeStruct, - {{spv::OpDecorate, {spv::DecorationBlock}}, - {spv::OpMemberDecorate, {0u, spv::DecorationOffset, 0u}}, - {spv::OpMemberDecorate, {0u, spv::DecorationNonWritable}}}, - array); + const auto words = ReadOnlyStorageBufferType(state, TypeU32(state), 4u); const auto block = state.module.AllocateId(); state.module.AddFunction(spv::OpConvertUToPtr, TypePointer(state, spv::StorageClassPhysicalStorageBuffer, words), block, base); const auto pointer = state.module.AllocateId(); @@ -113,9 +119,7 @@ std::uint32_t dataAddressLoad(SpirvEmitterState& state, RuntimeAbi::RootStageFie return value; } const auto pointer = EmitStageRingWordPointer(state, field, index); - const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer, spv::MemoryAccessAlignedMask, 4u); - return value; + return EmitAlignedLoadU32(state, pointer); } } @@ -184,9 +188,7 @@ void EmitHeapSlotPreload(SpirvEmitterState& state) { const IrBindingLayout& layout = state.program.Metadata().bindings; std::vector dwords; for (auto dword = layout.SamplerSlotDword(); dword < layout.ShaderDataDwords(); ++dword) dwords.push_back(dword); - constexpr auto metadataWords = static_cast(sizeof(RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t)); - constexpr auto firstElement = static_cast(offsetof(RuntimeAbi::ResourceMetadata, firstElement) / sizeof(std::uint32_t)); - for (std::uint32_t image = 0; image < layout.runtimeImageCount; ++image) dwords.push_back(layout.ImageMetadataDword() + image * metadataWords + firstElement); + for (std::uint32_t image = 0; image < layout.runtimeImageCount; ++image) dwords.push_back(layout.ImageFirstElementDword(image)); const auto pointerType = TypePointer(state, spv::StorageClassPrivate, TypeU32(state)); for (const auto dword : dwords) { if (dword >= layout.ShaderDataDwords() || state.heapSlotVariables.contains(dword)) continue; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp index bf8c1d32f2f2..667566a2f692 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp @@ -80,28 +80,22 @@ void DecorateTableNonUniform(SpirvEmitterState& state, std::uint32_t id) { namespace { -std::uint32_t tableMapWord(SpirvEmitterState& state, std::uint32_t index) { - const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, EmitStageRingWordPointer(state, RuntimeAbi::RootStageField::TableMap, index), spv::MemoryAccessAlignedMask, 4u); - return value; -} - std::uint32_t tableHeapSlot(SpirvEmitterState& state, RuntimeAbi::HeapPart part, std::uint32_t element, std::uint32_t slots) { using RuntimeAbi::HeapPart; const auto partIndex = static_cast(part); const auto u32 = TypeU32(state); - const auto base = tableMapWord(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)); - const auto count = tableMapWord(state, ConstantU32(state, ImageTableAbi::HeaderElementCount)); + const auto base = LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementBase)); + const auto count = LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderElementCount)); std::uint32_t partBase = base; if (part == HeapPart::Storage || part == HeapPart::Sampler) { partBase = Binary(state, spv::OpIAdd, u32, base, Binary(state, spv::OpIMul, u32, count, ConstantU32(state, partIndex))); } else if (part >= HeapPart::Atomic) { - const auto samplers = tableMapWord(state, ConstantU32(state, ImageTableAbi::HeaderSamplerCount)); + const auto samplers = LoadTableMap(state, ConstantU32(state, ImageTableAbi::HeaderSamplerCount)); const auto samplerSpan = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), count, samplers), samplers, count); const auto extra = Binary(state, spv::OpIMul, u32, count, ConstantU32(state, partIndex - 1u)); partBase = Binary(state, spv::OpIAdd, u32, Binary(state, spv::OpIAdd, u32, base, samplerSpan), extra); } - const auto slot = tableMapWord(state, Binary(state, spv::OpIAdd, u32, partBase, element)); + const auto slot = LoadTableMap(state, Binary(state, spv::OpIAdd, u32, partBase, element)); const auto fallback = RuntimeAbi::HeapPartFirstBinding(part); const auto clamped = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), slot, ConstantU32(state, slots)), slot, ConstantU32(state, fallback)); DecorateTableNonUniform(state, clamped); @@ -198,8 +192,7 @@ void RequireDynamicIndexing(SpirvEmitterState& state, std::uint32_t capability, std::uint32_t HeapImageSlot(SpirvEmitterState& state, DescriptorBindingKind kind, std::uint32_t resource) { RequireDynamicIndexing(state, spv::CapabilitySampledImageArrayDynamicIndexing, kind, resource, "the image heap needs image array dynamic indexing, which the device lacks"); - const auto dword = state.program.Metadata().bindings.ImageMetadataDword() + resource * static_cast(sizeof(RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t)) + static_cast(offsetof(RuntimeAbi::ResourceMetadata, firstElement) / sizeof(std::uint32_t)); - return LoadHeapSlotWord(state, dword); + return LoadHeapSlotWord(state, state.program.Metadata().bindings.ImageFirstElementDword(resource)); } std::uint32_t HeapImageSlotWord(SpirvEmitterState& state, DescriptorBindingKind kind, std::uint32_t resource, std::uint32_t arrayIndex) { @@ -272,7 +265,7 @@ std::uint32_t LoadSamplerDescriptor(SpirvEmitterState& state, std::uint32_t samp const auto variant = image != nullptr && image->depthCompare ? 2u : 0u; const auto element = Binary(state, spv::OpIAdd, TypeU32(state), state.tableAccess.samplerElement, ConstantU32(state, variant + (point ? 1u : 0u))); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.tableSamplerVariable, state.tableHeap ? tableHeapSlot(state, RuntimeAbi::HeapPart::Sampler, element, RuntimeAbi::GpuSamplerHeapSlots) : element); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.tableSamplerVariable, state.TableHeap() ? tableHeapSlot(state, RuntimeAbi::HeapPart::Sampler, element, RuntimeAbi::GpuSamplerHeapSlots) : element); DecorateTableNonUniform(state, pointer); const auto loaded = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, samplerType, loaded, pointer); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index 94a6ce5a2a35..d65b883b5bbd 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -465,6 +465,19 @@ void DefineOutputs(SpirvEmitterState& state) { } } +namespace { + +std::uint32_t defineHeapArray(SpirvEmitterState& state, std::uint32_t slotCount, std::uint32_t elementType, const char* name, std::uint32_t heapKind) { + const auto type = state.module.Type(spv::OpTypeArray, elementType, slotCount); + const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniformConstant, type), spv::StorageClassUniformConstant); + state.module.AddName(variable, name); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, RuntimeAbi::FragmentDescriptorSet); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, NativeBinding(IrShaderStage::Pixel, static_cast(heapKind))); + return variable; +} + +} + void DefineDescriptors(SpirvEmitterState& state) { const IrBindingLayout& layout = state.program.Metadata().bindings; const IrShaderStage stage = state.program.Resources().stage; @@ -475,14 +488,12 @@ void DefineDescriptors(SpirvEmitterState& state) { state.module.AddName(state.pushConstantVariable, "vsharp"); } for (const IrDescriptorBinding& binding : layout.descriptors) { - const bool gpuHeap = state.gpuResolvedImages && (binding.kind == DescriptorBindingKind::Samplers || layout.HeapImageKind(binding.kind)); + const bool gpuHeap = SharedHeapArray(layout, binding.kind, state.gpuResolvedImages); const auto Define = [&](std::uint32_t type, const char* name, std::uint32_t storage = spv::StorageClassStorageBuffer) { const auto variable = state.module.DefineGlobalVariable(TypePointer(state, storage, type), storage); state.module.AddName(variable, name); - const bool gpuData = state.gpuResolvedImages && (binding.kind == DescriptorBindingKind::ShaderData || binding.kind == DescriptorBindingKind::FlattenedSrt); - const bool fragmentSet = gpuHeap || (!state.gpuResolvedImages && state.fragmentDescriptorSet && stage == IrShaderStage::Pixel); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, binding.kind == DescriptorBindingKind::Gds && layout.UsesDataAddress() ? RuntimeAbi::GpuGdsSet : gpuData ? RuntimeAbi::GpuDataSet : fragmentSet ? RuntimeAbi::FragmentDescriptorSet : RuntimeAbi::DescriptorSet); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, NativeBinding(gpuHeap ? IrShaderStage::Pixel : stage, binding.kind)); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, DescriptorSetNumber(layout, binding.kind, stage, state.gpuResolvedImages, state.fragmentDescriptorSet, false)); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, DescriptorBindingNumber(layout, binding.kind, stage, state.gpuResolvedImages)); return variable; }; const auto ArrayType = [&](std::uint32_t type) { @@ -513,7 +524,6 @@ void DefineDescriptors(SpirvEmitterState& state) { case DescriptorBindingKind::BdaPagetable: if (layout.UsesDataAddress()) { state.bdaPagetableVariable = state.module.AllocateId(); - state.bdaAddressed = true; } else { state.bdaPagetableVariable = Define(StorageBufferBlockType(state), "bda_pagetable"); state.module.AddAnnotation(spv::OpDecorate, state.bdaPagetableVariable, spv::DecorationNonWritable); @@ -522,7 +532,6 @@ void DefineDescriptors(SpirvEmitterState& state) { case DescriptorBindingKind::FaultBuffer: if (layout.UsesDataAddress()) { state.faultBufferVariable = state.module.AllocateId(); - state.bdaAddressed = true; } else { state.faultBufferVariable = Define(StorageBufferBlockType(state), "fault_buffer"); } @@ -556,7 +565,6 @@ void DefineDescriptors(SpirvEmitterState& state) { case DescriptorBindingKind::ImageStorageTable: RequireTableIndexing(state); if (binding.kind == DescriptorBindingKind::ImageStorageTable) state.module.EmitCapability(spv::CapabilityStorageImageArrayDynamicIndexing); - state.tableHeap = state.gpuResolvedImages && layout.UsesDataAddress(); for (std::uint32_t resource = 0; resource < state.program.Info().images.size(); ++resource) { const auto& image = state.program.Info().images[resource]; if (image.table == NoTable) continue; @@ -566,16 +574,12 @@ void DefineDescriptors(SpirvEmitterState& state) { if ((ImageBindingResourceClass(kind) == ImageResourceClass::Storage) != (binding.kind == DescriptorBindingKind::ImageStorageTable)) continue; if (std::any_of(state.tableImageVariables.begin(), state.tableImageVariables.end(), [&](const SpirvTableImageVariable& variable) { return variable.kind == kind; })) continue; const auto name = "table_images_" + std::to_string(static_cast(kind)); - if (state.tableHeap) { + if (state.TableHeap()) { const auto value = static_cast(kind); const auto part = RuntimeAbi::StorageHeapPart(value); const auto heapKind = binding.kind != DescriptorBindingKind::ImageStorageTable ? RuntimeAbi::FirstImageBinding : part == RuntimeAbi::HeapPart::Atomic || part == RuntimeAbi::HeapPart::Atomic64 ? RuntimeAbi::HeapPartFirstBinding(part) : RuntimeAbi::FirstStorageImageBinding; - const auto type = state.module.Type(spv::OpTypeArray, ImageType(state, mode), ConstantU32(state, RuntimeAbi::GpuImageHeapSlots)); - const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniformConstant, type), spv::StorageClassUniformConstant); - state.module.AddName(variable, name.c_str()); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, RuntimeAbi::FragmentDescriptorSet); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, NativeBinding(IrShaderStage::Pixel, static_cast(heapKind))); - state.tableImageVariables.push_back({kind, variable}); + const auto slotCount = ConstantU32(state, RuntimeAbi::GpuImageHeapSlots); + state.tableImageVariables.push_back({kind, defineHeapArray(state, slotCount, ImageType(state, mode), name.c_str(), heapKind)}); } else { state.tableImageVariables.push_back({kind, Define(state.module.Type(spv::OpTypeRuntimeArray, ImageType(state, mode)), name.c_str(), spv::StorageClassUniformConstant)}); } @@ -586,12 +590,8 @@ void DefineDescriptors(SpirvEmitterState& state) { case DescriptorBindingKind::SamplerTable: RequireTableIndexing(state); if (state.gpuResolvedImages && layout.UsesDataAddress()) { - const auto type = state.module.Type(spv::OpTypeArray, state.module.Type(spv::OpTypeSampler), ConstantU32(state, RuntimeAbi::GpuSamplerHeapSlots)); - state.tableSamplerVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniformConstant, type), spv::StorageClassUniformConstant); - state.module.AddName(state.tableSamplerVariable, "table_samplers"); - state.module.AddAnnotation(spv::OpDecorate, state.tableSamplerVariable, spv::DecorationDescriptorSet, RuntimeAbi::FragmentDescriptorSet); - state.module.AddAnnotation(spv::OpDecorate, state.tableSamplerVariable, spv::DecorationBinding, NativeBinding(IrShaderStage::Pixel, DescriptorBindingKind::Samplers)); - state.tableHeap = true; + const auto slotCount = ConstantU32(state, RuntimeAbi::GpuSamplerHeapSlots); + state.tableSamplerVariable = defineHeapArray(state, slotCount, state.module.Type(spv::OpTypeSampler), "table_samplers", static_cast(DescriptorBindingKind::Samplers)); } else { state.tableSamplerVariable = Define(state.module.Type(spv::OpTypeRuntimeArray, state.module.Type(spv::OpTypeSampler)), "table_samplers", spv::StorageClassUniformConstant); } @@ -599,7 +599,6 @@ void DefineDescriptors(SpirvEmitterState& state) { case DescriptorBindingKind::ImageTableMap: if (layout.UsesDataAddress()) { state.tableMapVariable = state.module.AllocateId(); - state.tableMapAddressed = true; } else { state.tableMapVariable = Define(StorageBufferBlockType(state), "table_map"); state.module.AddAnnotation(spv::OpDecorate, state.tableMapVariable, spv::DecorationNonWritable); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp index 1a668c9d8a92..dbc57f23ae0e 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvTypes.cpp @@ -7,22 +7,22 @@ namespace ShaderRecompiler { -namespace { - -std::uint32_t StorageBufferType(SpirvEmitterState& state) { - const auto array = state.module.DecoratedType(spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4u}}}, TypeU32(state)); +std::uint32_t ReadOnlyStorageBufferType(SpirvEmitterState& state, std::uint32_t element, std::uint32_t stride) { + const auto array = state.module.DecoratedType(spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, stride}}}, element); return state.module.DecoratedType(spv::OpTypeStruct, {{spv::OpDecorate, {spv::DecorationBlock}}, - {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}}, + {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, + {spv::OpMemberDecorate, {0, spv::DecorationNonWritable}}}, array); } -std::uint32_t ReadOnlyStorageBufferType(SpirvEmitterState& state, std::uint32_t element, std::uint32_t stride) { - const auto array = state.module.DecoratedType(spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, stride}}}, element); +namespace { + +std::uint32_t StorageBufferType(SpirvEmitterState& state) { + const auto array = state.module.DecoratedType(spv::OpTypeRuntimeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4u}}}, TypeU32(state)); return state.module.DecoratedType(spv::OpTypeStruct, {{spv::OpDecorate, {spv::DecorationBlock}}, - {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}, - {spv::OpMemberDecorate, {0, spv::DecorationNonWritable}}}, + {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}}, array); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp index 1f4feb9c94e9..75784384f2ca 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp @@ -1,6 +1,7 @@ #include "SpirvBackend/SpirvModuleEmitter.hpp" #include "SpirvBackend/SpirvBufferFormat.hpp" #include "SpirvBackend/SpirvEmitterHelpers.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include "SpirvBackend/SpirvEmitterInstructions.hpp" #include "SpirvBackend/SpirvFlowEmitter.hpp" #include "SpirvBackend/SpirvBda.hpp" @@ -2014,9 +2015,7 @@ std::uint32_t LoadMeshArgumentWord(SpirvEmitterState& state, std::uint32_t addre const auto element = Binary(state, spv::OpIAdd, TypeScalarU64(state), address, Binary(state, spv::OpShiftLeftLogical, TypeScalarU64(state), Unary(state, spv::OpUConvert, TypeScalarU64(state), dword), ConstantU32(state, 2u))); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpConvertUToPtr, TypePointer(state, spv::StorageClassPhysicalStorageBuffer, TypeU32(state)), pointer, element); - const auto loaded = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), loaded, pointer, spv::MemoryAccessAlignedMask, 4u); - return loaded; + return EmitAlignedLoadU32(state, pointer); } } @@ -2063,8 +2062,7 @@ std::uint32_t EmitMeshArgument(SpirvValueEmitContext& ctx, const IrValue& inst) const auto element = Binary(state, spv::OpIAdd, TypeScalarU64(state), address, BdaConstant(state, 4ull * index)); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpConvertUToPtr, TypePointer(state, spv::StorageClassPhysicalStorageBuffer, TypeU32(state)), pointer, element); - const auto loaded = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), loaded, pointer, spv::MemoryAccessAlignedMask, 4u); + const auto loaded = EmitAlignedLoadU32(state, pointer); state.module.AddFunction(spv::OpBranch, merge); EmitLabel(state, merge); const auto value = state.module.AllocateId(); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index a51f59e46988..1e0bfc38c97b 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -203,9 +203,7 @@ MemoryResourceAccess directAccess(SpirvValueEmitContext& context, const IrValue& const auto element = ResourceForDescriptor(state, DescriptorBindingKind::Buffers, memory.resource); const auto dword = state.program.Metadata().bindings.BufferAddressDword() + element * RuntimeAbi::BufferAddressWords; const auto u64 = TypeScalarU64(state); - const auto low = Unary(state, spv::OpUConvert, u64, EmitShaderDataDwordLoad(state, dword)); - const auto high = Binary(state, spv::OpShiftLeftLogical, u64, Unary(state, spv::OpUConvert, u64, EmitShaderDataDwordLoad(state, dword + 1u)), BdaConstant(state, 32u)); - auto address = Binary(state, spv::OpBitwiseOr, u64, low, high); + auto address = ComposeAddress64(state, [&] { return EmitShaderDataDwordLoad(state, dword); }, [&] { return EmitShaderDataDwordLoad(state, dword + 1u); }); MemoryResourceAccess access; access.kind = memory.kind; access.physical = true; From 09cc865e29c365a5b8152d68f2fb8f8d3f963872 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 1 Nov 2026 07:44:18 +0530 Subject: [PATCH 093/269] test(agc): tidy the GPU heap tests GPU heap test variants now skip instead of passing on the per-draw path when the device has no descriptor heap. One env-test registration helper, one heap sample kernel shared by the compute-sample and journal tests, shared environment and no-heap skip helpers, loops instead of repeated draw-sample calls, and removed dead branches, diagnostics, locals and includes. The registered test list and every test's command and environment are unchanged. --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 27 ++-- .../libSceAgcDriver/tests/BdaContracts.cpp | 3 - .../tests/BindlessHeapSlots.cpp | 32 ++--- .../prx/libSceAgcDriver/tests/Graphics.cpp | 1 + .../libSceAgcDriver/tests/HeapWalkMemo.cpp | 1 - .../tests/PresentationPass.cpp | 5 +- .../libSceAgcDriver/tests/ShaderMemory.cpp | 68 ++++------ ...river_address_draw_space_reuse_tests.cmake | 16 +-- .../agc_driver_bindless_images_tests.cmake | 7 +- .../agc_driver_dispatch_move_tests.cmake | 7 +- ...agc_driver_heap_compute_sample_tests.cmake | 21 +-- .../agc_driver_heap_draw_sample_tests.cmake | 29 ++--- .../cmake/agc_driver_heap_slots_tests.cmake | 15 +-- .../agc_driver_pipeline_journal_tests.cmake | 7 +- ...gc_driver_sampled_cache_budget_tests.cmake | 6 +- ...gc_driver_storage_cache_budget_tests.cmake | 16 +-- .../tests/cmake/agc_shader_memory_tests.cmake | 18 +-- .../tests/execution/AddressDrawSpaceReuse.cpp | 11 +- .../tests/execution/HeapComputeSample.cpp | 102 +++------------ .../tests/execution/HeapDrawSample.cpp | 123 ++++++------------ .../tests/execution/HeapSampleKernel.hpp | 69 ++++++++++ .../tests/execution/HeapTableStageReuse.cpp | 13 +- .../tests/execution/ImageTableCacheBounds.cpp | 37 +++--- .../tests/execution/MultisampleRetirement.cpp | 2 +- .../tests/execution/PipelineJournal.cpp | 33 +---- .../tests/execution/SampledCacheBudget.cpp | 16 +-- .../tests/execution/StorageCacheBudget.cpp | 22 ++-- .../tests/execution/VulkanTestDevice.hpp | 18 ++- 28 files changed, 285 insertions(+), 440 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/HeapSampleKernel.hpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 4f6965a816f9..4dcede6458f3 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -625,20 +625,29 @@ function(agc_add_default_test agcTest) endif() endfunction() -function(agc_add_draw_pipeline_test agcTestName) - add_test(NAME ${agcTestName}_draw_pipeline COMMAND ${agcTestName}_tests) - set_tests_properties(${agcTestName}_draw_pipeline PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") +function(agc_add_env_test agcTestName agcTestTarget) + cmake_parse_arguments(PARSE_ARGV 2 agcEnvTest "NO_WORKING_DIRECTORY" "TIMEOUT" "ARGS;ENV") + add_test(NAME ${agcTestName} COMMAND ${agcTestTarget} ${agcEnvTest_ARGS}) + set_tests_properties(${agcTestName} PROPERTIES ENVIRONMENT "${agcEnvTest_ENV}" SKIP_RETURN_CODE 77) + if(NOT agcEnvTest_NO_WORKING_DIRECTORY) + set_tests_properties(${agcTestName} PROPERTIES WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + endif() + if(agcEnvTest_TIMEOUT) + set_tests_properties(${agcTestName} PROPERTIES TIMEOUT ${agcEnvTest_TIMEOUT}) + endif() if(WIN32) - set_tests_properties(${agcTestName}_draw_pipeline PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + set_tests_properties(${agcTestName} PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endfunction() +function(agc_add_draw_pipeline_test agcTestName) + agc_add_env_test(${agcTestName}_draw_pipeline ${agcTestName}_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) +endfunction() + function(agc_add_gpu_heap_test agcTestName) - add_test(NAME ${agcTestName}_gpu_heap COMMAND ${agcTestName}_tests) - set_tests_properties(${agcTestName}_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(${agcTestName}_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - endif() + agc_add_env_test(${agcTestName}_gpu_heap ${agcTestName}_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) endfunction() function(agc_add_spirv_mode_tests agcTest) diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp b/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp index fd6aadb9db7f..1fb04efb8632 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp @@ -2,14 +2,11 @@ #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "ControlFlow/RequestSerializer.hpp" #include "SpirvBackend/SpirvBda.hpp" -#include #include -#include #include #include #include #include -#include namespace { diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 0c3be4226d8a..77dad0d71a0d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -1,4 +1,4 @@ -#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "execution/VulkanTestDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" #include "prx/libSceAgcDriver/Graphics/include/PlaceholderImages.hpp" @@ -20,8 +20,6 @@ namespace { using namespace AgcDriver::Graphics; namespace Abi = ShaderRecompiler::RuntimeAbi; -constexpr int VulkanTestSkipped = 77; - void require(bool condition, const std::string& what) { if (!condition) throw std::runtime_error(what); } @@ -228,7 +226,7 @@ void ringSpans(const Context& context) { void ringLargeSpans(const Context& context) { BindlessHeap heap(context); - if (heap.RingChunkCount() < 5u) return; + require(heap.RingChunkCount() >= 5u, "the ring has fewer than five chunks, so a span over three chunks cannot be tested"); constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); constexpr std::size_t largeWords = chunkWords * 2u + 1024u; BindlessHeap::SpanMark pin; @@ -285,8 +283,6 @@ void ringCurrentChunk(const Context& context) { require(heap.Held(live), "the current chunk's span is still held"); } -} - void heapComesBack(const Context& context, VkImageView view) { auto& heap = BindlessHeap::For(context); const auto kind = Abi::FirstImageBinding; @@ -388,32 +384,20 @@ void twoHeapsComeBack(const Context& context, VkImageView view) { first.reset(); } +} + int main(int argc, char** argv) { const std::string mode = argc > 1 ? argv[1] : ""; const bool comesBack = !mode.empty(); try { -#ifdef _WIN32 - _putenv_s("APS5_GPU_HEAP", "1"); -#else - setenv("APS5_GPU_HEAP", "1", 1); -#endif - std::unique_ptr device; - try { - device = std::make_unique(); - } catch (const std::exception& error) { - if (std::getenv("ANYPS5_REQUIRE_VULKAN") != nullptr) throw; - std::printf("skipped, no usable Vulkan device: %s\n", error.what()); - return VulkanTestSkipped; - } + SetTestEnvironment("APS5_GPU_HEAP", "1"); + auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; if (!device->graphicsContext().descriptorHeap) { std::printf("skipped, the device has no VK_EXT_descriptor_heap\n"); return VulkanTestSkipped; } -#ifdef _WIN32 - _putenv_s("APS5_HEAP_SLOT_CAP", comesBack ? "8" : "1"); -#else - setenv("APS5_HEAP_SLOT_CAP", comesBack ? "8" : "1", 1); -#endif + SetTestEnvironment("APS5_HEAP_SLOT_CAP", comesBack ? "8" : "1"); if (comesBack) { { const auto context = device->graphicsContext(); diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index 48e106cd0b0a..d95503e136fc 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -6051,6 +6051,7 @@ void pooledBufferAddressTests() { Require(staging.Handle() == pooled, "a device-local buffer of the pooled device buffer's size and usage did not reuse its allocation"); const VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, pooled}; expected = mockGetBufferDeviceAddress(context.device, &info); + Require(expected != 0, "the mock device address of the pooled buffer is zero"); try { address = staging.DeviceAddress(); } catch (const std::exception&) { diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp index 136b7bb8802c..a1cd55a36bee 100644 --- a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp @@ -128,7 +128,6 @@ void sharedResultsChargedOnceTests() { result->heapUserWords.resize(resultWords); result->heapUserWords.shrink_to_fit(); const std::shared_ptr shared = std::move(result); - std::weak_ptr watched = shared; const auto ownBytes = AgcDriver::DriverDetail::HeapWalkEntryOwnBytes(sizedEntry(1)); const auto sharedBytes = AgcDriver::DriverDetail::HeapWalkResultBytes(*shared); HeapWalkMemo memo; diff --git a/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp index 723d1f722926..6a21e2e18c5d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp @@ -830,10 +830,7 @@ int main() { if (GpuHeapEnabled()) { const auto heapDevice = OpenVulkanTestDevice(); if (!heapDevice) return VulkanTestSkipped; - if (!DescriptorHeapEnabled()) { - std::printf("skipped, the device has no descriptor heap\n"); - return VulkanTestSkipped; - } + if (SkipWithoutDescriptorHeap()) return VulkanTestSkipped; const auto context = heapDevice->graphicsContext(); Require(BindlessHeap::For(context).DescriptorHeapMode(), "the test device did not open the descriptor heap"); residentPresentTests(context); diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index abe9138fd0b7..d707fd8ad9c4 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -8078,7 +8078,7 @@ void verifyCoherentGds() { require(std::ranges::find(decorations[gds], static_cast(spv::DecorationCoherent)) != decorations[gds].end(), "coherent GDS: the gds buffer is not Coherent"); } -void verifyCoherentBufferAccesses() { +auto recompileCoherent(const std::vector& code, std::uint32_t address, std::span capabilities, bool addressed) { using namespace ShaderRecompiler; alignas(256) static std::array input{}; alignas(256) static std::array output{}; @@ -8088,6 +8088,28 @@ void verifyCoherentBufferAccesses() { static_cast(inputAddress), static_cast((inputAddress >> 32u) & 0xffffu), 256u, 0x31016facu, static_cast(outputAddress), static_cast((outputAddress >> 32u) & 0xffffu), 256u, 0x31016facu}; const std::array extensions{"SPV_KHR_physical_storage_buffer", "SPV_KHR_8bit_storage"}; + RecompileRequest request{}; + request.shader = {ShaderStage::Compute, address, code, 0, {}}; + request.context.waveSize = 32; + request.context.userDataBaseRegister = 0; + request.context.userData = userData; + request.context.compute = ShaderComputeStageInfo{{32u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; + request.target.vulkanVersion = 0x00401000u; + request.target.spirvVersion = 0x00010300u; + request.target.subgroupSize = 32; + request.target.bdaAbiVersion = BdaAbi::Version; + request.target.supportedCapabilities = capabilities; + request.target.supportedExtensions = extensions; + request.target.fragmentShaderBarycentricEnabled = false; + request.target.gpuResolvedImages = addressed; + request.target.descriptorMemory = addressed; + request.layout.pushConstantSizeBytes = 128; + request.useCache = false; + return Recompile(request).spirv; +} + +void verifyCoherentBufferAccesses() { + using namespace ShaderRecompiler; const std::array capabilities{spv::CapabilityInt64, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess}; struct Module { std::map names; @@ -8099,22 +8121,7 @@ void verifyCoherentBufferAccesses() { std::vector code{0x34020082u}; if (invalidate) code.insert(code.end(), {0xe1c40000u, 0u}); code.insert(code.end(), {0xe0301000u | (glcLoad ? 0x4000u : 0u), 0x80000201u, 0xbf8c3f70u, 0xe0701000u | (glcStore ? 0x4000u : 0u), 0x80010201u, 0xbf810000u}); - RecompileRequest request{}; - request.shader = {ShaderStage::Compute, 0x5a000u, code, 0, {}}; - request.context.waveSize = 32; - request.context.userDataBaseRegister = 0; - request.context.userData = userData; - request.context.compute = ShaderComputeStageInfo{{32u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; - request.target.vulkanVersion = 0x00401000u; - request.target.spirvVersion = 0x00010300u; - request.target.subgroupSize = 32; - request.target.bdaAbiVersion = BdaAbi::Version; - request.target.supportedCapabilities = capabilities; - request.target.supportedExtensions = extensions; - request.target.fragmentShaderBarycentricEnabled = false; - request.layout.pushConstantSizeBytes = 128; - request.useCache = false; - const auto words = Recompile(request).spirv; + const auto words = recompileCoherent(code, 0x5a000u, capabilities, false); Module module; std::map bases; const auto base = [&](std::uint32_t pointer) { @@ -8176,14 +8183,6 @@ void verifyCoherentBufferAccesses() { void verifyAddressedCoherentBufferAccesses() { using namespace ShaderRecompiler; - alignas(256) static std::array input{}; - alignas(256) static std::array output{}; - const auto inputAddress = static_cast(reinterpret_cast(input.data())); - const auto outputAddress = static_cast(reinterpret_cast(output.data())); - const std::array userData{ - static_cast(inputAddress), static_cast((inputAddress >> 32u) & 0xffffu), 256u, 0x31016facu, - static_cast(outputAddress), static_cast((outputAddress >> 32u) & 0xffffu), 256u, 0x31016facu}; - const std::array extensions{"SPV_KHR_physical_storage_buffer", "SPV_KHR_8bit_storage"}; const std::array capabilities{spv::CapabilityInt64, spv::CapabilityInt64Atomics, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess}; struct Counts { std::uint32_t loads = 0, stores = 0, wideLoads = 0; @@ -8194,24 +8193,7 @@ void verifyAddressedCoherentBufferAccesses() { std::vector code{0x34020082u}; if (invalidate) code.insert(code.end(), {0xe1c40000u, 0u}); code.insert(code.end(), {loadOp | (glcLoad ? 0x4000u : 0u), 0x80000201u, 0xbf8c3f70u, storeOp | (glcStore ? 0x4000u : 0u), 0x80010201u, 0xbf810000u}); - RecompileRequest request{}; - request.shader = {ShaderStage::Compute, 0x5b000u, code, 0, {}}; - request.context.waveSize = 32; - request.context.userDataBaseRegister = 0; - request.context.userData = userData; - request.context.compute = ShaderComputeStageInfo{{32u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; - request.target.vulkanVersion = 0x00401000u; - request.target.spirvVersion = 0x00010300u; - request.target.subgroupSize = 32; - request.target.bdaAbiVersion = BdaAbi::Version; - request.target.supportedCapabilities = capabilities; - request.target.supportedExtensions = extensions; - request.target.fragmentShaderBarycentricEnabled = false; - request.target.gpuResolvedImages = true; - request.target.descriptorMemory = true; - request.layout.pushConstantSizeBytes = 128; - request.useCache = false; - const auto words = Recompile(request).spirv; + const auto words = recompileCoherent(code, 0x5b000u, capabilities, true); std::set wideTypes; Counts counts; for (std::size_t cursor = 5; cursor < words.size();) { diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_draw_space_reuse_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_draw_space_reuse_tests.cmake index c29fb7c03e04..826cdfc32052 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_draw_space_reuse_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_draw_space_reuse_tests.cmake @@ -1,14 +1,6 @@ if(BUILD_TESTING) - add_test(NAME agc_driver_address_draw_space_reuse_heap COMMAND agc_driver_address_draw_space_reuse_tests) - set_tests_properties(agc_driver_address_draw_space_reuse_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1" SKIP_RETURN_CODE 77 TIMEOUT 60) - if(WIN32) - set_tests_properties(agc_driver_address_draw_space_reuse_heap PROPERTIES ENVIRONMENT_MODIFICATION - "PATH=path_list_prepend:$") - endif() - add_test(NAME agc_driver_address_draw_space_reuse_heap_transitions COMMAND agc_driver_address_draw_space_reuse_tests) - set_tests_properties(agc_driver_address_draw_space_reuse_heap_transitions PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_DRAW_TRANSITIONS=1" SKIP_RETURN_CODE 77 TIMEOUT 60) - if(WIN32) - set_tests_properties(agc_driver_address_draw_space_reuse_heap_transitions PROPERTIES ENVIRONMENT_MODIFICATION - "PATH=path_list_prepend:$") - endif() + agc_add_env_test(agc_driver_address_draw_space_reuse_heap agc_driver_address_draw_space_reuse_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 TIMEOUT 60 NO_WORKING_DIRECTORY) + agc_add_env_test(agc_driver_address_draw_space_reuse_heap_transitions agc_driver_address_draw_space_reuse_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_DRAW_TRANSITIONS=1 TIMEOUT 60 NO_WORKING_DIRECTORY) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_bindless_images_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_bindless_images_tests.cmake index 41e3cbcfc15f..3892cefc3235 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_bindless_images_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_bindless_images_tests.cmake @@ -2,9 +2,6 @@ if(BUILD_TESTING) agc_add_gpu_heap_test(agc_driver_bindless_images) endif() if(BUILD_TESTING AND TARGET agc_driver_bindless_images_tests) - add_test(NAME agc_driver_bindless_images_heap COMMAND agc_driver_bindless_images_tests) - set_tests_properties(agc_driver_bindless_images_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1" SKIP_RETURN_CODE 77) - if(WIN32) - set_tests_properties(agc_driver_bindless_images_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - endif() + agc_add_env_test(agc_driver_bindless_images_heap agc_driver_bindless_images_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 NO_WORKING_DIRECTORY) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_move_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_move_tests.cmake index 59a811f328aa..401ae774dfbe 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_move_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_move_tests.cmake @@ -1,7 +1,4 @@ if(BUILD_TESTING AND TARGET agc_driver_dispatch_move_tests) - add_test(NAME agc_driver_dispatch_move_gpu_heap COMMAND agc_driver_dispatch_move_tests) - set_tests_properties(agc_driver_dispatch_move_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(agc_driver_dispatch_move_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - endif() + agc_add_env_test(agc_driver_dispatch_move_gpu_heap agc_driver_dispatch_move_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake index 10af572b6cdf..a9d4ef8d3cbb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake @@ -1,17 +1,8 @@ if(BUILD_TESTING AND TARGET agc_driver_heap_compute_sample_tests) - add_test(NAME agc_driver_heap_compute_sample_heap_pipelined COMMAND agc_driver_heap_compute_sample_tests) - set_tests_properties(agc_driver_heap_compute_sample_heap_pipelined PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_PIPELINE_DISPATCH=1;APS5_PIPELINED_DRAWS=32" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(agc_driver_heap_compute_sample_heap_pipelined PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - endif() - add_test(NAME agc_driver_heap_compute_sample_heap COMMAND agc_driver_heap_compute_sample_tests) - set_tests_properties(agc_driver_heap_compute_sample_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(agc_driver_heap_compute_sample_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - endif() - add_test(NAME agc_driver_heap_compute_sample_full_heap COMMAND agc_driver_heap_compute_sample_tests) - set_tests_properties(agc_driver_heap_compute_sample_full_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_HEAP_SLOT_CAP=4" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(agc_driver_heap_compute_sample_full_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - endif() + agc_add_env_test(agc_driver_heap_compute_sample_heap_pipelined agc_driver_heap_compute_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_PIPELINE_DISPATCH=1 APS5_PIPELINED_DRAWS=32) + agc_add_env_test(agc_driver_heap_compute_sample_heap agc_driver_heap_compute_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) + agc_add_env_test(agc_driver_heap_compute_sample_full_heap agc_driver_heap_compute_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=4) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake index 4d10febda596..c468b0a1252b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake @@ -1,21 +1,12 @@ if(BUILD_TESTING AND TARGET agc_driver_heap_draw_sample_tests) - add_test(NAME agc_driver_heap_draw_sample_heap COMMAND agc_driver_heap_draw_sample_tests) - set_tests_properties(agc_driver_heap_draw_sample_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(agc_driver_heap_draw_sample_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - endif() - add_test(NAME agc_driver_heap_draw_sample_full_heap COMMAND agc_driver_heap_draw_sample_tests) - set_tests_properties(agc_driver_heap_draw_sample_full_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_HEAP_SLOT_CAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - add_test(NAME agc_driver_heap_draw_sample_full_heap_pipelined COMMAND agc_driver_heap_draw_sample_tests) - set_tests_properties(agc_driver_heap_draw_sample_full_heap_pipelined PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1;APS5_HEAP_SLOT_CAP=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(agc_driver_heap_draw_sample_full_heap agc_driver_heap_draw_sample_full_heap_pipelined PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - endif() - add_test(NAME agc_driver_heap_draw_sample_nogpl COMMAND agc_driver_heap_draw_sample_tests) - set_tests_properties(agc_driver_heap_draw_sample_nogpl PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_GPL=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - add_test(NAME agc_driver_heap_draw_sample_nogpl_heap COMMAND agc_driver_heap_draw_sample_tests) - set_tests_properties(agc_driver_heap_draw_sample_nogpl_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_GPL=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(agc_driver_heap_draw_sample_nogpl agc_driver_heap_draw_sample_nogpl_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - endif() + agc_add_env_test(agc_driver_heap_draw_sample_heap agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) + agc_add_env_test(agc_driver_heap_draw_sample_full_heap agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=1) + agc_add_env_test(agc_driver_heap_draw_sample_full_heap_pipelined agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) + agc_add_env_test(agc_driver_heap_draw_sample_nogpl agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_NO_GPL=1) + agc_add_env_test(agc_driver_heap_draw_sample_nogpl_heap agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_NO_GPL=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake index ac40e45a2ec8..84e4a7b66241 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake @@ -6,6 +6,7 @@ target_include_directories(agc_driver_heap_slots_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/core/shader/recompiler ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} + ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR} ) target_link_libraries(agc_driver_heap_slots_tests PRIVATE @@ -19,17 +20,9 @@ configure_windows_unwind(agc_driver_heap_slots_tests) if(BUILD_TESTING) agc_add_default_test(agc_driver_heap_slots_tests) - add_test(NAME agc_driver_heap_slots_comes_back COMMAND agc_driver_heap_slots_tests comes-back) - set_tests_properties(agc_driver_heap_slots_comes_back PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(agc_driver_heap_slots_comes_back PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - endif() - foreach(agcHeapSlotsMode IN ITEMS storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release) + foreach(agcHeapSlotsMode IN ITEMS comes-back storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release) string(REPLACE "-" "_" agcHeapSlotsName "${agcHeapSlotsMode}") - add_test(NAME agc_driver_heap_slots_${agcHeapSlotsName} COMMAND agc_driver_heap_slots_tests ${agcHeapSlotsMode}) - set_tests_properties(agc_driver_heap_slots_${agcHeapSlotsName} PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(agc_driver_heap_slots_${agcHeapSlotsName} PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - endif() + agc_add_env_test(agc_driver_heap_slots_${agcHeapSlotsName} agc_driver_heap_slots_tests + ARGS ${agcHeapSlotsMode} ENV ANYPS5_NO_SHADER_CACHE=1) endforeach() endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_journal_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_journal_tests.cmake index 6eeee940c973..b4adc276eb74 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_journal_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_journal_tests.cmake @@ -1,9 +1,6 @@ target_include_directories(agc_driver_pipeline_journal_tests PRIVATE $) target_link_libraries(agc_driver_pipeline_journal_tests PRIVATE ${CMAKE_DL_LIBS}) if(BUILD_TESTING AND TARGET agc_driver_pipeline_journal_tests) - add_test(NAME agc_driver_pipeline_journal_gpu_heap COMMAND agc_driver_pipeline_journal_tests --gpu-heap) - set_tests_properties(agc_driver_pipeline_journal_gpu_heap PROPERTIES ENVIRONMENT "APS5_GPU_HEAP=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(agc_driver_pipeline_journal_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") - endif() + agc_add_env_test(agc_driver_pipeline_journal_gpu_heap agc_driver_pipeline_journal_tests + ARGS --gpu-heap ENV APS5_GPU_HEAP=1 TIMEOUT 30) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sampled_cache_budget_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sampled_cache_budget_tests.cmake index 991b402d0732..219baa1f3676 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sampled_cache_budget_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sampled_cache_budget_tests.cmake @@ -1,8 +1,8 @@ if(BUILD_TESTING) add_test(NAME agc_driver_sampled_cache_budget_memory COMMAND agc_driver_sampled_cache_budget_tests memory) set_tests_properties(agc_driver_sampled_cache_budget_memory PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77) - add_test(NAME agc_driver_sampled_cache_budget_heap_view COMMAND agc_driver_sampled_cache_budget_tests heap-view) - set_tests_properties(agc_driver_sampled_cache_budget_heap_view PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + agc_add_env_test(agc_driver_sampled_cache_budget_heap_view agc_driver_sampled_cache_budget_tests + ARGS heap-view ENV ANYPS5_NO_SHADER_CACHE=1) add_test(NAME agc_driver_sampled_cache_budget_without_storage_image_multisample COMMAND agc_driver_sampled_cache_budget_tests without-storage-image-multisample) set_tests_properties(agc_driver_sampled_cache_budget_without_storage_image_multisample PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30) add_test(NAME agc_sampled_cache_device_selection COMMAND agc_driver_sampled_cache_budget_tests device-selection-cpu) @@ -30,7 +30,7 @@ if(BUILD_TESTING) add_test(NAME agc_driver_resource_cache_collect_refusals COMMAND agc_driver_sampled_cache_budget_tests collect-refusals) set_tests_properties(agc_driver_resource_cache_storage_admission agc_driver_resource_cache_oversized_storage_admission agc_driver_resource_cache_storage_clear agc_driver_resource_cache_replaced_texture agc_driver_resource_cache_lookup_changed agc_driver_resource_cache_collect_refusals PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30) if(WIN32) - set_tests_properties(agc_driver_sampled_cache_budget_memory agc_driver_sampled_cache_budget_heap_view agc_driver_sampled_cache_budget_without_storage_image_multisample agc_driver_resource_cache_storage_admission agc_driver_resource_cache_oversized_storage_admission agc_driver_resource_cache_storage_clear agc_driver_resource_cache_replaced_texture agc_driver_resource_cache_lookup_changed agc_driver_resource_cache_collect_refusals PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(agc_driver_sampled_cache_budget_memory agc_driver_sampled_cache_budget_without_storage_image_multisample agc_driver_resource_cache_storage_admission agc_driver_resource_cache_oversized_storage_admission agc_driver_resource_cache_storage_clear agc_driver_resource_cache_replaced_texture agc_driver_resource_cache_lookup_changed agc_driver_resource_cache_collect_refusals PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_cache_budget_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_cache_budget_tests.cmake index 714d8168ebc5..f191610bf636 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_cache_budget_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_cache_budget_tests.cmake @@ -6,16 +6,8 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_storage_cache_retained_batch PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() - add_test(NAME agc_driver_storage_cache_budget_heap_slots COMMAND agc_driver_storage_cache_budget_tests --heap-slots) - set_tests_properties(agc_driver_storage_cache_budget_heap_slots PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(agc_driver_storage_cache_budget_heap_slots PROPERTIES ENVIRONMENT_MODIFICATION - "PATH=path_list_prepend:$") - endif() - add_test(NAME agc_driver_storage_cache_retained_batch_heap_slots COMMAND agc_driver_storage_cache_budget_tests --retained-batch-heap-slots) - set_tests_properties(agc_driver_storage_cache_retained_batch_heap_slots PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - if(WIN32) - set_tests_properties(agc_driver_storage_cache_retained_batch_heap_slots PROPERTIES ENVIRONMENT_MODIFICATION - "PATH=path_list_prepend:$") - endif() + agc_add_env_test(agc_driver_storage_cache_budget_heap_slots agc_driver_storage_cache_budget_tests + ARGS --heap-slots ENV ANYPS5_NO_SHADER_CACHE=1 TIMEOUT 30) + agc_add_env_test(agc_driver_storage_cache_retained_batch_heap_slots agc_driver_storage_cache_budget_tests + ARGS --retained-batch-heap-slots ENV ANYPS5_NO_SHADER_CACHE=1 TIMEOUT 30) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake index 3839b59a735b..d4bfdf002c8f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake @@ -32,18 +32,18 @@ if(BUILD_TESTING) set_tests_properties(agc_shader_table_snapshot_reuse_unmasked PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_MASKED_RESULT_MEMO=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") add_test(NAME agc_driver_image_table_vouched_lookups COMMAND agc_driver_image_table_cache_bounds_tests --vouched-lookups) set_tests_properties(agc_driver_image_table_vouched_lookups PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_WRITE_WATCH_IMPORTS=watch" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) - add_test(NAME agc_driver_image_table_atomics COMMAND agc_driver_image_table_cache_bounds_tests --atomic-table) - set_tests_properties(agc_driver_image_table_atomics PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) - add_test(NAME agc_driver_image_table_atomics_gpu_heap COMMAND agc_driver_image_table_cache_bounds_tests --atomic-table) - set_tests_properties(agc_driver_image_table_atomics_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) - add_test(NAME agc_driver_image_table_store_gpu_heap COMMAND agc_driver_image_table_cache_bounds_tests --store-table) - set_tests_properties(agc_driver_image_table_store_gpu_heap PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_VERIFY_GPU_HEAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) + agc_add_env_test(agc_driver_image_table_atomics agc_driver_image_table_cache_bounds_tests + ARGS --atomic-table ENV ANYPS5_NO_SHADER_CACHE=1 TIMEOUT 60) + agc_add_env_test(agc_driver_image_table_atomics_gpu_heap agc_driver_image_table_cache_bounds_tests + ARGS --atomic-table ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 TIMEOUT 60) + agc_add_env_test(agc_driver_image_table_store_gpu_heap agc_driver_image_table_cache_bounds_tests + ARGS --store-table ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 TIMEOUT 60) add_test(NAME agc_driver_image_table_vouch_queued_draws COMMAND agc_driver_image_table_cache_bounds_tests --queued-draws) set_tests_properties(agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) - add_test(NAME agc_driver_image_table_cache_bounds_heap_small COMMAND agc_driver_image_table_cache_bounds_tests) - set_tests_properties(agc_driver_image_table_cache_bounds_heap_small PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GPU_HEAP=1;APS5_HEAP_SLOT_CAP=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) + agc_add_env_test(agc_driver_image_table_cache_bounds_heap_small agc_driver_image_table_cache_bounds_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=1 TIMEOUT 60) if(WIN32) - set_tests_properties(agc_shader_table_snapshot_reuse agc_shader_table_snapshot_reuse_unmasked agc_driver_image_table_vouched_lookups agc_driver_image_table_vouch_queued_draws agc_driver_image_table_cache_bounds_heap_small agc_driver_image_table_atomics agc_driver_image_table_atomics_gpu_heap agc_driver_image_table_store_gpu_heap PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") + set_tests_properties(agc_shader_table_snapshot_reuse agc_shader_table_snapshot_reuse_unmasked agc_driver_image_table_vouched_lookups agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() add_test(NAME agc_shader_type_zero_image_materialization COMMAND agc_shader_memory_tests --type-zero-image-materialization) set_tests_properties(agc_shader_type_zero_image_materialization PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp index c837ff204562..f7b236bfdb40 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp @@ -357,11 +357,6 @@ void RecipeAfterSnapshotChange(Scene& scene) { Require(scene.Color() == 150, "address draw space reuse: the draw asked for a recipe did not read the guest constant"); scene.constants.Data()[CapturedOffset] ^= 0xffu; const auto before = Builds(); - if (recipe != nullptr) { - const bool recorded = scene.DrawFromRecipe(recipe) == AgcDriver::RecipeOutcome::Recorded; - const auto color = scene.Color(); - Require(!recorded, "address draw space reuse: a draw recipe made from a build whose reuse retakes its address space recorded the draw (read " + std::to_string(color) + ") after a snapshot inside that space changed, with " + std::to_string(Builds() - before) + " builds, where the draw path builds anew"); - } const auto color = scene.DrawnColor(); const auto built = Builds() - before; scene.constants.Data()[CapturedOffset] ^= 0xffu; @@ -497,11 +492,7 @@ void Disabled(Scene& scene) { void LimitPinWait() { if (std::getenv("APS5_PIN_WAIT_MS") != nullptr) return; const auto wait = std::to_string(PinWaitMs); -#ifdef _WIN32 - _putenv_s("APS5_PIN_WAIT_MS", wait.c_str()); -#else - setenv("APS5_PIN_WAIT_MS", wait.c_str(), 1); -#endif + SetTestEnvironment("APS5_PIN_WAIT_MS", wait.c_str()); } using Case = void (*)(Scene&); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp index 598ec18ba216..d9e3e2aa3178 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp @@ -4,6 +4,7 @@ #include "prx/libSceAgcDriver/Submit/include/Acb.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "Recompiler.hpp" +#include "HeapSampleKernel.hpp" #include "VulkanTestDevice.hpp" #include #include @@ -24,12 +25,8 @@ void Require(bool condition, const std::string& message) { if (!condition) throw std::runtime_error(message); } -constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; constexpr std::array OtherTexel{0xf0u, 0x20u, 0x00u, 0x40u}; -alignas(256) constexpr std::array SampleCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, - 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; - alignas(256) constexpr std::array LdsSampleCode{ 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0x7e080280u, 0xbf8c0000u, 0xd8340000u, 0x00000004u, 0xbf8c0000u, 0xd8d80000u, 0x00000004u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u, 0xbf810000u}; @@ -58,26 +55,6 @@ void Registered(Header& header, const std::uint32_t* code, std::size_t bytes) { AgcDriverRegisterShader_nid_postfix(&header.shader); } -std::uint32_t Low(const void* pointer) { - return static_cast(reinterpret_cast(pointer)); -} - -std::uint32_t High(const void* pointer) { - return static_cast(static_cast(reinterpret_cast(pointer)) >> 32u); -} - -std::array Image(const void* pointer) { - const auto address = static_cast(reinterpret_cast(pointer)); - return {static_cast(address >> 8u), - static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), - 3u << 14u, - 0xfacu | (9u << 28u), - 0u, - 0u, - 0u, - 0u}; -} - void SetShaderRegister(std::vector& words, std::uint32_t offset, std::uint32_t value) { words.insert(words.end(), {0xc0017600u, offset, value}); } @@ -89,11 +66,7 @@ void Sample(std::vector& words, const void* image, float* output) for (const std::uint32_t offset : {0x207u, 0x208u, 0x209u}) SetShaderRegister(words, offset, 1); SetShaderRegister(words, 0x212, 0); SetShaderRegister(words, 0x213, 16u << 1u); - std::vector userData; - const auto descriptor = Image(image); - userData.insert(userData.end(), descriptor.begin(), descriptor.end()); - userData.insert(userData.end(), {0u, 0u, 0u, 0u}); - userData.insert(userData.end(), {Low(output), High(output) & 0xffffu, static_cast(4u * sizeof(float)), 0x31016facu}); + const auto userData = SampleUserData(image, output); std::uint32_t offset = 0x240; for (const auto value : userData) SetShaderRegister(words, offset++, value); words.insert(words.end(), {0xc0031500u, 1, 1, 1, 0x8041u}); @@ -105,20 +78,6 @@ void Submit(std::vector& words) { AgcDriverWaitIdle_nid_postfix(); } -void RequireSampled(const float* output, const std::array& expected, const std::string& what, bool heap) { - for (std::size_t channel = 0; channel < 4; ++channel) { - const float wanted = static_cast(expected[channel]) / 255.0f; - Require(std::fabs(output[channel] - wanted) < 1e-6f, what + ": channel " + std::to_string(channel) + " is " + - std::to_string(output[channel]) + ", expected " + std::to_string(wanted) + - (heap ? " through the heap" : "")); - } -} - -void Fill(std::array& memory, const std::array& texel) { - for (std::size_t offset = 0; offset < memory.size(); offset += texel.size()) - std::memcpy(memory.data() + offset, texel.data(), texel.size()); -} - void DriverSample(bool heap) { Outputs[0].fill(-1.0f); const auto before = AgcDriver::Graphics::HeapComputeStages(); @@ -126,7 +85,7 @@ void DriverSample(bool heap) { Sample(words, TextureMemory.data(), Outputs[0].data()); Sample(words, TextureMemory.data(), Outputs[0].data()); Submit(words); - RequireSampled(Outputs[0].data(), Texel, "the sampled texture", heap); + RequireSampled(Outputs[0].data(), SampleTexel, "the sampled texture", heap); if (heap) Require(AgcDriver::Graphics::HeapComputeStages() > before, "the heap did not take the sampling compute stage"); } @@ -136,32 +95,14 @@ void FullHeapSample() { for (std::size_t index = 0; index < FullHeapTextures; ++index) Sample(words, ManyTextures[index].data(), Outputs[0].data() + 4u * index); Submit(words); for (std::size_t index = 0; index < FullHeapTextures; ++index) - RequireSampled(Outputs[0].data() + 4u * index, Texel, "texture " + std::to_string(index) + " of a heap with too few image slots", true); + RequireSampled(Outputs[0].data() + 4u * index, SampleTexel, "texture " + std::to_string(index) + " of a heap with too few image slots", true); Require(AgcDriver::Graphics::BindlessHeap::NearlyFull(), "the capped heap never ran short of image slots"); } -ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const void* image, float* output, - std::span code = SampleCode, std::uint32_t ldsDwords = 0u) { - std::vector userData; - const auto descriptor = Image(image); - userData.insert(userData.end(), descriptor.begin(), descriptor.end()); - userData.insert(userData.end(), {0u, 0u, 0u, 0u}); - userData.insert(userData.end(), {Low(output), High(output) & 0xffffu, static_cast(4u * sizeof(float)), 0x31016facu}); - const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; - const ShaderRecompiler::ShaderComputeStageInfo compute{{1u, 1u, 1u}, ldsDwords, {false, false, false}, false, 1u}; - ShaderRecompiler::RecompileRequest request{ - {ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, - {32u, 0u, userData, compute, std::nullopt, std::nullopt, memory}, - device.ComputeTarget(32u), - {0u, 0u, 0u, 128u}}; - request.useCache = false; - return ShaderRecompiler::Recompile(request); -} - void DeviceSample(AgcDriver::VulkanDevice& device, bool heap) { for (std::size_t index = 1; index < Outputs.size(); ++index) Outputs[index].fill(-1.0f); - const auto first = Compile(device, OtherTextureMemory.data(), Outputs[1].data()); - const auto second = Compile(device, TextureMemory.data(), Outputs[2].data()); + const auto first = CompileSampleKernel(device, OtherTextureMemory.data(), Outputs[1].data(), false); + const auto second = CompileSampleKernel(device, TextureMemory.data(), Outputs[2].data(), false); Require(first.gpuResolvedImages == heap && second.gpuResolvedImages == heap, heap ? "a sampling compute stage is not GPU mode" : "a compute stage took the heap without it"); const auto before = AgcDriver::Graphics::HeapComputeStages(); @@ -170,25 +111,26 @@ void DeviceSample(AgcDriver::VulkanDevice& device, bool heap) { device.Dispatch(second, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); device.WaitIdle(); RequireSampled(Outputs[1].data(), OtherTexel, "the first of two textures in one batch", heap); - RequireSampled(Outputs[2].data(), Texel, "the second of two textures in one batch", heap); - if (heap) Require(AgcDriver::Graphics::HeapComputeStages() >= before + 2u, "the heap did not take both sampling compute stages"); - if (heap) + RequireSampled(Outputs[2].data(), SampleTexel, "the second of two textures in one batch", heap); + if (heap) { + Require(AgcDriver::Graphics::HeapComputeStages() >= before + 2u, "the heap did not take both sampling compute stages"); Require(AgcDriver::Graphics::DataAddressPushes() >= pushesBefore + 2u, "a heap dispatch did not read its shader data through pushed addresses"); - const auto again = Compile(device, TextureMemory.data(), Outputs[3].data()); + } + const auto again = CompileSampleKernel(device, TextureMemory.data(), Outputs[3].data(), false); device.Dispatch(again, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); device.WaitIdle(); - RequireSampled(Outputs[3].data(), Texel, "the first texture again in a later batch", heap); + RequireSampled(Outputs[3].data(), SampleTexel, "the first texture again in a later batch", heap); Outputs[1].fill(-1.0f); - const auto lds = Compile(device, TextureMemory.data(), Outputs[1].data(), LdsSampleCode, - (device.ComputeTarget(32u).maxWorkgroupSharedMemoryBytes + 4096u) / 4u); + const auto lds = CompileSampleKernel(device, TextureMemory.data(), Outputs[1].data(), false, LdsSampleCode, + (device.ComputeTarget(32u).maxWorkgroupSharedMemoryBytes + 4096u) / 4u); Require(lds.workgroupMemoryDwords != 0u && lds.gpuResolvedImages == heap, "the LDS sampling stage did not get workgroup memory in the expected mode"); const auto heapPipelines = device.DescriptorHeapComputePipelines(); device.Dispatch(lds, 1u, 1u, 1u, {}, reinterpret_cast(LdsSampleCode.data())); device.WaitIdle(); - RequireSampled(Outputs[1].data(), Texel, "the texture sampled through workgroup memory", heap); - if (heap && heapPipelines != 0u) + RequireSampled(Outputs[1].data(), SampleTexel, "the texture sampled through workgroup memory", heap); + if (heap) Require(device.DescriptorHeapComputePipelines() > heapPipelines, "the LDS sampling stage did not take the descriptor heap"); } @@ -201,14 +143,10 @@ int main() { if (!device) return VulkanTestSkipped; } const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; - if (heap && !AgcDriver::Graphics::DescriptorHeapEnabled()) { - std::cout - << "skipped, the device lacks VK_EXT_descriptor_heap, or the maintenance5, slot room and push data the GPU heap needs with it, so APS5_GPU_HEAP has no heap to dispatch through\n"; - return VulkanTestSkipped; - } - Fill(TextureMemory, Texel); - Fill(OtherTextureMemory, OtherTexel); - for (auto& texture : ManyTextures) Fill(texture, Texel); + if (heap && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; + FillTexels(TextureMemory, SampleTexel); + FillTexels(OtherTextureMemory, OtherTexel); + for (auto& texture : ManyTextures) FillTexels(texture, SampleTexel); Registered(SampleHeader, SampleCode.data(), sizeof(SampleCode)); if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) { FullHeapSample(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index d68fe30067aa..28faa160a936 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -152,59 +152,44 @@ const char* TakenWhat(Mode mode, bool buffer) { return ""; } +std::array ImageDescriptor(const void* memory) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u}; +} + +std::array BufferDescriptor(const void* memory, std::size_t bytes) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), static_cast(bytes), + 0xfacu}; +} + std::vector Draw(const std::uint32_t* pixelCode, Mode mode, const std::uint32_t* vertexCode = nullptr) { const bool vertexSampling = mode == Mode::Vertex || mode == Mode::VertexTable; const auto vertex = reinterpret_cast(vertexCode != nullptr ? vertexCode : VertexProgram(mode)); const auto pixel = reinterpret_cast(pixelCode); const auto color = reinterpret_cast(ColorMemory.data()); - const auto texture = static_cast(reinterpret_cast(TextureMemory.data())); - const auto bufferAddress = static_cast(reinterpret_cast(BufferMemory.data() + 1)); - const auto storage = static_cast(reinterpret_cast(StorageMemory.data())); - const std::array descriptors{static_cast(texture >> 8u), - static_cast((texture >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), - 3u << 14u, - 0xfacu | (9u << 28u), - 0u, - 0u, - 0u, - 0u, - 0u, - 0u, - 0u, - 0u, - static_cast(bufferAddress), - static_cast((bufferAddress >> 32u) & 0xffffu), - static_cast(sizeof(BufferMemory) - sizeof(float)), - 0xfacu, - static_cast(storage >> 8u), - static_cast((storage >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), - 3u << 14u, - 0xfacu | (9u << 28u), - 0u, - 0u, - 0u, - 0u}; + std::array descriptors{}; + const auto textureImage = ImageDescriptor(TextureMemory.data()); + const auto bufferDescriptor = BufferDescriptor(BufferMemory.data() + 1, sizeof(BufferMemory) - sizeof(float)); + const auto storageImage = ImageDescriptor(StorageMemory.data()); + std::copy(textureImage.begin(), textureImage.end(), descriptors.begin()); + std::copy(bufferDescriptor.begin(), bufferDescriptor.end(), descriptors.begin() + 12); + std::copy(storageImage.begin(), storageImage.end(), descriptors.begin() + 16); const auto userWords = PixelUserWords(mode, vertexSampling); - const auto bufferWords = [](const void* pointer, std::uint32_t bytes) { - const auto address = static_cast(reinterpret_cast(pointer)); - return std::array{static_cast(address), static_cast((address >> 32u) & 0xffffu), - bytes, 0xfacu}; - }; - const auto other = static_cast(reinterpret_cast(OtherTextureMemory.data())); - const std::array otherImage{static_cast(other >> 8u), - static_cast((other >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), - 3u << 14u, - 0xfacu | (9u << 28u), - 0u, - 0u, - 0u, - 0u}; + const auto otherImage = ImageDescriptor(OtherTextureMemory.data()); std::copy(otherImage.begin(), otherImage.end(), TableMemory.begin()); std::copy(descriptors.begin(), descriptors.begin() + 8, TableMemory.begin() + 8); MaterialMemory = {1u, 0u, 0u, 0u}; std::array tableWords{}; - const auto table = bufferWords(TableMemory.data(), sizeof(TableMemory)); - const auto material = bufferWords(MaterialMemory.data(), sizeof(MaterialMemory)); + const auto table = BufferDescriptor(TableMemory.data(), sizeof(TableMemory)); + const auto material = BufferDescriptor(MaterialMemory.data(), sizeof(MaterialMemory)); std::copy(table.begin(), table.end(), tableWords.begin()); std::copy(material.begin(), material.end(), tableWords.begin() + 8); const std::vector> context{ @@ -301,7 +286,7 @@ std::vector Draw(const std::uint32_t* pixelCode, Mode mode, const Append(commands, 0x76, {0x00cu + 13u, static_cast(second >> 32u)}); } if (mode == Mode::MovedBuffer) { - const auto moved = bufferWords(BufferMemory.data() + 3, static_cast(sizeof(BufferMemory) - 3 * sizeof(float))); + const auto moved = BufferDescriptor(BufferMemory.data() + 3, sizeof(BufferMemory) - 3 * sizeof(float)); for (std::uint32_t index = 0; index < 4u; ++index) Append(commands, 0x76, {0x00cu + 12u + index, moved[index]}); } if (mode == Mode::MovedTexture) { @@ -386,20 +371,15 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { std::to_string(StorageMemory[channel]) + ", expected the sampled " + std::to_string(Texel[channel]) + (heap ? " through the heap" : "")); } - if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) return; - const bool descriptorMemory = AgcDriver::Graphics::DescriptorHeapEnabled(); - if (heap && descriptorMemory && (mode == Mode::Vertex || mode == Mode::VertexTable)) + if (!heap || std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) return; + if (mode == Mode::Vertex || mode == Mode::VertexTable) Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, "the heap did not take the sampling vertex stage with descriptor memory"); - else if (heap && (mode == Mode::Vertex || mode == Mode::VertexTable)) - Require(AgcDriver::DriverDetail::HeapStagesTaken() == takenBefore, - "the heap took a vertex stage whose constants are read on the CPU"); - else if (heap) + else Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, std::string("the heap did not take the fragment stage") + TakenWhat(mode, buffer)); - if (heap && descriptorMemory) - Require(AgcDriver::Graphics::DataAddressPushes() > pushesBefore, - "the heap stages did not read their shader data through pushed addresses"); + Require(AgcDriver::Graphics::DataAddressPushes() > pushesBefore, + "the heap stages did not read their shader data through pushed addresses"); } void MixedDrawTakesThePerDrawPath() { @@ -457,45 +437,28 @@ void MixedDrawTakesThePerDrawPath() { } int main() { -#ifdef _WIN32 - _putenv_s("APS5_EAGER_WRITEBACK", "1"); -#else - setenv("APS5_EAGER_WRITEBACK", "1", 1); -#endif + SetTestEnvironment("APS5_EAGER_WRITEBACK", "1"); try { { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; } const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; - if (heap && !AgcDriver::Graphics::DescriptorHeapEnabled()) { - std::cout - << "skipped, the device lacks VK_EXT_descriptor_heap, or the maintenance5, slot room and push data the GPU heap needs with it, so APS5_GPU_HEAP has no heap to draw through\n"; - return VulkanTestSkipped; - } + if (heap && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; { GuestAllocations::Mutation mutation; mutation.Add(StorageMemory.data(), StorageMemory.size(), true, true, true); mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); } - DrawSamplesTheTexture(heap, Mode::Texture); - DrawSamplesTheTexture(heap, Mode::Buffer); - DrawSamplesTheTexture(heap, Mode::Storage); - DrawSamplesTheTexture(heap, Mode::Gds); - DrawSamplesTheTexture(heap, Mode::Vertex); - DrawSamplesTheTexture(heap, Mode::Bda); - DrawSamplesTheTexture(heap, Mode::Table); - DrawSamplesTheTexture(heap, Mode::VertexTable); - DrawSamplesTheTexture(heap, Mode::MovedBuffer); - DrawSamplesTheTexture(heap, Mode::MovedTexture); - DrawSamplesTheTexture(heap, Mode::PixelLds); - DrawSamplesTheTexture(heap, Mode::Texture); - if (heap && AgcDriver::Graphics::DescriptorHeapEnabled() && std::getenv("APS5_HEAP_SLOT_CAP") == nullptr) - MixedDrawTakesThePerDrawPath(); - if (heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) + for (const auto mode : {Mode::Texture, Mode::Buffer, Mode::Storage, Mode::Gds, Mode::Vertex, Mode::Bda, Mode::Table, Mode::VertexTable, + Mode::MovedBuffer, Mode::MovedTexture, Mode::PixelLds, Mode::Texture}) + DrawSamplesTheTexture(heap, mode); + const bool capped = heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr; + if (heap && !capped) MixedDrawTakesThePerDrawPath(); + if (capped) Require(AgcDriver::DriverDetail::HeapRefused(), "a draw found the capped heap full and the heap was not refused"); AgcDriverShutdown_nid_postfix(); - if (heap && AgcDriver::Graphics::DescriptorHeapEnabled() && std::getenv("APS5_HEAP_SLOT_CAP") == nullptr) + if (heap && !capped) Require(AgcDriver::Graphics::EmptyResourceSets() != 0, "no heap draw bound without a per-draw resource set"); std::cout << "A sampled texture reached the drawn pixels" << (heap ? " through the heap" : "") << '\n'; return 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapSampleKernel.hpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapSampleKernel.hpp new file mode 100644 index 000000000000..f256baf2b6c6 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapSampleKernel.hpp @@ -0,0 +1,69 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_TESTS_EXECUTION_HEAPSAMPLEKERNEL_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_TESTS_EXECUTION_HEAPSAMPLEKERNEL_HPP + +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +alignas(256) inline constexpr std::array SampleCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; +inline constexpr std::array SampleTexel{0x10u, 0x80u, 0xc0u, 0xffu}; + +inline std::array SampleUserData(const void* image, const float* output) { + const auto imageAddress = static_cast(reinterpret_cast(image)); + const auto outputAddress = static_cast(reinterpret_cast(output)); + return {static_cast(imageAddress >> 8u), + static_cast((imageAddress >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u, + 0u, + 0u, + 0u, + 0u, + static_cast(outputAddress), + static_cast(outputAddress >> 32u) & 0xffffu, + static_cast(4u * sizeof(float)), + 0x31016facu}; +} + +inline void FillTexels(std::span memory, const std::array& texel) { + for (std::size_t offset = 0; offset < memory.size(); offset += texel.size()) std::memcpy(memory.data() + offset, texel.data(), texel.size()); +} + +inline void RequireSampled(const float* output, const std::array& expected, const std::string& what, bool heap = false) { + for (std::size_t channel = 0; channel < 4; ++channel) { + const float wanted = static_cast(expected[channel]) / 255.0f; + if (!(std::fabs(output[channel] - wanted) < 1e-6f)) + throw std::runtime_error(what + ": channel " + std::to_string(channel) + " is " + std::to_string(output[channel]) + ", expected " + + std::to_string(wanted) + (heap ? " through the heap" : "")); + } +} + +inline ShaderRecompiler::RecompileResult CompileSampleKernel(AgcDriver::VulkanDevice& device, const void* image, const float* output, + bool useCache = true, std::span code = SampleCode, + std::uint32_t ldsDwords = 0u) { + const auto userData = SampleUserData(image, output); + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{1u, 1u, 1u}, ldsDwords, {false, false, false}, false, 1u}; + ShaderRecompiler::RecompileRequest request{ + {ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, + {32u, 0u, userData, compute, std::nullopt, std::nullopt, memory}, + device.ComputeTarget(32u), + {0u, 0u, 0u, 128u}}; + request.useCache = useCache; + return ShaderRecompiler::Recompile(request); +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp index e82efe809341..e4f7b17703ef 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp @@ -205,20 +205,11 @@ void RefreshAfterOriginalDestroyed(const AgcDriver::VulkanDevice& device, const } int main() { -#ifdef _WIN32 - _putenv_s("APS5_GPU_HEAP", "1"); - _putenv_s("APS5_VERIFY_GPU_HEAP", "1"); -#else - setenv("APS5_GPU_HEAP", "1", 1); - setenv("APS5_VERIFY_GPU_HEAP", "1", 1); -#endif + SetTestEnvironment("APS5_GPU_HEAP", "1"); + SetTestEnvironment("APS5_VERIFY_GPU_HEAP", "1"); try { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; - if (!AgcDriver::Graphics::DescriptorHeapEnabled()) { - std::cout << "skipped, the device lacks VK_EXT_descriptor_heap, or the maintenance5, slot room and push data the GPU heap needs with it\n"; - return VulkanTestSkipped; - } GuestBlock block(BlockBytes, true); GuestBlock surfaces(SurfaceBlockBytes, false); Prepare(block, surfaces); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp index b9808d38c1a9..1873494e7f0c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp @@ -373,14 +373,14 @@ void VouchedLookups(const GuestBlock& block) { std::uint32_t AtomicStart(std::uint32_t texel) { return texel * 7u + 3u; } -void AtomicTable(const GuestBlock& block) { - std::memcpy(block.Bytes(AtomicKernelOffset), AtomicTableCode.data(), sizeof(AtomicTableCode)); +template +void PrepareAtomicRecords(const GuestBlock& block, const void* kernel, std::size_t kernelBytes, std::uint32_t format, std::size_t surfaceBytes, FillSurface&& fillSurface) { + std::memcpy(block.Bytes(AtomicKernelOffset), kernel, kernelBytes); for (std::uint32_t record = 0; record < AtomicRecords; ++record) { - const auto surface = TexturesOffset + static_cast(record) * AtomicSurfaceBytes; - auto* texels = reinterpret_cast(block.Bytes(surface)); - for (std::uint32_t texel = 0; texel < AtomicWidth; ++texel) texels[texel] = AtomicStart(texel) + record * 1000u; + const auto surface = TexturesOffset + static_cast(record) * surfaceBytes; + fillSurface(record, block.Bytes(surface)); const auto address = block.At(surface); - const std::array words{static_cast(address >> 8u), static_cast((address >> 40u) & 0xffu) | (Format32UInt << 20u) | (((AtomicWidth - 1u) & 3u) << 30u), (AtomicWidth - 1u) >> 2u, 0xfacu | (Type2D << 28u), 0u, 0u, 0u, 0u}; + const std::array words{static_cast(address >> 8u), static_cast((address >> 40u) & 0xffu) | (format << 20u) | (((AtomicWidth - 1u) & 3u) << 30u), (AtomicWidth - 1u) >> 2u, 0xfacu | (Type2D << 28u), 0u, 0u, 0u, 0u}; std::memcpy(block.Bytes(HeapOffset + static_cast(record) * Stride), words.data(), sizeof(words)); } auto* srt = reinterpret_cast(block.Bytes(SrtOffset)); @@ -389,6 +389,13 @@ void AtomicTable(const GuestBlock& block) { const auto output = V(block.At(OutputOffset), 0u, 4096u); std::copy(heap.begin(), heap.end(), srt); std::copy(output.begin(), output.end(), srt + 12); +} + +void AtomicTable(const GuestBlock& block) { + PrepareAtomicRecords(block, AtomicTableCode.data(), sizeof(AtomicTableCode), Format32UInt, AtomicSurfaceBytes, [](std::uint32_t record, std::uint8_t* surface) { + auto* texels = reinterpret_cast(surface); + for (std::uint32_t texel = 0; texel < AtomicWidth; ++texel) texels[texel] = AtomicStart(texel) + record * 1000u; + }); const auto heapStages = AgcDriver::Graphics::HeapComputeStages(); for (std::uint32_t dispatch = 0; dispatch < 2; ++dispatch) { std::memset(block.Bytes(OutputOffset), 0xee, AtomicWidth * 4u); @@ -405,20 +412,8 @@ void AtomicTable(const GuestBlock& block) { } bool StoreTable(const GuestBlock& block) { - std::memcpy(block.Bytes(AtomicKernelOffset), StoreTableCode.data(), sizeof(StoreTableCode)); - for (std::uint32_t record = 0; record < AtomicRecords; ++record) { - const auto surface = TexturesOffset + static_cast(record) * StoreSurfaceBytes; - std::memset(block.Bytes(surface), 0, StoreSurfaceBytes); - const auto address = block.At(surface); - const std::array words{static_cast(address >> 8u), static_cast((address >> 40u) & 0xffu) | (Format16x4Float << 20u) | (((AtomicWidth - 1u) & 3u) << 30u), (AtomicWidth - 1u) >> 2u, 0xfacu | (Type2D << 28u), 0u, 0u, 0u, 0u}; - std::memcpy(block.Bytes(HeapOffset + static_cast(record) * Stride), words.data(), sizeof(words)); - } - auto* srt = reinterpret_cast(block.Bytes(SrtOffset)); - std::fill(srt, srt + SrtBytes / 4u, 0u); - const auto heap = V(block.At(HeapOffset), Stride, AtomicRecords); - const auto output = V(block.At(OutputOffset), 0u, 4096u); - std::copy(heap.begin(), heap.end(), srt); - std::copy(output.begin(), output.end(), srt + 12); + PrepareAtomicRecords(block, StoreTableCode.data(), sizeof(StoreTableCode), Format16x4Float, StoreSurfaceBytes, + [](std::uint32_t, std::uint8_t* surface) { std::memset(surface, 0, StoreSurfaceBytes); }); const auto heapStages = AgcDriver::Graphics::HeapComputeStages(); Dispatch(block, 0, AtomicKernelOffset); if (!AgcDriver::Graphics::DescriptorHeapEnabled()) { @@ -433,7 +428,7 @@ bool StoreTable(const GuestBlock& block) { static_cast(texels[texel]), static_cast(StoredTexel)); Require(texels[texel] == StoredTexel, text); } - if (AgcDriver::Graphics::DescriptorHeapEnabled()) Require(AgcDriver::Graphics::HeapComputeStages() > heapStages, "image table store: the dispatch did not take the descriptor heap"); + Require(AgcDriver::Graphics::HeapComputeStages() > heapStages, "image table store: the dispatch did not take the descriptor heap"); std::puts("image table store passed"); return true; } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp index 3fbf87df0e83..0d0224c87856 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleRetirement.cpp @@ -579,7 +579,7 @@ class Run { resource.format = 60; bool refused = false; try { - MultisampleTargetStorageView(context, resource).view; + MultisampleTargetStorageView(context, resource); } catch (const std::exception&) { refused = true; } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp index fe2c7ef236d7..6d81bcf71743 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PipelineJournal.cpp @@ -16,6 +16,7 @@ #include "../NarrowConstantStoreFixture.hpp" #include "Recompiler.hpp" #include "Optimization/ResourceProgram.hpp" +#include "HeapSampleKernel.hpp" #include "VulkanTestDevice.hpp" #ifdef _WIN32 #ifndef NOMINMAX @@ -306,43 +307,22 @@ Totals Snapshot() { return {AgcDriver::Graphics::PipelineJournalTotals(), AgcDriver::Graphics::PipelineStoreTotals()}; } -alignas(256) constexpr std::array SampleCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; -constexpr std::array SampleTexel{0x10u, 0x80u, 0xc0u, 0xffu}; alignas(256) std::array SampleTexture{}; alignas(4096) std::array SampleOutput{}; -ShaderRecompiler::RecompileResult CompileSample(AgcDriver::VulkanDevice& device) { - using namespace ShaderRecompiler; - const auto image = static_cast(reinterpret_cast(SampleTexture.data())); - const auto output = static_cast(reinterpret_cast(SampleOutput.data())); - const std::array userData{ - static_cast(image >> 8u), static_cast((image >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), 3u << 14u, 0xfacu | (9u << 28u), 0u, 0u, 0u, 0u, - 0u, 0u, 0u, 0u, - static_cast(output), static_cast(output >> 32u) & 0xffffu, static_cast(4u * sizeof(float)), 0x31016facu, - }; - const std::span code(SampleCode); - const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; - const ShaderComputeStageInfo compute{{1u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; - RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, memory}, device.ComputeTarget(32u), {0u, 0u, 0u, 128u}}; - return Recompile(request); -} - void DispatchSample(AgcDriver::VulkanDevice& device, const char* what) { SampleOutput.fill(-1.0f); - const auto result = CompileSample(device); + const auto result = CompileSampleKernel(device, SampleTexture.data(), SampleOutput.data()); Require(result.gpuResolvedImages, std::string(what) + ": the sampling compute stage is not GPU mode"); const auto before = AgcDriver::Graphics::HeapComputeStages(); device.Dispatch(result, 1u, 1u, 1u, {}, reinterpret_cast(SampleCode.data())); device.WaitIdle(); Require(AgcDriver::Graphics::HeapComputeStages() > before, std::string(what) + ": the heap did not take the sampling compute stage"); - for (std::size_t channel = 0; channel < SampleTexel.size(); ++channel) { - const float wanted = static_cast(SampleTexel[channel]) / 255.0f; - Require(std::fabs(SampleOutput[channel] - wanted) < 1e-6f, std::string(what) + ": channel " + std::to_string(channel) + " is " + std::to_string(SampleOutput[channel]) + ", expected " + std::to_string(wanted)); - } + RequireSampled(SampleOutput.data(), SampleTexel, what); } void HeapJournalTests() { - for (std::size_t offset = 0; offset < SampleTexture.size(); offset += SampleTexel.size()) std::memcpy(SampleTexture.data() + offset, SampleTexel.data(), SampleTexel.size()); + FillTexels(SampleTexture, SampleTexel); { const auto device = OpenVulkanTestDevice(); Require(device != nullptr, "the first device is required once the second opened"); @@ -837,10 +817,7 @@ int main(int argc, char** argv) { return 0; } if (argc >= 2 && std::string(argv[1]) == "--gpu-heap") { - if (AgcDriver::Graphics::GpuHeapEnabled() && !AgcDriver::Graphics::DescriptorHeapEnabled()) { - std::puts("skipped, the device lacks VK_EXT_descriptor_heap, or the maintenance5, slot room and push data the GPU heap needs with it, so no compute stage can run in GPU mode to record"); - return VulkanTestSkipped; - } + if (AgcDriver::Graphics::GpuHeapEnabled() && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; HeapJournalTests(); std::puts("pipeline journal record and replay of a GPU-mode compute stage passed"); return 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp index 6d2ca20ecc93..dff3e519982b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp @@ -1368,19 +1368,9 @@ int main(int argc, char** argv) { setenv("APS5_TEMPLATE_AUDIT_MS", "250", 0); #endif if (mode == "heap-view") { -#ifdef _WIN32 - _putenv_s("APS5_GPU_HEAP", "1"); -#else - setenv("APS5_GPU_HEAP", "1", 1); -#endif - std::unique_ptr heapDevice; - try { - heapDevice = std::make_unique(); - } catch (const std::exception& error) { - if (std::getenv("ANYPS5_REQUIRE_VULKAN") != nullptr) throw; - std::printf("skipped, no usable Vulkan device: %s\n", error.what()); - return VulkanTestSkipped; - } + SetTestEnvironment("APS5_GPU_HEAP", "1"); + auto heapDevice = OpenVulkanTestDevice(); + if (!heapDevice) return VulkanTestSkipped; if (!heapDevice->graphicsContext().descriptorHeap) { std::puts("skipped, the device has no VK_EXT_descriptor_heap"); return VulkanTestSkipped; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp index 8ad29aead3cf..162fa7849c14 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StorageCacheBudget.cpp @@ -110,6 +110,12 @@ std::shared_ptr Store(AgcDriver::VulkanDevice& device, std::uint return heapSlotted(device, address, StorageTexture::FindLive(address, SurfaceBytes)); } +bool LacksHeapSlots(AgcDriver::VulkanDevice& device) { + if (!heapSlots || device.graphicsContext().descriptorHeap) return false; + std::puts("skipped, the device has no VK_EXT_descriptor_heap"); + return true; +} + int RetainedBatch() { #ifdef _WIN32 Require(_putenv_s("APS5_TEXTURE_CACHE_MIB", "32") == 0, "cannot set the test cache budget"); @@ -120,10 +126,7 @@ int RetainedBatch() { #endif const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; - if (heapSlots && !device->graphicsContext().descriptorHeap) { - std::puts("skipped, the device has no VK_EXT_descriptor_heap"); - return VulkanTestSkipped; - } + if (LacksHeapSlots(*device)) return VulkanTestSkipped; std::vector storage((SurfaceBytes + MaxSurfaces * Stride + Stride) / 4u, 0u); auto* texels = reinterpret_cast((reinterpret_cast(storage.data()) + Stride - 1u) & ~std::uintptr_t{Stride - 1u}); const auto base = static_cast(reinterpret_cast(texels)); @@ -172,11 +175,7 @@ int main(int argc, char** argv) { try { const std::string mode = argc == 2 ? argv[1] : ""; heapSlots = mode == "--heap-slots" || mode == "--retained-batch-heap-slots"; -#ifdef _WIN32 - if (heapSlots) Require(_putenv_s("APS5_GPU_HEAP", "1") == 0, "cannot enable the GPU heap"); -#else - if (heapSlots) Require(setenv("APS5_GPU_HEAP", "1", 1) == 0, "cannot enable the GPU heap"); -#endif + if (heapSlots) Require(SetTestEnvironment("APS5_GPU_HEAP", "1") == 0, "cannot enable the GPU heap"); if (mode == "--retained-batch" || mode == "--retained-batch-heap-slots") return RetainedBatch(); #ifdef _WIN32 Require(_putenv_s("APS5_TEXTURE_CACHE_MIB", "32") == 0, "cannot set the test cache budget"); @@ -185,10 +184,7 @@ int main(int argc, char** argv) { #endif const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; - if (heapSlots && !device->graphicsContext().descriptorHeap) { - std::puts("skipped, the device has no VK_EXT_descriptor_heap"); - return VulkanTestSkipped; - } + if (LacksHeapSlots(*device)) return VulkanTestSkipped; const auto budget = TestBudget; std::vector storage((SurfaceBytes + MaxSurfaces * Stride + Stride) / 4u, 0u); auto* texels = reinterpret_cast((reinterpret_cast(storage.data()) + Stride - 1u) & ~std::uintptr_t{Stride - 1u}); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/VulkanTestDevice.hpp b/core/libs/prx/libSceAgcDriver/tests/execution/VulkanTestDevice.hpp index 4cbf73216610..9eb435e06832 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/VulkanTestDevice.hpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/VulkanTestDevice.hpp @@ -17,9 +17,25 @@ inline bool TargetHasCapability(const ShaderRecompiler::SpirvTarget& target, spv return std::find(capabilities.begin(), capabilities.end(), static_cast(capability)) != capabilities.end(); } +inline int SetTestEnvironment(const char* name, const char* value) { +#ifdef _WIN32 + return _putenv_s(name, value); +#else + return setenv(name, value, 1); +#endif +} + +inline bool SkipWithoutDescriptorHeap() { + if (AgcDriver::Graphics::DescriptorHeapEnabled()) return false; + std::puts("skipped, the device lacks VK_EXT_descriptor_heap, or the maintenance5, slot room and push data the GPU heap needs with it, so the GPU heap has nothing to run through"); + return true; +} + inline std::unique_ptr OpenVulkanTestDevice() { try { - return std::make_unique(); + auto device = std::make_unique(); + if (std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr && SkipWithoutDescriptorHeap()) return nullptr; + return device; } catch (const AgcDriver::VulkanUnavailable& error) { if (std::getenv("ANYPS5_REQUIRE_VULKAN") != nullptr) throw; std::printf("skipped, no usable Vulkan device: %s\n", error.what()); From b9a210ee5917f492b7c58cc46da13998fa2790b3 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 2 Nov 2026 06:14:31 +0530 Subject: [PATCH 094/269] test(agc): report the heap ring large-span test as skipped when the ring has too few chunks --- .../tests/BindlessHeapSlots.cpp | 24 +++++++++++++++---- .../cmake/agc_driver_heap_slots_tests.cmake | 2 ++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 77dad0d71a0d..58c224500e37 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -224,9 +224,9 @@ void ringSpans(const Context& context) { require(untilWrap() == 0u && !heap.Held(first) && heap.Statistics().spansExpired == 1u, "a span the ring wrote over has expired"); } -void ringLargeSpans(const Context& context) { +bool ringLargeSpans(const Context& context) { BindlessHeap heap(context); - require(heap.RingChunkCount() >= 5u, "the ring has fewer than five chunks, so a span over three chunks cannot be tested"); + if (heap.RingChunkCount() < 5u) return false; constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); constexpr std::size_t largeWords = chunkWords * 2u + 1024u; BindlessHeap::SpanMark pin; @@ -257,6 +257,7 @@ void ringLargeSpans(const Context& context) { refused = true; } require(refused, "a span over half the ring is refused"); + return true; } void ringCurrentChunk(const Context& context) { @@ -388,7 +389,8 @@ void twoHeapsComeBack(const Context& context, VkImageView view) { int main(int argc, char** argv) { const std::string mode = argc > 1 ? argv[1] : ""; - const bool comesBack = !mode.empty(); + const bool largeSpans = mode == "ring-large-spans"; + const bool comesBack = !mode.empty() && !largeSpans; try { SetTestEnvironment("APS5_GPU_HEAP", "1"); auto device = OpenVulkanTestDevice(); @@ -398,6 +400,21 @@ int main(int argc, char** argv) { return VulkanTestSkipped; } SetTestEnvironment("APS5_HEAP_SLOT_CAP", comesBack ? "8" : "1"); + if (largeSpans) { + bool ran = false; + { + const auto context = device->graphicsContext(); + ran = ringLargeSpans(context); + device->WaitIdle(); + } + device.reset(); + if (!ran) { + std::printf("skipped, the heap ring has fewer than five chunks\n"); + return VulkanTestSkipped; + } + std::cout << "bindless heap ring large span tests passed\n"; + return 0; + } if (comesBack) { { const auto context = device->graphicsContext(); @@ -425,7 +442,6 @@ int main(int argc, char** argv) { textureSlots(context, placeholders.View(Abi::FirstImageBinding)); samplerSlots(context); ringSpans(context); - ringLargeSpans(context); ringCurrentChunk(context); viewSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); encodedViews(context); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake index 84e4a7b66241..b22d0f5ca9cf 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake @@ -20,6 +20,8 @@ configure_windows_unwind(agc_driver_heap_slots_tests) if(BUILD_TESTING) agc_add_default_test(agc_driver_heap_slots_tests) + agc_add_env_test(agc_driver_heap_slots_ring_large_spans agc_driver_heap_slots_tests + ARGS ring-large-spans ENV ANYPS5_NO_SHADER_CACHE=1) foreach(agcHeapSlotsMode IN ITEMS comes-back storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release) string(REPLACE "-" "_" agcHeapSlotsName "${agcHeapSlotsMode}") agc_add_env_test(agc_driver_heap_slots_${agcHeapSlotsName} agc_driver_heap_slots_tests From bcb8efaeb36eb6a5513f0eefde0fe001b5742067 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 2 Nov 2026 06:20:05 +0530 Subject: [PATCH 095/269] fix(shader): round-trip the heap profile and the other keyed target fields in serialized shader requests Request serialization version 52 writes gpuResolvedImages, descriptorMemory and heapDataUniformDwords, then ldsLockFences, meshWindowBuffer, waveLdsMemoryBarriers, deviceScopeLdsMemoryBarriers, exactRobustLoads and robustBufferAccess2, so a dump keeps every target field that the shader cache key includes and that selects an emitter path. Older versions deserialize to heap off with limit 0 and the other fields off, as before. --- .../libSceAgcDriver/tests/ShaderMemory.cpp | 20 +-- .../ControlFlow/src/RequestSerializer.cpp | 24 +++- .../tests/RequestSerializerTests.cpp | 132 +++++++++++++++--- 3 files changed, 147 insertions(+), 29 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 1e5a43e8aee2..78375012ecda 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -7036,7 +7036,7 @@ void verifyPixelRequestSerialization() { minimal.context.pixel->layerExported = true; minimal.context.pixel->ditheredAlphaToCoverage = true; const auto encoded = serializer.Serialize(minimal); - require(requestPrefix(encoded, 8u) == "NVNQQTMAAAA=", "new requests did not use serialization version 51"); + require(requestPrefix(encoded, 8u) == "NVNQQTQAAAA=", "new requests did not use serialization version 52"); auto withBarycentric = minimal; withBarycentric.target.fragmentBarycentricBuiltins = true; require(serializer.Deserialize(serializer.Serialize(withBarycentric)).request.target.fragmentBarycentricBuiltins && !serializer.Deserialize(encoded).request.target.fragmentBarycentricBuiltins, "barycentric built-ins were lost in serialization"); @@ -7157,7 +7157,7 @@ void verifyPixelRequestSerialization() { for (std::size_t bytes = 0; bytes < 45u; ++bytes) { expectFailure([&] { static_cast(serializer.Deserialize(requestPrefix(encoded, mappingOffset + bytes))); }, "truncated data", "a truncated pixel mapping, packing, dual-source, alpha-to-coverage, stencil reference export flag, primitive class, layer export, dither or front-face flag, quad pixel mask or quad sample mask was accepted"); } - for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQTQAAAA="}) { + for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQTUAAAA="}) { expectFailure([&] { static_cast(serializer.Deserialize(unsupported)); }, "serialization version", "an unsupported request version was accepted"); } static constexpr std::string_view version18Request{ @@ -7278,12 +7278,13 @@ void verifyDepthExportClamp() { both.request.context.pixel->depthExportMin == 0.25f && both.request.context.pixel->depthExportMax == 0.75f, "depth export: a version 49 request lost the bounds or the version 45 target tail"); auto bytes = decodeBase64(RequestSerializer{}.Serialize(tail)); - require(bytes.size() > 8u && bytes[4] == 51u, "depth export: a depth exporting request did not use serialization version 51"); + require(bytes.size() > 8u && bytes[4] == 52u, "depth export: a depth exporting request did not use serialization version 52"); static constexpr std::array boundBytes{0x00u, 0x00u, 0x80u, 0x3eu, 0x00u, 0x00u, 0x40u, 0x3fu}; const auto found = std::search(bytes.begin(), bytes.end(), boundBytes.begin(), boundBytes.end()); require(found != bytes.end() && std::search(found + 1, bytes.end(), boundBytes.begin(), boundBytes.end()) == bytes.end(), "depth export: the clamp bounds were not written exactly once"); bytes.erase(found, found + boundBytes.size()); + bytes.resize(bytes.size() - 12u); bytes.pop_back(); for (const std::uint8_t legacyVersion : {48u, 47u, 46u}) { if (legacyVersion == 47u) bytes.pop_back(); @@ -7304,12 +7305,13 @@ void verifyDepthExportClamp() { ditheredPixel.ditheredAlphaSamples = 2u; dithered.context.pixel = ditheredPixel; auto ditheredBytes = decodeBase64(RequestSerializer{}.Serialize(dithered)); - require(ditheredBytes.size() > 8u && ditheredBytes[4] == 51u, "a two-sample dithered request did not use serialization version 51"); + require(ditheredBytes.size() > 8u && ditheredBytes[4] == 52u, "a two-sample dithered request did not use serialization version 52"); if (depthExport) { const auto bounds = std::search(ditheredBytes.begin(), ditheredBytes.end(), boundBytes.begin(), boundBytes.end()); require(bounds != ditheredBytes.end(), "a two-sample dithered depth exporting request lacks the clamp bounds"); ditheredBytes.erase(bounds, bounds + boundBytes.size()); } + ditheredBytes.resize(ditheredBytes.size() - 12u); ditheredBytes.pop_back(); ditheredBytes[4] = 48u; const auto main48 = RequestSerializer{}.Deserialize(encodeBase64(ditheredBytes)); @@ -7467,7 +7469,7 @@ void verifyVertexInfoVersion19() { const auto version43Bytes = [&](std::vector bytes) { require(bytes.end() - bytes.begin() > mergeOffset + static_cast(mergeBytes) && std::equal(plainPixel.begin() + mergeOffset, plainPixel.begin() + mergeOffset + static_cast(mergeBytes), bytes.begin() + mergeOffset), "a replay fixture does not hold the default color target merge after the sample order"); bytes.erase(bytes.begin() + mergeOffset, bytes.begin() + mergeOffset + static_cast(mergeBytes)); - bytes.resize(bytes.size() - sizeof(std::uint32_t) - 4u); + bytes.resize(bytes.size() - sizeof(std::uint32_t) - 4u - 12u); return bytes; }; auto version42 = version43Bytes(plainPixel); @@ -7629,9 +7631,10 @@ void verifyDepthRemapRequests() { const auto plainBytes = decodeBase64(plain); const auto remappedBytes = decodeBase64(remapped); constexpr std::size_t pointTailBytes = 13u; - require(plainBytes.size() == remappedBytes.size() && plainBytes.size() > 15u + pointTailBytes && std::equal(plainBytes.begin(), plainBytes.end() - 15 - pointTailBytes, remappedBytes.begin()) && std::equal(plainBytes.end() - 8 - pointTailBytes, plainBytes.end(), remappedBytes.end() - 8 - pointTailBytes), "the depth remap flag and mode are not the 6 bytes before the f32 flush and denormal preserve flags, the point tail, the fused arithmetic flag, the pixel function LDS flag, the pixel function storage size, the barycentric built-in flag and the tessellation evaluation subgroup flag of a vertex request"); + require(plainBytes.size() == remappedBytes.size() && plainBytes.size() > 27u + pointTailBytes && std::equal(plainBytes.begin(), plainBytes.end() - 27 - pointTailBytes, remappedBytes.begin()) && std::equal(plainBytes.end() - 20 - pointTailBytes, plainBytes.end(), remappedBytes.end() - 20 - pointTailBytes), "the depth remap flag and mode are not the 6 bytes before the f32 flush and denormal preserve flags, the point tail, the fused arithmetic flag, the pixel function LDS flag, the pixel function storage size, the barycentric built-in flag, the tessellation evaluation subgroup flag, the heap profile and the other keyed target flags of a vertex request"); for (const std::uint8_t legacyVersion : {32u, 34u}) { auto legacyBytes = remappedBytes; + legacyBytes.resize(legacyBytes.size() - 12u); legacyBytes.resize(legacyBytes.size() - sizeof(std::uint32_t)); legacyBytes.pop_back(); legacyBytes.pop_back(); @@ -7645,6 +7648,7 @@ void verifyDepthRemapRequests() { require(serializer.Serialize(legacy.request) == plain, ("a version " + std::to_string(legacyVersion) + " vertex request misread the fields before the depth remap").c_str()); } auto version35 = remappedBytes; + version35.resize(version35.size() - 12u); version35.resize(version35.size() - sizeof(std::uint32_t)); version35.pop_back(); version35.pop_back(); @@ -7698,8 +7702,8 @@ void verifyMergedHullConfiguration() { require(!serializer.Deserialize(separate).request.graphics->tessellation->mergedHull, "a separate hull configuration was read as merged"); constexpr std::size_t pointTailBytes = 13u; auto legacy = decodeBase64(merged); - require(legacy.size() > 56u + pointTailBytes && legacy[4] == 51u, "a merged hull request did not use serialization version 51"); - legacy.resize(legacy.size() - sizeof(std::uint32_t) - 3u - pointTailBytes); + require(legacy.size() > 56u + pointTailBytes && legacy[4] == 52u, "a merged hull request did not use serialization version 52"); + legacy.resize(legacy.size() - sizeof(std::uint32_t) - 3u - pointTailBytes - 12u); legacy.pop_back(); legacy.pop_back(); require(legacy[legacy.size() - 52u] == 1u, "the merged hull flag is not the last byte of the tessellation configuration"); diff --git a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp index e6b6c9de1ae6..e89cedf0911c 100644 --- a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp +++ b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp @@ -898,7 +898,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const std::string buffer; Writer writer(buffer); writer.WriteU32(0x41505335u); - writer.WriteU32(51u); + writer.WriteU32(52u); writeShaderBinary(writer, request.shader); writeGuestContext(writer, request.context); writeSpirvTarget(writer, request.target); @@ -941,6 +941,15 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const writer.WriteU32(request.target.pixelFunctionStorageDwords); writer.WriteBool(request.target.fragmentBarycentricBuiltins); writer.WriteBool(request.target.tessellationEvaluationSubgroups); + writer.WriteBool(request.target.gpuResolvedImages); + writer.WriteBool(request.target.descriptorMemory); + writer.WriteU32(request.target.heapDataUniformDwords); + writer.WriteBool(request.target.ldsLockFences); + writer.WriteBool(request.target.meshWindowBuffer); + writer.WriteBool(request.target.waveLdsMemoryBarriers); + writer.WriteBool(request.target.deviceScopeLdsMemoryBarriers); + writer.WriteBool(request.target.exactRobustLoads); + writer.WriteBool(request.target.robustBufferAccess2); return base64Encode(buffer); } @@ -949,7 +958,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const Reader reader(decoded); if (reader.ReadU32() != 0x41505335u) throw std::runtime_error("invalid recompile request signature"); const auto version = reader.ReadU32(); - if (version < 1u || version > 51u || version == 50u) throw std::runtime_error("unsupported recompile request serialization version"); + if (version < 1u || version > 52u || version == 50u) throw std::runtime_error("unsupported recompile request serialization version"); DeserializedRequest result{}; result.request.shader = readShaderBinary(reader, result.shaderCode, result.shaderHeader); result.request.context = readGuestContext(reader, result, version); @@ -1010,6 +1019,17 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const } if (version >= 48u) result.request.target.fragmentBarycentricBuiltins = reader.ReadBool(); if (version >= 51u) result.request.target.tessellationEvaluationSubgroups = reader.ReadBool(); + if (version >= 52u) { + result.request.target.gpuResolvedImages = reader.ReadBool(); + result.request.target.descriptorMemory = reader.ReadBool(); + result.request.target.heapDataUniformDwords = reader.ReadU32(); + result.request.target.ldsLockFences = reader.ReadBool(); + result.request.target.meshWindowBuffer = reader.ReadBool(); + result.request.target.waveLdsMemoryBarriers = reader.ReadBool(); + result.request.target.deviceScopeLdsMemoryBarriers = reader.ReadBool(); + result.request.target.exactRobustLoads = reader.ReadBool(); + result.request.target.robustBufferAccess2 = reader.ReadBool(); + } if (version >= 21u && reader.Remaining() != 0u) throw std::runtime_error("RequestSerializer: unexpected trailing data"); return result; } diff --git a/core/shader/recompiler/tests/RequestSerializerTests.cpp b/core/shader/recompiler/tests/RequestSerializerTests.cpp index 58f91c2f3635..ea6b975a6109 100644 --- a/core/shader/recompiler/tests/RequestSerializerTests.cpp +++ b/core/shader/recompiler/tests/RequestSerializerTests.cpp @@ -174,6 +174,12 @@ std::string EncodeBase64(const std::vector& bytes) { return text; } +std::string EncodeWithDefaultVersion52Tail(std::vector bytes) { + bytes[4] = 52u; + bytes.insert(bytes.end(), 12u, 0u); + return EncodeBase64(bytes); +} + } namespace { @@ -193,6 +199,84 @@ void VerifyTessellationInstancePatches() { } +void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { + struct Profile { + bool gpuResolvedImages; + bool descriptorMemory; + std::uint32_t heapDataUniformDwords; + }; + constexpr std::array profiles{{{false, false, 0u}, {true, true, 0u}, {true, true, 4096u}, {true, true, 16384u}, {true, false, 16384u}, {false, true, 16384u}}}; + for (const auto& profile : profiles) { + ShaderRecompiler::RecompileRequest request{}; + request.target.gpuResolvedImages = profile.gpuResolvedImages; + request.target.descriptorMemory = profile.descriptorMemory; + request.target.heapDataUniformDwords = profile.heapDataUniformDwords; + const auto encoded = serializer.Serialize(request); + const auto replay = serializer.Deserialize(encoded); + Require(replay.request.target.gpuResolvedImages == profile.gpuResolvedImages); + Require(replay.request.target.descriptorMemory == profile.descriptorMemory); + Require(replay.request.target.heapDataUniformDwords == profile.heapDataUniformDwords); + Require(serializer.Serialize(replay.request) == encoded); + auto bytes = DecodeBase64(encoded); + Require(bytes[4] == 52u && bytes.size() > 12u); + bytes.resize(bytes.size() - 12u); + bytes[4] = 51u; + const auto older = serializer.Deserialize(EncodeBase64(bytes)).request.target; + Require(!older.gpuResolvedImages && !older.descriptorMemory && older.heapDataUniformDwords == 0u); + bytes[4] = 52u; + bool truncated = false; + try { + static_cast(serializer.Deserialize(EncodeBase64(bytes))); + } catch (const std::runtime_error& error) { + truncated = std::string_view(error.what()) == "RequestSerializer: truncated data"; + } + Require(truncated); + bytes = DecodeBase64(encoded); + bytes.push_back(0u); + bool trailing = false; + try { + static_cast(serializer.Deserialize(EncodeBase64(bytes))); + } catch (const std::runtime_error& error) { + trailing = std::string_view(error.what()) == "RequestSerializer: unexpected trailing data"; + } + Require(trailing); + } + ShaderRecompiler::RecompileRequest limits{}; + limits.target.gpuResolvedImages = true; + limits.target.descriptorMemory = true; + limits.target.heapDataUniformDwords = 16384u; + ShaderRecompiler::RecompileRequest addressed = limits; + addressed.target.heapDataUniformDwords = 0u; + Require(serializer.Serialize(limits) != serializer.Serialize(addressed)); +} + +void VerifyKeyedTargetFields(const ShaderRecompiler::RequestSerializer& serializer) { + using Field = bool ShaderRecompiler::SpirvTarget::*; + constexpr std::array fields{&ShaderRecompiler::SpirvTarget::ldsLockFences, &ShaderRecompiler::SpirvTarget::meshWindowBuffer, &ShaderRecompiler::SpirvTarget::waveLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::deviceScopeLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::exactRobustLoads, &ShaderRecompiler::SpirvTarget::robustBufferAccess2}; + const ShaderRecompiler::RecompileRequest defaults{}; + const auto defaultEncoded = serializer.Serialize(defaults); + for (std::size_t chosen = 0; chosen <= fields.size(); ++chosen) { + ShaderRecompiler::RecompileRequest request{}; + for (std::size_t index = 0; index < fields.size(); ++index) request.target.*fields[index] = chosen == fields.size() || index == chosen; + const auto encoded = serializer.Serialize(request); + Require(chosen == fields.size() ? encoded != defaultEncoded : encoded != defaultEncoded && encoded.size() == defaultEncoded.size()); + const auto replay = serializer.Deserialize(encoded); + for (std::size_t index = 0; index < fields.size(); ++index) Require(replay.request.target.*fields[index] == (chosen == fields.size() || index == chosen)); + Require(serializer.Serialize(replay.request) == encoded); + auto bytes = DecodeBase64(encoded); + Require(bytes[4] == 52u && bytes.size() > 12u); + bytes.resize(bytes.size() - 12u); + bytes[4] = 51u; + const auto older = serializer.Deserialize(EncodeBase64(bytes)).request.target; + for (const auto field : fields) Require(!(older.*field)); + for (std::size_t index = 0; index < fields.size(); ++index) { + auto other = request; + other.target.*fields[index] = !(other.target.*fields[index]); + Require(serializer.Serialize(other) != encoded); + } + } +} + int main() { VerifyMemoryView(); VerifyTessellationInstancePatches(); @@ -327,7 +411,7 @@ int main() { upgraded.insert(upgraded.end(), {0u, 0x10u, 0u, 0u}); upgraded.push_back(0u); upgraded.push_back(1u); - Require(serializer.Serialize(request) == EncodeBase64(upgraded)); + Require(serializer.Serialize(request) == EncodeWithDefaultVersion52Tail(upgraded)); auto truncated = bytes; truncated.pop_back(); bool rejected = false; @@ -341,7 +425,7 @@ int main() { auto vertex23 = bytes; vertex23[4] = 23u; const auto vertexReplay = serializer.Deserialize(EncodeBase64(vertex23)); - Require(serializer.Serialize(vertexReplay.request) == EncodeBase64(upgraded)); + Require(serializer.Serialize(vertexReplay.request) == EncodeWithDefaultVersion52Tail(upgraded)); continue; } for (const bool layer : {false, true}) { @@ -372,7 +456,7 @@ int main() { layered.insert(layered.end(), {0u, 0x10u, 0u, 0u}); layered.push_back(0u); layered.push_back(1u); - Require(serializer.Serialize(layerReplay.request) == EncodeBase64(layered)); + Require(serializer.Serialize(layerReplay.request) == EncodeWithDefaultVersion52Tail(layered)); } } } @@ -402,7 +486,7 @@ int main() { bytes.insert(bytes.end(), {0u, 0x10u, 0u, 0u}); bytes.push_back(0u); bytes.push_back(1u); - Require(serializer.Serialize(replay.request) == EncodeBase64(bytes)); + Require(serializer.Serialize(replay.request) == EncodeWithDefaultVersion52Tail(bytes)); auto truncated23 = DecodeBase64(encoded23); truncated23.pop_back(); @@ -540,13 +624,13 @@ int main() { upgraded.insert(upgraded.end(), {0u, 0x10u, 0u, 0u}); upgraded.push_back(0u); upgraded.push_back(1u); - Require(serializer.Serialize(request) == EncodeBase64(upgraded)); + Require(serializer.Serialize(request) == EncodeWithDefaultVersion52Tail(upgraded)); const auto replay38 = serializer.Deserialize(EncodeBase64(main38)); Require(replay38.request.graphics.has_value() && replay38.request.graphics->tessellation.has_value() == fixture.tessellation); Require(!fixture.tessellation || (!replay38.request.graphics->tessellation->mergedHull && replay38.request.graphics->tessellation->primitiveGroupSize == 37u && replay38.request.graphics->tessellation->breakAtInstance)); Require(replay38.request.graphics->draw.indexAddress == 0xabcdef3400u && replay38.request.graphics->draw.indexCount == 57u && replay38.request.graphics->draw.indexElementBytes == 4u && replay38.request.graphics->draw.instanceCount == 9u); Require(replay38.request.target.float16DenormPreserve == preserve); - Require(serializer.Serialize(replay38.request) == EncodeBase64(upgraded)); + Require(serializer.Serialize(replay38.request) == EncodeWithDefaultVersion52Tail(upgraded)); if (fixture.tessellation) { for (const bool merged : {false, true}) { auto pointed = request; @@ -555,9 +639,10 @@ int main() { pointed.context.vertex->pointSize = 3.0f; pointed.context.vertex->pointSizeMin = 1.0f; pointed.context.vertex->pointSizeMax = 8.0f; - auto version51 = DecodeBase64(serializer.Serialize(pointed)); - Require(version51.size() > 17u && version51[4] == 51u); - auto version48 = version51; + auto version52 = DecodeBase64(serializer.Serialize(pointed)); + Require(version52.size() > 17u && version52[4] == 52u); + auto version48 = version52; + version48.resize(version48.size() - 12u); version48.pop_back(); version48[4] = 48u; auto version46 = version48; @@ -576,7 +661,7 @@ int main() { version43.pop_back(); version43[4] = 43u; const auto replay43 = serializer.Deserialize(EncodeBase64(version43)); - Require(serializer.Serialize(replay43.request) == EncodeBase64(version51)); + Require(serializer.Serialize(replay43.request) == EncodeBase64(version52)); Require(replay43.request.graphics->tessellation->mergedHull == merged && replay43.request.context.vertex->pointList && replay43.request.context.vertex->pointSize == 3.0f && replay43.request.context.vertex->pointSizeMin == 1.0f && replay43.request.context.vertex->pointSizeMax == 8.0f); auto version42 = version43; version42.resize(version42.size() - 13u); @@ -616,7 +701,7 @@ int main() { main25.insert(main25.end(), {0u, 0x10u, 0u, 0u}); main25.push_back(0u); main25.push_back(1u); - Require(serializer.Serialize(replay25.request) == EncodeBase64(main25)); + Require(serializer.Serialize(replay25.request) == EncodeWithDefaultVersion52Tail(main25)); } } } @@ -633,8 +718,9 @@ int main() { const auto replay = serializer.Deserialize(encoded); Require(replay.request.target.float16DenormPreserve == preserve && replay.request.target.float32FlushToZero == !preserve && replay.request.target.float32DenormPreserve == preserve && replay.request.target.largePixelFunctionLdsBuffer == !preserve && replay.request.target.pixelFunctionStorageDwords == request.target.pixelFunctionStorageDwords); auto bytes = DecodeBase64(encoded); - Require(bytes.size() >= 8u && bytes[4] == 51u && bytes[5] == 0u && bytes[6] == 0u && bytes[7] == 0u); + Require(bytes.size() >= 8u && bytes[4] == 52u && bytes[5] == 0u && bytes[6] == 0u && bytes[7] == 0u); auto version40 = bytes; + version40.resize(version40.size() - 12u); version40.resize(version40.size() - sizeof(std::uint32_t)); version40.pop_back(); version40.pop_back(); @@ -645,7 +731,7 @@ int main() { const auto replay40 = serializer.Deserialize(EncodeBase64(version40)); Require(!replay40.request.target.float32DenormPreserve && replay40.request.target.float32FlushToZero == !preserve); auto future = bytes; - future[4] = 52u; + future[4] = 53u; bool futureRejected = false; try { static_cast(serializer.Deserialize(EncodeBase64(future))); @@ -688,6 +774,7 @@ int main() { const auto orderEncoded = serializer.Serialize(request); Require(serializer.Deserialize(orderEncoded).request.context.pixel->sampleOrder == pixel.sampleOrder); auto version42 = DecodeBase64(orderEncoded); + version42.resize(version42.size() - 12u); const auto orderOffset = std::search(version42.begin(), version42.end(), pixel.sampleLocations.begin(), pixel.sampleLocations.end()) - version42.begin() + static_cast(pixel.sampleLocations.size() + 1u); Require(version42.end() - version42.begin() > orderOffset + static_cast(sizeof(pixel.sampleOrder)) && version42[static_cast(orderOffset)] == 0x10u); EraseDefaultTargetMerge(version42, orderOffset + static_cast(sizeof(pixel.sampleOrder))); @@ -714,6 +801,7 @@ int main() { Require(serializer.Deserialize(serializer.Serialize(request)).request.target.spannedWaves == spanned); request.target.float32FlushToZero = true; auto version35 = DecodeBase64(serializer.Serialize(request)); + version35.resize(version35.size() - 12u); version35.resize(version35.size() - sizeof(std::uint32_t)); version35.pop_back(); version35.pop_back(); @@ -765,7 +853,7 @@ int main() { for (const std::uint8_t version : {32u, 33u, 34u, 35u, 36u, 37u, 38u}) { pointRequest.target.spannedWaves = spanned; auto legacy = DecodeBase64(serializer.Serialize(pointRequest)); - legacy.resize(legacy.size() - (version >= 36u ? 22u : version >= 35u ? 23u : 28u)); + legacy.resize(legacy.size() - (version >= 36u ? 34u : version >= 35u ? 35u : 40u)); legacy[4] = version; const auto replayLegacy = serializer.Deserialize(EncodeBase64(legacy)); Require(replayLegacy.request.target.spannedWaves == spanned); @@ -777,7 +865,7 @@ int main() { Require(!replayLegacy.request.context.vertex->pointList && replayLegacy.request.context.vertex->pointSize == 1.0f); Require(replayLegacy.request.context.vertex->pointSizeMin == 0.0f && replayLegacy.request.context.vertex->pointSizeMax == 0.0f); const auto upgradedLegacy = DecodeBase64(serializer.Serialize(replayLegacy.request)); - Require(upgradedLegacy[4] == 51u && upgradedLegacy.size() == legacy.size() + (version >= 36u ? 22u : version >= 35u ? 23u : 28u)); + Require(upgradedLegacy[4] == 52u && upgradedLegacy.size() == legacy.size() + (version >= 36u ? 34u : version >= 35u ? 35u : 40u)); } } @@ -786,6 +874,7 @@ int main() { const auto sampledPoint = serializer.Deserialize(serializer.Serialize(pointRequest)); Require(sampledPoint.request.context.vertex->pointList && sampledPoint.request.context.pixel->sampleOrder == pixel.sampleOrder); auto legacy43 = DecodeBase64(serializer.Serialize(pointRequest)); + legacy43.resize(legacy43.size() - 12u); const auto mergeOffset = std::search(legacy43.begin(), legacy43.end(), pixel.sampleLocations.begin(), pixel.sampleLocations.end()) - legacy43.begin() + static_cast(pixel.sampleLocations.size() + 1u + sizeof(pixel.sampleOrder)); EraseDefaultTargetMerge(legacy43, mergeOffset); legacy43.resize(legacy43.size() - 4u); @@ -805,7 +894,7 @@ int main() { pixel.sampleOrder = {}; pointRequest.context.pixel = pixel; auto legacy34 = DecodeBase64(serializer.Serialize(pointRequest)); - legacy34.resize(legacy34.size() - 28u); + legacy34.resize(legacy34.size() - 40u); const auto stencil34 = std::search(legacy34.begin(), legacy34.end(), pixel.sampleLocations.begin(), pixel.sampleLocations.begin() + 4) + pixel.sampleLocations.size(); const auto legacyPixelTail = static_cast(1u + sizeof(pixel.sampleOrder)); Require(legacy34.end() - stencil34 > legacyPixelTail && std::all_of(stencil34, stencil34 + legacyPixelTail, [](std::uint8_t value) { return value == 0u; })); @@ -820,7 +909,8 @@ int main() { request.target.fusedExactArithmetic = fused; request.target.largePixelFunctionLdsBuffer = false; auto bytes = DecodeBase64(serializer.Serialize(request)); - Require(serializer.Deserialize(EncodeBase64(bytes)).request.target.fusedExactArithmetic == fused && bytes[bytes.size() - 8u] == (fused ? 1u : 0u) && bytes[bytes.size() - 7u] == 0u); + Require(serializer.Deserialize(EncodeBase64(bytes)).request.target.fusedExactArithmetic == fused && bytes[bytes.size() - 20u] == (fused ? 1u : 0u) && bytes[bytes.size() - 19u] == 0u); + bytes.resize(bytes.size() - 12u); bytes.pop_back(); bytes.pop_back(); const auto fusedMerge = std::search(bytes.begin(), bytes.end(), pixel.sampleLocations.begin(), pixel.sampleLocations.end()) - bytes.begin() + static_cast(pixel.sampleLocations.size() + 1u + sizeof(pixel.sampleOrder)); @@ -862,6 +952,7 @@ int main() { return false; }; auto version46Dither = twoSample; + version46Dither.resize(version46Dither.size() - 12u); version46Dither.pop_back(); version46Dither.pop_back(); version46Dither[4] = 46u; @@ -878,8 +969,9 @@ int main() { domain.target.tessellationEvaluationSubgroups = subgroups; const auto encoded = serializer.Serialize(domain); auto bytes = DecodeBase64(encoded); - Require(bytes.size() > 8u && bytes[4] == 51u && bytes.back() == (subgroups ? 1u : 0u)); + Require(bytes.size() > 8u && bytes[4] == 52u && bytes[bytes.size() - 13u] == (subgroups ? 1u : 0u)); Require(serializer.Deserialize(encoded).request.target.tessellationEvaluationSubgroups == subgroups); + bytes.resize(bytes.size() - 12u); bytes.pop_back(); bool truncatedRejected = false; try { @@ -894,7 +986,7 @@ int main() { auto upgraded = bytes; upgraded[4] = 51u; upgraded.push_back(1u); - Require(serializer.Serialize(replay49.request) == EncodeBase64(upgraded)); + Require(serializer.Serialize(replay49.request) == EncodeWithDefaultVersion52Tail(upgraded)); for (auto skipped : {bytes, upgraded}) { skipped[4] = 50u; bool skippedRejected = false; @@ -907,5 +999,7 @@ int main() { } } + VerifyHeapProfile(serializer); + VerifyKeyedTargetFields(serializer); return 0; } From 268a7a3d81b6e89d666d508907b51fb40a6d29d0 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 2 Nov 2026 06:20:05 +0530 Subject: [PATCH 096/269] feat(agc): replay a request with its captured heap profile unless overridden agc_shader_replay keeps the captured heap profile and prints it with its source. --gpu-heap, --no-gpu-heap and --heap-data-uniform-dwords N are explicit overrides; --gpu-heap with --no-gpu-heap and --no-gpu-heap with a nonzero limit exit 2. The target flag options force their flag on over the captured value and are listed on a forced-on line. The replay tool check compares SPIR-V of requests whose shader reads shader data, so the uniform and addressed limits differ. --- .../tests/ShaderReplayRequests.cpp | 22 ++++ .../tests/ShaderReplayTool.cmake | 67 +++++++++++ .../libSceAgcDriver/tools/ShaderReplay.cpp | 104 ++++++++++++++++-- 3 files changed, 182 insertions(+), 11 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderReplayRequests.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderReplayRequests.cpp index e34aeeb6faf9..3293ff101a72 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderReplayRequests.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderReplayRequests.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include int main(int argc, char** argv) try { @@ -75,6 +76,27 @@ int main(int argc, char** argv) try { file << RequestSerializer{}.Serialize(lds); if (!file) throw std::runtime_error("cannot write synthetic replay request"); } + for (const auto& [name, dwords] : {std::pair{"heap-addressed.req", 0u}, std::pair{"heap-4096.req", 4096u}}) { + auto heap = lds; + heap.target.gpuResolvedImages = true; + heap.target.descriptorMemory = true; + heap.target.heapDataUniformDwords = dwords; + std::ofstream file(directory / name, std::ios::binary); + file << RequestSerializer{}.Serialize(heap); + if (!file) throw std::runtime_error("cannot write synthetic replay request"); + } + srt[20] = 0u; + const std::array dataCapabilities{spv::CapabilityImageGatherExtended, spv::CapabilityInt64, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess, spv::CapabilitySampledImageArrayDynamicIndexing, spv::CapabilityStorageImageArrayDynamicIndexing}; + for (const auto& [name, dwords] : {std::pair{"heap-data-addressed.req", 0u}, std::pair{"heap-data-4096.req", 4096u}}) { + auto heap = request; + heap.target.supportedCapabilities = dataCapabilities; + heap.target.gpuResolvedImages = true; + heap.target.descriptorMemory = true; + heap.target.heapDataUniformDwords = dwords; + std::ofstream file(directory / name, std::ios::binary); + file << RequestSerializer{}.Serialize(heap); + if (!file) throw std::runtime_error("cannot write synthetic replay request"); + } std::puts("synthetic guarded replay requests written"); return 0; } catch (const std::exception& error) { diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake b/core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake index 528f42d8e28f..5316a1f81fc2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake @@ -42,3 +42,70 @@ foreach(mode IN ITEMS --prepare --materialize) message(FATAL_ERROR "${mode} ignored --wave-lds-memory-barriers\n${baseline}") endif() endforeach() + +function(expect_heap_profile description profile) + execute_process(COMMAND "${TOOL}" ${ARGN} RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE errors) + if(NOT code STREQUAL "0" OR NOT output MATCHES "heap profile ${profile}\n") + message(FATAL_ERROR "${description}: expected heap profile ${profile}: ${code}\n${output}${errors}") + endif() +endfunction() + +expect_heap_profile("captured heap off" "\\(captured\\): no heap, gpuResolvedImages 0, descriptorMemory 0, data uniform dwords 0" "${CAPTURE}/lds.req") +expect_heap_profile("captured heap with limit 0" "\\(captured\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 0" "${CAPTURE}/heap-addressed.req") +expect_heap_profile("captured heap with limit 4096" "\\(captured\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 4096" "${CAPTURE}/heap-4096.req") +expect_heap_profile("--gpu-heap on a heap-off capture" "\\(override\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 16384" --gpu-heap "${CAPTURE}/lds.req") +expect_heap_profile("--gpu-heap on a limit 0 capture" "\\(override\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 16384" --gpu-heap "${CAPTURE}/heap-addressed.req") +expect_heap_profile("--gpu-heap with a limit" "\\(override\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 8192" --gpu-heap --heap-data-uniform-dwords 8192 "${CAPTURE}/lds.req") +expect_heap_profile("--no-gpu-heap on a heap capture" "\\(override\\): no heap, gpuResolvedImages 0, descriptorMemory 0, data uniform dwords 0" --no-gpu-heap "${CAPTURE}/heap-4096.req") +expect_heap_profile("--heap-data-uniform-dwords alone keeps the captured heap" "\\(override\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 0" --heap-data-uniform-dwords 0 "${CAPTURE}/heap-4096.req") + +execute_process(COMMAND "${TOOL}" --heap-data-uniform-dwords x "${CAPTURE}/lds.req" RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE errors) +if(NOT code STREQUAL "2") + message(FATAL_ERROR "a malformed --heap-data-uniform-dwords value was accepted: ${code}\n${output}${errors}") +endif() + +function(expect_usage_error description message) + execute_process(COMMAND "${TOOL}" ${ARGN} RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE errors) + if(NOT code STREQUAL "2" OR NOT errors MATCHES "${message}") + message(FATAL_ERROR "${description}: expected exit 2 with '${message}': ${code}\n${output}${errors}") + endif() +endfunction() + +expect_usage_error("--gpu-heap then --no-gpu-heap" "--gpu-heap and --no-gpu-heap conflict" --gpu-heap --no-gpu-heap "${CAPTURE}/lds.req") +expect_usage_error("--no-gpu-heap then --gpu-heap" "--gpu-heap and --no-gpu-heap conflict" --no-gpu-heap --gpu-heap "${CAPTURE}/lds.req") +expect_usage_error("--no-gpu-heap with a limit" "--no-gpu-heap conflicts with --heap-data-uniform-dwords 4096" --no-gpu-heap --heap-data-uniform-dwords 4096 "${CAPTURE}/lds.req") +expect_usage_error("a limit then --no-gpu-heap" "--no-gpu-heap conflicts with --heap-data-uniform-dwords 4096" --heap-data-uniform-dwords 4096 --no-gpu-heap "${CAPTURE}/lds.req") +expect_usage_error("a missing limit" "needs an unsigned 32-bit number" --heap-data-uniform-dwords) +expect_usage_error("an overflowing limit" "needs an unsigned 32-bit number" --heap-data-uniform-dwords 99999999999 "${CAPTURE}/lds.req") +expect_usage_error("a negative limit" "needs an unsigned 32-bit number" --heap-data-uniform-dwords -1 "${CAPTURE}/lds.req") +expect_heap_profile("--no-gpu-heap with limit 0" "\\(override\\): no heap, gpuResolvedImages 0, descriptorMemory 0, data uniform dwords 0" --no-gpu-heap --heap-data-uniform-dwords 0 "${CAPTURE}/heap-4096.req") +expect_heap_profile("--gpu-heap replaces a captured limit" "\\(override\\): heap, gpuResolvedImages 1, descriptorMemory 1, data uniform dwords 16384" --gpu-heap "${CAPTURE}/heap-4096.req") + +execute_process(COMMAND "${TOOL}" --robust2 --lds-lock-fences "${CAPTURE}/lds.req" RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE errors) +if(NOT code STREQUAL "0" OR NOT output MATCHES "target flags forced on: robust2, lds-lock-fences\n" OR NOT output MATCHES "heap profile \\(captured\\)") + message(FATAL_ERROR "forced target flags were not reported next to the captured heap profile: ${code}\n${output}${errors}") +endif() + +function(replay_spv result) + execute_process(COMMAND "${TOOL}" --spv ${ARGN} RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE errors) + if(NOT code STREQUAL "0" OR NOT output MATCHES "recompiled: [0-9]+ SPIR-V words") + message(FATAL_ERROR "--spv ${ARGN} failed: ${code}\n${output}${errors}") + endif() + string(FIND "${output}" "\n" firstLine) + math(EXPR firstLine "${firstLine} + 1") + string(SUBSTRING "${output}" ${firstLine} -1 output) + string(REGEX REPLACE "[^\n]*heap profile[^\n]*\n" "" output "${output}") + set(${result} "${output}" PARENT_SCOPE) +endfunction() + +replay_spv(addressed "${CAPTURE}/heap-data-addressed.req") +replay_spv(uniform "${CAPTURE}/heap-data-4096.req") +replay_spv(addressedAgain --heap-data-uniform-dwords 0 "${CAPTURE}/heap-data-addressed.req") +replay_spv(uniformOverride --heap-data-uniform-dwords 4096 "${CAPTURE}/heap-data-addressed.req") +replay_spv(addressedOverride --heap-data-uniform-dwords 0 "${CAPTURE}/heap-data-4096.req") +if(addressed STREQUAL uniform) + message(FATAL_ERROR "the captured limits 0 and 4096 replayed to the same SPIR-V\n${addressed}") +endif() +if(NOT addressed STREQUAL addressedAgain OR NOT uniform STREQUAL uniformOverride OR NOT addressed STREQUAL addressedOverride) + message(FATAL_ERROR "--heap-data-uniform-dwords did not reproduce the captured limit's SPIR-V\n${addressed}\n${addressedAgain}\n${uniform}\n${uniformOverride}\n${addressedOverride}") +endif() diff --git a/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp b/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp index 6aa5676114a9..de407eb7903b 100644 --- a/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp +++ b/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp @@ -13,7 +13,9 @@ #include "spirv-tools/libspirv.hpp" #endif +#include #include +#include #include #include #include @@ -52,21 +54,87 @@ bool g_waveLdsMemoryBarriers = false; bool g_deviceScopeLdsMemoryBarriers = false; bool g_ldsLockFences = false; bool g_gpuHeap = false; +bool g_noGpuHeap = false; +bool g_hasHeapDataUniformDwords = false; +std::uint32_t g_heapDataUniformDwords = 0; + +constexpr std::uint32_t DefaultHeapDataUniformDwords = 16384u; + +struct HeapProfileSelection { + const char* source; + bool heap; +}; + +HeapProfileSelection SelectHeapProfile(ShaderRecompiler::SpirvTarget& target) { + HeapProfileSelection selection{"captured", target.gpuResolvedImages || target.descriptorMemory}; + if (g_noGpuHeap) { + target.gpuResolvedImages = false; + target.descriptorMemory = false; + target.heapDataUniformDwords = 0u; + selection = {"override", false}; + } + if (g_gpuHeap) { + target.gpuResolvedImages = true; + target.descriptorMemory = true; + if (!g_hasHeapDataUniformDwords) target.heapDataUniformDwords = DefaultHeapDataUniformDwords; + selection = {"override", true}; + } + if (g_hasHeapDataUniformDwords) { + target.heapDataUniformDwords = g_heapDataUniformDwords; + selection.source = "override"; + } + return selection; +} bool g_code = false; +bool ParseHeapDataUniformDwords(int index, int argc, char** argv, std::uint32_t& result) { + char* end = nullptr; + const auto value = index + 1 < argc ? std::strtoull(argv[index + 1], &end, 10) : 0ull; + if (index + 1 >= argc || end == argv[index + 1] || *end != '\0' || value > UINT32_MAX) return false; + result = static_cast(value); + return true; +} + +bool HeapFlagsConflict(int argc, char** argv) { + bool gpuHeap = false; + bool noGpuHeap = false; + std::uint32_t dwords = 0; + for (int i = 1; i < argc; ++i) { + const std::string argument = argv[i]; + if (argument == "--gpu-heap") gpuHeap = true; + else if (argument == "--no-gpu-heap") noGpuHeap = true; + else if (argument == "--heap-data-uniform-dwords") ParseHeapDataUniformDwords(i, argc, argv, dwords); + } + if (gpuHeap && noGpuHeap) { + std::fprintf(stderr, "--gpu-heap and --no-gpu-heap conflict\n"); + return true; + } + if (noGpuHeap && dwords != 0u) { + std::fprintf(stderr, "--no-gpu-heap conflicts with --heap-data-uniform-dwords %u: the limit needs a heap profile\n", dwords); + return true; + } + return false; +} + bool Replay(const char* path) { auto request = ShaderRecompiler::RequestSerializer{}.Deserialize(ReadText(path)); - if (g_maintenance8) request.request.target.nonConstantImageOffsets = true; - if (g_robust2) request.request.target.robustBufferAccess2 = true; - if (g_waveLdsMemoryBarriers) request.request.target.waveLdsMemoryBarriers = true; - if (g_deviceScopeLdsMemoryBarriers) request.request.target.deviceScopeLdsMemoryBarriers = true; - if (g_ldsLockFences) request.request.target.ldsLockFences = true; - if (g_gpuHeap) { - request.request.target.gpuResolvedImages = true; - request.request.target.descriptorMemory = true; - request.request.target.heapDataUniformDwords = 16384u; - } + std::string forced; + const auto force = [&](bool enabled, bool& field, const char* name) { + if (!enabled) return; + if (!forced.empty()) forced += ", "; + forced += field ? std::string(name) + " (already captured)" : name; + field = true; + }; + auto& target = request.request.target; + force(g_maintenance8, target.nonConstantImageOffsets, "maintenance8"); + force(g_robust2, target.robustBufferAccess2, "robust2"); + force(g_waveLdsMemoryBarriers, target.waveLdsMemoryBarriers, "wave-lds-memory-barriers"); + force(g_deviceScopeLdsMemoryBarriers, target.deviceScopeLdsMemoryBarriers, "device-scope-lds-memory-barriers"); + force(g_ldsLockFences, target.ldsLockFences, "lds-lock-fences"); + const auto heapProfile = SelectHeapProfile(request.request.target); std::printf("%s: %zu code words, %zu user data, %zu memory regions, wave%u\n", path, request.request.shader.code.size(), request.request.context.userData.size(), request.request.context.memory.size(), request.request.context.waveSize); + std::printf(" heap profile (%s): %s, gpuResolvedImages %d, descriptorMemory %d, data uniform dwords %u\n", heapProfile.source, heapProfile.heap ? "heap" : "no heap", request.request.target.gpuResolvedImages, request.request.target.descriptorMemory, request.request.target.heapDataUniformDwords); + if (!forced.empty()) std::printf(" target flags forced on: %s\n", forced.c_str()); if (request.request.context.compute.has_value()) { const auto& compute = *request.request.context.compute; std::printf(" compute: threads %ux%ux%u, lds %u dwords, group ids %d%d%d, tg size %d, thread id components %u\n", compute.numThreads[0], compute.numThreads[1], compute.numThreads[2], compute.ldsSizeDwords, compute.groupIdEnable[0], compute.groupIdEnable[1], compute.groupIdEnable[2], compute.tgSizeEnable, compute.threadIdComponentCount); @@ -195,9 +263,10 @@ bool Replay(const char* path) { int main(int argc, char** argv) { if (argc < 2) { - std::fprintf(stderr, "usage: agc_shader_replay [--dis] [--asm] [--cfg] [--mem] [--spv] [--prepare] [--materialize] [--code] [--maintenance8] [--robust2] [--wave-lds-memory-barriers] [--device-scope-lds-memory-barriers] [--lds-lock-fences] [--gpu-heap] ...\n the driver writes shader_
.req files when APS5_DUMP_SHADERS is set; shader_
.prepare.req holds a request whose preparation failed before any resource capture, so replay it with --prepare\n"); + std::fprintf(stderr, "usage: agc_shader_replay [--dis] [--asm] [--cfg] [--mem] [--spv] [--prepare] [--materialize] [--code] [--maintenance8] [--robust2] [--wave-lds-memory-barriers] [--device-scope-lds-memory-barriers] [--lds-lock-fences] [--gpu-heap] [--no-gpu-heap] [--heap-data-uniform-dwords N] ...\n the driver writes shader_
.req files when APS5_DUMP_SHADERS is set; shader_
.prepare.req holds a request whose preparation failed before any resource capture, so replay it with --prepare\n a request replays with the heap profile it was captured with; --gpu-heap forces the heap profile (gpuResolvedImages, descriptorMemory, and 16384 data uniform dwords unless --heap-data-uniform-dwords is given, replacing a captured limit), --no-gpu-heap forces it off, --heap-data-uniform-dwords N forces the limit (0 selects ring-address reads); --gpu-heap with --no-gpu-heap, and --no-gpu-heap with a nonzero limit, exit 2\n --maintenance8, --robust2, --wave-lds-memory-barriers, --device-scope-lds-memory-barriers and --lds-lock-fences force their target flag on over the captured value and are listed on a 'target flags forced on' line\n"); return 2; } + if (HeapFlagsConflict(argc, argv)) return 2; int failures = 0; for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "--gcn") { @@ -224,6 +293,19 @@ int main(int argc, char** argv) { g_gpuHeap = true; continue; } + if (std::string(argv[i]) == "--no-gpu-heap") { + g_noGpuHeap = true; + continue; + } + if (std::string(argv[i]) == "--heap-data-uniform-dwords") { + if (!ParseHeapDataUniformDwords(i, argc, argv, g_heapDataUniformDwords)) { + std::fprintf(stderr, "--heap-data-uniform-dwords needs an unsigned 32-bit number\n"); + return 2; + } + g_hasHeapDataUniformDwords = true; + ++i; + continue; + } if (std::string(argv[i]) == "--robust2") { g_robust2 = true; continue; From f3a1d40b5d96fa1da96be78daa44a621860b6b36 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 2 Nov 2026 20:51:02 +0530 Subject: [PATCH 097/269] perf(agc): relocate cached heap draws across moved user-data V#s A heap stage keeps its draw's descriptor words in HeapStageWords while the compiled result is a shared template, so tagUserValueWords counted a stale draw's words and never tagged a V# value word. Read the draw's own words (ignoring the user-word copy in shader data), and patch a relocated hit's ring template bindings as well as the compiled result. --- .../include/Driver/Draw/HeapStages.hpp | 2 ++ .../Execution/include/Driver/Driver.hpp | 2 +- .../Execution/src/Driver/Draw/DrawCapture.cpp | 2 +- .../src/Driver/Draw/DrawRelocate.cpp | 28 +++++++++++++++---- .../Execution/src/Driver/Draw/HeapStages.cpp | 8 ++++++ 5 files changed, 35 insertions(+), 7 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index 852c7bc11724..0715d9dd663d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -73,6 +73,8 @@ void NoteHeapDirect(); void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const ShaderRecompiler::RecompileResult& expected, const ShaderRecompiler::ResourceCapture* expectedCapture = nullptr); std::uint64_t HeapStagesTaken(); +std::uint64_t HeapRingHitsVerified(); +std::uint64_t HeapRingHitsDiffering(); std::shared_ptr PatchedHeapResult(const ShaderRecompiler::RecompileResult& shared, const ShaderRecompiler::HeapStageWords& words); void VerifyHeapAccessor(const Graphics::CompiledShader& stage); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp index e1bdaf697623..027e6ad8610e 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp @@ -130,7 +130,7 @@ class Driver { static void FoldDrawOffsets(const ShaderRecompiler::RecompileResult& result, const DrawProgram& program, Pm4::DrawParameters& parameters); static std::optional ClassifyIndirectDraw(const ShaderRecompiler::RecompileResult& result, const Graphics::State& graphics, const DrawProgram& frontProgram, const std::shared_ptr& localDevice, Pm4::DrawParameters& drawParameters, bool traceIndirect); static void tagVariantRuns(DispatchVariant& variant, std::span regions, const ShaderRecompiler::SrtUserDataUse& use, bool eligible, std::uint32_t hiddenWords, std::span> supplied = {}); - static void tagUserValueWords(DispatchVariant& variant, const DrawProgram& program); + static void tagUserValueWords(DispatchVariant& variant, const DrawProgram& program, const ShaderRecompiler::HeapStageWords* heap = nullptr); static std::uint64_t relocatedContentKey(const RelocatableUserWord& word, std::uint32_t value, bool& readable); static void applyShaderDataPatches(DispatchVariant& variant); static std::string dumpRequest(std::uint64_t address, const ShaderRecompiler::RecompileRequest& request, std::string_view suffix = {}); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 2400ce71d11d..b38a841f0d1d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -380,7 +380,7 @@ void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawP std::stable_sort(regions.begin(), regions.end(), [](const ShaderRecompiler::MemoryRegion& a, const ShaderRecompiler::MemoryRegion& b) { return a.guestAddress < b.guestAddress; }); const bool relocatable = decodeReads[i].empty() && (!vertexInfos[i] || vertexInfos[i]->resourcesNum == 0); tagVariantRuns(*variant, regions, stageCapture.userDataUse, relocatable, programs[i].hiddenUserWords, stageCapture.supplied); - if (relocatable) tagUserValueWords(*variant, programs[i]); + if (relocatable && (stageCapture.heapWords == nullptr || variant->ringTemplate != nullptr)) tagUserValueWords(*variant, programs[i], stageCapture.heapWords.get()); if (drawStageDataHits() && stageCapture.capture != nullptr && !stageCapture.capture->readTrace.leaves.empty()) recordStageDataPositions(*variant, *stageCapture.capture, decodeReads[i]); if (traceDrawCache() && entry != nullptr && matched[i] == nullptr && i < entry->stages.size()) { const auto& variants = entry->stages[i]; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp index 50a32e557d8b..6c2e100c4f99 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp @@ -5,6 +5,7 @@ #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include #include #include @@ -61,14 +62,18 @@ std::uint64_t Driver::relocatedContentKey(const RelocatableUserWord& word, std:: return hash; } -void Driver::tagUserValueWords(DispatchVariant& variant, const DrawProgram& program) { +void Driver::tagUserValueWords(DispatchVariant& variant, const DrawProgram& program, const ShaderRecompiler::HeapStageWords* heap) { if (!drawRelocationEnabled() || variant.compiled == nullptr) return; const auto& compiled = *variant.compiled; const auto& forwarded = compiled.shaderDataUserWords; const auto users = std::min(program.userData.size(), 64); const auto bound = [&](std::uint32_t value) { std::size_t count = 0; - for (const auto& binding : compiled.bindings) count += static_cast(std::count(binding.guestDescriptor.begin(), binding.guestDescriptor.end(), value)); + for (const auto& binding : compiled.bindings) { + if (heap != nullptr && binding.role == ShaderRecompiler::DescriptorRole::ShaderData) continue; + const auto& words = Graphics::DrawGuestWords(compiled, heap, binding); + count += static_cast(std::count(words.begin(), words.end(), value)); + } return count; }; const auto elsewhere = [&](std::uint32_t index, std::uint32_t value) { @@ -115,16 +120,18 @@ void Driver::tagUserValueWords(DispatchVariant& variant, const DrawProgram& prog if (base == 0 || taken(index) || bound(base) != 1 || elsewhere(index, base)) continue; std::uint32_t binding = 0, word = 0; for (std::size_t b = 0; b < compiled.bindings.size(); ++b) { - const auto& descriptor = compiled.bindings[b].guestDescriptor; + if (heap != nullptr && compiled.bindings[b].role == ShaderRecompiler::DescriptorRole::ShaderData) continue; + const auto& descriptor = Graphics::DrawGuestWords(compiled, heap, compiled.bindings[b]); const auto found = std::find(descriptor.begin(), descriptor.end(), base); if (found == descriptor.end()) continue; binding = static_cast(b); word = static_cast(found - descriptor.begin()); } const auto& target = compiled.bindings[binding]; + const auto& targetWords = Graphics::DrawGuestWords(compiled, heap, target); const auto element = word / 4u; - const bool readOnly = target.role == ShaderRecompiler::DescriptorRole::GuestBuffers && target.guestDescriptor.size() == static_cast(target.count) * 4u && word % 4u == 0 && element < target.bufferWritten.size() && !target.bufferWritten[element] && (element >= target.bufferAtomic.size() || !target.bufferAtomic[element]); - if (!readOnly || target.guestDescriptor[word + 1] != program.userData[index + 1] || target.guestDescriptor[word + 2] != program.userData[index + 2] || readThrough(target.guestDescriptor.data() + word)) continue; + const bool readOnly = target.role == ShaderRecompiler::DescriptorRole::GuestBuffers && targetWords.size() == static_cast(target.count) * 4u && word % 4u == 0 && element < target.bufferWritten.size() && !target.bufferWritten[element] && (element >= target.bufferAtomic.size() || !target.bufferAtomic[element]); + if (!readOnly || targetWords[word + 1] != program.userData[index + 1] || targetWords[word + 2] != program.userData[index + 2] || readThrough(targetWords.data() + word)) continue; variant.valueWords |= std::uint64_t {1} << index; variant.valueSlots.push_back({index, binding, word}); const auto records = program.userData[index + 2]; @@ -363,6 +370,17 @@ void Driver::applyShaderDataPatches(DispatchVariant& variant) { for (const auto& [binding, word, value] : variant.descriptorPatches) { if (binding < rebased->bindings.size() && word < rebased->bindings[binding].guestDescriptor.size()) rebased->bindings[binding].guestDescriptor[word] = value; } + if (variant.ringTemplate != nullptr && !variant.descriptorPatches.empty()) { + auto ringTemplate = std::make_shared(*variant.ringTemplate); + if (ringTemplate->bindings.empty()) ringTemplate->bindings.resize(variant.compiled->bindings.size()); + for (const auto& [binding, word, value] : variant.descriptorPatches) { + if (binding >= ringTemplate->bindings.size()) continue; + auto& words = ringTemplate->bindings[binding]; + if (words.empty()) words = variant.compiled->bindings[binding].guestDescriptor; + if (word < words.size()) words[word] = value; + } + variant.ringTemplate = std::move(ringTemplate); + } variant.compiled = std::move(rebased); variant.shaderDataPatches.clear(); variant.descriptorPatches.clear(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 14fb2c93467d..64088b9649f2 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -659,6 +659,14 @@ std::uint64_t HeapStagesTaken() { return heapStages().load(); } +std::uint64_t HeapRingHitsVerified() { + return verifyCounts().ring.load(); +} + +std::uint64_t HeapRingHitsDiffering() { + return verifyCounts().ringDiffer.load(); +} + std::shared_ptr PatchedHeapResult(const ShaderRecompiler::RecompileResult& shared, const ShaderRecompiler::HeapStageWords& words) { auto result = std::make_shared(shared); From 7df371014243a9fcada6e81ff672e0d4790a85e1 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 2 Nov 2026 20:51:02 +0530 Subject: [PATCH 098/269] test(agc): run the user-data V# relocation test on the GPU heap Registers agc_driver_draw_relocate_user_values_gpu_heap with APS5_VERIFY_GPU_HEAP and APS5_VERIFY_DRAW_ENTRIES, so relocated heap draws are checked against a fresh capture: the draws must reach the heap stage path, ring hits must be verified with no differences, and each old V# buffer is poisoned after its draw so a stale base renders wrong. Adds a forwarded-base draw case whose shader reads the V# base, and unit checks that heap and default tag the same user words. --- ...iver_draw_relocate_user_values_tests.cmake | 4 + .../execution/DrawRelocateUserValues.cpp | 73 +++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_relocate_user_values_tests.cmake diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_relocate_user_values_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_relocate_user_values_tests.cmake new file mode 100644 index 000000000000..a7861b87515a --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_relocate_user_values_tests.cmake @@ -0,0 +1,4 @@ +if(BUILD_TESTING) + agc_add_env_test(agc_driver_draw_relocate_user_values_gpu_heap agc_driver_draw_relocate_user_values_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_VERIFY_DRAW_ENTRIES=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRelocateUserValues.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRelocateUserValues.cpp index 1c2407762fac..e89a689ee1a6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRelocateUserValues.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRelocateUserValues.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" @@ -9,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -163,6 +165,30 @@ void BufferValueWordsArePatchedInTheirBinding() { Require(sharedCount->valueSlots.size() == 1u && sharedCount->valueSlots[0] == std::array{4u, 0u, 0u}, "a V# whose record count builds a second descriptor recorded a record-count patch"); const auto ownCount = shared(descriptor[2] + 1u); Require((ownCount->valueWords >> 6u & 1u) != 0u, "a record count used by one descriptor only was not tagged next to an independent second descriptor"); + + const auto tagged = [&](bool forwardedAsPushData, bool shaderDataCopy, bool heapMode) { + auto compiled = result(false); + if (!shaderDataCopy) { + compiled->pushConstants.resize(sizeof(std::uint32_t)); + std::memcpy(compiled->pushConstants.data(), &descriptor[0], sizeof(std::uint32_t)); + } + if (forwardedAsPushData) compiled->shaderDataUserWords = {4u}; + const std::vector userWords(program.userData.begin(), program.userData.end()); + if (shaderDataCopy) compiled->bindings.push_back(ShaderRecompiler::DescriptorBinding{ShaderRecompiler::DescriptorKind::UniformBuffer, ShaderRecompiler::DescriptorRole::ShaderData, 1, 0, 1, heapMode ? std::vector(userWords.size(), 0u) : userWords}); + const auto variant = Variant(compiled); + ShaderRecompiler::HeapStageWords words; + words.userData = userWords; + words.bindings = {descriptor, {}}; + Driver::tagUserValueWords(*variant, program, heapMode ? &words : nullptr); + return variant->valueWords; + }; + for (const auto forwardedAsPushData : {false, true}) { + const auto expected = forwardedAsPushData ? std::uint64_t {(1u << 4u) | (1u << 6u)} : std::uint64_t {0}; + Require(tagged(forwardedAsPushData, false, false) == expected, std::string("default: a V# base ") + (forwardedAsPushData ? "forwarded as push data from its own user word" : "also present in push data but not forwarded from it") + " was tagged as " + std::to_string(tagged(forwardedAsPushData, false, false))); + Require(tagged(forwardedAsPushData, false, true) == tagged(forwardedAsPushData, false, false), std::string("heap and default disagree on a V# base ") + (forwardedAsPushData ? "forwarded as push data" : "that is not forwarded") + " (heap " + std::to_string(tagged(forwardedAsPushData, false, true)) + ", default " + std::to_string(tagged(forwardedAsPushData, false, false)) + ")"); + } + Require(tagged(false, true, false) == 0u, "default: a V# base copied into a shader data binding was tagged"); + Require(tagged(false, true, true) == ((1u << 4u) | (1u << 6u)), "heap: the user-word copy in shader data hid a V# from tagging (mask " + std::to_string(tagged(false, true, true)) + ")"); } alignas(256) constexpr std::array VertexCode{ @@ -177,6 +203,10 @@ alignas(256) constexpr std::array OwnCountPixelCode{ 0xbe880304u, 0xbe890305u, 0xbe8a0306u, 0xbe8b0307u, 0xf4200300u, 0xfa000000u, 0xf4200344u, 0xfa000004u, 0xbf8cc07fu, 0x7e00020cu, 0x7e02020du, 0x7e040280u, 0x7e0602f2u, 0xf800180fu, 0x03020100u, 0xbf810000u, }; +alignas(256) constexpr std::array ForwardedBasePixelCode{ + 0xbe880304u, 0xbe890305u, 0xbe8a0306u, 0xbe8b0307u, 0xf4200300u, 0xfa000000u, 0xf4200344u, 0xfa000004u, + 0xbf8cc07fu, 0x7e00020cu, 0x7e02020du, 0x7e040280u, 0x7e062200u, 0xf800180fu, 0x03020100u, 0xbf810000u, +}; alignas(256) std::array ColorMemory{}; struct Header { @@ -187,6 +217,7 @@ struct Header { alignas(8) Header VertexHeader{}; alignas(8) Header SharedCountHeader{}; alignas(8) Header OwnCountHeader{}; +alignas(8) Header ForwardedBaseHeader{}; void Registered(Header& header, const std::uint32_t* code, std::size_t bytes, std::uint8_t type) { header.shader.file_header = 0x34333231u; @@ -266,12 +297,21 @@ void MovedRecordCountsReachEveryDescriptor(bool sharedCount) { return std::array{Low(first[i].data()), High(first[i].data()), sharedCount ? records : 12u, 0x20077facu, Low(second[i].data()), High(second[i].data()), sharedCount ? 4u : records, 0x20077facu}; }; const auto start = Driver::Get().DrawCacheCounters(); + const auto heapStart = AgcDriver::DriverDetail::HeapStagesTaken(); + const auto ringStart = AgcDriver::DriverDetail::HeapRingHitsVerified(); for (std::size_t i = 0; i < 5; ++i) { const auto pixel = DrawWithUserData(pixelCode, userData(i, 4u)); Require(pixel == std::array{255, 0, 0, 255}, mode + ": a draw whose second descriptor holds one dword drew " + std::to_string(pixel[0]) + "," + std::to_string(pixel[1]) + "," + std::to_string(pixel[2]) + "," + std::to_string(pixel[3])); + first[i] = {0.0f, 0.0f, 1.0f, 0.0f}; + second[i] = {1.0f, 0.0f, 1.0f, 0.0f}; } const auto taught = Driver::Get().DrawCacheCounters(); Require(taught.hits > start.hits, mode + ": draws whose descriptors moved to equal contents never reused the cached draw (" + std::to_string(taught.lookups - start.lookups) + " lookups)"); + if (std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr) { + Require(AgcDriver::DriverDetail::HeapStagesTaken() > heapStart, mode + ": the draws never reached the GPU heap"); + Require(AgcDriver::DriverDetail::HeapRingHitsVerified() > ringStart, mode + ": no relocated ring hit was compared with a fresh capture"); + Require(AgcDriver::DriverDetail::HeapRingHitsDiffering() == 0, mode + ": a relocated ring hit's rebuilt words differ from a fresh capture"); + } const auto pixel = DrawWithUserData(pixelCode, userData(5, 8u)); Require(pixel == std::array{255, 255, 0, 255}, mode + ": after the record count grew to two dwords, the second descriptor's second dword drew " + std::to_string(pixel[1]) + " (a reused draw kept the earlier count)"); if (!sharedCount) { @@ -280,6 +320,38 @@ void MovedRecordCountsReachEveryDescriptor(bool sharedCount) { } } +struct alignas(256) Block { + std::array, 16> entries{}; +}; + +void ForwardedBaseWordsFollowRelocatedDraws() { + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + Registered(ForwardedBaseHeader, ForwardedBasePixelCode.data(), sizeof(ForwardedBasePixelCode), 1); + static std::array blocks{}; + alignas(16) static std::array, 8> other{}; + for (auto& block : blocks) { + for (auto& entry : block.entries) entry = {1.0f, 0.0f, 0.0f, 0.0f}; + } + for (auto& entry : other) entry = {0.0f, 1.0f, 0.0f, 0.0f}; + const auto ringStart = AgcDriver::DriverDetail::HeapRingHitsVerified(); + const auto start = Driver::Get().DrawCacheCounters(); + for (std::size_t i = 0; i < blocks.size(); ++i) { + const bool lowByteSet = i % 2 == 1; + const auto* first = blocks[i].entries[lowByteSet ? 1 : 0].data(); + const auto* second = other[i % other.size()].data(); + const std::array words{Low(first), High(first), 4u, 0x20077facu, Low(second), High(second), 4u, 0x20077facu}; + const auto pixel = DrawWithUserData(ForwardedBasePixelCode.data(), words); + const std::array expected{255, 0, 0, static_cast(lowByteSet ? 255 : 0)}; + Require(pixel == expected, "draw " + std::to_string(i) + " read a stale forwarded V# base word: drew " + std::to_string(pixel[0]) + "," + std::to_string(pixel[1]) + "," + std::to_string(pixel[2]) + "," + std::to_string(pixel[3]) + ", expected alpha " + std::to_string(expected[3])); + } + const auto after = Driver::Get().DrawCacheCounters(); + Require(after.hits > start.hits, "draws that moved only their first V# never reused the cached draw, so the forwarded base word was never rebuilt for a hit"); + if (std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr) { + Require(AgcDriver::DriverDetail::HeapRingHitsVerified() > ringStart, "no relocated ring hit of the forwarded-base draws was compared with a fresh capture"); + Require(AgcDriver::DriverDetail::HeapRingHitsDiffering() == 0, "a relocated ring hit of the forwarded-base draws differs from a fresh capture"); + } +} + void BufferValueWordsKeyByNothing() { const RelocatableUserWord word{4u, {}, true, 0u}; bool readable = true; @@ -301,6 +373,7 @@ int main() { } MovedRecordCountsReachEveryDescriptor(true); MovedRecordCountsReachEveryDescriptor(false); + ForwardedBaseWordsFollowRelocatedDraws(); AgcDriverShutdown_nid_postfix(); std::cout << "User-data V# values and fetch subroutine pointers relocate\n"; return 0; From ff64a9a09fc495b8b5d33cfeb74974f9d47a8f34 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 2 Nov 2026 21:53:07 +0530 Subject: [PATCH 099/269] fix(shader): write shader requests as serialization version 55 Version 53 is taken by #12662 (and #12980 on top of it) and #11551 takes 54, so the heap profile tail moves to 55: it is read at version 55 and later, versions 52 to 54 default it, and the byte-exact fixtures follow. --- .../libSceAgcDriver/tests/ShaderMemory.cpp | 12 ++--- .../ControlFlow/src/RequestSerializer.cpp | 6 +-- .../tests/RequestSerializerTests.cpp | 52 ++++++++++--------- 3 files changed, 36 insertions(+), 34 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 7553ef039d2c..66d2302155fe 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -7399,7 +7399,7 @@ void verifyPixelRequestSerialization() { minimal.context.pixel->layerExported = true; minimal.context.pixel->ditheredAlphaToCoverage = true; const auto encoded = serializer.Serialize(minimal); - require(requestPrefix(encoded, 8u) == "NVNQQTUAAAA=", "new requests did not use serialization version 53"); + require(requestPrefix(encoded, 8u) == "NVNQQTcAAAA=", "new requests did not use serialization version 55"); auto withBarycentric = minimal; withBarycentric.target.fragmentBarycentricBuiltins = true; require(serializer.Deserialize(serializer.Serialize(withBarycentric)).request.target.fragmentBarycentricBuiltins && !serializer.Deserialize(encoded).request.target.fragmentBarycentricBuiltins, "barycentric built-ins were lost in serialization"); @@ -7520,7 +7520,7 @@ void verifyPixelRequestSerialization() { for (std::size_t bytes = 0; bytes < 45u; ++bytes) { expectFailure([&] { static_cast(serializer.Deserialize(requestPrefix(encoded, mappingOffset + bytes))); }, "truncated data", "a truncated pixel mapping, packing, dual-source, alpha-to-coverage, stencil reference export flag, primitive class, layer export, dither or front-face flag, quad pixel mask or quad sample mask was accepted"); } - for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQTYAAAA="}) { + for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQTgAAAA="}) { expectFailure([&] { static_cast(serializer.Deserialize(unsupported)); }, "serialization version", "an unsupported request version was accepted"); } static constexpr std::string_view version18Request{ @@ -7639,9 +7639,9 @@ void verifyDepthExportClamp() { const auto both = RequestSerializer{}.Deserialize(RequestSerializer{}.Serialize(tail)); require(both.request.target.largePixelFunctionLdsBuffer && both.request.target.pixelFunctionStorageDwords == 2048u && both.request.context.pixel->depthExportMin == 0.25f && both.request.context.pixel->depthExportMax == 0.75f, - "depth export: a version 53 request lost the bounds or the version 45 target tail"); + "depth export: a version 55 request lost the bounds or the version 45 target tail"); auto bytes = decodeBase64(RequestSerializer{}.Serialize(tail)); - require(bytes.size() > 8u && bytes[4] == 53u, "depth export: a depth exporting request did not use serialization version 53"); + require(bytes.size() > 8u && bytes[4] == 55u, "depth export: a depth exporting request did not use serialization version 55"); static constexpr std::array boundBytes{0x00u, 0x00u, 0x80u, 0x3eu, 0x00u, 0x00u, 0x40u, 0x3fu}; const auto found = std::search(bytes.begin(), bytes.end(), boundBytes.begin(), boundBytes.end()); require(found != bytes.end() && std::search(found + 1, bytes.end(), boundBytes.begin(), boundBytes.end()) == bytes.end(), @@ -7669,7 +7669,7 @@ void verifyDepthExportClamp() { ditheredPixel.ditheredAlphaSamples = 2u; dithered.context.pixel = ditheredPixel; auto ditheredBytes = decodeBase64(RequestSerializer{}.Serialize(dithered)); - require(ditheredBytes.size() > 8u && ditheredBytes[4] == 53u, "a two-sample dithered request did not use serialization version 53"); + require(ditheredBytes.size() > 8u && ditheredBytes[4] == 55u, "a two-sample dithered request did not use serialization version 55"); if (depthExport) { const auto bounds = std::search(ditheredBytes.begin(), ditheredBytes.end(), boundBytes.begin(), boundBytes.end()); require(bounds != ditheredBytes.end(), "a two-sample dithered depth exporting request lacks the clamp bounds"); @@ -8069,7 +8069,7 @@ void verifyMergedHullConfiguration() { require(!serializer.Deserialize(separate).request.graphics->tessellation->mergedHull, "a separate hull configuration was read as merged"); constexpr std::size_t pointTailBytes = 13u; auto legacy = decodeBase64(merged); - require(legacy.size() > 57u + pointTailBytes && legacy[4] == 53u, "a merged hull request did not use serialization version 53"); + require(legacy.size() > 57u + pointTailBytes && legacy[4] == 55u, "a merged hull request did not use serialization version 55"); legacy.resize(legacy.size() - sizeof(std::uint32_t) - 4u - pointTailBytes - 12u); legacy.pop_back(); legacy.pop_back(); diff --git a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp index 36164de1f050..b2b07b7feeea 100644 --- a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp +++ b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp @@ -898,7 +898,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const std::string buffer; Writer writer(buffer); writer.WriteU32(0x41505335u); - writer.WriteU32(53u); + writer.WriteU32(55u); writeShaderBinary(writer, request.shader); writeGuestContext(writer, request.context); writeSpirvTarget(writer, request.target); @@ -959,7 +959,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const Reader reader(decoded); if (reader.ReadU32() != 0x41505335u) throw std::runtime_error("invalid recompile request signature"); const auto version = reader.ReadU32(); - if (version < 1u || version > 53u || version == 50u) throw std::runtime_error("unsupported recompile request serialization version"); + if (version < 1u || version > 55u || version == 50u) throw std::runtime_error("unsupported recompile request serialization version"); DeserializedRequest result{}; result.request.shader = readShaderBinary(reader, result.shaderCode, result.shaderHeader); result.request.context = readGuestContext(reader, result, version); @@ -1021,7 +1021,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const if (version >= 48u) result.request.target.fragmentBarycentricBuiltins = reader.ReadBool(); if (version >= 51u) result.request.target.tessellationEvaluationSubgroups = reader.ReadBool(); if (version >= 52u) result.request.target.hostInterpolationFirst = reader.ReadBool(); - if (version >= 53u) { + if (version >= 55u) { result.request.target.gpuResolvedImages = reader.ReadBool(); result.request.target.descriptorMemory = reader.ReadBool(); result.request.target.heapDataUniformDwords = reader.ReadU32(); diff --git a/core/shader/recompiler/tests/RequestSerializerTests.cpp b/core/shader/recompiler/tests/RequestSerializerTests.cpp index d22008feb152..8413f327c4ba 100644 --- a/core/shader/recompiler/tests/RequestSerializerTests.cpp +++ b/core/shader/recompiler/tests/RequestSerializerTests.cpp @@ -174,8 +174,8 @@ std::string EncodeBase64(const std::vector& bytes) { return text; } -std::string EncodeWithDefaultVersion53Tail(std::vector bytes) { - bytes[4] = 53u; +std::string EncodeWithDefaultVersion55Tail(std::vector bytes) { + bytes[4] = 55u; bytes.insert(bytes.end(), 12u, 0u); return EncodeBase64(bytes); } @@ -218,12 +218,14 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { Require(replay.request.target.heapDataUniformDwords == profile.heapDataUniformDwords); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 53u && bytes.size() > 12u); + Require(bytes[4] == 55u && bytes.size() > 12u); bytes.resize(bytes.size() - 12u); - bytes[4] = 52u; - const auto older = serializer.Deserialize(EncodeBase64(bytes)).request.target; - Require(!older.gpuResolvedImages && !older.descriptorMemory && older.heapDataUniformDwords == 0u); - bytes[4] = 53u; + for (const std::uint8_t version : {52u, 53u, 54u}) { + bytes[4] = version; + const auto older = serializer.Deserialize(EncodeBase64(bytes)).request.target; + Require(!older.gpuResolvedImages && !older.descriptorMemory && older.heapDataUniformDwords == 0u); + } + bytes[4] = 55u; bool truncated = false; try { static_cast(serializer.Deserialize(EncodeBase64(bytes))); @@ -264,7 +266,7 @@ void VerifyKeyedTargetFields(const ShaderRecompiler::RequestSerializer& serializ for (std::size_t index = 0; index < fields.size(); ++index) Require(replay.request.target.*fields[index] == (chosen == fields.size() || index == chosen)); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 53u && bytes.size() > 12u); + Require(bytes[4] == 55u && bytes.size() > 12u); bytes.resize(bytes.size() - 12u); bytes[4] = 52u; const auto older = serializer.Deserialize(EncodeBase64(bytes)).request.target; @@ -412,7 +414,7 @@ int main() { upgraded.push_back(0u); upgraded.push_back(1u); upgraded.push_back(0u); - Require(serializer.Serialize(request) == EncodeWithDefaultVersion53Tail(upgraded)); + Require(serializer.Serialize(request) == EncodeWithDefaultVersion55Tail(upgraded)); auto truncated = bytes; truncated.pop_back(); bool rejected = false; @@ -426,7 +428,7 @@ int main() { auto vertex23 = bytes; vertex23[4] = 23u; const auto vertexReplay = serializer.Deserialize(EncodeBase64(vertex23)); - Require(serializer.Serialize(vertexReplay.request) == EncodeWithDefaultVersion53Tail(upgraded)); + Require(serializer.Serialize(vertexReplay.request) == EncodeWithDefaultVersion55Tail(upgraded)); continue; } for (const bool layer : {false, true}) { @@ -458,7 +460,7 @@ int main() { layered.push_back(0u); layered.push_back(1u); layered.push_back(0u); - Require(serializer.Serialize(layerReplay.request) == EncodeWithDefaultVersion53Tail(layered)); + Require(serializer.Serialize(layerReplay.request) == EncodeWithDefaultVersion55Tail(layered)); } } } @@ -489,7 +491,7 @@ int main() { bytes.push_back(0u); bytes.push_back(1u); bytes.push_back(0u); - Require(serializer.Serialize(replay.request) == EncodeWithDefaultVersion53Tail(bytes)); + Require(serializer.Serialize(replay.request) == EncodeWithDefaultVersion55Tail(bytes)); auto truncated23 = DecodeBase64(encoded23); truncated23.pop_back(); @@ -628,13 +630,13 @@ int main() { upgraded.push_back(0u); upgraded.push_back(1u); upgraded.push_back(0u); - Require(serializer.Serialize(request) == EncodeWithDefaultVersion53Tail(upgraded)); + Require(serializer.Serialize(request) == EncodeWithDefaultVersion55Tail(upgraded)); const auto replay38 = serializer.Deserialize(EncodeBase64(main38)); Require(replay38.request.graphics.has_value() && replay38.request.graphics->tessellation.has_value() == fixture.tessellation); Require(!fixture.tessellation || (!replay38.request.graphics->tessellation->mergedHull && replay38.request.graphics->tessellation->primitiveGroupSize == 37u && replay38.request.graphics->tessellation->breakAtInstance)); Require(replay38.request.graphics->draw.indexAddress == 0xabcdef3400u && replay38.request.graphics->draw.indexCount == 57u && replay38.request.graphics->draw.indexElementBytes == 4u && replay38.request.graphics->draw.instanceCount == 9u); Require(replay38.request.target.float16DenormPreserve == preserve); - Require(serializer.Serialize(replay38.request) == EncodeWithDefaultVersion53Tail(upgraded)); + Require(serializer.Serialize(replay38.request) == EncodeWithDefaultVersion55Tail(upgraded)); if (fixture.tessellation) { for (const bool merged : {false, true}) { auto pointed = request; @@ -643,9 +645,9 @@ int main() { pointed.context.vertex->pointSize = 3.0f; pointed.context.vertex->pointSizeMin = 1.0f; pointed.context.vertex->pointSizeMax = 8.0f; - auto version53 = DecodeBase64(serializer.Serialize(pointed)); - Require(version53.size() > 30u && version53[4] == 53u); - auto version52 = version53; + auto version55 = DecodeBase64(serializer.Serialize(pointed)); + Require(version55.size() > 30u && version55[4] == 55u); + auto version52 = version55; version52.resize(version52.size() - 12u); Require(version52.back() == 0u); auto version51 = version52; @@ -670,7 +672,7 @@ int main() { version43.pop_back(); version43[4] = 43u; const auto replay43 = serializer.Deserialize(EncodeBase64(version43)); - Require(serializer.Serialize(replay43.request) == EncodeBase64(version53)); + Require(serializer.Serialize(replay43.request) == EncodeBase64(version55)); Require(replay43.request.graphics->tessellation->mergedHull == merged && replay43.request.context.vertex->pointList && replay43.request.context.vertex->pointSize == 3.0f && replay43.request.context.vertex->pointSizeMin == 1.0f && replay43.request.context.vertex->pointSizeMax == 8.0f); auto version42 = version43; version42.resize(version42.size() - 13u); @@ -711,7 +713,7 @@ int main() { main25.push_back(0u); main25.push_back(1u); main25.push_back(0u); - Require(serializer.Serialize(replay25.request) == EncodeWithDefaultVersion53Tail(main25)); + Require(serializer.Serialize(replay25.request) == EncodeWithDefaultVersion55Tail(main25)); } } } @@ -728,7 +730,7 @@ int main() { const auto replay = serializer.Deserialize(encoded); Require(replay.request.target.float16DenormPreserve == preserve && replay.request.target.float32FlushToZero == !preserve && replay.request.target.float32DenormPreserve == preserve && replay.request.target.largePixelFunctionLdsBuffer == !preserve && replay.request.target.pixelFunctionStorageDwords == request.target.pixelFunctionStorageDwords); auto bytes = DecodeBase64(encoded); - Require(bytes.size() >= 8u && bytes[4] == 53u && bytes[5] == 0u && bytes[6] == 0u && bytes[7] == 0u); + Require(bytes.size() >= 8u && bytes[4] == 55u && bytes[5] == 0u && bytes[6] == 0u && bytes[7] == 0u); auto version40 = bytes; version40.resize(version40.size() - 13u); version40.resize(version40.size() - sizeof(std::uint32_t)); @@ -741,7 +743,7 @@ int main() { const auto replay40 = serializer.Deserialize(EncodeBase64(version40)); Require(!replay40.request.target.float32DenormPreserve && replay40.request.target.float32FlushToZero == !preserve); auto future = bytes; - future[4] = 54u; + future[4] = 56u; bool futureRejected = false; try { static_cast(serializer.Deserialize(EncodeBase64(future))); @@ -876,7 +878,7 @@ int main() { Require(!replayLegacy.request.context.vertex->pointList && replayLegacy.request.context.vertex->pointSize == 1.0f); Require(replayLegacy.request.context.vertex->pointSizeMin == 0.0f && replayLegacy.request.context.vertex->pointSizeMax == 0.0f); const auto upgradedLegacy = DecodeBase64(serializer.Serialize(replayLegacy.request)); - Require(upgradedLegacy[4] == 53u && upgradedLegacy.size() == legacy.size() + (version >= 36u ? 35u : version >= 35u ? 36u : 41u)); + Require(upgradedLegacy[4] == 55u && upgradedLegacy.size() == legacy.size() + (version >= 36u ? 35u : version >= 35u ? 36u : 41u)); } } @@ -982,7 +984,7 @@ int main() { domain.target.tessellationEvaluationSubgroups = subgroups; const auto encoded = serializer.Serialize(domain); auto bytes = DecodeBase64(encoded); - Require(bytes.size() > 8u && bytes[4] == 53u && bytes[bytes.size() - 14u] == (subgroups ? 1u : 0u)); + Require(bytes.size() > 8u && bytes[4] == 55u && bytes[bytes.size() - 14u] == (subgroups ? 1u : 0u)); Require(serializer.Deserialize(encoded).request.target.tessellationEvaluationSubgroups == subgroups); bytes.resize(bytes.size() - 12u); bytes.pop_back(); @@ -1003,7 +1005,7 @@ int main() { upgraded[4] = 52u; upgraded.push_back(1u); upgraded.push_back(0u); - Require(serializer.Serialize(replay49.request) == EncodeWithDefaultVersion53Tail(upgraded)); + Require(serializer.Serialize(replay49.request) == EncodeWithDefaultVersion55Tail(upgraded)); for (auto skipped : {bytes, upgraded}) { skipped[4] = 50u; bool skippedRejected = false; @@ -1022,7 +1024,7 @@ int main() { const auto replay = serializer.Deserialize(hostFirstEncoded[hostFirst]); Require(replay.request.target.hostInterpolationFirst == hostFirst && serializer.Serialize(replay.request) == hostFirstEncoded[hostFirst]); auto bytes = DecodeBase64(hostFirstEncoded[hostFirst]); - Require(bytes[4] == 53u && bytes[bytes.size() - 13u] == (hostFirst ? 1u : 0u)); + Require(bytes[4] == 55u && bytes[bytes.size() - 13u] == (hostFirst ? 1u : 0u)); bytes.resize(bytes.size() - 13u); bytes[4] = 51u; Require(!serializer.Deserialize(EncodeBase64(bytes)).request.target.hostInterpolationFirst); From 8e07d51c12264881db9f84a5dd3c3905df0310d7 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 3 Nov 2026 10:41:10 +0530 Subject: [PATCH 100/269] fix(shader): keep GPU-mode compute scratch in function storage The compute scratch pool from #12764 sizes itself with OpArrayLength on a storage buffer at descriptor set 2. A GPU-mode stage maps its buffers onto VK_EXT_descriptor_heap through pushed addresses, which cannot carry an array length (VUID-VkPipelineShaderStageCreateInfo-pNext-11378), so every GPU-mode compute stage with scratch was refused by the heap and recompiled in CPU mode. GPU-mode compute stages keep scratch in function storage, as they did before the merge; the scratch pool test also runs in heap mode. --- .../cmake/agc_driver_scratch_pool_tests.cmake | 3 ++ .../tests/execution/ScratchPool.cpp | 39 ++++++++++++++----- .../src/SpirvMemory/SpirvScratchPool.cpp | 2 +- 3 files changed, 33 insertions(+), 11 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_scratch_pool_tests.cmake diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_scratch_pool_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_scratch_pool_tests.cmake new file mode 100644 index 000000000000..73356a9c5815 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_scratch_pool_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_scratch_pool) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp index 0359abebcc3a..24cdb0dd1e54 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp @@ -244,14 +244,16 @@ struct Facts { bool functionArrayAccess = false; }; -Facts Inspect(std::span words) { +Facts Inspect(const ShaderRecompiler::RecompileResult& result) { + const std::span words(result.spirv.data(), result.spirv.size()); + const auto poolSet = result.gpuResolvedImages ? ~0u : ShaderRecompiler::ScratchPoolDescriptorSet; Facts facts; std::set arrays, pointers, variables; for (std::size_t cursor = 5; cursor < words.size();) { const auto count = words[cursor] >> 16u; const auto op = words[cursor] & 0xffffu; Require(count != 0u, "scratch pool: malformed SPIR-V"); - if (op == spv::OpDecorate && words[cursor + 2u] == spv::DecorationDescriptorSet && words[cursor + 3u] == ShaderRecompiler::ScratchPoolDescriptorSet) facts.poolBinding = true; + if (op == spv::OpDecorate && words[cursor + 2u] == spv::DecorationDescriptorSet && words[cursor + 3u] == poolSet) facts.poolBinding = true; if (op == spv::OpTypeArray) arrays.insert(words[cursor + 1u]); if (op == spv::OpTypePointer && words[cursor + 2u] == spv::StorageClassFunction && arrays.contains(words[cursor + 3u])) pointers.insert(words[cursor + 1u]); if (op == spv::OpVariable && pointers.contains(words[cursor + 1u])) variables.insert(words[cursor + 2u]); @@ -261,15 +263,23 @@ Facts Inspect(std::span words) { return facts; } +void RequireHeapPipeline(const AgcDriver::VulkanDevice& device, const ShaderRecompiler::RecompileResult& result, std::uint64_t before, const std::string& name) { + if (std::getenv("APS5_GPU_HEAP") == nullptr) return; + Require(result.gpuResolvedImages, name + ": the scratch program is not GPU mode"); + Require(device.DescriptorHeapComputePipelines() > before, name + ": the scratch program did not take the descriptor heap"); +} + ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const Words& code, std::vector& userData, std::uint32_t waveSize, std::uint32_t threads, bool groupId, std::uint32_t scratchDwords) { const std::span codeSpan(code); const std::array memory{{{reinterpret_cast(codeSpan.data()), std::as_bytes(codeSpan)}}}; ShaderRecompiler::ShaderComputeStageInfo compute{{threads, 1, 1}, 0, {groupId, false, false}, false, 1}; compute.scratchDwords = scratchDwords; + auto target = device.Target(); + target.gpuResolvedImages = device.ComputeTarget(waveSize).gpuResolvedImages; ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, reinterpret_cast(codeSpan.data()), codeSpan, 0, {}}, {waveSize, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + target, {0, 0, 0, 128} }; request.useCache = false; @@ -294,11 +304,14 @@ void RunAlias(AgcDriver::VulkanDevice& device, Form form, bool atomic, std::uint std::copy(tableDescriptor.begin(), tableDescriptor.end(), userData.begin() + 4); const auto code = AliasKernel(form, atomic); const auto result = Compile(device, code, userData, waveSize, waveSize, false, AliasScratchDwords); - const auto facts = Inspect(std::span(result.spirv.data(), result.spirv.size())); - Require(facts.poolBinding && result.scratchPoolSlotDwords != 0u, name + ": the scratch program has no scratch pool binding"); - Require(!facts.functionArrayAccess, name + ": the scratch program indexes a Function array"); + const auto facts = Inspect(result); + const bool pooled = !result.gpuResolvedImages; + Require(facts.poolBinding == pooled && (result.scratchPoolSlotDwords != 0u) == pooled, name + ": the scratch pool binding does not match the stage's mode"); + Require(!pooled || !facts.functionArrayAccess, name + ": the scratch program indexes a Function array"); + const auto heapPipelines = device.DescriptorHeapComputePipelines(); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); + RequireHeapPipeline(device, result, heapPipelines, name); for (std::uint32_t lane = 0; lane < waveSize; ++lane) { const auto first = output[lane * 8u]; const auto second = output[lane * 8u + 1u]; @@ -325,9 +338,11 @@ void RunCallee(AgcDriver::VulkanDevice& device, std::uint32_t waveSize) { std::copy(tableDescriptor.begin(), tableDescriptor.end(), userData.begin() + 4); const auto code = CalleeKernel(); const auto result = Compile(device, code, userData, waveSize, waveSize, false, AliasScratchDwords); - Require(result.scratchPoolSlotDwords != 0u, name + ": the scratch program has no scratch pool binding"); + Require((result.scratchPoolSlotDwords != 0u) == !result.gpuResolvedImages, name + ": the scratch pool binding does not match the stage's mode"); + const auto heapPipelines = device.DescriptorHeapComputePipelines(); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); + RequireHeapPipeline(device, result, heapPipelines, name); for (std::uint32_t lane = 0; lane < waveSize; ++lane) { Require(output[lane * 8u] == OperandA(lane), name + ": lane " + std::to_string(lane) + " read " + Hex(output[lane * 8u]) + " back, expected " + Hex(OperandA(lane))); } @@ -343,7 +358,7 @@ void RunPlain(AgcDriver::VulkanDevice& device) { std::copy(tableDescriptor.begin(), tableDescriptor.end(), userData.begin() + 4); const auto code = PlainKernel(); const auto result = Compile(device, code, userData, 32u, 32u, false, 0u); - const auto facts = Inspect(std::span(result.spirv.data(), result.spirv.size())); + const auto facts = Inspect(result); Require(!facts.poolBinding && result.scratchPoolSlotDwords == 0u, "scratch pool: a program without scratch got a scratch pool binding"); } @@ -477,9 +492,12 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; const bool wave64 = device->Target().subgroupSize >= 32u; + const bool pooled = !device->ComputeTarget(32u).gpuResolvedImages; RunPlain(*device); - RunDiscardedInitialization(*device); - RunEviction(*device); + if (pooled) { + RunDiscardedInitialization(*device); + RunEviction(*device); + } for (const std::uint32_t waveSize : {32u, 64u}) { if (waveSize == 64u && !wave64) continue; for (const Form form : {Form::Table, Form::Literal, Form::Computed}) { @@ -487,6 +505,7 @@ int main() { RunAlias(*device, form, true, waveSize); } RunCallee(*device, waveSize); + if (!pooled) continue; RunContention(*device, "isolation", ContentionKernel(waveSize), waveSize, false); RunContention(*device, "divergent exit", DivergentExitKernel(waveSize), waveSize, true); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvScratchPool.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvScratchPool.cpp index cf40d62fc2ef..0b84252f141e 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvScratchPool.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvScratchPool.cpp @@ -49,7 +49,7 @@ std::uint32_t LinearWorkgroupId(SpirvEmitterState& state) { } bool ScratchPoolActive(const SpirvEmitterState& state) { - return state.requirements.functionScratch && state.program.Resources().stage == IrShaderStage::Compute; + return state.requirements.functionScratch && state.program.Resources().stage == IrShaderStage::Compute && !state.gpuResolvedImages; } std::uint32_t ScratchPoolSlotDwords(const SpirvEmitterState& state) { From c2747b936709f1675033ad7eab123b4b297a1424 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 3 Nov 2026 11:10:39 +0530 Subject: [PATCH 101/269] fix(agc): clamp compacted indices by the draw's own heap vertex attributes The indirect and restart-compacted index path computed the zero-fetch clamp from the shared program's vertex attributes. A heap stage serves many draws from one program, and each draw's vertex buffers live in its heap words, so a later draw's indices were clamped by the first draw's buffer size and fetched the wrong vertex. The path now uses DrawVertexAttributes() like the other two index paths. --- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 2 +- ...agc_driver_draw_offset_indices_tests.cmake | 8 ++++++ .../tests/execution/DrawOffsetIndices.cpp | 27 +++++++++++++++++-- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 3bcf4cf08801..f2e1208b49f6 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1697,7 +1697,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P const bool restartLeft = draw.indirect.has_value(); auto highest = HighestDrawIndex(kept, draw.indexSize, restartLeft); constexpr std::uint32_t ZeroFetchSlack = 0x10000u; - if (const auto zeroFrom = highest && !shaders.front().program->vertexAttributes.empty() ? ZeroFetchVertex(shaders.front().program->vertexAttributes) : std::nullopt) { + if (const auto zeroFrom = highest && !DrawVertexAttributes(shaders.front()).empty() ? ZeroFetchVertex(DrawVertexAttributes(shaders.front())) : std::nullopt) { const auto limit = *zeroFrom > draw.firstVertex ? *zeroFrom - draw.firstVertex : 0u; if (*highest >= limit && *highest - limit >= ZeroFetchSlack) highest = ClampDrawIndices(kept, draw.indexSize, restartLeft, limit); } diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_offset_indices_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_offset_indices_tests.cmake index da26ba76dbc0..554bfae39456 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_offset_indices_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_offset_indices_tests.cmake @@ -16,4 +16,12 @@ if(BUILD_TESTING) endif() endforeach() endforeach() + add_test(NAME agc_driver_draw_heap_attributes_compact_restart COMMAND agc_driver_draw_offset_indices_tests heap-attributes) + set_tests_properties(agc_driver_draw_heap_attributes_compact_restart PROPERTIES + ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" TIMEOUT 45 SKIP_RETURN_CODE 77 + WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_draw_heap_attributes_compact_restart PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawOffsetIndices.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawOffsetIndices.cpp index 34895d5545ec..0579fa8ac844 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawOffsetIndices.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawOffsetIndices.cpp @@ -383,7 +383,7 @@ class Fixture { return state; } - void Draw(const ShaderRecompiler::RecompileResult& vertex, const AgcDriver::Pm4::DrawParameters& draw, bool compactRestart = false) { + void Draw(const ShaderRecompiler::RecompileResult& vertex, const AgcDriver::Pm4::DrawParameters& draw, bool compactRestart = false, const ShaderRecompiler::HeapStageWords* heap = nullptr) { const auto vertexPush = static_cast(vertex.pushConstants.size()); ShaderRecompiler::ShaderPixelStageInfo pixelInfo{}; pixelInfo.wave32 = true; @@ -392,7 +392,7 @@ class Fixture { ShaderRecompiler::RecompileRequest pixelRequest{{ShaderStage::Fragment, reinterpret_cast(PixelCode.data()), PixelCode, 0, {}}, {32u, 0u, {}, std::nullopt, pixelInfo, std::nullopt, {}}, device->Target(), PixelPushLayout(vertexPush, device->Target())}; pixelRequest.useCache = false; const auto pixel = ShaderRecompiler::Recompile(pixelRequest); - const std::array shaders{{{ShaderStage::Vertex, &vertex, 0u}, {ShaderStage::Fragment, &pixel, PixelPushOffset(vertexPush, device->Target())}}}; + const std::array shaders{{{ShaderStage::Vertex, &vertex, 0u, nullptr, heap}, {ShaderStage::Fragment, &pixel, PixelPushOffset(vertexPush, device->Target())}}}; Output.fill(Unwritten); if (compactRestart) { auto context = device->graphicsContext(); @@ -519,6 +519,28 @@ std::string RuntimeFetch(Fixture& fixture, std::uint32_t index, bool compactRest return std::equal(expected.begin(), expected.end(), Output.begin()) ? "" : "runtime-fetched VertexIndex was changed\n"; } +std::string HeapAttributes(Fixture& fixture) { + const auto userData = fixture.UserData(0, 0); + const auto perDraw = fixture.Vertex(VertexCode, userData); + const auto records = BufferTable[2]; + BufferTable[2] = 1u; + const auto shared = fixture.Vertex(VertexCode, userData); + BufferTable[2] = records; + Require(!perDraw.vertexAttributes.empty() && shared.vertexAttributes.size() == perDraw.vertexAttributes.size(), "the vertex buffers did not become fixed vertex attributes"); + ShaderRecompiler::HeapStageWords words; + words.vertexAttributes = perDraw.vertexAttributes; + const auto index = static_cast(VertexSlots.size() - 1u); + const std::array fetched{index}; + fixture.Place(0, fetched, 0); + alignas(256) static std::array indices{}; + indices = {0xffffffffu, index, index, index, 0xffffffffu}; + const AgcDriver::Pm4::DrawParameters draw{reinterpret_cast(indices.data()), 5, 4, 1, 0, true, 0, 0}; + fixture.Draw(shared, draw, true, &words); + std::cout << "heap vertex attributes, index " << index << ", compact restart: readback " << Output[0] << ' ' << Output[1] << ' ' << Output[2] << ' ' << Output[3] << '\n'; + const std::array expected{index, 0, index, 0}; + return std::equal(expected.begin(), expected.end(), Output.begin()) ? "" : "a compacted index inside the draw's own vertex buffer was clamped by the shared program's buffer size\n"; +} + std::string Run(Fixture& fixture) { std::string failures = Analysis(fixture); const std::array autoIndices{0, 1, 2}; @@ -633,6 +655,7 @@ int main(int argc, char** argv) { Fixture fixture(device); std::string failures; if (argc == 1) failures = Run(fixture); + else if (argc == 2 && std::string(argv[1]) == "heap-attributes") failures = HeapAttributes(fixture); else { Require(argc == 3 || argc == 4, "expected runtime-fetch INDEX [compact-restart]"); Require(std::string(argv[1]) == "runtime-fetch", "unknown case"); From 4bd2c7db5211ae2171bacc000c6c0f52f74307af Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 3 Nov 2026 11:10:39 +0530 Subject: [PATCH 102/269] perf(agc): back GPU-mode compute scratch with the scratch pool GPU-mode compute stages now use the #12764 scratch pool instead of function-storage scratch. The pool binds at descriptor set 5 through a pushed address after the workgroup memory address, and because a pushed address carries no array length, the stage reads its pool size in dwords from push data instead of OpArrayLength. The scratch pool test runs every case in heap mode and requires the descriptor heap pipeline. --- .../Execution/src/Driver/Draw/HeapStages.cpp | 2 +- .../Execution/src/VulkanDevice.cpp | 30 ++++++++++++++----- .../Graphics/include/BindlessHeap.hpp | 4 +-- .../Graphics/src/BindlessHeap.cpp | 20 +++++++++---- .../tests/execution/ScratchPool.cpp | 17 ++++------- core/shader/recompiler/Recompiler.hpp | 3 ++ .../SpirvBackend/SpirvEmitterHelpers.hpp | 1 + .../SpirvMemory/SpirvBufferAccess.hpp | 1 + .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 6 ++-- .../src/SpirvMemory/SpirvScratchPool.cpp | 15 ++++++++-- 10 files changed, 67 insertions(+), 32 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 64088b9649f2..1c69ac53a688 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -263,7 +263,7 @@ bool HeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool wor if (const auto found = known.find(key); found != known.end()) return found->second; if (known.size() >= ThreadCacheLimit) known.clear(); const bool mappable = heapClassesAllowed(result) && - Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), workgroupAddress, result.dataAddressPush, result.functionLdsBuffer, result.meshWindowBuffer); + Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), workgroupAddress, result.dataAddressPush, result.functionLdsBuffer, result.meshWindowBuffer, result.scratchPoolSlotDwords != 0u); known.emplace(key, mappable); return mappable; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index e79b29b74dae..044d270baa0a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -266,6 +266,10 @@ const wchar_t* ComputePipelineDumpDirectory() { return _wgetenv(L"APS5_DUMP_COMP const char* ComputePipelineDumpDirectory() { return std::getenv("APS5_DUMP_COMPUTE_PIPELINES"); } #endif +static_assert(Graphics::ComputePushConstantBytes + sizeof(VkDeviceAddress) == ShaderRecompiler::GpuScratchPoolAddressPushByte && + ShaderRecompiler::GpuScratchPoolAddressPushByte + sizeof(VkDeviceAddress) <= ShaderRecompiler::GpuScratchPoolDwordsPushByte && + ShaderRecompiler::GpuScratchPoolDwordsPushByte + sizeof(std::uint32_t) <= ShaderRecompiler::RuntimeAbi::RootDword * sizeof(std::uint32_t)); + void CreateComputeHeapPipeline(VkDevice device, PFN_vkCreateComputePipelines create, VkPipelineCache cache, VkShaderModule module, VkPipelineCreateFlags flags, VkPipelineShaderStageCreateFlags stageFlags, const VkSpecializationInfo* specialization, std::uint32_t subgroupSize, std::span mappings, VkPipeline* pipeline, Graphics::PipelineCacheSynchronization* synchronization) { auto flags2 = Graphics::DescriptorHeapFlags(static_cast(flags)); VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, &flags2}; @@ -437,6 +441,7 @@ struct ScratchPool { std::unique_ptr buffer; VkDescriptorPool pool = VK_NULL_HANDLE; VkDescriptorSet set = VK_NULL_HANDLE; + VkDeviceAddress address = 0; std::uint64_t slots = 0; std::uint64_t headerBytes = 0; std::uint64_t bytes = 0; @@ -845,7 +850,7 @@ struct VulkanDevice::State { created->headerBytes = wanted * 2u * 4u; created->bytes = size; created->lastUse = use; - created->buffer = std::make_unique(context, static_cast(size), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); + created->buffer = std::make_unique(context, static_cast(size), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | (context.descriptorHeap ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u)); const VkDescriptorPoolSize poolSize{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; poolInfo.maxSets = 1; @@ -865,6 +870,7 @@ struct VulkanDevice::State { write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &described; DeviceFunction("vkUpdateDescriptorSets")(device, 1, &write, 0, nullptr); + if (context.descriptorHeap) created->address = Graphics::BufferDeviceAddress(context, created->buffer->Handle()); ZeroScratchPoolHeader(context, *created); scratchPools[identity] = created; return created; @@ -5677,19 +5683,27 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { const auto workgroupSet = record.shader->program->gpuResolvedImages ? ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet : ShaderRecompiler::WorkgroupMemoryDescriptorSet; if (record.objects->descriptorHeap) { workgroupAddress = memory->address; - if (record.pushStages == 0) { - const VkPushDataInfoEXT push{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, Graphics::ComputePushConstantBytes, {&memory->address, sizeof(memory->address)}}; - context.Function("vkCmdPushDataEXT")(commands, &push); - } } else { Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, workgroupSet, 1, &memory->set, Graphics::SetBindSite::Dispatch); } recorder.Keep(std::move(memory)); } + std::array stageAddresses{}; + std::memcpy(stageAddresses.data(), &workgroupAddress, sizeof(workgroupAddress)); if (pool != nullptr) { - context.Resolved(&Graphics::DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, ShaderRecompiler::ScratchPoolDescriptorSet, 1, &pool->set, 0, nullptr); + if (record.objects->descriptorHeap) { + const auto dwords = static_cast(pool->bytes / sizeof(std::uint32_t)); + std::memcpy(stageAddresses.data() + (ShaderRecompiler::GpuScratchPoolAddressPushByte - Graphics::ComputePushConstantBytes), &pool->address, sizeof(pool->address)); + std::memcpy(stageAddresses.data() + (ShaderRecompiler::GpuScratchPoolDwordsPushByte - Graphics::ComputePushConstantBytes), &dwords, sizeof(dwords)); + } else { + context.Resolved(&Graphics::DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, ShaderRecompiler::ScratchPoolDescriptorSet, 1, &pool->set, 0, nullptr); + } recorder.Keep(std::move(pool)); } + if (record.objects->descriptorHeap && record.pushStages == 0 && (workgroupAddress != 0 || record.shader->program->scratchPoolSlotDwords != 0)) { + const VkPushDataInfoEXT push{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, Graphics::ComputePushConstantBytes, {stageAddresses.data(), stageAddresses.size()}}; + context.Function("vkCmdPushDataEXT")(commands, &push); + } if (record.pushStages != 0) { std::array patchedBytes; const std::byte* pushed = record.pushBytes->data(); @@ -5699,7 +5713,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { pushed = patchedBytes.data(); } if (record.objects->descriptorHeap) { - std::memcpy(patchedBytes.data() + Graphics::ComputePushConstantBytes, &workgroupAddress, sizeof(workgroupAddress)); + std::memcpy(patchedBytes.data() + Graphics::ComputePushConstantBytes, stageAddresses.data(), stageAddresses.size()); const VkPushDataInfoEXT push{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {patchedBytes.data(), patchedBytes.size()}}; context.Function("vkCmdPushDataEXT")(commands, &push); } else { @@ -5847,7 +5861,7 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons const bool heapDevice = gpuMode && context.descriptorHeap && Graphics::DescriptorHeapEnabled(); const auto workgroupAddressOffset = workgroupAddress ? Graphics::ComputePushConstantBytes : ~0u; const std::span spirv(shader.spirv.data(), shader.spirv.size()); - objects->descriptorHeap = heapDevice && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(spirv, heapMappings, workgroupAddressOffset, shader.dataAddressPush); + objects->descriptorHeap = heapDevice && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(spirv, heapMappings, workgroupAddressOffset, shader.dataAddressPush, false, false, false, scratchPool); require(!gpuMode || objects->descriptorHeap, "a GPU-mode compute stage does not map onto VK_EXT_descriptor_heap"); const auto createPipelines = state->DeviceFunction("vkCreateComputePipelines"); if (objects->descriptorHeap) CreateComputeHeapPipeline(state->device, createPipelines, context.pipelineCache, objects->module, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, heapMappings, &objects->pipeline, context.pipelineCacheSynchronization); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 7956a2134293..5642d0249bb5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -41,7 +41,7 @@ class BindlessHeap { void BindDescriptorHeaps(VkCommandBuffer commands) const; bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset = ~0u, bool rootGds = false, bool rootFault = false, - bool pixelLds = false, bool meshWindow = false) const; + bool pixelLds = false, bool meshWindow = false, bool scratchPool = false) const; void WritePixelLdsBuffer(VkDeviceAddress address, VkDeviceSize bytes); void WriteMeshWindowBuffer(VkDeviceAddress address, VkDeviceSize bytes); VkDeviceAddress RingAddress() const; @@ -204,7 +204,7 @@ class HeapSlotOwner { bool GpuHeapEnabled(); void SetDescriptorHeapDevice(bool available); bool DescriptorHeapEnabled(); -bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds = false, bool meshWindow = false); +bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds = false, bool meshWindow = false, bool scratchPool = false); void NoteHeapComputeStage(); std::uint64_t HeapComputeStages(); void NoteImageTableBuild(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index e3b7c8e4c7ab..a617fd2aa82d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -638,6 +638,7 @@ struct HeapBindingRoots { bool faultAddress = false; bool pixelLds = false; bool meshWindow = false; + bool scratchPool = false; }; struct HeapBindingUse { @@ -647,6 +648,7 @@ struct HeapBindingUse { bool faultMemory = false; bool pixelLdsMemory = false; bool meshWindowMemory = false; + bool scratchPoolMemory = false; std::vector dataUniforms; std::pair refused{~0u, ~0u}; }; @@ -701,6 +703,10 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& use.meshWindowMemory = true; continue; } + if (roots.scratchPool && set == ShaderRecompiler::GpuScratchPoolDescriptorSet && binding == 0u) { + use.scratchPoolMemory = true; + continue; + } if (set == Abi::GpuDataSet && binding % bindingCount == static_cast(Abi::Binding::ShaderData) && binding / bindingCount < Abi::StageCount) { use.dataUniforms.push_back(binding); continue; @@ -714,7 +720,7 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& use.imageBindings.push_back(binding); } return (!roots.workgroupAddress || use.workgroupMemory) && (!roots.faultAddress || use.faultMemory) && - (!roots.pixelLds || use.pixelLdsMemory) && (!roots.meshWindow || use.meshWindowMemory); + (!roots.pixelLds || use.pixelLdsMemory) && (!roots.meshWindow || use.meshWindowMemory) && (!roots.scratchPool || use.scratchPoolMemory); } VkDescriptorSetAndBindingMappingEXT heapMapping(std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, @@ -760,9 +766,9 @@ VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, Vk } -bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds, bool meshWindow) { +bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds, bool meshWindow, bool scratchPool) { HeapBindingUse use; - const bool mappable = heapBindings(spirv, {.workgroupAddress = workgroupAddress, .gdsAddress = gdsAddress, .pixelLds = pixelLds, .meshWindow = meshWindow}, use); + const bool mappable = heapBindings(spirv, {.workgroupAddress = workgroupAddress, .gdsAddress = gdsAddress, .pixelLds = pixelLds, .meshWindow = meshWindow, .scratchPool = scratchPool}, use); if (!mappable && pipelineStats()) { static std::mutex causesMutex; static std::map causes; @@ -780,12 +786,14 @@ bool DescriptorHeapMappable(std::span spirv, bool workgroup } bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::vector& mappings, - std::uint32_t workgroupAddressOffset, bool rootGds, bool rootFault, bool pixelLds, bool meshWindow) const { + std::uint32_t workgroupAddressOffset, bool rootGds, bool rootFault, bool pixelLds, bool meshWindow, + bool scratchPool) const { mappings.clear(); if (resourceHeap == nullptr) return false; HeapBindingUse use; const HeapBindingRoots roots{ - .workgroupAddress = workgroupAddressOffset != ~0u, .gdsAddress = rootGds, .faultAddress = rootFault, .pixelLds = pixelLds, .meshWindow = meshWindow}; + .workgroupAddress = workgroupAddressOffset != ~0u, .gdsAddress = rootGds, .faultAddress = rootFault, .pixelLds = pixelLds, .meshWindow = meshWindow, + .scratchPool = scratchPool}; if (!heapBindings(spirv, roots, use)) return false; if (!use.dataUniforms.empty() && !ringInHeap) return false; constexpr auto bindingCount = static_cast(Abi::Binding::Count); @@ -803,6 +811,8 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, ringHeapOffset)); if (use.workgroupMemory) mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset)); + if (use.scratchPoolMemory) + mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuScratchPoolDescriptorSet, 0, ShaderRecompiler::GpuScratchPoolAddressPushByte)); if (use.gdsBinding != ~0u) mappings.push_back(pushAddressMapping(Abi::GpuGdsSet, use.gdsBinding, rootAddressOffset(Abi::RootGdsAddress))); if (use.faultMemory) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp index 24cdb0dd1e54..d0d92918f951 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp @@ -246,7 +246,7 @@ struct Facts { Facts Inspect(const ShaderRecompiler::RecompileResult& result) { const std::span words(result.spirv.data(), result.spirv.size()); - const auto poolSet = result.gpuResolvedImages ? ~0u : ShaderRecompiler::ScratchPoolDescriptorSet; + const auto poolSet = result.gpuResolvedImages ? ShaderRecompiler::GpuScratchPoolDescriptorSet : ShaderRecompiler::ScratchPoolDescriptorSet; Facts facts; std::set arrays, pointers, variables; for (std::size_t cursor = 5; cursor < words.size();) { @@ -305,9 +305,8 @@ void RunAlias(AgcDriver::VulkanDevice& device, Form form, bool atomic, std::uint const auto code = AliasKernel(form, atomic); const auto result = Compile(device, code, userData, waveSize, waveSize, false, AliasScratchDwords); const auto facts = Inspect(result); - const bool pooled = !result.gpuResolvedImages; - Require(facts.poolBinding == pooled && (result.scratchPoolSlotDwords != 0u) == pooled, name + ": the scratch pool binding does not match the stage's mode"); - Require(!pooled || !facts.functionArrayAccess, name + ": the scratch program indexes a Function array"); + Require(facts.poolBinding && result.scratchPoolSlotDwords != 0u, name + ": the scratch program has no scratch pool binding"); + Require(!facts.functionArrayAccess, name + ": the scratch program indexes a Function array"); const auto heapPipelines = device.DescriptorHeapComputePipelines(); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); @@ -338,7 +337,7 @@ void RunCallee(AgcDriver::VulkanDevice& device, std::uint32_t waveSize) { std::copy(tableDescriptor.begin(), tableDescriptor.end(), userData.begin() + 4); const auto code = CalleeKernel(); const auto result = Compile(device, code, userData, waveSize, waveSize, false, AliasScratchDwords); - Require((result.scratchPoolSlotDwords != 0u) == !result.gpuResolvedImages, name + ": the scratch pool binding does not match the stage's mode"); + Require(result.scratchPoolSlotDwords != 0u, name + ": the scratch program has no scratch pool binding"); const auto heapPipelines = device.DescriptorHeapComputePipelines(); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); @@ -492,12 +491,9 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; const bool wave64 = device->Target().subgroupSize >= 32u; - const bool pooled = !device->ComputeTarget(32u).gpuResolvedImages; RunPlain(*device); - if (pooled) { - RunDiscardedInitialization(*device); - RunEviction(*device); - } + RunDiscardedInitialization(*device); + RunEviction(*device); for (const std::uint32_t waveSize : {32u, 64u}) { if (waveSize == 64u && !wave64) continue; for (const Form form : {Form::Table, Form::Literal, Form::Computed}) { @@ -505,7 +501,6 @@ int main() { RunAlias(*device, form, true, waveSize); } RunCallee(*device, waveSize); - if (!pooled) continue; RunContention(*device, "isolation", ContentionKernel(waveSize), waveSize, false); RunContention(*device, "divergent exit", DivergentExitKernel(waveSize), waveSize, true); } diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index c20ed09e0572..cc689f9276ba 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -440,6 +440,9 @@ inline constexpr std::uint32_t MeshIndexBufferUserWord = 4; inline constexpr std::uint32_t WorkgroupMemoryDescriptorSet = 1; inline constexpr std::uint32_t ScratchPoolDescriptorSet = 2; inline constexpr std::uint32_t GpuWorkgroupMemoryDescriptorSet = 3; +inline constexpr std::uint32_t GpuScratchPoolDescriptorSet = 5; +inline constexpr std::uint32_t GpuScratchPoolAddressPushByte = 136; +inline constexpr std::uint32_t GpuScratchPoolDwordsPushByte = 144; struct GraphicsDrawParameters { std::uint64_t indexAddress; std::uint32_t indexCount; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp index ae86feb655b3..b701e078c67f 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp @@ -124,6 +124,7 @@ std::uint32_t LdsMemorySemantics(const SpirvEmitterState& state); std::uint32_t LdsMemoryBarrierScope(const SpirvEmitterState& state); void EmitLdsBufferBase(SpirvEmitterState& state); bool ScratchPoolActive(const SpirvEmitterState& state); +bool GpuScratchPool(const SpirvEmitterState& state); std::uint32_t ScratchPoolSlotDwords(const SpirvEmitterState& state); void DefineScratchPool(SpirvEmitterState& state); void EmitScratchPoolAcquire(SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp index 5f902b1b6bd9..ae2dc1b7d4d1 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp @@ -30,6 +30,7 @@ std::uint32_t LdsMemorySemantics(const SpirvEmitterState& state); std::uint32_t LdsMemoryBarrierScope(const SpirvEmitterState& state); void EmitLdsBufferBase(SpirvEmitterState& state); bool ScratchPoolActive(const SpirvEmitterState& state); +bool GpuScratchPool(const SpirvEmitterState& state); std::uint32_t ScratchPoolSlotDwords(const SpirvEmitterState& state); void DefineScratchPool(SpirvEmitterState& state); void EmitScratchPoolAcquire(SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index efc4b7623764..2b4761b8ce3e 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -141,7 +141,7 @@ std::uint32_t StorageBufferU64BlockType(SpirvEmitterState& state) { } std::uint32_t PushConstantArrayType(SpirvEmitterState& state) { - const auto count = ConstantU32(state, state.program.Metadata().bindings.UsesDataAddress() ? RuntimeAbi::PushDataDwords : PushData::DwordCount); + const auto count = ConstantU32(state, state.program.Metadata().bindings.UsesDataAddress() || GpuScratchPool(state) ? RuntimeAbi::PushDataDwords : PushData::DwordCount); return state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, static_cast(sizeof(std::uint32_t))}}}, TypeU32(state), count); @@ -486,7 +486,7 @@ std::uint32_t defineHeapArray(SpirvEmitterState& state, std::uint32_t slotCount, void DefineDescriptors(SpirvEmitterState& state) { const IrBindingLayout& layout = state.program.Metadata().bindings; const IrShaderStage stage = state.program.Resources().stage; - if (layout.UsesPushData() || layout.UsesDataAddress() || state.stencilReplay || stage == IrShaderStage::Mesh || stage == IrShaderStage::TessellationControl || (state.depthRangeRemap && (stage == IrShaderStage::Vertex || stage == IrShaderStage::TessellationEvaluation))) { + if (layout.UsesPushData() || layout.UsesDataAddress() || GpuScratchPool(state) || state.stencilReplay || stage == IrShaderStage::Mesh || stage == IrShaderStage::TessellationControl || (state.depthRangeRemap && (stage == IrShaderStage::Vertex || stage == IrShaderStage::TessellationEvaluation))) { const auto type = PushConstantBlockType(state); state.pushConstantVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassPushConstant, type), spv::StorageClassPushConstant); state.module.AddName(type, "BufferResource"); @@ -671,7 +671,7 @@ void DefineScratchPool(SpirvEmitterState& state) { if (!ScratchPoolActive(state)) return; state.scratchPoolVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassStorageBuffer, StorageBufferBlockType(state)), spv::StorageClassStorageBuffer); state.module.AddName(state.scratchPoolVariable, "scratch_pool"); - state.module.AddAnnotation(spv::OpDecorate, state.scratchPoolVariable, spv::DecorationDescriptorSet, ScratchPoolDescriptorSet); + state.module.AddAnnotation(spv::OpDecorate, state.scratchPoolVariable, spv::DecorationDescriptorSet, GpuScratchPool(state) ? GpuScratchPoolDescriptorSet : ScratchPoolDescriptorSet); state.module.AddAnnotation(spv::OpDecorate, state.scratchPoolVariable, spv::DecorationBinding, 0u); state.module.AddAnnotation(spv::OpDecorate, state.scratchPoolVariable, spv::DecorationCoherent); state.scratchPoolSlotVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassWorkgroup, TypeU32(state)), spv::StorageClassWorkgroup); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvScratchPool.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvScratchPool.cpp index 0b84252f141e..b003e8b35514 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvScratchPool.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvScratchPool.cpp @@ -49,7 +49,11 @@ std::uint32_t LinearWorkgroupId(SpirvEmitterState& state) { } bool ScratchPoolActive(const SpirvEmitterState& state) { - return state.requirements.functionScratch && state.program.Resources().stage == IrShaderStage::Compute && !state.gpuResolvedImages; + return state.requirements.functionScratch && state.program.Resources().stage == IrShaderStage::Compute; +} + +bool GpuScratchPool(const SpirvEmitterState& state) { + return state.gpuResolvedImages && ScratchPoolActive(state); } std::uint32_t ScratchPoolSlotDwords(const SpirvEmitterState& state) { @@ -69,7 +73,14 @@ void EmitScratchPoolAcquire(SpirvEmitterState& state) { const auto device = ConstantU32(state, spv::ScopeDevice); const auto acquire = ConstantU32(state, spv::MemorySemanticsAcquireMask | spv::MemorySemanticsUniformMemoryMask); const auto length = state.module.AllocateId(); - state.module.AddFunction(spv::OpArrayLength, TypeU32(state), length, state.scratchPoolVariable, 0u); + if (GpuScratchPool(state)) { + if (state.pushConstantVariable == 0u) FailEmit("a GPU-mode scratch pool has no push data for its length"); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0u), ConstantU32(state, GpuScratchPoolDwordsPushByte / 4u)); + state.module.AddFunction(spv::OpLoad, TypeU32(state), length, pointer); + } else { + state.module.AddFunction(spv::OpArrayLength, TypeU32(state), length, state.scratchPoolVariable, 0u); + } const auto slotDwords = ScratchPoolSlotDwords(state); const auto slots = EmitBinaryU32(state, spv::OpUDiv, length, ConstantU32(state, slotDwords + HeaderWordsPerSlot)); state.scratchPoolSlotCount = slots; From 7bf7e13c7f428dae1d3cffbd1f57febcd6deb007 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 3 Nov 2026 11:13:37 +0530 Subject: [PATCH 103/269] fix(agc): size indirect draws' vertex buffers from the draw's heap words The indirect draw classifier picked the CPU path for vertex buffers over APS5_INDIRECT_VERTEX_MIB from the stage's program attributes. On a draw cache hit or a reused heap stage that program is the shared template, so the check used the first draw's buffer sizes. It now reads the draw's own heap words, as the index paths do. --- .../Execution/include/Driver/Driver.hpp | 2 +- .../Execution/src/Driver/Draw/Draw.cpp | 2 +- .../Execution/src/Driver/Draw/IndirectDraw.cpp | 4 ++-- .../tests/execution/DrawOffsetIndices.cpp | 11 +++++++++-- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp index 027e6ad8610e..788876d27826 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp @@ -128,7 +128,7 @@ class Driver { [[nodiscard]] std::vector> PreparedEntryHashes(const Shader* shader); [[nodiscard]] std::array PrebuiltLibraries(); static void FoldDrawOffsets(const ShaderRecompiler::RecompileResult& result, const DrawProgram& program, Pm4::DrawParameters& parameters); - static std::optional ClassifyIndirectDraw(const ShaderRecompiler::RecompileResult& result, const Graphics::State& graphics, const DrawProgram& frontProgram, const std::shared_ptr& localDevice, Pm4::DrawParameters& drawParameters, bool traceIndirect); + static std::optional ClassifyIndirectDraw(const ShaderRecompiler::RecompileResult& result, const Graphics::State& graphics, const DrawProgram& frontProgram, const std::shared_ptr& localDevice, Pm4::DrawParameters& drawParameters, bool traceIndirect, const ShaderRecompiler::HeapStageWords* heap = nullptr); static void tagVariantRuns(DispatchVariant& variant, std::span regions, const ShaderRecompiler::SrtUserDataUse& use, bool eligible, std::uint32_t hiddenWords, std::span> supplied = {}); static void tagUserValueWords(DispatchVariant& variant, const DrawProgram& program, const ShaderRecompiler::HeapStageWords* heap = nullptr); static std::uint64_t relocatedContentKey(const RelocatableUserWord& word, std::uint32_t value, bool& readable); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 86eeee15f9ed..d30db4ac2753 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -1060,7 +1060,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { } const auto& result = *programResults[i]; if (i == 0 && drawParameters.indirect) { - indirectCpu = ClassifyIndirectDraw(result, graphics, programs.front(), localDevice, drawParameters, traceIndirect); + indirectCpu = ClassifyIndirectDraw(result, graphics, programs.front(), localDevice, drawParameters, traceIndirect, stageCaptures[0].heapWords.get()); if (EmptyIndirectSkip()) CpuIndirectPrograms()[programs.front().binary.codeAddress] = indirectCpu.has_value(); } else if (i == 0) { fold(result, drawParameters); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/IndirectDraw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/IndirectDraw.cpp index fa1676e68c33..f53baccda375 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/IndirectDraw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/IndirectDraw.cpp @@ -22,7 +22,7 @@ void Driver::FoldDrawOffsets(const ShaderRecompiler::RecompileResult& result, co if (result.instanceOffsetSgpr >= 0) parameters.firstInstance = drawUserWord(program, result.instanceOffsetSgpr); } -std::optional Driver::ClassifyIndirectDraw(const ShaderRecompiler::RecompileResult& result, const Graphics::State& graphics, const DrawProgram& frontProgram, const std::shared_ptr& localDevice, Pm4::DrawParameters& drawParameters, bool traceIndirect) { +std::optional Driver::ClassifyIndirectDraw(const ShaderRecompiler::RecompileResult& result, const Graphics::State& graphics, const DrawProgram& frontProgram, const std::shared_ptr& localDevice, Pm4::DrawParameters& drawParameters, bool traceIndirect, const ShaderRecompiler::HeapStageWords* heap) { std::optional indirectCpu; auto& indirect = *drawParameters.indirect; using Rule = Pm4::DrawParameters::IndirectDraw::Rule; @@ -57,7 +57,7 @@ std::optional Driver::ClassifyIndirectDraw(const Sha if ((indirect.vertexRule == Rule::Constant || indirect.instanceRule == Rule::Constant) && indirect.count > 256) fail(Path::FeatureGap); static const std::uint64_t vertexCap = [] { const char* text = std::getenv("APS5_INDIRECT_VERTEX_MIB"); return (text ? std::strtoull(text, nullptr, 10) : 64ull) << 20u; }(); - for (const auto& attribute : result.vertexAttributes) { + for (const auto& attribute : heap != nullptr && !heap->vertexAttributes.empty() ? heap->vertexAttributes : result.vertexAttributes) { const auto stride = (attribute.resource.fields[1] >> 16u) & 0x3fffu; const auto extent = stride == 0 ? static_cast(attribute.resource.fields[2]) : static_cast(attribute.resource.fields[2]) * stride; if (extent > vertexCap) fail(Path::VertexRange); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawOffsetIndices.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawOffsetIndices.cpp index 0579fa8ac844..f8fbeea2a51c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawOffsetIndices.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawOffsetIndices.cpp @@ -458,8 +458,8 @@ std::string PathName(const std::optional& path) { return path ? "the CPU path (" + std::string(AgcDriver::Graphics::IndirectDrawPathName(*path)) + ")" : std::string("the GPU"); } -std::string Classified(Fixture& fixture, const std::string& what, const ShaderRecompiler::RecompileResult& vertex, const std::vector& userData, AgcDriver::Pm4::DrawParameters& draw, std::optional expectedPath, Rule expectedRule, bool rectList = false) { - const auto path = AgcDriver::DriverDetail::Driver::ClassifyIndirectDraw(vertex, fixture.State(rectList), Program(userData), fixture.device, draw, false); +std::string Classified(Fixture& fixture, const std::string& what, const ShaderRecompiler::RecompileResult& vertex, const std::vector& userData, AgcDriver::Pm4::DrawParameters& draw, std::optional expectedPath, Rule expectedRule, bool rectList = false, const ShaderRecompiler::HeapStageWords* heap = nullptr) { + const auto path = AgcDriver::DriverDetail::Driver::ClassifyIndirectDraw(vertex, fixture.State(rectList), Program(userData), fixture.device, draw, false, heap); const auto& indirect = *draw.indirect; const bool rules = expectedPath || (indirect.vertexRule == expectedRule && indirect.instanceRule == expectedRule); std::cout << what << ": classified to " << PathName(path) << '\n'; @@ -614,6 +614,13 @@ std::string Run(Fixture& fixture) { AgcDriver::Pm4::DrawParameters draw{indexAddress, static_cast(Indices.size()), 2, 0, 0, true, 0, 0}; draw.indirect = indexedIndirect; failures += Classified(fixture, what, vertex, staleUserData, draw, std::nullopt, Rule::InPlace); + if (code == &PostAddCode) { + ShaderRecompiler::HeapStageWords words; + words.vertexAttributes = vertex.vertexAttributes; + for (auto& attribute : words.vertexAttributes) attribute.resource.fields[2] = 0x2000000u; + auto heapDraw = draw; + failures += Classified(fixture, what + ", with a 128 MiB vertex buffer in its heap words", vertex, staleUserData, heapDraw, Path::VertexRange, Rule::InPlace, false, &words); + } fixture.Place(indexedRecord[3], bufferIndices, indexedRecord[4]); fixture.Draw(vertex, draw); failures += fixture.Check(what + ", drawn in place on the GPU", bufferIndices, indexedRecord[3], indexedRecord[4], false); From 64de7b5a68b1077a9ecaab5237b8e58ffa7c9597 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 3 Nov 2026 11:49:50 +0530 Subject: [PATCH 104/269] test(agc): word the presentation pass host-memory skip as a device limitation agc_driver_presentation_pass_gpu_heap runs the non-heap suites before it skips for a missing descriptor heap. On lavapipe without VK_EXT_descriptor_heap one of them prints "the device offers no host memory type", which tools/check_skips.py does not accept as a device limitation, so the skip counted as unexpected. It now reads "the device has no host memory type". --- core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp index 6a21e2e18c5d..d50b80305a02 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PresentationPass.cpp @@ -790,7 +790,7 @@ void sourceImageOutsideDeviceMemoryTests(const Context& base) { base.Function("vkGetImageMemoryRequirements")(base.device, probe, &requirements); base.Function("vkDestroyImage")(base.device, probe, nullptr); if (!base.HostMemoryType(requirements.memoryTypeBits)) { - std::printf("presentation source in host memory: skipped, the device offers no host memory type for the image\n"); + std::printf("presentation source in host memory: skipped, the device has no host memory type for the image\n"); return; } auto context = base; From 4353aabe1ab0c831a01a9c020d08f1a5b46f9f62 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 3 Nov 2026 19:26:17 +0530 Subject: [PATCH 105/269] perf(agc): keep the descriptor heaps bound across the indirect argument checks The dispatch and mesh argument checks read only push constants, but they pushed them with vkCmdPushConstants, which puts a command buffer back in classic descriptor mode, so in heap mode the next draw bound the heaps again. In descriptor heap mode they now also get a heap pipeline and take their parameters through vkCmdPushDataEXT, as the changed copy does since the main merge. --- .../Graphics/include/Recorder.hpp | 2 + .../libSceAgcDriver/Graphics/src/Recorder.cpp | 12 ++++-- .../tests/execution/PushOnlyHeapPasses.cpp | 41 +++++++++++++++++++ 3 files changed, 51 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index b270f516044f..407435656f2f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -772,6 +772,7 @@ class Recorder { int meshArgumentState = 0; VkPipelineLayout meshArgumentLayout = VK_NULL_HANDLE; VkPipeline meshArgumentPipeline = VK_NULL_HANDLE; + VkPipeline meshArgumentHeapPipeline = VK_NULL_HANDLE; int changedCopyState = 0; VkPipelineLayout changedCopyLayout = VK_NULL_HANDLE; VkPipeline changedCopyPipeline = VK_NULL_HANDLE; @@ -794,6 +795,7 @@ class Recorder { int dispatchArgumentState = 0; VkPipelineLayout dispatchArgumentLayout = VK_NULL_HANDLE; VkPipeline dispatchArgumentPipeline = VK_NULL_HANDLE; + VkPipeline dispatchArgumentHeapPipeline = VK_NULL_HANDLE; // BeginGpuTiming on the open batch without Commands() (RecordStore times its own run, which // Commands() would close). std::uint32_t beginTiming(std::uint64_t key); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 8027b660ebe4..2e825030fb4a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -1254,6 +1254,7 @@ Recorder::~Recorder() { if (labelTableOwner == this) labelTableOwner = nullptr; } if (meshArgumentPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, meshArgumentPipeline, nullptr); + if (meshArgumentHeapPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, meshArgumentHeapPipeline, nullptr); if (meshArgumentLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, meshArgumentLayout, nullptr); if (changedCopyPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, changedCopyPipeline, nullptr); if (changedCopyHeapPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, changedCopyHeapPipeline, nullptr); @@ -1269,6 +1270,7 @@ Recorder::~Recorder() { sampleCounter.reset(); } if (dispatchArgumentPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, dispatchArgumentPipeline, nullptr); + if (dispatchArgumentHeapPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, dispatchArgumentHeapPipeline, nullptr); if (dispatchArgumentLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, dispatchArgumentLayout, nullptr); for (const auto fence : spare) context.Function("vkDestroyFence")(context.device, fence, nullptr); spare.clear(); @@ -2276,6 +2278,7 @@ bool Recorder::RecordDispatchArguments(VkCommandBuffer commands, VkDeviceAddress pipelineInfo.stage.pName = "main"; pipelineInfo.layout = dispatchArgumentLayout; Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &dispatchArgumentPipeline), "vkCreateComputePipelines dispatch arguments"); + dispatchArgumentHeapPipeline = createPushOnlyHeapPipeline(pipelineInfo); context.Function("vkDestroyShaderModule")(context.device, module, nullptr); dispatchArgumentState = 1; } catch (const std::exception& error) { @@ -2285,7 +2288,7 @@ bool Recorder::RecordDispatchArguments(VkCommandBuffer commands, VkDeviceAddress } if (dispatchArgumentState < 0) return false; recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); - function(cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, dispatchArgumentPipeline); + bindPushOnlyPipeline(commands, dispatchArgumentPipeline, dispatchArgumentHeapPipeline); const auto* limit = context.limits.maxComputeWorkGroupCount; struct { VkDeviceAddress source; @@ -2295,7 +2298,7 @@ bool Recorder::RecordDispatchArguments(VkCommandBuffer commands, VkDeviceAddress } parameters{source, arguments, {limit[0], limit[1], limit[2], threadGroup != nullptr ? 1u : 0u}, {1u, 1u, 1u, 0u}}; if (threadGroup != nullptr) std::copy(threadGroup->begin(), threadGroup->end(), parameters.group.begin()); static_assert(sizeof(parameters) == PushBytes); - CmdPushConstants(context, commands, dispatchArgumentLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); + pushOnlyParameters(commands, dispatchArgumentHeapPipeline, dispatchArgumentLayout, PushBytes, ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, 1, 1, 1); const VkPipelineStageFlags readers = VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | (threadGroup != nullptr ? VK_PIPELINE_STAGE_TRANSFER_BIT : 0u); const VkAccessFlags reads = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | (threadGroup != nullptr ? VK_ACCESS_TRANSFER_READ_BIT : 0u); @@ -2754,6 +2757,7 @@ bool Recorder::RecordMeshArguments(VkCommandBuffer commands, VkDeviceAddress rec auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &meshArgumentPipeline), "vkCreateComputePipelines mesh arguments"); } + meshArgumentHeapPipeline = createPushOnlyHeapPipeline(pipelineInfo); context.Function("vkDestroyShaderModule")(context.device, module, nullptr); meshArgumentState = 1; } catch (const std::exception& error) { @@ -2763,14 +2767,14 @@ bool Recorder::RecordMeshArguments(VkCommandBuffer commands, VkDeviceAddress rec } if (meshArgumentState < 0) return false; recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); - function(cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, meshArgumentPipeline); + bindPushOnlyPipeline(commands, meshArgumentPipeline, meshArgumentHeapPipeline); struct { VkDeviceAddress record; VkDeviceAddress arguments; std::array rules; } parameters{record, arguments, {rules[0], rules[1], rules[2], rules[3], rules[4], rules[5], rules[6], 0u}}; static_assert(sizeof(parameters) == PushBytes); - CmdPushConstants(context, commands, meshArgumentLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); + pushOnlyParameters(commands, meshArgumentHeapPipeline, meshArgumentLayout, PushBytes, ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, 1, 1, 1); recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_MESH_SHADER_BIT_EXT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_SHADER_READ_BIT); CountBarriers(CommandClass::Draw, 2); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PushOnlyHeapPasses.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PushOnlyHeapPasses.cpp index 98ead19f9afc..885593af4a75 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PushOnlyHeapPasses.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PushOnlyHeapPasses.cpp @@ -4,6 +4,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "VulkanTestDevice.hpp" +#include #include #include #include @@ -57,6 +58,45 @@ void RunChangedCopy(const AgcDriver::VulkanDevice& device) { } } +// The indirect dispatch argument check is the same kind of pass: group counts from thread counts, +// and a count past the device limit dispatches nothing. +void RunDispatchArguments(const AgcDriver::VulkanDevice& device) { + const auto context = device.graphicsContext(); + const bool heapMode = AgcDriver::Graphics::DescriptorHeapEnabled() && context.descriptorHeap && BindlessHeap::For(context).DescriptorHeapMode(); + constexpr auto usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + auto threads = std::make_shared(context, 16, usage); + auto oversized = std::make_shared(context, 16, usage); + auto grouped = std::make_shared(context, 32, usage); + auto refused = std::make_shared(context, 32, usage); + const std::uint32_t threadCounts[4] = {3u, 5u, 7u, 0u}; + const std::uint32_t tooMany[4] = {0xffffffffu, 1u, 1u, 0u}; + std::memcpy(threads->Bytes().data(), threadCounts, sizeof(threadCounts)); + std::memcpy(oversized->Bytes().data(), tooMany, sizeof(tooMany)); + std::memset(grouped->Bytes().data(), 0xff, 32); + std::memset(refused->Bytes().data(), 0xff, 32); + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + auto* recorder = Recorder::Active(); + Require(recorder != nullptr, "push-only heap passes: no active recorder"); + if (heapMode) BindlessHeap::For(context).BindDescriptorHeaps(recorder->Commands()); + const auto binds = AgcDriver::Graphics::DescriptorHeapBinds(); + const std::array group{2u, 2u, 2u}; + Require(recorder->RecordDispatchArguments(recorder->Commands(), threads->DeviceAddress(), grouped->DeviceAddress(), &group), "push-only heap passes: the dispatch argument kernel is unavailable"); + Require(recorder->RecordDispatchArguments(recorder->Commands(), oversized->DeviceAddress(), refused->DeviceAddress()), "push-only heap passes: the dispatch argument kernel is unavailable"); + if (heapMode) { + BindlessHeap::For(context).BindDescriptorHeaps(recorder->Commands()); + Require(AgcDriver::Graphics::DescriptorHeapBinds() == binds, "push-only heap passes: the dispatch argument check put its command buffer back in classic descriptor mode, so the heaps were bound again"); + } + for (const auto& kept : {threads, oversized, grouped, refused}) recorder->Keep(kept); + recorder->Submit(); + recorder->Sync(); + std::uint32_t words[6]{}; + std::memcpy(words, grouped->Bytes().data(), sizeof(words)); + const std::uint32_t expected[6] = {2u, 3u, 4u, 3u, 5u, 7u}; + for (std::size_t i = 0; i < 6; ++i) Require(words[i] == expected[i], "push-only heap passes: dispatch argument word " + std::to_string(i) + " is " + std::to_string(words[i]) + ", expected " + std::to_string(expected[i])); + std::memcpy(words, refused->Bytes().data(), 3 * sizeof(std::uint32_t)); + Require(words[0] == 0u && words[1] == 0u && words[2] == 0u, "push-only heap passes: a group count past the device limit was dispatched"); +} + } int main() { @@ -64,6 +104,7 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; RunChangedCopy(*device); + RunDispatchArguments(*device); device->WaitIdle(); std::puts("push-only heap pass tests passed"); return 0; From 78079485cc34b8ef1c54e1d3ec04d42b9c540a0c Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 3 Nov 2026 21:26:07 +0530 Subject: [PATCH 106/269] perf(agc): bind GPU-heap guest buffers and the flattened SRT through ring descriptors GPU-mode stages read their guest buffers and flattened SRT through raw device addresses, which costs RADV 64-bit address math, a software bounds clamp and a scalar load per dword where the per-draw path's descriptors give hardware-checked buffer loads: about 18% more instructions in MCD2's shaders on RDNA2. Each GPU-mode stage now writes a run of storage buffer descriptors into the shader-data ring inside the resource heap, its flattened SRT then its guest buffers, and puts the run's first index in its root FlattenedSrt word. The shaders declare the per-draw buffer array and SRT buffer, which the pipeline maps over the run with VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT, the way vkd3d-proton binds descriptor tables. A stage keeps its run while its SRT span and buffers do not change. Heap shader data is read four dwords at a time. In ring mode a stage's shader data no longer carries buffer addresses: they are not written per draw, and moved or snapshotted buffers only get a fresh descriptor run instead of a second copy of the data span. The heap SRT buffer is not NonWritable: with that decoration NVIDIA's driver miscompiles the mesh vector window test's program through the heap mapping. APS5_NO_HEAP_DATA_UNIFORM is removed. Request serialization version 55 gains the heapBufferDescriptors target flag. --- .../Execution/src/VulkanDevice.cpp | 7 +- .../Graphics/include/BindlessHeap.hpp | 4 +- .../Graphics/include/Context.hpp | 1 + .../Graphics/include/ShaderResources.hpp | 13 +++- .../Graphics/src/BindlessHeap.cpp | 65 +++++++++++++++-- .../Graphics/src/ShaderResources.cpp | 62 +++++++++++++--- .../Graphics/src/ShaderValidation.cpp | 9 ++- .../libSceAgcDriver/tests/ShaderMemory.cpp | 7 +- core/shader/recompiler/CacheKey.hpp | 1 + .../ControlFlow/src/RequestSerializer.cpp | 2 + core/shader/recompiler/Recompiler.cpp | 1 + core/shader/recompiler/Recompiler.hpp | 1 + .../include/SpirvBackend/SpirvEmitter.hpp | 1 + .../SpirvBackend/SpirvEmitterState.hpp | 1 + .../SpirvBackend/src/SpirvEmitter.cpp | 1 + .../src/SpirvMemory/SpirvBufferAccess.cpp | 7 +- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 9 +-- .../tests/RequestSerializerTests.cpp | 71 ++++++++++++------- docs/dev/ENVIRONMENT.md | 1 - 19 files changed, 211 insertions(+), 53 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 984ed2a43fa4..ac33143b6d6b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -650,6 +650,7 @@ struct VulkanDevice::State { bool descriptorHeap = false; VkPhysicalDeviceDescriptorHeapPropertiesEXT descriptorHeapProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_PROPERTIES_EXT}; std::uint32_t heapDataUniformDwords = 0; + bool heapBufferDescriptors = false; std::unique_ptr recorder; // Device-local buffers of a repeated 16-byte fill pattern (FillBuffer), most recently used // last; each is filled once by a doubling chain in device memory. @@ -2140,8 +2141,10 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : if (descriptorHeapFeatures.descriptorHeap == VK_TRUE && heapMaintenance5.maintenance5 == VK_TRUE && Graphics::BindlessHeap::Fits(state->descriptorHeapProperties)) { state->descriptorHeap = true; state->maintenance5 = true; - if (Graphics::BindlessHeap::RingInResourceHeap(state->descriptorHeapProperties, state->properties.limits.minUniformBufferOffsetAlignment)) + if (Graphics::BindlessHeap::RingInResourceHeap(state->descriptorHeapProperties, state->properties.limits.minUniformBufferOffsetAlignment)) { state->heapDataUniformDwords = std::min(HeapDataUniformDwordCap, state->properties.limits.maxUniformBufferRange / 4u); + state->heapBufferDescriptors = state->descriptorHeapProperties.bufferDescriptorSize == Graphics::BindlessHeap::BufferSlotBytes; + } deviceExtensions.push_back(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME); for (const char* required : {VK_KHR_MAINTENANCE_5_EXTENSION_NAME, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME}) { if (std::find_if(deviceExtensions.begin(), deviceExtensions.end(), [&](const char* name) { return std::strcmp(name, required) == 0; }) == deviceExtensions.end()) deviceExtensions.push_back(required); @@ -4387,6 +4390,7 @@ ShaderRecompiler::SpirvTarget VulkanDevice::Target() const { target.float32DenormPreserve = state->float32DenormPreserve; target.descriptorMemory = Graphics::DescriptorHeapEnabled(); target.heapDataUniformDwords = target.descriptorMemory ? state->heapDataUniformDwords : 0u; + target.heapBufferDescriptors = target.descriptorMemory && state->heapBufferDescriptors; return target; } @@ -4532,6 +4536,7 @@ Graphics::Context VulkanDevice::buildContext() const { context.recorder = state->recorder.get(); context.descriptorHeap = state->descriptorHeap; context.descriptorHeapProperties = state->descriptorHeapProperties; + context.heapBufferDescriptors = state->heapBufferDescriptors; context.descriptorCache = state->descriptorCache.get(); context.vertexInputs = state->vertexInputs.get(); context.vertexFormats = &state->vertexFormats; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 5642d0249bb5..1eaf69d63c7e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -76,6 +76,8 @@ class BindlessHeap { }; DataSpan Allocate(std::size_t words, SpanMark& mark); bool Held(const SpanMark& mark); + std::uint32_t RingBufferDescriptors(std::span buffers, SpanMark& mark); + static constexpr std::uint32_t BufferSlotBytes = 16u; static constexpr std::uint32_t SamplerKind = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Samplers); void Submitted(Recorder& recorder, std::uint64_t serial); @@ -83,7 +85,7 @@ class BindlessHeap { struct Counts { std::uint64_t ringWraps = 0, encodes = 0, encodedCopies = 0; std::uint64_t slotsFreed = 0, slotsReused = 0; - std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0; + std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0, bufferDescriptors = 0; }; Counts Statistics() const; std::size_t RingChunkCount() const { return ringChunks.size(); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index 0ca0e115edff..b9dab7bf82e1 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -245,6 +245,7 @@ struct Context { // Batches GPU work across guest commands (see Recorder); null before the device finished setup. Recorder* recorder = nullptr; bool descriptorHeap = false; + bool heapBufferDescriptors = false; VkPhysicalDeviceDescriptorHeapPropertiesEXT descriptorHeapProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_PROPERTIES_EXT}; // Per-device caches of the immutable descriptor objects a ShaderResources build needs (set // layouts, descriptor pools, samplers); null (tests) means every build makes and destroys its own. diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 49b7693e254d..5f71533e8fca 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -643,6 +643,11 @@ class ShaderResources { bool heapStage = false; std::array heapOffsets{}; void writeHeapStage(const CompiledShader& shader); + struct RingDescriptors { + std::vector ranges; + BindlessHeap::SpanMark mark; + std::uint32_t first = 0; + }; struct HeapStageState { std::vector key; std::array, static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)> slots; @@ -657,6 +662,7 @@ class ShaderResources { }; KeptSpan data, flat, map; std::vector dataInput; + RingDescriptors descriptors; }; std::array heapStages; std::uint32_t heapSpan(HeapStageState::KeptSpan& kept, std::span words); @@ -700,7 +706,12 @@ class ShaderResources { std::array heapTableMaps{}; std::array heapTableMapSet{}; void writeHeapTableMap(const CompiledShader& shader, std::size_t stageIndex); - void writeBufferAddresses(std::span words, std::uint32_t dataStage, const std::vector* overrides) const; + void writeBufferAddresses(std::span words, std::uint32_t dataStage, const std::vector* overrides, + std::vector* ranges = nullptr) const; + VkDeviceAddressRangeEXT srtRange(std::size_t stage) const; + std::uint32_t ringDescriptors(std::size_t stage, const std::vector* overrides, RingDescriptors& kept) const; + std::array heapSrtOffsets{}; + std::array ringDescriptorStages{}; std::array addressedOffsets(const std::vector* overrides) const; struct FaultDescriptor { std::size_t write; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index a617fd2aa82d..cd7f5d89f89e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -164,8 +164,6 @@ struct ResourceRing { }; ResourceRing resourceRing(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, VkDeviceSize uniformAlignment) { - static const bool disabled = std::getenv("APS5_NO_HEAP_DATA_UNIFORM") != nullptr; - if (disabled) return {}; const auto sizes = heapSizes(properties); const auto offset = alignUp(sizes.resourceUsed + properties.minResourceHeapReservedRange, std::max(uniformAlignment, properties.resourceHeapAlignment)); if (offset >= properties.maxResourceHeapSize) return {}; @@ -641,6 +639,8 @@ struct HeapBindingRoots { bool scratchPool = false; }; +using SetAndBinding = std::pair; + struct HeapBindingUse { std::vector imageBindings; bool workgroupMemory = false; @@ -650,11 +650,10 @@ struct HeapBindingUse { bool meshWindowMemory = false; bool scratchPoolMemory = false; std::vector dataUniforms; + std::vector ringDescriptors; std::pair refused{~0u, ~0u}; }; -using SetAndBinding = std::pair; - std::optional> decoratedVariables(std::span spirv) { constexpr std::size_t HeaderWords = 5u; constexpr std::uint32_t DecorateWords = 4u; @@ -711,6 +710,12 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& use.dataUniforms.push_back(binding); continue; } + const bool stageBinding = binding / bindingCount < Abi::StageCount; + if (roots.gdsAddress && stageBinding && ((set == Abi::DescriptorSet && binding % bindingCount == static_cast(Abi::Binding::Buffers)) || + (set == Abi::GpuDataSet && binding % bindingCount == static_cast(Abi::Binding::FlattenedSrt)))) { + if (std::find(use.ringDescriptors.begin(), use.ringDescriptors.end(), entry) == use.ringDescriptors.end()) use.ringDescriptors.push_back(entry); + continue; + } const bool heapImageOrSampler = set == Abi::FragmentDescriptorSet && binding >= firstImage && binding <= samplers; if (!heapImageOrSampler) { use.refused = entry; @@ -751,6 +756,22 @@ constexpr std::uint32_t rootAddressOffset(std::uint32_t rootField) { return (Abi::RootDword + rootField) * sizeof(std::uint32_t); } +VkDescriptorSetAndBindingMappingEXT ringDescriptorMapping(std::uint32_t set, std::uint32_t binding, VkDeviceSize ringOffset) { + constexpr auto bindingCount = static_cast(Abi::Binding::Count); + const bool buffers = binding % bindingCount == static_cast(Abi::Binding::Buffers); + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = set; + mapping.firstBinding = binding; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; + mapping.sourceData.pushIndex.heapOffset = static_cast(ringOffset + (buffers ? BindlessHeap::BufferSlotBytes : 0u)); + mapping.sourceData.pushIndex.pushOffset = rootAddressOffset(Abi::RootStageDword(static_cast(binding / bindingCount), Abi::RootStageField::FlattenedSrt)); + mapping.sourceData.pushIndex.heapIndexStride = BindlessHeap::BufferSlotBytes; + mapping.sourceData.pushIndex.heapArrayStride = BindlessHeap::BufferSlotBytes; + return mapping; +} + VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, VkDeviceSize heapOffset) { constexpr auto bindingCount = static_cast(Abi::Binding::Count); VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; @@ -795,7 +816,8 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, .workgroupAddress = workgroupAddressOffset != ~0u, .gdsAddress = rootGds, .faultAddress = rootFault, .pixelLds = pixelLds, .meshWindow = meshWindow, .scratchPool = scratchPool}; if (!heapBindings(spirv, roots, use)) return false; - if (!use.dataUniforms.empty() && !ringInHeap) return false; + if ((!use.dataUniforms.empty() || !use.ringDescriptors.empty()) && !ringInHeap) return false; + if (!use.ringDescriptors.empty() && context.descriptorHeapProperties.bufferDescriptorSize != BufferSlotBytes) return false; constexpr auto bindingCount = static_cast(Abi::Binding::Count); constexpr VkSpirvResourceTypeFlagsEXT imageResources = VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_IMAGE_BIT_EXT | @@ -809,6 +831,8 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, else mappings.push_back(heapMapping(Abi::FragmentDescriptorSet, binding, imageResources, 0, imageHeapStride)); } for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, ringHeapOffset)); + std::sort(use.ringDescriptors.begin(), use.ringDescriptors.end()); + for (const auto& [set, binding] : use.ringDescriptors) mappings.push_back(ringDescriptorMapping(set, binding, ringHeapOffset)); if (use.workgroupMemory) mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset)); if (use.scratchPoolMemory) @@ -826,6 +850,31 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, return true; } +std::uint32_t BindlessHeap::RingBufferDescriptors(std::span buffers, SpanMark& mark) { + Require(ringInHeap && context.descriptorHeapProperties.bufferDescriptorSize == BufferSlotBytes, "ring buffer descriptors need the shader-data ring inside the resource heap"); + const auto span = Allocate(buffers.size() * (BufferSlotBytes / sizeof(std::uint32_t)), mark); + Require(span.offset % BufferSlotBytes == 0u, "a ring buffer descriptor span is misaligned"); + thread_local std::vector resources; + thread_local std::vector ranges; + resources.assign(buffers.size(), {VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT}); + ranges.resize(buffers.size()); + auto* bytes = reinterpret_cast(span.words.data()); + for (std::size_t index = 0; index < buffers.size(); ++index) { + resources[index].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + resources[index].data.pAddressRange = &buffers[index]; + ranges[index] = {bytes + index * BufferSlotBytes, BufferSlotBytes}; + } + PFN_vkWriteResourceDescriptorsEXT write = nullptr; + { + std::lock_guard lock(mutex); + if (writeResourceDescriptors == nullptr) writeResourceDescriptors = context.Function("vkWriteResourceDescriptorsEXT"); + write = writeResourceDescriptors; + counts.bufferDescriptors += buffers.size(); + } + Check(write(context.device, static_cast(buffers.size()), resources.data(), ranges.data()), "vkWriteResourceDescriptorsEXT ring buffers"); + return static_cast(span.offset / BufferSlotBytes); +} + void BindlessHeap::writeBufferDescriptor(VkDeviceSize offset, VkDeviceAddress address, VkDeviceSize bytes, const char* what) { const auto& properties = context.descriptorHeapProperties; Require(offset + properties.bufferDescriptorSize <= resourceHeapUsed, std::string("the ") + what + " descriptor lies outside the resource heap"); @@ -945,6 +994,7 @@ void reportHeapStatistics() { totals.spansExpired += counts.spansExpired; totals.encodes += counts.encodes; totals.encodedCopies += counts.encodedCopies; + totals.bufferDescriptors += counts.bufferDescriptors; } } const auto windowDelta = [](std::uint64_t now, std::uint64_t before) { return now >= before ? now - before : now; }; @@ -953,15 +1003,16 @@ void reportHeapStatistics() { const auto spansExpired = windowDelta(totals.spansExpired, lastTotals.spansExpired); const auto imageEncodes = windowDelta(totals.encodes, lastTotals.encodes); const auto imageCopies = windowDelta(totals.encodedCopies, lastTotals.encodedCopies); + const auto bufferDescriptors = windowDelta(totals.bufferDescriptors, lastTotals.bufferDescriptors); lastTotals = totals; const auto templates = ShaderRecompiler::HeapTemplateCounts(); std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired; image descriptors %llu encoded / %llu copied; templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(spansExpired), printed(imageEncodes), printed(imageCopies), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(spansExpired), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 3a6b975b61a1..458cc1eb3f88 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6275,6 +6275,15 @@ std::shared_ptr ShaderResources::PrepareDrawBindi return result; } +namespace { + +std::size_t DataOffsetIndex(std::size_t stage, ShaderRecompiler::RuntimeAbi::Binding binding) { + Require(binding == ShaderRecompiler::RuntimeAbi::Binding::ShaderData || binding == ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt, "only shader data and the flattened SRT have ring offsets"); + return stage * 2u + (binding == ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt ? 1u : 0u); +} + +} + void ShaderResources::RefreshMovedAddresses(DrawBindings& rewritten) const { if (rewritten.addressOffsets) rewritten.heapOffsets = addressedOffsets(&rewritten.addressOverrides); } @@ -6290,6 +6299,11 @@ std::array ShaderR std::memcpy(span.words.data(), words.data(), words.size() * sizeof(std::uint32_t)); offsets[stageDataIndex[stage]] = span.offset; } + for (std::size_t stage = 0; stage < ringDescriptorStages.size(); ++stage) { + if (!ringDescriptorStages[stage]) continue; + RingDescriptors moved; + offsets[DataOffsetIndex(stage, ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt)] = ringDescriptors(stage, overrides, moved); + } return offsets; } @@ -6347,7 +6361,8 @@ void ShaderResources::RefreshHeapStage(std::span shaders) } } -void ShaderResources::writeBufferAddresses(std::span words, std::uint32_t dataStage, const std::vector* overrides) const { +void ShaderResources::writeBufferAddresses(std::span words, std::uint32_t dataStage, const std::vector* overrides, + std::vector* ranges) const { for (const auto& binding : bindings) { if (!binding.addressed || binding.dataStage != dataStage) continue; for (std::size_t element = 0; element < binding.allocations.size(); ++element) { @@ -6369,6 +6384,8 @@ void ShaderResources::writeBufferAddresses(std::span words, std:: address = base + info.offset; range = info.range; } + if (ranges != nullptr) ranges->push_back({address, std::min(range, context.limits.maxStorageBufferRange)}); + if (words.empty()) continue; const auto at = static_cast(binding.addressDword) + element * 4u; Require(at + 3u < words.size(), "buffer address words lie outside the shader data"); words[at] = static_cast(address); @@ -6379,13 +6396,29 @@ void ShaderResources::writeBufferAddresses(std::span words, std:: } } -namespace { - -std::size_t DataOffsetIndex(std::size_t stage, ShaderRecompiler::RuntimeAbi::Binding binding) { - Require(binding == ShaderRecompiler::RuntimeAbi::Binding::ShaderData || binding == ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt, "only shader data and the flattened SRT have ring offsets"); - return stage * 2u + (binding == ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt ? 1u : 0u); +VkDeviceAddressRangeEXT ShaderResources::srtRange(std::size_t stage) const { + const auto bytes = static_cast(heapSrtDwords[stage]) * sizeof(std::uint32_t); + if (bytes == 0u || bytes > context.limits.maxStorageBufferRange) { + const auto empty = BufferDeviceAddress(context, context.emptyBuffer); + Require(empty != 0, "the empty buffer has no device address"); + return {empty, EmptyBufferBytes}; + } + return {BindlessHeap::For(context).RingAddress() + heapSrtOffsets[stage], bytes}; } +std::uint32_t ShaderResources::ringDescriptors(std::size_t stage, const std::vector* overrides, RingDescriptors& kept) const { + struct RangeStorage {}; + auto& ranges = HostThreadLocal, RangeStorage>(); + ranges.clear(); + ranges.push_back(srtRange(stage)); + writeBufferAddresses({}, static_cast(stage), overrides, &ranges); + auto& heap = BindlessHeap::For(context); + const auto equal = [](const VkDeviceAddressRangeEXT& a, const VkDeviceAddressRangeEXT& b) { return a.address == b.address && a.size == b.size; }; + if (!std::ranges::equal(ranges, kept.ranges, equal) || !heap.Held(kept.mark)) { + kept.first = heap.RingBufferDescriptors(ranges, kept.mark); + kept.ranges.assign(ranges.begin(), ranges.end()); + } + return kept.first; } std::pair ShaderResources::shaderDataLocation(const CompiledShader& shader, const DrawBindings* rewritten) const { @@ -6810,6 +6843,11 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { const std::size_t flatIndex = DataOffsetIndex(stageIndex, Abi::Binding::FlattenedSrt); const auto& program = *shader.program; if (program.dataAddressPush) writeHeapTableMap(shader, stageIndex); + const bool ringStage = context.heapBufferDescriptors && program.dataAddressPush; + ringDescriptorStages[stageIndex] = ringStage; + if (ringStage) stageDataWords[stageIndex].clear(); + bool dataKept = false; + bool flattened = false; for (const auto& binding : program.bindings) { const bool shaderData = binding.role == ShaderRecompiler::DescriptorRole::ShaderData; if (!shaderData && binding.role != ShaderRecompiler::DescriptorRole::FlattenedSrt) continue; @@ -6825,13 +6863,15 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { if (sameInput && !verifySlots) { if (heap.Held(stageState.data.mark)) { heapOffsets[dataIndex] = stageState.data.mark.offset; + dataKept = true; continue; } stageState.data.mark.entry = 0; } if (!shaderData) { - heapOffsets[flatIndex] = heapSpan(stageState.flat, words); + (ringStage ? heapSrtOffsets[stageIndex] : heapOffsets[flatIndex]) = heapSpan(stageState.flat, words); heapSrtDwords[stageIndex] = static_cast(words.size()); + flattened = true; continue; } ValidateRuntimeResources(shader, words); @@ -6845,7 +6885,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { reinterpret_cast(patched.data())[byte] = static_cast(adjustment); } patchHeapSlotWords(shader, stageState, patched, current); - if (addressedBuffers) { + if (addressedBuffers && !ringStage) { HeapCostScope bufferCost(HeapCost::BufferAddresses); writeBufferAddresses(patched, static_cast(stageIndex), nullptr); bufferCost.Stop(); @@ -6858,6 +6898,12 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { stageState.dataInput.assign(words.begin(), words.end()); stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); } + if (!ringStage) return; + if (!flattened) heapSrtDwords[stageIndex] = 0u; + auto& kept = stageState.descriptors; + const auto srt = srtRange(stageIndex); + const bool reuse = dataKept && !kept.ranges.empty() && kept.ranges.front().address == srt.address && kept.ranges.front().size == srt.size && heap.Held(kept.mark); + heapOffsets[flatIndex] = reuse ? kept.first : ringDescriptors(stageIndex, nullptr, kept); } namespace { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index 2a9554840626..ef2566671ba5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -503,6 +503,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi for (const auto& [name, operands] : module.modes) Require(operands.empty() && (name == spv::ExecutionModeOriginUpperLeft || name == spv::ExecutionModeEarlyFragmentTests || name == spv::ExecutionModeDepthReplacing || name == spv::ExecutionModeDepthLess || name == spv::ExecutionModeDepthGreater || name == spv::ExecutionModePixelInterlockOrderedEXT || name == spv::ExecutionModeStencilRefReplacingEXT), "unsupported fragment execution mode"); } else Require(module.modes.empty(), "unsupported vertex execution mode"); std::set> descriptors; + std::set declared; std::map, bool> bufferViews; bool push = false; for (const auto& [id, variable] : module.variables) { @@ -626,16 +627,18 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi Require(mesh && *decoration.binding == 0u, "mesh window buffer binding is wrong"); continue; } - if (*decoration.set == ShaderRecompiler::PixelFunctionLdsDescriptorSet) { + const bool gpuData = shader.gpuResolvedImages && key.first == ShaderRecompiler::RuntimeAbi::GpuDataSet && + std::any_of(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { return item.binding == key.second && (item.role == ShaderRecompiler::DescriptorRole::ShaderData || item.role == ShaderRecompiler::DescriptorRole::FlattenedSrt); }); + if (!gpuData && *decoration.set == ShaderRecompiler::PixelFunctionLdsDescriptorSet) { Require(fragment && *decoration.binding == 0u, "pixel function LDS buffer binding is wrong"); continue; } - const bool gpuData = shader.gpuResolvedImages && key.first == ShaderRecompiler::RuntimeAbi::GpuDataSet; const auto binding = std::find_if(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { return (gpuData || item.descriptorSet == key.first) && item.binding == key.second; }); const bool array = binding != shader.bindings.end() && binding->role == ShaderRecompiler::DescriptorRole::GuestBuffers; const auto [view, first] = bufferViews.emplace(key, decoration.aliased); Require(descriptors.insert(key).second || (!first && view->second && decoration.aliased && array), "duplicate SPIR-V resource binding"); Require(binding != shader.bindings.end(), "SPIR-V resource is absent from recompiler binding metadata"); + declared.insert(&*binding); Require(binding->kind == ShaderRecompiler::DescriptorKind::StorageBuffer, "SPIR-V descriptor type disagrees with recompiler binding metadata"); Require(!binding->readOnly, "read-only descriptor metadata is unsupported because the recompiler emits no NonWritable decoration"); Require(array || (shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version && (binding->role == ShaderRecompiler::DescriptorRole::BdaPagetable || binding->role == ShaderRecompiler::DescriptorRole::FaultBuffer)) || binding->role == ShaderRecompiler::DescriptorRole::ShaderData || binding->role == ShaderRecompiler::DescriptorRole::FlattenedSrt || binding->role == ShaderRecompiler::DescriptorRole::ImageTableMap || binding->role == ShaderRecompiler::DescriptorRole::Gds, "SPIR-V descriptor role is unsupported"); @@ -670,7 +673,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi } else { Require(shader.vertexAttributes.empty(), "vertex attribute metadata is invalid for this stage"); } - const auto addressedBindings = static_cast(std::count_if(shader.bindings.begin(), shader.bindings.end(), [&](const ShaderRecompiler::DescriptorBinding& binding) { return (shader.bufferAddressCount != 0u && binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers) || (shader.dataAddressPush && (binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt || binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable || binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer || binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable || binding.role == ShaderRecompiler::DescriptorRole::SamplerTable || binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap)); })); + const auto addressedBindings = static_cast(std::count_if(shader.bindings.begin(), shader.bindings.end(), [&](const ShaderRecompiler::DescriptorBinding& binding) { return !declared.contains(&binding) && ((shader.bufferAddressCount != 0u && binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers) || (shader.dataAddressPush && (binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt || binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable || binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer || binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable || binding.role == ShaderRecompiler::DescriptorRole::SamplerTable || binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap))); })); Require(descriptors.size() + addressedBindings == shader.bindings.size(), "recompiler binding metadata contains undeclared resources"); Require(push == (!shader.pushConstants.empty() || shader.readsDepthRemapPush || shader.dataAddressPush || mesh || (control && !rectListControl && !barycentricPatches) || (geometry && state.tessellationCapture)), "recompiler push constant metadata disagrees with SPIR-V"); for (const auto id : module.interface) Require(module.variables.contains(id), "entry point interface contains an unknown variable"); diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 0e2051e8097b..f5203fac694c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -7878,10 +7878,15 @@ std::vector decodeBase64(std::string_view text) { bytes.push_back(static_cast((chunk >> bits) & 0xffu)); } } + if (bytes.size() > 5u && bytes[4] == 55u) { + require(bytes.back() == 0u, "a version 55 request in these checks set the GPU heap buffer descriptors"); + bytes.pop_back(); + } return bytes; } -std::string encodeBase64(const std::vector& bytes) { +std::string encodeBase64(std::vector bytes) { + if (bytes.size() > 4u && bytes[4] == 55u) bytes.push_back(0u); constexpr std::string_view alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string text; for (std::size_t index = 0; index < bytes.size(); index += 3u) { diff --git a/core/shader/recompiler/CacheKey.hpp b/core/shader/recompiler/CacheKey.hpp index 1c9ef73c7ecc..ef1500ab1f21 100644 --- a/core/shader/recompiler/CacheKey.hpp +++ b/core/shader/recompiler/CacheKey.hpp @@ -381,6 +381,7 @@ class RecompileCacheKey { append(key, value.gpuResolvedImages); append(key, value.descriptorMemory); append(key, value.heapDataUniformDwords); + append(key, value.heapBufferDescriptors); append(key, value.ldsLockFences); append(key, value.meshWindowBuffer); append(key, value.hostInterpolationFirst); diff --git a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp index 6a2c65e159b2..953935f6408b 100644 --- a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp +++ b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp @@ -952,6 +952,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const writer.WriteBool(request.target.deviceScopeLdsMemoryBarriers); writer.WriteBool(request.target.exactRobustLoads); writer.WriteBool(request.target.robustBufferAccess2); + writer.WriteBool(request.target.heapBufferDescriptors); return base64Encode(buffer); } @@ -1033,6 +1034,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const result.request.target.deviceScopeLdsMemoryBarriers = reader.ReadBool(); result.request.target.exactRobustLoads = reader.ReadBool(); result.request.target.robustBufferAccess2 = reader.ReadBool(); + result.request.target.heapBufferDescriptors = reader.ReadBool(); } if (version >= 21u && reader.Remaining() != 0u) throw std::runtime_error("RequestSerializer: unexpected trailing data"); return result; diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 896b5cc7e652..8bbe91e714e6 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -787,6 +787,7 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) targetOptions.deviceScopeLdsMemoryBarriers = request.target.deviceScopeLdsMemoryBarriers; targetOptions.gpuResolvedImages = allocation.gpuResolvedImages; targetOptions.heapDataUniformDwords = request.target.heapDataUniformDwords; + targetOptions.heapBufferDescriptors = request.target.descriptorMemory && request.target.heapBufferDescriptors; targetOptions.ldsLockFences = request.target.ldsLockFences; targetOptions.meshWindowBuffer = request.target.meshWindowBuffer; diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 8626085d9f97..08b9a3f30844 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -360,6 +360,7 @@ struct SpirvTarget { bool gpuResolvedImages = false; bool descriptorMemory = false; std::uint32_t heapDataUniformDwords = 0; + bool heapBufferDescriptors = false; bool ldsLockFences = false; bool fragmentBarycentricBuiltins = false; bool meshWindowBuffer = false; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp index 6c9bebe6a013..f3a11d957138 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp @@ -46,6 +46,7 @@ struct SpirvTargetOptions { bool deviceScopeLdsMemoryBarriers = false; bool gpuResolvedImages = false; std::uint32_t heapDataUniformDwords = 0; + bool heapBufferDescriptors = false; bool ldsLockFences = false; bool meshWindowBuffer = false; }; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index 23af8bda15a9..70c29d29f79a 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -116,6 +116,7 @@ struct SpirvEmitterState { bool registrationModules = false; bool gpuResolvedImages = false; std::uint32_t heapDataUniformDwords = 0; + bool heapBufferDescriptors = false; bool addressedBuffers = false; std::optional guestBuffersWritten; bool fragmentDescriptorSet = false; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp index 70c8433965db..c2e861015149 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp @@ -282,6 +282,7 @@ std::vector SpirvEmitter::Emit(const IrProgram& program, const Sh state.registrationModules = target.registrationModules; state.gpuResolvedImages = target.gpuResolvedImages; state.heapDataUniformDwords = target.heapDataUniformDwords; + state.heapBufferDescriptors = target.heapBufferDescriptors; state.fragmentDescriptorSet = target.fragmentDescriptorSet; state.meshBarycentricPixel = target.meshBarycentricPixel; state.meshBarycentricVertex = target.meshBarycentricVertex; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 19d704c40b48..c4050709b034 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -112,10 +112,13 @@ std::uint32_t dataAddressLoad(SpirvEmitterState& state, RuntimeAbi::RootStageFie const auto u32 = TypeU32(state); const auto vector = Binary(state, spv::OpShiftRightLogical, u32, index, ConstantU32(state, 2u)); const auto component = Binary(state, spv::OpBitwiseAnd, u32, index, ConstantU32(state, 3u)); + const auto u32x4 = TypeU32Vector(state, 4); const auto element = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassUniform, u32), element, state.shaderDataUniformVariable, ConstantU32(state, 0u), vector, component); + state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassUniform, u32x4), element, state.shaderDataUniformVariable, ConstantU32(state, 0u), vector); + const auto words = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, u32x4, words, element); const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, u32, value, element); + state.module.AddFunction(spv::OpVectorExtractDynamic, u32, value, words, component); return value; } const auto pointer = EmitStageRingWordPointer(state, field, index); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index 2b4761b8ce3e..a096ef9b5359 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -508,8 +508,8 @@ void DefineDescriptors(SpirvEmitterState& state) { return state.module.Type(spv::OpTypeArray, type, length); }; switch (binding.kind) { - case DescriptorBindingKind::Buffers: - if (layout.bufferAddressDwords != 0u) { + case DescriptorBindingKind::Buffers: { + if (layout.bufferAddressDwords != 0u && !state.heapBufferDescriptors) { state.addressedBuffers = true; break; } @@ -526,6 +526,7 @@ void DefineDescriptors(SpirvEmitterState& state) { if (state.storageBufferU64Variable != 0u) state.module.AddAnnotation(spv::OpDecorate, state.storageBufferU64Variable, spv::DecorationCoherent); } break; + } case DescriptorBindingKind::BdaPagetable: if (layout.UsesDataAddress()) { state.bdaPagetableVariable = state.module.AllocateId(); @@ -553,10 +554,10 @@ void DefineDescriptors(SpirvEmitterState& state) { } break; case DescriptorBindingKind::FlattenedSrt: - if (layout.UsesDataAddress()) state.flattenedSrtAddressed = true; + if (layout.UsesDataAddress() && !state.heapBufferDescriptors) state.flattenedSrtAddressed = true; else { state.flattenedSrtVariable = Define(StorageBufferBlockType(state), "flattened_srt"); - state.module.AddAnnotation(spv::OpDecorate, state.flattenedSrtVariable, spv::DecorationNonWritable); + if (!layout.UsesDataAddress()) state.module.AddAnnotation(spv::OpDecorate, state.flattenedSrtVariable, spv::DecorationNonWritable); } break; case DescriptorBindingKind::Samplers: diff --git a/core/shader/recompiler/tests/RequestSerializerTests.cpp b/core/shader/recompiler/tests/RequestSerializerTests.cpp index 5c653fcfcca6..2de7ca0bb6e3 100644 --- a/core/shader/recompiler/tests/RequestSerializerTests.cpp +++ b/core/shader/recompiler/tests/RequestSerializerTests.cpp @@ -174,9 +174,21 @@ std::string EncodeBase64(const std::vector& bytes) { return text; } +std::vector WithoutHeapBufferDescriptors(std::vector bytes) { + Require(bytes.size() > 1u && bytes[4] == 55u && bytes.back() == 0u); + bytes.pop_back(); + return bytes; +} + +std::vector WithHeapBufferDescriptors(std::vector bytes) { + Require(bytes.size() > 4u && bytes[4] == 55u); + bytes.push_back(0u); + return bytes; +} + std::string EncodeWithDefaultVersion55Tail(std::vector bytes) { bytes[4] = 55u; - bytes.insert(bytes.end(), 13u, 0u); + bytes.insert(bytes.end(), 14u, 0u); return EncodeBase64(bytes); } @@ -218,8 +230,8 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { Require(replay.request.target.heapDataUniformDwords == profile.heapDataUniformDwords); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 55u && bytes.size() > 12u); - bytes.resize(bytes.size() - 12u); + Require(bytes[4] == 55u && bytes.size() > 13u); + bytes.resize(bytes.size() - 13u); for (const std::uint8_t version : {54u, 53u, 52u}) { if (version == 52u) bytes.pop_back(); bytes[4] = version; @@ -252,6 +264,17 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { ShaderRecompiler::RecompileRequest addressed = limits; addressed.target.heapDataUniformDwords = 0u; Require(serializer.Serialize(limits) != serializer.Serialize(addressed)); + for (const bool descriptors : {false, true}) { + auto request = limits; + request.target.heapBufferDescriptors = descriptors; + const auto encoded = serializer.Serialize(request); + Require(serializer.Deserialize(encoded).request.target.heapBufferDescriptors == descriptors); + Require((encoded == serializer.Serialize(limits)) == !descriptors); + auto bytes = DecodeBase64(encoded); + bytes.resize(bytes.size() - 13u); + bytes[4] = 54u; + Require(!serializer.Deserialize(EncodeBase64(bytes)).request.target.heapBufferDescriptors); + } } void VerifyKeyedTargetFields(const ShaderRecompiler::RequestSerializer& serializer) { @@ -268,8 +291,8 @@ void VerifyKeyedTargetFields(const ShaderRecompiler::RequestSerializer& serializ for (std::size_t index = 0; index < fields.size(); ++index) Require(replay.request.target.*fields[index] == (chosen == fields.size() || index == chosen)); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 55u && bytes.size() > 12u); - bytes.resize(bytes.size() - 12u); + Require(bytes[4] == 55u && bytes.size() > 13u); + bytes.resize(bytes.size() - 13u); for (const std::uint8_t version : {54u, 53u, 52u}) { if (version == 52u) bytes.pop_back(); bytes[4] = version; @@ -650,7 +673,7 @@ int main() { pointed.context.vertex->pointSize = 3.0f; pointed.context.vertex->pointSizeMin = 1.0f; pointed.context.vertex->pointSizeMax = 8.0f; - auto version55 = DecodeBase64(serializer.Serialize(pointed)); + auto version55 = WithoutHeapBufferDescriptors(DecodeBase64(serializer.Serialize(pointed))); Require(version55.size() > 31u && version55[4] == 55u); auto version53 = version55; version53.resize(version53.size() - 12u); @@ -681,7 +704,7 @@ int main() { version43.pop_back(); version43[4] = 43u; const auto replay43 = serializer.Deserialize(EncodeBase64(version43)); - Require(serializer.Serialize(replay43.request) == EncodeBase64(version55)); + Require(serializer.Serialize(replay43.request) == EncodeBase64(WithHeapBufferDescriptors(version55))); Require(replay43.request.graphics->tessellation->mergedHull == merged && replay43.request.context.vertex->pointList && replay43.request.context.vertex->pointSize == 3.0f && replay43.request.context.vertex->pointSizeMin == 1.0f && replay43.request.context.vertex->pointSizeMax == 8.0f); auto version42 = version43; version42.resize(version42.size() - 13u); @@ -738,7 +761,7 @@ int main() { const auto encoded = serializer.Serialize(request); const auto replay = serializer.Deserialize(encoded); Require(replay.request.target.float16DenormPreserve == preserve && replay.request.target.float32FlushToZero == !preserve && replay.request.target.float32DenormPreserve == preserve && replay.request.target.largePixelFunctionLdsBuffer == !preserve && replay.request.target.pixelFunctionStorageDwords == request.target.pixelFunctionStorageDwords); - auto bytes = DecodeBase64(encoded); + auto bytes = WithoutHeapBufferDescriptors(DecodeBase64(encoded)); Require(bytes.size() >= 8u && bytes[4] == 55u && bytes[5] == 0u && bytes[6] == 0u && bytes[7] == 0u); auto version40 = bytes; version40.resize(version40.size() - 14u); @@ -794,7 +817,7 @@ int main() { request.context.pixel = pixel; const auto orderEncoded = serializer.Serialize(request); Require(serializer.Deserialize(orderEncoded).request.context.pixel->sampleOrder == pixel.sampleOrder); - auto version42 = DecodeBase64(orderEncoded); + auto version42 = WithoutHeapBufferDescriptors(DecodeBase64(orderEncoded)); version42.resize(version42.size() - 12u); const auto orderOffset = std::search(version42.begin(), version42.end(), pixel.sampleLocations.begin(), pixel.sampleLocations.end()) - version42.begin() + static_cast(pixel.sampleLocations.size() + 1u); Require(version42.end() - version42.begin() > orderOffset + static_cast(sizeof(pixel.sampleOrder)) && version42[static_cast(orderOffset)] == 0x10u); @@ -823,7 +846,7 @@ int main() { request.target.spannedWaves = spanned; Require(serializer.Deserialize(serializer.Serialize(request)).request.target.spannedWaves == spanned); request.target.float32FlushToZero = true; - auto version35 = DecodeBase64(serializer.Serialize(request)); + auto version35 = WithoutHeapBufferDescriptors(DecodeBase64(serializer.Serialize(request))); version35.resize(version35.size() - 14u); version35.resize(version35.size() - sizeof(std::uint32_t)); version35.pop_back(); @@ -875,7 +898,7 @@ int main() { for (const bool spanned : {false, true}) { for (const std::uint8_t version : {32u, 33u, 34u, 35u, 36u, 37u, 38u}) { pointRequest.target.spannedWaves = spanned; - auto legacy = DecodeBase64(serializer.Serialize(pointRequest)); + auto legacy = WithoutHeapBufferDescriptors(DecodeBase64(serializer.Serialize(pointRequest))); legacy.resize(legacy.size() - (version >= 36u ? 36u : version >= 35u ? 37u : 42u)); legacy[4] = version; const auto replayLegacy = serializer.Deserialize(EncodeBase64(legacy)); @@ -887,7 +910,7 @@ int main() { Require(replayLegacy.request.context.vertex->paClVsOutCntl == pointRequest.context.vertex->paClVsOutCntl); Require(!replayLegacy.request.context.vertex->pointList && replayLegacy.request.context.vertex->pointSize == 1.0f); Require(replayLegacy.request.context.vertex->pointSizeMin == 0.0f && replayLegacy.request.context.vertex->pointSizeMax == 0.0f); - const auto upgradedLegacy = DecodeBase64(serializer.Serialize(replayLegacy.request)); + const auto upgradedLegacy = WithoutHeapBufferDescriptors(DecodeBase64(serializer.Serialize(replayLegacy.request))); Require(upgradedLegacy[4] == 55u && upgradedLegacy.size() == legacy.size() + (version >= 36u ? 36u : version >= 35u ? 37u : 42u)); } } @@ -896,7 +919,7 @@ int main() { pointRequest.context.pixel = pixel; const auto sampledPoint = serializer.Deserialize(serializer.Serialize(pointRequest)); Require(sampledPoint.request.context.vertex->pointList && sampledPoint.request.context.pixel->sampleOrder == pixel.sampleOrder); - auto legacy43 = DecodeBase64(serializer.Serialize(pointRequest)); + auto legacy43 = WithoutHeapBufferDescriptors(DecodeBase64(serializer.Serialize(pointRequest))); legacy43.resize(legacy43.size() - 12u); const auto mergeOffset = std::search(legacy43.begin(), legacy43.end(), pixel.sampleLocations.begin(), pixel.sampleLocations.end()) - legacy43.begin() + static_cast(pixel.sampleLocations.size() + 1u + sizeof(pixel.sampleOrder)); EraseDefaultTargetMerge(legacy43, mergeOffset); @@ -918,7 +941,7 @@ int main() { Require(pointReplay42.request.context.pixel->sampleOrder == pixel.sampleOrder && !pointReplay42.request.context.vertex->pointList && pointReplay42.request.context.vertex->pointSize == 1.0f); pixel.sampleOrder = {}; pointRequest.context.pixel = pixel; - auto legacy34 = DecodeBase64(serializer.Serialize(pointRequest)); + auto legacy34 = WithoutHeapBufferDescriptors(DecodeBase64(serializer.Serialize(pointRequest))); legacy34.resize(legacy34.size() - 42u); const auto stencil34 = std::search(legacy34.begin(), legacy34.end(), pixel.sampleLocations.begin(), pixel.sampleLocations.begin() + 4) + pixel.sampleLocations.size(); const auto legacyPixelTail = static_cast(1u + sizeof(pixel.sampleOrder)); @@ -933,8 +956,8 @@ int main() { for (const bool fused : {false, true}) { request.target.fusedExactArithmetic = fused; request.target.largePixelFunctionLdsBuffer = false; - auto bytes = DecodeBase64(serializer.Serialize(request)); - Require(serializer.Deserialize(EncodeBase64(bytes)).request.target.fusedExactArithmetic == fused && bytes[bytes.size() - 22u] == (fused ? 1u : 0u) && bytes[bytes.size() - 21u] == 0u); + auto bytes = WithoutHeapBufferDescriptors(DecodeBase64(serializer.Serialize(request))); + Require(serializer.Deserialize(EncodeBase64(WithHeapBufferDescriptors(bytes))).request.target.fusedExactArithmetic == fused && bytes[bytes.size() - 22u] == (fused ? 1u : 0u) && bytes[bytes.size() - 21u] == 0u); bytes.resize(bytes.size() - 14u); bytes.pop_back(); bytes.pop_back(); @@ -952,12 +975,12 @@ int main() { Require(request.context.pixel.has_value()); request.context.pixel->ditheredAlphaToCoverage = true; request.context.pixel->ditheredAlphaSamples = 2u; - auto twoSample = DecodeBase64(serializer.Serialize(request)); - const auto twoReplay = serializer.Deserialize(EncodeBase64(twoSample)); + auto twoSample = WithoutHeapBufferDescriptors(DecodeBase64(serializer.Serialize(request))); + const auto twoReplay = serializer.Deserialize(EncodeBase64(WithHeapBufferDescriptors(twoSample))); Require(twoReplay.request.context.pixel->ditheredAlphaToCoverage && twoReplay.request.context.pixel->ditheredAlphaSamples == 2u); request.context.pixel->ditheredAlphaSamples = 8u; - const auto eightSample = DecodeBase64(serializer.Serialize(request)); - const auto eightReplay = serializer.Deserialize(EncodeBase64(eightSample)); + const auto eightSample = WithoutHeapBufferDescriptors(DecodeBase64(serializer.Serialize(request))); + const auto eightReplay = serializer.Deserialize(EncodeBase64(WithHeapBufferDescriptors(eightSample))); Require(eightReplay.request.context.pixel->ditheredAlphaToCoverage && eightReplay.request.context.pixel->ditheredAlphaSamples == 8u); Require(twoSample.size() == eightSample.size()); std::size_t ditherByte = 0u; @@ -995,7 +1018,7 @@ int main() { for (const bool subgroups : {false, true}) { domain.target.tessellationEvaluationSubgroups = subgroups; const auto encoded = serializer.Serialize(domain); - auto bytes = DecodeBase64(encoded); + auto bytes = WithoutHeapBufferDescriptors(DecodeBase64(encoded)); Require(bytes.size() > 15u && bytes[4] == 55u && bytes[bytes.size() - 15u] == (subgroups ? 1u : 0u)); Require(serializer.Deserialize(encoded).request.target.tessellationEvaluationSubgroups == subgroups); bytes.resize(bytes.size() - 12u); @@ -1038,7 +1061,7 @@ int main() { hostFirstEncoded[hostFirst] = serializer.Serialize(request); const auto replay = serializer.Deserialize(hostFirstEncoded[hostFirst]); Require(replay.request.target.hostInterpolationFirst == hostFirst && serializer.Serialize(replay.request) == hostFirstEncoded[hostFirst]); - auto bytes = DecodeBase64(hostFirstEncoded[hostFirst]); + auto bytes = WithoutHeapBufferDescriptors(DecodeBase64(hostFirstEncoded[hostFirst])); Require(bytes[4] == 55u && bytes[bytes.size() - 13u] == 0u && bytes[bytes.size() - 14u] == (hostFirst ? 1u : 0u)); bytes.resize(bytes.size() - 13u); bytes[4] = 52u; @@ -1051,8 +1074,8 @@ int main() { request.target.hostInterpolationFirst = false; for (const bool minLod : {false, true}) { request.target.shaderImageMinLod = minLod; - auto bytes = DecodeBase64(serializer.Serialize(request)); - Require(serializer.Deserialize(EncodeBase64(bytes)).request.target.shaderImageMinLod == minLod && bytes[4] == 55u && bytes[bytes.size() - 13u] == (minLod ? 1u : 0u)); + auto bytes = WithoutHeapBufferDescriptors(DecodeBase64(serializer.Serialize(request))); + Require(serializer.Deserialize(EncodeBase64(WithHeapBufferDescriptors(bytes))).request.target.shaderImageMinLod == minLod && bytes[4] == 55u && bytes[bytes.size() - 13u] == (minLod ? 1u : 0u)); bytes.resize(bytes.size() - 12u); for (const std::uint8_t version : {53u, 54u}) { bytes[4] = version; diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index d4366c808487..5e7bdd8a3afd 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -668,7 +668,6 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_MIMALLOC` | presence | `core/libs/prx/libkernel/System/src/MimallocMacOs.cpp` | | makes the process allocate through mimalloc instead of the system allocator: on Windows the entry stub (`core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp`) loads `mimalloc.dll`, on macOS libkernel restarts the title with `libmimalloc.dylib` in `DYLD_INSERT_LIBRARIES` | | `APS5_MIMALLOC_RESTARTED` | presence | `core/libs/prx/libkernel/System/src/MimallocMacOs.cpp` | | on macOS, set by libkernel for the restart that loads mimalloc and removed at start-up, so a restart that did not load it is not repeated | | `APS5_NO_DIRECT_MEMORY_SECTION_POOL` | presence | `core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp` | | on Windows, creates a section for every direct-memory allocation and closes it at release instead of reusing released sections that never held guest data | -| `APS5_NO_HEAP_DATA_UNIFORM` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | | keeps the GPU heap's shader-data ring in its own buffer and has GPU-mode stages read their shader data through device-address pointers, instead of placing the ring inside the resource heap and reading it as a uniform buffer mapped from heap data | | `APS5_NO_HEAP_DEVICE_DESCRIPTORS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | | allocates the GPU heap's resource and sampler heaps in host-visible memory instead of device-local host-visible memory (the resource heap stays device-local while it holds the shader-data ring) | | `APS5_NO_JOB_AFFINITY` | presence | `core/libs/prx/libkernel/Pthread/src/Thread.cpp` | | on Windows, disables pinning of job worker threads | | `APS5_NO_SLEEP_WAKE` | presence | `core/libs/prx/libkernel/Time/SleepWake.cpp` | | keeps every sleep of 1 ms or less in full instead of ending it at a GPU batch, batch completion action or flip completion | From c9bac36abbd92237d776a094769386e2b8ce74a2 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 3 Nov 2026 21:56:32 +0530 Subject: [PATCH 107/269] fix(agc): put the push-only dispatch limit check on the lowest-limit axis RunDispatchArguments put its oversized group count, 0xffffffff, on X. AMD's Windows driver and RADV report a maxComputeWorkGroupCount X of 4294967295, so the count was within the limit and the refusal check failed. The count now goes on the axis with the lowest limit, at that limit plus one, and the refusal check is skipped when every axis allows UINT32_MAX. createPushOnlyHeapPipeline returns no pipeline when creating it throws, so a refused heap variant leaves the classic dispatch-argument and mesh-argument pipelines in use. Drops the explanatory comments added in Recorder.hpp, HeapTemplateBudget.hpp and PushOnlyHeapPasses.cpp. --- .../libSceAgcDriver/Graphics/include/Recorder.hpp | 4 ---- .../prx/libSceAgcDriver/Graphics/src/Recorder.cpp | 8 ++++++-- .../tests/execution/PushOnlyHeapPasses.cpp | 15 ++++++++------- core/shader/recompiler/HeapTemplateBudget.hpp | 8 -------- 4 files changed, 14 insertions(+), 21 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index 407435656f2f..37930ad3436a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -777,10 +777,6 @@ class Recorder { VkPipelineLayout changedCopyLayout = VK_NULL_HANDLE; VkPipeline changedCopyPipeline = VK_NULL_HANDLE; VkPipeline changedCopyHeapPipeline = VK_NULL_HANDLE; - // The descriptor heap variant of a compute pipeline that reads only push constants (null outside - // descriptor heap mode or when the driver refuses it). Its parameters go in with vkCmdPushDataEXT, - // so the pass leaves a command buffer in descriptor heap mode: a classic vkCmdPushConstants would - // make the next heap draw bind the heaps again. VkPipeline createPushOnlyHeapPipeline(const VkComputePipelineCreateInfo& info) const; void bindPushOnlyPipeline(VkCommandBuffer commands, VkPipeline pipeline, VkPipeline heapPipeline) const; void pushOnlyParameters(VkCommandBuffer commands, VkPipeline heapPipeline, VkPipelineLayout layout, std::uint32_t bytes, const void* values) const; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 2e825030fb4a..5a883158e27c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -2788,8 +2788,12 @@ VkPipeline Recorder::createPushOnlyHeapPipeline(const VkComputePipelineCreateInf heapInfo.pNext = &heapFlags; heapInfo.layout = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; - auto pipelineCacheLock = context.LockPipelineCacheForUse(); - if (context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &heapInfo, nullptr, &pipeline) != VK_SUCCESS) return VK_NULL_HANDLE; + try { + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + if (context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &heapInfo, nullptr, &pipeline) != VK_SUCCESS) return VK_NULL_HANDLE; + } catch (const std::exception&) { + return VK_NULL_HANDLE; + } return pipeline; } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PushOnlyHeapPasses.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PushOnlyHeapPasses.cpp index 885593af4a75..610fc266e510 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PushOnlyHeapPasses.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PushOnlyHeapPasses.cpp @@ -4,10 +4,12 @@ #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "VulkanTestDevice.hpp" +#include #include #include #include #include +#include #include #include #include @@ -20,9 +22,6 @@ using AgcDriver::Graphics::Buffer; using AgcDriver::Graphics::Recorder; using AgcDriver::Graphics::Require; -// The changed copy reads only push constants. It copies the same in both modes; in descriptor heap -// mode it must also leave its command buffer in heap mode (parameters through vkCmdPushDataEXT on a -// heap pipeline): a classic vkCmdPushConstants would make the next heap draw bind the heaps again. void RunChangedCopy(const AgcDriver::VulkanDevice& device) { const auto context = device.graphicsContext(); const bool heapMode = AgcDriver::Graphics::DescriptorHeapEnabled() && context.descriptorHeap && BindlessHeap::For(context).DescriptorHeapMode(); @@ -58,8 +57,6 @@ void RunChangedCopy(const AgcDriver::VulkanDevice& device) { } } -// The indirect dispatch argument check is the same kind of pass: group counts from thread counts, -// and a count past the device limit dispatches nothing. void RunDispatchArguments(const AgcDriver::VulkanDevice& device) { const auto context = device.graphicsContext(); const bool heapMode = AgcDriver::Graphics::DescriptorHeapEnabled() && context.descriptorHeap && BindlessHeap::For(context).DescriptorHeapMode(); @@ -69,7 +66,11 @@ void RunDispatchArguments(const AgcDriver::VulkanDevice& device) { auto grouped = std::make_shared(context, 32, usage); auto refused = std::make_shared(context, 32, usage); const std::uint32_t threadCounts[4] = {3u, 5u, 7u, 0u}; - const std::uint32_t tooMany[4] = {0xffffffffu, 1u, 1u, 0u}; + const auto* limit = context.limits.maxComputeWorkGroupCount; + const auto axis = static_cast(std::min_element(limit, limit + 3) - limit); + const bool limited = limit[axis] < std::numeric_limits::max(); + std::uint32_t tooMany[4] = {1u, 1u, 1u, 0u}; + tooMany[axis] = limited ? limit[axis] + 1u : limit[axis]; std::memcpy(threads->Bytes().data(), threadCounts, sizeof(threadCounts)); std::memcpy(oversized->Bytes().data(), tooMany, sizeof(tooMany)); std::memset(grouped->Bytes().data(), 0xff, 32); @@ -94,7 +95,7 @@ void RunDispatchArguments(const AgcDriver::VulkanDevice& device) { const std::uint32_t expected[6] = {2u, 3u, 4u, 3u, 5u, 7u}; for (std::size_t i = 0; i < 6; ++i) Require(words[i] == expected[i], "push-only heap passes: dispatch argument word " + std::to_string(i) + " is " + std::to_string(words[i]) + ", expected " + std::to_string(expected[i])); std::memcpy(words, refused->Bytes().data(), 3 * sizeof(std::uint32_t)); - Require(words[0] == 0u && words[1] == 0u && words[2] == 0u, "push-only heap passes: a group count past the device limit was dispatched"); + if (limited) Require(words[0] == 0u && words[1] == 0u && words[2] == 0u, "push-only heap passes: a group count past the device limit was dispatched"); } } diff --git a/core/shader/recompiler/HeapTemplateBudget.hpp b/core/shader/recompiler/HeapTemplateBudget.hpp index 6885e9d28c21..ee94bc9741d0 100644 --- a/core/shader/recompiler/HeapTemplateBudget.hpp +++ b/core/shader/recompiler/HeapTemplateBudget.hpp @@ -27,8 +27,6 @@ template OwnedBytes(binding.bufferExtent); } -// The bytes a heap template's result owns. Its SPIR-V module is shared with the variant it was -// materialized from, so it is not charged. [[nodiscard]] inline std::uint64_t OwnedBytes(const RecompileResult& result) { std::uint64_t bytes = sizeof(RecompileResult) + OwnedBytes(result.vertexInputPatches) + OwnedBytes(result.runtimeImageResources) + OwnedBytes(result.vertexInputs) + OwnedBytes(result.parameterExports) + OwnedBytes(result.fragmentParameters) + OwnedBytes(result.stencilReferences) + OwnedBytes(result.specialization) + OwnedBytes(result.heapSlotWords) + OwnedBytes(result.bindings) + @@ -40,10 +38,6 @@ template return bytes; } -// Least recently used order of the heap templates of every shader, under one byte budget. A -// template is named by its owner (the shader it belongs to), its key in that shader's map, and -// the id of the template built for that key, so a touch or an eviction never reaches a later -// template that took the same owner and key. class HeapTemplateLru { public: struct Name { @@ -59,8 +53,6 @@ class HeapTemplateLru { explicit HeapTemplateLru(std::uint64_t budget) : budget(budget) {} - // Adds a template as the most recently used, and returns the templates evicted to bring the - // total back under the budget, least recently used first. [[nodiscard]] std::vector Insert(const Name& name, std::uint64_t bytes, std::weak_ptr owner = {}) { std::vector evicted; if (const auto found = index.find(Slot{name.owner, name.key}); found != index.end()) { From 39b8256b44013337b36fd011445b1fe4e66b891a Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 3 Nov 2026 22:29:47 +0530 Subject: [PATCH 108/269] docs(agc): list the GPU heap's per-draw stages as the code takes them Mesh and tessellation stages, compute stages without images, GDS and the fault buffer all map onto the heap now; geometry stages and registration modules' set 0 storage images are what still take the per-draw path. --- docs/dev/debt/libSceAgcDriver.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index dcd83f8d544e..8f1e0e700d23 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -370,5 +370,5 @@ ### Opt-in draw paths - [Draw finisher](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp) (`APS5_DRAW_PIPELINE`) - opt-in. The Linux main-image page table it adds matches what Windows already does by default. -- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap`. A stage whose module keeps a set 0 binding (storage images of registration modules, GDS, the fault buffer), mesh and tessellation pipelines and compute stages without images take the per-draw path, and so does every other stage of their draw. A stage that needs more image slots than the heap holds also takes the per-draw path; with `APS5_HEAP_SLOT_CAP` far below the default, stages that each fit can still exhaust the heap between their compile and their bind, because the nearly-full margin scales with the cap. +- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap`. Geometry stages and stages whose module keeps a set 0 binding the heap does not map (storage images of registration modules) take the per-draw path, and so does every other stage of their draw. A stage that needs more image slots than the heap holds also takes the per-draw path; with `APS5_HEAP_SLOT_CAP` far below the default, stages that each fit can still exhaust the heap between their compile and their bind, because the nearly-full margin scales with the cap. - [Multi-submit count overflow and buffer validation](../../../core/libs/prx/libSceAgcDriver/Submit/src/Dcb.cpp) (libSceAgcDriver) - whether the console driver imposes an architectural submission packet limit or allows null buffer pointers with non-zero sizes in multi-submit arrays is unmeasured; AgcDriver::SubmitMany validates count against 32-bit pointer array bounds overflow and rejects null addresses for non-empty command buffers with a runtime exception. From 0720b80827d53399a0297fef2e338c868da0b93a Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 3 Nov 2026 22:35:10 +0530 Subject: [PATCH 109/269] test(agc): submit a tessellation draw followed by a geometry stage agc_driver_tessellation_submit now also submits the tessellation and geometry routing (VGT_SHADER_STAGES_EN 0x212d, the domain program merged with its geometry half), so the inserted capture geometry shader runs through the PM4 draw path. Under APS5_GPU_HEAP every guest stage of that draw takes the heap, which the existing data-address push check requires. The debt entry no longer lists geometry stages as per-draw: the only geometry stages are host-generated, declare no descriptors and map onto the heap. --- .../tests/execution/TessellationSubmit.cpp | 62 ++++++++++++++----- docs/dev/debt/libSceAgcDriver.md | 2 +- 2 files changed, 48 insertions(+), 16 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp index c241cf1a0abf..61a57f73e8f8 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -42,6 +43,26 @@ alignas(256) constexpr std::array DomainCode{ 0x040a0d05, 0x102424ff, 0x40400000, 0x7e260280, 0x7e2802f2, 0xf80008cf, 0x14131110, 0xf800020f, 0x14131214, 0xbf810000, }; +alignas(256) constexpr std::array DomainGeometryCode{ + 0x8f6a9003, 0x94fe6ac1, 0xbf880028, 0x342a0e84, 0x162a2a83, 0xe0341000, 0x04030a15, 0xe0341010, + 0x04030c15, 0xe0341020, 0x04030e15, 0xbf8c3f70, 0x082c0af2, 0x082c0d16, 0x10201505, 0x3e201906, + 0x3e201d16, 0x10221705, 0x3e221b06, 0x3e221f16, 0xd5510012, 0x045a0d05, 0x102424ff, 0x40400000, + 0x7e260280, 0x7e2802f2, 0xd7650009, 0x000100c1, 0xd7660009, 0x000212c1, 0x93ebff03, 0x00040018, + 0xd7460009, 0x04250c6b, 0x34121285, 0xd8380100, 0x00111009, 0xd8380302, 0x00141309, 0xd8380504, + 0x00121409, 0xd8380706, 0x00141309, 0xbf8cc07f, 0xbefe04c1, 0xbf8a0000, 0x938dff02, 0x00090016, + 0x9382ff03, 0x00040018, 0x938cff03, 0x00080008, 0xd7650009, 0x000100c1, 0xd7660009, 0x000212c1, + 0xd746000a, 0x04250c02, 0x7da8120c, 0xbf88002e, 0x361600ff, 0x0000ffff, 0x34161682, 0x2c180090, + 0x34181882, 0x361a02ff, 0x0000ffff, 0x341a1a82, 0xdbfc0000, 0x1000000b, 0xdbfc0010, 0x1400000b, + 0xdbfc0000, 0x1800000c, 0xdbfc0010, 0x1c00000c, 0xdbfc0000, 0x2000000d, 0xdbfc0010, 0x2400000d, + 0xbf8cc07f, 0xbf800000, 0xbf800000, 0xbf800000, 0x161c1483, 0x161e14ff, 0x00000060, 0xbf8c3f70, + 0xdb7c0400, 0x0000100f, 0xdb7c0410, 0x0000140f, 0xdb7c0420, 0x0000180f, 0xdb7c0430, 0x00001c0f, + 0xdb7c0440, 0x0000200f, 0xdb7c0450, 0x0000240f, 0x4a501c81, 0x4a521c82, 0x3450508a, 0x34525294, + 0xd772002a, 0x04a6510e, 0xbf8cc07f, 0xbefe04c1, 0xbf8a0000, 0x930e830d, 0xbf078002, 0xbf850003, + 0x8f0f8c0d, 0x887c0f0e, 0xbf900009, 0x7da8140d, 0xbf880002, 0xf8000941, 0x0000002a, 0xbefe04c1, + 0x7da8140e, 0xbf88000a, 0x34561485, 0xdbfc0400, 0x2c00002b, 0xdbfc0410, 0x3000002b, 0xbf8cc07f, + 0xf80008cf, 0x2f2e2d2c, 0xf800020f, 0x33323130, 0xbf810000, +}; + alignas(256) constexpr std::array PixelCode{ 0xc8020002, 0xc8060102, 0xc80a0202, 0xc80e0302, 0xf800180f, 0x03020100, 0xbf810000, }; @@ -65,6 +86,7 @@ struct Header { Header LocalHeader{}; Header HullHeader{}; Header DomainHeader{}; +Header DomainGeometryHeader{}; Header PixelHeader{}; void Register(Header& header, const std::uint32_t* code, std::size_t size, std::uint8_t type) { @@ -90,10 +112,10 @@ std::uint32_t Hi(const void* address) { return static_cast(reinterpret_cast(address) >> 40u); } -std::vector Commands() { +std::vector Commands(bool geometry) { const auto color = reinterpret_cast(Pixels.data()); const auto users = reinterpret_cast(HullUserMemory.data()); - const std::vector> context{{0x2d5, 0x0200210du}, + const std::vector> context{{0x2d5, geometry ? 0x0000212du : 0x0200210du}, {0x2d6, 128u | (3u << 8u) | (3u << 14u)}, {0x2db, 1u | (2u << 2u) | (2u << 5u)}, {0x286, std::bit_cast(64.0f)}, @@ -158,15 +180,20 @@ std::vector Commands() { {0x102, static_cast(users)}, {0x103, static_cast(users >> 32u)}, {0x10b, 0}, - {0xc8, Lo(DomainCode.data())}, - {0xc9, Hi(DomainCode.data())}, - {0x8b, 0}, + {0xc8, geometry ? Lo(DomainGeometryCode.data()) : Lo(DomainCode.data())}, + {0xc9, geometry ? Hi(DomainGeometryCode.data()) : Hi(DomainCode.data())}, + {0x8a, 0}, + {0x8b, geometry ? 0x400010u : 0u}, {0x8, Lo(PixelCode.data())}, {0x9, Hi(PixelCode.data())}, {0xb, 0}}; std::vector commands; Write(commands, 0x79, 0x242, 9); for (const auto& [offset, value] : context) Write(commands, 0x69, offset, value); + if (geometry) { + for (const auto& [offset, value] : std::initializer_list>{{0x1ff, 12u}, {0x2ce, 3u}, {0x2ab, 8u}, {0x29b, 2u}}) Write(commands, 0x69, offset, value); + Write(commands, 0x79, 0x25b, 0x1804u); + } for (const auto& [offset, value] : shaders) Write(commands, 0x76, offset, value); commands.insert(commands.end(), {0xc0002a00u, 0u}); const auto address = reinterpret_cast(Indices.data()); @@ -208,30 +235,32 @@ std::uint32_t CoveredPixels(std::uint32_t patch, bool interior) { return count; } -void SubmittedPatches() { +void SubmittedPatches(bool geometry) { for (std::size_t i = 0; i < Pixels.size(); i += 4) { for (std::size_t c = 0; c < 4; ++c) Pixels[i + c] = std::byte{Background[c]}; } const auto pushes = AgcDriver::Graphics::DataAddressPushes(); - auto commands = Commands(); + auto commands = Commands(geometry); + const std::string path = geometry ? "tessellation and geometry" : "tessellation"; Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; - Require(sceAgcDriverSubmitDcb(&packet) == 0, "tessellation submission failed"); + Require(sceAgcDriverSubmitDcb(&packet) == 0, path + " submission failed"); AgcDriverWaitIdle_nid_postfix(); const auto center = Row(-0.5f + 1.0f / 3.0f); Require(CoveredPixels(0, false) > 100 && CoveredPixels(0, true) == 0, - "the level-1 patch was not drawn as one flat triangle, centre " + PixelText(PixelAt(Column(0, 0.25f), center))); - Require(CoveredPixels(1, false) == 0, "the patch with level 0 was not culled"); + path + ": the level-1 patch was not drawn as one flat triangle, centre " + PixelText(PixelAt(Column(0, 0.25f), center))); + Require(CoveredPixels(1, false) == 0, path + ": the patch with level 0 was not culled"); Require(CoveredPixels(2, false) > 100 && PixelAt(Column(2, 0.25f), center)[1] > 32, - "the level-5 patch has no interior domain points at its centre, " + PixelText(PixelAt(Column(2, 0.25f), center))); - Require(PixelAt(0, 0) == Background && PixelAt(Width - 1, Height - 1) == Background, "the corners changed"); + path + ": the level-5 patch has no interior domain points at its centre, " + PixelText(PixelAt(Column(2, 0.25f), center))); + Require(PixelAt(0, 0) == Background && PixelAt(Width - 1, Height - 1) == Background, path + ": the corners changed"); Require(!AgcDriver::Graphics::DescriptorHeapEnabled() || AgcDriver::Graphics::DataAddressPushes() > pushes, - "the submitted tessellation draw did not take the descriptor heap"); + "the submitted " + path + " draw did not take the descriptor heap"); } } int main() { try { + bool geometry = false; { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; @@ -239,14 +268,17 @@ int main() { std::cout << "skipped, the device has no tessellation shaders\n"; return VulkanTestSkipped; } + geometry = device->GeometryLimits().has_value() && (device->SubgroupStages() & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) != 0; } Register(LocalHeader, LocalCode.data(), sizeof(LocalCode), 5); Register(HullHeader, HullCode.data(), sizeof(HullCode), 7); Register(DomainHeader, DomainCode.data(), sizeof(DomainCode), 2); + Register(DomainGeometryHeader, DomainGeometryCode.data(), sizeof(DomainGeometryCode), 2); Register(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1); - SubmittedPatches(); + SubmittedPatches(false); + if (geometry) SubmittedPatches(true); AgcDriverShutdown_nid_postfix(); - std::cout << "A submitted tessellation draw drew its patches\n"; + std::cout << (geometry ? "Submitted tessellation and tessellation-and-geometry draws drew their patches\n" : "A submitted tessellation draw drew its patches; the device has no geometry shaders or subgroup operations in tessellation-evaluation shaders, so the geometry draw was skipped\n"); return 0; } catch (const std::exception& error) { std::cerr << error.what() << '\n'; diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 8f1e0e700d23..b2e36bba9557 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -370,5 +370,5 @@ ### Opt-in draw paths - [Draw finisher](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp) (`APS5_DRAW_PIPELINE`) - opt-in. The Linux main-image page table it adds matches what Windows already does by default. -- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap`. Geometry stages and stages whose module keeps a set 0 binding the heap does not map (storage images of registration modules) take the per-draw path, and so does every other stage of their draw. A stage that needs more image slots than the heap holds also takes the per-draw path; with `APS5_HEAP_SLOT_CAP` far below the default, stages that each fit can still exhaust the heap between their compile and their bind, because the nearly-full margin scales with the cap. +- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap`. A stage whose module keeps a set 0 binding the heap does not map (storage images of registration modules) takes the per-draw path, and so does every other stage of its draw. A stage that needs more image slots than the heap holds also takes the per-draw path; with `APS5_HEAP_SLOT_CAP` far below the default, stages that each fit can still exhaust the heap between their compile and their bind, because the nearly-full margin scales with the cap. - [Multi-submit count overflow and buffer validation](../../../core/libs/prx/libSceAgcDriver/Submit/src/Dcb.cpp) (libSceAgcDriver) - whether the console driver imposes an architectural submission packet limit or allows null buffer pointers with non-zero sizes in multi-submit arrays is unmeasured; AgcDriver::SubmitMany validates count against 32-bit pointer array bounds overflow and rejects null addresses for non-empty command buffers with a runtime exception. From 63fe18f7f7c3c72fcdd16ce797de120acda1f10c Mon Sep 17 00:00:00 2001 From: raghav314 Date: Wed, 4 Nov 2026 01:58:08 +0530 Subject: [PATCH 110/269] fix(agc): keep the ring descriptor scratch vectors out of thread_local destructors RingBufferDescriptors kept its descriptor info and host range vectors in thread_local objects with destructors, which prx_thread_local_destructors rejects on MinGW: the destructor runs after emulated TLS freed the object. Both now live in HostThreadLocal, like ShaderResources::ringDescriptors. Under APS5_VERIFY_GPU_HEAP a stage whose inputs and descriptor run would have been kept recomputes the run's buffer ranges and fails if the kept run would bind other buffers. The tessellation-and-geometry submission is its own registration, agc_driver_tessellation_submit_geometry (and _gpu_heap), which exits 77 on a device without geometry shaders or subgroup operations in tessellation-evaluation shaders. --- .../Graphics/src/BindlessHeap.cpp | 7 +++++-- .../Graphics/src/ShaderResources.cpp | 18 ++++++++++++++++-- .../agc_driver_tessellation_submit_tests.cmake | 3 +++ .../tests/execution/TessellationSubmit.cpp | 15 +++++++++------ 4 files changed, 33 insertions(+), 10 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index cd7f5d89f89e..db10f6642635 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -8,6 +8,7 @@ #include "Recompiler.hpp" #include "RuntimeAbi.hpp" #include "SpirvBackend/SpirvAnalysis.hpp" +#include "prx/libc/include/HostThreadLocal.hpp" #include #include #include @@ -854,8 +855,10 @@ std::uint32_t BindlessHeap::RingBufferDescriptors(std::span resources; - thread_local std::vector ranges; + struct ResourcesStorage {}; + struct RangesStorage {}; + auto& resources = HostThreadLocal, ResourcesStorage>(); + auto& ranges = HostThreadLocal, RangesStorage>(); resources.assign(buffers.size(), {VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT}); ranges.resize(buffers.size()); auto* bytes = reinterpret_cast(span.words.data()); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 458cc1eb3f88..3ef31322cefb 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6847,6 +6847,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { ringDescriptorStages[stageIndex] = ringStage; if (ringStage) stageDataWords[stageIndex].clear(); bool dataKept = false; + bool inputsKept = false; bool flattened = false; for (const auto& binding : program.bindings) { const bool shaderData = binding.role == ShaderRecompiler::DescriptorRole::ShaderData; @@ -6860,6 +6861,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { stageState.dataInput.size() == words.size() + userData.size() && std::equal(words.begin(), words.end(), stageState.dataInput.begin()) && std::equal(userData.begin(), userData.end(), stageState.dataInput.begin() + static_cast(words.size())); + if (sameInput && verifySlots && heap.Held(stageState.data.mark)) inputsKept = true; if (sameInput && !verifySlots) { if (heap.Held(stageState.data.mark)) { heapOffsets[dataIndex] = stageState.data.mark.offset; @@ -6902,8 +6904,20 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { if (!flattened) heapSrtDwords[stageIndex] = 0u; auto& kept = stageState.descriptors; const auto srt = srtRange(stageIndex); - const bool reuse = dataKept && !kept.ranges.empty() && kept.ranges.front().address == srt.address && kept.ranges.front().size == srt.size && heap.Held(kept.mark); - heapOffsets[flatIndex] = reuse ? kept.first : ringDescriptors(stageIndex, nullptr, kept); + const bool keepable = !kept.ranges.empty() && kept.ranges.front().address == srt.address && kept.ranges.front().size == srt.size && heap.Held(kept.mark); + if (dataKept && keepable) { + heapOffsets[flatIndex] = kept.first; + return; + } + if (!(inputsKept && keepable)) { + heapOffsets[flatIndex] = ringDescriptors(stageIndex, nullptr, kept); + return; + } + const std::vector before(kept.ranges.begin(), kept.ranges.end()); + const auto first = kept.first; + heapOffsets[flatIndex] = ringDescriptors(stageIndex, nullptr, kept); + if (kept.first != first || !std::ranges::equal(before, kept.ranges, [](const auto& a, const auto& b) { return a.address == b.address && a.size == b.size; })) + throw std::runtime_error("AGC graphics: a GPU-mode stage's kept buffer descriptor run would bind other buffers although its inputs did not change"); } namespace { diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_tessellation_submit_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_tessellation_submit_tests.cmake index b8aeb1635260..7c5e93e4d111 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_tessellation_submit_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_tessellation_submit_tests.cmake @@ -1,3 +1,6 @@ if(BUILD_TESTING) agc_add_gpu_heap_test(agc_driver_tessellation_submit) + agc_add_env_test(agc_driver_tessellation_submit_geometry agc_driver_tessellation_submit_tests ARGS --geometry) + agc_add_env_test(agc_driver_tessellation_submit_geometry_gpu_heap agc_driver_tessellation_submit_tests ARGS --geometry + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp index 61a57f73e8f8..a58c70692612 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/TessellationSubmit.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -258,9 +259,9 @@ void SubmittedPatches(bool geometry) { } -int main() { +int main(int argc, char** argv) { try { - bool geometry = false; + const bool geometry = argc > 1 && std::string_view(argv[1]) == "--geometry"; { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; @@ -268,17 +269,19 @@ int main() { std::cout << "skipped, the device has no tessellation shaders\n"; return VulkanTestSkipped; } - geometry = device->GeometryLimits().has_value() && (device->SubgroupStages() & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) != 0; + if (geometry && (!device->GeometryLimits().has_value() || (device->SubgroupStages() & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) == 0)) { + std::cout << "skipped, the device has no geometry shaders or no subgroup operations in tessellation-evaluation shaders\n"; + return VulkanTestSkipped; + } } Register(LocalHeader, LocalCode.data(), sizeof(LocalCode), 5); Register(HullHeader, HullCode.data(), sizeof(HullCode), 7); Register(DomainHeader, DomainCode.data(), sizeof(DomainCode), 2); Register(DomainGeometryHeader, DomainGeometryCode.data(), sizeof(DomainGeometryCode), 2); Register(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1); - SubmittedPatches(false); - if (geometry) SubmittedPatches(true); + SubmittedPatches(geometry); AgcDriverShutdown_nid_postfix(); - std::cout << (geometry ? "Submitted tessellation and tessellation-and-geometry draws drew their patches\n" : "A submitted tessellation draw drew its patches; the device has no geometry shaders or subgroup operations in tessellation-evaluation shaders, so the geometry draw was skipped\n"); + std::cout << (geometry ? "A submitted tessellation and geometry draw drew its patches\n" : "A submitted tessellation draw drew its patches\n"); return 0; } catch (const std::exception& error) { std::cerr << error.what() << '\n'; From 09391147a4b1f23eec010bb8da3b0b0be3cc4e34 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Wed, 4 Nov 2026 02:19:42 +0530 Subject: [PATCH 111/269] refactor(agc): bind the mesh window, pixel LDS and scratch pool sets through CmdBindDescriptorSets These classic binds were recorded directly, so the heap tracker would not learn that the command buffer left descriptor-heap mode. They only run for per-draw pipelines, whose other sets already go through the wrapper, so no heap draw ran without its heaps; routing them through the wrapper keeps every classic bind visible to it. --- core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp | 2 +- core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index b9b5a33920d8..c2995691e7c1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -5719,7 +5719,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { std::memcpy(stageAddresses.data() + (ShaderRecompiler::GpuScratchPoolAddressPushByte - Graphics::ComputePushConstantBytes), &pool->address, sizeof(pool->address)); std::memcpy(stageAddresses.data() + (ShaderRecompiler::GpuScratchPoolDwordsPushByte - Graphics::ComputePushConstantBytes), &dwords, sizeof(dwords)); } else { - context.Resolved(&Graphics::DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, ShaderRecompiler::ScratchPoolDescriptorSet, 1, &pool->set, 0, nullptr); + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, ShaderRecompiler::ScratchPoolDescriptorSet, 1, &pool->set, Graphics::SetBindSite::Dispatch); } recorder.Keep(std::move(pool)); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index c964cddc6693..d8bc51090e16 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -343,7 +343,7 @@ void BindMeshWindow(const Context& context, VkCommandBuffer commands, VkPipeline std::lock_guard lock(MeshWindowMutex()); const auto& pool = MeshWindowPools().at(context.device); Require(pool.set != VK_NULL_HANDLE, "mesh window buffer was not prepared"); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::MeshWindowDescriptorSet, 1, &pool.set, 0, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::MeshWindowDescriptorSet, 1, &pool.set, SetBindSite::Draw); } void ReleaseMeshWindow(VkDevice device) { @@ -366,7 +366,7 @@ void BindPixelFunctionLds(const Context& context, VkCommandBuffer commands, VkPi std::lock_guard lock(PixelLdsMutex()); const auto& pool = PixelLdsPools().at(context.device); Require(pool.set != VK_NULL_HANDLE, "pixel function LDS buffer was not prepared"); - context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::PixelFunctionLdsDescriptorSet, 1, &pool.set, 0, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, ShaderRecompiler::PixelFunctionLdsDescriptorSet, 1, &pool.set, SetBindSite::Draw); } void CheckPixelFunctionLds(const Context& context) { From 98c53701c2d5d1fedecb1906b8f290f8f67cd62c Mon Sep 17 00:00:00 2001 From: raghav314 Date: Wed, 4 Nov 2026 09:58:47 +0530 Subject: [PATCH 112/269] fix(agc): bind the first-sample copy's set through CmdBindDescriptorSets FirstSampleCopy::Record recorded vkCmdBindDescriptorSets directly into the active recorder's command buffer. A stage reading sample 0 of a 2D MSAA texture records that copy while a heap draw captures its resources, so in a heap draw, first-sample copy, heap draw sequence the heap tracker still listed the command buffer as bound and the second draw ran without its heaps. The bind now goes through the wrapper, which clears that entry. agc_driver_sample_multisample_target checks it in heap mode: it binds the heaps on the active recorder, records a first-sample copy through MultisampleTargetFirstSample, and requires the next BindDescriptorHeaps to bind again. The check failed before the fix. --- .../Graphics/include/BindlessHeap.hpp | 2 +- .../Graphics/src/BindlessHeap.cpp | 2 +- .../Graphics/src/FirstSampleCopy.cpp | 3 ++- .../execution/SampleMultisampleTarget.cpp | 24 +++++++++++++++++++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 0dfe89f773c5..938ec1d8a7e9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -215,7 +215,7 @@ void NoteDataAddressPush(); void NoteEmptyResourceSet(); std::uint64_t EmptyResourceSets(); std::uint64_t DataAddressPushes(); -enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, DepthTransfer, StagedMerge, Count }; +enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, DepthTransfer, StagedMerge, FirstSampleCopy, Count }; enum class HeapFallback : std::uint8_t { DrawUnmapped, DrawMixedRetry, DrawRefusedPair, DrawMixedReused, DispatchUnmapped, Count }; enum class HeapStageReason : std::uint8_t { Heap, diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 1b92022039d8..48a70d93d663 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -925,7 +925,7 @@ constexpr std::array(HeapStageReason::Coun "unresolved image source", "known ineligible"}; constexpr std::array(SetBindSite::Count)> SetBindSiteNames{"draw", "dispatch", "detiler", - "color transfer", "presentation", "depth transfer", "staged merge"}; + "color transfer", "presentation", "depth transfer", "staged merge", "first-sample copy"}; constexpr std::array(HeapFallback::Count)> HeapFallbackNames{ "draw unmapped", "draw mixed retry", "draw refused pair", "draw mixed reused", "dispatch unmapped"}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/FirstSampleCopy.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/FirstSampleCopy.cpp index 7fd0a5434bb5..469f9fbae3d1 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/FirstSampleCopy.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/FirstSampleCopy.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" @@ -244,7 +245,7 @@ void FirstSampleCopy::Record(Recorder& recorder, VkImageView source, VkImageLayo begin.renderArea = {{0, 0}, extent}; context.Resolved(&DeviceFunctions::cmdBeginRenderPass, "vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, 0, nullptr); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, SetBindSite::FirstSampleCopy); context.Function("vkCmdDraw")(commands, 3, 1, 0, 0); context.Resolved(&DeviceFunctions::cmdEndRenderPass, "vkCmdEndRenderPass")(commands); }); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp index c919a0d5b521..e0e2b81201b2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp @@ -2,12 +2,15 @@ #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/GuestTextureResource.hpp" #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" #include "prx/libSceAgcDriver/Graphics/include/MultisampleTextureLayout.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderInputState.hpp" #include "prx/libSceAgcDriver/Graphics/include/State.hpp" #include "prx/libc/include/GuestAllocations.hpp" @@ -597,6 +600,26 @@ void CheckFirstSampleReads(AgcDriver::VulkanDevice& device, const std::arrayCommands()); + const auto binds = AgcDriver::Graphics::DescriptorHeapBinds(); + const auto texture = AgcDriver::Graphics::MultisampleTargetFirstSample(context, resource, {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY}); + Require(texture != nullptr, "first-sample copy in heap mode: the drawn 4x target has no sample 0 texture"); + heap.BindDescriptorHeaps(recorder->Commands()); + Require(AgcDriver::Graphics::DescriptorHeapBinds() == binds + 1u, + "a first-sample copy recorded after the descriptor heaps were bound left them marked bound, so a heap draw or dispatch after it would run without them"); + recorder->Submit(); + recorder->Sync(); +} + std::array CompressedDescriptor(const Block& block, std::uint32_t tileMode, std::uint64_t htile) { auto texture = TargetDescriptor(block, SampleShift, Format16161616Float, tileMode); const auto meta = htile >> 8u; @@ -1331,6 +1354,7 @@ int main(int argc, char** argv) { const auto drawn = LoadSamples(*device, block); CheckSamples(state, drawn, {}); CheckFirstSampleReads(*device, TargetDescriptor(block, SampleShift), drawn, true, "from the drawn 4x target"); + CheckFirstSampleCopyLeavesHeapMode(*device, block); CheckFirstSampleReads(*device, TargetDescriptor(block, SampleShift), drawn, true, "from the drawn 4x target", AdjustedPlaneCode, "image_sample_a"); std::puts("a DIM 2D image_sample_a read of a 4x color target returns each pixel's sample 0"); Draw(*device, state, 0, 2u, Unorm8PixelCode); From 25987eee6611cfd39bdd0a0d86dafd2f59b39285 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Wed, 4 Nov 2026 22:42:45 +0530 Subject: [PATCH 113/269] test(agc): run the heap-view recovery check with asynchronous texture uploads agc_driver_sampled_cache_budget_heap_view set APS5_SYNC_TEXTURE_UPLOAD=1 so that its recovery check could free exactly one of two textures. With asynchronous uploads the active recorder keeps each texture's image until its batch completes, and a finished batch's kept objects are destroyed on the release thread only after the GpuMutex hold ends. The recovery, which counts bytes actually freed since #10472, then freed nothing on the test's thread and evicted both textures. The check now syncs the active recorder before the recovery, and the test runs with APS5_RELEASE_UNDER_LOCK=1, so the synced batches' images are freed inside Sync(). Uploads stay asynchronous, the default path. Without the sync, or without the switch, the check fails as before. --- .../tests/cmake/agc_driver_sampled_cache_budget_tests.cmake | 2 +- .../prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sampled_cache_budget_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sampled_cache_budget_tests.cmake index 31688188395f..70823848a447 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sampled_cache_budget_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_sampled_cache_budget_tests.cmake @@ -2,7 +2,7 @@ if(BUILD_TESTING) add_test(NAME agc_driver_sampled_cache_budget_memory COMMAND agc_driver_sampled_cache_budget_tests memory) set_tests_properties(agc_driver_sampled_cache_budget_memory PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77) agc_add_env_test(agc_driver_sampled_cache_budget_heap_view agc_driver_sampled_cache_budget_tests - ARGS heap-view ENV ANYPS5_NO_SHADER_CACHE=1 APS5_NO_IMAGE_SLABS=1 APS5_SYNC_TEXTURE_UPLOAD=1) + ARGS heap-view ENV ANYPS5_NO_SHADER_CACHE=1 APS5_NO_IMAGE_SLABS=1 APS5_RELEASE_UNDER_LOCK=1) add_test(NAME agc_driver_sampled_cache_budget_without_storage_image_multisample COMMAND agc_driver_sampled_cache_budget_tests without-storage-image-multisample) set_tests_properties(agc_driver_sampled_cache_budget_without_storage_image_multisample PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30) add_test(NAME agc_sampled_cache_device_selection COMMAND agc_driver_sampled_cache_budget_tests device-selection-cpu) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp index 759143161fc9..fdca38533c47 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampledCacheBudget.cpp @@ -618,6 +618,7 @@ void heapHeldReleaseTests(const Context& context) { } Require(TextureCacheUsage().sampledEntries == 2u, "the two sampled textures were not cached"); Require(!held[0].expired() && !held[1].expired(), "the cache and the heap slots did not keep the sampled textures"); + if (auto* recorder = Recorder::Active()) recorder->Sync(); const auto released = ReleaseTextureCaches(SurfaceBytes, true); Require(held[0].expired() != held[1].expired(), "a memory recovery for one texture's bytes did not free exactly one of two textures that only the cache and the GPU heap held"); Require(released >= SurfaceBytes && TextureCacheUsage().sampledEntries == 1u, "a memory recovery did not count the texture it freed from the cache and the GPU heap, or went past its target"); From 6ef671193e13d1d7402065b9cb8ad45bcdd827a9 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Wed, 4 Nov 2026 23:25:14 +0530 Subject: [PATCH 114/269] perf(agc): run driver-internal passes on the descriptor heap In descriptor-heap mode the driver's internal passes recorded classic descriptor binds or push constants. Each one put the command buffer back in classic mode, so the next heap draw or dispatch bound the heaps again. Like vkd3d-proton's meta shaders, each pass now has a heap twin pipeline: the same SPIR-V with a null layout and the descriptor-heap flag, buffers mapped to pushed addresses, and images mapped to heap slots indexed from push data. The pass's push constants stay at push-data offset 0, with the addresses and slot indices after them. The classic pipeline is still used outside heap mode, and when no slot is free or the twin cannot be created. Passes: color transfer, multisample readback and upload, staged merge, depth to storage, first-sample copy (its sampler embedded in the mapping), sample order (storage and depth halves), and the detiler's buffer detile and repack. A buffer detile that the descriptor shader would run through its word path (elements under 4 bytes) keeps the addressed shader, which reads the same push layout: on RADV the word path costs 71 instructions against 40. Slot owners release their slots before they destroy the views; a staged write keeps the merge target that owns its slot. Tests: the sample order and multisample readback tests give their passes a slot owner and require, in heap mode, that recording a pass does not make the heaps bind again. The first-sample check now requires the same. The heap slot tests set APS5_HEAP_SLOT_CAP before opening the device, since the twins create the heap while it opens. --- .../Graphics/include/BindlessHeap.hpp | 19 +++ .../Graphics/include/FirstSampleCopy.hpp | 4 +- .../Graphics/include/GpuColorTransfer.hpp | 2 + .../Graphics/include/MultisampleTarget.hpp | 1 + .../Graphics/include/SampleOrder.hpp | 3 + .../Graphics/include/StagedMerge.hpp | 4 +- .../Graphics/include/TextureDetiler.hpp | 9 +- .../Graphics/src/BindlessHeap.cpp | 74 ++++++++++ .../Graphics/src/DepthSurface.cpp | 49 ++++++- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 13 +- .../Graphics/src/FirstSampleCopy.cpp | 28 +++- .../Graphics/src/GpuColorTransfer.cpp | 39 ++++- .../Graphics/src/MultisampleReadback.cpp | 39 ++++- .../Graphics/src/MultisampleTarget.cpp | 12 +- .../Graphics/src/MultisampleUpload.cpp | 43 +++++- .../Graphics/src/SampleOrder.cpp | 135 ++++++++++++++---- .../Graphics/src/StagedMerge.cpp | 48 ++++++- .../Graphics/src/TextureDetiler.cpp | 57 ++++++-- .../tests/BindlessHeapSlots.cpp | 2 +- .../tests/execution/MultisampleReadback.cpp | 26 +++- .../execution/SampleMultisampleTarget.cpp | 8 +- .../tests/execution/SampleOrder.cpp | 38 +++-- 22 files changed, 543 insertions(+), 110 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 938ec1d8a7e9..26b086312bbe 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -280,6 +280,25 @@ void CmdBindDescriptorSets(const Context& context, VkCommandBuffer commands, VkP void CmdPushDescriptorSet(PFN_vkCmdPushDescriptorSetKHR push, VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t set, std::uint32_t writeCount, const VkWriteDescriptorSet* writes, SetBindSite site); std::uint64_t DescriptorHeapBinds(); +inline constexpr std::uint32_t HeapPassSampledKind = ShaderRecompiler::RuntimeAbi::FirstImageBinding; +inline constexpr std::uint32_t HeapPassStorageKind = ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding; +inline constexpr VkSpirvResourceTypeFlagsEXT HeapPassStorageImages = VK_SPIRV_RESOURCE_TYPE_READ_ONLY_IMAGE_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; +class HeapPassSlots : public HeapSlotOwner { +public: + explicit HeapPassSlots(const Context& context) : context(context) {} + ~HeapPassSlots() { ReleaseHeapSlots(context); } + void Release() noexcept { ReleaseHeapSlots(context); } + +private: + Context context; +}; +bool HeapPassesActive(const Context& context); +VkDescriptorSetAndBindingMappingEXT HeapPushAddressMapping(std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset); +VkDescriptorSetAndBindingMappingEXT HeapPushIndexMapping(const BindlessHeap& heap, std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, + std::uint32_t pushOffset); +VkPipeline CreateHeapComputePipeline(const Context& context, VkComputePipelineCreateInfo info, std::span mappings); +VkPipeline CreateHeapGraphicsPipeline(const Context& context, VkGraphicsPipelineCreateInfo info, std::span mappings); +void CmdPushData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp index 4f973ff75e27..6b384ab00c81 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp @@ -6,6 +6,7 @@ namespace AgcDriver::Graphics { class Recorder; +class Texture; class FirstSampleCopy { public: @@ -14,7 +15,7 @@ class FirstSampleCopy { FirstSampleCopy(const FirstSampleCopy&) = delete; FirstSampleCopy& operator=(const FirstSampleCopy&) = delete; - void Record(Recorder& recorder, VkImageView source, VkImageLayout layout); + void Record(Recorder& recorder, Texture& source); VkImage Image() const { return image; } private: @@ -33,6 +34,7 @@ class FirstSampleCopy { VkShaderModule vertex = VK_NULL_HANDLE; VkShaderModule fragment = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + VkPipeline heapPipeline = VK_NULL_HANDLE; }; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp index 672a39649356..69d20e25bce0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp @@ -32,6 +32,8 @@ class GpuColorTransfer { VkDescriptorSet descriptorSet = VK_NULL_HANDLE; VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + VkPipeline heapPipeline = VK_NULL_HANDLE; + VkBufferUsageFlags addressUsage = 0; // Guest bytes in host memory, and the device-local copies the conversion shader works on. std::unique_ptr tiled; std::unique_ptr tiledDevice; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp index 51e5e862cfae..cd0cedad85d5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp @@ -25,6 +25,7 @@ class HeapSlotOwner; struct MultisampleStorage { VkImageView view = VK_NULL_HANDLE; const HeapSlotOwner* owner = nullptr; + std::shared_ptr keep; }; class StorageTexture; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp index dc1a089fc536..2479210a4249 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp @@ -37,6 +37,8 @@ struct SampleOrderPass { bool located = false; }; +class HeapSlotOwner; + struct SampleOrderTarget { VkImage image = VK_NULL_HANDLE; VkImageView view = VK_NULL_HANDLE; @@ -45,6 +47,7 @@ struct SampleOrderTarget { std::uint32_t samples = 1; SampleOrderMethod method = SampleOrderMethod::Storage; std::shared_ptr keep; + const HeapSlotOwner* owner = nullptr; }; struct DepthSampleLocations { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/StagedMerge.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/StagedMerge.hpp index 60e2a764f7d2..3add8e5d57a7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/StagedMerge.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/StagedMerge.hpp @@ -15,7 +15,9 @@ struct StagedTemporary { std::shared_ptr AcquireStagedTemporary(const Context& context, VkExtent2D extent, std::uint32_t samples); void RecordStagedClear(const Context& context, VkCommandBuffer commands, StagedTemporary& temporary); -void RecordStagedMerge(const Context& context, VkCommandBuffer commands, StagedTemporary& temporary, VkImageView target, std::uint32_t mask, std::uint32_t samples, VkRect2D area); +class HeapSlotOwner; +void RecordStagedMerge(const Context& context, VkCommandBuffer commands, StagedTemporary& temporary, VkImageView target, std::uint32_t mask, std::uint32_t samples, VkRect2D area, + const HeapSlotOwner* targetOwner = nullptr); void ClearStagedMerges(VkDevice device); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp index 11c7476e03ab..4de881e0b9b8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp @@ -57,12 +57,12 @@ class HeapSlotOwner; void BeginBatch(); void DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask, std::uint64_t cmaskOffset, std::size_t cmaskBytes, VkImageView view, std::uint32_t width, std::uint32_t height, std::uint32_t elementBytes, const std::array& clearWords, bool write, const HeapSlotOwner* owner = nullptr); std::uint32_t CmaskErrors(); - void DispatchMultisampleReadback(VkCommandBuffer commands, VkFormat format, VkBuffer destination, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements); - void DispatchMultisampleImage(VkCommandBuffer commands, std::uint32_t elementBytes, VkBuffer source, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements); + void DispatchMultisampleReadback(VkCommandBuffer commands, VkFormat format, VkBuffer destination, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements, const HeapSlotOwner* owner = nullptr); + void DispatchMultisampleImage(VkCommandBuffer commands, std::uint32_t elementBytes, VkBuffer source, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements, const HeapSlotOwner* owner = nullptr); private: - VkPipeline multisampleReadbackPipeline(std::uint32_t elementBytes, bool depth); - VkPipeline multisampleUploadPipeline(std::uint32_t elementBytes); + VkPipeline multisampleReadbackPipeline(std::uint32_t elementBytes, bool depth, bool heap); + VkPipeline multisampleUploadPipeline(std::uint32_t elementBytes, bool heap); VkPipeline pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image = false, bool addressed = false, bool heap = false); VkDeviceAddress bufferAddress(VkBuffer buffer) const; void release() noexcept; @@ -96,6 +96,7 @@ class HeapSlotOwner; VkShaderModule imageModule = VK_NULL_HANDLE; VkShaderModule repackModule = VK_NULL_HANDLE; VkPipeline repackPipeline = VK_NULL_HANDLE; + VkPipeline heapRepackPipeline = VK_NULL_HANDLE; VkPipelineLayout addressedPipelineLayout = VK_NULL_HANDLE; VkPipelineLayout addressedRepackLayout = VK_NULL_HANDLE; VkShaderModule addressedModule = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 48a70d93d663..4d43fadf807a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -1088,6 +1088,80 @@ std::uint64_t DescriptorHeapBinds() { return heapBinds.load(std::memory_order_relaxed); } +bool HeapPassesActive(const Context& context) { + return DescriptorHeapEnabled() && context.descriptorHeap && BindlessHeap::For(context).DescriptorHeapMode(); +} + +VkDescriptorSetAndBindingMappingEXT HeapPushAddressMapping(std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = set; + mapping.firstBinding = binding; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; + mapping.sourceData.pushAddressOffset = pushOffset; + return mapping; +} + +VkDescriptorSetAndBindingMappingEXT HeapPushIndexMapping(const BindlessHeap& heap, std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, + std::uint32_t pushOffset) { + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = set; + mapping.firstBinding = binding; + mapping.bindingCount = 1; + mapping.resourceMask = resources; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; + mapping.sourceData.pushIndex.pushOffset = pushOffset; + mapping.sourceData.pushIndex.heapIndexStride = static_cast(heap.ImageHeapStride()); + mapping.sourceData.pushIndex.heapArrayStride = static_cast(heap.ImageHeapStride()); + return mapping; +} + +VkPipeline CreateHeapComputePipeline(const Context& context, VkComputePipelineCreateInfo info, std::span mappings) { + if (!HeapPassesActive(context)) return VK_NULL_HANDLE; + VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; + mappingInfo.pNext = info.stage.pNext; + mappingInfo.mappingCount = static_cast(mappings.size()); + mappingInfo.pMappings = mappings.data(); + info.stage.pNext = &mappingInfo; + auto heapFlags = DescriptorHeapFlags(); + heapFlags.pNext = info.pNext; + info.pNext = &heapFlags; + info.layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + if (context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline) != VK_SUCCESS) + return VK_NULL_HANDLE; + return pipeline; +} + +VkPipeline CreateHeapGraphicsPipeline(const Context& context, VkGraphicsPipelineCreateInfo info, std::span mappings) { + if (!HeapPassesActive(context)) return VK_NULL_HANDLE; + std::vector stages(info.pStages, info.pStages + info.stageCount); + std::vector mappingInfos(stages.size(), {VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}); + for (std::size_t index = 0; index < stages.size(); ++index) { + mappingInfos[index].pNext = stages[index].pNext; + mappingInfos[index].mappingCount = static_cast(mappings.size()); + mappingInfos[index].pMappings = mappings.data(); + stages[index].pNext = &mappingInfos[index]; + } + info.pStages = stages.data(); + auto heapFlags = DescriptorHeapFlags(); + heapFlags.pNext = info.pNext; + info.pNext = &heapFlags; + info.layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + if (context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline) != VK_SUCCESS) + return VK_NULL_HANDLE; + return pipeline; +} + +void CmdPushData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values) { + const VkPushDataInfoEXT data{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {values, bytes}}; + context.Function("vkCmdPushDataEXT")(commands, &data); +} + void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { if (resourceHeap == nullptr) return; { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp index 81ffece1ae2d..11994425eeef 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp @@ -22,6 +22,7 @@ #include "RdnaDecoder/include/RdnaDecoder/RdnaDescriptorFormat.hpp" #include #include +#include #include #include #include @@ -94,6 +95,14 @@ struct RectPush { std::array extent; }; +struct HeapRectPush { + RectPush rect; + std::uint32_t depth; + std::uint32_t texels; +}; + +static_assert(offsetof(HeapRectPush, depth) == 16 && offsetof(HeapRectPush, texels) == 20); + class DepthToStoragePass { public: explicit DepthToStoragePass(const Context& context) : context(context) { @@ -122,6 +131,13 @@ class DepthToStoragePass { auto pipelineCacheLock = context.LockPipelineCacheForUse(); created = context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline); } + if (created == VK_SUCCESS && HeapPassesActive(context)) { + const auto& heap = BindlessHeap::For(context); + const std::array mappings{ + HeapPushIndexMapping(heap, 0, 0, VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT, offsetof(HeapRectPush, depth)), + HeapPushIndexMapping(heap, 0, 1, HeapPassStorageImages, offsetof(HeapRectPush, texels))}; + heapPipeline = CreateHeapComputePipeline(context, info, mappings); + } context.Function("vkDestroyShaderModule")(context.device, compute, nullptr); Check(created, "vkCreateComputePipelines depth to storage"); } catch (...) { @@ -135,13 +151,28 @@ class DepthToStoragePass { VkDevice Device() const { return context.device; } - void Record(VkCommandBuffer commands, VkImageView depthPlane, VkImageView texels, std::span rects) const { + void Record(VkCommandBuffer commands, VkImageView depthPlane, const HeapSlotOwner* depthOwner, VkImageView texels, const HeapSlotOwner* texelOwner, std::span rects) const { + const auto dispatch = context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch"); + if (heapPipeline != VK_NULL_HANDLE) { + auto& heap = BindlessHeap::For(context); + const auto depthSlot = heap.ViewSlot(HeapPassSampledKind, depthOwner, depthPlane); + const auto texelSlot = depthSlot ? heap.ViewSlot(HeapPassStorageKind, texelOwner, texels) : std::nullopt; + if (texelSlot) { + heap.BindDescriptorHeaps(commands); + context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, heapPipeline); + for (const auto& rect : rects) { + const HeapRectPush push{{{static_cast(rect.offset.x), static_cast(rect.offset.y)}, {rect.extent.width, rect.extent.height}}, *depthSlot, *texelSlot}; + CmdPushData(context, commands, sizeof(push), &push); + dispatch(commands, (rect.extent.width + 7u) / 8u, (rect.extent.height + 7u) / 8u, 1); + } + return; + } + } const VkDescriptorImageInfo depthInfo{VK_NULL_HANDLE, depthPlane, VK_IMAGE_LAYOUT_GENERAL}; const VkDescriptorImageInfo texelInfo{VK_NULL_HANDLE, texels, VK_IMAGE_LAYOUT_GENERAL}; const std::array writes{imageWrite(0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, depthInfo), imageWrite(1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, texelInfo)}; context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); CmdPushDescriptorSet(pushSet, commands, VK_PIPELINE_BIND_POINT_COMPUTE, layout, 0, static_cast(writes.size()), writes.data(), SetBindSite::DepthTransfer); - const auto dispatch = context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch"); for (const auto& rect : rects) { const RectPush push{{static_cast(rect.offset.x), static_cast(rect.offset.y)}, {rect.extent.width, rect.extent.height}}; CmdPushConstants(context, commands, layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); @@ -161,9 +192,11 @@ class DepthToStoragePass { void release() noexcept { context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); + if (heapPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, heapPipeline, nullptr); context.Function("vkDestroyPipelineLayout")(context.device, layout, nullptr); context.Function("vkDestroyDescriptorSetLayout")(context.device, setLayout, nullptr); pipeline = VK_NULL_HANDLE; + heapPipeline = VK_NULL_HANDLE; layout = VK_NULL_HANDLE; setLayout = VK_NULL_HANDLE; } @@ -173,6 +206,7 @@ class DepthToStoragePass { VkDescriptorSetLayout setLayout = VK_NULL_HANDLE; VkPipelineLayout layout = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + VkPipeline heapPipeline = VK_NULL_HANDLE; }; std::mutex& depthToStoragePassesMutex() { @@ -858,13 +892,13 @@ class DepthSurface { return texture; } - std::shared_ptr FirstSample(const Texture& source, VkComponentMapping components) { + std::shared_ptr FirstSample(Texture& source, VkComponentMapping components) { auto* recorder = RecorderFor(context); Require(recorder != nullptr, "a native multisampled depth target is sampled only by recorded draws and dispatches"); const bool d16 = target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT; const auto format = d16 ? VK_FORMAT_R16_UNORM : VK_FORMAT_R32_SFLOAT; if (firstSample == nullptr) firstSample = std::make_shared(context, format, target.extent); - firstSample->copy.Record(*recorder, source.View(), source.Layout()); + firstSample->copy.Record(*recorder, source); const std::array key{static_cast(components.r), static_cast(components.g), static_cast(components.b), static_cast(components.a)}; auto& texture = firstSample->textures[key]; if (texture == nullptr) { @@ -1598,6 +1632,7 @@ class DepthSurface { std::uint64_t stencilMemory = 0; StencilCopy stencilCopy; VkImageView transferView = VK_NULL_HANDLE; + HeapPassSlots transferSlots{context}; void createSampleShadow() { VkImage image = VK_NULL_HANDLE; @@ -1817,7 +1852,7 @@ class DepthSurface { const auto& areas = rects != nullptr ? *rects : whole; const auto texels = storage->AtomicView(0, storage->Descriptor().dimension == TextureDimension::k2DArray); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); - depthToStoragePassFor(context).Record(commands, depthTransferView(), texels, areas); + depthToStoragePassFor(context).Record(commands, depthTransferView(), &transferSlots, texels, storage.get(), areas); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT); depthTransferPassCount.fetch_add(1, std::memory_order_relaxed); if (batch) { @@ -1883,6 +1918,7 @@ class DepthSurface { mirrorPlane = {}; stencilMirror = {}; textures.clear(); + transferSlots.Release(); if (transferView) context.Function("vkDestroyImageView")(context.device, transferView, nullptr); transferView = VK_NULL_HANDLE; if (view) context.Function("vkDestroyImageView")(context.device, view, nullptr); @@ -2431,10 +2467,11 @@ void DepthSurface::PublishToGuest() { info.format = hostFormat; info.subresourceRange = {static_cast(aspect), 0u, 1u, 0u, 1u}; Check(context.Function("vkCreateImageView")(context.device, &info, nullptr, &arrayView), "vkCreateImageView depth publication"); + HeapPassSlots passSlots(context); CommandBatch batch(context); constexpr VkAccessFlags writes = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT; RecordMemoryBarrier(context, batch.Handle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, writes, VK_ACCESS_SHADER_READ_BIT); - context.detiler->DispatchMultisampleReadback(batch.Handle(), format, linear.Handle(), 0u, linearBytes, arrayView, target.extent.width, target.extent.height, 1u, target.samples, 0u, static_cast(layout.LinearBytes() / elementBytes)); + context.detiler->DispatchMultisampleReadback(batch.Handle(), format, linear.Handle(), 0u, linearBytes, arrayView, target.extent.width, target.extent.height, 1u, target.samples, 0u, static_cast(layout.LinearBytes() / elementBytes), &passSlots); RecordMemoryBarrier(context, batch.Handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); batch.SubmitAndWait(); } catch (...) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 9c9bb678cf72..d79277713bae 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -2422,6 +2422,7 @@ void keepRecordedDraw(Recorder& recorder, const std::shared_ptr struct StagedWrite { std::shared_ptr temporary; VkImageView target = VK_NULL_HANDLE; + const HeapSlotOwner* targetOwner = nullptr; std::uint16_t mask = 0; std::uint32_t samples = 1; VkRect2D area{}; @@ -2870,7 +2871,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam if (!record.staged.empty()) { const auto merged = recorder->Commands(); for (auto& write : record.staged) { - RecordStagedMerge(context, merged, *write.temporary, write.target, write.mask, write.samples, write.area); + RecordStagedMerge(context, merged, *write.temporary, write.target, write.mask, write.samples, write.area, write.targetOwner); recorder->Keep(write.temporary); } } @@ -2958,6 +2959,8 @@ struct TargetBinding { std::shared_ptr multisampleOwner; std::shared_ptr stagedTemporary; VkImageView stagedTarget = VK_NULL_HANDLE; + const HeapSlotOwner* stagedTargetOwner = nullptr; + std::shared_ptr stagedTargetKeep; std::unique_ptr dump; }; @@ -3209,7 +3212,10 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara const auto packed = StagedMergeTarget(color); binding.stagedTemporary = AcquireStagedTemporary(context, color.extent, color.samples); static_cast(MultisampleTargetView(context, packed, binding.multisampleOwner, &binding.multisampleImage)); - binding.stagedTarget = MultisampleTargetStorageView(context, TargetMergeSurface(packed)).view; + const auto storage = MultisampleTargetStorageView(context, TargetMergeSurface(packed)); + binding.stagedTarget = storage.view; + binding.stagedTargetOwner = storage.owner; + binding.stagedTargetKeep = storage.keep; Require(MultisampleTargetStorable(context, packed), "a partial write of a multisampled packed color target needs a multisample image of this form to allow storage"); targetViews.push_back(binding.stagedTemporary->View()); timer.phase(PhaseReadTarget); @@ -3628,6 +3634,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D if (binding.multisampled) { record.multisampleImages.push_back(binding.multisampleImage); record.multisampleTargets.push_back(binding.multisampleOwner); + if (binding.stagedTargetKeep != nullptr && binding.stagedTargetKeep != binding.multisampleOwner) record.multisampleTargets.push_back(binding.stagedTargetKeep); } if (binding.stagedTemporary != nullptr) { record.multisampleImages.push_back(binding.stagedTemporary->Image()); @@ -3639,7 +3646,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D const auto right = std::min(static_cast(state.scissor.offset.x) + state.scissor.extent.width, color.extent.width); const auto bottom = std::min(static_cast(state.scissor.offset.y) + state.scissor.extent.height, color.extent.height); area.extent = {static_cast(std::max(right - area.offset.x, 0)), static_cast(std::max(bottom - area.offset.y, 0))}; - record.staged.push_back({binding.stagedTemporary, binding.stagedTarget, color.stagedMask, color.samples, area}); + record.staged.push_back({binding.stagedTemporary, binding.stagedTarget, binding.stagedTargetOwner, color.stagedMask, color.samples, area}); } } record.indirect = args != nullptr ? &indirect : nullptr; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/FirstSampleCopy.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/FirstSampleCopy.cpp index 469f9fbae3d1..9582ffbde8af 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/FirstSampleCopy.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/FirstSampleCopy.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" @@ -180,6 +181,11 @@ FirstSampleCopy::FirstSampleCopy(const Context& context, VkFormat format, VkExte pipelineInfo.layout = pipelineLayout; pipelineInfo.renderPass = renderPass; Check(context.Function("vkCreateGraphicsPipelines")(context.device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &pipeline), "vkCreateGraphicsPipelines first sample"); + if (HeapPassesActive(context)) { + auto mapping = HeapPushIndexMapping(BindlessHeap::For(context), 0, 0, VK_SPIRV_RESOURCE_TYPE_COMBINED_SAMPLED_IMAGE_BIT_EXT, 0); + mapping.sourceData.pushIndex.pEmbeddedSampler = &samplerInfo; + heapPipeline = CreateHeapGraphicsPipeline(context, pipelineInfo, std::span(&mapping, 1)); + } } catch (...) { release(); throw; @@ -191,6 +197,7 @@ FirstSampleCopy::~FirstSampleCopy() { } void FirstSampleCopy::release() noexcept { + if (heapPipeline) context.Function("vkDestroyPipeline")(context.device, heapPipeline, nullptr); if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); if (fragment) context.Function("vkDestroyShaderModule")(context.device, fragment, nullptr); if (vertex) context.Function("vkDestroyShaderModule")(context.device, vertex, nullptr); @@ -214,7 +221,26 @@ void FirstSampleCopy::release() noexcept { memory = VK_NULL_HANDLE; } -void FirstSampleCopy::Record(Recorder& recorder, VkImageView source, VkImageLayout layout) { +void FirstSampleCopy::Record(Recorder& recorder, Texture& texture) { + const auto source = texture.View(); + const auto layout = texture.Layout(); + const auto slot = heapPipeline != VK_NULL_HANDLE ? BindlessHeap::For(context).TextureSlot(ShaderRecompiler::RuntimeAbi::FirstImageBinding, &texture, source, layout) : std::nullopt; + if (slot) { + recorder.RecordUncounted([&](VkCommandBuffer commands) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; + begin.renderPass = renderPass; + begin.framebuffer = framebuffer; + begin.renderArea = {{0, 0}, extent}; + context.Resolved(&DeviceFunctions::cmdBeginRenderPass, "vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE); + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, heapPipeline); + const std::uint32_t pushed = *slot; + CmdPushData(context, commands, sizeof(pushed), &pushed); + context.Function("vkCmdDraw")(commands, 3, 1, 0, 0); + context.Resolved(&DeviceFunctions::cmdEndRenderPass, "vkCmdEndRenderPass")(commands); + }); + return; + } const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1}; VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; poolInfo.maxSets = 1; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp index 690654ab9985..68be732d841d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GpuColorTransfer.cpp @@ -7,10 +7,23 @@ #include #include #include +#include #include namespace AgcDriver::Graphics { +namespace { + +struct HeapPush { + std::array values; + std::uint32_t pad; + std::array buffers; +}; + +static_assert(offsetof(HeapPush, buffers) == 24 && sizeof(HeapPush) == 56); + +} + GpuColorTransfer::GpuColorTransfer(const Context& context) : context(context) { VkShaderModule module = VK_NULL_HANDLE; try { @@ -40,6 +53,10 @@ GpuColorTransfer::GpuColorTransfer(const Context& context) : context(context) { auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &pipeline), "vkCreateComputePipelines color transfer"); } + std::array mappings{}; + for (std::uint32_t i = 0; i < mappings.size(); ++i) mappings[i] = HeapPushAddressMapping(0, i, static_cast(offsetof(HeapPush, buffers) + i * sizeof(VkDeviceAddress))); + heapPipeline = CreateHeapComputePipeline(context, pipelineInfo, mappings); + if (heapPipeline != VK_NULL_HANDLE) addressUsage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; context.Function("vkDestroyShaderModule")(context.device, module, nullptr); module = VK_NULL_HANDLE; const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 4}; @@ -54,10 +71,10 @@ GpuColorTransfer::GpuColorTransfer(const Context& context) : context(context) { allocation.pSetLayouts = &descriptorLayout; Check(context.Function("vkAllocateDescriptorSets")(context.device, &allocation, &descriptorSet), "vkAllocateDescriptorSets color transfer"); const auto& table = HalfFloatScanoutThresholds(); - thresholds = std::make_unique(context, sizeof(table), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + thresholds = std::make_unique(context, sizeof(table), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | addressUsage); std::memcpy(thresholds->Bytes().data(), table.data(), sizeof(table)); const auto& luminance = AgcDriver::PqEotfNits(); - pqNits = std::make_unique(context, sizeof(luminance), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + pqNits = std::make_unique(context, sizeof(luminance), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | addressUsage); std::memcpy(pqNits->Bytes().data(), luminance.data(), sizeof(luminance)); const std::array tableInfo{{{thresholds->Handle(), 0, sizeof(table)}, {pqNits->Handle(), 0, sizeof(luminance)}}}; std::array tableWrites{}; @@ -84,6 +101,7 @@ GpuColorTransfer::~GpuColorTransfer() { void GpuColorTransfer::release() noexcept { if (descriptorPool) context.Function("vkDestroyDescriptorPool")(context.device, descriptorPool, nullptr); if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); + if (heapPipeline) context.Function("vkDestroyPipeline")(context.device, heapPipeline, nullptr); if (pipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, pipelineLayout, nullptr); if (descriptorLayout) context.Function("vkDestroyDescriptorSetLayout")(context.device, descriptorLayout, nullptr); } @@ -97,8 +115,8 @@ void GpuColorTransfer::prepare(std::uint32_t newWidth, std::uint32_t newHeight, if (tiled && width == newWidth && height == newHeight && mode == newMode && elementBytes == newElementBytes) return; constexpr VkBufferUsageFlags copies = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; auto newTiled = std::make_unique(context, layout.Bytes(), copies); - auto newTiledDevice = std::make_unique(context, layout.Bytes(), copies | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); - auto newLinear = std::make_unique(context, linearBytes, copies | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + auto newTiledDevice = std::make_unique(context, layout.Bytes(), copies | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | addressUsage); + auto newLinear = std::make_unique(context, linearBytes, copies | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | addressUsage); const std::array buffers{{{newTiledDevice->Handle(), 0, layout.Bytes()}, {newLinear->Handle(), 0, linearBytes}}}; std::array writes{}; for (std::uint32_t i = 0; i < writes.size(); ++i) { @@ -147,9 +165,16 @@ void GpuColorTransfer::dispatch(VkCommandBuffer commands, bool toTiled, bool swa const auto barrier = context.Function("vkCmdPipelineBarrier"); barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr); const std::array push{width, height, (width + 127u) / 128u, (toTiled ? 1u : 0u) | (swapRedBlue ? 2u : 0u) | (tiledSource ? 4u : 0u) | (tenBit ? 8u : 0u) | (halfFloat ? 16u : 0u) | (pqWhiteNits ? 32u : 0u), std::bit_cast(pqWhiteNits.value_or(0.0f))}; - context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); - CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &descriptorSet, SetBindSite::ColorTransfer); - CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); + if (heapPipeline != VK_NULL_HANDLE) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, heapPipeline); + const HeapPush pushed{push, 0u, {BufferDeviceAddress(context, tiledDevice->Handle()), BufferDeviceAddress(context, linear->Handle()), thresholds->DeviceAddress(), pqNits->DeviceAddress()}}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + } else { + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); + CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &descriptorSet, SetBindSite::ColorTransfer); + CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data()); + } context.Function("vkCmdDispatch")(commands, (width + 7u) / 8u, (height + 7u) / 8u, 1); VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleReadback.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleReadback.cpp index 37125033c923..42c47502769b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleReadback.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleReadback.cpp @@ -5,11 +5,22 @@ #include "prx/libSceAgcDriver/Graphics/shaders/MultisampleReadbackDepth_spv.h" #include #include +#include #include namespace AgcDriver::Graphics { namespace { +struct HeapReadbackPush { + std::array values; + std::uint32_t pad; + VkDeviceAddress buffer; + std::uint32_t slot; + std::uint32_t pad2; +}; + +static_assert(offsetof(HeapReadbackPush, buffer) == 32 && offsetof(HeapReadbackPush, slot) == 40 && sizeof(HeapReadbackPush) == 48); + std::uint32_t readbackElementBytes(VkFormat format) { switch (format) { case VK_FORMAT_R8_UINT: return 1u; @@ -23,8 +34,8 @@ std::uint32_t readbackElementBytes(VkFormat format) { } -VkPipeline TextureDetiler::multisampleReadbackPipeline(std::uint32_t elementBytes, bool depth) { - const auto key = elementBytes | (depth ? 32u : 0u); +VkPipeline TextureDetiler::multisampleReadbackPipeline(std::uint32_t elementBytes, bool depth, bool heap) { + const auto key = elementBytes | (depth ? 32u : 0u) | (heap ? 64u : 0u); for (const auto& entry : readbackPipelines) if (entry.first == key) return entry.second; if (readbackDescriptorLayout == VK_NULL_HANDLE) { const std::array bindings{{ @@ -61,7 +72,12 @@ VkPipeline TextureDetiler::multisampleReadbackPipeline(std::uint32_t elementByte info.layout = readbackPipelineLayout; readbackPipelines.reserve(readbackPipelines.size() + 1u); VkPipeline result = VK_NULL_HANDLE; - { + if (heap) { + const std::array mappings{ + HeapPushAddressMapping(0u, 0u, offsetof(HeapReadbackPush, buffer)), + HeapPushIndexMapping(BindlessHeap::For(context), 0u, 1u, VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT, offsetof(HeapReadbackPush, slot))}; + result = CreateHeapComputePipeline(context, info, mappings); + } else { auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1u, &info, nullptr, &result), "vkCreateComputePipelines multisample readback"); } @@ -69,7 +85,7 @@ VkPipeline TextureDetiler::multisampleReadbackPipeline(std::uint32_t elementByte return result; } -void TextureDetiler::DispatchMultisampleReadback(VkCommandBuffer commands, VkFormat format, VkBuffer destination, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements) { +void TextureDetiler::DispatchMultisampleReadback(VkCommandBuffer commands, VkFormat format, VkBuffer destination, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements, const HeapSlotOwner* owner) { GuestMemory::AssertGpuLockHeld("TextureDetiler::DispatchMultisampleReadback"); const auto elementBytes = readbackElementBytes(format); Require(commands != VK_NULL_HANDLE && destination != VK_NULL_HANDLE && arrayView != VK_NULL_HANDLE, "multisample readback requires commands, buffer and array view"); @@ -88,7 +104,19 @@ void TextureDetiler::DispatchMultisampleReadback(VkCommandBuffer commands, VkFor Require(groupsX != 0u, "device has no multisample readback workgroups"); const auto groupsY = (groups + groupsX - 1u) / groupsX; Require(groupsY <= context.limits.maxComputeWorkGroupCount[1] && groupsX * groupsY * 64u <= std::numeric_limits::max(), "multisample readback dispatch exceeds device limits"); - const auto pipeline = multisampleReadbackPipeline(elementBytes, format == VK_FORMAT_D32_SFLOAT); + const std::array push{width, height, layers, fragments, firstElement, elements, static_cast(groupsX * 64u)}; + const auto address = owner != nullptr && HeapPassesActive(context) ? bufferAddress(destination) : 0; + const auto heapPipeline = address != 0 ? multisampleReadbackPipeline(elementBytes, format == VK_FORMAT_D32_SFLOAT, true) : VK_NULL_HANDLE; + const auto slot = heapPipeline != VK_NULL_HANDLE ? BindlessHeap::For(context).ViewSlot(HeapPassSampledKind, owner, arrayView) : std::nullopt; + if (slot) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, heapPipeline); + const HeapReadbackPush pushed{push, 0u, address + offset, *slot, 0u}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + context.Function("vkCmdDispatch")(commands, static_cast(groupsX), static_cast(groupsY), 1u); + return; + } + const auto pipeline = multisampleReadbackPipeline(elementBytes, format == VK_FORMAT_D32_SFLOAT, false); const auto set = allocateFrom(readbackDescriptorSets, readbackDescriptorLayout, {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 64u}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 64u}}, "vkCreateDescriptorPool multisample readback", "vkAllocateDescriptorSets multisample readback", "vkResetDescriptorPool multisample readback"); const VkDescriptorBufferInfo buffer{destination, offset, bytes}; const VkDescriptorImageInfo image{VK_NULL_HANDLE, arrayView, VK_IMAGE_LAYOUT_GENERAL}; @@ -99,7 +127,6 @@ void TextureDetiler::DispatchMultisampleReadback(VkCommandBuffer commands, VkFor context.Function("vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0u, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, readbackPipelineLayout, 0u, 1u, &set, SetBindSite::ColorTransfer); - const std::array push{width, height, layers, fragments, firstElement, elements, static_cast(groupsX * 64u)}; CmdPushConstants(context, commands, readbackPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(push), push.data()); context.Function("vkCmdDispatch")(commands, static_cast(groupsX), static_cast(groupsY), 1u); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp index 92acd4dba71f..713c74a9d03e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp @@ -280,7 +280,7 @@ class MultisampleTarget : public std::enable_shared_from_this const auto bytes = static_cast(target.extent.width) * target.extent.height * target.samples * target.elementBytes; for (std::uint64_t offset = 0; offset < bytes; offset += stride) { const auto count = std::min(stride, bytes - offset); - context.detiler->DispatchMultisampleImage(commands, target.elementBytes, upload->Handle(), offset, (count + 3u) & ~std::uint64_t{3}, uploadView, target.extent.width, target.extent.height, 1u, target.samples, static_cast(offset / target.elementBytes), static_cast(count / target.elementBytes)); + context.detiler->DispatchMultisampleImage(commands, target.elementBytes, upload->Handle(), offset, (count + 3u) & ~std::uint64_t{3}, uploadView, target.extent.width, target.extent.height, 1u, target.samples, static_cast(offset / target.elementBytes), static_cast(count / target.elementBytes), this); } RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); if (recorder != nullptr) { @@ -565,7 +565,7 @@ class MultisampleTarget : public std::enable_shared_from_this std::shared_ptr FirstSample(VkComponentMapping components) { const auto source = Sampled({}); if (firstSampleCopy == nullptr) firstSampleCopy = std::make_unique(context, target.format, target.extent); - firstSampleCopy->Record(*Recorder::Active(), source->View(), source->Layout()); + firstSampleCopy->Record(*Recorder::Active(), *source); const std::array key{static_cast(components.r), static_cast(components.g), static_cast(components.b), static_cast(components.a)}; auto& texture = firstSampleTextures[key]; if (texture == nullptr) { @@ -895,10 +895,10 @@ class MultisampleTarget : public std::enable_shared_from_this firstSampleTextures.clear(); firstSampleCopy.reset(); for (const auto& [format, resolvePass] : resolvePasses) context.Function("vkDestroyRenderPass")(context.device, resolvePass, nullptr); + ReleaseHeapSlots(context); if (uploadView) context.Function("vkDestroyImageView")(context.device, uploadView, nullptr); if (orderView) context.Function("vkDestroyImageView")(context.device, orderView, nullptr); if (twinView) context.Function("vkDestroyImageView")(context.device, twinView, nullptr); - ReleaseHeapSlots(context); if (storageView) context.Function("vkDestroyImageView")(context.device, storageView, nullptr); if (uintStorageView) context.Function("vkDestroyImageView")(context.device, uintStorageView, nullptr); destroy({image, memory, view}); @@ -1429,7 +1429,7 @@ SampleOrderTarget MultisampleTargetOrderTarget(const Context& context, const Col auto& found = acquire(context, target); found.drawn = true; ++found.contents; - return {found.image, found.OrderView(), found.orderFormat, target.extent, target.samples, SampleOrderMethod::Storage, found.shared_from_this()}; + return {found.image, found.OrderView(), found.orderFormat, target.extent, target.samples, SampleOrderMethod::Storage, found.shared_from_this(), &found}; } VkImageView MultisampleTargetView(const Context& context, const ColorTarget& target, VkImage* image) { @@ -1548,14 +1548,14 @@ MultisampleStorage MultisampleTargetStorageView(const Context& context, const Gu if (rendered.eqaaFragments != 0) throw std::runtime_error(eqaaReadRefusal("storage image access to", rendered, resource)); if (sameStorageForm(context, rendered.format, format) && rendered.extent.width == resource.width && rendered.extent.height == resource.height && rendered.samples == resource.samples && rendered.mip == 0) { if (!holdHostOnly(*target)) continue; - return {target->Storage(StorageFormatForGuest(context, resource.format), uintStorage), target.get()}; + return {target->Storage(StorageFormatForGuest(context, resource.format), uintStorage), target.get(), target}; } other = target.get(); } if (other == nullptr) { Require(Recorder::Active() != nullptr, "a multisampled color target is only written by recorded dispatches"); auto& created = createFilled(context, resource, format, "writing", true); - return {created.Storage(StorageFormatForGuest(context, resource.format), uintStorage), &created}; + return {created.Storage(StorageFormatForGuest(context, resource.format), uintStorage), &created, created.shared_from_this()}; } char text[320]; std::snprintf(text, sizeof(text), "AGC graphics: storage image access to multisampled color target 0x%llx (%ux%u, %u samples, vk format %d) as a %ux%u texture of %u samples and guest format %u (vk %d) is not implemented", static_cast(resource.baseAddress), other->target.extent.width, other->target.extent.height, other->target.samples, static_cast(other->target.format), resource.width, resource.height, resource.samples, resource.format, static_cast(format)); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleUpload.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleUpload.cpp index ca9f2fd37edb..46551bd95b31 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleUpload.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleUpload.cpp @@ -4,12 +4,27 @@ #include #include #include +#include #include namespace AgcDriver::Graphics { -VkPipeline TextureDetiler::multisampleUploadPipeline(std::uint32_t elementBytes) { - const auto key = (1u << 19u) | elementBytes; +namespace { + +struct HeapMultisamplePush { + std::array values; + std::uint32_t pad; + VkDeviceAddress buffer; + std::uint32_t slot; + std::uint32_t pad2; +}; + +static_assert(offsetof(HeapMultisamplePush, buffer) == 32 && offsetof(HeapMultisamplePush, slot) == 40 && sizeof(HeapMultisamplePush) == 48); + +} + +VkPipeline TextureDetiler::multisampleUploadPipeline(std::uint32_t elementBytes, bool heap) { + const auto key = (1u << 19u) | (heap ? 1u << 18u : 0u) | elementBytes; for (const auto& entry : pipelines) if (entry.first == key) return entry.second; if (multisampleUploadModule == VK_NULL_HANDLE) { VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; @@ -28,7 +43,12 @@ VkPipeline TextureDetiler::multisampleUploadPipeline(std::uint32_t elementBytes) info.layout = imagePipelineLayout; pipelines.reserve(pipelines.size() + 1u); VkPipeline result = VK_NULL_HANDLE; - { + if (heap) { + const std::array mappings{ + HeapPushAddressMapping(0u, 0u, offsetof(HeapMultisamplePush, buffer)), + HeapPushIndexMapping(BindlessHeap::For(context), 0u, 1u, HeapPassStorageImages, offsetof(HeapMultisamplePush, slot))}; + result = CreateHeapComputePipeline(context, info, mappings); + } else { auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1u, &info, nullptr, &result), "vkCreateComputePipelines multisample upload"); } @@ -36,7 +56,7 @@ VkPipeline TextureDetiler::multisampleUploadPipeline(std::uint32_t elementBytes) return result; } -void TextureDetiler::DispatchMultisampleImage(VkCommandBuffer commands, std::uint32_t elementBytes, VkBuffer source, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements) { +void TextureDetiler::DispatchMultisampleImage(VkCommandBuffer commands, std::uint32_t elementBytes, VkBuffer source, std::uint64_t offset, std::uint64_t bytes, VkImageView arrayView, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t firstElement, std::uint32_t elements, const HeapSlotOwner* owner) { Require(context.storageImageMultisample && context.storageImageWriteWithoutFormat, "device does not enable multisampled storage image writes without format"); Require(commands != VK_NULL_HANDLE && source != VK_NULL_HANDLE && arrayView != VK_NULL_HANDLE, "multisample upload requires commands, buffer and array view"); Require(std::has_single_bit(elementBytes) && elementBytes <= 16u, "multisample upload element size is unsupported"); @@ -53,7 +73,19 @@ void TextureDetiler::DispatchMultisampleImage(VkCommandBuffer commands, std::uin Require(groupsX != 0u, "device has no multisample upload workgroups"); const auto groupsY = (groups + groupsX - 1u) / groupsX; Require(groupsY <= context.limits.maxComputeWorkGroupCount[1] && groupsX * groupsY * 64u <= std::numeric_limits::max(), "multisample upload dispatch exceeds the device limits"); - const auto target = multisampleUploadPipeline(elementBytes); + const std::array push{width, height, layers, fragments, firstElement, elements, static_cast(groupsX * 64u)}; + const auto address = owner != nullptr && HeapPassesActive(context) ? bufferAddress(source) : 0; + const auto heapTarget = address != 0 ? multisampleUploadPipeline(elementBytes, true) : VK_NULL_HANDLE; + const auto slot = heapTarget != VK_NULL_HANDLE ? BindlessHeap::For(context).ViewSlot(HeapPassStorageKind, owner, arrayView) : std::nullopt; + if (slot) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, heapTarget); + const HeapMultisamplePush pushed{push, 0u, address + offset, *slot, 0u}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + context.Function("vkCmdDispatch")(commands, static_cast(groupsX), static_cast(groupsY), 1u); + return; + } + const auto target = multisampleUploadPipeline(elementBytes, false); const auto set = allocateSet(true); const VkDescriptorBufferInfo buffer{source, offset, bytes}; const VkDescriptorImageInfo image{VK_NULL_HANDLE, arrayView, VK_IMAGE_LAYOUT_GENERAL}; @@ -61,7 +93,6 @@ void TextureDetiler::DispatchMultisampleImage(VkCommandBuffer commands, std::uin context.Function("vkUpdateDescriptorSets")(context.device, 2u, writes.data(), 0u, nullptr); context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0u, 1u, &set, SetBindSite::ColorTransfer); - const std::array push{width, height, layers, fragments, firstElement, elements, static_cast(groupsX * 64u)}; CmdPushConstants(context, commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(push), push.data()); context.Function("vkCmdDispatch")(commands, static_cast(groupsX), static_cast(groupsY), 1u); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp index 3e236343fcb0..428af2c39e34 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/SampleOrder.cpp @@ -19,10 +19,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include @@ -45,6 +47,20 @@ struct DepthPush { std::uint32_t bit; }; +struct HeapStoragePush { + StoragePush push; + std::uint32_t image; +}; + +struct HeapDepthPush { + DepthPush push; + std::uint32_t depth; + std::uint32_t stencil; +}; + +static_assert(offsetof(HeapStoragePush, image) == 28); +static_assert(offsetof(HeapDepthPush, depth) == 20 && offsetof(HeapDepthPush, stencil) == 24); + bool exactDepth(VkFormat format) { return format == VK_FORMAT_D16_UNORM || format == VK_FORMAT_D32_SFLOAT || format == VK_FORMAT_D16_UNORM_S8_UINT || format == VK_FORMAT_D32_SFLOAT_S8_UINT; } @@ -91,7 +107,7 @@ void transitionLocated(const Context& context, VkCommandBuffer commands, VkImage context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, sourceStages, destinationStages, 0, 0, nullptr, 0, nullptr, 1, &barrier); } -class CopyImage { +class CopyImage : public HeapSlotOwner { public: CopyImage(const Context& context, VkFormat format, std::uint32_t samples, VkExtent2D extent, bool stencil) : context(context), format(format), samples(samples), extent(extent) { try { @@ -148,6 +164,7 @@ class CopyImage { } void release() noexcept { + ReleaseHeapSlots(context); if (stencilView) context.Function("vkDestroyImageView")(context.device, stencilView, nullptr); if (depthView) context.Function("vkDestroyImageView")(context.device, depthView, nullptr); if (image) context.Function("vkDestroyImage")(context.device, image, nullptr); @@ -166,6 +183,20 @@ class SampleOrders { void Storage(VkCommandBuffer commands, const SampleOrderTarget& target, const std::array& map, VkExtent2D region) { const auto pipeline = storagePipeline(target.format); + const StoragePush push{map, {region.width, region.height}, target.samples}; + const auto dispatch = [&] { context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, ((region.width + 1u) / 2u + 7u) / 8u, ((region.height + 1u) / 2u + 7u) / 8u, 1); }; + const auto heapPipeline = heapStoragePipelines[storageIndex(target.format)]; + if (heapPipeline != VK_NULL_HANDLE && target.owner != nullptr) { + auto& heap = BindlessHeap::For(context); + if (const auto slot = heap.ViewSlot(HeapPassStorageKind, target.owner, target.view)) { + heap.BindDescriptorHeaps(commands); + context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, heapPipeline); + const HeapStoragePush pushed{push, *slot}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + dispatch(); + return; + } + } const auto set = allocate(storageSetLayout, {{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, setsPerPool}}); const VkDescriptorImageInfo imageInfo{VK_NULL_HANDLE, target.view, VK_IMAGE_LAYOUT_GENERAL}; VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; @@ -175,11 +206,10 @@ class SampleOrders { write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; write.pImageInfo = &imageInfo; context.Function("vkUpdateDescriptorSets")(context.device, 1, &write, 0, nullptr); - const StoragePush push{map, {region.width, region.height}, target.samples}; context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, storagePipelineLayout, 0, 1, &set, SetBindSite::Detiler); CmdPushConstants(context, commands, storagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); - context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, ((region.width + 1u) / 2u + 7u) / 8u, ((region.height + 1u) / 2u + 7u) / 8u, 1); + dispatch(); } void Depth(VkCommandBuffer commands, const SampleOrderTarget& target, const std::array& map, VkExtent2D region, const SampleOrderPass& order, std::vector>& kept) { @@ -214,18 +244,16 @@ class SampleOrders { if (located) transitionLocated(context, commands, target.image, target.format, info, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, fragmentStages, depthAccess); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, fragmentStages, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | depthAccess); const auto& pass = depthPass(target.format, target.samples, target.method, located, locations); - const auto set = allocate(sampledSetLayout, {{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, setsPerPool * 2u}}); - std::array images{{{VK_NULL_HANDLE, copy->depthView, VK_IMAGE_LAYOUT_GENERAL}, {VK_NULL_HANDLE, stencil ? copy->stencilView : copy->depthView, VK_IMAGE_LAYOUT_GENERAL}}}; - std::array writes{}; - for (std::uint32_t binding = 0; binding < writes.size(); ++binding) { - writes[binding].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[binding].dstSet = set; - writes[binding].dstBinding = binding; - writes[binding].descriptorCount = 1; - writes[binding].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; - writes[binding].pImageInfo = &images[binding]; + std::optional depthSlot; + std::optional stencilSlot; + if (pass.heapDepth != VK_NULL_HANDLE) { + auto& heap = BindlessHeap::For(context); + depthSlot = heap.ViewSlot(HeapPassSampledKind, copy.get(), copy->depthView); + stencilSlot = depthSlot && stencil ? heap.ViewSlot(HeapPassSampledKind, copy.get(), copy->stencilView) : depthSlot; } - context.Function("vkUpdateDescriptorSets")(context.device, stencil ? 2u : 1u, writes.data(), 0, nullptr); + const bool heapPass = depthSlot && stencilSlot; + VkDescriptorSet set = VK_NULL_HANDLE; + if (!heapPass) set = writeDepthSet(*copy, stencil); const std::array views{target.view}; auto framebuffer = std::make_shared(context, pass.renderPass, views, region); kept.push_back(framebuffer); @@ -246,18 +274,24 @@ class SampleOrders { const VkRect2D scissor{{0, 0}, region}; context.Resolved(&DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, 1, &viewport); context.Resolved(&DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, 1, &scissor); - CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, sampledPipelineLayout, 0, 1, &set, SetBindSite::Detiler); - const auto draw = [&](VkPipeline pipeline, std::uint32_t bit, std::uint32_t writeMask, std::uint32_t reference) { - context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + if (heapPass) BindlessHeap::For(context).BindDescriptorHeaps(commands); + else CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, sampledPipelineLayout, 0, 1, &set, SetBindSite::Detiler); + const auto draw = [&](VkPipeline pipeline, VkPipeline heapPipeline, std::uint32_t bit, std::uint32_t writeMask, std::uint32_t reference) { + context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, heapPass ? heapPipeline : pipeline); context.Resolved(&DeviceFunctions::cmdSetStencilWriteMask, "vkCmdSetStencilWriteMask")(commands, VK_STENCIL_FACE_FRONT_AND_BACK, writeMask); context.Resolved(&DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference")(commands, VK_STENCIL_FACE_FRONT_AND_BACK, reference); const DepthPush push{map, bit}; - CmdPushConstants(context, commands, sampledPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push), &push); + if (heapPass) { + const HeapDepthPush pushed{push, *depthSlot, *stencilSlot}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + } else { + CmdPushConstants(context, commands, sampledPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push), &push); + } context.Resolved(&DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, 3, 1, 0, 0); }; - draw(pass.depth, 0u, 0xffu, 0u); + draw(pass.depth, pass.heapDepth, 0u, 0xffu, 0u); if (target.method == SampleOrderMethod::DepthStencilBits) { - for (std::uint32_t bit = 0; bit < 8u; ++bit) draw(pass.stencilBits, bit, 1u << bit, 0xffu); + for (std::uint32_t bit = 0; bit < 8u; ++bit) draw(pass.stencilBits, pass.heapStencilBits, bit, 1u << bit, 0xffu); } context.Resolved(&DeviceFunctions::cmdEndRenderPass, "vkCmdEndRenderPass")(commands); } @@ -276,8 +310,33 @@ class SampleOrders { VkRenderPass renderPass = VK_NULL_HANDLE; VkPipeline depth = VK_NULL_HANDLE; VkPipeline stencilBits = VK_NULL_HANDLE; + VkPipeline heapDepth = VK_NULL_HANDLE; + VkPipeline heapStencilBits = VK_NULL_HANDLE; }; + VkDescriptorSet writeDepthSet(const CopyImage& copy, bool stencil) { + const auto set = allocate(sampledSetLayout, {{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, setsPerPool * 2u}}); + std::array images{{{VK_NULL_HANDLE, copy.depthView, VK_IMAGE_LAYOUT_GENERAL}, {VK_NULL_HANDLE, stencil ? copy.stencilView : copy.depthView, VK_IMAGE_LAYOUT_GENERAL}}}; + std::array writes{}; + for (std::uint32_t binding = 0; binding < writes.size(); ++binding) { + writes[binding].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[binding].dstSet = set; + writes[binding].dstBinding = binding; + writes[binding].descriptorCount = 1; + writes[binding].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; + writes[binding].pImageInfo = &images[binding]; + } + context.Function("vkUpdateDescriptorSets")(context.device, stencil ? 2u : 1u, writes.data(), 0, nullptr); + return set; + } + + static std::size_t storageIndex(VkFormat format) { + const std::array formats{VK_FORMAT_R8_UINT, VK_FORMAT_R16_UINT, VK_FORMAT_R32_UINT, VK_FORMAT_R32G32_UINT, VK_FORMAT_R32G32B32A32_UINT}; + const auto found = std::ranges::find(formats, format); + Require(found != formats.end(), "reordering the samples of a color target through a storage view of this format is not implemented"); + return static_cast(found - formats.begin()); + } + using DepthKey = std::tuple>; using CopyKey = std::tuple; @@ -318,10 +377,7 @@ class SampleOrders { } VkPipeline storagePipeline(VkFormat format) { - const std::array formats{VK_FORMAT_R8_UINT, VK_FORMAT_R16_UINT, VK_FORMAT_R32_UINT, VK_FORMAT_R32G32_UINT, VK_FORMAT_R32G32B32A32_UINT}; - const auto found = std::ranges::find(formats, format); - Require(found != formats.end(), "reordering the samples of a color target through a storage view of this format is not implemented"); - const auto index = static_cast(found - formats.begin()); + const auto index = storageIndex(format); if (storagePipelines[index] != VK_NULL_HANDLE) return storagePipelines[index]; if (storageSetLayout == VK_NULL_HANDLE) storageSetLayout = setLayout(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT); if (storagePipelineLayout == VK_NULL_HANDLE) storagePipelineLayout = pipelineLayout(storageSetLayout, VK_SHADER_STAGE_COMPUTE_BIT, sizeof(StoragePush)); @@ -338,6 +394,10 @@ class SampleOrders { auto pipelineCacheLock = context.LockPipelineCacheForUse(); created = context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &storagePipelines[index]); } + if (created == VK_SUCCESS && HeapPassesActive(context)) { + const auto mapping = HeapPushIndexMapping(BindlessHeap::For(context), 0, 0, HeapPassStorageImages, offsetof(HeapStoragePush, image)); + heapStoragePipelines[index] = CreateHeapComputePipeline(context, info, std::span(&mapping, 1)); + } destroyModule(shader); Check(created, "vkCreateComputePipelines sample order"); return storagePipelines[index]; @@ -442,14 +502,27 @@ class SampleOrders { auto pipelineCacheLock = context.LockPipelineCacheForUse(); created = context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline); } + VkPipeline heapPipeline = VK_NULL_HANDLE; + if (created == VK_SUCCESS && HeapPassesActive(context)) { + const auto& heap = BindlessHeap::For(context); + const std::array mappings{ + HeapPushIndexMapping(heap, 0, 0, VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT, offsetof(HeapDepthPush, depth)), + HeapPushIndexMapping(heap, 0, 1, VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT, offsetof(HeapDepthPush, stencil))}; + heapPipeline = CreateHeapGraphicsPipeline(context, info, mappings); + } destroyModule(fragment); destroyModule(vertex); Check(created, "vkCreateGraphicsPipelines sample order"); - return pipeline; + return std::pair{pipeline, heapPipeline}; }; - if (method == SampleOrderMethod::DepthStencilExport) pass.depth = create(SAMPLE_ORDER_STENCILEXPORT_SPV, sizeof(SAMPLE_ORDER_STENCILEXPORT_SPV), true); - else pass.depth = create(SAMPLE_ORDER_DEPTH_SPV, sizeof(SAMPLE_ORDER_DEPTH_SPV), true); - if (method == SampleOrderMethod::DepthStencilBits) pass.stencilBits = create(SAMPLE_ORDER_STENCILBITS_SPV, sizeof(SAMPLE_ORDER_STENCILBITS_SPV), false); + if (method == SampleOrderMethod::DepthStencilExport) std::tie(pass.depth, pass.heapDepth) = create(SAMPLE_ORDER_STENCILEXPORT_SPV, sizeof(SAMPLE_ORDER_STENCILEXPORT_SPV), true); + else std::tie(pass.depth, pass.heapDepth) = create(SAMPLE_ORDER_DEPTH_SPV, sizeof(SAMPLE_ORDER_DEPTH_SPV), true); + if (method == SampleOrderMethod::DepthStencilBits) std::tie(pass.stencilBits, pass.heapStencilBits) = create(SAMPLE_ORDER_STENCILBITS_SPV, sizeof(SAMPLE_ORDER_STENCILBITS_SPV), false); + if (method == SampleOrderMethod::DepthStencilBits && (pass.heapDepth == VK_NULL_HANDLE) != (pass.heapStencilBits == VK_NULL_HANDLE)) { + if (pass.heapDepth) context.Function("vkDestroyPipeline")(context.device, pass.heapDepth, nullptr); + if (pass.heapStencilBits) context.Function("vkDestroyPipeline")(context.device, pass.heapStencilBits, nullptr); + pass.heapDepth = pass.heapStencilBits = VK_NULL_HANDLE; + } } catch (...) { destroyPass(pass); throw; @@ -513,6 +586,8 @@ class SampleOrders { } void destroyPass(const DepthPass& pass) noexcept { + if (pass.heapStencilBits) context.Function("vkDestroyPipeline")(context.device, pass.heapStencilBits, nullptr); + if (pass.heapDepth) context.Function("vkDestroyPipeline")(context.device, pass.heapDepth, nullptr); if (pass.stencilBits) context.Function("vkDestroyPipeline")(context.device, pass.stencilBits, nullptr); if (pass.depth) context.Function("vkDestroyPipeline")(context.device, pass.depth, nullptr); if (pass.renderPass) context.Function("vkDestroyRenderPass")(context.device, pass.renderPass, nullptr); @@ -522,6 +597,9 @@ class SampleOrders { copies.clear(); for (const auto& [key, pass] : depthPasses) destroyPass(pass); depthPasses.clear(); + for (const auto pipeline : heapStoragePipelines) { + if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); + } for (const auto pipeline : storagePipelines) { if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); } @@ -542,6 +620,7 @@ class SampleOrders { VkPipelineLayout storagePipelineLayout = VK_NULL_HANDLE; VkPipelineLayout sampledPipelineLayout = VK_NULL_HANDLE; std::array storagePipelines{}; + std::array heapStoragePipelines{}; std::map depthPasses; std::map, std::uint64_t>> copies; std::uint64_t uses = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/StagedMerge.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/StagedMerge.cpp index 798e9c5985a4..d848be7759ca 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/StagedMerge.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/StagedMerge.cpp @@ -5,6 +5,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/PackedMerge_spv.h" #include +#include #include #include #include @@ -24,7 +25,15 @@ struct MergePush { std::uint32_t samples; }; -class Temporary final : public StagedTemporary { +struct HeapMergePush { + MergePush push; + std::uint32_t temporary; + std::uint32_t target; +}; + +static_assert(offsetof(HeapMergePush, temporary) == 24 && offsetof(HeapMergePush, target) == 28); + +class Temporary final : public StagedTemporary, public HeapSlotOwner { public: Temporary(const Context& context, VkExtent2D extent, std::uint32_t samples) : context(context), extent(extent), samples(samples) { try { @@ -71,6 +80,7 @@ class Temporary final : public StagedTemporary { private: void release() noexcept { + ReleaseHeapSlots(context); if (view) context.Function("vkDestroyImageView")(context.device, view, nullptr); if (image) context.Function("vkDestroyImage")(context.device, image, nullptr); if (memory) context.Function("vkFreeMemory")(context.device, memory, nullptr); @@ -100,8 +110,25 @@ class StagedMerges { return temporaries.back(); } - void Merge(VkCommandBuffer commands, StagedTemporary& temporary, VkImageView target, std::uint32_t mask, std::uint32_t samples, VkRect2D area) { + void Merge(VkCommandBuffer commands, StagedTemporary& temporary, VkImageView target, std::uint32_t mask, std::uint32_t samples, VkRect2D area, const HeapSlotOwner* targetOwner) { const auto pipeline = mergePipeline(); + const auto x = static_cast(area.offset.x); + const auto y = static_cast(area.offset.y); + const MergePush push{{x, y}, {x + area.extent.width, y + area.extent.height}, mask, samples}; + auto* owned = dynamic_cast(&temporary); + if (heapPipeline != VK_NULL_HANDLE && targetOwner != nullptr && owned != nullptr) { + auto& heap = BindlessHeap::For(context); + const auto temporarySlot = heap.ViewSlot(HeapPassStorageKind, owned, temporary.View()); + const auto targetSlot = temporarySlot ? heap.ViewSlot(HeapPassStorageKind, targetOwner, target) : std::nullopt; + if (targetSlot) { + heap.BindDescriptorHeaps(commands); + context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, heapPipeline); + const HeapMergePush pushed{push, *temporarySlot, *targetSlot}; + CmdPushData(context, commands, sizeof(pushed), &pushed); + context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, (area.extent.width + 7u) / 8u, (area.extent.height + 7u) / 8u, 1); + return; + } + } const auto set = allocate(); const std::array images{{{VK_NULL_HANDLE, temporary.View(), VK_IMAGE_LAYOUT_GENERAL}, {VK_NULL_HANDLE, target, VK_IMAGE_LAYOUT_GENERAL}}}; std::array writes{}; @@ -114,9 +141,6 @@ class StagedMerges { writes[binding].pImageInfo = &images[binding]; } context.Function("vkUpdateDescriptorSets")(context.device, 2, writes.data(), 0, nullptr); - const auto x = static_cast(area.offset.x); - const auto y = static_cast(area.offset.y); - const MergePush push{{x, y}, {x + area.extent.width, y + area.extent.height}, mask, samples}; context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, SetBindSite::StagedMerge); CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); @@ -152,6 +176,13 @@ class StagedMerges { auto pipelineCacheLock = context.LockPipelineCacheForUse(); created = context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline); } + if (created == VK_SUCCESS && HeapPassesActive(context)) { + const auto& heap = BindlessHeap::For(context); + const std::array mappings{ + HeapPushIndexMapping(heap, 0, 0, HeapPassStorageImages, offsetof(HeapMergePush, temporary)), + HeapPushIndexMapping(heap, 0, 1, HeapPassStorageImages, offsetof(HeapMergePush, target))}; + heapPipeline = CreateHeapComputePipeline(context, info, mappings); + } context.Function("vkDestroyShaderModule")(context.device, shader, nullptr); Check(created, "vkCreateComputePipelines staged merge"); return pipeline; @@ -199,6 +230,7 @@ class StagedMerges { void release() noexcept { temporaries.clear(); if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); + if (heapPipeline) context.Function("vkDestroyPipeline")(context.device, heapPipeline, nullptr); for (const auto pool : pools) context.Function("vkDestroyDescriptorPool")(context.device, pool, nullptr); if (pipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, pipelineLayout, nullptr); if (setLayout) context.Function("vkDestroyDescriptorSetLayout")(context.device, setLayout, nullptr); @@ -208,6 +240,7 @@ class StagedMerges { VkDescriptorSetLayout setLayout = VK_NULL_HANDLE; VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + VkPipeline heapPipeline = VK_NULL_HANDLE; std::vector pools; std::vector serials; std::size_t current = 0; @@ -258,12 +291,13 @@ void RecordStagedClear(const Context& context, VkCommandBuffer commands, StagedT if (Recorder::Active() != nullptr) Recorder::CountBarriers(Recorder::CommandClass::Draw, 2); } -void RecordStagedMerge(const Context& context, VkCommandBuffer commands, StagedTemporary& temporary, VkImageView target, std::uint32_t mask, std::uint32_t samples, VkRect2D area) { +void RecordStagedMerge(const Context& context, VkCommandBuffer commands, StagedTemporary& temporary, VkImageView target, std::uint32_t mask, std::uint32_t samples, VkRect2D area, + const HeapSlotOwner* targetOwner) { if (area.extent.width == 0 || area.extent.height == 0) return; RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, anyWrite, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); { std::lock_guard lock(mergesMutex()); - mergesFor(context).Merge(commands, temporary, target, mask, samples, area); + mergesFor(context).Merge(commands, temporary, target, mask, samples, area, targetOwner); } RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_SHADER_WRITE_BIT, anyAccess); if (Recorder::Active() != nullptr) Recorder::CountBarriers(Recorder::CommandClass::Draw, 2); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index 097e4d64da92..fb196b069393 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -203,6 +203,7 @@ void TextureDetiler::release() noexcept { if (addressedModule) context.Function("vkDestroyShaderModule")(context.device, addressedModule, nullptr); if (addressedRepackLayout) context.Function("vkDestroyPipelineLayout")(context.device, addressedRepackLayout, nullptr); if (addressedPipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, addressedPipelineLayout, nullptr); + if (heapRepackPipeline) context.Function("vkDestroyPipeline")(context.device, heapRepackPipeline, nullptr); if (repackPipeline) context.Function("vkDestroyPipeline")(context.device, repackPipeline, nullptr); if (repackModule) context.Function("vkDestroyShaderModule")(context.device, repackModule, nullptr); if (imageWordModule) context.Function("vkDestroyShaderModule")(context.device, imageWordModule, nullptr); @@ -266,13 +267,15 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem values[2] = 2u; std::copy(equation->bits.begin(), equation->bits.end(), values.begin() + 4); } + const bool descriptorWords = elementBytes < 4u && (image ? retile && values[2] != 2u : !retile || values[2] != 2u); + addressed = addressed || (heap && !image && descriptorWords); if (addressed && addressedModule == VK_NULL_HANDLE) { VkShaderModuleCreateInfo moduleInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; moduleInfo.codeSize = sizeof(TEXTURE_DETILE_ADDRESSED_SPV); moduleInfo.pCode = TEXTURE_DETILE_ADDRESSED_SPV; Check(context.Function("vkCreateShaderModule")(context.device, &moduleInfo, nullptr, &addressedModule), "vkCreateShaderModule"); } - const bool words = !addressed && elementBytes < 4u && (image ? retile && values[2] != 2u : !retile || values[2] != 2u); + const bool words = !addressed && descriptorWords; auto& shader = addressed ? addressedModule : image ? (words ? imageWordModule : imageModule) : (words ? wordModule : module); if (shader == VK_NULL_HANDLE) { if (!image) shader = CreateShaderModule(context, TEXTURE_DETILE_WORDS_SPV, sizeof(TEXTURE_DETILE_WORDS_SPV), "vkCreateShaderModule detile words"); @@ -298,11 +301,14 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; auto heapFlags = DescriptorHeapFlags(); if (heap) { - Require(image && !addressed, "only the image detiler runs on the descriptor heap"); - const auto& bindless = BindlessHeap::For(context); - mappings[0] = PushAddressMapping(0, offsetof(HeapImagePush, tiled)); - mappings[1] = PushIndexMapping(bindless, 1, offsetof(HeapImagePush, slot)); - mappingInfo.mappingCount = static_cast(mappings.size()); + if (image) { + mappings[0] = PushAddressMapping(0, offsetof(HeapImagePush, tiled)); + mappings[1] = PushIndexMapping(BindlessHeap::For(context), 1, offsetof(HeapImagePush, slot)); + } else if (!addressed) { + mappings[0] = PushAddressMapping(0, offsetof(AddressedPush, input)); + mappings[1] = PushAddressMapping(1, offsetof(AddressedPush, output)); + } + mappingInfo.mappingCount = addressed ? 0u : static_cast(mappings.size()); mappingInfo.pMappings = mappings.data(); createInfo.stage.pNext = &mappingInfo; createInfo.pNext = &heapFlags; @@ -311,7 +317,9 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem VkPipeline result = VK_NULL_HANDLE; { auto pipelineCacheLock = context.LockPipelineCacheForUse(); - Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &createInfo, nullptr, &result), "vkCreateComputePipelines"); + const auto created = context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &createInfo, nullptr, &result); + if (created != VK_SUCCESS && heap) result = VK_NULL_HANDLE; + else Check(created, "vkCreateComputePipelines"); } pipelines.emplace_back(key, result); return result; @@ -356,8 +364,13 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode Require(sourceRange <= context.limits.maxStorageBufferRange && destinationRange <= context.limits.maxStorageBufferRange, "texture detiling buffer range exceeds device limits"); const auto sourceAddress = bufferAddress(source); const auto destinationAddress = sourceAddress != 0 ? bufferAddress(destination) : 0; - const bool addressed = sourceAddress != 0 && destinationAddress != 0; - if (addressed) { + const auto heapPipeline = sourceAddress != 0 && destinationAddress != 0 && HeapPassesActive(context) ? pipeline(MipTileMode(tileMode, layout), elementBytes, retile, thickPipeline, false, false, true) : VK_NULL_HANDLE; + const bool heap = heapPipeline != VK_NULL_HANDLE; + const bool addressed = !heap && sourceAddress != 0 && destinationAddress != 0; + if (heap) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, heapPipeline); + } else if (addressed) { context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline(MipTileMode(tileMode, layout), elementBytes, retile, thickPipeline, false, true)); } else { const auto set = allocateSet(); @@ -400,9 +413,10 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode push.rowBegin = window.rowBegin; push.pipeBankXor = window.pipeBankXor ^ layerBankXor(tileMode, elementBytes, layout, slice); push.splitStride = layout.gcnSplitStride; - if (addressed) { + if (heap || addressed) { const AddressedPush pushed{push, sourceAddress + sourceDescriptorOffset, destinationAddress + destinationDescriptorOffset}; - CmdPushConstants(context, commands, addressedPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pushed), &pushed); + if (heap) CmdPushData(context, commands, sizeof(pushed), &pushed); + else CmdPushConstants(context, commands, addressedPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pushed), &pushed); } else { CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); } @@ -423,8 +437,12 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s VkComputePipelineCreateInfo createInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; createInfo.stage = stage; createInfo.layout = pipelineLayout; - auto pipelineCacheLock = context.LockPipelineCacheForUse(); - Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &createInfo, nullptr, &repackPipeline), "vkCreateComputePipelines repack"); + { + auto pipelineCacheLock = context.LockPipelineCacheForUse(); + Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &createInfo, nullptr, &repackPipeline), "vkCreateComputePipelines repack"); + } + const std::array mappings{PushAddressMapping(0, offsetof(AddressedRepackPush, source)), PushAddressMapping(1, offsetof(AddressedRepackPush, destination))}; + heapRepackPipeline = CreateHeapComputePipeline(context, createInfo, mappings); } const auto alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); const auto sourceDescriptorOffset = sourceOffset - sourceOffset % alignment; @@ -439,6 +457,14 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s const std::array repackPush{static_cast(sourceOffset - sourceDescriptorOffset), static_cast(destinationOffset - destinationDescriptorOffset), static_cast(words), static_cast(std::min(words, rowWords))}; const auto sourceAddress = bufferAddress(source); const auto destinationAddress = sourceAddress != 0 ? bufferAddress(destination) : 0; + if (sourceAddress != 0 && destinationAddress != 0 && heapRepackPipeline != VK_NULL_HANDLE && HeapPassesActive(context)) { + const AddressedRepackPush pushed{repackPush, sourceAddress + sourceDescriptorOffset, destinationAddress + destinationDescriptorOffset}; + BindlessHeap::For(context).BindDescriptorHeaps(commands); + context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, heapRepackPipeline); + CmdPushData(context, commands, sizeof(pushed), &pushed); + context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, static_cast((std::min(words, rowWords) + 63u) / 64u), static_cast(rows), 1); + return; + } if (sourceAddress != 0 && destinationAddress != 0) { if (addressedRepackPipeline == VK_NULL_HANDLE) { VkShaderModuleCreateInfo moduleInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; @@ -629,11 +655,12 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til push.splitStride = layout.gcnSplitStride; std::optional slot; const auto tiledAddress = owner != nullptr && DescriptorHeapEnabled() ? bufferAddress(tiled) : 0; - if (tiledAddress != 0) slot = BindlessHeap::For(context).ViewSlot(DetileHeapKind, owner, view); + const auto heapPipeline = tiledAddress != 0 ? pipeline(MipTileMode(tileMode, layout), elementBytes, retile, false, true, false, true) : VK_NULL_HANDLE; + if (heapPipeline != VK_NULL_HANDLE) slot = BindlessHeap::For(context).ViewSlot(DetileHeapKind, owner, view); if (slot) { auto& bindless = BindlessHeap::For(context); bindless.BindDescriptorHeaps(commands); - context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline(MipTileMode(tileMode, layout), elementBytes, retile, false, true, false, true)); + context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, heapPipeline); const HeapImagePush pushed{push, tiledAddress + descriptorOffset, *slot, 0u}; const VkPushDataInfoEXT data{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {&pushed, sizeof(pushed)}}; context.Function("vkCmdPushDataEXT")(commands, &data); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 58c224500e37..7f92e9023e18 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -393,13 +393,13 @@ int main(int argc, char** argv) { const bool comesBack = !mode.empty() && !largeSpans; try { SetTestEnvironment("APS5_GPU_HEAP", "1"); + SetTestEnvironment("APS5_HEAP_SLOT_CAP", comesBack ? "8" : "1"); auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; if (!device->graphicsContext().descriptorHeap) { std::printf("skipped, the device has no VK_EXT_descriptor_heap\n"); return VulkanTestSkipped; } - SetTestEnvironment("APS5_HEAP_SLOT_CAP", comesBack ? "8" : "1"); if (largeSpans) { bool ran = false; { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleReadback.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleReadback.cpp index a6c84ad27f7d..1701dd301d90 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleReadback.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampleReadback.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp" @@ -16,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -30,6 +32,21 @@ struct VulkanDeviceTestAccess { namespace { +template +void RecordStayingOnHeap(const AgcDriver::Graphics::Context& context, VkCommandBuffer commands, const std::string& what, Record&& record) { + if (!AgcDriver::Graphics::HeapPassesActive(context)) { + record(); + return; + } + auto& heap = AgcDriver::Graphics::BindlessHeap::For(context); + heap.BindDescriptorHeaps(commands); + const auto binds = AgcDriver::Graphics::DescriptorHeapBinds(); + record(); + heap.BindDescriptorHeaps(commands); + if (AgcDriver::Graphics::DescriptorHeapBinds() != binds) throw std::runtime_error(what + " put its command buffer back in classic descriptor mode, so the heaps were bound again"); +} + + using namespace AgcDriver::Graphics; PFN_vkGetDeviceProcAddr originalDeviceProc = nullptr; @@ -80,7 +97,7 @@ bool SurfaceSupported(const Context& context, VkFormat format, std::uint32_t sam return false; } -struct Surface { +struct Surface : AgcDriver::Graphics::HeapSlotOwner { Context context; VkFormat format; std::uint32_t elementBytes; @@ -234,6 +251,7 @@ struct Surface { Surface& operator=(const Surface&) = delete; void Release() noexcept { + ReleaseHeapSlots(context); if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); if (pipelineLayout) context.Function("vkDestroyPipelineLayout")(context.device, pipelineLayout, nullptr); for (const auto module : modules) if (module) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); @@ -294,7 +312,7 @@ std::vector CheckReadback(TextureDetiler& reader, const Surface& surf CommandBatch batch(surface.context); RecordMemoryBarrier(surface.context, batch.Handle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); for (std::uint32_t repeat = 0u; repeat < repetitions; ++repeat) { - reader.DispatchMultisampleReadback(batch.Handle(), surface.format, output.Handle(), offset, bytes, surface.arrayView, surface.width, surface.height, surface.layers, surface.samples, first, elements); + RecordStayingOnHeap(surface.context, batch.Handle(), "the multisample readback", [&] { reader.DispatchMultisampleReadback(batch.Handle(), surface.format, output.Handle(), offset, bytes, surface.arrayView, surface.width, surface.height, surface.layers, surface.samples, first, elements, &surface); }); if (repeat + 1u < repetitions) RecordMemoryBarrier(surface.context, batch.Handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); } RecordMemoryBarrier(surface.context, batch.Handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); @@ -373,7 +391,7 @@ void CheckRefusals(TextureDetiler& reader, const Surface& surface) { Buffer output(surface.context, 4096u, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); CommandBatch batch(surface.context); const auto call = [&](VkFormat format, std::uint64_t offset, std::uint64_t bytes, std::uint32_t width, std::uint32_t height, std::uint32_t layers, std::uint32_t fragments, std::uint32_t first, std::uint32_t elements) { - reader.DispatchMultisampleReadback(batch.Handle(), format, output.Handle(), offset, bytes, surface.arrayView, width, height, layers, fragments, first, elements); + RecordStayingOnHeap(surface.context, batch.Handle(), "the multisample readback", [&] { reader.DispatchMultisampleReadback(batch.Handle(), format, output.Handle(), offset, bytes, surface.arrayView, width, height, layers, fragments, first, elements, &surface); }); }; for (auto format : {VK_FORMAT_UNDEFINED, VK_FORMAT_R32_SFLOAT, VK_FORMAT_D16_UNORM, VK_FORMAT_D32_SFLOAT_S8_UINT}) Refused([&] { call(format, 0u, 4u, 1u, 1u, 1u, 4u, 0u, 1u); }, "requires an unsigned element view or D32 depth"); for (auto fragments : {0u, 1u, 3u, 16u}) Refused([&] { call(surface.format, 0u, 4u, 1u, 1u, 1u, fragments, 0u, 1u); }, "fragment count is unsupported"); @@ -406,7 +424,7 @@ std::vector Upload(TextureDetiler& transfer, TextureDetiler& reader, for (std::uint32_t repeat = 0; repeat < repetitions; ++repeat) { for (std::size_t done = 0; done < bytes; done += stride) { const auto count = std::min(stride, bytes - done); - transfer.DispatchMultisampleImage(batch.Handle(), surface.elementBytes, source.Handle(), offset + done, (count + 3u) & ~std::size_t{3}, surface.arrayView, surface.width, surface.height, surface.layers, surface.samples, first + static_cast(done / surface.elementBytes), static_cast(count / surface.elementBytes)); + RecordStayingOnHeap(surface.context, batch.Handle(), "the multisample upload", [&] { transfer.DispatchMultisampleImage(batch.Handle(), surface.elementBytes, source.Handle(), offset + done, (count + 3u) & ~std::size_t{3}, surface.arrayView, surface.width, surface.height, surface.layers, surface.samples, first + static_cast(done / surface.elementBytes), static_cast(count / surface.elementBytes), &surface); }); } RecordMemoryBarrier(surface.context, batch.Handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp index e2b68ff7d27e..33fc60fd157a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp @@ -600,7 +600,7 @@ void CheckFirstSampleReads(AgcDriver::VulkanDevice& device, const std::arrayCommands()); - Require(AgcDriver::Graphics::DescriptorHeapBinds() == binds + 1u, - "a first-sample copy recorded after the descriptor heaps were bound left them marked bound, so a heap draw or dispatch after it would run without them"); + Require(AgcDriver::Graphics::DescriptorHeapBinds() == binds, + "a first-sample copy in heap mode put its command buffer back in classic descriptor mode, so the heaps were bound again"); recorder->Submit(); recorder->Sync(); } @@ -1354,7 +1354,7 @@ int main(int argc, char** argv) { const auto drawn = LoadSamples(*device, block); CheckSamples(state, drawn, {}); CheckFirstSampleReads(*device, TargetDescriptor(block, SampleShift), drawn, true, "from the drawn 4x target"); - CheckFirstSampleCopyLeavesHeapMode(*device, block); + CheckFirstSampleCopyStaysInHeapMode(*device, block); CheckFirstSampleReads(*device, TargetDescriptor(block, SampleShift), drawn, true, "from the drawn 4x target", AdjustedPlaneCode, "image_sample_a"); std::puts("a DIM 2D image_sample_a read of a 4x color target returns each pixel's sample 0"); Draw(*device, state, 0, 2u, Unorm8PixelCode); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampleOrder.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampleOrder.cpp index ba9346b3e716..e3a921640cd3 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampleOrder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampleOrder.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" @@ -61,6 +62,21 @@ struct VulkanDeviceTestAccess { namespace { +template +void RecordStayingOnHeap(const AgcDriver::Graphics::Context& context, VkCommandBuffer commands, const std::string& what, Record&& record) { + if (!AgcDriver::Graphics::HeapPassesActive(context)) { + record(); + return; + } + auto& heap = AgcDriver::Graphics::BindlessHeap::For(context); + heap.BindDescriptorHeaps(commands); + const auto binds = AgcDriver::Graphics::DescriptorHeapBinds(); + record(); + heap.BindDescriptorHeaps(commands); + if (AgcDriver::Graphics::DescriptorHeapBinds() != binds) throw std::runtime_error(what + " put its command buffer back in classic descriptor mode, so the heaps were bound again"); +} + + using AgcDriver::Graphics::Check; using AgcDriver::Graphics::Context; using AgcDriver::Graphics::KeptSampleOrder; @@ -524,7 +540,8 @@ bool ColorSwaps(const Context& context, VkFormat format, std::uint32_t elementBy texels.Storage(1u, values.Handle()); const std::array store{SwapExtent.width, SwapExtent.height, samples, 1u}; const std::array load{SwapExtent.width, SwapExtent.height, samples, 0u}; - const SampleOrderTarget target{image.Handle(), view, alias, SwapExtent, samples, SampleOrderMethod::Storage, nullptr}; + const AgcDriver::Graphics::HeapPassSlots slots(context); + const SampleOrderTarget target{image.Handle(), view, alias, SwapExtent, samples, SampleOrderMethod::Storage, nullptr, &slots}; const SampleOrderPass pass{order, SwapRegion, {}, false}; std::vector> kept; Submit(context, [&](VkCommandBuffer commands) { @@ -536,14 +553,14 @@ bool ColorSwaps(const Context& context, VkFormat format, std::uint32_t elementBy }); Require(Masked(ReadValues(values, count), elementBytes) == before, name + ": the stored samples did not read back"); Submit(context, [&](VkCommandBuffer commands) { - AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, std::span(&target, 1u), true, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, std::span(&target, 1u), true, kept); }); FullBarrier(context, commands); texels.Dispatch(commands, load.data(), SwapExtent); HostBarrier(context, commands); }); CheckOrdered(before, Masked(ReadValues(values, count), elementBytes), SwapExtent, SwapRegion, samples, order, true, name + " put in the host's order"); Submit(context, [&](VkCommandBuffer commands) { - AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, std::span(&target, 1u), false, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, std::span(&target, 1u), false, kept); }); FullBarrier(context, commands); texels.Dispatch(commands, load.data(), SwapExtent); HostBarrier(context, commands); @@ -624,14 +641,14 @@ bool DepthSwaps(const Context& context, VkFormat format, std::uint32_t samples, Require(depthHeld && (!stencil || before[index][1] == filled[index][1]), name + ": the filled sample " + std::to_string(index) + " did not read back"); } Submit(context, [&](VkCommandBuffer commands) { - AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, std::span(&target, 1u), true, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, std::span(&target, 1u), true, kept); }); FullBarrier(context, commands); read.Dispatch(commands, push.data(), SwapExtent); HostBarrier(context, commands); }); CheckOrdered(before, ReadValues(values, count), SwapExtent, SwapRegion, samples, order, true, name + " put in the host's order"); Submit(context, [&](VkCommandBuffer commands) { - AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, std::span(&target, 1u), false, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, std::span(&target, 1u), false, kept); }); FullBarrier(context, commands); read.Dispatch(commands, push.data(), SwapExtent); HostBarrier(context, commands); @@ -1442,8 +1459,9 @@ int Bench(AgcDriver::VulkanDevice& device, VkExtent2D extent, std::uint32_t samp Image depth(context, VK_FORMAT_D32_SFLOAT, samples, extent, DepthUsage, located ? VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT : 0u); const auto storage = color.View(alias, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_USAGE_STORAGE_BIT); const auto attachment = depth.View(VK_FORMAT_D32_SFLOAT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); + const AgcDriver::Graphics::HeapPassSlots slots(context); const std::array targets{{ - {color.Handle(), storage, alias, extent, samples, SampleOrderMethod::Storage, nullptr}, + {color.Handle(), storage, alias, extent, samples, SampleOrderMethod::Storage, nullptr, &slots}, {depth.Handle(), attachment, VK_FORMAT_D32_SFLOAT, extent, samples, SampleOrderMethod::Depth, nullptr}, }}; VkQueryPoolCreateInfo queryInfo{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; @@ -1466,13 +1484,13 @@ int Bench(AgcDriver::VulkanDevice& device, VkExtent2D extent, std::uint32_t samp context.Function("vkCmdWriteTimestamp")(commands, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, queries, query); }; stamp(0u); - AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, std::span(targets).subspan(1u), true, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, std::span(targets).subspan(1u), true, kept); }); stamp(1u); - AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, std::span(targets).subspan(1u), false, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, std::span(targets).subspan(1u), false, kept); }); stamp(2u); - AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, targets, true, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, targets, true, kept); }); stamp(3u); - AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, targets, false, kept); + RecordStayingOnHeap(context, commands, "the sample order pass", [&] { AgcDriver::Graphics::RecordSampleOrder(context, commands, pass, targets, false, kept); }); stamp(4u); }); std::array ticks{}; From bf0d6d17f848c59ad949c6e9ff8e623b95a896f2 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 5 Nov 2026 13:51:20 +0530 Subject: [PATCH 115/269] fix(agc): read guest memory in place in heap stages of address draws Since address-based draws became reusable over their cached space, PrepareDrawBindings gives them per-draw copies of guest memory: a snapshot of every read-only input on a build, and a copy of every read-only buffer that moved on a reused hit. Heap stages bind those copies through their ring descriptors, so a draw reads memory as the CPU saw it at record time instead of at execution, and Minecraft Dungeons II shows flickering shadows. Heap stages of an address draw now read guest memory in place, as the BDA table and the hardware do. No snapshot is taken, and a moved buffer is viewed at its new address through the build's own memory (GuestBufferMemory::TryDescriptor, a non-throwing Descriptor). A hit whose moved buffer the build's memory cannot view with the alignment offset the build baked into the shader data is built again. The heap variant of the address draw reuse test never built heap stages; --heap-stages compiles both stages for the heap and checks that a CPU write and a buffer moved inside the space are read in place, with no copies taken (DrawInputCopies), and that a move off the build's alignment is refused. Heap stages report no BDA fault per use, so that case is skipped there and listed in the debt file. --- .../Graphics/include/GuestBufferMemory.hpp | 2 + .../Graphics/include/ShaderResources.hpp | 4 +- .../Graphics/src/GuestBufferMemory.cpp | 31 ++++++++--- .../Graphics/src/ShaderResources.cpp | 41 ++++++++++++-- ...river_address_draw_space_reuse_tests.cmake | 2 + .../tests/execution/AddressDrawSpaceReuse.cpp | 55 +++++++++++++++++-- docs/dev/debt/libSceAgcDriver.md | 2 +- 7 files changed, 117 insertions(+), 20 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index 4ee2ce5ad2dc..8eb9292d87a3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -374,6 +374,8 @@ class GuestBufferMemory { void UploadPrepare(bool addressable); void UploadFinish(bool addressable, std::optional> htileClear = std::nullopt); VkDescriptorBufferInfo Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment) const; + // Descriptor's view, or nothing (the reason in failure) where the memory cannot describe it. + std::optional TryDescriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, std::string* failure = nullptr) const; static std::uint64_t ViewBytes(std::uint64_t bytes, std::uint32_t adjustment); std::vector AddressRanges() const; // The BDA table of the cached address space when it serves this upload alone (an address-based diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 27c62b827606..8cf2fb5fa58b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -170,6 +170,8 @@ ImageTableReuseCounts ImageTableReuses(); std::uint64_t SampledTexturesCleared(); std::uint64_t SampledLookupKeyScans(); std::uint64_t SampledLookupKeyProofs(); +// Copies of guest memory taken for draws to read instead of the memory itself (all time). +std::uint64_t DrawInputCopies(); struct PresyncSurface { std::uint64_t address; @@ -743,7 +745,7 @@ class ShaderResources { }; std::vector faultDescriptors; void prepareFaultSlot() const; - void writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord) const; + void writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord, std::span> inPlace = {}) const; std::shared_ptr> ownRecordBusy = std::make_shared>(false); mutable std::vector drawPoolSizes; // Guest buffer elements bound read-only: each use of this object skips that many pending-write diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index dd07bb7663ce..24b4ec1d2bac 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -6702,34 +6702,47 @@ void GuestBufferMemory::RecordCopyBacks(Recorder& recorder) { } VkDescriptorBufferInfo GuestBufferMemory::Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment) const { - Require(uploaded && !committed, "guest GPU memory is not available"); - Require(bytes != 0 && bytes <= std::numeric_limits::max() - address, "invalid guest buffer view"); + std::string failure; + const auto info = TryDescriptor(address, bytes, adjustment, &failure); + if (!info.has_value()) Require(false, failure); + return *info; +} + +std::optional GuestBufferMemory::TryDescriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, std::string* failure) const { + const auto fail = [failure](std::string text) -> std::optional { + if (failure != nullptr) *failure = std::move(text); + return std::nullopt; + }; + if (!uploaded || committed) return fail("guest GPU memory is not available"); + if (bytes == 0 || bytes > std::numeric_limits::max() - address) return fail("invalid guest buffer view"); const auto* found = owner(address, address + bytes); - Require(found != nullptr, "guest buffer has no GPU owner"); + if (found == nullptr) return fail("guest buffer has no GPU owner"); const auto& region = *found; const auto describe = [&](const char* what) { + if (failure == nullptr) return std::string(); char text[256]; std::snprintf(text, sizeof(text), "guest buffer view 0x%llx+0x%llx %s its GPU owner 0x%llx-0x%llx (buffer %d, direct %d, mirror %d)", static_cast(address), static_cast(bytes), what, static_cast(region.begin), static_cast(region.end), region.buffer != nullptr, region.direct != nullptr, region.mirror != nullptr); return std::string(text); }; - if (!(address >= region.begin && address + bytes <= region.end && (region.buffer != nullptr || region.direct != nullptr || region.mirror != nullptr))) Require(false, describe("exceeds")); + if (!(address >= region.begin && address + bytes <= region.end && (region.buffer != nullptr || region.direct != nullptr || region.mirror != nullptr))) return fail(describe("exceeds")); const auto base = region.direct != nullptr ? region.direct->base - region.direct->lead : region.mirror != nullptr ? mirrorStart(*region.mirror) : region.begin; const auto offset = address - base; Require(context.limits.minStorageBufferOffsetAlignment != 0, "no storage buffer offset alignment"); - Require(base % 4 == 0, "a guest buffer view in a GPU owner that does not start at a DWORD boundary is not implemented"); + if (base % 4 != 0) return fail("a guest buffer view in a GPU owner that does not start at a DWORD boundary is not implemented"); adjustment = static_cast(offset % std::max(context.limits.minStorageBufferOffsetAlignment, 4)); + if (bytes / 4 + adjustment / 4 + 2 > std::numeric_limits::max() / 4) return fail("guest buffer view range overflow"); auto range = ViewBytes(bytes, adjustment); const auto end = region.direct != nullptr ? region.direct->base + region.direct->bytes : servedEnd(region); const bool cut = (region.direct == nullptr || region.runCut) && end < region.end; if (cut) { - Require(address - adjustment < end, "guest buffer view starts past its copy"); + if (address - adjustment >= end) return fail("guest buffer view starts past its copy"); range = std::min(range, end - (address - adjustment)); } if (bytes <= context.limits.maxStorageBufferRange) range = std::min(range, context.limits.maxStorageBufferRange & ~std::uint64_t{3}); - if (address - adjustment + range > end) Require(false, describe("rounded up to its view range exceeds")); - Require(range <= context.limits.maxStorageBufferRange, "guest buffer view exceeds descriptor range limit"); + if (address - adjustment + range > end) return fail(describe("rounded up to its view range exceeds")); + if (range > context.limits.maxStorageBufferRange) return fail("guest buffer view exceeds descriptor range limit"); const auto handle = region.direct != nullptr ? region.direct->buffer : region.mirror != nullptr ? mirrorHandle(*region.mirror) : region.buffer->Handle(); - return {handle, offset - adjustment, range}; + return VkDescriptorBufferInfo{handle, offset - adjustment, range}; } std::uint64_t GuestBufferMemory::ViewBytes(std::uint64_t bytes, std::uint32_t adjustment) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 01993d6e04a9..5c2ca2983621 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -5944,6 +5944,14 @@ std::uint64_t SampledLookupKeyProofs() { return sampledLookupKeyProofs; } +namespace { +std::atomic drawInputCopies{0}; +} + +std::uint64_t DrawInputCopies() { + return drawInputCopies.load(std::memory_order_relaxed); +} + std::uint64_t SampledTexturesCleared() { return TextureCounts().cleared.load(std::memory_order_relaxed); } @@ -6197,6 +6205,14 @@ std::optional> ShaderResources::MovedR const auto bytes = static_cast(GuestBufferMemory::ViewBytes(size, item.adjustment)); if (!GuestMemory::Accessible(reinterpret_cast(begin), bytes)) return std::nullopt; if (guestMemory.WritesOverlap(begin, bytes) || recorder.PendingWriteOverlaps(begin, bytes) || PendingStorageOverlaps(begin, bytes, nullptr) || AnyShadowedOverlaps(begin, bytes)) return std::nullopt; + if (usesBda && heapStage) { + // Heap stages of an address draw read a moved buffer in place, as the build does; + // where the build's memory cannot view it that way, the draw is built again. + std::uint32_t adjustment = 0; + const auto inPlace = guestMemory.TryDescriptor(address, static_cast(size), adjustment); + const bool classic = std::any_of(bindings.begin(), bindings.end(), [&](const Binding& other) { return !(other.heap && other.addressed) && std::find(other.allocations.begin(), other.allocations.end(), index) != other.allocations.end(); }); + if (!inPlace.has_value() || adjustment != item.adjustment || classic) return std::nullopt; + } if (moved.empty()) moved.reserve(allocations.size()); moved.push_back({index, address, static_cast(size)}); } @@ -6280,10 +6296,18 @@ std::size_t ShaderResources::DrawUploadLimit() { std::shared_ptr ShaderResources::PrepareDrawBindings(Recorder& recorder, std::span moved, bool movedOnly, const BdaResources* faultRecord) const { requireGuestBuffers(moved); if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE && !heapStage) || (usesBda && !spaceReuse)) return {}; + // Heap stages of an address draw read guest memory in place, at execution, as the BDA table + // and the hardware do: nothing is snapshotted, and a buffer that moved is viewed at its new + // address (MovedReadOnlyBuffers checked that the build's memory holds that view). + const bool readsInPlace = usesBda && heapStage; + movedOnly = movedOnly || readsInPlace; + thread_local std::vector>* inPlaceSlot = nullptr; + auto& inPlace = ShaderRecompiler::ThreadOwned(inPlaceSlot); + inPlace.clear(); prepareFaultSlot(); thread_local std::vector>* readsSlot = nullptr; auto& reads = ShaderRecompiler::ThreadOwned(readsSlot); - guestMemory.InPlaceReads(reads); + if (!readsInPlace) guestMemory.InPlaceReads(reads); const auto maxSnapshotBytes = maxDrawSnapshotBytes; const auto uploadLimit = DrawUploadLimit(); std::size_t totalSnapshotBytes = 0; @@ -6300,6 +6324,12 @@ std::shared_ptr ShaderResources::PrepareDrawBindi for (std::size_t index = 0; index < allocations.size(); ++index) { const auto& item = allocations[index]; const auto override = std::find_if(moved.begin(), moved.end(), [&](const MovedBuffer& entry) { return entry.allocation == index; }); + if (override != moved.end() && override->words.empty() && readsInPlace) { + std::uint32_t adjustment = 0; + inPlace.push_back({index, wholeDwordRange(guestMemory.Descriptor(override->address, override->size, adjustment))}); + Require(adjustment == item.adjustment, "a moved buffer read in place lost its view's alignment"); + continue; + } if (override != moved.end() && !override->words.empty()) { auto slice = recorder.DrawUpload(override->size); std::memcpy(slice.bytes, override->words.data(), override->size); @@ -6359,19 +6389,21 @@ std::shared_ptr ShaderResources::PrepareDrawBindi if (GuestMemory::TrackerGeneration() != stamp[0]) stamped = false; else if (!uploaded || stamp[1] != 0) recorder.NoteUnwrittenDrawSnapshot(begin, bytes, stamp, buffer, offset); } + drawInputCopies.fetch_add(1, std::memory_order_relaxed); selected.push_back(index); keep({begin, std::move(buffer), offset, bytes}); totalSnapshotBytes += bytes; CaptureTrace::Log("draw-snapshot batch=%llu address=%llx bytes=%zu", static_cast(recorder.Submissions() + 1), static_cast(begin), bytes); } - if (selected.empty()) return {}; - writeDrawSets(*result, selected, faultRecord); + if (selected.empty() && inPlace.empty()) return {}; + Require(inPlace.empty() || addressedBuffers, "a moved buffer read in place has no addressed binding"); + writeDrawSets(*result, selected, faultRecord, inPlace); recorder.Keep(result); for (const auto& snapshot : result->snapshots) recorder.KeepBytes(snapshot.buffer.get(), snapshot.buffer->Bytes().size()); return result; } -void ShaderResources::writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord) const { +void ShaderResources::writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord, std::span> inPlace) const { Require(context.descriptorCache != nullptr, "draw snapshots require a descriptor cache"); std::array described{}; thread_local std::array, 2>* countsSlot = nullptr; @@ -6441,6 +6473,7 @@ void ShaderResources::writeDrawSets(DrawBindings& result, std::spanHandle(), snapshot.offset, snapshot.bytes}; } + for (const auto& [index, info] : inPlace) overrides[index] = info; for (const auto& binding : bindings) { if (!binding.addressed) continue; for (const auto allocation : binding.allocations) overridden = overridden || overrides[allocation].buffer != VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_draw_space_reuse_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_draw_space_reuse_tests.cmake index 4d5d72c9476f..fcfb73e7b6a2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_draw_space_reuse_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_address_draw_space_reuse_tests.cmake @@ -25,6 +25,8 @@ if(BUILD_TESTING) endif() agc_add_env_test(agc_driver_address_draw_space_reuse_heap agc_driver_address_draw_space_reuse_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 TIMEOUT 60 NO_WORKING_DIRECTORY) + agc_add_env_test(agc_driver_address_draw_space_reuse_heap_stages agc_driver_address_draw_space_reuse_tests + ARGS --heap-stages ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 TIMEOUT 60 NO_WORKING_DIRECTORY) agc_add_env_test(agc_driver_address_draw_space_reuse_heap_transitions agc_driver_address_draw_space_reuse_tests ARGS --transitions ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_DRAW_TRANSITIONS=1 TIMEOUT 60 NO_WORKING_DIRECTORY) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp index cc06c649cd96..c034f8c11d2a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp @@ -2,10 +2,13 @@ #include "prx/libSceAgcDriver/Execution/include/Recipe.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "prx/libc/include/GuestArena.hpp" @@ -36,6 +39,7 @@ #include #include #include +#include #include namespace AgcDriver { @@ -61,6 +65,8 @@ constexpr std::size_t PixelCodeOffset = 256; constexpr std::size_t IndirectCodeOffset = 512; constexpr std::size_t PointerSlots = 1024; constexpr std::size_t MovedVerticesOffset = 32768; +// Inside the space, but off the alignment the build's view of the vertices was cut at. +constexpr std::size_t ShiftedVerticesOffset = MovedVerticesOffset + 4100; constexpr std::size_t RingSlotBytes = 256; constexpr std::size_t RingSlots = 8; constexpr std::uint32_t PinWaitMs = 4000; @@ -295,6 +301,8 @@ class Outcomes { AgcDriver::Graphics::AddressDrawReuseCounts before = AgcDriver::Graphics::AddressDrawReuseCounters(); }; +bool HeapStages = false; + std::uint64_t Builds() { const auto counters = AgcDriver::Graphics::BdaResources::TableCacheCounters(); return counters.hits + counters.misses - AgcDriver::Graphics::AddressDrawReuseVerifications(); @@ -324,6 +332,7 @@ struct Scene { pixels.Register(true); std::memcpy(vertices.Data(), Triangle.data(), sizeof(Triangle)); std::memcpy(vertices.Data() + MovedVerticesOffset, Triangle.data(), sizeof(Triangle)); + std::memcpy(vertices.Data() + ShiftedVerticesOffset, Triangle.data(), sizeof(Triangle)); vertices.Register(false); std::memcpy(code.Data() + VertexCodeOffset, VertexCode.data(), sizeof(VertexCode)); std::memcpy(code.Data() + PixelCodeOffset, PixelCode.data(), sizeof(PixelCode)); @@ -362,7 +371,7 @@ struct Scene { ShaderRecompiler::RecompileRequest vertex{ {ShaderStage::Vertex, code.Address(VertexCodeOffset), VertexCode, 0, {}}, {64, 0, userData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, vertexMemory}, - device.Target(), + Target(), {0, 0, 0, 64} }; vertex.useCache = cachedVertex; @@ -372,8 +381,15 @@ struct Scene { shaders[0] = {ShaderStage::Vertex, &vertexResults.back(), 0}; } + // --heap-stages builds both stages as heap stages, as the driver does with the descriptor heap on. + ShaderRecompiler::SpirvTarget Target() const { + auto target = device.Target(); + target.gpuResolvedImages = HeapStages; + return target; + } + void Point(std::uint64_t slot, std::span program = PixelCode, std::size_t offset = PixelCodeOffset) { - const auto target = device.Target(); + const auto target = Target(); ShaderRecompiler::ShaderPixelStageInfo pixel{}; pixel.inputAddr = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionX) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionY); pixel.posX = true; @@ -464,8 +480,13 @@ void CpuWrite(Scene& scene) { Require(scene.DrawnColor() == 120, "address draw space reuse: the draw before the CPU write did not read the guest constant"); scene.Store(scene.constants, 0, 40); const auto before = Builds(); + const auto copies = AgcDriver::Graphics::DrawInputCopies(); const auto color = scene.DrawnColor(); Require(color == 40, "address draw space reuse: a draw after a CPU write into its constant read " + std::to_string(color) + " instead of the written 40"); + if (HeapStages) { + const auto taken = AgcDriver::Graphics::DrawInputCopies() - copies; + Require(taken == 0, "address draw space reuse: heap stages of an address draw read " + std::to_string(taken) + " per-draw copies instead of guest memory in place"); + } Require(Builds() == before, "address draw space reuse: a CPU write into memory the draw reads in place made it build its resources again (" + std::to_string(Builds() - before) + " builds)"); } @@ -746,10 +767,24 @@ void RingRefusals(Scene& scene) { { const Outcomes outcomes; scene.Fetch(MovedVerticesOffset); + const auto copies = AgcDriver::Graphics::DrawInputCopies(); const auto color = scene.DrawnColor(); Require(color == 170, "address draw space reuse: the draw after its read-only vertex buffer moved read " + std::to_string(color) + " instead of 170"); + if (HeapStages) { + const auto taken = AgcDriver::Graphics::DrawInputCopies() - copies; + Require(taken == 0, "address draw space reuse: heap stages read " + std::to_string(taken) + " copies of a vertex buffer that moved inside the space instead of the buffer in place"); + } Require(outcomes[AddressDrawReuse::Reused] == 1 && outcomes.Total() == 1, "address draw space reuse: a draw whose read-only vertex buffer moved inside the space counted " + outcomes.Text() + ", expected one reuse with the buffer bound anew"); } + if (HeapStages) { + const Outcomes outcomes; + scene.Fetch(ShiftedVerticesOffset); + const auto copies = AgcDriver::Graphics::DrawInputCopies(); + const auto color = scene.DrawnColor(); + Require(color == 170, "address draw space reuse: the draw after its vertex buffer moved off its view's alignment read " + std::to_string(color) + " instead of 170"); + Require(outcomes[AddressDrawReuse::MovedBuffer] == 1 && outcomes.Total() == 1, "address draw space reuse: a heap-stage draw whose vertex buffer moved off its view's alignment counted " + outcomes.Text() + ", expected one refusal for a moved GuestBuffers element"); + Require(AgcDriver::Graphics::DrawInputCopies() == copies, "address draw space reuse: heap stages read a copy of a vertex buffer that moved off its view's alignment"); + } { std::memcpy(scene.spare.Data(), Triangle.data(), sizeof(Triangle)); constexpr std::size_t Filled = 64; @@ -1006,20 +1041,28 @@ constexpr std::array TransitionCases{{ int main(int argc, char** argv) { try { - const std::string mode = argc > 1 ? argv[1] : ""; - const std::string only = mode == "--case" && argc > 2 ? argv[2] : ""; - Require(mode.empty() || mode == "--off" || mode == "--transitions" || mode == "--verify" || mode == "--held" || !only.empty(), "usage: [--off | --transitions | --verify | --held | --case ]"); + // --heap-stages [--case ] builds both stages as heap stages. + HeapStages = argc > 1 && std::string_view(argv[1]) == "--heap-stages"; + const int first = HeapStages ? 2 : 1; + const std::string mode = argc > first ? argv[first] : HeapStages ? "--heap-stages" : ""; + const std::string only = mode == "--case" && argc > first + 1 ? argv[first + 1] : ""; + Require(mode.empty() || mode == "--off" || mode == "--transitions" || mode == "--verify" || mode == "--held" || mode == "--heap-stages" || !only.empty(), "usage: [--off | --transitions | --verify | --held | --heap-stages [--case ] | --case ]"); Require(mode != "--verify" || std::getenv("APS5_VERIFY_ADDRESS_DRAW_REUSE") != nullptr, "address draw space reuse: --verify needs APS5_VERIFY_ADDRESS_DRAW_REUSE=1"); Require(mode != "--held" || std::getenv("APS5_RELEASE_ON_UNLOCK") != nullptr, "address draw space reuse: --held needs APS5_RELEASE_ON_UNLOCK=1"); LimitPinWait(); const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; + if (HeapStages && !AgcDriver::Graphics::DescriptorHeapEnabled()) { + std::puts("skipped, the device has no VK_EXT_descriptor_heap, which --heap-stages needs"); + return VulkanTestSkipped; + } { Scene scene(*device); if (!Imported(scene)) { std::puts("skipped, host imports are unavailable: the cached address space needs one"); return VulkanTestSkipped; } + if (HeapStages) Require(std::all_of(scene.shaders.begin(), scene.shaders.end(), [](const AgcDriver::Graphics::CompiledShader& shader) { return AgcDriver::Graphics::HeapShader(shader); }), "address draw space reuse: --heap-stages built a stage that is not a heap stage"); const Outcomes outcomes; const auto verifiedBefore = AgcDriver::Graphics::AddressDrawReuseVerifications(); if (mode == "--off") { @@ -1029,6 +1072,8 @@ int main(int argc, char** argv) { bool ran = false; for (const auto& entry : cases) { if (!only.empty() && only != entry.name) continue; + // Heap stages do not report BDA faults per use yet. + if (HeapStages && std::string_view(entry.name) == "fault-per-use") continue; entry.run(scene); ran = true; } diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index d12123f1234d..dccb2b4208e6 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -388,5 +388,5 @@ ### Opt-in draw paths - [Draw finisher](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp) (`APS5_DRAW_PIPELINE`) - opt-in. The Linux main-image page table it adds matches what Windows already does by default. -- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap`. A stage whose module keeps a set 0 binding the heap does not map (storage images of registration modules) takes the per-draw path, and so does every other stage of its draw. A stage that needs more image slots than the heap holds also takes the per-draw path; with `APS5_HEAP_SLOT_CAP` far below the default, stages that each fit can still exhaust the heap between their compile and their bind, because the nearly-full margin scales with the cap. +- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap`. A stage whose module keeps a set 0 binding the heap does not map (storage images of registration modules) takes the per-draw path, and so does every other stage of its draw. A stage that needs more image slots than the heap holds also takes the per-draw path; with `APS5_HEAP_SLOT_CAP` far below the default, stages that each fit can still exhaust the heap between their compile and their bind, because the nearly-full margin scales with the cap. Heap stages read guest memory in place and report no BDA fault per use, so the address draw reuse test skips its fault-per-use case with `--heap-stages`. A reused address-based draw whose moved read-only buffer cannot be viewed in place with the alignment offset its build baked into the shader data is built again. - [Multi-submit count overflow and buffer validation](../../../core/libs/prx/libSceAgcDriver/Submit/src/Dcb.cpp) (libSceAgcDriver) - whether the console driver imposes an architectural submission packet limit or allows null buffer pointers with non-zero sizes in multi-submit arrays is unmeasured; AgcDriver::SubmitMany validates count against 32-bit pointer array bounds overflow and rejects null addresses for non-empty command buffers with a runtime exception. From c461e5b2f808abc9c5592e47d5482712193a80d0 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 5 Nov 2026 14:11:00 +0530 Subject: [PATCH 116/269] style(agc): drop the comments added with the in-place heap reads --- .../libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp | 1 - .../prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp | 1 - .../prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp | 5 ----- .../tests/execution/AddressDrawSpaceReuse.cpp | 4 ---- 4 files changed, 11 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index 8eb9292d87a3..efd41c0dc136 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -374,7 +374,6 @@ class GuestBufferMemory { void UploadPrepare(bool addressable); void UploadFinish(bool addressable, std::optional> htileClear = std::nullopt); VkDescriptorBufferInfo Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment) const; - // Descriptor's view, or nothing (the reason in failure) where the memory cannot describe it. std::optional TryDescriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, std::string* failure = nullptr) const; static std::uint64_t ViewBytes(std::uint64_t bytes, std::uint32_t adjustment); std::vector AddressRanges() const; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 8cf2fb5fa58b..7ac839c1e880 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -170,7 +170,6 @@ ImageTableReuseCounts ImageTableReuses(); std::uint64_t SampledTexturesCleared(); std::uint64_t SampledLookupKeyScans(); std::uint64_t SampledLookupKeyProofs(); -// Copies of guest memory taken for draws to read instead of the memory itself (all time). std::uint64_t DrawInputCopies(); struct PresyncSurface { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 5c2ca2983621..3bdb86d186f4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6206,8 +6206,6 @@ std::optional> ShaderResources::MovedR if (!GuestMemory::Accessible(reinterpret_cast(begin), bytes)) return std::nullopt; if (guestMemory.WritesOverlap(begin, bytes) || recorder.PendingWriteOverlaps(begin, bytes) || PendingStorageOverlaps(begin, bytes, nullptr) || AnyShadowedOverlaps(begin, bytes)) return std::nullopt; if (usesBda && heapStage) { - // Heap stages of an address draw read a moved buffer in place, as the build does; - // where the build's memory cannot view it that way, the draw is built again. std::uint32_t adjustment = 0; const auto inPlace = guestMemory.TryDescriptor(address, static_cast(size), adjustment); const bool classic = std::any_of(bindings.begin(), bindings.end(), [&](const Binding& other) { return !(other.heap && other.addressed) && std::find(other.allocations.begin(), other.allocations.end(), index) != other.allocations.end(); }); @@ -6296,9 +6294,6 @@ std::size_t ShaderResources::DrawUploadLimit() { std::shared_ptr ShaderResources::PrepareDrawBindings(Recorder& recorder, std::span moved, bool movedOnly, const BdaResources* faultRecord) const { requireGuestBuffers(moved); if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE && !heapStage) || (usesBda && !spaceReuse)) return {}; - // Heap stages of an address draw read guest memory in place, at execution, as the BDA table - // and the hardware do: nothing is snapshotted, and a buffer that moved is viewed at its new - // address (MovedReadOnlyBuffers checked that the build's memory holds that view). const bool readsInPlace = usesBda && heapStage; movedOnly = movedOnly || readsInPlace; thread_local std::vector>* inPlaceSlot = nullptr; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp index c034f8c11d2a..0ec36bed065e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp @@ -65,7 +65,6 @@ constexpr std::size_t PixelCodeOffset = 256; constexpr std::size_t IndirectCodeOffset = 512; constexpr std::size_t PointerSlots = 1024; constexpr std::size_t MovedVerticesOffset = 32768; -// Inside the space, but off the alignment the build's view of the vertices was cut at. constexpr std::size_t ShiftedVerticesOffset = MovedVerticesOffset + 4100; constexpr std::size_t RingSlotBytes = 256; constexpr std::size_t RingSlots = 8; @@ -381,7 +380,6 @@ struct Scene { shaders[0] = {ShaderStage::Vertex, &vertexResults.back(), 0}; } - // --heap-stages builds both stages as heap stages, as the driver does with the descriptor heap on. ShaderRecompiler::SpirvTarget Target() const { auto target = device.Target(); target.gpuResolvedImages = HeapStages; @@ -1041,7 +1039,6 @@ constexpr std::array TransitionCases{{ int main(int argc, char** argv) { try { - // --heap-stages [--case ] builds both stages as heap stages. HeapStages = argc > 1 && std::string_view(argv[1]) == "--heap-stages"; const int first = HeapStages ? 2 : 1; const std::string mode = argc > first ? argv[first] : HeapStages ? "--heap-stages" : ""; @@ -1072,7 +1069,6 @@ int main(int argc, char** argv) { bool ran = false; for (const auto& entry : cases) { if (!only.empty() && only != entry.name) continue; - // Heap stages do not report BDA faults per use yet. if (HeapStages && std::string_view(entry.name) == "fault-per-use") continue; entry.run(scene); ran = true; From a6ecdf81e42586bac9536fa67edab9aa44c866ad Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 5 Nov 2026 16:51:54 +0530 Subject: [PATCH 117/269] perf(agc): push heap stages' root and shader data like vkd3d's root signature Descriptor-heap stages read their root (ring, pagetable, fault and GDS addresses, stencil reference, and each stage's data offset, SRT index, SRT size and table map) and their shader data (heap slot indices, image first elements, user data, memory offsets, image metadata) from push data, as vkd3d-proton maps a root signature and PS5 delivers user SGPRs. Like a root signature, a graphics pipeline gets one layout for all its stages: nothing is reserved; the driver packs only the root items its stages read and each stage's wanted shader-data dwords into the 64 push dwords (the pixel stage from the top, pre-rasterization stages from the bottom, the mesh, tessellation, depth-remap and compute words kept clear only when used, pushed data shared evenly when short) and passes the positions as specialization constants. A pixel stage that fits is placed as it is alone, so its fragment library stays shared. Shader data that does not fit stays in the ring. APS5_NO_HEAP_PUSHED_DATA reads all shader data from the ring. --- .../Execution/src/VulkanDevice.cpp | 15 +- .../Graphics/include/BindlessHeap.hpp | 7 +- .../Graphics/include/Pipeline.hpp | 2 + .../include/PipelineSpecialization.hpp | 12 ++ .../Graphics/include/ShaderResources.hpp | 3 +- .../Graphics/include/Shaders.hpp | 31 +++ .../Graphics/src/BindlessHeap.cpp | 25 +-- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 19 +- .../libSceAgcDriver/Graphics/src/Pipeline.cpp | 13 +- .../Graphics/src/ShaderResources.cpp | 83 +++++--- .../tests/PushDataPlacements.cpp | 154 ++++++++++++++ .../libSceAgcDriver/tests/ShaderDiskCache.cpp | 1 + ...gc_driver_push_data_placements_tests.cmake | 23 ++ .../tests/execution/HeapTableStageReuse.cpp | 7 +- core/shader/recompiler/CMakeLists.txt | 4 + .../IrMetadata/DescriptorBinding.hpp | 5 +- .../Optimization/src/BindingAllocator.cpp | 25 ++- .../recompiler/PipelineSpecialization.hpp | 7 + core/shader/recompiler/PushDataLayout.hpp | 201 ++++++++++++++++++ core/shader/recompiler/Recompiler.cpp | 11 +- core/shader/recompiler/Recompiler.hpp | 2 + core/shader/recompiler/RuntimeAbi.hpp | 27 +-- core/shader/recompiler/ShaderDiskCache.cpp | 22 +- .../include/SpirvBackend/SpirvEmitter.hpp | 1 + .../SpirvBackend/SpirvEmitterState.hpp | 1 + .../SpirvMemory/SpirvBufferAccess.hpp | 9 +- .../SpirvBackend/src/SpirvBdaFault.cpp | 4 +- .../SpirvBackend/src/SpirvBdaLookup.cpp | 2 +- .../SpirvBackend/src/SpirvEmitter.cpp | 1 + .../SpirvBackend/src/SpirvFlowEmitter.cpp | 16 +- .../SpirvBackend/src/SpirvImageEmitter.cpp | 2 +- .../src/SpirvMemory/SpirvBufferAccess.cpp | 65 ++++-- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 4 + .../SpirvBackend/src/SpirvModuleEmitter.cpp | 1 + docs/dev/ENVIRONMENT.md | 1 + 35 files changed, 679 insertions(+), 127 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_push_data_placements_tests.cmake create mode 100644 core/shader/recompiler/PushDataLayout.hpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index e08affb39ee0..dfaf2ee7e424 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -290,7 +290,7 @@ const char* ComputePipelineDumpDirectory() { return std::getenv("APS5_DUMP_COMPU static_assert(Graphics::ComputePushConstantBytes + sizeof(VkDeviceAddress) == ShaderRecompiler::GpuScratchPoolAddressPushByte && ShaderRecompiler::GpuScratchPoolAddressPushByte + sizeof(VkDeviceAddress) <= ShaderRecompiler::GpuScratchPoolDwordsPushByte && - ShaderRecompiler::GpuScratchPoolDwordsPushByte + sizeof(std::uint32_t) <= ShaderRecompiler::RuntimeAbi::RootDword * sizeof(std::uint32_t)); + (ShaderRecompiler::StagePushFeatures(ShaderRecompiler::ShaderStage::Compute, 0u) & ShaderRecompiler::PushBytesMask(Graphics::ComputePushConstantBytes, ShaderRecompiler::GpuScratchPoolDwordsPushByte + sizeof(std::uint32_t) - Graphics::ComputePushConstantBytes)) == ShaderRecompiler::PushBytesMask(Graphics::ComputePushConstantBytes, ShaderRecompiler::GpuScratchPoolDwordsPushByte + sizeof(std::uint32_t) - Graphics::ComputePushConstantBytes)); void CreateComputeHeapPipeline(VkDevice device, PFN_vkCreateComputePipelines create, VkPipelineCache cache, VkShaderModule module, VkPipelineCreateFlags flags, VkPipelineShaderStageCreateFlags stageFlags, const VkSpecializationInfo* specialization, std::uint32_t subgroupSize, std::span mappings, VkPipeline* pipeline, Graphics::PipelineCacheSynchronization* synchronization) { auto flags2 = Graphics::DescriptorHeapFlags(static_cast(flags)); @@ -423,6 +423,7 @@ struct ComputePipelineObjects { VkDescriptorSetLayout resourcesLayout = VK_NULL_HANDLE; std::mutex splitMutex; std::map, VkPipeline> splitPipelines; + std::vector pushPlacements; bool descriptorHeap = false; ~ComputePipelineObjects() { for (const auto& [base, split] : splitPipelines) destroyPipeline(device, split, nullptr); @@ -5833,7 +5834,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { const std::byte* pushed = record.pushBytes->data(); if (resources.HeapStage() || record.objects->descriptorHeap) { patchedBytes = *record.pushBytes; - resources.PatchDataAddresses(patchedBytes, std::span(record.shader, 1), record.bindings.get()); + resources.PatchDataAddresses(patchedBytes, std::span(record.shader, 1), record.objects->pushPlacements, record.bindings.get()); pushed = patchedBytes.data(); } if (record.objects->descriptorHeap) { @@ -5951,7 +5952,10 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons check(state->DeviceFunction("vkCreatePipelineLayout")(state->device, &layoutInfo, nullptr, &objects->layout), "vkCreatePipelineLayout"); } const VkPipelineCreateFlags pipelineFlags = computePipelineFlags(); - const Graphics::PipelineSpecialization specialization(shader); + const Graphics::CompiledShader placed{ShaderRecompiler::ShaderStage::Compute, &shader, 0u}; + objects->pushPlacements = Graphics::PushDataPlacements(std::span(&placed, 1)); + Graphics::PipelineSpecialization specialization(shader); + specialization.PlacePushData(objects->pushPlacements.front()); const auto subgroupSize = computeSubgroupSize(shader); const auto stageFlags = computeStageFlags(shader); if (const auto* directory = ComputePipelineDumpDirectory(); directory != nullptr && *directory != 0 && !state->probingFloatControls && ComputePipelineCapture::OptionalEnabled() && CaptureComputePipeline(shader.spirv.size())) { @@ -5987,7 +5991,7 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons const bool heapDevice = gpuMode && context.descriptorHeap && Graphics::DescriptorHeapEnabled(); const auto workgroupAddressOffset = workgroupAddress ? Graphics::ComputePushConstantBytes : ~0u; const std::span spirv(shader.spirv.data(), shader.spirv.size()); - objects->descriptorHeap = heapDevice && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(spirv, heapMappings, workgroupAddressOffset, shader.dataAddressPush, false, false, false, scratchPool); + objects->descriptorHeap = heapDevice && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(spirv, heapMappings, workgroupAddressOffset, shader.dataAddressPush, false, false, false, scratchPool, &objects->pushPlacements.front()); require(!gpuMode || objects->descriptorHeap, "a GPU-mode compute stage does not map onto VK_EXT_descriptor_heap"); const auto createPipelines = state->DeviceFunction("vkCreateComputePipelines"); if (objects->descriptorHeap) CreateComputeHeapPipeline(state->device, createPipelines, context.pipelineCache, objects->module, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, heapMappings, &objects->pipeline, context.pipelineCacheSynchronization); @@ -6010,7 +6014,8 @@ VkPipeline VulkanDevice::splitComputePipeline(const Graphics::Context& context, if (const auto found = objects.splitPipelines.find(base); found != objects.splitPipelines.end()) return found->second; std::array offsets{}; for (std::uint32_t component = 0; component < offsets.size(); ++component) offsets[component] = {ShaderRecompiler::PipelineSpecialization::WorkgroupOffsetBase + component, base[component]}; - const Graphics::PipelineSpecialization specialization(shader, offsets); + Graphics::PipelineSpecialization specialization(shader, offsets); + specialization.PlacePushData(objects.pushPlacements.front()); VkShaderModule module = Graphics::CreateShaderModule(state->DeviceFunction("vkCreateShaderModule"), state->device, state->graphicsPipelineLibrary, shader.spirv.data(), shader.spirv.size() * sizeof(std::uint32_t), "vkCreateShaderModule"); VkPipeline pipeline = VK_NULL_HANDLE; try { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 26b086312bbe..272a755e97f8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -14,6 +14,10 @@ #include #include +namespace ShaderRecompiler { +struct StagePushPlacement; +} + namespace AgcDriver::Graphics { class Buffer; @@ -41,7 +45,8 @@ class BindlessHeap { void BindDescriptorHeaps(VkCommandBuffer commands) const; bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset = ~0u, bool rootGds = false, bool rootFault = false, - bool pixelLds = false, bool meshWindow = false, bool scratchPool = false) const; + bool pixelLds = false, bool meshWindow = false, bool scratchPool = false, + const ShaderRecompiler::StagePushPlacement* placement = nullptr) const; void WritePixelLdsBuffer(VkDeviceAddress address, VkDeviceSize bytes); void WriteMeshWindowBuffer(VkDeviceAddress address, VkDeviceSize bytes); VkDeviceAddress RingAddress() const; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Pipeline.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Pipeline.hpp index 9a5b637fa647..0c42e343878f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Pipeline.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Pipeline.hpp @@ -64,6 +64,7 @@ class Pipeline { bool SampleLocationsEnabled() const { return sampleLocationsEnabled; } VkExtent2D HostSampleLocationGrid() const { return sampleLocationGrid; } void PushConstants(VkCommandBuffer commands, VkShaderStageFlags stages, std::span bytes) const; + std::span PushPlacements() const { return pushPlacements; } // Forgets the Vulkan objects without destroying them: for entries of a device that is already gone. void Abandon() noexcept; @@ -81,6 +82,7 @@ class Pipeline { void setLibraryState(VkCommandBuffer commands, const State& state) const; Context context; std::vector _modules; + std::vector pushPlacements; VkPipelineLayout layout = VK_NULL_HANDLE; VkRenderPass renderPass = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp index d7628355bbed..b8da76209be2 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp @@ -79,6 +79,18 @@ class PipelineSpecialization { [[nodiscard]] const VkSpecializationInfo* Info() const { return entries.empty() ? nullptr : &info; } + void PlacePushData(const ShaderRecompiler::StagePushPlacement& placement) { + namespace Ids = ShaderRecompiler::PipelineSpecialization; + for (auto& constant : values) { + if (constant.id == Ids::PushedDataBase) constant.value = placement.pushed.base; + if (constant.id == Ids::PushedDataCount) constant.value = placement.pushed.count; + if (constant.id >= Ids::RootItemPositionBase && constant.id < Ids::RootItemPositionBase + ShaderRecompiler::RuntimeAbi::RootItemCount) { + constant.value = placement.items[constant.id - Ids::RootItemPositionBase]; + Require(constant.value != ShaderRecompiler::RuntimeAbi::NoPushPosition, "a stage reads a root item its pipeline's push layout does not hold"); + } + } + } + private: void describe(std::span constants) { entries.reserve(constants.size()); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index c66824d32530..f16dc4f4b6cd 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -368,7 +368,8 @@ class ShaderResources { void PatchPushConstants(std::span bytes) const { for (const auto& [position, adjustment] : pushPatches) bytes[position] = static_cast(adjustment); } - void PatchDataAddresses(std::span bytes, std::span shaders, const DrawBindings* rewritten) const; + void PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const; + void writePushedData(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const; // Whether RefreshData would record anything for `shader` (the per-word compare; verification). bool DataWordsDiffer(const CompiledShader& shader) const; std::size_t BindingCount() const { return bindings.size(); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp index 6707ebd73113..eab75a0ccf7d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp @@ -4,6 +4,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include "IntermediateRepresentation/IrMetadata/ResourcePlan.hpp" #include "Recompiler.hpp" +#include "PushDataLayout.hpp" #include #include #include @@ -57,6 +58,36 @@ inline bool AnyHeapShader(std::span shaders) { return std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return HeapShader(shader); }); } +inline bool RootedPushData(std::span shaders) { + return std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->dataAddressPush; }); +} + +inline bool PushesGeneratedFaultAddress(const CompiledShader& shader, bool rooted) { + if (!rooted || shader.program == nullptr || shader.program->dataAddressPush || HeapShader(shader)) return false; + return std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer; }); +} + +inline std::vector PushDataPlacements(std::span shaders) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + std::vector stages(shaders.size()); + std::uint64_t occupied = 0; + const bool rooted = RootedPushData(shaders); + for (std::size_t index = 0; index < shaders.size(); ++index) { + const auto* program = shaders[index].program; + stages[index].part = ShaderRecompiler::PushPartOf(shaders[index].stage); + if (program == nullptr) continue; + occupied |= ShaderRecompiler::StagePushFeatures(shaders[index].stage, program->pushItems); + if (program->dataAddressPush) { + stages[index].items = program->pushItems & ShaderRecompiler::RootItemMask; + stages[index].pushedWanted = static_cast(program->pushedData.size()); + continue; + } + if (!program->pushConstants.empty()) occupied |= ShaderRecompiler::PushBytesMask(shaders[index].pushConstantOffset, static_cast(program->pushConstants.size())); + if (PushesGeneratedFaultAddress(shaders[index], rooted)) stages[index].items = Abi::RootItemBit(Abi::RootItem::FaultAddress); + } + return ShaderRecompiler::PlacePushData(stages, occupied); +} + inline const std::vector& DrawGuestWords(const ShaderRecompiler::RecompileResult& program, const ShaderRecompiler::HeapStageWords* heap, const ShaderRecompiler::DescriptorBinding& binding) { if (heap == nullptr || heap->bindings.empty()) return binding.guestDescriptor; const auto index = static_cast(&binding - program.bindings.data()); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 4d43fadf807a..7275e37fbae9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "PushDataLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" @@ -753,11 +754,12 @@ VkDescriptorSetAndBindingMappingEXT pushAddressMapping(std::uint32_t set, std::u return mapping; } -constexpr std::uint32_t rootAddressOffset(std::uint32_t rootField) { - return (Abi::RootDword + rootField) * sizeof(std::uint32_t); +std::uint32_t rootItemOffset(const ShaderRecompiler::StagePushPlacement* placement, Abi::RootItem item) { + Require(placement != nullptr && placement->Item(item) != Abi::NoPushPosition, "a heap mapping reads a root item its pipeline's push layout does not hold"); + return placement->Item(item) * static_cast(sizeof(std::uint32_t)); } -VkDescriptorSetAndBindingMappingEXT ringDescriptorMapping(std::uint32_t set, std::uint32_t binding, VkDeviceSize ringOffset) { +VkDescriptorSetAndBindingMappingEXT ringDescriptorMapping(std::uint32_t set, std::uint32_t binding, VkDeviceSize ringOffset, const ShaderRecompiler::StagePushPlacement* placement) { constexpr auto bindingCount = static_cast(Abi::Binding::Count); const bool buffers = binding % bindingCount == static_cast(Abi::Binding::Buffers); VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; @@ -767,14 +769,13 @@ VkDescriptorSetAndBindingMappingEXT ringDescriptorMapping(std::uint32_t set, std mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; mapping.sourceData.pushIndex.heapOffset = static_cast(ringOffset + (buffers ? BindlessHeap::BufferSlotBytes : 0u)); - mapping.sourceData.pushIndex.pushOffset = rootAddressOffset(Abi::RootStageDword(static_cast(binding / bindingCount), Abi::RootStageField::FlattenedSrt)); + mapping.sourceData.pushIndex.pushOffset = rootItemOffset(placement, Abi::RootItem::FlattenedSrt); mapping.sourceData.pushIndex.heapIndexStride = BindlessHeap::BufferSlotBytes; mapping.sourceData.pushIndex.heapArrayStride = BindlessHeap::BufferSlotBytes; return mapping; } -VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, VkDeviceSize heapOffset) { - constexpr auto bindingCount = static_cast(Abi::Binding::Count); +VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, VkDeviceSize heapOffset, const ShaderRecompiler::StagePushPlacement* placement) { VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; mapping.descriptorSet = Abi::GpuDataSet; mapping.firstBinding = binding; @@ -782,7 +783,7 @@ VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, Vk mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT; mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_RESOURCE_HEAP_DATA_EXT; mapping.sourceData.heapData.heapOffset = static_cast(heapOffset); - mapping.sourceData.heapData.pushOffset = rootAddressOffset(Abi::RootStageDword(static_cast(binding / bindingCount), Abi::RootStageField::ShaderData)); + mapping.sourceData.heapData.pushOffset = rootItemOffset(placement, Abi::RootItem::ShaderData); return mapping; } @@ -809,7 +810,7 @@ bool DescriptorHeapMappable(std::span spirv, bool workgroup bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset, bool rootGds, bool rootFault, bool pixelLds, bool meshWindow, - bool scratchPool) const { + bool scratchPool, const ShaderRecompiler::StagePushPlacement* placement) const { mappings.clear(); if (resourceHeap == nullptr) return false; HeapBindingUse use; @@ -831,17 +832,17 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, heapMapping(Abi::FragmentDescriptorSet, binding, VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT, 0, samplerHeapStride)); else mappings.push_back(heapMapping(Abi::FragmentDescriptorSet, binding, imageResources, 0, imageHeapStride)); } - for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, ringHeapOffset)); + for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, ringHeapOffset, placement)); std::sort(use.ringDescriptors.begin(), use.ringDescriptors.end()); - for (const auto& [set, binding] : use.ringDescriptors) mappings.push_back(ringDescriptorMapping(set, binding, ringHeapOffset)); + for (const auto& [set, binding] : use.ringDescriptors) mappings.push_back(ringDescriptorMapping(set, binding, ringHeapOffset, placement)); if (use.workgroupMemory) mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset)); if (use.scratchPoolMemory) mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuScratchPoolDescriptorSet, 0, ShaderRecompiler::GpuScratchPoolAddressPushByte)); if (use.gdsBinding != ~0u) - mappings.push_back(pushAddressMapping(Abi::GpuGdsSet, use.gdsBinding, rootAddressOffset(Abi::RootGdsAddress))); + mappings.push_back(pushAddressMapping(Abi::GpuGdsSet, use.gdsBinding, rootItemOffset(placement, Abi::RootItem::GdsAddress))); if (use.faultMemory) - mappings.push_back(pushAddressMapping(Abi::DescriptorSet, GeneratedFaultBinding, rootAddressOffset(Abi::RootFaultAddress))); + mappings.push_back(pushAddressMapping(Abi::DescriptorSet, GeneratedFaultBinding, rootItemOffset(placement, Abi::RootItem::FaultAddress))); if (use.pixelLdsMemory) mappings.push_back(heapMapping(ShaderRecompiler::PixelFunctionLdsDescriptorSet, 0, VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT, pixelLdsHeapOffset, 0)); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 5903dc36740e..d7d738979542 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -2498,8 +2498,11 @@ struct RecordedDraw { // A remapped viewport depth range reads its scale and offset from the draw's push block (the vertex shader's // RemapPositionDepth), so draws that differ only in them share one pipeline; the draw's own state supplies them. -void patchDepthRemapPush(std::array& block, const State& state) { +void patchDepthRemapPush(std::array& block, const State& state, std::span shaders) { if (state.depthRemap.mode == 0u) return; + const auto reads = [](const CompiledShader& shader) { return shader.program != nullptr && (shader.program->pushItems & ShaderRecompiler::RuntimeAbi::DepthRemapPushBit) != 0u; }; + const auto rooted = [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->dataAddressPush; }; + if (std::ranges::any_of(shaders, rooted) && !std::ranges::any_of(shaders, reads)) return; static_assert(ShaderRecompiler::DepthRemapPushOffsetBytes + ShaderRecompiler::DepthRemapPushBytes <= PipelinePushSlotBytes); const std::array words{state.depthRemap.scale, state.depthRemap.offset}; std::memcpy(block.data() + ShaderRecompiler::DepthRemapPushOffsetBytes, words.data(), sizeof(words)); @@ -2512,11 +2515,15 @@ void recordStencilReplay(const Context& context, VkCommandBuffer commands, const resources.PatchPushConstants(block); stages = PushConstantStages(shaders); } - patchDepthRemapPush(block, state); - resources.PatchDataAddresses(block, shaders, drawBindings); + patchDepthRemapPush(block, state, shaders); + Require(!replay.empty(), "stencil replay has no pipelines"); + const auto placements = replay.front().second->PushPlacements(); + resources.PatchDataAddresses(block, shaders, placements, drawBindings); const auto fragment = std::ranges::find_if(shaders, [](const CompiledShader& shader) { return shader.stage == ShaderRecompiler::ShaderStage::Fragment && !shader.program->stencilReferences.empty(); }); Require(fragment != shaders.end(), "stencil replay fragment stage is missing"); - const auto referenceOffset = (fragment->program->dataAddressPush ? 0u : fragment->pushConstantOffset) + fragment->program->stencilReferenceDword * sizeof(std::uint32_t); + const auto stencilItem = fragment->program->dataAddressPush ? placements[static_cast(fragment - shaders.begin())].Item(ShaderRecompiler::RuntimeAbi::RootItem::StencilReference) : 0u; + Require(stencilItem != ShaderRecompiler::RuntimeAbi::NoPushPosition, "stencil replay fragment stage has no stencil reference in its push layout"); + const auto referenceOffset = fragment->program->dataAddressPush ? stencilItem * sizeof(std::uint32_t) : fragment->pushConstantOffset + fragment->program->stencilReferenceDword * sizeof(std::uint32_t); Require(referenceOffset <= block.size() - sizeof(std::uint32_t), "stencil replay reference exceeds the push block"); const auto run = [&](const Pm4::DrawParameters& piece, std::optional firstIndex) { std::uint32_t unusedSubdraw = 0; @@ -2553,8 +2560,8 @@ void pushDrawConstants(const Pipeline& pipeline, VkCommandBuffer commands, const resources.PatchPushConstants(block); stages = PushConstantStages(shaders); } - patchDepthRemapPush(block, state); - resources.PatchDataAddresses(block, shaders, drawBindings); + patchDepthRemapPush(block, state, shaders); + resources.PatchDataAddresses(block, shaders, pipeline.PushPlacements(), drawBindings); if (state.stages.tessellation) { for (const auto& shader : shaders) Require(shader.program->pushConstants.empty() || shader.pushConstantOffset >= PipelinePushSlotBytes || shader.pushConstantOffset + shader.program->pushConstants.size() <= ShaderRecompiler::TessellationLevelPushOffsetBytes, "a stage's push constants overlap the tessellation levels"); const std::array levels{state.stages.minTessellationLevel, state.stages.maxTessellationLevel}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index 9564c62a6abd..fae2f795e77c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -334,7 +334,7 @@ void appendKey(std::vector& key, const TValue& value) { key.insert(key.end(), bytes.begin(), bytes.end()); } -bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& state, const VertexInputLayout& input, const PipelineSetLayouts& resources, std::span shaders) { +bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& state, const VertexInputLayout& input, const PipelineSetLayouts& resources, std::span shaders, std::span pushPlacements) { using Stage = ShaderRecompiler::ShaderStage; if (!context.graphicsPipelineLibrary || context.pipelineExecutableInfo || (state.stages.tessellation && !context.tessellationPipelineCache) || state.depthBiasPerFace || state.rectList || BarycentricPatches(state, shaders) || SplitsAlternateAlpha(state) || std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; }) || UsesMeshWindow(shaders) || FragmentInterlock(shaders)) return false; keys = {}; @@ -348,6 +348,7 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& appendKey(key, shader.pushConstantOffset); appendKey(key, state.meshLayerBase); appendKey(key, state.meshLayerCount); + appendKey(key, pushPlacements[static_cast(&shader - shaders.data())]); if (resources.split) { auto& sets = shader.stage == Stage::Fragment ? keys.fragmentSets : keys.preRasterizationSets; if (HeapShader(shader)) { @@ -467,7 +468,7 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& Pipeline::Pipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const ShaderResources& resources, std::span shaders, VkImageLayout attachmentLayout) : Pipeline(context, state, vertexInput, resources.SetLayouts(), shaders, attachmentLayout) {} -Pipeline::Pipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span shaders, VkImageLayout attachmentLayout) : context(context), _modules(shaders.size()), attachments(state.colors.size() + (state.depth ? 1u : 0u)), colorAttachments(state.colors.size()), depthBounds(state.depth.has_value() && state.depthBoundsTest), depthBias(state.depth.has_value() && state.depthBias), dynamicRendering(context.graphicsPipelineLibrary) { +Pipeline::Pipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span shaders, VkImageLayout attachmentLayout) : context(context), _modules(shaders.size()), pushPlacements(PushDataPlacements(shaders)), attachments(state.colors.size() + (state.depth ? 1u : 0u)), colorAttachments(state.colors.size()), depthBounds(state.depth.has_value() && state.depthBoundsTest), depthBias(state.depth.has_value() && state.depthBias), dynamicRendering(context.graphicsPipelineLibrary) { PerformanceTimer timing("Vulkan.GraphicsPipeline"); for (const auto& color : state.colors) boundAttachments.push_back(color.partialWriteMask == 0u); if (state.depth) boundAttachments.push_back(true); @@ -523,11 +524,10 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput std::vector heapMappingInfos(shaders.size(), VkShaderDescriptorSetAndBindingMappingInfoEXT{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}); if (context.descriptorHeap && DescriptorHeapEnabled() && AnyHeapShader(shaders)) { auto& heap = BindlessHeap::For(context); - const bool rooted = std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program->dataAddressPush; }); + const bool rooted = RootedPushData(shaders); descriptorHeap = std::all_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { const auto index = static_cast(&shader - shaders.data()); - const bool generatedFault = !HeapShader(shader) && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const auto& binding) { return binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer; }); - return heap.DescriptorHeapMappings(std::span(shader.program->spirv.data(), shader.program->spirv.size()), heapMappings[index], ~0u, shader.program->dataAddressPush, generatedFault && rooted, shader.program->functionLdsBuffer, shader.program->meshWindowBuffer); + return heap.DescriptorHeapMappings(std::span(shader.program->spirv.data(), shader.program->spirv.size()), heapMappings[index], ~0u, shader.program->dataAddressPush, PushesGeneratedFaultAddress(shader, rooted), shader.program->functionLdsBuffer, shader.program->meshWindowBuffer, false, &pushPlacements[index]); }); } Require(descriptorHeap || !AnyHeapShader(shaders), "a pipeline with GPU-mode stages does not map onto VK_EXT_descriptor_heap"); @@ -548,6 +548,7 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput stages[i].pNext = &heapMappingInfos[i]; } specializations.emplace_back(shader, state.meshLayerBase, state.meshLayerCount); + specializations.back().PlacePushData(pushPlacements[i]); stages[i].pSpecializationInfo = specializations.back().Info(); } if (std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && !shader.program->stencilReferences.empty(); })) { @@ -656,7 +657,7 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput viewports.viewportCount = 1; viewports.scissorCount = 1; PipelineLibraryKeys keys; - libraries = libraryKeys(keys, context, state, vertexInput, resources, shaders); + libraries = libraryKeys(keys, context, state, vertexInput, resources, shaders, pushPlacements); std::vector dynamicStates{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; if (state.stencilReplayReference) dynamicStates.push_back(VK_DYNAMIC_STATE_STENCIL_REFERENCE); if (depthBounds) dynamicStates.push_back(VK_DYNAMIC_STATE_DEPTH_BOUNDS); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 9ee5b29d66a0..517b0ead5216 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -5123,7 +5123,6 @@ void ShaderResources::forgetShaderDataWords(const CompiledShader& shader) { if (HeapShader(shader)) { auto& stageState = heapStages[HeapStageIndex(shader.stage)]; stageState.data.mark.entry = 0; - stageState.data.words.clear(); stageState.dataInput.clear(); } if (const auto allocation = shaderDataAllocation(shader)) { @@ -6731,7 +6730,7 @@ std::pair ShaderResources::shaderDataLocation(const Comp return {heap.RingBuffer(), heap.RingOffset() + offsets[DataOffsetIndex(HeapStageIndex(shader.stage), ShaderRecompiler::RuntimeAbi::Binding::ShaderData)]}; } -void ShaderResources::PatchDataAddresses(std::span bytes, std::span shaders, const DrawBindings* rewritten) const { +void ShaderResources::PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const { namespace Abi = ShaderRecompiler::RuntimeAbi; if (!heapStage) return; const auto& offsets = rewritten != nullptr && rewritten->addressOffsets ? rewritten->heapOffsets : heapOffsets; @@ -6757,41 +6756,65 @@ void ShaderResources::PatchDataAddresses(std::spanFault()); } - std::array root{}; - bool rooted = false; - for (const auto& shader : shaders) { - if (shader.program == nullptr || !shader.program->dataAddressPush) continue; - if (ring == 0) ring = BindlessHeap::For(context).RingAddress(); - const auto stage = HeapStageIndex(shader.stage); - const auto record = [&](Abi::RootStageField field) -> std::uint32_t& { return root[Abi::RootStageDword(static_cast(stage), field)]; }; - record(Abi::RootStageField::ShaderData) = offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]; - record(Abi::RootStageField::FlattenedSrt) = offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)]; - record(Abi::RootStageField::SrtDwords) = heapSrtDwords[stage]; - record(Abi::RootStageField::TableMap) = heapTableMapSet[stage] ? heapTableMaps[stage] : 0u; - rooted = true; - } - if (!rooted) return; - const auto split = [&](std::uint32_t at, VkDeviceAddress address) { - root[at] = static_cast(address); - root[at + 1u] = static_cast(address >> 32u); - }; - split(Abi::RootRingAddress, ring); - split(Abi::RootPagetableAddress, table); - split(Abi::RootFaultAddress, fault); - root[Abi::RootPagetableDwords] = tableDwords; - if (gdsAllocation != std::numeric_limits::max()) { + Require(placements.size() == shaders.size(), "the push layout does not describe the draw's stages"); + std::optional gds; + const auto gdsAddress = [&] { + if (gds) return *gds; + gds = VkDeviceAddress{0}; + if (gdsAllocation == std::numeric_limits::max()) return *gds; const auto* overrides = rewritten != nullptr && rewritten->addressOffsets ? &rewritten->addressOverrides : nullptr; auto adjustment = allocations[gdsAllocation].adjustment; const auto info = overrides != nullptr && (*overrides)[gdsAllocation].buffer != VK_NULL_HANDLE ? (*overrides)[gdsAllocation] : descriptor(allocations[gdsAllocation], adjustment); Require(info.buffer != VK_NULL_HANDLE, "the GDS buffer is missing"); const auto base = BufferDeviceAddress(context, info.buffer); Require(base != 0, "the GDS buffer has no device address"); - split(Abi::RootGdsAddress, base + info.offset); + gds = base + info.offset; + return *gds; + }; + bool rooted = false; + for (std::size_t index = 0; index < shaders.size(); ++index) { + const auto& shader = shaders[index]; + const auto& placement = placements[index]; + const auto put = [&](Abi::RootItem item, std::uint32_t word, std::uint32_t value) { + const auto position = placement.Item(item); + if (position == Abi::NoPushPosition) return; + Require((position + word + 1u) * sizeof(std::uint32_t) <= bytes.size(), "a root item lies outside the push data"); + std::memcpy(bytes.data() + (position + word) * sizeof(std::uint32_t), &value, sizeof(value)); + }; + const auto putAddress = [&](Abi::RootItem item, VkDeviceAddress address) { + put(item, 0u, static_cast(address)); + put(item, 1u, static_cast(address >> 32u)); + }; + if (placement.Item(Abi::RootItem::RingAddress) != Abi::NoPushPosition) { + if (ring == 0) ring = BindlessHeap::For(context).RingAddress(); + putAddress(Abi::RootItem::RingAddress, ring); + } + putAddress(Abi::RootItem::PagetableAddress, table); + putAddress(Abi::RootItem::FaultAddress, fault); + put(Abi::RootItem::PagetableDwords, 0u, tableDwords); + if (placement.Item(Abi::RootItem::GdsAddress) != Abi::NoPushPosition) putAddress(Abi::RootItem::GdsAddress, gdsAddress()); + if (shader.program == nullptr || !shader.program->dataAddressPush) continue; + const auto stage = HeapStageIndex(shader.stage); + put(Abi::RootItem::ShaderData, 0u, offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); + put(Abi::RootItem::FlattenedSrt, 0u, offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)]); + put(Abi::RootItem::SrtDwords, 0u, heapSrtDwords[stage]); + put(Abi::RootItem::TableMap, 0u, heapTableMapSet[stage] ? heapTableMaps[stage] : 0u); + writePushedData(bytes, shader, placement.pushed); + rooted = true; + } + if (rooted) NoteDataAddressPush(); +} + +void ShaderResources::writePushedData(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const { + const auto& program = *shader.program; + if (placement.count == 0u) return; + const auto& words = heapStages[HeapStageIndex(shader.stage)].data.words; + Require(placement.count <= program.pushedData.size() && (placement.base + placement.count) * sizeof(std::uint32_t) <= bytes.size(), "a stage's pushed shader data does not fit"); + for (std::uint32_t index = 0; index < placement.count; ++index) { + const auto dword = program.pushedData[index]; + Require(dword < words.size(), "a pushed shader-data dword lies outside the stage's shader data"); + std::memcpy(bytes.data() + (placement.base + index) * sizeof(std::uint32_t), &words[dword], sizeof(std::uint32_t)); } - std::memcpy(&root[Abi::RootStencilReference], bytes.data() + (Abi::RootDword + Abi::RootStencilReference) * sizeof(std::uint32_t), sizeof(std::uint32_t)); - static_assert((Abi::RootDword + Abi::RootDwords) * sizeof(std::uint32_t) <= PipelinePushConstantBytes); - std::memcpy(bytes.data() + Abi::RootDword * sizeof(std::uint32_t), root.data(), sizeof(root)); - NoteDataAddressPush(); } VkImageView ShaderResources::heapPlaceholderView(std::uint32_t kind) const { diff --git a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp new file mode 100644 index 000000000000..838152b08fd3 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp @@ -0,0 +1,154 @@ +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" +#include "PushDataLayout.hpp" +#include "RuntimeAbi.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::CompiledShader; +using AgcDriver::Graphics::PushDataPlacements; +using ShaderRecompiler::ShaderStage; +using ShaderRecompiler::StagePushPlacement; +namespace Abi = ShaderRecompiler::RuntimeAbi; +using Item = Abi::RootItem; + +void require(bool condition, const std::string& what) { + if (!condition) throw std::runtime_error(what); +} + +struct Stage { + ShaderStage stage; + std::uint32_t items; + std::size_t pushed; +}; + +std::uint32_t bits(std::initializer_list items) { + std::uint32_t mask = 0; + for (const auto item : items) mask |= Abi::RootItemBit(item); + return mask; +} + +std::vector place(const std::vector& stages) { + static std::vector programs; + programs.assign(stages.size(), {}); + std::vector shaders; + for (std::size_t index = 0; index < stages.size(); ++index) { + programs[index].dataAddressPush = true; + programs[index].gpuResolvedImages = true; + programs[index].pushItems = stages[index].items; + programs[index].pushedData.resize(stages[index].pushed); + for (std::size_t dword = 0; dword < stages[index].pushed; ++dword) programs[index].pushedData[dword] = static_cast(dword); + shaders.push_back({stages[index].stage, &programs[index], 0u}); + } + return PushDataPlacements(shaders); +} + +void disjoint(const std::vector& stages, const std::vector& placements, std::uint64_t occupied, const char* what) { + std::uint64_t used = occupied; + std::uint64_t globals = 0; + for (std::size_t index = 0; index < placements.size(); ++index) { + const auto claim = [&](std::uint32_t first, std::uint32_t width, bool shared) { + for (auto dword = first; dword < first + width; ++dword) { + require(dword < Abi::PushDataDwords, std::string("a push entry leaves the push data: ") + what); + const auto bit = 1ull << dword; + if (shared && (globals & bit) != 0u) continue; + require((used & bit) == 0u, std::string("two push entries share a dword: ") + what); + used |= bit; + if (shared) globals |= bit; + } + }; + for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { + const bool wanted = (stages[index].items & (1u << item)) != 0u; + const auto position = placements[index].items[item]; + require(wanted == (position != Abi::NoPushPosition), std::string("a stage's root items and its placement disagree: ") + what); + if (!wanted) continue; + const auto kind = static_cast(item); + if (Abi::RootAddressItem(kind)) require(position % 2u == 0u, std::string("a root address is not 8-byte aligned: ") + what); + claim(position, Abi::RootAddressItem(kind) ? 2u : 1u, static_cast(kind) < static_cast(Abi::RootItem::ShaderData)); + } + claim(placements[index].pushed.base, placements[index].pushed.count, false); + require(placements[index].pushed.count <= stages[index].pushed, std::string("a stage pushes more than it asked for: ") + what); + } +} + +} + +int main() { + try { + const auto vertexItems = bits({Item::RingAddress, Item::ShaderData, Item::FlattenedSrt}); + const auto pixelItems = bits({Item::RingAddress, Item::ShaderData, Item::TableMap}); + { + const std::vector stages{{ShaderStage::Vertex, vertexItems, 6}, {ShaderStage::Fragment, pixelItems, 30}}; + const auto placements = place(stages); + disjoint(stages, placements, 0, "vertex and pixel"); + require(placements[0].pushed.count == 6 && placements[1].pushed.count == 30, "stages that fit push everything they want"); + require(place({stages[1]})[0] == placements[1], "a pixel stage that fits is placed as it is alone, so its fragment library is shared"); + require(placements[0].Item(Item::RingAddress) != placements[1].Item(Item::RingAddress), "the pre-rasterization and fragment parts hold their own globals"); + } + { + const std::vector stages{{ShaderStage::Vertex, vertexItems, 40}, {ShaderStage::Fragment, pixelItems, 40}}; + const auto placements = place(stages); + disjoint(stages, placements, 0, "stages that want too much"); + require(placements[0].pushed.count == 28 && placements[1].pushed.count == 28, "stages that want too much share the room evenly"); + } + { + const std::vector stages{{ShaderStage::Local, vertexItems, 4}, {ShaderStage::TessellationControl, bits({Item::RingAddress, Item::ShaderData}), 3}, {ShaderStage::TessellationEvaluation, vertexItems, 10}, {ShaderStage::Fragment, pixelItems, 48}}; + const auto placements = place(stages); + disjoint(stages, placements, ShaderRecompiler::PushFeatureDwords(false, true, false), "a tessellation pipeline"); + require(placements[0].Item(Item::RingAddress) == placements[1].Item(Item::RingAddress), "pre-rasterization stages share their part's globals"); + } + { + const std::vector stages{{ShaderStage::Mesh, vertexItems, 8}, {ShaderStage::Fragment, pixelItems, 20}}; + disjoint(stages, place(stages), ShaderRecompiler::PushFeatureDwords(true, false, false), "a mesh pipeline"); + } + { + const std::vector stages{{ShaderStage::Compute, bits({Item::RingAddress, Item::GdsAddress, Item::ShaderData}), 60}}; + const auto placements = place(stages); + disjoint(stages, placements, ShaderRecompiler::StagePushFeatures(ShaderStage::Compute, 0u), "a compute stage"); + require(placements[0] == ShaderRecompiler::StandalonePushPlacement(ShaderStage::Compute, stages[0].items, stages[0].pushed), "the compiler's standalone compute placement is the driver's"); + } + { + std::vector programs(2); + programs[0].dataAddressPush = true; + programs[0].gpuResolvedImages = true; + programs[0].pushItems = vertexItems; + programs[0].pushedData.resize(48); + programs[1].pushConstants.resize(12); + programs[1].stencilReferences.push_back(1u); + programs[1].stencilReferenceDword = 2u; + const std::array shaders{CompiledShader{ShaderStage::Vertex, &programs[0], 0u}, CompiledShader{ShaderStage::Fragment, &programs[1], 128u}}; + const auto placements = PushDataPlacements(shaders); + const auto stencil = 128u / 4u + programs[1].stencilReferenceDword; + const auto pushed = placements[0].pushed; + require(stencil < pushed.base || stencil >= pushed.base + pushed.count, "a pushed run covers a per-draw stage's stencil reference"); + } + { + std::vector programs(3); + for (const std::size_t index : {0u, 2u}) { + programs[index].dataAddressPush = true; + programs[index].gpuResolvedImages = true; + } + programs[0].pushItems = vertexItems; + programs[0].pushedData.resize(6); + programs[1].pushConstants.resize(8); + programs[2].pushItems = pixelItems; + programs[2].pushedData.resize(20); + const std::array shaders{CompiledShader{ShaderStage::Vertex, &programs[0], 0u}, CompiledShader{ShaderStage::TessellationControl, &programs[1], 200u}, CompiledShader{ShaderStage::Fragment, &programs[2], 0u}}; + const auto placements = PushDataPlacements(shaders); + const std::vector stages{{ShaderStage::Vertex, vertexItems, 6}, {ShaderStage::TessellationControl, 0u, 0}, {ShaderStage::Fragment, pixelItems, 20}}; + disjoint(stages, placements, ShaderRecompiler::PushBytesMask(200u, 8u) | ShaderRecompiler::PushFeatureDwords(false, true, false), "a pixel stage wider than the top free run"); + require(placements[2].pushed.count == 20, "a pixel stage wider than the top free run takes a lower run instead of being cut"); + } + std::puts("push data placements passed"); + return 0; + } catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp index cae1e73c7378..7ed6868be81f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp @@ -400,6 +400,7 @@ CompiledVariant sampleVariant() { info.bindings.memoryOffsetDword = 1; info.bindings.memoryOffsetCount = 5; info.bindings.stencilReferenceDword = 23u; + info.bindings.dataAddress = true; info.bindings.userDataRegisters = {4, 5, 9}; info.bindings.descriptors = {{DescriptorBindingKind::Buffers, {0, 1}}, {DescriptorBindingKind::FlattenedSrt, {}}}; variant.bindings.layout = info.bindings; diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_push_data_placements_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_push_data_placements_tests.cmake new file mode 100644 index 000000000000..d21b0671b563 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_push_data_placements_tests.cmake @@ -0,0 +1,23 @@ +add_test_executable(agc_driver_push_data_placements_tests EXCLUDE_FROM_ALL + tests/PushDataPlacements.cpp +) + +target_include_directories(agc_driver_push_data_placements_tests PRIVATE + ${LIBS_INCLUDE_DIR} + ${CMAKE_SOURCE_DIR}/core/shader/recompiler + ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} + ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR} +) + +target_link_libraries(agc_driver_push_data_placements_tests PRIVATE + libSceAgcDriver + SDL2-static + libc +) + +set_target_properties(agc_driver_push_data_placements_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_driver_push_data_placements_tests) + +if(BUILD_TESTING) + agc_add_default_test(agc_driver_push_data_placements_tests) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp index e4f7b17703ef..a720df4970c1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp @@ -156,9 +156,12 @@ void RequireHeapTable(const ShaderRecompiler::RecompileResult& result) { std::uint32_t TableMapRoot(const ShaderResources& resources, const CompiledShader& shader) { namespace Abi = ShaderRecompiler::RuntimeAbi; std::array bytes{}; - resources.PatchDataAddresses(bytes, std::span(&shader, 1), nullptr); + const auto placements = AgcDriver::Graphics::PushDataPlacements(std::span(&shader, 1)); + resources.PatchDataAddresses(bytes, std::span(&shader, 1), placements, nullptr); std::uint32_t value = 0; - std::memcpy(&value, bytes.data() + (Abi::RootDword + Abi::RootStageDword(Abi::Stage::Main, Abi::RootStageField::TableMap)) * sizeof(std::uint32_t), sizeof(value)); + const auto position = placements.front().Item(Abi::RootItem::TableMap); + Require(position != Abi::NoPushPosition, "heap table stage reuse: the stage's push layout holds no table map"); + std::memcpy(&value, bytes.data() + position * sizeof(std::uint32_t), sizeof(value)); return value; } diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index 60d5595790ac..d4d719163fc2 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -244,6 +244,7 @@ function(add_shader_recompiler target runtimeTarget) BdaAbi::RangesOrdered RuntimeAbi::GpuHeapStorageKind RuntimeAbi::StageGroup + StagePushFeatures RuntimeAbi::UintStorageImageKind StorageElementPointer FirstAtomicStorageImageBinding @@ -273,6 +274,9 @@ function(add_shader_recompiler target runtimeTarget) PipelineSpecialization::WorkgroupOffsetWords PixelInput PixelInputBit + PlacePushData + PushBytesMask + PushPartOf RayTracingStrict RayTracingMiss ReadWholeFile diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp index 0911b62c97f7..40215a9ce071 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp @@ -39,7 +39,7 @@ struct IrDescriptorBinding { struct IrBindingLayout { std::uint32_t pushDataStartDword = PushData::NoStart; - std::uint32_t dataAddressDword = PushData::NoStart; + bool dataAddress = false; std::uint32_t stencilReferenceDword = PushData::NoStart; std::uint32_t memoryOffsetDword = 0; std::uint32_t memoryOffsetCount = 0; @@ -49,6 +49,7 @@ struct IrBindingLayout { std::uint32_t samplerSlotDwords = 0; std::uint32_t imageSlotDwords = 0; std::uint32_t bufferAddressDwords = 0; + std::vector pushedData; bool gpuResolvedImages = false; bool heapStorageImages = false; std::vector userDataRegisters; @@ -86,7 +87,7 @@ struct IrBindingLayout { return pushDataStartDword != PushData::NoStart; } [[nodiscard]] bool UsesDataAddress() const { - return dataAddressDword != PushData::NoStart; + return dataAddress; } [[nodiscard]] std::uint32_t PushSlotDword() const { return UsesPushData() ? pushDataStartDword / PushData::DwordCount * PushData::DwordCount : 0u; diff --git a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp index 7222b420070c..42da8b0e968c 100644 --- a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp +++ b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp @@ -2,6 +2,7 @@ #include "Optimization/ResourceMaterializer.hpp" #include #include +#include #include #include #include @@ -13,6 +14,23 @@ namespace { throw std::runtime_error(message); } +bool PushHeapData() { + static const bool enabled = std::getenv("APS5_NO_HEAP_PUSHED_DATA") == nullptr; + return enabled; +} + +void placePushedData(IrBindingLayout& layout) { + const auto capacity = RuntimeAbi::PushedDataWantedLimit; + const auto take = [&](std::uint32_t dword) { + if (layout.pushedData.size() < capacity && std::ranges::find(layout.pushedData, dword) == layout.pushedData.end()) layout.pushedData.push_back(dword); + }; + for (auto dword = layout.SamplerSlotDword(); dword < layout.BufferAddressDword(); ++dword) take(dword); + for (std::uint32_t image = 0; image < layout.runtimeImageCount; ++image) take(layout.ImageFirstElementDword(image)); + for (std::uint32_t dword = 0; dword < layout.userDataRegisters.size(); ++dword) take(dword); + for (auto dword = layout.memoryOffsetDword; dword < layout.memoryOffsetDword + (layout.memoryOffsetCount + 3u) / 4u; ++dword) take(dword); + for (auto dword = layout.ImageMetadataDword(); dword < layout.SamplerSlotDword(); ++dword) take(dword); +} + std::vector collectUserData(const IrProgram& program) { std::array registers {}; for (const auto& block : program.Blocks()) { @@ -120,10 +138,8 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin } const auto pushSize = layout.pushConstantSizeBytes / 4u; next.pushDataStartDword = !gpuResolvedImages && next.runtimeImageCount == 0u && next.ShaderDataDwords() != 0u && next.ShaderDataDwords() <= pushSize ? layout.pushConstantOffsetBytes / 4u : PushData::NoStart; - if (descriptorMemory && gpuResolvedImages) next.dataAddressDword = RuntimeAbi::RootDword; - if (stencilReplay && next.UsesDataAddress()) { - next.stencilReferenceDword = RuntimeAbi::RootDword + RuntimeAbi::RootStencilReference; - } else if (stencilReplay) { + next.dataAddress = descriptorMemory && gpuResolvedImages; + if (stencilReplay && !next.UsesDataAddress()) { const auto offset = next.UsesPushData() ? next.ShaderDataDwords() : 0u; if (offset >= pushSize) fail("stencil replay requires an unused push constant dword"); next.stencilReferenceDword = offset; @@ -168,6 +184,7 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin } } if (descriptorMemory && gpuResolvedImages) next.bufferAddressDwords = static_cast(info.buffers.size()) * RuntimeAbi::BufferAddressWords; + if (next.UsesDataAddress() && PushHeapData()) placePushedData(next); std::vector samplers; for (std::uint32_t i = 0; i < info.samplers.size(); i++) { diff --git a/core/shader/recompiler/PipelineSpecialization.hpp b/core/shader/recompiler/PipelineSpecialization.hpp index 57143c36d535..d00c84c49cd6 100644 --- a/core/shader/recompiler/PipelineSpecialization.hpp +++ b/core/shader/recompiler/PipelineSpecialization.hpp @@ -39,6 +39,9 @@ inline constexpr std::uint32_t DepthRemapBase = 8240u; inline constexpr std::uint32_t DepthRemapWords = 1u; inline constexpr std::uint32_t WorkgroupOffsetBase = 8241u; inline constexpr std::uint32_t WorkgroupOffsetWords = 3u; +inline constexpr std::uint32_t PushedDataBase = 8244u; +inline constexpr std::uint32_t PushedDataCount = 8245u; +inline constexpr std::uint32_t RootItemPositionBase = 8246u; inline constexpr std::uint32_t HeapCountBase = 8256u; inline constexpr std::uint32_t MipCountBase = 8320u; inline constexpr std::uint32_t StoreQuantizeBase = 12288u; @@ -56,6 +59,10 @@ inline constexpr std::uint32_t DescriptorIndex(std::uint32_t binding, std::uint3 return DescriptorIndexBase + binding * DescriptorIndexStride + element; } +inline constexpr bool IsPushPlacement(std::uint32_t id) { + return id == PushedDataBase || id == PushedDataCount || (id >= RootItemPositionBase && id < HeapCountBase); +} + inline constexpr bool IsWorkgroupOffset(std::uint32_t id) { return id >= WorkgroupOffsetBase && id < WorkgroupOffsetBase + WorkgroupOffsetWords; } diff --git a/core/shader/recompiler/PushDataLayout.hpp b/core/shader/recompiler/PushDataLayout.hpp new file mode 100644 index 000000000000..0bccc9015eee --- /dev/null +++ b/core/shader/recompiler/PushDataLayout.hpp @@ -0,0 +1,201 @@ +#ifndef CORE_SHADER_RECOMPILER_PUSHDATALAYOUT_HPP +#define CORE_SHADER_RECOMPILER_PUSHDATALAYOUT_HPP + +#include "PipelineSpecialization.hpp" +#include "Recompiler.hpp" +#include "RuntimeAbi.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace ShaderRecompiler { + +enum class PushPart : std::uint32_t { PreRasterization, Fragment, Compute }; + +inline PushPart PushPartOf(ShaderStage stage) { + if (stage == ShaderStage::Fragment) return PushPart::Fragment; + return stage == ShaderStage::Compute ? PushPart::Compute : PushPart::PreRasterization; +} + +struct PushStage { + PushPart part = PushPart::PreRasterization; + std::uint32_t items = 0; + std::uint32_t pushedWanted = 0; +}; + +struct StagePushPlacement { + std::array items{}; + RuntimeAbi::PushedPlacement pushed; + + [[nodiscard]] std::uint32_t Item(RuntimeAbi::RootItem item) const { return items[static_cast(item)]; } + bool operator==(const StagePushPlacement&) const = default; +}; + +constexpr std::uint64_t PushBytesMask(std::uint32_t offset, std::uint32_t bytes) { + std::uint64_t mask = 0; + for (auto dword = offset / 4u; dword < (offset + bytes + 3u) / 4u && dword < RuntimeAbi::PushDataDwords; ++dword) mask |= 1ull << dword; + return mask; +} + +constexpr std::uint64_t PushFeatureDwords(bool meshDraw, bool tessellationLevels, bool depthRemap) { + std::uint64_t mask = 0; + if (meshDraw) mask |= PushBytesMask(MeshDrawPushOffsetBytes, MeshDrawPushBytes); + if (tessellationLevels) mask |= PushBytesMask(TessellationLevelPushOffsetBytes, TessellationLevelPushBytes); + if (depthRemap) mask |= PushBytesMask(DepthRemapPushOffsetBytes, DepthRemapPushBytes); + return mask; +} + +inline constexpr std::uint32_t RootItemMask = (1u << RuntimeAbi::RootItemCount) - 1u; + +constexpr std::uint64_t StagePushFeatures(ShaderStage stage, std::uint32_t pushItems) { + const bool depthRemap = (pushItems & RuntimeAbi::DepthRemapPushBit) != 0u; + std::uint64_t mask = PushFeatureDwords(stage == ShaderStage::Mesh || stage == ShaderStage::Geometry, stage == ShaderStage::TessellationControl || stage == ShaderStage::TessellationEvaluation, depthRemap); + if (stage == ShaderStage::Compute) mask |= PushBytesMask(GpuScratchPoolAddressPushByte - 8u, GpuScratchPoolDwordsPushByte + 4u - (GpuScratchPoolAddressPushByte - 8u)); + return mask; +} + +inline std::vector PlacePushData(std::span stages, std::uint64_t occupied) { + namespace Abi = RuntimeAbi; + constexpr std::uint32_t total = Abi::PushDataDwords; + std::vector placements(stages.size()); + for (auto& placement : placements) placement.items.fill(Abi::NoPushPosition); + auto used = occupied; + const auto isFree = [&](std::uint32_t first, std::uint32_t width) { + for (auto dword = first; dword < first + width; ++dword) { + if (dword >= total || (used >> dword & 1ull) != 0u) return false; + } + return true; + }; + const auto take = [&](std::uint32_t width, bool aligned, bool top) { + for (std::uint32_t step = 0; step + width <= total; ++step) { + const auto first = top ? total - width - step : step; + if ((aligned && first % 2u != 0u) || !isFree(first, width)) continue; + for (auto dword = first; dword < first + width; ++dword) used |= 1ull << dword; + return first; + } + throw std::runtime_error("the push data has no room for a pipeline's root"); + }; + const auto placeRoot = [&](std::uint32_t items, bool top, std::array& positions) { + for (const bool addresses : {true, false}) { + for (std::uint32_t index = 0; index < Abi::RootItemCount; ++index) { + const auto item = static_cast(index); + if ((items & Abi::RootItemBit(item)) == 0u || Abi::RootAddressItem(item) != addresses) continue; + positions[index] = take(addresses ? 2u : 1u, addresses, top); + } + } + }; + constexpr auto globalItems = Abi::RootItemBit(Abi::RootItem::ShaderData) - 1u; + for (const auto part : {PushPart::Fragment, PushPart::Compute, PushPart::PreRasterization}) { + const bool top = part != PushPart::PreRasterization; + std::uint32_t globals = 0; + for (const auto& stage : stages) { + if (stage.part == part) globals |= stage.items & globalItems; + } + std::array shared{}; + shared.fill(Abi::NoPushPosition); + placeRoot(globals, top, shared); + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part != part) continue; + for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { + if ((stages[index].items & globalItems & (1u << item)) != 0u) placements[index].items[item] = shared[item]; + } + placeRoot(stages[index].items & ~globalItems, top, placements[index].items); + } + } + std::vector> runs; + for (std::uint32_t dword = 0; dword < total;) { + if ((used >> dword & 1ull) != 0u) { + ++dword; + continue; + } + auto end = dword; + while (end < total && (used >> end & 1ull) == 0u) ++end; + runs.emplace_back(dword, end); + dword = end; + } + std::uint32_t room = 0; + std::uint32_t largest = 0; + for (const auto& [first, end] : runs) { + room += end - first; + largest = std::max(largest, end - first); + } + std::vector wanted(stages.size(), 0u); + std::uint32_t sum = 0; + for (std::size_t index = 0; index < stages.size(); ++index) { + wanted[index] = std::min({stages[index].pushedWanted, Abi::PushedDataWantedLimit, largest}); + sum += wanted[index]; + } + auto counts = wanted; + if (sum > room) { + const auto sharedAt = [&](std::uint32_t level) { + std::uint32_t shared = 0; + for (const auto want : wanted) shared += std::min(want, level); + return shared; + }; + std::uint32_t level = 0; + while (sharedAt(level + 1u) <= room) ++level; + auto left = room - sharedAt(level); + for (std::size_t index = 0; index < counts.size(); ++index) { + counts[index] = std::min(wanted[index], level); + if (left != 0u && wanted[index] > level) { + ++counts[index]; + --left; + } + } + } + const auto claim = [&](std::size_t index, bool top) { + auto count = counts[index]; + if (count == 0u) return; + auto chosen = runs.end(); + if (top) { + for (auto run = runs.rbegin(); run != runs.rend(); ++run) { + if (run->second - run->first >= count) { + chosen = std::prev(run.base()); + break; + } + } + } else { + chosen = std::find_if(runs.begin(), runs.end(), [&](const auto& run) { return run.second - run.first >= count; }); + } + if (chosen == runs.end()) { + chosen = std::max_element(runs.begin(), runs.end(), [](const auto& left, const auto& right) { return left.second - left.first < right.second - right.first; }); + if (chosen == runs.end()) return; + count = chosen->second - chosen->first; + } + if (top) { + placements[index].pushed = {chosen->second - count, count}; + chosen->second -= count; + } else { + placements[index].pushed = {chosen->first, count}; + chosen->first += count; + } + }; + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part == PushPart::Fragment) claim(index, true); + } + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part != PushPart::Fragment) claim(index, false); + } + return placements; +} + +inline StagePushPlacement StandalonePushPlacement(ShaderStage stage, std::uint32_t pushItems, std::size_t pushedWanted) { + const PushStage pushStage{PushPartOf(stage), pushItems & RootItemMask, static_cast(pushedWanted)}; + return PlacePushData(std::span(&pushStage, 1), StagePushFeatures(stage, pushItems)).front(); +} + +inline void AppendPushSpecialization(std::vector& constants, const StagePushPlacement& placement) { + for (std::uint32_t item = 0; item < RuntimeAbi::RootItemCount; ++item) { + if (placement.items[item] != RuntimeAbi::NoPushPosition) constants.push_back({PipelineSpecialization::RootItemPositionBase + item, placement.items[item]}); + } + constants.push_back({PipelineSpecialization::PushedDataBase, placement.pushed.base}); + constants.push_back({PipelineSpecialization::PushedDataCount, placement.pushed.count}); +} + +} + +#endif diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 1118c5ec5863..080a294c9d08 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -1,5 +1,6 @@ #include "prx/libc/include/HostThreadLocal.hpp" #include "Recompiler.hpp" +#include "PushDataLayout.hpp" #include "HeapTemplateBudget.hpp" #include "RdnaDecoder/DiagnosticSink.hpp" #include "StencilReplay.hpp" @@ -828,7 +829,9 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) result.bufferAddressDword = bindings.layout.bufferAddressDwords != 0u ? bindings.layout.BufferAddressDword() : 0u; result.bufferAddressCount = bindings.layout.bufferAddressDwords / RuntimeAbi::BufferAddressWords; result.dataAddressPush = bindings.layout.UsesDataAddress(); + result.pushedData = bindings.layout.pushedData; result.bdaStores = emitted.bdaStores; + result.pushItems = emitted.pushItems; result.bdaAbiVersion = program.Info().usesDma || program.Info().usesFaultBuffer ? request.target.bdaAbiVersion : 0u; result.windowLaneGuards = 0; @@ -950,7 +953,7 @@ std::vector specializeWords(const CompiledShaderArtifact& artifac } const auto found = supplied.find(words[cursor + 3u]); if (found == supplied.end()) throw std::runtime_error("missing prepared specialization value"); - if (found->first == PipelineSpecialization::MeshLayerBase || found->first == PipelineSpecialization::MeshLayerCount) { + if (found->first == PipelineSpecialization::MeshLayerBase || found->first == PipelineSpecialization::MeshLayerCount || PipelineSpecialization::IsPushPlacement(found->first)) { retained.insert(words[cursor + 1u]); cursor += count; continue; @@ -1287,6 +1290,8 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil .samplerSlotDword = artifact.samplerSlotDword, .bufferAddressDword = artifact.bufferAddressDword, .bufferAddressCount = artifact.bufferAddressCount, + .pushedData = artifact.pushedData, + .pushItems = artifact.pushItems, .dataAddressPush = artifact.dataAddressPush, .bdaStores = artifact.bdaStores, .bdaAbiVersion = artifact.bdaAbiVersion, @@ -1390,6 +1395,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil auto constants = plan->bindings.specialization; constants.push_back({PipelineSpecialization::MeshLayerBase, 0u}); constants.push_back({PipelineSpecialization::MeshLayerCount, 0xffffffffu}); + if (artifact.dataAddressPush) AppendPushSpecialization(constants, StandalonePushPlacement(request.shader.stage, artifact.pushItems, artifact.pushedData.size())); std::size_t index = 0; if (variant.bindings.layout.UsesPushData()) constants.push_back({PipelineSpecialization::PushDataOffset, moduleKey[index++]}); if (StencilInPush(artifact, variant.bindings.layout)) constants.push_back({PipelineSpecialization::StencilReferenceOffset, moduleKey[index++]}); @@ -1466,6 +1472,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil if (std::ranges::none_of(result.bindings, [](const DescriptorBinding& binding) { return binding.role == DescriptorRole::BdaPagetable || binding.role == DescriptorRole::FaultBuffer; })) result.bdaAbiVersion = 0u; result.pushConstants = std::move(bindings.pushConstants); result.readsDepthRemapPush = depthRemap; + if ((result.pushItems & RuntimeAbi::DepthRemapPushBit) != 0u && !depthRemap) throw std::runtime_error("a stage reads the depth remap push words its request does not remap"); if (request.shader.stage == ShaderStage::Compute) { for (std::uint32_t component = 0; component < PipelineSpecialization::WorkgroupOffsetWords; ++component) result.specialization.push_back({PipelineSpecialization::WorkgroupOffsetBase + component, 0u}); } @@ -2323,7 +2330,7 @@ bool MatchesPreparedShader(const RecompileRequest& request, const SourceHandle& const bool usesPush = !prepared.gpuResolvedImages && prepared.runtimeImageCount == 0u && words != 0u && words <= layout.pushConstantSizeBytes / 4u; if (prepared.UsesPushData() != usesPush) return false; if (!handle.artifact->artifact.stencilReferences.empty()) { - const bool misplaced = prepared.UsesDataAddress() ? prepared.stencilReferenceDword != RuntimeAbi::RootDword + RuntimeAbi::RootStencilReference : prepared.stencilReferenceDword >= layout.pushConstantSizeBytes / 4u || prepared.stencilReferenceDword != (usesPush ? words : 0u); + const bool misplaced = prepared.UsesDataAddress() ? prepared.stencilReferenceDword != PushData::NoStart : prepared.stencilReferenceDword >= layout.pushConstantSizeBytes / 4u || prepared.stencilReferenceDword != (usesPush ? words : 0u); if (misplaced) return false; } if (!std::ranges::equal(key, handle.staticKey) || handle.source->code.size() != request.shader.code.size()) return false; diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 08b9a3f30844..252397e80be8 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -782,6 +782,8 @@ struct CompiledShaderArtifact { std::uint32_t samplerSlotDword = 0; std::uint32_t bufferAddressDword = 0; std::uint32_t bufferAddressCount = 0; + std::vector pushedData; + std::uint32_t pushItems = 0; bool dataAddressPush = false; bool bdaStores = false; std::uint32_t bdaAbiVersion = 0; diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index b867860ca5b8..8b74064ed767 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -9,7 +9,7 @@ namespace ShaderRecompiler::RuntimeAbi { -inline constexpr std::uint32_t Version = 14u; +inline constexpr std::uint32_t Version = 15u; inline constexpr std::uint32_t DescriptorSet = 0u; inline constexpr std::uint32_t FragmentDescriptorSet = 1u; inline constexpr std::uint32_t StageCount = 4u; @@ -88,18 +88,19 @@ inline constexpr std::uint32_t GpuDataSet = 2u; inline constexpr std::uint32_t GpuGdsSet = 4u; inline constexpr std::uint32_t GdsBytes = 0x10000u; inline constexpr std::uint32_t PushDataDwords = 64u; -inline constexpr std::uint32_t RootDword = 38u; -inline constexpr std::uint32_t RootRingAddress = 0u; -inline constexpr std::uint32_t RootPagetableAddress = 2u; -inline constexpr std::uint32_t RootFaultAddress = 4u; -inline constexpr std::uint32_t RootGdsAddress = 6u; -inline constexpr std::uint32_t RootPagetableDwords = 8u; -inline constexpr std::uint32_t RootStencilReference = 9u; -inline constexpr std::uint32_t RootStageRecords = 10u; -enum class RootStageField : std::uint32_t { ShaderData, FlattenedSrt, SrtDwords, TableMap, Count }; -inline constexpr std::uint32_t RootStageDword(Stage stage, RootStageField field) { return RootStageRecords + static_cast(stage) * static_cast(RootStageField::Count) + static_cast(field); } -inline constexpr std::uint32_t RootDwords = RootStageRecords + StageCount * static_cast(RootStageField::Count); -static_assert(RootDword * 4u % 8u == 0u && RootDword + RootDwords == PushDataDwords); +inline constexpr std::uint32_t PushedDataWantedLimit = 48u; +enum class RootItem : std::uint32_t { RingAddress, PagetableAddress, FaultAddress, GdsAddress, PagetableDwords, StencilReference, ShaderData, FlattenedSrt, SrtDwords, TableMap, Count }; +inline constexpr std::uint32_t RootItemCount = static_cast(RootItem::Count); +inline constexpr std::uint32_t RootItemBit(RootItem item) { return 1u << static_cast(item); } +inline constexpr bool RootAddressItem(RootItem item) { return static_cast(item) <= static_cast(RootItem::GdsAddress); } +inline constexpr std::uint32_t DepthRemapPushBit = 1u << 16u; +inline constexpr std::uint32_t NoPushPosition = 0xffffffffu; +struct PushedPlacement { + std::uint32_t base = 0; + std::uint32_t count = 0; + + bool operator==(const PushedPlacement&) const = default; +}; struct HeapSlotWord { std::uint32_t dword = 0; std::uint32_t kind = 0; diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index f4871a3267fd..405e0a0cf19c 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -85,16 +85,16 @@ std::filesystem::path ShaderCacheDirectory() { namespace ShaderRecompiler::ShaderDiskCache { #if defined(__linux__) && defined(__x86_64__) && defined(__GLIBCXX__) -static_assert(sizeof(CompiledShaderArtifact) == 304, "CompiledShaderArtifact changed: update the artifact encoder"); +static_assert(sizeof(CompiledShaderArtifact) == 328, "CompiledShaderArtifact changed: update the artifact encoder"); static_assert(sizeof(ShaderInvocation) == 240, "ShaderInvocation changed: update the invocation encoder"); #if defined(__cpp_lib_atomic_shared_ptr) -static_assert(sizeof(RecompileResult) == 624, "RecompileResult changed: update EncodeResult and DecodeResult"); +static_assert(sizeof(RecompileResult) == 648, "RecompileResult changed: update EncodeResult and DecodeResult"); #endif static_assert(sizeof(DescriptorBinding) == 656, "DescriptorBinding changed: update the binding encoder"); static_assert(sizeof(VertexAttribute) == 32, "VertexAttribute changed: update the attribute encoder"); static_assert(sizeof(VertexInput) == 16, "VertexInput changed: update the vertex input encoder"); static_assert(sizeof(FragmentParameter) == 16, "FragmentParameter changed: update the parameter encoder"); -static_assert(sizeof(CompiledShaderInfo) == 368, "CompiledShaderInfo changed: update the info encoder"); +static_assert(sizeof(CompiledShaderInfo) == 400, "CompiledShaderInfo changed: update the info encoder"); static_assert(sizeof(ShaderInfo) == 232, "ShaderInfo changed: update the info encoder"); static_assert(sizeof(BufferResource) == 32, "BufferResource changed: update the info encoder"); static_assert(sizeof(ImageResource) == 108, "ImageResource changed: update the info encoder"); @@ -102,10 +102,10 @@ static_assert(sizeof(SamplerResource) == 24, "SamplerResource changed: update th static_assert(sizeof(SampledResourcePair) == 16, "SampledResourcePair changed: update the info encoder"); static_assert(sizeof(StageInput) == 56, "StageInput changed: update the info encoder"); static_assert(sizeof(StageOutput) == 48, "StageOutput changed: update the info encoder"); -static_assert(sizeof(IrBindingLayout) == 96, "IrBindingLayout changed: update the layout encoder"); +static_assert(sizeof(IrBindingLayout) == 128, "IrBindingLayout changed: update the layout encoder"); static_assert(sizeof(IrDescriptorBinding) == 32, "IrDescriptorBinding changed: update the layout encoder"); -static_assert(sizeof(BindingAllocationResult) == 200, "BindingAllocationResult changed: update the allocation encoder"); -static_assert(sizeof(CompiledBindingLayout) == 104, "CompiledBindingLayout changed: update the allocation encoder"); +static_assert(sizeof(BindingAllocationResult) == 232, "BindingAllocationResult changed: update the allocation encoder"); +static_assert(sizeof(CompiledBindingLayout) == 136, "CompiledBindingLayout changed: update the allocation encoder"); static_assert(sizeof(BindingLayout) == 16, "BindingLayout changed: update BuildKey"); static_assert(sizeof(IrResourcePlan) == 728, "IrResourcePlan changed: update EncodePlan and DecodePlan"); static_assert(sizeof(IrValue) == 144, "IrValue changed: update the plan value encoder"); @@ -527,6 +527,8 @@ void encodeArtifact(Writer& writer, const CompiledShaderArtifact& result) { writer.Value(result.samplerSlotDword); writer.Value(result.bufferAddressDword); writer.Value(result.bufferAddressCount); + writer.Values(std::span(result.pushedData)); + writer.Value(result.pushItems); writer.Value(result.dataAddressPush); writer.Value(result.bdaStores); writer.List(result.vertexInputPatches, [](Writer& out, const VertexInputPatch& patch) { @@ -600,6 +602,8 @@ void decodeArtifact(Reader& reader, CompiledShaderArtifact& result) { reader.Value(result.samplerSlotDword); reader.Value(result.bufferAddressDword); reader.Value(result.bufferAddressCount); + reader.Values(result.pushedData); + reader.Value(result.pushItems); reader.Value(result.dataAddressPush); reader.Value(result.bdaStores); reader.List(result.vertexInputPatches, 20, [](Reader& in, VertexInputPatch& patch) { @@ -753,7 +757,7 @@ void decodeInvocation(Reader& reader, ShaderInvocation& invocation) { void encodeLayout(Writer& writer, const IrBindingLayout& layout) { writer.Value(layout.pushDataStartDword); - writer.Value(layout.dataAddressDword); + writer.Value(layout.dataAddress); writer.Value(layout.stencilReferenceDword); writer.Value(layout.memoryOffsetDword); writer.Value(layout.memoryOffsetCount); @@ -763,6 +767,7 @@ void encodeLayout(Writer& writer, const IrBindingLayout& layout) { writer.Value(layout.samplerSlotDwords); writer.Value(layout.imageSlotDwords); writer.Value(layout.bufferAddressDwords); + writer.Values(std::span(layout.pushedData)); writer.Value(layout.heapStorageImages); writer.Value(layout.gpuResolvedImages); writer.Values(std::span(layout.userDataRegisters)); @@ -774,7 +779,7 @@ void encodeLayout(Writer& writer, const IrBindingLayout& layout) { void decodeLayout(Reader& reader, IrBindingLayout& layout) { reader.Value(layout.pushDataStartDword); - reader.Value(layout.dataAddressDword); + reader.Value(layout.dataAddress); reader.Value(layout.stencilReferenceDword); reader.Value(layout.memoryOffsetDword); reader.Value(layout.memoryOffsetCount); @@ -784,6 +789,7 @@ void decodeLayout(Reader& reader, IrBindingLayout& layout) { reader.Value(layout.samplerSlotDwords); reader.Value(layout.imageSlotDwords); reader.Value(layout.bufferAddressDwords); + reader.Values(layout.pushedData); reader.Value(layout.heapStorageImages); reader.Value(layout.gpuResolvedImages); reader.Values(layout.userDataRegisters); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp index f3a11d957138..ee04616929e3 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp @@ -56,6 +56,7 @@ struct SpirvEmitInfo { bool functionLdsBuffer = false; bool bdaStores = false; bool meshWindowBuffer = false; + std::uint32_t pushItems = 0; std::uint32_t scratchPoolSlotDwords = 0; }; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index 0a9b56910c41..69a74d60c548 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -234,6 +234,7 @@ struct SpirvEmitterState { std::uint32_t pushConstantVariable = 0; std::uint32_t shaderDataStorageVariable = 0; std::uint32_t shaderDataUniformVariable = 0; + std::uint32_t pushItems = 0; std::unordered_map heapSlotVariables; std::uint32_t flattenedSrtVariable = 0; bool flattenedSrtAddressed = false; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp index ae2dc1b7d4d1..d7e28603f116 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp @@ -13,12 +13,11 @@ std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dw std::uint32_t EmitShaderDataWordLoad(SpirvEmitterState& state, std::uint32_t index); std::uint32_t ComposeAddress64(SpirvEmitterState& state, const std::function& loadLow, const std::function& loadHigh); std::uint32_t EmitAlignedLoadU32(SpirvEmitterState& state, std::uint32_t pointer); -std::uint32_t EmitRootDword(SpirvEmitterState& state, std::uint32_t field); -std::uint32_t EmitStageRootDword(SpirvEmitterState& state, RuntimeAbi::RootStageField field); -std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, std::uint32_t field, std::uint32_t index); -std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, std::uint32_t field, std::uint32_t index); +std::uint32_t EmitRootItemDword(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t word); +std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); +std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); std::uint32_t EmitRingAddress(SpirvEmitterState& state); -std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::RootStageField field, std::uint32_t index); +std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index); bool HasFlattenedSrt(const SpirvEmitterState& state); void EmitMemoryOffsets(SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp index 94cfcd0a9176..b4f864a5ec2d 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp @@ -13,8 +13,8 @@ std::uint32_t BdaConstant(SpirvEmitterState& state, std::uint64_t value) { } std::uint32_t BdaWord(SpirvEmitterState& state, std::uint32_t variable, std::uint32_t index) { - if (state.BdaAddressed() && variable == state.bdaPagetableVariable) return EmitRootAddressReadOnlyWordPointer(state, RuntimeAbi::RootPagetableAddress, index); - if (state.BdaAddressed() && variable == state.faultBufferVariable) return EmitRootAddressWordPointer(state, RuntimeAbi::RootFaultAddress, index); + if (state.BdaAddressed() && variable == state.bdaPagetableVariable) return EmitRootAddressReadOnlyWordPointer(state, RuntimeAbi::RootItem::PagetableAddress, index); + if (state.BdaAddressed() && variable == state.faultBufferVariable) return EmitRootAddressWordPointer(state, RuntimeAbi::RootItem::FaultAddress, index); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, variable, ConstantU32(state, 0u), index); return pointer; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp index 68f7b42b2497..c1ae3df21d13 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp @@ -65,7 +65,7 @@ std::uint32_t DefineBdaLookup(SpirvEmitterState& state, const char* name, bool r } leaveIf(binary(spv::OpINotEqual, boolean, reason, constant(0u)), reason); }; - auto length = state.BdaAddressed() ? EmitRootDword(state, RuntimeAbi::RootPagetableDwords) : state.module.AllocateId(); + auto length = state.BdaAddressed() ? EmitRootItemDword(state, RuntimeAbi::RootItem::PagetableDwords, 0u) : state.module.AllocateId(); if (!state.BdaAddressed()) state.module.AddFunction(spv::OpArrayLength, u32, length, state.bdaPagetableVariable, 0u); fail(binary(spv::OpULessThan, boolean, length, constant(4)), BdaAbi::FaultReason::InvalidTable); const auto count = BdaLoadWord(state, constant(1)); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp index c2e861015149..6bcd776df5f5 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp @@ -357,6 +357,7 @@ std::vector SpirvEmitter::Emit(const IrProgram& program, const Sh info->fullSubgroups = state.spannedWave; info->functionLdsBuffer = state.pixelFunctionLdsBuffer; info->bdaStores = state.bdaWritePointerFunction != 0; + info->pushItems = state.pushItems; info->meshWindowBuffer = state.meshWindowBuffer; info->scratchPoolSlotDwords = ScratchPoolActive(state) ? ScratchPoolSlotDwords(state) : 0u; } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp index ae3a346b7849..3c1b600f982a 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp @@ -3,6 +3,7 @@ #include "SpirvBackend/SpirvBda.hpp" #include "SpirvBackend/SpirvEmitterInstructions.hpp" #include "SpirvBackend/SpirvRuntimeBuffer.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include "SpirvBackend/SpirvMemory/SpirvSubgroup.hpp" #include #include @@ -103,11 +104,16 @@ void EmitReturnTerminator(SpirvValueEmitContext& ctx) { const auto reference = Unary(state, spv::OpBitcast, TypeU32(state), value); const auto masked = Binary(state, spv::OpBitwiseAnd, TypeU32(state), reference, ConstantU32(state, 0xffu)); const auto& layout = state.program.Metadata().bindings; - const auto offset = layout.UsesDataAddress() ? ConstantU32(state, layout.stencilReferenceDword) : state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::StencilReferenceOffset, layout.stencilReferenceDword); - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0u), offset); - const auto expected = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), expected, pointer); + auto expected = 0u; + if (layout.UsesDataAddress()) { + expected = EmitRootItemDword(state, RuntimeAbi::RootItem::StencilReference, 0u); + } else { + const auto offset = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::StencilReferenceOffset, layout.stencilReferenceDword); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0u), offset); + expected = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), expected, pointer); + } EmitKillIfBoolFalse(state, Binary(state, spv::OpIEqual, TypeBool(state), masked, expected)); } EmitReturnReleasingScratch(state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp index 83b066f32736..21b74075790c 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp @@ -2025,7 +2025,7 @@ ScalarBufferDword EmitScalarBufferDword(SpirvEmitterState& state, std::uint32_t std::uint32_t LoadTableMap(SpirvEmitterState& state, std::uint32_t index) { if (state.TableMapAddressed()) { const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, EmitStageRingWordPointer(state, RuntimeAbi::RootStageField::TableMap, index), spv::MemoryAccessAlignedMask, 4u); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, EmitStageRingWordPointer(state, RuntimeAbi::RootItem::TableMap, index), spv::MemoryAccessAlignedMask, 4u); return value; } const auto pointer = state.module.AllocateId(); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index c4050709b034..8bf1ced75a5e 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -40,19 +40,37 @@ std::uint32_t EmitAlignedLoadU32(SpirvEmitterState& state, std::uint32_t pointer return value; } -std::uint32_t EmitRootDword(SpirvEmitterState& state, std::uint32_t field) { +std::uint32_t EmitRootItemDword(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t word) { if (!state.program.Metadata().bindings.UsesDataAddress()) FailEmit("the root is read only by stages that take their data through it"); + state.pushItems |= RuntimeAbi::RootItemBit(item); const auto u32 = TypeU32(state); + const auto position = state.module.SpecializationConstant(u32, PipelineSpecialization::RootItemPositionBase + static_cast(item), 0u); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), ConstantU32(state, RuntimeAbi::RootDword + field)); + state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), word == 0u ? position : Binary(state, spv::OpIAdd, u32, position, ConstantU32(state, word))); const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, u32, value, pointer); return value; } -std::uint32_t EmitStageRootDword(SpirvEmitterState& state, RuntimeAbi::RootStageField field) { - const auto stage = state.program.Resources().stage; - return EmitRootDword(state, RuntimeAbi::RootStageDword(RuntimeAbi::StageGroup(stage == IrShaderStage::Pixel, stage == IrShaderStage::TessellationControl, stage == IrShaderStage::TessellationEvaluation), field)); +namespace { + +std::uint32_t EmitPushedDataSelect(SpirvEmitterState& state, std::uint32_t position, std::uint32_t ring) { + const auto u32 = TypeU32(state); + const auto base = state.module.SpecializationConstant(u32, PipelineSpecialization::PushedDataBase, 0u); + const auto count = state.module.SpecializationConstant(u32, PipelineSpecialization::PushedDataCount, 0u); + const auto inside = state.module.AllocateId(); + state.module.AddFunction(spv::OpULessThan, TypeBool(state), inside, ConstantU32(state, position), count); + const auto index = state.module.AllocateId(); + state.module.AddFunction(spv::OpSelect, u32, index, inside, Binary(state, spv::OpIAdd, u32, base, ConstantU32(state, position)), ConstantU32(state, 0u)); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), index); + const auto pushedValue = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, u32, pushedValue, pointer); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpSelect, u32, value, inside, pushedValue, ring); + return value; +} + } std::uint32_t ComposeAddress64(SpirvEmitterState& state, const std::function& loadLow, const std::function& loadHigh) { @@ -64,8 +82,8 @@ std::uint32_t ComposeAddress64(SpirvEmitterState& state, const std::function(pushed - layout.pushedData.begin()), ring); + } const auto pointer = state.module.AllocateId(); const auto value = state.module.AllocateId(); if (layout.UsesPushData()) { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index a096ef9b5359..a2ae2a251cc9 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -514,6 +514,7 @@ void DefineDescriptors(SpirvEmitterState& state) { break; } state.storageBufferVariable = Define(ArrayType(StorageBufferBlockType(state)), "buffers"); + if (layout.UsesDataAddress()) state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::FlattenedSrt); if (state.requirements.coherentBufferAlias) state.storageBufferCoherentVariable = Define(ArrayType(StorageBufferBlockType(state)), "buffers_coherent"); if (state.requirements.bufferU64View) state.storageBufferU64Variable = Define(ArrayType(StorageBufferU64BlockType(state)), "buffers_u64"); if (state.storageBufferU64Variable != 0u || state.storageBufferCoherentVariable != 0u) { @@ -551,12 +552,14 @@ void DefineDescriptors(SpirvEmitterState& state) { const auto array = state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 16u}}}, TypeU32Vector(state, 4), ConstantU32(state, vectors)); const auto block = state.module.DecoratedType(spv::OpTypeStruct, {{spv::OpDecorate, {spv::DecorationBlock}}, {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}}, array); state.shaderDataUniformVariable = Define(block, "shader_data", spv::StorageClassUniform); + state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::ShaderData); } break; case DescriptorBindingKind::FlattenedSrt: if (layout.UsesDataAddress() && !state.heapBufferDescriptors) state.flattenedSrtAddressed = true; else { state.flattenedSrtVariable = Define(StorageBufferBlockType(state), "flattened_srt"); + if (layout.UsesDataAddress()) state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::FlattenedSrt); if (!layout.UsesDataAddress()) state.module.AddAnnotation(spv::OpDecorate, state.flattenedSrtVariable, spv::DecorationNonWritable); } break; @@ -565,6 +568,7 @@ void DefineDescriptors(SpirvEmitterState& state) { break; case DescriptorBindingKind::Gds: state.gdsVariable = Define(StorageBufferBlockType(state), "gds"); + if (layout.UsesDataAddress()) state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::GdsAddress); state.module.AddAnnotation(spv::OpDecorate, state.gdsVariable, spv::DecorationCoherent); break; case DescriptorBindingKind::ImageTable: diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp index bf10d0bf4200..62ab543149d2 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp @@ -891,6 +891,7 @@ std::uint32_t RemapPositionDepth(SpirvEmitterState& state, std::uint32_t positio state.module.AddFunction(spv::OpCompositeExtract, f32, components.at(i), position, i); } const auto mode = state.module.SpecializationConstant(u32, PipelineSpecialization::DepthRemapBase, remap.mode); + state.pushItems |= RuntimeAbi::DepthRemapPushBit; if (state.pushConstantVariable == 0u) throw std::runtime_error("depth remap push constants were not declared"); const auto pushFloat = [&](std::uint32_t dword) { const auto pointer = state.module.AllocateId(); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 0f84362f053e..1ab6116e63f3 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -47,6 +47,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_CODE_HASH_KEY` | presence | `core/shader/recompiler/CacheKey.hpp` | | appends every code word to the cache key instead of hashing the code | | `APS5_NO_FAILURE_MEMO` | presence | `core/shader/recompiler/Recompiler.cpp` | | rebuilds a program whose compilation failed instead of reusing the memoized failure | | `APS5_NO_FAULT_CHECK_DEDUP` | presence | `core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp` | | emits every invalid-descriptor fault check of a GPU-descriptor buffer access instead of skipping one that an identical check on the same descriptor under the same execution guard already covers in the same IR block or a dominating block; read once per program | +| `APS5_NO_HEAP_PUSHED_DATA` | presence | `core/shader/recompiler/Optimization/src/BindingAllocator.cpp` | | reads all of a descriptor-heap stage's shader data from the ring instead of pushing its heap slot indices and then its user data (each pipeline packs its stages' root items and pushed dwords into the 64 push dwords) | | `APS5_NO_IMAGE_TABLES` | presence | `core/shader/recompiler/Optimization/src/ResourceTracker.cpp` | | disables image tables, leaving table-loaded descriptors unplanned | | `APS5_NO_MASKED_RESULT_MEMO` | presence | `core/shader/recompiler/Recompiler.cpp` | | materializes every result memo miss instead of patching the buffer descriptors, user data and flattened SRT of a cached result whose snapshot differs only in those words | | `APS5_NO_PERF_DISK_PLANS` | presence | `core/shader/recompiler/Recompiler.cpp` | | disables the disk cache of planning results | From 8be80b264c349706e380b265c9527d5c4b492825 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 5 Nov 2026 21:03:59 +0530 Subject: [PATCH 118/269] fix(shader): take shader disk cache format 57 above main's 56 The heap branch encodes new artifact (gpuResolvedImages, sampler slot and buffer address dwords, pushed data, push items, data-address push, BDA stores), invocation (heap slot words) and binding-layout fields (data address, slot and address dword counts, pushed data, heap storage images, GPU-resolved images), so its entries need their own format number above main's. --- core/shader/recompiler/ShaderDiskCache.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index 3e43cbb22130..12df2ae98d01 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -13,7 +13,7 @@ namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 56; +inline constexpr std::uint32_t FormatVersion = 57; enum class LoadStatus { Loaded, From 36caa8b0fe15220f9655bbecf7ebe733cc0a01b7 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 5 Nov 2026 23:46:40 +0530 Subject: [PATCH 119/269] perf(agc): evict idle GPU heap image slots and size the heap from the device A nearly full GPU heap used to send every draw down the per-draw path until owners released slots. Like vkd3d-proton, which leaves descriptor lifetime to the heap's owner, the heap now frees the image slots no draw has used for two submissions. An evicted slot moves its generation, so templates holding it take fresh slots on their next draw, and it is handed out again only after the submission that followed the eviction completes. Draws that keep using a slot refresh it on every heap stage write. APS5_NO_HEAP_EVICTION turns it off. The image heap length is now the HeapImageSlots specialization constant instead of a constant in the module, the way vkd3d-proton sizes its heap arrays at pipeline creation. Pipelines set it to the device heap's slot count, which grows past the ABI's 233472 into resource heap space the shader data ring leaves unused, up to 524288 slots. Shader disk cache format 58. The 10 s [gpu-heap] line adds the slot count, evictions and their waits, and ring waits, the largest bytes one batch wrote into the ring and the largest span. --- .../Execution/src/VulkanDevice.cpp | 2 + .../Graphics/include/BindlessHeap.hpp | 18 +- .../include/PipelineSpecialization.hpp | 6 + .../Graphics/src/BindlessHeap.cpp | 193 ++++++++++++++---- .../libSceAgcDriver/Graphics/src/Pipeline.cpp | 1 + .../Graphics/src/ShaderResources.cpp | 2 + .../Graphics/src/ShaderValidation.cpp | 17 +- .../tests/BindlessHeapSlots.cpp | 57 +++++- .../cmake/agc_driver_heap_slots_tests.cmake | 2 +- .../recompiler/PipelineSpecialization.hpp | 1 + core/shader/recompiler/Recompiler.cpp | 3 +- core/shader/recompiler/ShaderDiskCache.hpp | 2 +- .../SpirvMemory/SpirvConstants.hpp | 1 + .../src/SpirvMemory/SpirvConstants.cpp | 6 + .../src/SpirvMemory/SpirvDescriptors.cpp | 8 +- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 7 +- docs/dev/ENVIRONMENT.md | 3 +- 17 files changed, 272 insertions(+), 57 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index dfaf2ee7e424..637f14d7c2fb 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -5956,6 +5956,7 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons objects->pushPlacements = Graphics::PushDataPlacements(std::span(&placed, 1)); Graphics::PipelineSpecialization specialization(shader); specialization.PlacePushData(objects->pushPlacements.front()); + if (gpuMode && context.descriptorHeap && Graphics::DescriptorHeapEnabled()) specialization.PlaceHeapImageSlots(Graphics::BindlessHeap::For(context).ImageSlots()); const auto subgroupSize = computeSubgroupSize(shader); const auto stageFlags = computeStageFlags(shader); if (const auto* directory = ComputePipelineDumpDirectory(); directory != nullptr && *directory != 0 && !state->probingFloatControls && ComputePipelineCapture::OptionalEnabled() && CaptureComputePipeline(shader.spirv.size())) { @@ -6016,6 +6017,7 @@ VkPipeline VulkanDevice::splitComputePipeline(const Graphics::Context& context, for (std::uint32_t component = 0; component < offsets.size(); ++component) offsets[component] = {ShaderRecompiler::PipelineSpecialization::WorkgroupOffsetBase + component, base[component]}; Graphics::PipelineSpecialization specialization(shader, offsets); specialization.PlacePushData(objects.pushPlacements.front()); + if (objects.descriptorHeap) specialization.PlaceHeapImageSlots(Graphics::BindlessHeap::For(context).ImageSlots()); VkShaderModule module = Graphics::CreateShaderModule(state->DeviceFunction("vkCreateShaderModule"), state->device, state->graphicsPipelineLibrary, shader.spirv.data(), shader.spirv.size() * sizeof(std::uint32_t), "vkCreateShaderModule"); VkPipeline pipeline = VK_NULL_HANDLE; try { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 272a755e97f8..37313f54ff8e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -68,6 +69,8 @@ class BindlessHeap { std::uint32_t AbsentSlot(std::uint32_t kind, VkImageView view); static bool NearlyFull(); static std::uint32_t ImageSlotCapacity(); + std::uint32_t ImageSlots() const { return slotCap; } + void TouchSlots(std::span> slots) const; struct DataSpan { std::uint32_t offset = 0; @@ -89,7 +92,8 @@ class BindlessHeap { struct Counts { std::uint64_t ringWraps = 0, encodes = 0, encodedCopies = 0; - std::uint64_t slotsFreed = 0, slotsReused = 0; + std::uint64_t slotsFreed = 0, slotsReused = 0, slotsEvicted = 0, evictionWaits = 0; + std::uint64_t ringWaits = 0, ringBatchPeakBytes = 0, ringSpanPeakBytes = 0; std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0, bufferDescriptors = 0; }; Counts Statistics() const; @@ -173,6 +177,18 @@ class BindlessHeap { SlotPool imagePool; SlotPool samplerPool; std::uint32_t slotCap = 0; + std::unique_ptr[]> slotUses; + std::atomic useEpoch{1}; + struct RetiringSlot { + std::uint32_t slot = 0; + std::uint64_t serial = 0; + }; + std::deque retiring; + std::size_t ringBatchBytes = 0; + Recorder* submitter = nullptr; + void touchLocked(std::uint32_t slot) const; + void evictLocked(); + bool reclaimLocked(bool wait); std::optional imageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view, VkImageLayout layout, Texture* texture); SlotOwner& claimSlotLocked(const ImageSlotKey& key, std::uint32_t slot); void freeSlotLocked(std::uint32_t slot); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp index b8da76209be2..3d9a7b194390 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp @@ -79,6 +79,12 @@ class PipelineSpecialization { [[nodiscard]] const VkSpecializationInfo* Info() const { return entries.empty() ? nullptr : &info; } + void PlaceHeapImageSlots(std::uint32_t slots) { + for (auto& constant : values) { + if (constant.id == ShaderRecompiler::PipelineSpecialization::HeapImageSlots) constant.value = slots; + } + } + void PlacePushData(const ShaderRecompiler::StagePushPlacement& placement) { namespace Ids = ShaderRecompiler::PipelineSpecialization; for (auto& constant : values) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 7275e37fbae9..e6bf238e0296 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -132,82 +132,96 @@ bool DescriptorHeapEnabled() { namespace { struct HeapSizes { + std::uint32_t imageSlots = 0; VkDeviceSize imageStride = 0; VkDeviceSize samplerStride = 0; VkDeviceSize pixelLdsOffset = 0; VkDeviceSize meshWindowOffset = 0; VkDeviceSize resourceUsed = 0; VkDeviceSize samplerUsed = 0; + VkDeviceSize ringOffset = 0; + std::size_t ringBytes = 0; }; VkDeviceSize alignUp(VkDeviceSize value, VkDeviceSize alignment) { return alignment == 0 ? value : (value + alignment - 1) / alignment * alignment; } -HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { +constexpr std::uint32_t MaximumImageSlots = 1u << 19u; + +HeapSizes heapLayout(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, std::uint32_t slots, VkDeviceSize uniformAlignment) { HeapSizes sizes; + sizes.imageSlots = slots; sizes.imageStride = alignUp(properties.imageDescriptorSize, properties.imageDescriptorAlignment); sizes.samplerStride = alignUp(properties.samplerDescriptorSize, properties.samplerDescriptorAlignment); - const auto imageBytes = static_cast(Abi::GpuImageHeapSlots) * sizes.imageStride; + const auto imageBytes = static_cast(slots) * sizes.imageStride; sizes.pixelLdsOffset = alignUp(imageBytes, properties.bufferDescriptorAlignment); sizes.meshWindowOffset = alignUp(sizes.pixelLdsOffset + properties.bufferDescriptorSize, properties.bufferDescriptorAlignment); sizes.resourceUsed = alignUp(sizes.meshWindowOffset + properties.bufferDescriptorSize, properties.resourceHeapAlignment); sizes.samplerUsed = alignUp(static_cast(Abi::GpuSamplerHeapSlots) * sizes.samplerStride, properties.samplerHeapAlignment); + const auto offset = alignUp(sizes.resourceUsed + properties.minResourceHeapReservedRange, std::max(uniformAlignment, properties.resourceHeapAlignment)); + if (offset >= properties.maxResourceHeapSize) return sizes; + const auto room = static_cast(properties.maxResourceHeapSize - offset) / BindlessHeap::RingChunkBytes * BindlessHeap::RingChunkBytes; + const auto bytes = std::min(room, BindlessHeap::RingBytes); + if (bytes < 2u * BindlessHeap::RingChunkBytes) return sizes; + sizes.ringOffset = offset; + sizes.ringBytes = bytes; return sizes; } +VkDeviceSize layoutEnd(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, const HeapSizes& sizes) { + return sizes.ringBytes != 0u ? sizes.ringOffset + sizes.ringBytes : sizes.resourceUsed + properties.minResourceHeapReservedRange; } -namespace { - -struct ResourceRing { - VkDeviceSize offset = 0; - std::size_t bytes = 0; -}; - -ResourceRing resourceRing(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, VkDeviceSize uniformAlignment) { - const auto sizes = heapSizes(properties); - const auto offset = alignUp(sizes.resourceUsed + properties.minResourceHeapReservedRange, std::max(uniformAlignment, properties.resourceHeapAlignment)); - if (offset >= properties.maxResourceHeapSize) return {}; - const auto room = static_cast(properties.maxResourceHeapSize - offset) / BindlessHeap::RingChunkBytes * BindlessHeap::RingChunkBytes; - const auto bytes = std::min(room, BindlessHeap::RingBytes); - if (bytes < 2u * BindlessHeap::RingChunkBytes) return {}; - return {offset, bytes}; +HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, VkDeviceSize uniformAlignment) { + const auto base = heapLayout(properties, Abi::GpuImageHeapSlots, uniformAlignment); + const auto end = layoutEnd(properties, base); + if (end >= properties.maxResourceHeapSize || base.imageStride == 0u) return base; + auto slots = static_cast(std::min(MaximumImageSlots, Abi::GpuImageHeapSlots + (properties.maxResourceHeapSize - end) / base.imageStride)); + while (slots > Abi::GpuImageHeapSlots) { + const auto grown = heapLayout(properties, slots, uniformAlignment); + const auto grownEnd = layoutEnd(properties, grown); + if (grown.ringBytes == base.ringBytes && grownEnd <= properties.maxResourceHeapSize) return grown; + const auto over = grown.ringBytes == base.ringBytes ? grownEnd - properties.maxResourceHeapSize : static_cast(BindlessHeap::RingChunkBytes); + const auto step = static_cast(std::min(slots, over / base.imageStride + 1u)); + slots = slots - step > Abi::GpuImageHeapSlots ? slots - step : Abi::GpuImageHeapSlots; + } + return base; } } bool BindlessHeap::RingInResourceHeap(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, VkDeviceSize uniformAlignment) { - return resourceRing(properties, uniformAlignment).bytes != 0u; + return heapSizes(properties, uniformAlignment).ringBytes != 0u; } bool BindlessHeap::Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { - const auto sizes = heapSizes(properties); + const auto sizes = heapLayout(properties, Abi::GpuImageHeapSlots, 0u); const bool resourcesFit = sizes.resourceUsed + properties.minResourceHeapReservedRange <= properties.maxResourceHeapSize; const bool samplersFit = sizes.samplerUsed + properties.minSamplerHeapReservedRangeWithEmbedded <= properties.maxSamplerHeapSize; return resourcesFit && samplersFit; } + namespace { -std::uint32_t configuredSlotCap() { - static const std::uint32_t cap = [] { - std::uint32_t result = Abi::GpuImageHeapSlots; - if (const char* value = std::getenv("APS5_HEAP_SLOT_CAP")) { - const auto requested = static_cast(std::strtoul(value, nullptr, 10)); - if (requested != 0u) result = static_cast(Abi::Binding::Samplers) + std::min(requested, Abi::GpuImageHeapSlots - static_cast(Abi::Binding::Samplers)); - } - return result; +std::uint32_t configuredSlotCap(std::uint32_t slots) { + static const std::uint32_t requested = [] { + const char* value = std::getenv("APS5_HEAP_SLOT_CAP"); + return value != nullptr ? static_cast(std::strtoul(value, nullptr, 10)) : 0u; }(); - return cap; + if (requested == 0u || slots <= BindlessHeap::SamplerKind) return slots; + return BindlessHeap::SamplerKind + std::min(requested, slots - BindlessHeap::SamplerKind); } +std::atomic deviceImageSlots{Abi::GpuImageHeapSlots}; + } BindlessHeap::BindlessHeap(const Context& context) : context(context) { Require(context.descriptorHeap, "the GPU heap needs VK_EXT_descriptor_heap"); const auto& heapProperties = context.descriptorHeapProperties; - const auto sizes = heapSizes(heapProperties); + const auto sizes = heapSizes(heapProperties, context.limits.minUniformBufferOffsetAlignment); imageHeapStride = sizes.imageStride; samplerHeapStride = sizes.samplerStride; resourceHeapUsed = sizes.resourceUsed; @@ -229,17 +243,16 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { constexpr VkBufferUsageFlags ringUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; constexpr VkBufferUsageFlags heapUsage = VK_BUFFER_USAGE_DESCRIPTOR_HEAP_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - const auto heapRing = resourceRing(heapProperties, context.limits.minUniformBufferOffsetAlignment); - ringInHeap = heapRing.bytes != 0u; - const auto resourceBytes = ringInHeap ? static_cast(heapRing.offset) + heapRing.bytes + ringInHeap = sizes.ringBytes != 0u; + const auto resourceBytes = ringInHeap ? static_cast(sizes.ringOffset) + sizes.ringBytes : static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange); resourceHeap = makeBuffer(resourceBytes, ringInHeap ? heapUsage | ringUsage : heapUsage, ringInHeap || !hostDescriptors); samplerHeap = makeBuffer(static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage, !hostDescriptors); std::fill(resourceHeap->Bytes().begin(), resourceHeap->Bytes().end(), std::byte{0}); std::fill(samplerHeap->Bytes().begin(), samplerHeap->Bytes().end(), std::byte{0}); if (ringInHeap) { - ringHeapOffset = heapRing.offset; - ringBytes = heapRing.bytes; + ringHeapOffset = sizes.ringOffset; + ringBytes = sizes.ringBytes; ringData = resourceHeap->Bytes().data() + ringHeapOffset; ringAlignment = static_cast(std::max({context.limits.minStorageBufferOffsetAlignment, context.limits.minUniformBufferOffsetAlignment, RingSpanAlignment})); } else { @@ -248,7 +261,9 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { ringAlignment = static_cast(std::max(context.limits.minStorageBufferOffsetAlignment, RingSpanAlignment)); } ringChunks.resize(ringBytes / RingChunkBytes); - slotCap = configuredSlotCap(); + slotCap = configuredSlotCap(sizes.imageSlots); + deviceImageSlots.store(slotCap, std::memory_order_relaxed); + slotUses = std::make_unique[]>(slotCap); imagePool.next = SamplerKind; imagePool.limit = slotCap; samplerPool.limit = Abi::GpuSamplerHeapSlots; @@ -257,6 +272,7 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { namespace { constexpr std::uint32_t ImageSlotMargin = 1024u; +constexpr std::uint32_t EvictIdleSubmissions = 2u; constexpr std::uint32_t SamplerSlotMargin = Abi::GpuSamplerHeapSlots / 4u; std::atomic refusedHeaps{0}; @@ -339,13 +355,18 @@ std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const He std::optional BindlessHeap::imageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view, VkImageLayout layout, Texture* texture) { std::lock_guard lock(mutex); const ImageSlotKey key{kind, owner, view, layout}; - if (const auto found = imageSlots.find(key); found != imageSlots.end()) return found->second; + if (const auto found = imageSlots.find(key); found != imageSlots.end()) { + touchLocked(found->second); + return found->second; + } bool reused = false; - const auto slot = imagePool.Take(reused); + auto slot = imagePool.Take(reused); + if (!slot && reclaimLocked(true)) slot = imagePool.Take(reused); if (!slot) return std::nullopt; if (reused) ++counts.slotsReused; writeImageSlot(kind, *slot, view, layout); claimSlotLocked(key, *slot).texture = texture; + touchLocked(*slot); owner->heapSlotted.store(true, std::memory_order_release); noteTakenLocked(); return slot; @@ -424,7 +445,7 @@ bool BindlessHeap::NearlyFull() { } std::uint32_t BindlessHeap::ImageSlotCapacity() { - return configuredSlotCap() - SamplerKind; + return deviceImageSlots.load(std::memory_order_relaxed) - SamplerKind; } std::uint32_t BindlessHeap::imageMargin() const { @@ -445,7 +466,73 @@ void BindlessHeap::noteRefusedLocked(const char* what, std::uint32_t margin) { void BindlessHeap::noteTakenLocked() { const auto margin = imageMargin(); - if (!refused && imagePool.Unused() < margin) noteRefusedLocked("image", margin); + if (imagePool.Unused() >= margin) return; + reclaimLocked(false); + if (imagePool.Unused() + retiring.size() < margin) evictLocked(); + if (!refused && imagePool.Unused() + retiring.size() < margin) noteRefusedLocked("image", margin); +} + +void BindlessHeap::touchLocked(std::uint32_t slot) const { + if (slot < slotCap) slotUses[slot].store(useEpoch.load(std::memory_order_relaxed), std::memory_order_relaxed); +} + +void BindlessHeap::TouchSlots(std::span> slots) const { + const auto epoch = useEpoch.load(std::memory_order_relaxed); + for (const auto& kindSlots : slots) { + for (const auto slot : kindSlots) { + if (slot < slotCap) slotUses[slot].store(epoch, std::memory_order_relaxed); + } + } +} + +void BindlessHeap::evictLocked() { + static const bool disabled = std::getenv("APS5_NO_HEAP_EVICTION") != nullptr; + if (disabled) return; + const auto epoch = useEpoch.load(std::memory_order_relaxed); + std::vector> idle; + for (std::uint32_t slot = SamplerKind; slot < imagePool.next && slot < owners.size(); ++slot) { + if (owners[slot].key.owner == nullptr) continue; + const auto use = slotUses[slot].load(std::memory_order_relaxed); + if (use + EvictIdleSubmissions <= epoch) idle.emplace_back(use, slot); + } + const auto wanted = std::min(idle.size(), 4u * static_cast(imageMargin())); + if (wanted == 0u) return; + std::nth_element(idle.begin(), idle.begin() + static_cast(wanted - 1u), idle.end()); + for (std::size_t index = 0; index < wanted; ++index) { + const auto slot = idle[index].second; + auto& owner = owners[slot]; + imageSlots.erase(owner.key); + if (const auto found = ownerSlots.find(owner.key.owner); found != ownerSlots.end()) { + auto& held = found->second; + held.erase(std::remove(held.begin(), held.end(), slot), held.end()); + if (held.empty()) ownerSlots.erase(found); + } + owner.texture = nullptr; + owner.key = {}; + ++imagePool.generations[slot]; + retiring.push_back({slot, 0u}); + ++counts.slotsEvicted; + } + slotSerial.fetch_add(1, std::memory_order_release); +} + +bool BindlessHeap::reclaimLocked(bool wait) { + bool reclaimed = false; + while (!retiring.empty() && retiring.front().serial != 0u && submitter != nullptr && submitter->HasTimeline()) { + const auto serial = retiring.front().serial; + if (!submitter->WaitSerialFor(serial, 0u)) { + if (!wait || reclaimed) break; + submitter->WaitSerial(serial); + ++counts.evictionWaits; + } + while (!retiring.empty() && retiring.front().serial != 0u && retiring.front().serial <= serial) { + imagePool.free.push_back(retiring.front().slot); + retiring.pop_front(); + reclaimed = true; + } + } + if (reclaimed) noteReleasedLocked(); + return reclaimed; } void BindlessHeap::noteSamplerTakenLocked() { @@ -559,6 +646,8 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) offset = wrapRingOffset((chunkOf(offset) + 1u) * RingChunkBytes, bytes); ++counts.keptChunksSkipped; } + ringBatchBytes += bytes + (offset >= ringCursor ? offset - ringCursor : ringBytes - ringCursor + offset); + counts.ringSpanPeakBytes = std::max(counts.ringSpanPeakBytes, bytes); ringCursor = offset + bytes; for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) enterRingChunk(chunk); auto* base = reinterpret_cast(ringData + offset); @@ -581,7 +670,10 @@ void BindlessHeap::enterRingChunk(std::size_t index) { if (chunk.serial != 0u) { if (!chunk.recorder->HasTimeline()) throw std::runtime_error("AGC bindless heap: the shader data ring needs the recorder timeline to wait for a batch"); - chunk.recorder->WaitSerial(chunk.serial); + if (!chunk.recorder->WaitSerialFor(chunk.serial, 0u)) { + chunk.recorder->WaitSerial(chunk.serial); + ++counts.ringWaits; + } chunk.serial = 0u; } chunk.open = true; @@ -999,6 +1091,11 @@ void reportHeapStatistics() { totals.encodes += counts.encodes; totals.encodedCopies += counts.encodedCopies; totals.bufferDescriptors += counts.bufferDescriptors; + totals.slotsEvicted += counts.slotsEvicted; + totals.evictionWaits += counts.evictionWaits; + totals.ringWaits += counts.ringWaits; + totals.ringBatchPeakBytes = std::max(totals.ringBatchPeakBytes, counts.ringBatchPeakBytes); + totals.ringSpanPeakBytes = std::max(totals.ringSpanPeakBytes, counts.ringSpanPeakBytes); } } const auto windowDelta = [](std::uint64_t now, std::uint64_t before) { return now >= before ? now - before : now; }; @@ -1008,15 +1105,18 @@ void reportHeapStatistics() { const auto imageEncodes = windowDelta(totals.encodes, lastTotals.encodes); const auto imageCopies = windowDelta(totals.encodedCopies, lastTotals.encodedCopies); const auto bufferDescriptors = windowDelta(totals.bufferDescriptors, lastTotals.bufferDescriptors); + const auto slotsEvicted = windowDelta(totals.slotsEvicted, lastTotals.slotsEvicted); + const auto evictionWaits = windowDelta(totals.evictionWaits, lastTotals.evictionWaits); + const auto ringWaits = windowDelta(totals.ringWaits, lastTotals.ringWaits); lastTotals = totals; const auto templates = ShaderRecompiler::HeapTemplateCounts(); std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired, %llu waits, peak %llu KiB per batch, largest span %llu KiB; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %u, %llu evicted (%llu waits); templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(spansExpired), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(spansExpired), printed(ringWaits), printed(totals.ringBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { @@ -1197,6 +1297,15 @@ VkDeviceSize BindlessHeap::RingOffset() const { void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { std::lock_guard lock(mutex); + submitter = &recorder; + useEpoch.fetch_add(1, std::memory_order_relaxed); + counts.ringBatchPeakBytes = std::max(counts.ringBatchPeakBytes, ringBatchBytes); + ringBatchBytes = 0; + for (auto entry = retiring.rbegin(); entry != retiring.rend() && entry->serial == 0u; ++entry) entry->serial = serial; + if (refused) { + reclaimLocked(false); + if (refused && retiring.empty()) evictLocked(); + } for (std::size_t index = 0; index < ringChunks.size(); ++index) { if (!ringChunks[index].open && index != ringChunk) continue; ringChunks[index].recorder = &recorder; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index fae2f795e77c..16bcd55fe47f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -549,6 +549,7 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput } specializations.emplace_back(shader, state.meshLayerBase, state.meshLayerCount); specializations.back().PlacePushData(pushPlacements[i]); + if (descriptorHeap) specializations.back().PlaceHeapImageSlots(BindlessHeap::For(context).ImageSlots()); stages[i].pSpecializationInfo = specializations.back().Info(); } if (std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && !shader.program->stencilReferences.empty(); })) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 517b0ead5216..d4acf7eb59a0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -7158,6 +7158,8 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { stageState.key = key; takeHeapSlots(heap, stageState, stageBit, key); noteHeapSlotGenerations(heap, stageState); + } else { + heap.TouchSlots(stageState.slots); } stageState.slotSerial = slotSerial; static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index 11f62434ef37..c5efb5d11748 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -42,6 +42,8 @@ struct Module { std::set> perPrimitiveMembers; std::map variables; std::map constants; + std::map specConstants; + std::map specIds; std::set interface; std::map inputs; std::map outputs; @@ -168,6 +170,13 @@ struct Module { } }; +bool heapImageSlotsLength(const Module& module, std::uint32_t id) { + const auto constant = module.specConstants.find(id); + const auto specId = module.specIds.find(id); + return constant != module.specConstants.end() && constant->second == ShaderRecompiler::RuntimeAbi::GpuImageHeapSlots && specId != module.specIds.end() && + specId->second == ShaderRecompiler::PipelineSpecialization::HeapImageSlots; +} + Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysicalDeviceSubgroupProperties& subgroup, bool fragmentShaderBarycentric, bool descriptorIndexing, bool imageInt64Atomics, bool geometryShader, bool sampleRateShading, bool bufferInt64Atomics, bool shaderClipDistance, bool shaderCullDistance, bool viewportIndexLayer, bool runtimeDescriptorArray, bool demoteToHelperInvocation, bool shaderTerminateInvocation, bool shaderResourceMinLod, bool fmaFloat16, std::span primitiveLocations = {}) { using Stage = ShaderRecompiler::ShaderStage; Require(compiled.program != nullptr, "missing compiled shader"); @@ -423,6 +432,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi decoration.perVertex = true; } if (kind == spv::DecorationBlock) decoration.block = true; + if (kind == spv::DecorationSpecId && count == 4) module.specIds[instruction[1]] = instruction[3]; if (kind == spv::DecorationAliased) decoration.aliased = true; break; } @@ -453,6 +463,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi if (count == 4) module.constants.emplace(instruction[2], instruction[3]); break; case spv::OpSpecConstant: + if (count == 4) module.specConstants.emplace(instruction[2], instruction[3]); break; default: break; } @@ -593,7 +604,8 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi tableAlias = tables && key.first == Abi::FragmentDescriptorSet && (samplerAlias || imageAlias); if (tableAlias && binding == shader.bindings.end()) { const auto count = type.size() == 4 && (type[0] & 0xffffu) == spv::OpTypeArray ? module.constants.find(type[3]) : module.constants.end(); - Require(count != module.constants.end() && count->second == (samplerAlias ? Abi::GpuSamplerHeapSlots : Abi::GpuImageHeapSlots), "an image table's heap array length disagrees with the global heap"); + Require(samplerAlias ? count != module.constants.end() && count->second == Abi::GpuSamplerHeapSlots : heapImageSlotsLength(module, type[3]), + "an image table's heap array length disagrees with the global heap"); continue; } } @@ -611,7 +623,8 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi const bool heapArray = binding->kind != ShaderRecompiler::DescriptorKind::StorageImage || (ShaderRecompiler::RuntimeAbi::GpuHeapStorageKind(static_cast(heap)) && binding->descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet); if (shader.gpuResolvedImages && heapArray) { const auto slots = binding->kind == ShaderRecompiler::DescriptorKind::Sampler ? ShaderRecompiler::RuntimeAbi::GpuSamplerHeapSlots : ShaderRecompiler::RuntimeAbi::GpuImageHeapSlots; - Require(binding->count != 0u && count != module.constants.end() && count->second == slots, "GPU-mode heap array length disagrees with the global heap"); + const bool length = binding->kind == ShaderRecompiler::DescriptorKind::Sampler ? count != module.constants.end() && count->second == slots : heapImageSlotsLength(module, type[3]); + Require(binding->count != 0u && length, "GPU-mode heap array length disagrees with the global heap"); } else { Require(binding->count != 0u && binding->count <= capacity && count != module.constants.end() && count->second == binding->count, "typed heap array length disagrees with compact binding"); } diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 7f92e9023e18..4beb9952298f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -5,7 +5,9 @@ #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "RuntimeAbi.hpp" +#include #include #include #include @@ -28,7 +30,7 @@ struct FakeOwner : HeapSlotOwner { FakeOwner() = default; }; -alignas(Texture) std::array, 8> fakeTextures{}; +alignas(Texture) std::array, 12> fakeTextures{}; std::shared_ptr fakeTexture(std::size_t index) { return std::shared_ptr(reinterpret_cast(fakeTextures[index].data()), [](Texture*) {}); @@ -302,6 +304,53 @@ void heapComesBack(const Context& context, VkImageView view) { BindlessHeap::Release(context.device); } +bool idleSlotsEvicted(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + const auto kind = Abi::FirstImageBinding; + Recorder recorder(context, true); + if (!recorder.HasTimeline()) return false; + recorder.Activate(); + const auto submit = [&] { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(recorder.Commands()); + recorder.Submit(); + }; + std::vector> held; + std::vector slots; + const auto take = [&](std::size_t index) { + if (held.size() <= index) held.resize(index + 1u); + if (held[index] == nullptr) held[index] = fakeTexture(index); + return heap.TextureSlot(kind, held[index].get(), view, VK_IMAGE_LAYOUT_GENERAL); + }; + for (std::size_t index = 0; index < 6u; ++index) { + const auto slot = take(index); + require(slot.has_value(), "a texture takes one of the eight capped slots"); + slots.push_back(*slot); + } + const auto idleGeneration = heap.SlotGeneration(slots[0]); + submit(); + submit(); + require(take(5) == slots[5], "a texture a draw uses again keeps its slot"); + require(take(6).has_value(), "the seventh texture takes a slot"); + require(heap.Statistics().slotsEvicted == 5u, "the five slots idle for two submissions are evicted"); + require(heap.SlotTexture(kind, slots[0]) == nullptr && heap.SlotGeneration(slots[0]) != idleGeneration, + "an evicted slot names no texture and moves its generation"); + require(heap.SlotTexture(kind, slots[5]) == held[5].get(), "the slot used again stays with its texture"); + require(take(7).has_value(), "the eighth texture takes the last never-used slot"); + require(!take(8).has_value(), "an evicted slot is not reused before a submission covers the draws that used it"); + require(!BindlessHeap::NearlyFull(), "evicted slots waiting for the GPU keep the heap open"); + submit(); + require(recorder.WaitSerialFor(recorder.Submissions(), ~std::uint64_t{0}), "the submission completes"); + const auto reused = take(8); + require(reused.has_value() && std::find(slots.begin(), slots.begin() + 5, *reused) != slots.begin() + 5, + "an evicted slot is reused once the submission after its eviction completes"); + const auto back = take(0); + require(back.has_value() && heap.SlotTexture(kind, *back) == held[0].get(), "an evicted texture takes a slot again when a draw uses it"); + for (const auto& texture : held) heap.ReleaseSlots(texture.get()); + BindlessHeap::Release(context.device); + return true; +} + void storageComesBack(const Context& context, VkImageView view) { auto& heap = BindlessHeap::For(context); std::array owners{}; @@ -429,6 +478,12 @@ int main(int argc, char** argv) { else if (mode == "two-heaps-come-back") twoHeapsComeBack(context, storage); else if (mode == "owner-views-release") ownerViewsRelease(context, storage); else if (mode == "shared-owner-release") sharedOwnerRelease(context, storage); + else if (mode == "idle-slots-evicted") { + if (!idleSlotsEvicted(context, sampled)) { + std::printf("skipped, the recorder has no timeline\n"); + return VulkanTestSkipped; + } + } else throw std::runtime_error("unknown mode " + mode); device->WaitIdle(); } diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake index b22d0f5ca9cf..c8db1612cd07 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake @@ -22,7 +22,7 @@ if(BUILD_TESTING) agc_add_default_test(agc_driver_heap_slots_tests) agc_add_env_test(agc_driver_heap_slots_ring_large_spans agc_driver_heap_slots_tests ARGS ring-large-spans ENV ANYPS5_NO_SHADER_CACHE=1) - foreach(agcHeapSlotsMode IN ITEMS comes-back storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release) + foreach(agcHeapSlotsMode IN ITEMS comes-back storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release idle-slots-evicted) string(REPLACE "-" "_" agcHeapSlotsName "${agcHeapSlotsMode}") agc_add_env_test(agc_driver_heap_slots_${agcHeapSlotsName} agc_driver_heap_slots_tests ARGS ${agcHeapSlotsMode} ENV ANYPS5_NO_SHADER_CACHE=1) diff --git a/core/shader/recompiler/PipelineSpecialization.hpp b/core/shader/recompiler/PipelineSpecialization.hpp index d00c84c49cd6..a6593943f8ec 100644 --- a/core/shader/recompiler/PipelineSpecialization.hpp +++ b/core/shader/recompiler/PipelineSpecialization.hpp @@ -35,6 +35,7 @@ inline constexpr std::uint32_t StencilReferenceOffset = 8235u; inline constexpr std::uint32_t ReversedBlend = 8236u; inline constexpr std::uint32_t MeshLayerBase = 8237u; inline constexpr std::uint32_t MeshLayerCount = 8238u; +inline constexpr std::uint32_t HeapImageSlots = 8239u; inline constexpr std::uint32_t DepthRemapBase = 8240u; inline constexpr std::uint32_t DepthRemapWords = 1u; inline constexpr std::uint32_t WorkgroupOffsetBase = 8241u; diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 080a294c9d08..2fefef082f89 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -953,7 +953,7 @@ std::vector specializeWords(const CompiledShaderArtifact& artifac } const auto found = supplied.find(words[cursor + 3u]); if (found == supplied.end()) throw std::runtime_error("missing prepared specialization value"); - if (found->first == PipelineSpecialization::MeshLayerBase || found->first == PipelineSpecialization::MeshLayerCount || PipelineSpecialization::IsPushPlacement(found->first)) { + if (found->first == PipelineSpecialization::MeshLayerBase || found->first == PipelineSpecialization::MeshLayerCount || found->first == PipelineSpecialization::HeapImageSlots || PipelineSpecialization::IsPushPlacement(found->first)) { retained.insert(words[cursor + 1u]); cursor += count; continue; @@ -1395,6 +1395,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil auto constants = plan->bindings.specialization; constants.push_back({PipelineSpecialization::MeshLayerBase, 0u}); constants.push_back({PipelineSpecialization::MeshLayerCount, 0xffffffffu}); + constants.push_back({PipelineSpecialization::HeapImageSlots, RuntimeAbi::GpuImageHeapSlots}); if (artifact.dataAddressPush) AppendPushSpecialization(constants, StandalonePushPlacement(request.shader.stage, artifact.pushItems, artifact.pushedData.size())); std::size_t index = 0; if (variant.bindings.layout.UsesPushData()) constants.push_back({PipelineSpecialization::PushDataOffset, moduleKey[index++]}); diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index 12df2ae98d01..8456006639dd 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -13,7 +13,7 @@ namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 57; +inline constexpr std::uint32_t FormatVersion = 58; enum class LoadStatus { Loaded, diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvConstants.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvConstants.hpp index fb59644f8bed..aece716687b0 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvConstants.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvConstants.hpp @@ -14,6 +14,7 @@ std::uint32_t ConstantF32Value(SpirvEmitterState& state, float value); std::uint32_t ConstantBool(SpirvEmitterState& state, bool value); std::uint32_t ConstantU64(SpirvEmitterState& state, std::uint64_t value); std::uint32_t ConstantU32CompositeZero(SpirvEmitterState& state, std::uint32_t components); +std::uint32_t HeapImageSlotCount(SpirvEmitterState& state); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvConstants.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvConstants.cpp index c4a0e26277db..5862b43cb8a7 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvConstants.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvConstants.cpp @@ -1,6 +1,8 @@ #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" #include "SpirvBackend/SpirvEmitterHelpers.hpp" #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" +#include "PipelineSpecialization.hpp" +#include "RuntimeAbi.hpp" #include #include #include @@ -36,6 +38,10 @@ std::uint32_t ConstantU64(SpirvEmitterState& state, std::uint64_t value) { return state.module.Constant(spv::OpConstantComposite, TypeU64(state), ConstantU32(state, static_cast(value)), ConstantU32(state, static_cast(value >> 32u))); } +std::uint32_t HeapImageSlotCount(SpirvEmitterState& state) { + return state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::HeapImageSlots, RuntimeAbi::GpuImageHeapSlots); +} + std::uint32_t ConstantU32CompositeZero(SpirvEmitterState& state, std::uint32_t components) { if (components < 2u || components > 4u) { FailEmit("u32 composite component count is out of range"); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp index 667566a2f692..5b1420dde035 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp @@ -97,7 +97,7 @@ std::uint32_t tableHeapSlot(SpirvEmitterState& state, RuntimeAbi::HeapPart part, } const auto slot = LoadTableMap(state, Binary(state, spv::OpIAdd, u32, partBase, element)); const auto fallback = RuntimeAbi::HeapPartFirstBinding(part); - const auto clamped = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), slot, ConstantU32(state, slots)), slot, ConstantU32(state, fallback)); + const auto clamped = Select(state, u32, Binary(state, spv::OpULessThan, TypeBool(state), slot, slots), slot, ConstantU32(state, fallback)); DecorateTableNonUniform(state, clamped); return clamped; } @@ -110,7 +110,7 @@ std::uint32_t TableStorageImagePointer(SpirvEmitterState& state, DescriptorBindi const auto pointer = state.module.AllocateId(); const auto value = static_cast(kind); const auto part = RuntimeAbi::StorageHeapPart(value); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, part, state.tableAccess.element, RuntimeAbi::GpuImageHeapSlots) : state.tableAccess.element); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, part, state.tableAccess.element, HeapImageSlotCount(state)) : state.tableAccess.element); DecorateTableNonUniform(state, pointer); return pointer; } @@ -229,7 +229,7 @@ std::uint32_t LoadSampledImageDescriptor(SpirvEmitterState& state, std::uint32_t const auto found = std::find_if(state.tableImageVariables.begin(), state.tableImageVariables.end(), [&](const SpirvTableImageVariable& variable) { return variable.kind == kind; }); if (found == state.tableImageVariables.end() || !state.tableAccess.active) ExitDescriptorBindingFailure(state, kind, resource, "image table array was not emitted for the mode"); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, RuntimeAbi::HeapPart::Sampled, state.tableAccess.element, RuntimeAbi::GpuImageHeapSlots) : state.tableAccess.element); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, found->variable, state.tableAccess.heap ? tableHeapSlot(state, RuntimeAbi::HeapPart::Sampled, state.tableAccess.element, HeapImageSlotCount(state)) : state.tableAccess.element); if (!state.tableAccess.uniform) DecorateTableNonUniform(state, pointer); const auto image = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, imageType, image, pointer); @@ -265,7 +265,7 @@ std::uint32_t LoadSamplerDescriptor(SpirvEmitterState& state, std::uint32_t samp const auto variant = image != nullptr && image->depthCompare ? 2u : 0u; const auto element = Binary(state, spv::OpIAdd, TypeU32(state), state.tableAccess.samplerElement, ConstantU32(state, variant + (point ? 1u : 0u))); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.tableSamplerVariable, state.TableHeap() ? tableHeapSlot(state, RuntimeAbi::HeapPart::Sampler, element, RuntimeAbi::GpuSamplerHeapSlots) : element); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.tableSamplerVariable, state.TableHeap() ? tableHeapSlot(state, RuntimeAbi::HeapPart::Sampler, element, ConstantU32(state, RuntimeAbi::GpuSamplerHeapSlots)) : element); DecorateTableNonUniform(state, pointer); const auto loaded = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, samplerType, loaded, pointer); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index a2ae2a251cc9..ee376662ce47 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -503,8 +503,9 @@ void DefineDescriptors(SpirvEmitterState& state) { }; const auto ArrayType = [&](std::uint32_t type) { const bool heap = binding.kind == DescriptorBindingKind::Samplers || ImageBindingResourceClass(binding.kind) != ImageResourceClass::None; - const auto count = gpuHeap ? (binding.kind == DescriptorBindingKind::Samplers ? RuntimeAbi::GpuSamplerHeapSlots : RuntimeAbi::GpuImageHeapSlots) : static_cast(binding.resources.size()); - const auto length = heap && !gpuHeap && !state.registrationModules ? state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::HeapCountBase + static_cast(binding.kind), count) : ConstantU32(state, count); + const bool samplers = binding.kind == DescriptorBindingKind::Samplers; + const auto count = gpuHeap ? (samplers ? RuntimeAbi::GpuSamplerHeapSlots : RuntimeAbi::GpuImageHeapSlots) : static_cast(binding.resources.size()); + const auto length = gpuHeap && !samplers ? HeapImageSlotCount(state) : heap && !gpuHeap && !state.registrationModules ? state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::HeapCountBase + static_cast(binding.kind), count) : ConstantU32(state, count); return state.module.Type(spv::OpTypeArray, type, length); }; switch (binding.kind) { @@ -588,7 +589,7 @@ void DefineDescriptors(SpirvEmitterState& state) { const auto value = static_cast(kind); const auto part = RuntimeAbi::StorageHeapPart(value); const auto heapKind = binding.kind != DescriptorBindingKind::ImageStorageTable ? RuntimeAbi::FirstImageBinding : part == RuntimeAbi::HeapPart::Atomic || part == RuntimeAbi::HeapPart::Atomic64 ? RuntimeAbi::HeapPartFirstBinding(part) : RuntimeAbi::FirstStorageImageBinding; - const auto slotCount = ConstantU32(state, RuntimeAbi::GpuImageHeapSlots); + const auto slotCount = HeapImageSlotCount(state); state.tableImageVariables.push_back({kind, defineHeapArray(state, slotCount, ImageType(state, mode), name.c_str(), heapKind)}); } else { state.tableImageVariables.push_back({kind, Define(state.module.Type(spv::OpTypeRuntimeArray, ImageType(state, mode)), name.c_str(), spv::StorageClassUniformConstant)}); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 1ab6116e63f3..c9adec8b66e5 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -200,7 +200,8 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_HEAP_MIRROR_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 24576 | budget in MiB for the heap mirrors held for registered allocations | | `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first | | `APS5_HEAP_WALK_MEMO_MB` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | 256 | MiB each thread's GPU heap walk memo may hold across both its generations before the previous generation and then the oldest walks are dropped (0 keeps them until the 16,384-key cap rotates them out) | -| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 233415 | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default; a stage needing more image slots than this takes the per-draw path | +| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a stage needing more image slots than this takes the per-draw path | +| `APS5_NO_HEAP_EVICTION` | flag | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | unset | set: a nearly full GPU heap no longer evicts image slots no draw used for two submissions, so draws take the per-draw path until owners release slots | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | | `APS5_HOOK_LOCKED_WAIT` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | keeps the flush hook's pending-write wait under the GpuMutex | From 097833507b9fb2ad5716178cb1eb24c127da9cfb Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 6 Nov 2026 00:02:08 +0530 Subject: [PATCH 120/269] fix(agc): count evicted heap slots as free only once a submission covers them Review of the eviction found that the margin counted evicted slots before any submission had a serial for them, so a busy batch could drain the free list without refusing the heap and fail a draw with "the global image heap is full". The margin now counts only evicted slots a submission covers, eviction starts at twice the margin, scans at most once per submission, needs the recorder timeline, and reclaims once per submit instead of per taken slot. A blocking reclaim waits only on submitted serials, heap stages refresh their slots once per submission, and the validator checks the image table alias is an array before reading its length. The [gpu-heap] line adds ring MiB written per 10 s and image slots held. --- .../Graphics/include/BindlessHeap.hpp | 6 ++- .../Graphics/include/ShaderResources.hpp | 1 + .../Graphics/src/BindlessHeap.cpp | 46 ++++++++++++------- .../Graphics/src/ShaderResources.cpp | 2 +- .../Graphics/src/ShaderValidation.cpp | 3 +- .../tests/BindlessHeapSlots.cpp | 3 +- 6 files changed, 40 insertions(+), 21 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 37313f54ff8e..de5c42632ec0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -70,7 +70,7 @@ class BindlessHeap { static bool NearlyFull(); static std::uint32_t ImageSlotCapacity(); std::uint32_t ImageSlots() const { return slotCap; } - void TouchSlots(std::span> slots) const; + std::uint32_t TouchSlots(std::span> slots, std::uint32_t touched) const; struct DataSpan { std::uint32_t offset = 0; @@ -93,7 +93,7 @@ class BindlessHeap { struct Counts { std::uint64_t ringWraps = 0, encodes = 0, encodedCopies = 0; std::uint64_t slotsFreed = 0, slotsReused = 0, slotsEvicted = 0, evictionWaits = 0; - std::uint64_t ringWaits = 0, ringBatchPeakBytes = 0, ringSpanPeakBytes = 0; + std::uint64_t ringWaits = 0, ringBatchPeakBytes = 0, ringSpanPeakBytes = 0, ringBytes = 0, imageSlotsHeld = 0; std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0, bufferDescriptors = 0; }; Counts Statistics() const; @@ -185,6 +185,8 @@ class BindlessHeap { }; std::deque retiring; std::size_t ringBatchBytes = 0; + std::size_t retiringAssigned = 0; + std::uint32_t evictScanEpoch = 0; Recorder* submitter = nullptr; void touchLocked(std::uint32_t slot) const; void evictLocked(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index f16dc4f4b6cd..7cefeb89fe71 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -683,6 +683,7 @@ class ShaderResources { std::vector samplerSlots; std::vector samplerGenerations; std::uint64_t slotSerial = 0; + std::uint32_t touchedEpoch = 0; std::vector> dataPatches; struct KeptSpan { std::vector words; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index e6bf238e0296..13423fdfe727 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -6,6 +6,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Sampler.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "Recompiler.hpp" #include "RuntimeAbi.hpp" #include "SpirvBackend/SpirvAnalysis.hpp" @@ -453,7 +454,7 @@ std::uint32_t BindlessHeap::imageMargin() const { } bool BindlessHeap::roomLocked() const { - if (imagePool.Unused() < 2u * static_cast(imageMargin())) return false; + if (imagePool.Unused() + retiringAssigned < 2u * static_cast(imageMargin())) return false; return samplerPool.Unused() >= 2u * SamplerSlotMargin; } @@ -466,29 +467,32 @@ void BindlessHeap::noteRefusedLocked(const char* what, std::uint32_t margin) { void BindlessHeap::noteTakenLocked() { const auto margin = imageMargin(); - if (imagePool.Unused() >= margin) return; - reclaimLocked(false); - if (imagePool.Unused() + retiring.size() < margin) evictLocked(); - if (!refused && imagePool.Unused() + retiring.size() < margin) noteRefusedLocked("image", margin); + if (imagePool.Unused() >= 2u * static_cast(margin)) return; + if (imagePool.Unused() + retiring.size() < 2u * static_cast(margin)) evictLocked(); + if (!refused && imagePool.Unused() + retiringAssigned < margin) noteRefusedLocked("image", margin); } void BindlessHeap::touchLocked(std::uint32_t slot) const { if (slot < slotCap) slotUses[slot].store(useEpoch.load(std::memory_order_relaxed), std::memory_order_relaxed); } -void BindlessHeap::TouchSlots(std::span> slots) const { +std::uint32_t BindlessHeap::TouchSlots(std::span> slots, std::uint32_t touched) const { const auto epoch = useEpoch.load(std::memory_order_relaxed); + if (touched == epoch) return epoch; for (const auto& kindSlots : slots) { for (const auto slot : kindSlots) { if (slot < slotCap) slotUses[slot].store(epoch, std::memory_order_relaxed); } } + return epoch; } void BindlessHeap::evictLocked() { static const bool disabled = std::getenv("APS5_NO_HEAP_EVICTION") != nullptr; - if (disabled) return; const auto epoch = useEpoch.load(std::memory_order_relaxed); + if (disabled || submitter == nullptr || !submitter->HasTimeline() || evictScanEpoch == epoch) return; + GuestMemory::AssertGpuLockHeld("BindlessHeap::evictLocked"); + evictScanEpoch = epoch; std::vector> idle; for (std::uint32_t slot = SamplerKind; slot < imagePool.next && slot < owners.size(); ++slot) { if (owners[slot].key.owner == nullptr) continue; @@ -521,13 +525,14 @@ bool BindlessHeap::reclaimLocked(bool wait) { while (!retiring.empty() && retiring.front().serial != 0u && submitter != nullptr && submitter->HasTimeline()) { const auto serial = retiring.front().serial; if (!submitter->WaitSerialFor(serial, 0u)) { - if (!wait || reclaimed) break; + if (!wait || reclaimed || serial > submitter->Submissions()) break; submitter->WaitSerial(serial); ++counts.evictionWaits; } while (!retiring.empty() && retiring.front().serial != 0u && retiring.front().serial <= serial) { imagePool.free.push_back(retiring.front().slot); retiring.pop_front(); + --retiringAssigned; reclaimed = true; } } @@ -646,7 +651,9 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) offset = wrapRingOffset((chunkOf(offset) + 1u) * RingChunkBytes, bytes); ++counts.keptChunksSkipped; } - ringBatchBytes += bytes + (offset >= ringCursor ? offset - ringCursor : ringBytes - ringCursor + offset); + const auto consumed = bytes + (offset >= ringCursor ? offset - ringCursor : ringBytes - ringCursor + offset); + ringBatchBytes += consumed; + counts.ringBytes += consumed; counts.ringSpanPeakBytes = std::max(counts.ringSpanPeakBytes, bytes); ringCursor = offset + bytes; for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) enterRingChunk(chunk); @@ -1094,6 +1101,8 @@ void reportHeapStatistics() { totals.slotsEvicted += counts.slotsEvicted; totals.evictionWaits += counts.evictionWaits; totals.ringWaits += counts.ringWaits; + totals.ringBytes += counts.ringBytes; + totals.imageSlotsHeld += counts.imageSlotsHeld; totals.ringBatchPeakBytes = std::max(totals.ringBatchPeakBytes, counts.ringBatchPeakBytes); totals.ringSpanPeakBytes = std::max(totals.ringSpanPeakBytes, counts.ringSpanPeakBytes); } @@ -1108,15 +1117,16 @@ void reportHeapStatistics() { const auto slotsEvicted = windowDelta(totals.slotsEvicted, lastTotals.slotsEvicted); const auto evictionWaits = windowDelta(totals.evictionWaits, lastTotals.evictionWaits); const auto ringWaits = windowDelta(totals.ringWaits, lastTotals.ringWaits); + const auto ringMiB = windowDelta(totals.ringBytes, lastTotals.ringBytes) >> 20u; lastTotals = totals; const auto templates = ShaderRecompiler::HeapTemplateCounts(); std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired, %llu waits, peak %llu KiB per batch, largest span %llu KiB; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %u, %llu evicted (%llu waits); templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired, %llu MiB, %llu waits, since start at most %llu KiB per batch and %llu KiB per span; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %llu of %u held, %llu evicted (%llu waits); templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(spansExpired), printed(ringWaits), printed(totals.ringBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(spansExpired), printed(ringMiB), printed(ringWaits), printed(totals.ringBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { @@ -1301,11 +1311,13 @@ void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { useEpoch.fetch_add(1, std::memory_order_relaxed); counts.ringBatchPeakBytes = std::max(counts.ringBatchPeakBytes, ringBatchBytes); ringBatchBytes = 0; - for (auto entry = retiring.rbegin(); entry != retiring.rend() && entry->serial == 0u; ++entry) entry->serial = serial; - if (refused) { - reclaimLocked(false); - if (refused && retiring.empty()) evictLocked(); + if (refused && imagePool.Unused() + retiring.size() < 2u * static_cast(imageMargin())) evictLocked(); + for (auto entry = retiring.rbegin(); entry != retiring.rend() && entry->serial == 0u; ++entry) { + entry->serial = serial; + ++retiringAssigned; } + if (!retiring.empty()) reclaimLocked(false); + noteReleasedLocked(); for (std::size_t index = 0; index < ringChunks.size(); ++index) { if (!ringChunks[index].open && index != ringChunk) continue; ringChunks[index].recorder = &recorder; @@ -1316,7 +1328,9 @@ void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { BindlessHeap::Counts BindlessHeap::Statistics() const { std::lock_guard lock(mutex); - return counts; + auto snapshot = counts; + snapshot.imageSlotsHeld = imagePool.next - std::min(imagePool.next, SamplerKind + imagePool.free.size() + retiring.size()); + return snapshot; } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index d4acf7eb59a0..4ecda1316de3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -7159,7 +7159,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { takeHeapSlots(heap, stageState, stageBit, key); noteHeapSlotGenerations(heap, stageState); } else { - heap.TouchSlots(stageState.slots); + stageState.touchedEpoch = heap.TouchSlots(stageState.slots, stageState.touchedEpoch); } stageState.slotSerial = slotSerial; static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index c5efb5d11748..dd250983a175 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -604,7 +604,8 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi tableAlias = tables && key.first == Abi::FragmentDescriptorSet && (samplerAlias || imageAlias); if (tableAlias && binding == shader.bindings.end()) { const auto count = type.size() == 4 && (type[0] & 0xffffu) == spv::OpTypeArray ? module.constants.find(type[3]) : module.constants.end(); - Require(samplerAlias ? count != module.constants.end() && count->second == Abi::GpuSamplerHeapSlots : heapImageSlotsLength(module, type[3]), + const bool array = type.size() == 4 && (type[0] & 0xffffu) == spv::OpTypeArray; + Require(array && (samplerAlias ? count != module.constants.end() && count->second == Abi::GpuSamplerHeapSlots : heapImageSlotsLength(module, type[3])), "an image table's heap array length disagrees with the global heap"); continue; } diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 4beb9952298f..4952a1e60b5f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -336,10 +336,11 @@ bool idleSlotsEvicted(const Context& context, VkImageView view) { require(heap.SlotTexture(kind, slots[0]) == nullptr && heap.SlotGeneration(slots[0]) != idleGeneration, "an evicted slot names no texture and moves its generation"); require(heap.SlotTexture(kind, slots[5]) == held[5].get(), "the slot used again stays with its texture"); + require(BindlessHeap::NearlyFull(), "evicted slots no submission covers yet do not count as free"); require(take(7).has_value(), "the eighth texture takes the last never-used slot"); require(!take(8).has_value(), "an evicted slot is not reused before a submission covers the draws that used it"); - require(!BindlessHeap::NearlyFull(), "evicted slots waiting for the GPU keep the heap open"); submit(); + require(!BindlessHeap::NearlyFull(), "evicted slots a submission covers take the heap again"); require(recorder.WaitSerialFor(recorder.Submissions(), ~std::uint64_t{0}), "the submission completes"); const auto reused = take(8); require(reused.has_value() && std::find(slots.begin(), slots.begin() + 5, *reused) != slots.begin() + 5, From 3e7446f81ab94cd1998094fe2e18e321eedbb3b5 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 6 Nov 2026 00:31:06 +0530 Subject: [PATCH 121/269] perf(agc): skip GPU heap ring chunks a batch in flight still reads A draw that reuses a ring span it wrote earlier reopens the span's chunk, so the chunk takes the serial of the newest batch, and when the ring came round to it later it waited for a batch the GPU had only just started: every ring wait in a MCD2 run was of that kind. Like vkd3d-proton, which takes another scratch buffer instead of waiting for one the GPU still reads, the ring now skips such a chunk. Only when every chunk is taken or busy does it wait, and then on the chunk whose batch is oldest. APS5_HEAP_RING_MIB sets the ring size between 4 and 64 MiB (default 64, less when it sits in a smaller resource heap). MCD2 writes up to ~10 MiB in one batch and stops with "one batch's shader data exceeds its ring" at 8 MiB, so the default stays as large as the heap allows. --- .../Graphics/include/BindlessHeap.hpp | 2 +- .../Graphics/src/BindlessHeap.cpp | 73 ++++++++++++++++--- .../tests/BindlessHeapSlots.cpp | 46 +++++++++++- .../cmake/agc_driver_heap_slots_tests.cmake | 2 + docs/dev/ENVIRONMENT.md | 1 + 5 files changed, 111 insertions(+), 13 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index de5c42632ec0..7e7bb8e5085a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -94,7 +94,7 @@ class BindlessHeap { std::uint64_t ringWraps = 0, encodes = 0, encodedCopies = 0; std::uint64_t slotsFreed = 0, slotsReused = 0, slotsEvicted = 0, evictionWaits = 0; std::uint64_t ringWaits = 0, ringBatchPeakBytes = 0, ringSpanPeakBytes = 0, ringBytes = 0, imageSlotsHeld = 0; - std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0, bufferDescriptors = 0; + std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0, busyChunksSkipped = 0, bufferDescriptors = 0; }; Counts Statistics() const; std::size_t RingChunkCount() const { return ringChunks.size(); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 13423fdfe727..5a4ec2f3dc1f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -144,6 +144,18 @@ struct HeapSizes { std::size_t ringBytes = 0; }; +std::size_t ringTargetBytes() { + static const std::size_t bytes = [] { + std::size_t target = BindlessHeap::RingBytes; + if (const char* value = std::getenv("APS5_HEAP_RING_MIB")) { + const auto mib = std::strtoull(value, nullptr, 10); + if (mib != 0u) target = static_cast(std::clamp(mib, (2u * BindlessHeap::RingChunkBytes) >> 20u, BindlessHeap::RingBytes >> 20u)) << 20u; + } + return target / BindlessHeap::RingChunkBytes * BindlessHeap::RingChunkBytes; + }(); + return bytes; +} + VkDeviceSize alignUp(VkDeviceSize value, VkDeviceSize alignment) { return alignment == 0 ? value : (value + alignment - 1) / alignment * alignment; } @@ -163,7 +175,7 @@ HeapSizes heapLayout(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properti const auto offset = alignUp(sizes.resourceUsed + properties.minResourceHeapReservedRange, std::max(uniformAlignment, properties.resourceHeapAlignment)); if (offset >= properties.maxResourceHeapSize) return sizes; const auto room = static_cast(properties.maxResourceHeapSize - offset) / BindlessHeap::RingChunkBytes * BindlessHeap::RingChunkBytes; - const auto bytes = std::min(room, BindlessHeap::RingBytes); + const auto bytes = std::min(room, ringTargetBytes()); if (bytes < 2u * BindlessHeap::RingChunkBytes) return sizes; sizes.ringOffset = offset; sizes.ringBytes = bytes; @@ -257,7 +269,8 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { ringData = resourceHeap->Bytes().data() + ringHeapOffset; ringAlignment = static_cast(std::max({context.limits.minStorageBufferOffsetAlignment, context.limits.minUniformBufferOffsetAlignment, RingSpanAlignment})); } else { - ring = makeBuffer(RingBytes, ringUsage, true); + ringBytes = ringTargetBytes(); + ring = makeBuffer(ringBytes, ringUsage, true); ringData = ring->Bytes().data(); ringAlignment = static_cast(std::max(context.limits.minStorageBufferOffsetAlignment, RingSpanAlignment)); } @@ -640,16 +653,54 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) if (bytes > ringBytes / 2u) throw std::runtime_error("AGC bindless heap: per-draw data exceeds half the shader data ring"); std::lock_guard lock(mutex); auto offset = wrapRingOffset(alignUp(ringCursor, ringAlignment), bytes); - const auto keptAhead = [&] { + enum class Taken { No, Kept, Busy }; + const auto taken = [&](bool skipBusy) { for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) { - if (chunk == ringChunk ? offset < ringCursor : ringChunks[chunk].open) return true; + if (chunk == ringChunk ? offset < ringCursor : ringChunks[chunk].open) return Taken::Kept; } - return false; + if (!skipBusy) return Taken::No; + for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) { + auto& entry = ringChunks[chunk]; + if (chunk == ringChunk || entry.serial == 0u || entry.recorder == nullptr || !entry.recorder->HasTimeline()) continue; + if (!entry.recorder->WaitSerialFor(entry.serial, 0u)) return Taken::Busy; + entry.serial = 0u; + } + return Taken::No; }; - for (std::size_t skipped = 0; keptAhead(); ++skipped) { - if (skipped == ringChunks.size()) throw std::runtime_error("AGC bindless heap: one batch's shader data exceeds its ring"); + const auto start = offset; + const auto wraps = counts.ringWraps; + const auto keptSkips = counts.keptChunksSkipped; + const auto busySkips = counts.busyChunksSkipped; + auto reason = taken(true); + for (std::size_t skipped = 0; reason != Taken::No && skipped < ringChunks.size(); ++skipped) { offset = wrapRingOffset((chunkOf(offset) + 1u) * RingChunkBytes, bytes); - ++counts.keptChunksSkipped; + ++(reason == Taken::Busy ? counts.busyChunksSkipped : counts.keptChunksSkipped); + reason = taken(true); + } + if (reason != Taken::No) { + counts.ringWraps = wraps; + counts.keptChunksSkipped = keptSkips; + counts.busyChunksSkipped = busySkips; + std::optional oldest; + std::uint64_t oldestSerial = ~std::uint64_t{0}; + offset = start; + for (std::size_t step = 0; step < ringChunks.size(); ++step) { + if (taken(false) == Taken::No) { + std::uint64_t serial = 0; + for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) { + if (chunk != ringChunk) serial = std::max(serial, ringChunks[chunk].serial); + } + if (serial < oldestSerial) { + oldest = offset; + oldestSerial = serial; + } + } + offset = wrapRingOffset((chunkOf(offset) + 1u) * RingChunkBytes, bytes); + } + counts.ringWraps = wraps; + if (!oldest) throw std::runtime_error("AGC bindless heap: one batch's shader data exceeds its ring"); + offset = *oldest; + if (offset < start) ++counts.ringWraps; } const auto consumed = bytes + (offset >= ringCursor ? offset - ringCursor : ringBytes - ringCursor + offset); ringBatchBytes += consumed; @@ -1101,6 +1152,7 @@ void reportHeapStatistics() { totals.slotsEvicted += counts.slotsEvicted; totals.evictionWaits += counts.evictionWaits; totals.ringWaits += counts.ringWaits; + totals.busyChunksSkipped += counts.busyChunksSkipped; totals.ringBytes += counts.ringBytes; totals.imageSlotsHeld += counts.imageSlotsHeld; totals.ringBatchPeakBytes = std::max(totals.ringBatchPeakBytes, counts.ringBatchPeakBytes); @@ -1117,16 +1169,17 @@ void reportHeapStatistics() { const auto slotsEvicted = windowDelta(totals.slotsEvicted, lastTotals.slotsEvicted); const auto evictionWaits = windowDelta(totals.evictionWaits, lastTotals.evictionWaits); const auto ringWaits = windowDelta(totals.ringWaits, lastTotals.ringWaits); + const auto busySkips = windowDelta(totals.busyChunksSkipped, lastTotals.busyChunksSkipped); const auto ringMiB = windowDelta(totals.ringBytes, lastTotals.ringBytes) >> 20u; lastTotals = totals; const auto templates = ShaderRecompiler::HeapTemplateCounts(); std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired, %llu MiB, %llu waits, since start at most %llu KiB per batch and %llu KiB per span; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %llu of %u held, %llu evicted (%llu waits); templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired, %llu MiB, %llu waits, %llu busy chunks skipped, since start at most %llu KiB per batch and %llu KiB per span; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %llu of %u held, %llu evicted (%llu waits); templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(spansExpired), printed(ringMiB), printed(ringWaits), printed(totals.ringBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(spansExpired), printed(ringMiB), printed(ringWaits), printed(busySkips), printed(totals.ringBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 4952a1e60b5f..7a0a63cd425c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -254,7 +254,7 @@ bool ringLargeSpans(const Context& context) { require(heap.Held(pin), "the pinned span outlives the large span"); bool refused = false; try { - static_cast(heap.Allocate(AgcDriver::Graphics::BindlessHeap::RingBytes / sizeof(std::uint32_t) / 2u + 1u)); + static_cast(heap.Allocate(heap.RingChunkCount() * AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t) / 2u + 1u)); } catch (const std::runtime_error&) { refused = true; } @@ -286,6 +286,32 @@ void ringCurrentChunk(const Context& context) { require(heap.Held(live), "the current chunk's span is still held"); } +bool ringBusyChunks(const Context& context) { + BindlessHeap heap(context); + if (heap.RingChunkCount() < 3u) return false; + Recorder recorder(context, true); + if (!recorder.HasTimeline()) return false; + constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); + const auto unreached = recorder.Submissions() + (1ull << 40u); + BindlessHeap::SpanMark busy; + static_cast(heap.Allocate(16u, busy)); + static_cast(heap.Allocate(chunkWords)); + heap.Submitted(recorder, unreached); + heap.Submitted(recorder, 0u); + BindlessHeap::SpanMark fill; + const auto wraps = heap.Statistics().ringWraps; + BindlessHeap::DataSpan last{}; + while (heap.Statistics().ringWraps == wraps) { + last = heap.Allocate(chunkWords, fill); + heap.Submitted(recorder, 0u); + } + require(last.offset >= AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips the chunk a batch still in flight reads"); + const auto counts = heap.Statistics(); + require(counts.busyChunksSkipped >= 1u && counts.ringWaits == 0u, "the busy chunk is skipped without a wait"); + require(heap.Held(busy), "a span in the skipped busy chunk is still held"); + return true; +} + void heapComesBack(const Context& context, VkImageView view) { auto& heap = BindlessHeap::For(context); const auto kind = Abi::FirstImageBinding; @@ -440,7 +466,8 @@ void twoHeapsComeBack(const Context& context, VkImageView view) { int main(int argc, char** argv) { const std::string mode = argc > 1 ? argv[1] : ""; const bool largeSpans = mode == "ring-large-spans"; - const bool comesBack = !mode.empty() && !largeSpans; + const bool busyChunks = mode == "ring-busy-chunks"; + const bool comesBack = !mode.empty() && !largeSpans && !busyChunks; try { SetTestEnvironment("APS5_GPU_HEAP", "1"); SetTestEnvironment("APS5_HEAP_SLOT_CAP", comesBack ? "8" : "1"); @@ -450,6 +477,21 @@ int main(int argc, char** argv) { std::printf("skipped, the device has no VK_EXT_descriptor_heap\n"); return VulkanTestSkipped; } + if (busyChunks) { + bool ran = false; + { + const auto context = device->graphicsContext(); + ran = ringBusyChunks(context); + device->WaitIdle(); + } + device.reset(); + if (!ran) { + std::printf("skipped, the heap ring has fewer than three chunks or the recorder no timeline\n"); + return VulkanTestSkipped; + } + std::cout << "bindless heap ring busy chunk tests passed\n"; + return 0; + } if (largeSpans) { bool ran = false; { diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake index c8db1612cd07..8b9e7cfee37b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake @@ -22,6 +22,8 @@ if(BUILD_TESTING) agc_add_default_test(agc_driver_heap_slots_tests) agc_add_env_test(agc_driver_heap_slots_ring_large_spans agc_driver_heap_slots_tests ARGS ring-large-spans ENV ANYPS5_NO_SHADER_CACHE=1) + agc_add_env_test(agc_driver_heap_slots_ring_busy_chunks agc_driver_heap_slots_tests + ARGS ring-busy-chunks ENV ANYPS5_NO_SHADER_CACHE=1 TIMEOUT 60) foreach(agcHeapSlotsMode IN ITEMS comes-back storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release idle-slots-evicted) string(REPLACE "-" "_" agcHeapSlotsName "${agcHeapSlotsMode}") agc_add_env_test(agc_driver_heap_slots_${agcHeapSlotsName} agc_driver_heap_slots_tests diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index c9adec8b66e5..dcb6a9f314f8 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -201,6 +201,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first | | `APS5_HEAP_WALK_MEMO_MB` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | 256 | MiB each thread's GPU heap walk memo may hold across both its generations before the previous generation and then the oldest walks are dropped (0 keeps them until the 16,384-key cap rotates them out) | | `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a stage needing more image slots than this takes the per-draw path | +| `APS5_HEAP_RING_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 64 | MiB of the GPU heap's per-draw shader data ring, between 4 and 64; a ring inside the resource heap also stays within the device's heap size, in whole 2 MiB chunks; one span may take at most half the ring and one batch's spans must fit in it | | `APS5_NO_HEAP_EVICTION` | flag | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | unset | set: a nearly full GPU heap no longer evicts image slots no draw used for two submissions, so draws take the per-draw path until owners release slots | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | From fcb483e308dd1f69650d61d8d871dcfc3075efbb Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 6 Nov 2026 01:08:37 +0530 Subject: [PATCH 122/269] perf(agc): move GPU heap shader data into a growing upload pool Shader data, flattened SRT data and table maps lived in the descriptor ring inside the resource heap. A batch writing more than the ring held aborted the run, and the ring took heap room from images. They now go into a pool of 2 MiB blocks, the way vkd3d-proton's uniform upload pool works. A batch takes new blocks instead of waiting, a span larger than a block gets a block of its own, a block is reused once the GPU has finished the batches that read it, and idle blocks over 32 MiB are freed. Shaders read the data through 64-bit addresses pushed per draw (shader data, table map, addressed flattened SRT), so the shared ring address push item is gone; the push-data size stays about the same. The ring inside the heap now holds only per-draw buffer descriptors and defaults to 16 MiB. The shader cache format moves to 59. --- .../Execution/src/VulkanDevice.cpp | 5 +- .../Graphics/include/BindlessHeap.hpp | 35 +++- .../Graphics/include/ShaderResources.hpp | 12 +- .../Graphics/src/BindlessHeap.cpp | 192 ++++++++++++++---- .../Graphics/src/ShaderResources.cpp | 29 ++- .../tests/BindlessHeapSlots.cpp | 95 +++++++-- .../tests/PushDataPlacements.cpp | 14 +- .../tests/execution/HeapTableStageReuse.cpp | 4 +- core/shader/recompiler/RuntimeAbi.hpp | 7 +- core/shader/recompiler/ShaderDiskCache.hpp | 2 +- .../SpirvMemory/SpirvBufferAccess.hpp | 2 +- .../src/SpirvMemory/SpirvBufferAccess.cpp | 10 +- .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 2 +- docs/dev/ENVIRONMENT.md | 2 +- 14 files changed, 306 insertions(+), 105 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 637f14d7c2fb..85cced74c660 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -2202,10 +2202,9 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : if (descriptorHeapFeatures.descriptorHeap == VK_TRUE && heapMaintenance5.maintenance5 == VK_TRUE && Graphics::BindlessHeap::Fits(state->descriptorHeapProperties)) { state->descriptorHeap = true; state->maintenance5 = true; - if (Graphics::BindlessHeap::RingInResourceHeap(state->descriptorHeapProperties, state->properties.limits.minUniformBufferOffsetAlignment)) { - state->heapDataUniformDwords = std::min(HeapDataUniformDwordCap, state->properties.limits.maxUniformBufferRange / 4u); + state->heapDataUniformDwords = std::min(HeapDataUniformDwordCap, state->properties.limits.maxUniformBufferRange / 4u); + if (Graphics::BindlessHeap::RingInResourceHeap(state->descriptorHeapProperties, state->properties.limits.minUniformBufferOffsetAlignment)) state->heapBufferDescriptors = state->descriptorHeapProperties.bufferDescriptorSize == Graphics::BindlessHeap::BufferSlotBytes; - } deviceExtensions.push_back(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME); for (const char* required : {VK_KHR_MAINTENANCE_5_EXTENSION_NAME, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME}) { if (std::find_if(deviceExtensions.begin(), deviceExtensions.end(), [&](const char* name) { return std::strcmp(name, required) == 0; }) == deviceExtensions.end()) deviceExtensions.push_back(required); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 7e7bb8e5085a..0c4bb7e162fa 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include namespace ShaderRecompiler { @@ -50,9 +51,7 @@ class BindlessHeap { const ShaderRecompiler::StagePushPlacement* placement = nullptr) const; void WritePixelLdsBuffer(VkDeviceAddress address, VkDeviceSize bytes); void WriteMeshWindowBuffer(VkDeviceAddress address, VkDeviceSize bytes); - VkDeviceAddress RingAddress() const; - VkBuffer RingBuffer() const; - VkDeviceSize RingOffset() const; + std::pair DataLocation(VkDeviceAddress address) const; std::optional TextureSlot(std::uint32_t kind, Texture* texture, VkImageView view, VkImageLayout layout); std::optional StorageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view); @@ -75,14 +74,18 @@ class BindlessHeap { struct DataSpan { std::uint32_t offset = 0; std::span words; + VkDeviceAddress address = 0; }; DataSpan Allocate(std::size_t words); struct SpanMark { std::uint32_t offset = 0; std::uint32_t words = 0; std::uint64_t entry = 0; + std::uint32_t block = 0; + VkDeviceAddress address = 0; }; DataSpan Allocate(std::size_t words, SpanMark& mark); + DataSpan RingAllocate(std::size_t words, SpanMark& mark); bool Held(const SpanMark& mark); std::uint32_t RingBufferDescriptors(std::span buffers, SpanMark& mark); static constexpr std::uint32_t BufferSlotBytes = 16u; @@ -95,18 +98,21 @@ class BindlessHeap { std::uint64_t slotsFreed = 0, slotsReused = 0, slotsEvicted = 0, evictionWaits = 0; std::uint64_t ringWaits = 0, ringBatchPeakBytes = 0, ringSpanPeakBytes = 0, ringBytes = 0, imageSlotsHeld = 0; std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0, busyChunksSkipped = 0, bufferDescriptors = 0; + std::uint64_t poolBytes = 0, poolBatchPeakBytes = 0, poolBlocksMade = 0, poolBlocksRecycled = 0, poolBlocksFreed = 0, poolBlocksHeld = 0, poolBlockBytes = 0; }; Counts Statistics() const; std::size_t RingChunkCount() const { return ringChunks.size(); } static constexpr std::size_t RingBytes = 64u << 20u; + static constexpr std::size_t DefaultRingBytes = 16u << 20u; + static constexpr std::size_t PoolBlockBytes = 2u << 20u; + static constexpr std::size_t PoolIdleBytes = 32u << 20u; static constexpr std::size_t RingChunkBytes = 2u << 20u; private: Context context; - std::unique_ptr ring; std::byte* ringData = nullptr; - std::size_t ringBytes = RingBytes; + std::size_t ringBytes = 0; VkDeviceSize ringHeapOffset = 0; bool ringInHeap = false; std::unique_ptr resourceHeap; @@ -135,6 +141,25 @@ class BindlessHeap { void enterRingChunk(std::size_t index); std::size_t wrapRingOffset(std::size_t offset, std::size_t bytes); std::size_t ringCursor = 0; + struct PoolBlock { + std::unique_ptr buffer; + std::byte* data = nullptr; + VkDeviceAddress address = 0; + std::size_t bytes = 0; + std::size_t cursor = 0; + std::uint64_t generation = 0; + Recorder* recorder = nullptr; + std::uint64_t serial = 0; + bool open = false; + }; + std::vector poolBlocks; + std::size_t poolCurrent = ~std::size_t{0}; + std::uint32_t poolAlignment = 256; + bool poolDeviceLocal = true; + std::size_t poolBatchBytes = 0; + std::size_t takePoolBlockLocked(std::size_t bytes); + bool poolBlockDoneLocked(PoolBlock& block); + void trimPoolLocked(); std::uint32_t ringAlignment = 256; mutable std::mutex mutex; std::atomic slotSerial{1}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 7cefeb89fe71..3429ecb960f8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -224,7 +224,7 @@ class ShaderResources { DescriptorCache::SetAllocation allocation; std::vector snapshots; bool addressOffsets = false; - std::array heapOffsets{}; + std::array heapOffsets{}; std::vector addressOverrides; ~DrawBindings(); }; @@ -669,7 +669,7 @@ class ShaderResources { }; bool splitSets = false; bool heapStage = false; - std::array heapOffsets{}; + std::array heapOffsets{}; void writeHeapStage(const CompiledShader& shader); struct RingDescriptors { std::vector ranges; @@ -694,7 +694,7 @@ class ShaderResources { RingDescriptors descriptors; }; std::array heapStages; - std::uint32_t heapSpan(HeapStageState::KeptSpan& kept, std::span words); + std::uint64_t heapSpan(HeapStageState::KeptSpan& kept, std::span words); bool ownsHeapBinding(const Binding& binding, VkShaderStageFlags stageBit) const; VkImageView heapPlaceholderView(std::uint32_t kind) const; VkImageView heapSampledView(std::size_t index) const; @@ -732,16 +732,16 @@ class ShaderResources { std::array, ShaderRecompiler::RuntimeAbi::StageCount> stageDataWords; std::array stageDataIndex{}; std::array heapSrtDwords{}; - std::array heapTableMaps{}; + std::array heapTableMaps{}; std::array heapTableMapSet{}; void writeHeapTableMap(const CompiledShader& shader, std::size_t stageIndex); void writeBufferAddresses(std::span words, std::uint32_t dataStage, const std::vector* overrides, std::vector* ranges = nullptr) const; VkDeviceAddressRangeEXT srtRange(std::size_t stage) const; std::uint32_t ringDescriptors(std::size_t stage, const std::vector* overrides, RingDescriptors& kept) const; - std::array heapSrtOffsets{}; + std::array heapSrtOffsets{}; std::array ringDescriptorStages{}; - std::array addressedOffsets(const std::vector* overrides) const; + std::array addressedOffsets(const std::vector* overrides) const; struct FaultDescriptor { std::size_t write; std::size_t buffer; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 5a4ec2f3dc1f..f23e7780f4e9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -146,7 +146,7 @@ struct HeapSizes { std::size_t ringTargetBytes() { static const std::size_t bytes = [] { - std::size_t target = BindlessHeap::RingBytes; + std::size_t target = BindlessHeap::DefaultRingBytes; if (const char* value = std::getenv("APS5_HEAP_RING_MIB")) { const auto mib = std::strtoull(value, nullptr, 10); if (mib != 0u) target = static_cast(std::clamp(mib, (2u * BindlessHeap::RingChunkBytes) >> 20u, BindlessHeap::RingBytes >> 20u)) << 20u; @@ -267,13 +267,12 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { ringHeapOffset = sizes.ringOffset; ringBytes = sizes.ringBytes; ringData = resourceHeap->Bytes().data() + ringHeapOffset; - ringAlignment = static_cast(std::max({context.limits.minStorageBufferOffsetAlignment, context.limits.minUniformBufferOffsetAlignment, RingSpanAlignment})); } else { - ringBytes = ringTargetBytes(); - ring = makeBuffer(ringBytes, ringUsage, true); - ringData = ring->Bytes().data(); - ringAlignment = static_cast(std::max(context.limits.minStorageBufferOffsetAlignment, RingSpanAlignment)); + ringBytes = 0; } + ringAlignment = static_cast(std::max(BufferSlotBytes, heapProperties.bufferDescriptorAlignment)); + poolAlignment = static_cast(std::max({context.limits.minStorageBufferOffsetAlignment, context.limits.minUniformBufferOffsetAlignment, RingSpanAlignment})); + poolDeviceLocal = !hostDescriptors; ringChunks.resize(ringBytes / RingChunkBytes); slotCap = configuredSlotCap(sizes.imageSlots); deviceImageSlots.store(slotCap, std::memory_order_relaxed); @@ -634,6 +633,17 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words) { bool BindlessHeap::Held(const SpanMark& mark) { if (mark.entry == 0u || mark.words == 0u) return false; + if (mark.block != 0u) { + std::lock_guard lock(mutex); + const auto index = mark.block - 1u; + if (index >= poolBlocks.size() || poolBlocks[index].generation != mark.entry) { + ++counts.spansExpired; + return false; + } + poolBlocks[index].open = true; + ++counts.spansKept; + return true; + } const auto first = chunkOf(mark.offset); const auto last = lastChunkOf(mark.offset, static_cast(mark.words) * sizeof(std::uint32_t)); std::lock_guard lock(mutex); @@ -649,8 +659,106 @@ bool BindlessHeap::Held(const SpanMark& mark) { } BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) { - const auto bytes = ringInHeap ? alignUp(words * sizeof(std::uint32_t), RingSpanAlignment) : words * sizeof(std::uint32_t); - if (bytes > ringBytes / 2u) throw std::runtime_error("AGC bindless heap: per-draw data exceeds half the shader data ring"); + const auto bytes = alignUp(std::max(words, 1u) * sizeof(std::uint32_t), RingSpanAlignment); + std::lock_guard lock(mutex); + if (poolCurrent >= poolBlocks.size() || alignUp(poolBlocks[poolCurrent].cursor, poolAlignment) + bytes > poolBlocks[poolCurrent].bytes) poolCurrent = takePoolBlockLocked(bytes); + auto& block = poolBlocks[poolCurrent]; + const auto offset = static_cast(alignUp(block.cursor, poolAlignment)); + block.cursor = offset + bytes; + block.open = true; + ++counts.spansWritten; + counts.poolBytes += bytes; + counts.ringSpanPeakBytes = std::max(counts.ringSpanPeakBytes, bytes); + poolBatchBytes += bytes; + mark = {static_cast(offset), static_cast(words), block.generation, static_cast(poolCurrent + 1u), block.address + offset}; + return {static_cast(offset), std::span(reinterpret_cast(block.data + offset), words), mark.address}; +} + +bool BindlessHeap::poolBlockDoneLocked(PoolBlock& block) { + if (block.serial == 0u) return true; + if (block.recorder == nullptr || !block.recorder->HasTimeline() || !block.recorder->WaitSerialFor(block.serial, 0u)) return false; + block.serial = 0u; + return true; +} + +std::size_t BindlessHeap::takePoolBlockLocked(std::size_t bytes) { + const auto need = std::max(bytes, PoolBlockBytes); + auto best = poolBlocks.size(); + std::size_t vacant = poolBlocks.size(); + for (std::size_t index = 0; index < poolBlocks.size(); ++index) { + auto& block = poolBlocks[index]; + if (block.buffer == nullptr) { + vacant = std::min(vacant, index); + continue; + } + if (index == poolCurrent || block.open || block.bytes < need) continue; + if (best < poolBlocks.size() && poolBlocks[best].bytes <= block.bytes) continue; + if (poolBlockDoneLocked(block)) best = index; + } + if (best < poolBlocks.size()) { + auto& block = poolBlocks[best]; + block.cursor = 0; + ++block.generation; + ++counts.poolBlocksRecycled; + return best; + } + const auto size = need == PoolBlockBytes ? PoolBlockBytes : static_cast(alignUp(need, PoolBlockBytes)); + constexpr VkBufferUsageFlags usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + constexpr VkMemoryPropertyFlags deviceVisible = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + std::unique_ptr buffer; + if (poolDeviceLocal) { + try { + buffer = std::make_unique(context, size, usage, deviceVisible); + } catch (const std::exception&) { + } + } + if (buffer == nullptr) buffer = std::make_unique(context, size, usage); + if (vacant == poolBlocks.size()) poolBlocks.emplace_back(); + auto& block = poolBlocks[vacant]; + block.data = buffer->Bytes().data(); + block.address = buffer->DeviceAddress(); + block.buffer = std::move(buffer); + block.bytes = size; + block.cursor = 0; + ++block.generation; + block.recorder = nullptr; + block.serial = 0u; + block.open = false; + ++counts.poolBlocksMade; + return vacant; +} + +void BindlessHeap::trimPoolLocked() { + std::size_t idle = 0; + for (std::size_t index = 0; index < poolBlocks.size(); ++index) { + const auto& block = poolBlocks[index]; + if (block.buffer != nullptr && index != poolCurrent && !block.open) idle += block.bytes; + } + for (std::size_t index = poolBlocks.size(); index-- > 0u && idle > PoolIdleBytes;) { + auto& block = poolBlocks[index]; + if (block.buffer == nullptr || index == poolCurrent || block.open || !poolBlockDoneLocked(block)) continue; + idle -= block.bytes; + block.buffer.reset(); + block.data = nullptr; + block.address = 0; + block.bytes = 0; + ++block.generation; + ++counts.poolBlocksFreed; + } +} + +std::pair BindlessHeap::DataLocation(VkDeviceAddress address) const { + std::lock_guard lock(mutex); + for (const auto& block : poolBlocks) { + if (block.buffer != nullptr && address >= block.address && address < block.address + block.bytes) return {block.buffer->Handle(), address - block.address}; + } + throw std::runtime_error("AGC bindless heap: shader data lies outside every data pool block"); +} + +BindlessHeap::DataSpan BindlessHeap::RingAllocate(std::size_t words, SpanMark& mark) { + Require(ringInHeap, "the GPU heap has no descriptor ring"); + const auto bytes = alignUp(words * sizeof(std::uint32_t), RingSpanAlignment); + if (bytes > ringBytes / 2u) throw std::runtime_error("AGC bindless heap: one draw's buffer descriptors exceed half the descriptor ring"); std::lock_guard lock(mutex); auto offset = wrapRingOffset(alignUp(ringCursor, ringAlignment), bytes); enum class Taken { No, Kept, Busy }; @@ -698,20 +806,19 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) offset = wrapRingOffset((chunkOf(offset) + 1u) * RingChunkBytes, bytes); } counts.ringWraps = wraps; - if (!oldest) throw std::runtime_error("AGC bindless heap: one batch's shader data exceeds its ring"); + if (!oldest) throw std::runtime_error("AGC bindless heap: one batch's buffer descriptors exceed the descriptor ring"); offset = *oldest; if (offset < start) ++counts.ringWraps; } const auto consumed = bytes + (offset >= ringCursor ? offset - ringCursor : ringBytes - ringCursor + offset); ringBatchBytes += consumed; counts.ringBytes += consumed; - counts.ringSpanPeakBytes = std::max(counts.ringSpanPeakBytes, bytes); ringCursor = offset + bytes; for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) enterRingChunk(chunk); auto* base = reinterpret_cast(ringData + offset); ++counts.spansWritten; - mark = {static_cast(offset), static_cast(words), ringEntries}; - return {static_cast(offset), std::span(base, words)}; + mark = {static_cast(offset), static_cast(words), ringEntries, 0u, resourceHeap->DeviceAddress() + ringHeapOffset + offset}; + return {static_cast(offset), std::span(base, words), mark.address}; } std::size_t BindlessHeap::wrapRingOffset(std::size_t offset, std::size_t bytes) { @@ -724,10 +831,10 @@ void BindlessHeap::enterRingChunk(std::size_t index) { if (index == ringChunk) return; ringChunk = index; auto& chunk = ringChunks[index]; - if (chunk.open) throw std::runtime_error("AGC bindless heap: one batch's shader data exceeds its ring"); + if (chunk.open) throw std::runtime_error("AGC bindless heap: one batch's buffer descriptors exceed the descriptor ring"); if (chunk.serial != 0u) { if (!chunk.recorder->HasTimeline()) - throw std::runtime_error("AGC bindless heap: the shader data ring needs the recorder timeline to wait for a batch"); + throw std::runtime_error("AGC bindless heap: the descriptor ring needs the recorder timeline to wait for a batch"); if (!chunk.recorder->WaitSerialFor(chunk.serial, 0u)) { chunk.recorder->WaitSerial(chunk.serial); ++counts.ringWaits; @@ -925,15 +1032,14 @@ VkDescriptorSetAndBindingMappingEXT ringDescriptorMapping(std::uint32_t set, std return mapping; } -VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, VkDeviceSize heapOffset, const ShaderRecompiler::StagePushPlacement* placement) { +VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, const ShaderRecompiler::StagePushPlacement* placement) { VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; mapping.descriptorSet = Abi::GpuDataSet; mapping.firstBinding = binding; mapping.bindingCount = 1; mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_RESOURCE_HEAP_DATA_EXT; - mapping.sourceData.heapData.heapOffset = static_cast(heapOffset); - mapping.sourceData.heapData.pushOffset = rootItemOffset(placement, Abi::RootItem::ShaderData); + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; + mapping.sourceData.pushAddressOffset = rootItemOffset(placement, Abi::RootItem::ShaderData); return mapping; } @@ -968,7 +1074,7 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, .workgroupAddress = workgroupAddressOffset != ~0u, .gdsAddress = rootGds, .faultAddress = rootFault, .pixelLds = pixelLds, .meshWindow = meshWindow, .scratchPool = scratchPool}; if (!heapBindings(spirv, roots, use)) return false; - if ((!use.dataUniforms.empty() || !use.ringDescriptors.empty()) && !ringInHeap) return false; + if (!use.ringDescriptors.empty() && !ringInHeap) return false; if (!use.ringDescriptors.empty() && context.descriptorHeapProperties.bufferDescriptorSize != BufferSlotBytes) return false; constexpr auto bindingCount = static_cast(Abi::Binding::Count); constexpr VkSpirvResourceTypeFlagsEXT imageResources = VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT | @@ -982,7 +1088,7 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, heapMapping(Abi::FragmentDescriptorSet, binding, VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT, 0, samplerHeapStride)); else mappings.push_back(heapMapping(Abi::FragmentDescriptorSet, binding, imageResources, 0, imageHeapStride)); } - for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, ringHeapOffset, placement)); + for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, placement)); std::sort(use.ringDescriptors.begin(), use.ringDescriptors.end()); for (const auto& [set, binding] : use.ringDescriptors) mappings.push_back(ringDescriptorMapping(set, binding, ringHeapOffset, placement)); if (use.workgroupMemory) @@ -1003,8 +1109,8 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, } std::uint32_t BindlessHeap::RingBufferDescriptors(std::span buffers, SpanMark& mark) { - Require(ringInHeap && context.descriptorHeapProperties.bufferDescriptorSize == BufferSlotBytes, "ring buffer descriptors need the shader-data ring inside the resource heap"); - const auto span = Allocate(buffers.size() * (BufferSlotBytes / sizeof(std::uint32_t)), mark); + Require(ringInHeap && context.descriptorHeapProperties.bufferDescriptorSize == BufferSlotBytes, "ring buffer descriptors need the descriptor ring inside the resource heap"); + const auto span = RingAllocate(buffers.size() * (BufferSlotBytes / sizeof(std::uint32_t)), mark); Require(span.offset % BufferSlotBytes == 0u, "a ring buffer descriptor span is misaligned"); struct ResourcesStorage {}; struct RangesStorage {}; @@ -1157,6 +1263,13 @@ void reportHeapStatistics() { totals.imageSlotsHeld += counts.imageSlotsHeld; totals.ringBatchPeakBytes = std::max(totals.ringBatchPeakBytes, counts.ringBatchPeakBytes); totals.ringSpanPeakBytes = std::max(totals.ringSpanPeakBytes, counts.ringSpanPeakBytes); + totals.poolBytes += counts.poolBytes; + totals.poolBlocksMade += counts.poolBlocksMade; + totals.poolBlocksRecycled += counts.poolBlocksRecycled; + totals.poolBlocksFreed += counts.poolBlocksFreed; + totals.poolBlocksHeld += counts.poolBlocksHeld; + totals.poolBlockBytes += counts.poolBlockBytes; + totals.poolBatchPeakBytes = std::max(totals.poolBatchPeakBytes, counts.poolBatchPeakBytes); } } const auto windowDelta = [](std::uint64_t now, std::uint64_t before) { return now >= before ? now - before : now; }; @@ -1171,15 +1284,19 @@ void reportHeapStatistics() { const auto ringWaits = windowDelta(totals.ringWaits, lastTotals.ringWaits); const auto busySkips = windowDelta(totals.busyChunksSkipped, lastTotals.busyChunksSkipped); const auto ringMiB = windowDelta(totals.ringBytes, lastTotals.ringBytes) >> 20u; + const auto poolMiB = windowDelta(totals.poolBytes, lastTotals.poolBytes) >> 20u; + const auto poolMade = windowDelta(totals.poolBlocksMade, lastTotals.poolBlocksMade); + const auto poolRecycled = windowDelta(totals.poolBlocksRecycled, lastTotals.poolBlocksRecycled); + const auto poolFreed = windowDelta(totals.poolBlocksFreed, lastTotals.poolBlocksFreed); lastTotals = totals; const auto templates = ShaderRecompiler::HeapTemplateCounts(); std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); ring spans %llu written / %llu kept / %llu expired, %llu MiB, %llu waits, %llu busy chunks skipped, since start at most %llu KiB per batch and %llu KiB per span; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %llu of %u held, %llu evicted (%llu waits); templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; descriptor ring %llu MiB, %llu waits, %llu busy chunks skipped, since start at most %llu KiB per batch; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %llu of %u held, %llu evicted (%llu waits); templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(spansExpired), printed(ringMiB), printed(ringWaits), printed(busySkips), printed(totals.ringBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(ringMiB), printed(ringWaits), printed(busySkips), printed(totals.ringBatchPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { @@ -1346,18 +1463,6 @@ void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { context.Function("vkCmdBindSamplerHeapEXT")(commands, &info); } -VkDeviceAddress BindlessHeap::RingAddress() const { - return ringInHeap ? resourceHeap->DeviceAddress() + ringHeapOffset : ring->DeviceAddress(); -} - -VkBuffer BindlessHeap::RingBuffer() const { - return ringInHeap ? resourceHeap->Handle() : ring->Handle(); -} - -VkDeviceSize BindlessHeap::RingOffset() const { - return ringInHeap ? ringHeapOffset : 0; -} - void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { std::lock_guard lock(mutex); submitter = &recorder; @@ -1377,11 +1482,26 @@ void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { ringChunks[index].serial = serial; ringChunks[index].open = index == ringChunk; } + counts.poolBatchPeakBytes = std::max(counts.poolBatchPeakBytes, poolBatchBytes); + poolBatchBytes = 0; + for (std::size_t index = 0; index < poolBlocks.size(); ++index) { + auto& block = poolBlocks[index]; + if (block.buffer == nullptr || (!block.open && index != poolCurrent)) continue; + block.recorder = &recorder; + block.serial = serial; + block.open = index == poolCurrent; + } + trimPoolLocked(); } BindlessHeap::Counts BindlessHeap::Statistics() const { std::lock_guard lock(mutex); auto snapshot = counts; + for (const auto& block : poolBlocks) { + if (block.buffer == nullptr) continue; + ++snapshot.poolBlocksHeld; + snapshot.poolBlockBytes += block.bytes; + } snapshot.imageSlotsHeld = imagePool.next - std::min(imagePool.next, SamplerKind + imagePool.free.size() + retiring.size()); return snapshot; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 4ecda1316de3..4c6e5b93bcbd 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6590,7 +6590,7 @@ void ShaderResources::RefreshMovedAddresses(DrawBindings& rewritten) const { if (rewritten.addressOffsets) rewritten.heapOffsets = addressedOffsets(&rewritten.addressOverrides); } -std::array ShaderResources::addressedOffsets(const std::vector* overrides) const { +std::array ShaderResources::addressedOffsets(const std::vector* overrides) const { auto offsets = heapOffsets; auto& heap = BindlessHeap::For(context); for (std::size_t stage = 0; stage < stageDataWords.size(); ++stage) { @@ -6599,7 +6599,7 @@ std::array ShaderR writeBufferAddresses(words, static_cast(stage), overrides); auto span = heap.Allocate(words.size()); std::memcpy(span.words.data(), words.data(), words.size() * sizeof(std::uint32_t)); - offsets[stageDataIndex[stage]] = span.offset; + offsets[stageDataIndex[stage]] = span.address; } for (std::size_t stage = 0; stage < ringDescriptorStages.size(); ++stage) { if (!ringDescriptorStages[stage]) continue; @@ -6705,7 +6705,7 @@ VkDeviceAddressRangeEXT ShaderResources::srtRange(std::size_t stage) const { Require(empty != 0, "the empty buffer has no device address"); return {empty, EmptyBufferBytes}; } - return {BindlessHeap::For(context).RingAddress() + heapSrtOffsets[stage], bytes}; + return {heapSrtOffsets[stage], bytes}; } std::uint32_t ShaderResources::ringDescriptors(std::size_t stage, const std::vector* overrides, RingDescriptors& kept) const { @@ -6726,15 +6726,13 @@ std::uint32_t ShaderResources::ringDescriptors(std::size_t stage, const std::vec std::pair ShaderResources::shaderDataLocation(const CompiledShader& shader, const DrawBindings* rewritten) const { if (!heapStage || !HeapShader(shader)) return {shaderDataBuffer(shader), 0}; const auto& offsets = rewritten != nullptr && rewritten->addressOffsets ? rewritten->heapOffsets : heapOffsets; - const auto& heap = BindlessHeap::For(context); - return {heap.RingBuffer(), heap.RingOffset() + offsets[DataOffsetIndex(HeapStageIndex(shader.stage), ShaderRecompiler::RuntimeAbi::Binding::ShaderData)]}; + return BindlessHeap::For(context).DataLocation(offsets[DataOffsetIndex(HeapStageIndex(shader.stage), ShaderRecompiler::RuntimeAbi::Binding::ShaderData)]); } void ShaderResources::PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const { namespace Abi = ShaderRecompiler::RuntimeAbi; if (!heapStage) return; const auto& offsets = rewritten != nullptr && rewritten->addressOffsets ? rewritten->heapOffsets : heapOffsets; - VkDeviceAddress ring = 0; VkDeviceAddress table = 0; VkDeviceAddress fault = 0; std::uint32_t tableDwords = 0; @@ -6785,20 +6783,17 @@ void ShaderResources::PatchDataAddresses(std::span(address)); put(item, 1u, static_cast(address >> 32u)); }; - if (placement.Item(Abi::RootItem::RingAddress) != Abi::NoPushPosition) { - if (ring == 0) ring = BindlessHeap::For(context).RingAddress(); - putAddress(Abi::RootItem::RingAddress, ring); - } putAddress(Abi::RootItem::PagetableAddress, table); putAddress(Abi::RootItem::FaultAddress, fault); put(Abi::RootItem::PagetableDwords, 0u, tableDwords); if (placement.Item(Abi::RootItem::GdsAddress) != Abi::NoPushPosition) putAddress(Abi::RootItem::GdsAddress, gdsAddress()); if (shader.program == nullptr || !shader.program->dataAddressPush) continue; const auto stage = HeapStageIndex(shader.stage); - put(Abi::RootItem::ShaderData, 0u, offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); - put(Abi::RootItem::FlattenedSrt, 0u, offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)]); + putAddress(Abi::RootItem::ShaderData, offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); + put(Abi::RootItem::FlattenedSrt, 0u, static_cast(offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)])); + putAddress(Abi::RootItem::SrtAddress, offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)]); put(Abi::RootItem::SrtDwords, 0u, heapSrtDwords[stage]); - put(Abi::RootItem::TableMap, 0u, heapTableMapSet[stage] ? heapTableMaps[stage] : 0u); + putAddress(Abi::RootItem::TableMap, heapTableMapSet[stage] ? heapTableMaps[stage] : offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); writePushedData(bytes, shader, placement.pushed); rooted = true; } @@ -6911,13 +6906,13 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ heapTableMapSet[stageIndex] = true; } -std::uint32_t ShaderResources::heapSpan(HeapStageState::KeptSpan& kept, std::span words) { +std::uint64_t ShaderResources::heapSpan(HeapStageState::KeptSpan& kept, std::span words) { auto& heap = BindlessHeap::For(context); - if (std::ranges::equal(kept.words, words) && heap.Held(kept.mark)) return kept.mark.offset; + if (std::ranges::equal(kept.words, words) && heap.Held(kept.mark)) return kept.mark.address; auto span = heap.Allocate(words.size(), kept.mark); std::memcpy(span.words.data(), words.data(), words.size() * sizeof(std::uint32_t)); kept.words.assign(words.begin(), words.end()); - return span.offset; + return span.address; } bool ShaderResources::ownsHeapBinding(const Binding& binding, VkShaderStageFlags stageBit) const { @@ -7192,7 +7187,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { if (sameInput && verifySlots && heap.Held(stageState.data.mark)) inputsKept = true; if (sameInput && !verifySlots) { if (heap.Held(stageState.data.mark)) { - heapOffsets[dataIndex] = stageState.data.mark.offset; + heapOffsets[dataIndex] = stageState.data.mark.address; dataKept = true; continue; } diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 7a0a63cd425c..700c0bc35fae 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -26,6 +26,11 @@ void require(bool condition, const std::string& what) { if (!condition) throw std::runtime_error(what); } +BindlessHeap::DataSpan ringAllocate(BindlessHeap& heap, std::size_t words) { + BindlessHeap::SpanMark mark; + return heap.RingAllocate(words, mark); +} + struct FakeOwner : HeapSlotOwner { FakeOwner() = default; }; @@ -196,19 +201,19 @@ void ringSpans(const Context& context) { BindlessHeap::SpanMark unwritten; require(!heap.Held(unwritten), "a span never written is not held"); BindlessHeap::SpanMark first; - const auto span = heap.Allocate(16u, first); + const auto span = heap.RingAllocate(16u, first); require(first.offset == span.offset && first.words == 16u && heap.Held(first), "a span written in the open chunk is held"); constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); BindlessHeap::SpanMark filler; - static_cast(heap.Allocate(chunkWords - 1024u, filler)); + static_cast(heap.RingAllocate(chunkWords - 1024u, filler)); BindlessHeap::SpanMark crossing; - static_cast(heap.Allocate(4096u, crossing)); + static_cast(heap.RingAllocate(4096u, crossing)); require(heap.Held(crossing), "a span over two chunks is kept"); require(heap.Held(first), "a span stays held while its batch keeps the chunk open"); const auto counts = heap.Statistics(); require(counts.spansWritten == 3u && counts.spansKept == 3u, "three spans written and kept"); BindlessHeap::SpanMark third; - static_cast(heap.Allocate(chunkWords, third)); + static_cast(heap.RingAllocate(chunkWords, third)); Recorder recorder(context); heap.Submitted(recorder, 0u); require(heap.Held(first), "a span stays held after its batch is submitted while the ring has not come back to its chunk"); @@ -216,7 +221,7 @@ void ringSpans(const Context& context) { const auto untilWrap = [&] { const auto wraps = heap.Statistics().ringWraps; BindlessHeap::DataSpan last{}; - while (heap.Statistics().ringWraps == wraps) last = heap.Allocate(chunkWords, fill); + while (heap.Statistics().ringWraps == wraps) last = heap.RingAllocate(chunkWords, fill); return last.offset; }; require(untilWrap() == AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips a chunk a later batch still reads kept spans from"); @@ -232,9 +237,9 @@ bool ringLargeSpans(const Context& context) { constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); constexpr std::size_t largeWords = chunkWords * 2u + 1024u; BindlessHeap::SpanMark pin; - static_cast(heap.Allocate(16u, pin)); + static_cast(heap.RingAllocate(16u, pin)); BindlessHeap::SpanMark large; - const auto span = heap.Allocate(largeWords, large); + const auto span = heap.RingAllocate(largeWords, large); require(span.words.size() == largeWords && heap.Held(large), "a span over three chunks is written and held"); Recorder recorder(context); BindlessHeap::SpanMark fill; @@ -244,7 +249,7 @@ bool ringLargeSpans(const Context& context) { while (heap.Statistics().ringWraps == wraps) { heap.Submitted(recorder, 0u); require(heap.Held(kept), "a kept span stays held while later batches fill the ring"); - last = heap.Allocate(chunkWords, fill); + last = heap.RingAllocate(chunkWords, fill); } return last.offset; }; @@ -254,7 +259,7 @@ bool ringLargeSpans(const Context& context) { require(heap.Held(pin), "the pinned span outlives the large span"); bool refused = false; try { - static_cast(heap.Allocate(heap.RingChunkCount() * AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t) / 2u + 1u)); + static_cast(ringAllocate(heap, heap.RingChunkCount() * AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t) / 2u + 1u)); } catch (const std::runtime_error&) { refused = true; } @@ -268,17 +273,17 @@ void ringCurrentChunk(const Context& context) { Recorder recorder(context); std::vector pins(heap.RingChunkCount() - 1u); for (auto& pin : pins) { - static_cast(heap.Allocate(chunkWords, pin)); + static_cast(heap.RingAllocate(chunkWords, pin)); heap.Submitted(recorder, 0u); for (const auto& kept : pins) { if (kept.entry != 0u) require(heap.Held(kept), "every pinned chunk stays held"); } } BindlessHeap::SpanMark live; - static_cast(heap.Allocate(16u, live)); + static_cast(heap.RingAllocate(16u, live)); bool refused = false; try { - static_cast(heap.Allocate(chunkWords)); + static_cast(ringAllocate(heap, chunkWords)); } catch (const std::runtime_error&) { refused = true; } @@ -294,15 +299,15 @@ bool ringBusyChunks(const Context& context) { constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); const auto unreached = recorder.Submissions() + (1ull << 40u); BindlessHeap::SpanMark busy; - static_cast(heap.Allocate(16u, busy)); - static_cast(heap.Allocate(chunkWords)); + static_cast(heap.RingAllocate(16u, busy)); + static_cast(ringAllocate(heap, chunkWords)); heap.Submitted(recorder, unreached); heap.Submitted(recorder, 0u); BindlessHeap::SpanMark fill; const auto wraps = heap.Statistics().ringWraps; BindlessHeap::DataSpan last{}; while (heap.Statistics().ringWraps == wraps) { - last = heap.Allocate(chunkWords, fill); + last = heap.RingAllocate(chunkWords, fill); heap.Submitted(recorder, 0u); } require(last.offset >= AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips the chunk a batch still in flight reads"); @@ -312,6 +317,57 @@ bool ringBusyChunks(const Context& context) { return true; } +bool dataPool(const Context& context) { + Recorder recorder(context, true); + if (!recorder.HasTimeline()) return false; + constexpr std::size_t blockWords = AgcDriver::Graphics::BindlessHeap::PoolBlockBytes / sizeof(std::uint32_t); + { + BindlessHeap heap(context); + std::vector marks(5); + for (auto& mark : marks) static_cast(heap.Allocate(blockWords / 2u, mark)); + require(heap.Statistics().poolBlocksMade == 3u, "one batch's shader data grows into new blocks instead of waiting"); + for (const auto& mark : marks) require(heap.Held(mark), "every span of the batch is held"); + BindlessHeap::SpanMark big; + const auto span = heap.Allocate(blockWords * 3u / 2u, big); + require(span.words.size() == blockWords * 3u / 2u && heap.Statistics().poolBlocksMade == 4u, "a span larger than a block gets a block of its own"); + const auto [buffer, offset] = heap.DataLocation(span.address + 64u); + require(buffer != VK_NULL_HANDLE && offset == span.offset + 64u, "a pooled address maps back to its buffer and offset"); + heap.Submitted(recorder, recorder.Submissions() + (1ull << 40u)); + const auto made = heap.Statistics().poolBlocksMade; + BindlessHeap::SpanMark fill; + for (int index = 0; index < 4; ++index) static_cast(heap.Allocate(blockWords / 2u + 1u, fill)); + const auto busy = heap.Statistics(); + require(busy.poolBlocksRecycled == 0u && busy.poolBlocksMade > made, "blocks a batch in flight still reads are not reused"); + } + { + BindlessHeap heap(context); + BindlessHeap::SpanMark kept; + BindlessHeap::SpanMark first; + static_cast(heap.Allocate(blockWords - 64u, kept)); + static_cast(heap.Allocate(blockWords - 64u, first)); + static_cast(heap.Allocate(blockWords - 64u)); + heap.Submitted(recorder, 0u); + require(heap.Held(kept), "a span a later draw reuses stays held"); + const auto made = heap.Statistics().poolBlocksMade; + BindlessHeap::SpanMark fill; + static_cast(heap.Allocate(blockWords - 64u, fill)); + const auto counts = heap.Statistics(); + require(counts.poolBlocksRecycled == 1u && counts.poolBlocksMade == made, "a completed block is reused instead of making a new one"); + require(heap.Held(kept), "the block a kept span reopened is not reused"); + require(!heap.Held(first), "a span in a reused block has expired"); + } + { + BindlessHeap heap(context); + constexpr std::size_t blocks = 2u * AgcDriver::Graphics::BindlessHeap::PoolIdleBytes / AgcDriver::Graphics::BindlessHeap::PoolBlockBytes; + for (std::size_t index = 0; index < blocks; ++index) static_cast(heap.Allocate(blockWords - 64u)); + heap.Submitted(recorder, 0u); + const auto counts = heap.Statistics(); + require(counts.poolBlocksFreed != 0u && counts.poolBlockBytes <= AgcDriver::Graphics::BindlessHeap::PoolIdleBytes + AgcDriver::Graphics::BindlessHeap::PoolBlockBytes, + "idle blocks beyond the pool's budget are freed"); + } + return true; +} + void heapComesBack(const Context& context, VkImageView view) { auto& heap = BindlessHeap::For(context); const auto kind = Abi::FirstImageBinding; @@ -539,8 +595,13 @@ int main(int argc, char** argv) { const PlaceholderImages placeholders(context); textureSlots(context, placeholders.View(Abi::FirstImageBinding)); samplerSlots(context); - ringSpans(context); - ringCurrentChunk(context); + if (!dataPool(context)) std::printf("the data pool tests need the recorder timeline\n"); + if (BindlessHeap(context).RingChunkCount() != 0u) { + ringSpans(context); + ringCurrentChunk(context); + } else { + std::printf("the device's resource heap holds no descriptor ring\n"); + } viewSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); encodedViews(context); ownerSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); diff --git a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp index 838152b08fd3..945800920555 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp @@ -81,34 +81,34 @@ void disjoint(const std::vector& stages, const std::vector stages{{ShaderStage::Vertex, vertexItems, 6}, {ShaderStage::Fragment, pixelItems, 30}}; const auto placements = place(stages); disjoint(stages, placements, 0, "vertex and pixel"); require(placements[0].pushed.count == 6 && placements[1].pushed.count == 30, "stages that fit push everything they want"); require(place({stages[1]})[0] == placements[1], "a pixel stage that fits is placed as it is alone, so its fragment library is shared"); - require(placements[0].Item(Item::RingAddress) != placements[1].Item(Item::RingAddress), "the pre-rasterization and fragment parts hold their own globals"); + require(placements[0].Item(Item::PagetableAddress) != placements[1].Item(Item::PagetableAddress), "the pre-rasterization and fragment parts hold their own globals"); } { const std::vector stages{{ShaderStage::Vertex, vertexItems, 40}, {ShaderStage::Fragment, pixelItems, 40}}; const auto placements = place(stages); disjoint(stages, placements, 0, "stages that want too much"); - require(placements[0].pushed.count == 28 && placements[1].pushed.count == 28, "stages that want too much share the room evenly"); + require(placements[0].pushed.count == 27 && placements[1].pushed.count == 26, "stages that want too much share the room evenly"); } { - const std::vector stages{{ShaderStage::Local, vertexItems, 4}, {ShaderStage::TessellationControl, bits({Item::RingAddress, Item::ShaderData}), 3}, {ShaderStage::TessellationEvaluation, vertexItems, 10}, {ShaderStage::Fragment, pixelItems, 48}}; + const std::vector stages{{ShaderStage::Local, vertexItems, 4}, {ShaderStage::TessellationControl, bits({Item::PagetableAddress, Item::ShaderData}), 3}, {ShaderStage::TessellationEvaluation, vertexItems, 10}, {ShaderStage::Fragment, pixelItems, 48}}; const auto placements = place(stages); disjoint(stages, placements, ShaderRecompiler::PushFeatureDwords(false, true, false), "a tessellation pipeline"); - require(placements[0].Item(Item::RingAddress) == placements[1].Item(Item::RingAddress), "pre-rasterization stages share their part's globals"); + require(placements[0].Item(Item::PagetableAddress) == placements[1].Item(Item::PagetableAddress), "pre-rasterization stages share their part's globals"); } { const std::vector stages{{ShaderStage::Mesh, vertexItems, 8}, {ShaderStage::Fragment, pixelItems, 20}}; disjoint(stages, place(stages), ShaderRecompiler::PushFeatureDwords(true, false, false), "a mesh pipeline"); } { - const std::vector stages{{ShaderStage::Compute, bits({Item::RingAddress, Item::GdsAddress, Item::ShaderData}), 60}}; + const std::vector stages{{ShaderStage::Compute, bits({Item::PagetableAddress, Item::GdsAddress, Item::ShaderData}), 60}}; const auto placements = place(stages); disjoint(stages, placements, ShaderRecompiler::StagePushFeatures(ShaderStage::Compute, 0u), "a compute stage"); require(placements[0] == ShaderRecompiler::StandalonePushPlacement(ShaderStage::Compute, stages[0].items, stages[0].pushed), "the compiler's standalone compute placement is the driver's"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp index a720df4970c1..4756ae1f406b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp @@ -153,12 +153,12 @@ void RequireHeapTable(const ShaderRecompiler::RecompileResult& result) { Require(has(ShaderRecompiler::DescriptorRole::ImageTable) && has(ShaderRecompiler::DescriptorRole::ImageTableMap), "heap table stage reuse: the program does not bind an image table and its map"); } -std::uint32_t TableMapRoot(const ShaderResources& resources, const CompiledShader& shader) { +std::uint64_t TableMapRoot(const ShaderResources& resources, const CompiledShader& shader) { namespace Abi = ShaderRecompiler::RuntimeAbi; std::array bytes{}; const auto placements = AgcDriver::Graphics::PushDataPlacements(std::span(&shader, 1)); resources.PatchDataAddresses(bytes, std::span(&shader, 1), placements, nullptr); - std::uint32_t value = 0; + std::uint64_t value = 0; const auto position = placements.front().Item(Abi::RootItem::TableMap); Require(position != Abi::NoPushPosition, "heap table stage reuse: the stage's push layout holds no table map"); std::memcpy(&value, bytes.data() + position * sizeof(std::uint32_t), sizeof(value)); diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index 8b74064ed767..5912f183af30 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -89,10 +89,13 @@ inline constexpr std::uint32_t GpuGdsSet = 4u; inline constexpr std::uint32_t GdsBytes = 0x10000u; inline constexpr std::uint32_t PushDataDwords = 64u; inline constexpr std::uint32_t PushedDataWantedLimit = 48u; -enum class RootItem : std::uint32_t { RingAddress, PagetableAddress, FaultAddress, GdsAddress, PagetableDwords, StencilReference, ShaderData, FlattenedSrt, SrtDwords, TableMap, Count }; +enum class RootItem : std::uint32_t { PagetableAddress, FaultAddress, GdsAddress, PagetableDwords, StencilReference, ShaderData, TableMap, SrtAddress, FlattenedSrt, SrtDwords, Count }; inline constexpr std::uint32_t RootItemCount = static_cast(RootItem::Count); inline constexpr std::uint32_t RootItemBit(RootItem item) { return 1u << static_cast(item); } -inline constexpr bool RootAddressItem(RootItem item) { return static_cast(item) <= static_cast(RootItem::GdsAddress); } +inline constexpr bool RootAddressItem(RootItem item) { + return item == RootItem::PagetableAddress || item == RootItem::FaultAddress || item == RootItem::GdsAddress || item == RootItem::ShaderData || item == RootItem::TableMap || + item == RootItem::SrtAddress; +} inline constexpr std::uint32_t DepthRemapPushBit = 1u << 16u; inline constexpr std::uint32_t NoPushPosition = 0xffffffffu; struct PushedPlacement { diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index 8456006639dd..a2a4476a2dcc 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -13,7 +13,7 @@ namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 58; +inline constexpr std::uint32_t FormatVersion = 59; enum class LoadStatus { Loaded, diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp index d7e28603f116..6f4363820763 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp @@ -16,7 +16,7 @@ std::uint32_t EmitAlignedLoadU32(SpirvEmitterState& state, std::uint32_t pointer std::uint32_t EmitRootItemDword(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t word); std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); -std::uint32_t EmitRingAddress(SpirvEmitterState& state); +std::uint32_t EmitRootAddress(SpirvEmitterState& state, RuntimeAbi::RootItem item); std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index); bool HasFlattenedSrt(const SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 8bf1ced75a5e..84a74cfe9799 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -113,14 +113,12 @@ std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, Runti return readOnlyWordPointer(state, rootAddress(state, item), index); } -std::uint32_t EmitRingAddress(SpirvEmitterState& state) { - return rootAddress(state, RuntimeAbi::RootItem::RingAddress); +std::uint32_t EmitRootAddress(SpirvEmitterState& state, RuntimeAbi::RootItem item) { + return rootAddress(state, item); } std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index) { - const auto u64 = TypeScalarU64(state); - const auto base = Binary(state, spv::OpIAdd, u64, rootAddress(state, RuntimeAbi::RootItem::RingAddress), Unary(state, spv::OpUConvert, u64, EmitRootItemDword(state, item, 0u))); - return readOnlyWordPointer(state, base, index); + return readOnlyWordPointer(state, rootAddress(state, item), index); } namespace { @@ -166,7 +164,7 @@ std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index const auto inBounds = Binary(state, spv::OpULessThan, TypeBool(state), index, dwords); const auto last = Select(state, u32, Binary(state, spv::OpIEqual, TypeBool(state), dwords, ConstantU32(state, 0u)), ConstantU32(state, 0u), Binary(state, spv::OpISub, u32, dwords, ConstantU32(state, 1u))); const auto clamped = Select(state, u32, inBounds, index, last); - return Select(state, u32, inBounds, dataAddressLoad(state, RuntimeAbi::RootItem::FlattenedSrt, clamped), ConstantU32(state, 0u)); + return Select(state, u32, inBounds, dataAddressLoad(state, RuntimeAbi::RootItem::SrtAddress, clamped), ConstantU32(state, 0u)); } if (state.flattenedSrtVariable == 0) FailEmit("the flattened SRT descriptor is missing"); const auto pointer = state.module.AllocateId(); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index 306ff087981f..d91059161cd9 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -241,7 +241,7 @@ MemoryResourceAccess directAccess(SpirvValueEmitContext& context, const IrValue& access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), EmitShaderDataDwordLoad(state, dword + 2u), ConstantU32(state, wide ? 3u : 2u)); if (state.program.Metadata().bindings.UsesDataAddress()) { const auto empty = Binary(state, spv::OpIEqual, TypeBool(state), access.length, ConstantU32(state, 0u)); - address = Select(state, u64, empty, EmitRingAddress(state), address); + address = Select(state, u64, empty, EmitRootAddress(state, RuntimeAbi::RootItem::ShaderData), address); access.clampedPhysical = true; } access.objectPointer = state.module.AllocateId(); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index dcb6a9f314f8..cab569995874 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -201,7 +201,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first | | `APS5_HEAP_WALK_MEMO_MB` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | 256 | MiB each thread's GPU heap walk memo may hold across both its generations before the previous generation and then the oldest walks are dropped (0 keeps them until the 16,384-key cap rotates them out) | | `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a stage needing more image slots than this takes the per-draw path | -| `APS5_HEAP_RING_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 64 | MiB of the GPU heap's per-draw shader data ring, between 4 and 64; a ring inside the resource heap also stays within the device's heap size, in whole 2 MiB chunks; one span may take at most half the ring and one batch's spans must fit in it | +| `APS5_HEAP_RING_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 16 | MiB of the GPU heap's per-draw buffer descriptor ring inside the resource heap, between 4 and 64, in whole 2 MiB chunks and within the device's heap size; one draw's descriptors may take at most half the ring and one batch's must fit in it (shader data lives in a data pool that grows instead) | | `APS5_NO_HEAP_EVICTION` | flag | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | unset | set: a nearly full GPU heap no longer evicts image slots no draw used for two submissions, so draws take the per-draw path until owners release slots | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | From de1bbf1af31cf9d448ff64d4cac066a9e180aade Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 6 Nov 2026 01:25:47 +0530 Subject: [PATCH 123/269] fix(agc): submit a GPU heap batch early once it holds half the descriptor ring A batch writing more per-draw buffer descriptors than the ring holds aborted the run. Before each draw and dispatch the recorder now submits once the open batch holds half the ring's chunks, and one draw may take at most a quarter of the ring, so a batch always fits. --- .../Execution/src/VulkanDevice.cpp | 4 +-- .../Graphics/include/BindlessHeap.hpp | 3 ++ .../Graphics/include/Recorder.hpp | 1 + .../Graphics/src/BindlessHeap.cpp | 22 +++++++++--- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 4 +-- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 6 ++++ .../tests/BindlessHeapSlots.cpp | 36 ++++++++++++++++--- docs/dev/ENVIRONMENT.md | 2 +- 8 files changed, 64 insertions(+), 14 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 85cced74c660..4c4d28ee6edc 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -6081,7 +6081,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec if (base != 0 && bytes != 0) static_cast(Graphics::FlushDepthPlanes(base, static_cast(bytes))); } } - state->recorder->BoundKeptBytes(); + state->recorder->BoundDrawBatch(); ShaderRecompiler::RuntimeAbi::RequireVersion(shader.runtimeAbiVersion); PerformanceTimer timing("Vulkan.Dispatch"); if (recipeOut != nullptr) *recipeOut = nullptr; @@ -6421,7 +6421,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::recordCompletedDispatch(const Shader } RecipeOutcome VulkanDevice::DispatchRecipe(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint64_t arguments, std::uint64_t programAddress, const std::shared_ptr& hit, IndirectOutcome& outcome, const std::shared_ptr& verify, bool refreshByWords, const std::array& threadGroup) { - state->recorder->BoundKeptBytes(); + state->recorder->BoundDrawBatch(); ShaderRecompiler::RuntimeAbi::RequireVersion(shader.runtimeAbiVersion); PerformanceTimer timing("Vulkan.DispatchRecipe"); outcome = {0, 0}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 0c4bb7e162fa..c32528f3c6f5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -92,12 +92,14 @@ class BindlessHeap { static constexpr std::uint32_t SamplerKind = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Samplers); void Submitted(Recorder& recorder, std::uint64_t serial); + bool TakeRingPressure(); struct Counts { std::uint64_t ringWraps = 0, encodes = 0, encodedCopies = 0; std::uint64_t slotsFreed = 0, slotsReused = 0, slotsEvicted = 0, evictionWaits = 0; std::uint64_t ringWaits = 0, ringBatchPeakBytes = 0, ringSpanPeakBytes = 0, ringBytes = 0, imageSlotsHeld = 0; std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0, busyChunksSkipped = 0, bufferDescriptors = 0; + std::uint64_t ringPressureSubmits = 0; std::uint64_t poolBytes = 0, poolBatchPeakBytes = 0, poolBlocksMade = 0, poolBlocksRecycled = 0, poolBlocksFreed = 0, poolBlocksHeld = 0, poolBlockBytes = 0; }; Counts Statistics() const; @@ -210,6 +212,7 @@ class BindlessHeap { }; std::deque retiring; std::size_t ringBatchBytes = 0; + std::atomic ringOpenChunks{0}; std::size_t retiringAssigned = 0; std::uint32_t evictScanEpoch = 0; Recorder* submitter = nullptr; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index f244f71d3563..9d37d07e9834 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -121,6 +121,7 @@ class Recorder { void FlushDeferredReleases(); static constexpr std::size_t KeptBytesBudget = std::size_t{512} << 20u; void BoundKeptBytes(); + void BoundDrawBatch(); std::size_t InFlightKeptBytes() const { return inFlightKeptBytes; } enum class SnapshotUse : std::uint8_t { Storage, Vertex, Index16, Index32, Index16Restart, Index32Restart, PaddedVertex }; static constexpr std::size_t DrawSnapshotBudget = std::size_t{1024} << 20u; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index f23e7780f4e9..9b951d08074d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -653,7 +653,10 @@ bool BindlessHeap::Held(const SpanMark& mark) { return false; } } - for (auto chunk = first; chunk <= last; ++chunk) ringChunks[chunk].open = true; + for (auto chunk = first; chunk <= last; ++chunk) { + if (!ringChunks[chunk].open) ringOpenChunks.fetch_add(1u, std::memory_order_relaxed); + ringChunks[chunk].open = true; + } ++counts.spansKept; return true; } @@ -747,6 +750,13 @@ void BindlessHeap::trimPoolLocked() { } } +bool BindlessHeap::TakeRingPressure() { + if (ringChunks.empty() || ringOpenChunks.load(std::memory_order_relaxed) < std::max(2u, ringChunks.size() / 2u)) return false; + std::lock_guard lock(mutex); + ++counts.ringPressureSubmits; + return true; +} + std::pair BindlessHeap::DataLocation(VkDeviceAddress address) const { std::lock_guard lock(mutex); for (const auto& block : poolBlocks) { @@ -758,7 +768,7 @@ std::pair BindlessHeap::DataLocation(VkDeviceAddress add BindlessHeap::DataSpan BindlessHeap::RingAllocate(std::size_t words, SpanMark& mark) { Require(ringInHeap, "the GPU heap has no descriptor ring"); const auto bytes = alignUp(words * sizeof(std::uint32_t), RingSpanAlignment); - if (bytes > ringBytes / 2u) throw std::runtime_error("AGC bindless heap: one draw's buffer descriptors exceed half the descriptor ring"); + if (bytes > ringBytes / 4u) throw std::runtime_error("AGC bindless heap: one draw's buffer descriptors exceed a quarter of the descriptor ring"); std::lock_guard lock(mutex); auto offset = wrapRingOffset(alignUp(ringCursor, ringAlignment), bytes); enum class Taken { No, Kept, Busy }; @@ -842,6 +852,7 @@ void BindlessHeap::enterRingChunk(std::size_t index) { chunk.serial = 0u; } chunk.open = true; + ringOpenChunks.fetch_add(1u, std::memory_order_relaxed); chunk.entered = ++ringEntries; } @@ -1264,6 +1275,7 @@ void reportHeapStatistics() { totals.ringBatchPeakBytes = std::max(totals.ringBatchPeakBytes, counts.ringBatchPeakBytes); totals.ringSpanPeakBytes = std::max(totals.ringSpanPeakBytes, counts.ringSpanPeakBytes); totals.poolBytes += counts.poolBytes; + totals.ringPressureSubmits += counts.ringPressureSubmits; totals.poolBlocksMade += counts.poolBlocksMade; totals.poolBlocksRecycled += counts.poolBlocksRecycled; totals.poolBlocksFreed += counts.poolBlocksFreed; @@ -1285,6 +1297,7 @@ void reportHeapStatistics() { const auto busySkips = windowDelta(totals.busyChunksSkipped, lastTotals.busyChunksSkipped); const auto ringMiB = windowDelta(totals.ringBytes, lastTotals.ringBytes) >> 20u; const auto poolMiB = windowDelta(totals.poolBytes, lastTotals.poolBytes) >> 20u; + const auto pressureSubmits = windowDelta(totals.ringPressureSubmits, lastTotals.ringPressureSubmits); const auto poolMade = windowDelta(totals.poolBlocksMade, lastTotals.poolBlocksMade); const auto poolRecycled = windowDelta(totals.poolBlocksRecycled, lastTotals.poolBlocksRecycled); const auto poolFreed = windowDelta(totals.poolBlocksFreed, lastTotals.poolBlocksFreed); @@ -1293,10 +1306,10 @@ void reportHeapStatistics() { std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; descriptor ring %llu MiB, %llu waits, %llu busy chunks skipped, since start at most %llu KiB per batch; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %llu of %u held, %llu evicted (%llu waits); templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; descriptor ring %llu MiB, %llu waits, %llu busy chunks skipped, %llu early submits, since start at most %llu KiB per batch; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %llu of %u held, %llu evicted (%llu waits); templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(ringMiB), printed(ringWaits), printed(busySkips), printed(totals.ringBatchPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(ringMiB), printed(ringWaits), printed(busySkips), printed(pressureSubmits), printed(totals.ringBatchPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { @@ -1482,6 +1495,7 @@ void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { ringChunks[index].serial = serial; ringChunks[index].open = index == ringChunk; } + ringOpenChunks.store(ringChunk < ringChunks.size() && ringChunks[ringChunk].open ? 1u : 0u, std::memory_order_relaxed); counts.poolBatchPeakBytes = std::max(counts.poolBatchPeakBytes, poolBatchBytes); poolBatchBytes = 0; for (std::size_t index = 0; index < poolBlocks.size(); ++index) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index d7d738979542..c92981977e00 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -3220,7 +3220,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara recipeOut = nullptr; } if (state.quadList || StripPatches(state, shaders)) recipeOut = nullptr; - if (context.recorder != nullptr) context.recorder->BoundKeptBytes(); + if (context.recorder != nullptr) context.recorder->BoundDrawBatch(); if (AnyHeapShader(shaders)) recipeOut = nullptr; auto& timing = prepared.timing.emplace("Graphics.Draw"); // APS5_PROFILE_DRAW prints the time of each phase of the draw (microseconds) and the [draws] totals. @@ -4141,7 +4141,7 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters& DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, const DrawRecipe& recipe, const DrawTraceContext* trace) { const DepthCopySourceScope depthCopySource(state.depthCopySource); - if (context.recorder != nullptr) context.recorder->BoundKeptBytes(); + if (context.recorder != nullptr) context.recorder->BoundDrawBatch(); static_cast(snapshots); PerformanceTimer timing("Graphics.DrawWithRecipe"); static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index eb2510e38abd..65fbc4213a8a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -3097,6 +3097,12 @@ void Recorder::KeepBytes(const void* owner, std::size_t bytes) { if (open->keptOwners.insert(owner).second) open->keptBytes += bytes; } +void Recorder::BoundDrawBatch() { + BoundKeptBytes(); + if (open == nullptr || !DescriptorHeapEnabled() || !GuestMemory::GpuMutex().HeldByThisThread()) return; + if (auto* heap = BindlessHeap::Existing(context); heap != nullptr && heap->TakeRingPressure()) Submit(); +} + void Recorder::BoundKeptBytes() { if (!GuestMemory::GpuMutex().HeldByThisThread()) return; if (open != nullptr && open->keptBytes >= KeptBytesBudget) Submit(); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 700c0bc35fae..4665c44bc05b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -235,12 +235,12 @@ bool ringLargeSpans(const Context& context) { BindlessHeap heap(context); if (heap.RingChunkCount() < 5u) return false; constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); - constexpr std::size_t largeWords = chunkWords * 2u + 1024u; + constexpr std::size_t largeWords = chunkWords + 1024u; BindlessHeap::SpanMark pin; static_cast(heap.RingAllocate(16u, pin)); BindlessHeap::SpanMark large; const auto span = heap.RingAllocate(largeWords, large); - require(span.words.size() == largeWords && heap.Held(large), "a span over three chunks is written and held"); + require(span.words.size() == largeWords && heap.Held(large), "a span over two chunks is written and held"); Recorder recorder(context); BindlessHeap::SpanMark fill; const auto untilWrap = [&](const BindlessHeap::SpanMark& kept) { @@ -253,17 +253,42 @@ bool ringLargeSpans(const Context& context) { } return last.offset; }; - require(untilWrap(large) == 3u * AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips every chunk a kept large span covers"); + require(untilWrap(large) == 2u * AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips every chunk a kept large span covers"); require(untilWrap(pin) == AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips only the pinned first chunk"); require(!heap.Held(large), "a large span expires once the ring writes over one of its later chunks"); require(heap.Held(pin), "the pinned span outlives the large span"); bool refused = false; try { - static_cast(ringAllocate(heap, heap.RingChunkCount() * AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t) / 2u + 1u)); + static_cast(ringAllocate(heap, heap.RingChunkCount() * AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t) / 4u + 1u)); } catch (const std::runtime_error&) { refused = true; } - require(refused, "a span over half the ring is refused"); + require(refused, "a span over a quarter of the ring is refused"); + return true; +} + +bool ringPressure(const Context& context) { + BindlessHeap heap(context); + if (heap.RingChunkCount() < 4u) return false; + constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); + Recorder recorder(context); + BindlessHeap::SpanMark fill; + require(!heap.TakeRingPressure(), "an empty ring is under no pressure"); + const auto half = heap.RingChunkCount() / 2u; + for (std::size_t chunk = 1; chunk < half; ++chunk) static_cast(heap.RingAllocate(chunkWords, fill)); + require(!heap.TakeRingPressure(), "a batch below half the ring's chunks is under no pressure"); + static_cast(heap.RingAllocate(chunkWords, fill)); + require(heap.TakeRingPressure() && heap.Statistics().ringPressureSubmits == 1u, "a batch holding half the ring's chunks asks for a submit"); + heap.Submitted(recorder, 0u); + require(!heap.TakeRingPressure(), "a submit relieves the pressure"); + BindlessHeap::SpanMark kept; + static_cast(heap.RingAllocate(16u, kept)); + for (std::size_t chunk = 1; chunk < half; ++chunk) { + heap.Submitted(recorder, 0u); + static_cast(heap.RingAllocate(chunkWords, fill)); + } + heap.Submitted(recorder, 0u); + require(heap.Held(kept) && !heap.TakeRingPressure(), "chunks of earlier batches do not count"); return true; } @@ -595,6 +620,7 @@ int main(int argc, char** argv) { const PlaceholderImages placeholders(context); textureSlots(context, placeholders.View(Abi::FirstImageBinding)); samplerSlots(context); + if (!ringPressure(context)) std::printf("the ring pressure test needs at least four chunks\n"); if (!dataPool(context)) std::printf("the data pool tests need the recorder timeline\n"); if (BindlessHeap(context).RingChunkCount() != 0u) { ringSpans(context); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index cab569995874..d070712e5ef4 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -201,7 +201,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first | | `APS5_HEAP_WALK_MEMO_MB` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | 256 | MiB each thread's GPU heap walk memo may hold across both its generations before the previous generation and then the oldest walks are dropped (0 keeps them until the 16,384-key cap rotates them out) | | `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a stage needing more image slots than this takes the per-draw path | -| `APS5_HEAP_RING_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 16 | MiB of the GPU heap's per-draw buffer descriptor ring inside the resource heap, between 4 and 64, in whole 2 MiB chunks and within the device's heap size; one draw's descriptors may take at most half the ring and one batch's must fit in it (shader data lives in a data pool that grows instead) | +| `APS5_HEAP_RING_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 16 | MiB of the GPU heap's per-draw buffer descriptor ring inside the resource heap, between 4 and 64, in whole 2 MiB chunks and within the device's heap size; one draw's descriptors may take at most a quarter of the ring, and a batch is submitted early once it holds half the ring (shader data lives in a data pool that grows instead) | | `APS5_NO_HEAP_EVICTION` | flag | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | unset | set: a nearly full GPU heap no longer evicts image slots no draw used for two submissions, so draws take the per-draw path until owners release slots | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | From 73c51878251612cc054cb4077e3b4abe2b2d81c3 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 6 Nov 2026 02:33:25 +0530 Subject: [PATCH 124/269] perf(agc): embed constant samplers in GPU heap pipelines A sampler whose four descriptor words are constants in the shader code still took a sampler heap slot, its index was patched into the shader data on every draw, and the shader loaded it before fetching the sampler from the heap. vkd3d-proton maps a root signature's static samplers as samplers embedded in the pipeline's descriptor mapping instead (HEAP_WITH_CONSTANT_OFFSET with pEmbeddedSampler). GPU heap stages now do the same. The recompiler marks a sampler whose words are all immediates, gives each of its elements its own sampler variable in set 6, and records the words (with the point-filter form for point-sampled elements) in the sampler binding. Pipeline creation maps those variables to embedded samplers built from the words and the binding's compare, unnormalized and border flags, deduplicated across pipelines. Draws no longer take or patch a slot for them. Past the device's maxDescriptorHeapEmbeddedSamplers a constant sampler reads a sampler heap slot at a fixed offset instead. APS5_NO_EMBEDDED_SAMPLERS turns it off; APS5_EMBEDDED_SAMPLER_CAP lowers the embedded limit for testing. Shader disk cache format 60. --- .../Execution/src/Driver/Draw/HeapStages.cpp | 1 + .../Execution/src/VulkanDevice.cpp | 2 +- .../Graphics/include/BindlessHeap.hpp | 18 ++- .../Graphics/include/Sampler.hpp | 1 + .../Graphics/include/ShaderResources.hpp | 1 + .../Graphics/src/BindlessHeap.cpp | 91 +++++++++++++- .../libSceAgcDriver/Graphics/src/Pipeline.cpp | 2 +- .../libSceAgcDriver/Graphics/src/Sampler.cpp | 27 +++-- .../Graphics/src/ShaderResources.cpp | 6 +- .../Graphics/src/ShaderValidation.cpp | 18 ++- ...c_driver_heap_embedded_sampler_tests.cmake | 8 ++ .../tests/execution/HeapDrawSample.cpp | 14 ++- .../tests/execution/HeapEmbeddedSampler.cpp | 111 ++++++++++++++++++ .../IrMetadata/Resources.hpp | 3 + .../src/DescriptorBindingBuilder.cpp | 13 +- .../Optimization/src/ShaderInfoCollector.cpp | 22 ++++ core/shader/recompiler/Recompiler.cpp | 4 +- core/shader/recompiler/Recompiler.hpp | 2 + core/shader/recompiler/RuntimeAbi.hpp | 2 + core/shader/recompiler/ShaderDiskCache.cpp | 16 ++- core/shader/recompiler/ShaderDiskCache.hpp | 2 +- .../SpirvBackend/SpirvEmitterState.hpp | 1 + .../src/SpirvMemory/SpirvDescriptors.cpp | 11 +- docs/dev/ENVIRONMENT.md | 2 + 24 files changed, 346 insertions(+), 32 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_embedded_sampler_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 1c69ac53a688..3b220fea339a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -333,6 +333,7 @@ std::uint64_t descriptorBindingBytes(const ShaderRecompiler::DescriptorBinding& vectorBytes(binding.imageDepthCompare) + vectorBytes(binding.imageAtomic) + vectorBytes(binding.imageAtomic64) + vectorBytes(binding.imageShapes) + vectorBytes(binding.bufferAtomic) + vectorBytes(binding.bufferWritten) + vectorBytes(binding.samplerUnnormalized) + vectorBytes(binding.samplerIntegerBorder) + vectorBytes(binding.samplerCoordinatesIgnored) + + vectorBytes(binding.samplerEmbedded) + vectorBytes(binding.samplerEmbeddedWords) + vectorBytes(binding.imageUnnormalized) + vectorBytes(binding.imageUnnormalizedBaseLevel) + vectorBytes(binding.imageSamplers) + vectorBytes(binding.bufferRead) + vectorBytes(binding.bufferExtent); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 15888afe76a8..d207ccf42cef 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -5992,7 +5992,7 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons const bool heapDevice = gpuMode && context.descriptorHeap && Graphics::DescriptorHeapEnabled(); const auto workgroupAddressOffset = workgroupAddress ? Graphics::ComputePushConstantBytes : ~0u; const std::span spirv(shader.spirv.data(), shader.spirv.size()); - objects->descriptorHeap = heapDevice && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(spirv, heapMappings, workgroupAddressOffset, shader.dataAddressPush, false, false, false, scratchPool, &objects->pushPlacements.front()); + objects->descriptorHeap = heapDevice && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(spirv, heapMappings, workgroupAddressOffset, shader.dataAddressPush, false, false, false, scratchPool, &objects->pushPlacements.front(), &shader.bindings); require(!gpuMode || objects->descriptorHeap, "a GPU-mode compute stage does not map onto VK_EXT_descriptor_heap"); const auto createPipelines = state->DeviceFunction("vkCreateComputePipelines"); if (objects->descriptorHeap) CreateComputeHeapPipeline(state->device, createPipelines, context.pipelineCache, objects->module, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, heapMappings, &objects->pipeline, context.pipelineCacheSynchronization); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index c32528f3c6f5..af6b6368aaaf 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -3,10 +3,12 @@ #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include "RuntimeAbi.hpp" +#include #include #include #include #include +#include #include #include #include @@ -18,6 +20,7 @@ namespace ShaderRecompiler { struct StagePushPlacement; +struct DescriptorBinding; } namespace AgcDriver::Graphics { @@ -48,10 +51,12 @@ class BindlessHeap { bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset = ~0u, bool rootGds = false, bool rootFault = false, bool pixelLds = false, bool meshWindow = false, bool scratchPool = false, - const ShaderRecompiler::StagePushPlacement* placement = nullptr) const; + const ShaderRecompiler::StagePushPlacement* placement = nullptr, + const std::vector* bindings = nullptr) const; void WritePixelLdsBuffer(VkDeviceAddress address, VkDeviceSize bytes); void WriteMeshWindowBuffer(VkDeviceAddress address, VkDeviceSize bytes); std::pair DataLocation(VkDeviceAddress address) const; + std::uint32_t EmbeddedSamplerCount() const; std::optional TextureSlot(std::uint32_t kind, Texture* texture, VkImageView view, VkImageLayout layout); std::optional StorageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view); @@ -164,6 +169,16 @@ class BindlessHeap { void trimPoolLocked(); std::uint32_t ringAlignment = 256; mutable std::mutex mutex; + struct EmbeddedSampler { + VkSamplerCreateInfo info{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; + VkSamplerReductionModeCreateInfoEXT reduction{VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT}; + std::shared_ptr heapSampler; + std::uint32_t slot = ~0u; + }; + mutable std::mutex embeddedMutex; + mutable std::map, EmbeddedSampler> embeddedSamplers; + mutable std::uint32_t embeddedSamplerCount = 0; + std::optional embeddedSamplerMapping(const ShaderRecompiler::DescriptorBinding& binding, std::size_t element) const; std::atomic slotSerial{1}; struct ImageSlotKey { std::uint32_t kind; @@ -266,6 +281,7 @@ void NoteDataAddressPush(); void NoteEmptyResourceSet(); std::uint64_t EmptyResourceSets(); std::uint64_t DataAddressPushes(); +std::uint64_t EmbeddedSamplerMappings(); enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, DepthTransfer, StagedMerge, FirstSampleCopy, Count }; enum class HeapFallback : std::uint8_t { DrawUnmapped, DrawMixedRetry, DrawRefusedPair, DrawMixedReused, DispatchUnmapped, Count }; enum class HeapStageReason : std::uint8_t { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp index 7616def6496a..2f433c97220d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Sampler.hpp @@ -29,6 +29,7 @@ class Sampler : public HeapSlotOwner { bool ReadsOpaqueBlackBorder() const; bool RequiresNonSeamlessCube() const; static void Validate(const Context& context, const GuestSamplerResource& descriptor); + static VkSamplerCreateInfo CreateInfo(const Context& context, const GuestSamplerResource& descriptor, VkSamplerReductionModeCreateInfoEXT& reduction); static bool ShaderAppliesLodBias(const GuestSamplerResource& descriptor); static bool ReadsOpaqueBlackBorder(const GuestSamplerResource& descriptor); const std::array* CacheKey() const { return cacheKey ? &*cacheKey : nullptr; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 3429ecb960f8..fbb2d9e67cfe 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -466,6 +466,7 @@ class ShaderResources { std::uint32_t dataStage = 0; std::uint32_t addressDword = 0; ShaderRecompiler::DescriptorRole role = ShaderRecompiler::DescriptorRole::GuestBuffers; + std::vector embeddedSamplers; }; struct TableStage { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 9b951d08074d..2fedf203746d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -81,6 +81,7 @@ std::atomic heapComputeStages{0}; std::atomic descriptorHeapDevice{false}; std::atomic imageTableBuilds{0}; std::atomic dataAddressPushes{0}; +std::atomic embeddedSamplerMappings{0}; std::atomic emptyResourceSets{0}; } @@ -106,6 +107,10 @@ std::uint64_t DataAddressPushes() { return dataAddressPushes.load(std::memory_order_relaxed); } +std::uint64_t EmbeddedSamplerMappings() { + return embeddedSamplerMappings.load(std::memory_order_relaxed); +} + void NoteEmptyResourceSet() { emptyResourceSets.fetch_add(1, std::memory_order_relaxed); } @@ -564,6 +569,7 @@ void BindlessHeap::noteReleasedLocked() { } std::uint32_t BindlessHeap::SamplerGeneration(std::uint32_t slot) const { + if (slot == Abi::NoEmbeddedSampler) return 0u; std::lock_guard lock(mutex); return samplerPool.Generation(slot); } @@ -579,6 +585,7 @@ bool BindlessHeap::GenerationsCurrent(std::span } } for (std::size_t i = 0; i < samplerSlots.size(); ++i) { + if (samplerSlots[i] == Abi::NoEmbeddedSampler) continue; if (i >= samplerGenerations.size() || samplerPool.Generation(samplerSlots[i]) != samplerGenerations[i]) return false; } return true; @@ -921,6 +928,7 @@ struct HeapBindingUse { bool scratchPoolMemory = false; std::vector dataUniforms; std::vector ringDescriptors; + std::vector embeddedSamplers; std::pair refused{~0u, ~0u}; }; @@ -980,6 +988,10 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& use.dataUniforms.push_back(binding); continue; } + if (set == Abi::EmbeddedSamplerSet) { + use.embeddedSamplers.push_back(binding); + continue; + } const bool stageBinding = binding / bindingCount < Abi::StageCount; if (roots.gdsAddress && stageBinding && ((set == Abi::DescriptorSet && binding % bindingCount == static_cast(Abi::Binding::Buffers)) || (set == Abi::GpuDataSet && binding % bindingCount == static_cast(Abi::Binding::FlattenedSrt)))) { @@ -1075,9 +1087,72 @@ bool DescriptorHeapMappable(std::span spirv, bool workgroup return mappable; } +namespace { + +constexpr std::uint32_t InternalEmbeddedSamplers = 8u; + +std::uint32_t embeddedSamplerLimit(const Context& context) { + static const auto cap = [] { + const char* value = std::getenv("APS5_EMBEDDED_SAMPLER_CAP"); + return value != nullptr ? static_cast(std::strtoul(value, nullptr, 10)) : ~0u; + }(); + const auto device = context.descriptorHeapProperties.maxDescriptorHeapEmbeddedSamplers; + return std::min(cap, device > InternalEmbeddedSamplers ? device - InternalEmbeddedSamplers : 0u); +} + +} + +std::uint32_t BindlessHeap::EmbeddedSamplerCount() const { + std::lock_guard lock(embeddedMutex); + return embeddedSamplerCount; +} + +std::optional BindlessHeap::embeddedSamplerMapping(const ShaderRecompiler::DescriptorBinding& binding, std::size_t element) const { + if (binding.samplerEmbeddedWords.size() < (element + 1u) * 4u || element >= binding.samplerDepthCompare.size()) return std::nullopt; + std::array words{}; + std::copy_n(binding.samplerEmbeddedWords.begin() + static_cast(element * 4u), 4u, words.begin()); + if (element < binding.samplerCoordinatesIgnored.size() && binding.samplerCoordinatesIgnored[element]) words[0] &= ~(1u << 15u); + const bool compare = binding.samplerDepthCompare[element]; + const bool unnormalized = element < binding.samplerUnnormalized.size() && binding.samplerUnnormalized[element]; + const bool integerBorder = element < binding.samplerIntegerBorder.size() && binding.samplerIntegerBorder[element]; + const std::array key{words[0], words[1], words[2], words[3], (compare ? 1u : 0u) | (unnormalized ? 2u : 0u) | (integerBorder ? 4u : 0u)}; + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = Abi::EmbeddedSamplerSet; + mapping.firstBinding = binding.samplerEmbedded[element]; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT; + std::lock_guard lock(embeddedMutex); + auto found = embeddedSamplers.find(key); + if (found == embeddedSamplers.end()) { + auto resource = DecodeSamplerResource(words, unnormalized, true, integerBorder); + resource.compareEnable = compare; + EmbeddedSampler made; + made.info = Sampler::CreateInfo(context, resource, made.reduction); + if (embeddedSamplerCount < embeddedSamplerLimit(context)) ++embeddedSamplerCount; + else made.heapSampler = std::make_shared(context, resource); + found = embeddedSamplers.emplace(key, std::move(made)).first; + if (found->second.info.pNext != nullptr) found->second.info.pNext = &found->second.reduction; + } + auto& entry = found->second; + if (entry.heapSampler == nullptr) { + mapping.sourceData.constantOffset.pEmbeddedSampler = &entry.info; + embeddedSamplerMappings.fetch_add(1, std::memory_order_relaxed); + return mapping; + } + if (entry.slot == ~0u) { + const auto slot = const_cast(this)->SamplerSlot(entry.heapSampler); + Require(slot.has_value(), "the global sampler heap is full"); + entry.slot = *slot; + } + mapping.sourceData.constantOffset.heapOffset = static_cast(entry.slot * samplerHeapStride); + return mapping; +} + bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::vector& mappings, std::uint32_t workgroupAddressOffset, bool rootGds, bool rootFault, bool pixelLds, bool meshWindow, - bool scratchPool, const ShaderRecompiler::StagePushPlacement* placement) const { + bool scratchPool, const ShaderRecompiler::StagePushPlacement* placement, + const std::vector* bindings) const { mappings.clear(); if (resourceHeap == nullptr) return false; HeapBindingUse use; @@ -1099,6 +1174,20 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, heapMapping(Abi::FragmentDescriptorSet, binding, VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT, 0, samplerHeapStride)); else mappings.push_back(heapMapping(Abi::FragmentDescriptorSet, binding, imageResources, 0, imageHeapStride)); } + std::sort(use.embeddedSamplers.begin(), use.embeddedSamplers.end()); + for (const auto binding : use.embeddedSamplers) { + if (bindings == nullptr) return false; + std::optional mapping; + for (const auto& candidate : *bindings) { + if (candidate.role != ShaderRecompiler::DescriptorRole::GuestSamplers) continue; + const auto found = std::ranges::find(candidate.samplerEmbedded, binding); + if (found == candidate.samplerEmbedded.end()) continue; + mapping = embeddedSamplerMapping(candidate, static_cast(found - candidate.samplerEmbedded.begin())); + break; + } + if (!mapping) return false; + mappings.push_back(*mapping); + } for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, placement)); std::sort(use.ringDescriptors.begin(), use.ringDescriptors.end()); for (const auto& [set, binding] : use.ringDescriptors) mappings.push_back(ringDescriptorMapping(set, binding, ringHeapOffset, placement)); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index 16bcd55fe47f..2e225e182d1d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -527,7 +527,7 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput const bool rooted = RootedPushData(shaders); descriptorHeap = std::all_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { const auto index = static_cast(&shader - shaders.data()); - return heap.DescriptorHeapMappings(std::span(shader.program->spirv.data(), shader.program->spirv.size()), heapMappings[index], ~0u, shader.program->dataAddressPush, PushesGeneratedFaultAddress(shader, rooted), shader.program->functionLdsBuffer, shader.program->meshWindowBuffer, false, &pushPlacements[index]); + return heap.DescriptorHeapMappings(std::span(shader.program->spirv.data(), shader.program->spirv.size()), heapMappings[index], ~0u, shader.program->dataAddressPush, PushesGeneratedFaultAddress(shader, rooted), shader.program->functionLdsBuffer, shader.program->meshWindowBuffer, false, &pushPlacements[index], &shader.program->bindings); }); } Require(descriptorHeap || !AnyHeapShader(shaders), "a pipeline with GPU-mode stages does not map onto VK_EXT_descriptor_heap"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp index be99fcb46abf..ce1bc1b69386 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Sampler.cpp @@ -26,16 +26,11 @@ namespace AgcDriver::Graphics { } } - Sampler::Sampler(const Context& context, const GuestSamplerResource& descriptor) : context(context) { + VkSamplerCreateInfo Sampler::CreateInfo(const Context& context, const GuestSamplerResource& descriptor, VkSamplerReductionModeCreateInfoEXT& reduction) { Validate(context, descriptor); - forcesDegamma = descriptor.forceDegamma; - VkSamplerCreateInfo info{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - VkSamplerReductionModeCreateInfoEXT reduction{VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT, nullptr, descriptor.reductionMode}; - if (descriptor.reductionMode != VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT) { - info.pNext = &reduction; - requiresFilterMinmax = descriptor.magFilter == VK_FILTER_LINEAR || descriptor.minFilter == VK_FILTER_LINEAR; - } + reduction = {VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT, nullptr, descriptor.reductionMode}; + if (descriptor.reductionMode != VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT) info.pNext = &reduction; info.magFilter = descriptor.magFilter; info.minFilter = descriptor.minFilter; info.mipmapMode = descriptor.mipmapMode; @@ -50,12 +45,18 @@ namespace AgcDriver::Graphics { info.minLod = descriptor.minLod; info.maxLod = descriptor.maxLod; info.borderColor = descriptor.borderColor; - opaqueBlackBorder = ReadsOpaqueBlackBorder(descriptor); info.unnormalizedCoordinates = descriptor.unnormalizedCoordinates ? VK_TRUE : VK_FALSE; - if (descriptor.nonSeamlessCube) { - if (context.nonSeamlessCubeMap) info.flags |= VK_SAMPLER_CREATE_NON_SEAMLESS_CUBE_MAP_BIT_EXT; - else requiresNonSeamlessCube = true; - } + if (descriptor.nonSeamlessCube && context.nonSeamlessCubeMap) info.flags |= VK_SAMPLER_CREATE_NON_SEAMLESS_CUBE_MAP_BIT_EXT; + return info; + } + + Sampler::Sampler(const Context& context, const GuestSamplerResource& descriptor) : context(context) { + VkSamplerReductionModeCreateInfoEXT reduction{}; + const auto info = CreateInfo(context, descriptor, reduction); + forcesDegamma = descriptor.forceDegamma; + requiresFilterMinmax = descriptor.reductionMode != VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT && (descriptor.magFilter == VK_FILTER_LINEAR || descriptor.minFilter == VK_FILTER_LINEAR); + opaqueBlackBorder = ReadsOpaqueBlackBorder(descriptor); + requiresNonSeamlessCube = descriptor.nonSeamlessCube && !context.nonSeamlessCubeMap; Check(context.Function("vkCreateSampler")(context.device, &info, nullptr, &sampler), "vkCreateSampler"); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 9fd46668063e..bbeec8515281 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -5209,6 +5209,7 @@ void ShaderResources::addImageBinding(const ShaderRecompiler::DescriptorBinding& } samplerSources.push_back({{words[0], words[1], words[2], words[3]}, compareEnable, unnormalized, integerBorder}); item.imageAllocations.push_back(samplers.size() - 1); + item.embeddedSamplers.push_back(element < binding.samplerEmbedded.size() && binding.samplerEmbedded[element] != ShaderRecompiler::RuntimeAbi::NoEmbeddedSampler); } Require(samplers.size() <= context.limits.maxDescriptorSetSamplers, "pipeline sampler descriptors exceed device limits"); } @@ -7016,9 +7017,10 @@ void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, V kindSlots.push_back(takenSlot(heap.StorageSlot(kind, storageTextures[index].get(), view), "the global storage image heap is full")); } } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { - for (const auto index : binding.imageAllocations) { + for (std::size_t element = 0; element < binding.imageAllocations.size(); ++element) { ++cursor; - state.samplerSlots.push_back(takenSlot(heap.SamplerSlot(samplers[index]), "the global sampler heap is full")); + const bool embedded = element < binding.embeddedSamplers.size() && binding.embeddedSamplers[element]; + state.samplerSlots.push_back(embedded ? ShaderRecompiler::RuntimeAbi::NoEmbeddedSampler : takenSlot(heap.SamplerSlot(samplers[binding.imageAllocations[element]]), "the global sampler heap is full")); } } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index dd250983a175..ef14a98adcca 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -454,6 +454,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi case spv::OpTypeRuntimeArray: case spv::OpTypeStruct: case spv::OpTypePointer: + case spv::OpTypeSampler: Require(count >= 2 && module.types.emplace(instruction[1], std::vector(instruction.begin(), instruction.end())).second, "invalid or duplicate SPIR-V type"); break; case spv::OpVariable: @@ -516,6 +517,8 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi } else Require(module.modes.empty(), "unsupported vertex execution mode"); std::set> descriptors; std::set declared; + std::set embeddedSamplers; + std::set embeddedOwners; std::map, bool> bufferViews; bool push = false; for (const auto& [id, variable] : module.variables) { @@ -594,6 +597,16 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi } else if (variable.storage == spv::StorageClassUniformConstant) { Require(decoration.set && decoration.binding, "unbound shader resource"); const auto key = std::make_pair(*decoration.set, *decoration.binding); + if (key.first == ShaderRecompiler::RuntimeAbi::EmbeddedSamplerSet) { + const auto owner = std::find_if(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { + return item.role == ShaderRecompiler::DescriptorRole::GuestSamplers && std::find(item.samplerEmbedded.begin(), item.samplerEmbedded.end(), key.second) != item.samplerEmbedded.end(); + }); + Require(shader.gpuResolvedImages && owner != shader.bindings.end(), "an embedded sampler has no constant sampler element in the recompiler binding metadata"); + Require(type.size() == 2 && (type[0] & 0xffffu) == spv::OpTypeSampler, "an embedded sampler must be declared as a single sampler"); + Require(embeddedSamplers.insert(key.second).second, "duplicate embedded sampler binding"); + embeddedOwners.insert(&*owner); + continue; + } const auto binding = std::find_if(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { return item.descriptorSet == key.first && item.binding == key.second; }); bool tableAlias = false; { @@ -689,7 +702,10 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi Require(shader.vertexAttributes.empty(), "vertex attribute metadata is invalid for this stage"); } const auto addressedBindings = static_cast(std::count_if(shader.bindings.begin(), shader.bindings.end(), [&](const ShaderRecompiler::DescriptorBinding& binding) { return !declared.contains(&binding) && ((shader.bufferAddressCount != 0u && binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers) || (shader.dataAddressPush && (binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt || binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable || binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer || binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable || binding.role == ShaderRecompiler::DescriptorRole::SamplerTable || binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap))); })); - Require(descriptors.size() + addressedBindings == shader.bindings.size(), "recompiler binding metadata contains undeclared resources"); + const auto embeddedOnly = static_cast(std::count_if(embeddedOwners.begin(), embeddedOwners.end(), [&](const ShaderRecompiler::DescriptorBinding* owner) { + return !descriptors.contains(std::make_pair(owner->descriptorSet, owner->binding)); + })); + Require(descriptors.size() + addressedBindings + embeddedOnly == shader.bindings.size(), "recompiler binding metadata contains undeclared resources"); Require(push == (!shader.pushConstants.empty() || shader.readsDepthRemapPush || shader.dataAddressPush || mesh || (control && !rectListControl && !barycentricPatches) || (geometry && state.tessellationCapture)), "recompiler push constant metadata disagrees with SPIR-V"); for (const auto id : module.interface) Require(module.variables.contains(id), "entry point interface contains an unknown variable"); if (mesh) Require(module.primitiveIndices == state.stages.mesh->outputPrimitiveSize, "mesh shader does not export primitive indices"); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_embedded_sampler_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_embedded_sampler_tests.cmake new file mode 100644 index 000000000000..bb87173efadf --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_embedded_sampler_tests.cmake @@ -0,0 +1,8 @@ +if(BUILD_TESTING AND TARGET agc_driver_heap_embedded_sampler_tests) + agc_add_env_test(agc_driver_heap_embedded_sampler_heap agc_driver_heap_embedded_sampler_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) + agc_add_env_test(agc_driver_heap_embedded_sampler_heap_off agc_driver_heap_embedded_sampler_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_NO_EMBEDDED_SAMPLERS=1) + agc_add_env_test(agc_driver_heap_embedded_sampler_heap_capped agc_driver_heap_embedded_sampler_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_EMBEDDED_SAMPLER_CAP=0) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index 28faa160a936..18a0cfa6b566 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -37,6 +37,9 @@ alignas(256) constexpr std::array VertexCode{ alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array ConstantSamplerPixelCode{ + 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; alignas(256) constexpr std::array BufferPixelCode{ 0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; @@ -105,7 +108,7 @@ void Append(std::vector& commands, std::uint32_t opcode, std::ini commands.insert(commands.end(), payload); } -enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds }; +enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds, ConstantSampler }; const std::uint32_t* VertexProgram(Mode mode) { if (mode == Mode::VertexTable) return TableVertexCode.data(); @@ -140,6 +143,7 @@ const char* DrawnWhat(Mode mode, bool buffer) { if (mode == Mode::MovedTexture) return " (a texture changed between two draws)"; if (buffer) return " (texture and buffer)"; if (mode == Mode::Table) return " (image table)"; + if (mode == Mode::ConstantSampler) return " (texture with a constant sampler)"; return " (texture)"; } @@ -149,6 +153,7 @@ const char* TakenWhat(Mode mode, bool buffer) { if (mode == Mode::Bda) return " loading through BDA"; if (mode == Mode::Table) return " reading an image table"; if (mode == Mode::VertexTable) return " (vertex stage reading an image table)"; + if (mode == Mode::ConstantSampler) return " sampling with a constant sampler"; return ""; } @@ -308,6 +313,8 @@ std::span PixelProgram(Mode mode, bool buffer, bool vertexS return StoragePixelCode; case Mode::Bda: return BdaPixelCode; + case Mode::ConstantSampler: + return ConstantSamplerPixelCode; default: break; } @@ -340,6 +347,7 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { const auto takenBefore = AgcDriver::DriverDetail::HeapStagesTaken(); const auto tablesBefore = AgcDriver::Graphics::ImageTableBuilds(); const auto pushesBefore = AgcDriver::Graphics::DataAddressPushes(); + const auto embeddedBefore = AgcDriver::Graphics::EmbeddedSamplerMappings(); auto* gdsCounter = reinterpret_cast(AgcDriver::Pm4::GdsAddress() + 0x10u); if (mode == Mode::Gds) *gdsCounter = 0u; auto commands = Draw(code, mode); @@ -380,6 +388,8 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { std::string("the heap did not take the fragment stage") + TakenWhat(mode, buffer)); Require(AgcDriver::Graphics::DataAddressPushes() > pushesBefore, "the heap stages did not read their shader data through pushed addresses"); + if (mode == Mode::ConstantSampler && std::getenv("APS5_NO_EMBEDDED_SAMPLERS") == nullptr) + Require(AgcDriver::Graphics::EmbeddedSamplerMappings() > embeddedBefore, "the fragment stage's constant sampler was not embedded in its pipeline"); } void MixedDrawTakesThePerDrawPath() { @@ -451,7 +461,7 @@ int main() { mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); } for (const auto mode : {Mode::Texture, Mode::Buffer, Mode::Storage, Mode::Gds, Mode::Vertex, Mode::Bda, Mode::Table, Mode::VertexTable, - Mode::MovedBuffer, Mode::MovedTexture, Mode::PixelLds, Mode::Texture}) + Mode::MovedBuffer, Mode::MovedTexture, Mode::PixelLds, Mode::ConstantSampler, Mode::Texture}) DrawSamplesTheTexture(heap, mode); const bool capped = heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr; if (heap && !capped) MixedDrawTakesThePerDrawPath(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp new file mode 100644 index 000000000000..732de6b2c626 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp @@ -0,0 +1,111 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "Recompiler.hpp" +#include "RuntimeAbi.hpp" +#include "HeapSampleKernel.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void Require(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +constexpr std::uint32_t BorderClamp = 6u | (6u << 3u) | (6u << 6u); +constexpr std::uint32_t OpaqueWhiteBorder = 2u << 30u; + +alignas(256) constexpr std::array ConstantSamplerCode{ + 0xbe8803ffu, BorderClamp, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, OpaqueWhiteBorder, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; +alignas(256) constexpr std::array UserSamplerCode{0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; +constexpr std::array White{0xffu, 0xffu, 0xffu, 0xffu}; + +alignas(256) std::array TextureMemory{}; +alignas(4096) std::array, 2> Outputs{}; + +ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, float* output, std::span code, bool userSampler) { + auto userData = SampleUserData(TextureMemory.data(), output); + if (userSampler) { + userData[8] = BorderClamp; + userData[11] = OpaqueWhiteBorder; + } + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{1u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; + ShaderRecompiler::RecompileRequest request{ + {ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0u, {}}, + {32u, 0u, userData, compute, std::nullopt, std::nullopt, memory}, + device.ComputeTarget(32u), + {0u, 0u, 0u, 128u}}; + request.useCache = false; + return ShaderRecompiler::Recompile(request); +} + +std::size_t EmbeddedElements(const ShaderRecompiler::RecompileResult& result) { + std::size_t count = 0; + for (const auto& binding : result.bindings) { + if (binding.role != ShaderRecompiler::DescriptorRole::GuestSamplers) continue; + count += static_cast(std::ranges::count_if(binding.samplerEmbedded, [](std::uint32_t value) { return value != ShaderRecompiler::RuntimeAbi::NoEmbeddedSampler; })); + } + return count; +} + +bool DecoratesEmbeddedSet(const ShaderRecompiler::RecompileResult& result) { + const auto& spirv = result.spirv; + for (std::size_t at = 5u; at < spirv.size();) { + const auto count = spirv[at] >> 16u; + if (count == 0u) break; + if ((spirv[at] & 0xffffu) == 71u && count >= 4u && spirv[at + 2u] == 34u && spirv[at + 3u] == ShaderRecompiler::RuntimeAbi::EmbeddedSamplerSet) return true; + at += count; + } + return false; +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; + if (heap && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; + const bool embedding = heap && std::getenv("APS5_NO_EMBEDDED_SAMPLERS") == nullptr; + FillTexels(TextureMemory, SampleTexel); + for (auto& output : Outputs) output.fill(-1.0f); + const auto constant = Compile(*device, Outputs[0].data(), ConstantSamplerCode, false); + const auto user = Compile(*device, Outputs[1].data(), UserSamplerCode, true); + Require(constant.gpuResolvedImages == heap, "the constant-sampler stage is not in the expected mode"); + Require((EmbeddedElements(constant) != 0u) == embedding, embedding ? "a constant sampler was not embedded" : "a sampler was embedded outside heap mode"); + Require(DecoratesEmbeddedSet(constant) == embedding, "the stage's SPIR-V does not match its embedded samplers"); + Require(EmbeddedElements(user) == 0u && !DecoratesEmbeddedSet(user), "a sampler read from user data was embedded"); + const auto* existing = AgcDriver::Graphics::BindlessHeap::Existing(device->graphicsContext()); + const auto embeddedBefore = existing != nullptr ? existing->EmbeddedSamplerCount() : 0u; + device->Dispatch(constant, 1u, 1u, 1u, {}, reinterpret_cast(ConstantSamplerCode.data())); + device->Dispatch(user, 1u, 1u, 1u, {}, reinterpret_cast(UserSamplerCode.data())); + device->WaitIdle(); + RequireSampled(Outputs[0].data(), White, "the constant sampler's opaque white border", heap); + RequireSampled(Outputs[1].data(), White, "the user-data sampler's opaque white border", heap); + if (embedding) { + const bool capped = std::getenv("APS5_EMBEDDED_SAMPLER_CAP") != nullptr; + const auto* heapObject = AgcDriver::Graphics::BindlessHeap::Existing(device->graphicsContext()); + Require(heapObject != nullptr, "the heap dispatch left no descriptor heap"); + Require(capped ? heapObject->EmbeddedSamplerCount() == 0u : heapObject->EmbeddedSamplerCount() > embeddedBefore, + capped ? "a capped device embedded a sampler past its limit" : "the pipeline did not embed the constant sampler"); + } + const bool capped = std::getenv("APS5_EMBEDDED_SAMPLER_CAP") != nullptr; + std::cout << "constant samplers sampled " << (!embedding ? "through descriptors" : capped ? "from sampler heap slots past the embedded sampler limit" : "as embedded samplers") << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp index cbc6fc798654..eb33bcc7da6f 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/Resources.hpp @@ -5,6 +5,7 @@ #include "IntermediateRepresentation/IrMetadata/ShaderStage.hpp" #include "IntermediateRepresentation/IrOpcode.hpp" #include "RdnaDecoder/RdnaInstruction.hpp" +#include #include #include #include @@ -155,6 +156,8 @@ struct SamplerResource { std::uint16_t uses = 0; bool foldTexelOffsetsOnly = false; std::uint32_t table = NoTable; + bool constant = false; + std::array constantWords{}; bool operator==(const SamplerResource& other) const = default; }; diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index f66774d00c23..6b2b769a48c7 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -558,7 +558,8 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l } if ((imageHeap || samplerHeap) && !registrationModules) plan.specialization.push_back({PipelineSpecialization::DescriptorIndex(static_cast(logical.kind), element), active ? static_cast(compact.resources.size()) : 0u}); if (active && sampledSlots) plan.heapSlotWords.push_back({imageSlotBase + element, static_cast(logical.kind), static_cast(compact.resources.size())}); - if (active && slotWords && samplerHeap) plan.heapSlotWords.push_back({layout.SamplerSlotDword() + element, static_cast(logical.kind), static_cast(compact.resources.size())}); + const bool embeddedSampler = samplerHeap && layout.gpuResolvedImages && info.samplers.at(resource).constant; + if (active && slotWords && samplerHeap && !embeddedSampler) plan.heapSlotWords.push_back({layout.SamplerSlotDword() + element, static_cast(logical.kind), static_cast(compact.resources.size())}); if (active || ((imageHeap || samplerHeap) && registrationModules)) { compact.resources.push_back(resource); originals.push_back(element); @@ -617,6 +618,13 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l const auto& words = snapshot.samplers.at(resource).dwords; const bool tablePointOnly = (directSamplerModes.at(resource) & 2u) == 0u; if ((originals[element] & 1u) != 0u && !inactive[element] && !(tablePointOnly && ReducesBetweenTexels(words[0], words[2]))) entry.samplerFilterElements.push_back(element); + const auto& sampler = info.samplers.at(resource); + const bool embedded = layout.gpuResolvedImages && sampler.constant && !inactive[element]; + physical.samplerEmbedded.push_back(embedded ? originals[element] : RuntimeAbi::NoEmbeddedSampler); + auto embeddedWords = sampler.constantWords; + if (embedded && (originals[element] & 1u) != 0u && !(tablePointOnly && ReducesBetweenTexels(embeddedWords[0], embeddedWords[2]))) + embeddedWords[2] = PointFilteredSamplerWord(embeddedWords[0], embeddedWords[2]); + physical.samplerEmbeddedWords.insert(physical.samplerEmbeddedWords.end(), embeddedWords.begin(), embeddedWords.end()); } } else if (physical.role == DescriptorRole::ShaderData && layout.UsesPushData()) { fail("DescriptorBindingBuilder::Populate shader-data binding must not exist when push data is used"); @@ -694,7 +702,8 @@ DescriptorBindingPlan DescriptorBindingBuilder::Select(const DescriptorBindingPl selected.bindings.reserve(remaining.size()); for (const auto& binding : plan.bindings) { const bool addressed = IsAddressedRole(plan, binding.descriptor.role); - if (remaining.erase(binding.descriptor.binding) == 0u && !addressed) continue; + const bool embedded = std::ranges::any_of(binding.descriptor.samplerEmbedded, [](std::uint32_t element) { return element != RuntimeAbi::NoEmbeddedSampler; }); + if (remaining.erase(binding.descriptor.binding) == 0u && !addressed && !embedded) continue; selected.storageData |= binding.descriptor.role == DescriptorRole::ShaderData; selected.bindings.push_back(binding); } diff --git a/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp b/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp index de12941c6593..4d02efe571c7 100644 --- a/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp +++ b/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -578,9 +579,30 @@ void AddTargetMerge(const ShaderPixelInputInfo& pixel, ShaderInfo& info) { if (pixel.mergeSamples > 1u) AddInput(info, StageInputKind::SampleId, 0, 1, "gl_SampleID"); } +bool embeddedSamplersEnabled() { + static const bool enabled = std::getenv("APS5_NO_EMBEDDED_SAMPLERS") == nullptr; + return enabled; +} + +void collectConstantSampler(const IrProgram& program, SamplerResource& sampler) { + sampler.constant = false; + sampler.constantWords = {}; + const auto& sources = program.Resources().descriptorSources; + if (!embeddedSamplersEnabled() || sampler.table != NoTable || sampler.source >= sources.size()) return; + const auto& source = sources[sampler.source]; + if (source.dwordCount != 4u) return; + for (std::uint32_t index = 0; index < 4u; ++index) { + const IrValue* word = source.dwords[index] != nullptr ? source.dwords[index]->Resolve() : nullptr; + if (word == nullptr || !word->HasImmediate() || word->Type() != IrType::U32) return; + sampler.constantWords[index] = word->ImmediateU32(); + } + sampler.constant = true; +} + void CollectSamplerUses(const IrProgram& program, ShaderInfo& info) { for (auto& sampler : info.samplers) { sampler.uses = 0; + collectConstantSampler(program, sampler); } const auto& memoryInfo = program.Resources().memoryInfo; for (const auto& block : program.Blocks()) { diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 2fefef082f89..5e6d0e0297c2 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -1040,7 +1040,7 @@ SpecializedSpirv buildSpecializedModule(const CompiledShaderArtifact& artifact, const auto op = static_cast(materialized[cursor] & 0xffffu); if (op == spv::OpEntryPoint && count >= 2u) compute = materialized[cursor + 1u] == spv::ExecutionModelGLCompute; if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationBinding) bindingNumbers.emplace(materialized[cursor + 1u], materialized[cursor + 3u]); - if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationDescriptorSet && (materialized[cursor + 3u] == PixelFunctionLdsDescriptorSet || materialized[cursor + 3u] == MeshWindowDescriptorSet || (compute && !target.gpuResolvedImages && materialized[cursor + 3u] == WorkgroupMemoryDescriptorSet))) ldsBuffers.insert(materialized[cursor + 1u]); + if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationDescriptorSet && (materialized[cursor + 3u] == PixelFunctionLdsDescriptorSet || materialized[cursor + 3u] == MeshWindowDescriptorSet || materialized[cursor + 3u] == RuntimeAbi::EmbeddedSamplerSet || (compute && !target.gpuResolvedImages && materialized[cursor + 3u] == WorkgroupMemoryDescriptorSet))) ldsBuffers.insert(materialized[cursor + 1u]); if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationSpecId) { const auto id = materialized[cursor + 3u]; if (!PipelineSpecialization::IsWorkgroupOffset(id)) module->specialization.push_back({id, supplied.at(id)}); @@ -1808,7 +1808,7 @@ std::uint64_t vectorBytes(const std::vector& values) { } std::uint64_t descriptorBindingBytes(const DescriptorBinding& binding) { - return vectorBytes(binding.guestDescriptor) + vectorBytes(binding.imageShapes) + vectorBytes(binding.imageSamplers) + vectorBytes(binding.bufferExtent) + vectorBytes(binding.samplerDepthCompare) + vectorBytes(binding.imageWritten) + vectorBytes(binding.imageDepthCompare) + vectorBytes(binding.imageAtomic) + vectorBytes(binding.imageAtomic64) + vectorBytes(binding.bufferAtomic) + vectorBytes(binding.bufferWritten) + vectorBytes(binding.samplerUnnormalized) + vectorBytes(binding.samplerIntegerBorder) + vectorBytes(binding.samplerCoordinatesIgnored) + vectorBytes(binding.imageUnnormalized) + vectorBytes(binding.imageUnnormalizedBaseLevel) + vectorBytes(binding.bufferRead); + return vectorBytes(binding.guestDescriptor) + vectorBytes(binding.samplerEmbedded) + vectorBytes(binding.samplerEmbeddedWords) + vectorBytes(binding.imageShapes) + vectorBytes(binding.imageSamplers) + vectorBytes(binding.bufferExtent) + vectorBytes(binding.samplerDepthCompare) + vectorBytes(binding.imageWritten) + vectorBytes(binding.imageDepthCompare) + vectorBytes(binding.imageAtomic) + vectorBytes(binding.imageAtomic64) + vectorBytes(binding.bufferAtomic) + vectorBytes(binding.bufferWritten) + vectorBytes(binding.samplerUnnormalized) + vectorBytes(binding.samplerIntegerBorder) + vectorBytes(binding.samplerCoordinatesIgnored) + vectorBytes(binding.imageUnnormalized) + vectorBytes(binding.imageUnnormalizedBaseLevel) + vectorBytes(binding.bufferRead); } std::uint64_t resultBytes(const RecompileResult& result) { diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 252397e80be8..eb4bdfa0b6c9 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -583,6 +583,8 @@ struct DescriptorBinding { std::vector samplerUnnormalized; std::vector samplerIntegerBorder; std::vector samplerCoordinatesIgnored; + std::vector samplerEmbedded; + std::vector samplerEmbeddedWords; std::vector imageUnnormalized; std::vector imageUnnormalizedBaseLevel; std::vector imageSamplers; diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index 5912f183af30..276795b47417 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -86,6 +86,8 @@ inline constexpr std::uint32_t GpuImageHeapSlots = static_cast(Bi inline constexpr std::uint32_t GpuSamplerHeapSlots = 2048u; inline constexpr std::uint32_t GpuDataSet = 2u; inline constexpr std::uint32_t GpuGdsSet = 4u; +inline constexpr std::uint32_t EmbeddedSamplerSet = 6u; +inline constexpr std::uint32_t NoEmbeddedSampler = ~0u; inline constexpr std::uint32_t GdsBytes = 0x10000u; inline constexpr std::uint32_t PushDataDwords = 64u; inline constexpr std::uint32_t PushedDataWantedLimit = 48u; diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index 405e0a0cf19c..eb9056af9f75 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -90,7 +90,7 @@ static_assert(sizeof(ShaderInvocation) == 240, "ShaderInvocation changed: update #if defined(__cpp_lib_atomic_shared_ptr) static_assert(sizeof(RecompileResult) == 648, "RecompileResult changed: update EncodeResult and DecodeResult"); #endif -static_assert(sizeof(DescriptorBinding) == 656, "DescriptorBinding changed: update the binding encoder"); +static_assert(sizeof(DescriptorBinding) == 704, "DescriptorBinding changed: update the binding encoder"); static_assert(sizeof(VertexAttribute) == 32, "VertexAttribute changed: update the attribute encoder"); static_assert(sizeof(VertexInput) == 16, "VertexInput changed: update the vertex input encoder"); static_assert(sizeof(FragmentParameter) == 16, "FragmentParameter changed: update the parameter encoder"); @@ -98,7 +98,7 @@ static_assert(sizeof(CompiledShaderInfo) == 400, "CompiledShaderInfo changed: up static_assert(sizeof(ShaderInfo) == 232, "ShaderInfo changed: update the info encoder"); static_assert(sizeof(BufferResource) == 32, "BufferResource changed: update the info encoder"); static_assert(sizeof(ImageResource) == 108, "ImageResource changed: update the info encoder"); -static_assert(sizeof(SamplerResource) == 24, "SamplerResource changed: update the info encoder"); +static_assert(sizeof(SamplerResource) == 44, "SamplerResource changed: update the info encoder"); static_assert(sizeof(SampledResourcePair) == 16, "SampledResourcePair changed: update the info encoder"); static_assert(sizeof(StageInput) == 56, "StageInput changed: update the info encoder"); static_assert(sizeof(StageOutput) == 48, "StageOutput changed: update the info encoder"); @@ -144,7 +144,7 @@ constexpr std::size_t fieldCount() { static_assert(fieldCount() == 24, "ShaderInfo changed: update the info encoder"); static_assert(fieldCount() == 12, "BufferResource changed: update the info encoder"); static_assert(fieldCount() == 50, "ImageResource changed: update the info encoder"); -static_assert(fieldCount() == 8, "SamplerResource changed: update the info encoder"); +static_assert(fieldCount() == 10, "SamplerResource changed: update the info encoder"); static_assert(fieldCount() == 4, "SampledResourcePair changed: update the info encoder"); static_assert(fieldCount() == 5, "StageInput changed: update the info encoder"); static_assert(fieldCount() == 4, "StageOutput changed: update the info encoder"); @@ -477,6 +477,8 @@ void encodeBinding(Writer& writer, const DescriptorBinding& binding) { writer.Flags(binding.imageUnnormalizedBaseLevel); writer.Flags(binding.samplerIntegerBorder); writer.Flags(binding.samplerCoordinatesIgnored); + writer.Values(std::span(binding.samplerEmbedded)); + writer.Values(std::span(binding.samplerEmbeddedWords)); writer.Values(std::span(binding.imageSamplers)); writer.Flags(binding.bufferRead); writer.Values(std::span(binding.bufferExtent)); @@ -506,6 +508,8 @@ void decodeBinding(Reader& reader, DescriptorBinding& binding) { reader.Flags(binding.imageUnnormalizedBaseLevel); reader.Flags(binding.samplerIntegerBorder); reader.Flags(binding.samplerCoordinatesIgnored); + reader.Values(binding.samplerEmbedded); + reader.Values(binding.samplerEmbeddedWords); reader.Values(binding.imageSamplers); reader.Flags(binding.bufferRead); reader.Values(binding.bufferExtent); @@ -878,6 +882,8 @@ void encodeShaderInfo(Writer& writer, const ShaderInfo& info) { out.Value(sampler.uses); out.Value(sampler.foldTexelOffsetsOnly); out.Value(sampler.table); + out.Value(sampler.constant); + for (const auto word : sampler.constantWords) out.Value(word); }); writer.List(info.sampledPairs, [](Writer& out, const SampledResourcePair& pair) { out.Value(pair.image); @@ -987,7 +993,7 @@ void decodeShaderInfo(Reader& reader, ShaderInfo& info) { bool preparedImageModes = false; reader.Value(preparedImageModes); if (preparedImageModes) ResourceMaterializer::PrepareImageModes(info); - reader.List(info.samplers, 21, [](Reader& in, SamplerResource& sampler) { + reader.List(info.samplers, 38, [](Reader& in, SamplerResource& sampler) { in.Value(sampler.source); in.Value(sampler.firstUsePc); in.Value(sampler.copyOf); @@ -996,6 +1002,8 @@ void decodeShaderInfo(Reader& reader, ShaderInfo& info) { in.Value(sampler.uses); in.Value(sampler.foldTexelOffsetsOnly); in.Value(sampler.table); + in.Value(sampler.constant); + for (auto& word : sampler.constantWords) in.Value(word); }); reader.List(info.sampledPairs, 13, [](Reader& in, SampledResourcePair& pair) { in.Value(pair.image); diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index a2a4476a2dcc..01c994efec02 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -13,7 +13,7 @@ namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 59; +inline constexpr std::uint32_t FormatVersion = 60; enum class LoadStatus { Loaded, diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index 69a74d60c548..f4ecd8d2c728 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -264,6 +264,7 @@ struct SpirvEmitterState { std::unordered_set meshWindowBufferLoads; std::array imageVariables {}; std::uint32_t samplerVariable = 0; + std::map embeddedSamplerVariables; std::vector tableImageVariables; std::uint32_t tableSamplerVariable = 0; std::uint32_t tableMapVariable = 0; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp index 5b1420dde035..1a70c04465ba 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp @@ -274,7 +274,16 @@ std::uint32_t LoadSamplerDescriptor(SpirvEmitterState& state, std::uint32_t samp } const auto arrayIndex = ResourceForDescriptor(state, DescriptorBindingKind::Samplers, sampler) + (point ? 1u : 0u); std::uint32_t pointer = 0; - if (state.gpuResolvedImages) { + if (state.gpuResolvedImages && samplerResource.constant) { + auto& variable = state.embeddedSamplerVariables[arrayIndex]; + if (variable == 0u) { + variable = state.module.DefineGlobalVariable(pointerType, spv::StorageClassUniformConstant); + state.module.AddName(variable, "embedded_sampler"); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, RuntimeAbi::EmbeddedSamplerSet); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, arrayIndex); + } + pointer = variable; + } else if (state.gpuResolvedImages) { if (state.samplerVariable == 0) ExitDescriptorBindingFailure(state, DescriptorBindingKind::Samplers, sampler, "sampler descriptor array was not emitted"); state.module.EmitCapability(spv::CapabilitySampledImageArrayDynamicIndexing); const auto slot = LoadHeapSlotWord(state, state.program.Metadata().bindings.SamplerSlotDword() + arrayIndex); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 65003ca910ea..d78ba15c582b 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -265,6 +265,8 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_DCC_PRESYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | leaves the DCC key ranges out of the surfaces a build pre-syncs, so only the surface itself waits for its producer | | `APS5_NO_DEFERRED_DESTRUCTION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | on MoltenVK, destroys buffers and frees device memory as soon as the driver releases them, instead of while the graphics queue is idle (KhronosGroup/MoltenVK#2876) | | `APS5_NO_DCC_WORD_SCAN` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp` | | restores the byte-by-byte DCC key scan instead of the word-at-a-time compare | +| `APS5_EMBEDDED_SAMPLER_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device limit | caps the samplers the GPU heap embeds in pipelines below the device's maxDescriptorHeapEmbeddedSamplers; constant samplers past it read a sampler heap slot at a fixed offset (testing) | +| `APS5_NO_EMBEDDED_SAMPLERS` | presence | `core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp` | | GPU heap stages fetch samplers whose four descriptor words are constants in the shader code from the sampler heap, like every other sampler, instead of as samplers embedded in the pipeline's descriptor mapping (vkd3d-proton's static samplers) | | `APS5_NO_DEFERRED_EVICTION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | destroys displaced resource-cache entries under the mutex instead of deferring them to the open batch | | `APS5_NO_DEFERRED_SETTLES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | settles watched private host imports as they open instead of through the deferred block-settling path (Windows only) | | `APS5_NO_DEPTH_TRANSFER_PASS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp` | | copies a D32 depth plane into a 32-bit color storage image (one `vkCmdCopyImage` where `APS5_NO_DIRECT_DEPTH_COPY` allows it, else through the staging buffer) instead of reading it into the image in a compute pass (used when `VK_KHR_push_descriptor` is enabled); copies back into the depth plane never use the pass | From 31d84cfedc2434eeb79bde33532e103436546238 Mon Sep 17 00:00:00 2001 From: Dean Galvin Date: Fri, 6 Nov 2026 21:34:58 +1300 Subject: [PATCH 125/269] fix(agc): include embedded sampler state in the compute pipeline identity RecompileResult::Identity() mixed the SPIR-V hash, specialization constants, subgroup flags and each binding's set, binding, kind and count, but not the embedded sampler state. ComputePipelineKey::Of and the pipeline journal key on that identity, so under APS5_GPU_HEAP two stages with the same code and different constant-sampler words or flags shared one pipeline and sampled with the first stage's embedded sampler. Mix samplerEmbedded, samplerEmbeddedWords and the depth-compare, unnormalized, integer-border and coordinates-ignored flags the embedded sampler is built from, and test that the words, the element index and each flag change the identity. Raised by EagleBearerYS. Fix-up on Raghav314's change. --- .../prx/libSceAgcDriver/tests/Graphics.cpp | 18 ++++++++++++++++++ core/shader/recompiler/Recompiler.hpp | 12 +++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index d444782f2cb3..79bd7ff985d0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -12947,6 +12947,24 @@ void pipelineJournalTests(bool longPath = false, bool extended = false) { subgroup.hostSubgroupSize = 64; Require(!(subgroup.Identity() == constFirst.Identity()), "the host subgroup size did not enter the identity"); Require(ShaderRecompiler::RecompileResult{}.Identity().Empty(), "a result without a module has an identity"); + const auto embedded = [&](std::uint32_t element, std::uint32_t word) { + auto result = module(1); + auto& binding = result.bindings.emplace_back(); + binding.samplerEmbedded = {element}; + binding.samplerEmbeddedWords = {word, 1u, 2u, 3u}; + return result; + }; + Require(embedded(0u, 5u).Identity() == embedded(0u, 5u).Identity() && !(embedded(0u, 5u).Identity() == constFirst.Identity()), "an embedded sampler did not enter the identity"); + Require(!(embedded(0u, 5u).Identity() == embedded(0u, 6u).Identity()), "the embedded sampler words did not enter the identity"); + Require(!(embedded(0u, 5u).Identity() == embedded(1u, 5u).Identity()), "the embedded sampler element did not enter the identity"); + const auto flagged = [&](std::size_t flag) { + auto result = embedded(0u, 5u); + auto& binding = result.bindings.back(); + for (auto* flags : {&binding.samplerDepthCompare, &binding.samplerUnnormalized, &binding.samplerIntegerBorder, &binding.samplerCoordinatesIgnored}) flags->assign(1, false); + if (flag < 4u) (*std::array{&binding.samplerDepthCompare, &binding.samplerUnnormalized, &binding.samplerIntegerBorder, &binding.samplerCoordinatesIgnored}[flag])[0] = true; + return result; + }; + for (std::size_t flag = 0; flag < 4u; ++flag) Require(!(flagged(flag).Identity() == flagged(4u).Identity()), "an embedded sampler flag did not enter the identity"); } mock = MockVulkan{}; auto context = mockContext(); diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index eb4bdfa0b6c9..5344f6934cd4 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -879,7 +879,17 @@ struct RecompileResult : CompiledShaderArtifact, ShaderInvocation { for (const auto& constant : specialization) mix(constant.id | (static_cast(constant.value) << 32u)); mix(hostSubgroupSize | (fullSubgroups ? 0x10000u : 0u) | (functionLdsBuffer ? 0x20000u : 0u) | (meshWindowBuffer ? 0x40000u : 0u) | (static_cast(workgroupMemoryDwords) << 32u)); mix(bindings.size()); - for (const auto& binding : bindings) mix(binding.descriptorSet | (static_cast(binding.binding) << 16u) | (static_cast(binding.kind) << 40u) | (static_cast(binding.count) << 48u)); + for (const auto& binding : bindings) { + mix(binding.descriptorSet | (static_cast(binding.binding) << 16u) | (static_cast(binding.kind) << 40u) | (static_cast(binding.count) << 48u)); + mix(binding.samplerEmbedded.size()); + for (const auto value : binding.samplerEmbedded) mix(value); + mix(binding.samplerEmbeddedWords.size()); + for (const auto value : binding.samplerEmbeddedWords) mix(value); + for (const auto* flags : {&binding.samplerDepthCompare, &binding.samplerUnnormalized, &binding.samplerIntegerBorder, &binding.samplerCoordinatesIgnored}) { + mix(flags->size()); + for (std::size_t element = 0; element < flags->size(); ++element) mix((*flags)[element] ? 1u : 0u); + } + } if (identity.Empty()) identity.low = 1; return identity; } From 507a1762d71007fd2d8c59e62b0fe04ecd9c0eec Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 6 Nov 2026 12:46:57 +0530 Subject: [PATCH 126/269] perf(agc): keep draws on a nearly full GPU heap by submitting early When fewer than a margin of image or sampler slots were free, the GPU heap refused every draw and dispatch until owners released slots, and they took the per-draw descriptor path meanwhile. vkd3d-proton never leaves heap mode, and our heap can always make room: slots are only a cache of descriptors whose owners are still alive. Now the nearly full state asks the next draw or dispatch entry to submit the open batch. At that point no draw is being prepared, so the heap evicts the least recently used slots outright; they retire with that submission's serial, and a slot request that finds no free slot waits for it to complete. Other submissions, including ones made while a draw is being prepared, keep the two-idle-submission rule, so a slot a draw already took is never freed under it. Sampler slots get the same eviction as image slots (use epochs, touch on lookup and on template reuse, retiring entries), except samplers whose slot index a pipeline bakes in (the embedded-sampler fallback), which are pinned. Eviction runs only under the GPU mutex. A heap whose recorder has no timeline cannot evict and still refuses, as does every heap under APS5_NO_HEAP_EVICTION. The [gpu-heap] line counts evicted samplers and pressure submits. --- .../Execution/src/Driver/Draw/HeapStages.cpp | 2 +- .../Graphics/include/BindlessHeap.hpp | 25 ++- .../Graphics/src/BindlessHeap.cpp | 161 +++++++++++++++-- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 2 +- .../Graphics/src/ShaderResources.cpp | 2 +- .../tests/BindlessHeapSlots.cpp | 163 +++++++++++++++--- ...agc_driver_heap_compute_sample_tests.cmake | 2 + .../agc_driver_heap_draw_sample_tests.cmake | 8 +- .../cmake/agc_driver_heap_slots_tests.cmake | 2 +- .../tests/cmake/agc_shader_memory_tests.cmake | 4 +- .../tests/execution/HeapComputeSample.cpp | 9 +- .../tests/execution/HeapDrawSample.cpp | 7 +- docs/dev/ENVIRONMENT.md | 4 +- 13 files changed, 336 insertions(+), 55 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 3b220fea339a..6b3a5c48280c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -112,7 +112,7 @@ VerifyCounts& verifyCounts() { } bool HeapRefused() { - return Graphics::BindlessHeap::NearlyFull(); + return Graphics::BindlessHeap::RefusesDraws(); } namespace { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index af6b6368aaaf..a6bfd442698c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -66,15 +66,18 @@ class BindlessHeap { const Texture* SlotTexture(std::uint32_t kind, std::uint32_t slot) const; bool SlotHoldsStorage(std::uint32_t kind, std::uint32_t slot, const HeapSlotOwner* owner, VkImageView view) const; std::optional SamplerSlot(const std::shared_ptr& sampler); + std::optional PinnedSamplerSlot(const std::shared_ptr& sampler); std::uint32_t SamplerGeneration(std::uint32_t slot) const; std::uint64_t SlotSerial() const { return slotSerial.load(std::memory_order_acquire); } bool GenerationsCurrent(std::span> slots, std::span slotGenerations, std::span samplerSlots, std::span samplerGenerations) const; std::uint32_t AbsentSlot(std::uint32_t kind, VkImageView view); static bool NearlyFull(); + static bool RefusesDraws(); + static bool WaitsWhenFull(); static std::uint32_t ImageSlotCapacity(); std::uint32_t ImageSlots() const { return slotCap; } - std::uint32_t TouchSlots(std::span> slots, std::uint32_t touched) const; + std::uint32_t TouchSlots(std::span> slots, std::span samplerSlots, std::uint32_t touched) const; struct DataSpan { std::uint32_t offset = 0; @@ -98,13 +101,14 @@ class BindlessHeap { static constexpr std::uint32_t SamplerKind = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Samplers); void Submitted(Recorder& recorder, std::uint64_t serial); bool TakeRingPressure(); + bool TakeSlotPressure(); struct Counts { std::uint64_t ringWraps = 0, encodes = 0, encodedCopies = 0; std::uint64_t slotsFreed = 0, slotsReused = 0, slotsEvicted = 0, evictionWaits = 0; std::uint64_t ringWaits = 0, ringBatchPeakBytes = 0, ringSpanPeakBytes = 0, ringBytes = 0, imageSlotsHeld = 0; std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0, busyChunksSkipped = 0, bufferDescriptors = 0; - std::uint64_t ringPressureSubmits = 0; + std::uint64_t ringPressureSubmits = 0, slotPressureSubmits = 0, samplersEvicted = 0; std::uint64_t poolBytes = 0, poolBatchPeakBytes = 0, poolBlocksMade = 0, poolBlocksRecycled = 0, poolBlocksFreed = 0, poolBlocksHeld = 0, poolBlockBytes = 0; }; Counts Statistics() const; @@ -224,15 +228,27 @@ class BindlessHeap { struct RetiringSlot { std::uint32_t slot = 0; std::uint64_t serial = 0; + bool sampler = false; }; std::deque retiring; std::size_t ringBatchBytes = 0; std::atomic ringOpenChunks{0}; std::size_t retiringAssigned = 0; + std::size_t retiringSamplers = 0; + std::size_t samplerRetiringAssigned = 0; std::uint32_t evictScanEpoch = 0; + std::uint32_t samplerEvictScanEpoch = 0; + std::vector samplerOwners; + std::vector samplerPinned; + std::unique_ptr[]> samplerUses; + std::atomic pressured{false}; Recorder* submitter = nullptr; void touchLocked(std::uint32_t slot) const; - void evictLocked(); + void touchSamplerLocked(std::uint32_t slot) const; + void evictLocked(std::uint32_t idleSubmissions); + void evictSamplersLocked(std::uint32_t idleSubmissions); + std::optional samplerSlot(const std::shared_ptr& sampler, bool pin); + std::size_t imageRetiring() const { return retiring.size() - retiringSamplers; } bool reclaimLocked(bool wait); std::optional imageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view, VkImageLayout layout, Texture* texture); SlotOwner& claimSlotLocked(const ImageSlotKey& key, std::uint32_t slot); @@ -241,6 +257,7 @@ class BindlessHeap { std::unordered_map samplerSlots; std::unordered_set absentSlots; bool refused = false; + bool refusing = false; void noteRefusedLocked(const char* what, std::uint32_t margin); void noteTakenLocked(); void noteSamplerTakenLocked(); @@ -282,6 +299,8 @@ void NoteEmptyResourceSet(); std::uint64_t EmptyResourceSets(); std::uint64_t DataAddressPushes(); std::uint64_t EmbeddedSamplerMappings(); +std::uint64_t SlotPressureSubmits(); +std::uint64_t HeapSlotEvictions(); enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, DepthTransfer, StagedMerge, FirstSampleCopy, Count }; enum class HeapFallback : std::uint8_t { DrawUnmapped, DrawMixedRetry, DrawRefusedPair, DrawMixedReused, DispatchUnmapped, Count }; enum class HeapStageReason : std::uint8_t { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 2fedf203746d..d145f461bce7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -82,6 +82,8 @@ std::atomic descriptorHeapDevice{false}; std::atomic imageTableBuilds{0}; std::atomic dataAddressPushes{0}; std::atomic embeddedSamplerMappings{0}; +std::atomic slotPressureSubmits{0}; +std::atomic heapSlotEvictions{0}; std::atomic emptyResourceSets{0}; } @@ -111,6 +113,14 @@ std::uint64_t EmbeddedSamplerMappings() { return embeddedSamplerMappings.load(std::memory_order_relaxed); } +std::uint64_t SlotPressureSubmits() { + return slotPressureSubmits.load(std::memory_order_relaxed); +} + +std::uint64_t HeapSlotEvictions() { + return heapSlotEvictions.load(std::memory_order_relaxed); +} + void NoteEmptyResourceSet() { emptyResourceSets.fetch_add(1, std::memory_order_relaxed); } @@ -285,6 +295,7 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { imagePool.next = SamplerKind; imagePool.limit = slotCap; samplerPool.limit = Abi::GpuSamplerHeapSlots; + samplerUses = std::make_unique[]>(Abi::GpuSamplerHeapSlots); } namespace { @@ -293,11 +304,18 @@ constexpr std::uint32_t ImageSlotMargin = 1024u; constexpr std::uint32_t EvictIdleSubmissions = 2u; constexpr std::uint32_t SamplerSlotMargin = Abi::GpuSamplerHeapSlots / 4u; std::atomic refusedHeaps{0}; +std::atomic refusingHeaps{0}; + +bool waitsWhenFull() { + static const bool waits = std::getenv("APS5_NO_HEAP_EVICTION") == nullptr; + return waits; +} } BindlessHeap::~BindlessHeap() { if (refused) refusedHeaps.fetch_sub(1, std::memory_order_relaxed); + if (refusing) refusingHeaps.fetch_sub(1, std::memory_order_relaxed); } namespace { @@ -400,6 +418,8 @@ void BindlessHeap::ReleaseSlots(const HeapSlotOwner* owner) { released = true; } if (const auto found = samplerSlots.find(owner); found != samplerSlots.end()) { + samplerOwners[found->second] = nullptr; + samplerPinned[found->second] = false; samplerPool.Free(found->second); samplerSlots.erase(found); ++counts.slotsFreed; @@ -462,6 +482,16 @@ bool BindlessHeap::NearlyFull() { return refusedHeaps.load(std::memory_order_relaxed) != 0u; } +bool BindlessHeap::WaitsWhenFull() { + return waitsWhenFull(); +} + +bool BindlessHeap::RefusesDraws() { + return refusingHeaps.load(std::memory_order_relaxed) != 0u; +} + + + std::uint32_t BindlessHeap::ImageSlotCapacity() { return deviceImageSlots.load(std::memory_order_relaxed) - SamplerKind; } @@ -472,20 +502,27 @@ std::uint32_t BindlessHeap::imageMargin() const { bool BindlessHeap::roomLocked() const { if (imagePool.Unused() + retiringAssigned < 2u * static_cast(imageMargin())) return false; - return samplerPool.Unused() >= 2u * SamplerSlotMargin; + return samplerPool.Unused() + samplerRetiringAssigned >= 2u * SamplerSlotMargin; } void BindlessHeap::noteRefusedLocked(const char* what, std::uint32_t margin) { if (refused) return; refused = true; refusedHeaps.fetch_add(1, std::memory_order_relaxed); + if (waitsWhenFull() && (submitter == nullptr || submitter->HasTimeline())) { + pressured.store(true, std::memory_order_relaxed); + std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; the next draw or dispatch submits its batch so idle slots can be evicted\n", margin, what); + return; + } + refusing = true; + refusingHeaps.fetch_add(1, std::memory_order_relaxed); std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; draws and dispatches take the per-draw path until released slots leave twice that many free\n", margin, what); } void BindlessHeap::noteTakenLocked() { const auto margin = imageMargin(); if (imagePool.Unused() >= 2u * static_cast(margin)) return; - if (imagePool.Unused() + retiring.size() < 2u * static_cast(margin)) evictLocked(); + if (imagePool.Unused() + imageRetiring() < 2u * static_cast(margin)) evictLocked(EvictIdleSubmissions); if (!refused && imagePool.Unused() + retiringAssigned < margin) noteRefusedLocked("image", margin); } @@ -493,7 +530,11 @@ void BindlessHeap::touchLocked(std::uint32_t slot) const { if (slot < slotCap) slotUses[slot].store(useEpoch.load(std::memory_order_relaxed), std::memory_order_relaxed); } -std::uint32_t BindlessHeap::TouchSlots(std::span> slots, std::uint32_t touched) const { +void BindlessHeap::touchSamplerLocked(std::uint32_t slot) const { + if (slot < Abi::GpuSamplerHeapSlots) samplerUses[slot].store(useEpoch.load(std::memory_order_relaxed), std::memory_order_relaxed); +} + +std::uint32_t BindlessHeap::TouchSlots(std::span> slots, std::span samplerSlots, std::uint32_t touched) const { const auto epoch = useEpoch.load(std::memory_order_relaxed); if (touched == epoch) return epoch; for (const auto& kindSlots : slots) { @@ -501,20 +542,23 @@ std::uint32_t BindlessHeap::TouchSlots(std::spanHasTimeline() || evictScanEpoch == epoch) return; - GuestMemory::AssertGpuLockHeld("BindlessHeap::evictLocked"); - evictScanEpoch = epoch; + if (disabled || submitter == nullptr || !submitter->HasTimeline() || !GuestMemory::GpuMutex().HeldByThisThread()) return; + if (idleSubmissions != 0u && evictScanEpoch == epoch) return; + if (idleSubmissions != 0u) evictScanEpoch = epoch; std::vector> idle; for (std::uint32_t slot = SamplerKind; slot < imagePool.next && slot < owners.size(); ++slot) { if (owners[slot].key.owner == nullptr) continue; const auto use = slotUses[slot].load(std::memory_order_relaxed); - if (use + EvictIdleSubmissions <= epoch) idle.emplace_back(use, slot); + if (use + idleSubmissions <= epoch) idle.emplace_back(use, slot); } const auto wanted = std::min(idle.size(), 4u * static_cast(imageMargin())); if (wanted == 0u) return; @@ -533,6 +577,35 @@ void BindlessHeap::evictLocked() { ++imagePool.generations[slot]; retiring.push_back({slot, 0u}); ++counts.slotsEvicted; + heapSlotEvictions.fetch_add(1, std::memory_order_relaxed); + } + slotSerial.fetch_add(1, std::memory_order_release); +} + +void BindlessHeap::evictSamplersLocked(std::uint32_t idleSubmissions) { + static const bool disabled = std::getenv("APS5_NO_HEAP_EVICTION") != nullptr; + const auto epoch = useEpoch.load(std::memory_order_relaxed); + if (disabled || submitter == nullptr || !submitter->HasTimeline() || !GuestMemory::GpuMutex().HeldByThisThread()) return; + if (idleSubmissions != 0u && samplerEvictScanEpoch == epoch) return; + if (idleSubmissions != 0u) samplerEvictScanEpoch = epoch; + std::vector> idle; + for (std::uint32_t slot = 0; slot < samplerPool.next && slot < samplerOwners.size(); ++slot) { + if (samplerOwners[slot] == nullptr || samplerPinned[slot]) continue; + const auto use = samplerUses[slot].load(std::memory_order_relaxed); + if (use + idleSubmissions <= epoch) idle.emplace_back(use, slot); + } + const auto wanted = std::min(idle.size(), 2u * static_cast(SamplerSlotMargin)); + if (wanted == 0u) return; + std::nth_element(idle.begin(), idle.begin() + static_cast(wanted - 1u), idle.end()); + for (std::size_t index = 0; index < wanted; ++index) { + const auto slot = idle[index].second; + samplerSlots.erase(samplerOwners[slot]); + samplerOwners[slot] = nullptr; + ++samplerPool.generations[slot]; + retiring.push_back({slot, 0u, true}); + ++retiringSamplers; + ++counts.samplersEvicted; + heapSlotEvictions.fetch_add(1, std::memory_order_relaxed); } slotSerial.fetch_add(1, std::memory_order_release); } @@ -547,9 +620,16 @@ bool BindlessHeap::reclaimLocked(bool wait) { ++counts.evictionWaits; } while (!retiring.empty() && retiring.front().serial != 0u && retiring.front().serial <= serial) { - imagePool.free.push_back(retiring.front().slot); + const auto entry = retiring.front(); retiring.pop_front(); - --retiringAssigned; + if (entry.sampler) { + samplerPool.free.push_back(entry.slot); + --retiringSamplers; + --samplerRetiringAssigned; + } else { + imagePool.free.push_back(entry.slot); + --retiringAssigned; + } reclaimed = true; } } @@ -558,13 +638,23 @@ bool BindlessHeap::reclaimLocked(bool wait) { } void BindlessHeap::noteSamplerTakenLocked() { - if (!refused && samplerPool.Unused() < SamplerSlotMargin) noteRefusedLocked("sampler", SamplerSlotMargin); + if (samplerPool.Unused() >= 2u * SamplerSlotMargin) return; + if (samplerPool.Unused() + retiringSamplers < 2u * SamplerSlotMargin) evictSamplersLocked(EvictIdleSubmissions); + if (!refused && samplerPool.Unused() + samplerRetiringAssigned < SamplerSlotMargin) noteRefusedLocked("sampler", SamplerSlotMargin); +} + +std::optional BindlessHeap::PinnedSamplerSlot(const std::shared_ptr& sampler) { + return samplerSlot(sampler, true); } void BindlessHeap::noteReleasedLocked() { if (!refused || !roomLocked()) return; refused = false; refusedHeaps.fetch_sub(1, std::memory_order_relaxed); + pressured.store(false, std::memory_order_relaxed); + if (!refusing) return; + refusing = false; + refusingHeaps.fetch_sub(1, std::memory_order_relaxed); std::fprintf(stderr, "[gpu-heap] released slots left twice the margin free; draws take the heap again\n"); } @@ -618,16 +708,32 @@ std::uint32_t BindlessHeap::AbsentSlot(std::uint32_t kind, VkImageView view) { } std::optional BindlessHeap::SamplerSlot(const std::shared_ptr& sampler) { + return samplerSlot(sampler, false); +} + +std::optional BindlessHeap::samplerSlot(const std::shared_ptr& sampler, bool pin) { Require(sampler != nullptr, "bindless heap: invalid sampler slot request"); std::lock_guard lock(mutex); - if (const auto found = samplerSlots.find(static_cast(sampler.get())); found != samplerSlots.end()) return found->second; + if (const auto found = samplerSlots.find(static_cast(sampler.get())); found != samplerSlots.end()) { + touchSamplerLocked(found->second); + if (pin) samplerPinned[found->second] = true; + return found->second; + } bool reused = false; - const auto slot = samplerPool.Take(reused); + auto slot = samplerPool.Take(reused); + if (!slot && reclaimLocked(true)) slot = samplerPool.Take(reused); if (!slot) return std::nullopt; if (reused) ++counts.slotsReused; writeSamplerSlot(*slot, sampler->Handle()); const HeapSlotOwner* owner = sampler.get(); samplerSlots.emplace(owner, *slot); + if (samplerOwners.size() <= *slot) { + samplerOwners.resize(*slot + 1u, nullptr); + samplerPinned.resize(*slot + 1u, false); + } + samplerOwners[*slot] = owner; + samplerPinned[*slot] = pin; + touchSamplerLocked(*slot); owner->heapSlotted.store(true, std::memory_order_release); noteSamplerTakenLocked(); return slot; @@ -757,6 +863,17 @@ void BindlessHeap::trimPoolLocked() { } } +bool BindlessHeap::TakeSlotPressure() { + if (!pressured.load(std::memory_order_relaxed)) return false; + std::lock_guard lock(mutex); + if (!refused) return false; + if (imagePool.Unused() + imageRetiring() < 2u * static_cast(imageMargin())) evictLocked(0u); + if (samplerPool.Unused() + retiringSamplers < 2u * SamplerSlotMargin) evictSamplersLocked(0u); + ++counts.slotPressureSubmits; + slotPressureSubmits.fetch_add(1, std::memory_order_relaxed); + return true; +} + bool BindlessHeap::TakeRingPressure() { if (ringChunks.empty() || ringOpenChunks.load(std::memory_order_relaxed) < std::max(2u, ringChunks.size() / 2u)) return false; std::lock_guard lock(mutex); @@ -1141,7 +1258,7 @@ std::optional BindlessHeap::embeddedSampler return mapping; } if (entry.slot == ~0u) { - const auto slot = const_cast(this)->SamplerSlot(entry.heapSampler); + const auto slot = const_cast(this)->PinnedSamplerSlot(entry.heapSampler); Require(slot.has_value(), "the global sampler heap is full"); entry.slot = *slot; } @@ -1365,6 +1482,8 @@ void reportHeapStatistics() { totals.ringSpanPeakBytes = std::max(totals.ringSpanPeakBytes, counts.ringSpanPeakBytes); totals.poolBytes += counts.poolBytes; totals.ringPressureSubmits += counts.ringPressureSubmits; + totals.slotPressureSubmits += counts.slotPressureSubmits; + totals.samplersEvicted += counts.samplersEvicted; totals.poolBlocksMade += counts.poolBlocksMade; totals.poolBlocksRecycled += counts.poolBlocksRecycled; totals.poolBlocksFreed += counts.poolBlocksFreed; @@ -1387,6 +1506,8 @@ void reportHeapStatistics() { const auto ringMiB = windowDelta(totals.ringBytes, lastTotals.ringBytes) >> 20u; const auto poolMiB = windowDelta(totals.poolBytes, lastTotals.poolBytes) >> 20u; const auto pressureSubmits = windowDelta(totals.ringPressureSubmits, lastTotals.ringPressureSubmits); + const auto slotPressureSubmits = windowDelta(totals.slotPressureSubmits, lastTotals.slotPressureSubmits); + const auto samplersEvicted = windowDelta(totals.samplersEvicted, lastTotals.samplersEvicted); const auto poolMade = windowDelta(totals.poolBlocksMade, lastTotals.poolBlocksMade); const auto poolRecycled = windowDelta(totals.poolBlocksRecycled, lastTotals.poolBlocksRecycled); const auto poolFreed = windowDelta(totals.poolBlocksFreed, lastTotals.poolBlocksFreed); @@ -1395,10 +1516,10 @@ void reportHeapStatistics() { std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; descriptor ring %llu MiB, %llu waits, %llu busy chunks skipped, %llu early submits, since start at most %llu KiB per batch; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %llu of %u held, %llu evicted (%llu waits); templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; descriptor ring %llu MiB, %llu waits, %llu busy chunks skipped, %llu early submits, since start at most %llu KiB per batch; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(ringMiB), printed(ringWaits), printed(busySkips), printed(pressureSubmits), printed(totals.ringBatchPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(ringMiB), printed(ringWaits), printed(busySkips), printed(pressureSubmits), printed(totals.ringBatchPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { @@ -1571,10 +1692,12 @@ void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { useEpoch.fetch_add(1, std::memory_order_relaxed); counts.ringBatchPeakBytes = std::max(counts.ringBatchPeakBytes, ringBatchBytes); ringBatchBytes = 0; - if (refused && imagePool.Unused() + retiring.size() < 2u * static_cast(imageMargin())) evictLocked(); + if (refused && imagePool.Unused() + imageRetiring() < 2u * static_cast(imageMargin())) evictLocked(EvictIdleSubmissions); + if (refused && samplerPool.Unused() + retiringSamplers < 2u * SamplerSlotMargin) evictSamplersLocked(EvictIdleSubmissions); for (auto entry = retiring.rbegin(); entry != retiring.rend() && entry->serial == 0u; ++entry) { entry->serial = serial; - ++retiringAssigned; + if (entry->sampler) ++samplerRetiringAssigned; + else ++retiringAssigned; } if (!retiring.empty()) reclaimLocked(false); noteReleasedLocked(); @@ -1605,7 +1728,7 @@ BindlessHeap::Counts BindlessHeap::Statistics() const { ++snapshot.poolBlocksHeld; snapshot.poolBlockBytes += block.bytes; } - snapshot.imageSlotsHeld = imagePool.next - std::min(imagePool.next, SamplerKind + imagePool.free.size() + retiring.size()); + snapshot.imageSlotsHeld = imagePool.next - std::min(imagePool.next, SamplerKind + imagePool.free.size() + imageRetiring()); return snapshot; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 65fbc4213a8a..3ba7c42ac2ae 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -3100,7 +3100,7 @@ void Recorder::KeepBytes(const void* owner, std::size_t bytes) { void Recorder::BoundDrawBatch() { BoundKeptBytes(); if (open == nullptr || !DescriptorHeapEnabled() || !GuestMemory::GpuMutex().HeldByThisThread()) return; - if (auto* heap = BindlessHeap::Existing(context); heap != nullptr && heap->TakeRingPressure()) Submit(); + if (auto* heap = BindlessHeap::Existing(context); heap != nullptr && (heap->TakeRingPressure() || heap->TakeSlotPressure())) Submit(); } void Recorder::BoundKeptBytes() { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index bbeec8515281..3e365190c645 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -7152,7 +7152,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { takeHeapSlots(heap, stageState, stageBit, key); noteHeapSlotGenerations(heap, stageState); } else { - stageState.touchedEpoch = heap.TouchSlots(stageState.slots, stageState.touchedEpoch); + stageState.touchedEpoch = heap.TouchSlots(stageState.slots, stageState.samplerSlots, stageState.touchedEpoch); } stageState.slotSerial = slotSerial; static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 4665c44bc05b..a42e4c1ba4f9 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -402,11 +402,11 @@ void heapComesBack(const Context& context, VkImageView view) { require(heap.TextureSlot(kind, held.back().get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture takes one of the eight capped slots"); } - require(BindlessHeap::NearlyFull(), "one free slot of eight refuses the heap"); + require(BindlessHeap::NearlyFull(), "one free slot of eight marks the heap nearly full"); for (std::size_t index = 0; index < 2u; ++index) heap.ReleaseSlots(held[index].get()); - require(BindlessHeap::NearlyFull(), "three free slots of eight leave the heap refused"); + require(BindlessHeap::NearlyFull(), "three free slots of eight leave the heap nearly full"); heap.ReleaseSlots(held[2].get()); - require(!BindlessHeap::NearlyFull(), "a release that leaves twice the margin free takes the heap again"); + require(!BindlessHeap::NearlyFull(), "a release that leaves twice the margin free clears the nearly full state"); for (std::size_t index = 3; index < held.size(); ++index) heap.ReleaseSlots(held[index].get()); BindlessHeap::Release(context.device); } @@ -427,6 +427,7 @@ bool idleSlotsEvicted(const Context& context, VkImageView view) { const auto take = [&](std::size_t index) { if (held.size() <= index) held.resize(index + 1u); if (held[index] == nullptr) held[index] = fakeTexture(index); + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); return heap.TextureSlot(kind, held[index].get(), view, VK_IMAGE_LAYOUT_GENERAL); }; for (std::size_t index = 0; index < 6u; ++index) { @@ -447,7 +448,7 @@ bool idleSlotsEvicted(const Context& context, VkImageView view) { require(take(7).has_value(), "the eighth texture takes the last never-used slot"); require(!take(8).has_value(), "an evicted slot is not reused before a submission covers the draws that used it"); submit(); - require(!BindlessHeap::NearlyFull(), "evicted slots a submission covers take the heap again"); + require(!BindlessHeap::NearlyFull(), "evicted slots a submission covers clear the nearly full state"); require(recorder.WaitSerialFor(recorder.Submissions(), ~std::uint64_t{0}), "the submission completes"); const auto reused = take(8); require(reused.has_value() && std::find(slots.begin(), slots.begin() + 5, *reused) != slots.begin() + 5, @@ -466,9 +467,9 @@ void storageComesBack(const Context& context, VkImageView view) { require(heap.StorageSlot(Abi::FirstStorageImageBinding, &owner, view).has_value(), "a storage owner takes one of the eight capped slots"); } - require(BindlessHeap::NearlyFull(), "storage owners that leave one free slot of eight refuse the heap"); + require(BindlessHeap::NearlyFull(), "storage owners that leave one free slot of eight mark the heap nearly full"); for (auto& owner : owners) heap.ReleaseSlots(&owner); - require(!BindlessHeap::NearlyFull(), "releasing the storage owners takes the heap again"); + require(!BindlessHeap::NearlyFull(), "releasing the storage owners clears the nearly full state"); BindlessHeap::Release(context.device); } @@ -482,13 +483,13 @@ void storageViewsComeBack(const Context& context, VkImageView view) { } } require(heap.StorageSlot(Abi::FirstStorageImageBinding, &owners[3], view).has_value(), "a single-view storage owner takes the seventh slot"); - require(BindlessHeap::NearlyFull(), "storage owners that leave one free slot of eight refuse the heap"); + require(BindlessHeap::NearlyFull(), "storage owners that leave one free slot of eight mark the heap nearly full"); const auto freed = heap.Statistics().slotsFreed; heap.ReleaseSlots(&owners[0]); require(heap.Statistics().slotsFreed == freed + 2u, "a storage owner's release freed " + std::to_string(heap.Statistics().slotsFreed - freed) + " of its two slots"); - require(BindlessHeap::NearlyFull(), "three free slots of eight leave the heap refused"); + require(BindlessHeap::NearlyFull(), "three free slots of eight leave the heap nearly full"); heap.ReleaseSlots(&owners[1]); - require(!BindlessHeap::NearlyFull(), "releasing a second two-view owner takes the heap again"); + require(!BindlessHeap::NearlyFull(), "releasing a second two-view owner clears the nearly full state"); heap.ReleaseSlots(&owners[2]); heap.ReleaseSlots(&owners[3]); BindlessHeap::Release(context.device); @@ -502,15 +503,15 @@ void mixedComesBack(const Context& context, VkImageView sampledView, VkImageView require(heap.TextureSlot(Abi::FirstImageBinding, textures.back().get(), sampledView, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture takes one of the eight capped slots"); } - require(!BindlessHeap::NearlyFull(), "four textures in eight capped slots leave the heap taken"); + require(!BindlessHeap::NearlyFull(), "four textures in eight capped slots do not mark the heap nearly full"); std::array owners{}; for (auto& owner : owners) { require(heap.StorageSlot(Abi::FirstStorageImageBinding, &owner, storageView).has_value(), "a storage owner takes one of the slots the textures left"); } - require(BindlessHeap::NearlyFull(), "storage owners that take the slots the textures left refuse the heap"); + require(BindlessHeap::NearlyFull(), "storage owners that take the slots the textures left mark the heap nearly full"); for (auto& owner : owners) heap.ReleaseSlots(&owner); - require(!BindlessHeap::NearlyFull(), "releasing the storage owners takes the heap again while the textures stay"); + require(!BindlessHeap::NearlyFull(), "releasing the storage owners clears the nearly full state while the textures stay"); for (const auto& texture : textures) heap.ReleaseSlots(texture.get()); BindlessHeap::Release(context.device); } @@ -520,9 +521,9 @@ void viewsComeBack(const Context& context, VkImageView view) { const auto kind = Abi::FirstStorageImageBinding + 27u; std::array owners{}; for (auto& owner : owners) require(heap.ViewSlot(kind, &owner, view).has_value(), "a view takes one of the eight capped slots"); - require(BindlessHeap::NearlyFull(), "views that leave one free slot of eight refuse the heap"); + require(BindlessHeap::NearlyFull(), "views that leave one free slot of eight mark the heap nearly full"); for (auto& owner : owners) heap.ReleaseSlots(&owner); - require(!BindlessHeap::NearlyFull(), "releasing the views takes the heap again"); + require(!BindlessHeap::NearlyFull(), "releasing the views clears the nearly full state"); BindlessHeap::Release(context.device); } @@ -532,16 +533,132 @@ void twoHeapsComeBack(const Context& context, VkImageView view) { std::array firstOwners{}, secondOwners{}; for (auto& owner : firstOwners) require(first->ViewSlot(Abi::FirstStorageImageBinding, &owner, view).has_value(), "a view takes one of the first heap's eight capped slots"); for (auto& owner : secondOwners) require(second->ViewSlot(Abi::FirstStorageImageBinding, &owner, view).has_value(), "a view takes one of the second heap's eight capped slots"); - require(BindlessHeap::NearlyFull(), "two nearly full heaps refuse the heap"); + require(BindlessHeap::NearlyFull(), "two nearly full heaps mark the heap nearly full"); for (auto& owner : secondOwners) second->ReleaseSlots(&owner); - require(BindlessHeap::NearlyFull(), "room in the second heap took the heap back while the first stays nearly full"); + require(BindlessHeap::NearlyFull(), "room in the second heap cleared the nearly full state while the first stays nearly full"); second.reset(); - require(BindlessHeap::NearlyFull(), "destroying the second heap took the heap back while the first stays nearly full"); + require(BindlessHeap::NearlyFull(), "destroying the second heap cleared the nearly full state while the first stays nearly full"); for (auto& owner : firstOwners) first->ReleaseSlots(&owner); - require(!BindlessHeap::NearlyFull(), "room in the last refused heap did not take the heap back"); + require(!BindlessHeap::NearlyFull(), "room in the last nearly full heap did not clear the nearly full state"); first.reset(); } +bool slotPressureSubmits(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + const auto kind = Abi::FirstImageBinding; + Recorder recorder(context, true); + if (!recorder.HasTimeline()) return false; + recorder.Activate(); + const auto submit = [&] { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(recorder.Commands()); + recorder.Submit(); + }; + require(BindlessHeap::WaitsWhenFull(), "a nearly full heap waits by default instead of refusing draws"); + std::vector> held; + std::vector slots; + for (std::size_t index = 0; index < 7u; ++index) { + held.push_back(fakeTexture(index)); + const auto slot = heap.TextureSlot(kind, held.back().get(), view, VK_IMAGE_LAYOUT_GENERAL); + require(slot.has_value(), "a texture takes one of the eight capped slots"); + slots.push_back(*slot); + } + require(BindlessHeap::NearlyFull() && !BindlessHeap::RefusesDraws(), "one free slot of eight marks the heap nearly full without refusing draws"); + submit(); + require(heap.Statistics().slotsEvicted == 0u && BindlessHeap::NearlyFull(), + "a submission in the middle of a draw evicts no slot the draw took in the batch it submitted"); + const auto submitsBefore = SlotPressureSubmits(); + const auto generation = heap.SlotGeneration(slots[0]); + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(recorder.Commands()); + require(heap.TakeSlotPressure() && SlotPressureSubmits() == submitsBefore + 1u, "a nearly full heap asks the next draw to submit its batch"); + recorder.Submit(); + } + require(heap.Statistics().slotsEvicted == slots.size(), "the pressure submission evicts every slot, since no draw is being prepared at draw entry"); + require(!heap.TakeSlotPressure() && !BindlessHeap::NearlyFull(), "slots the submission covers clear the nearly full state"); + require(heap.SlotGeneration(slots[0]) != generation && heap.SlotTexture(kind, slots[0]) == nullptr, "an evicted slot moves its generation and names no texture"); + for (std::size_t index = 7; index < 12u; ++index) { + held.push_back(fakeTexture(index)); + const auto slot = heap.TextureSlot(kind, held.back().get(), view, VK_IMAGE_LAYOUT_GENERAL); + require(slot.has_value(), "a new texture takes a slot after the pressure submission, waiting for it when none is free"); + } + const auto back = heap.TextureSlot(kind, held[0].get(), view, VK_IMAGE_LAYOUT_GENERAL); + require(back.has_value() && heap.SlotTexture(kind, *back) == held[0].get(), "an evicted texture takes a slot again"); + for (const auto& texture : held) heap.ReleaseSlots(texture.get()); + BindlessHeap::Release(context.device); + return true; +} + +void noTimelineRefuses(const Context& context, VkImageView view) { + auto& heap = BindlessHeap::For(context); + Recorder recorder(context, false); + recorder.Activate(); + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(recorder.Commands()); + recorder.Submit(); + } + std::vector> held; + for (std::size_t index = 0; index < 7u; ++index) { + held.push_back(fakeTexture(index)); + require(heap.TextureSlot(Abi::FirstImageBinding, held.back().get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture takes one of the eight capped slots"); + } + require(BindlessHeap::RefusesDraws() && !heap.TakeSlotPressure(), "a heap whose recorder has no timeline cannot evict, so it refuses draws instead of submitting early"); + for (const auto& texture : held) heap.ReleaseSlots(texture.get()); + require(!BindlessHeap::RefusesDraws(), "releasing the textures takes the heap again"); + BindlessHeap::Release(context.device); +} + +bool samplersEvicted(const Context& context) { + auto& heap = BindlessHeap::For(context); + Recorder recorder(context, true); + if (!recorder.HasTimeline()) return false; + recorder.Activate(); + const auto submit = [&] { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(recorder.Commands()); + recorder.Submit(); + }; + SamplerCache cache(Abi::GpuSamplerHeapSlots); + const auto sampler = [&](std::uint32_t bias) { + const std::array words{0u, 0u, bias, 0u}; + return cache.Get(context, words, false); + }; + constexpr std::uint32_t Taken = Abi::GpuSamplerHeapSlots - Abi::GpuSamplerHeapSlots / 4u + 8u; + const auto pinnedSampler = sampler(Taken); + const auto pinned = heap.PinnedSamplerSlot(pinnedSampler); + require(pinned.has_value(), "a pinned sampler takes a slot"); + const auto pinnedGeneration = heap.SamplerGeneration(*pinned); + std::vector> held; + std::vector slots; + for (std::uint32_t index = 0; index < Taken; ++index) { + held.push_back(sampler(index)); + const auto slot = heap.SamplerSlot(held.back()); + require(slot.has_value(), "a sampler takes a slot"); + require(*slot > *pinned, "the pinned sampler holds a lower slot than every later sampler"); + slots.push_back(*slot); + } + require(BindlessHeap::NearlyFull(), "too few free sampler slots mark the heap nearly full"); + const auto generation = heap.SamplerGeneration(slots[0]); + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + static_cast(recorder.Commands()); + require(heap.TakeSlotPressure(), "a heap short of sampler slots asks the next draw to submit its batch"); + recorder.Submit(); + } + require(heap.Statistics().samplersEvicted != 0u, "the pressure submission evicts samplers the new batch has not used"); + require(!BindlessHeap::NearlyFull(), "evicted sampler slots the submission covers clear the nearly full state"); + require(heap.SamplerGeneration(*pinned) == pinnedGeneration && heap.SamplerSlot(pinnedSampler) == pinned, "a pinned sampler slot is never evicted"); + require(heap.SamplerGeneration(slots[0]) != generation, "the oldest sampler's slot was evicted and moved its generation"); + require(recorder.WaitSerialFor(recorder.Submissions(), ~std::uint64_t{0}), "the submission completes"); + const auto back = heap.SamplerSlot(held[0]); + require(back.has_value(), "an evicted sampler takes a slot again"); + held.clear(); + BindlessHeap::Release(context.device); + return true; +} + } int main(int argc, char** argv) { @@ -601,9 +718,13 @@ int main(int argc, char** argv) { else if (mode == "views-come-back") viewsComeBack(context, storage); else if (mode == "two-heaps-come-back") twoHeapsComeBack(context, storage); else if (mode == "owner-views-release") ownerViewsRelease(context, storage); + else if (mode == "no-timeline-refuses") noTimelineRefuses(context, sampled); else if (mode == "shared-owner-release") sharedOwnerRelease(context, storage); - else if (mode == "idle-slots-evicted") { - if (!idleSlotsEvicted(context, sampled)) { + else if (mode == "idle-slots-evicted" || mode == "pressure-submit" || mode == "samplers-evicted") { + const bool ran = mode == "idle-slots-evicted" ? idleSlotsEvicted(context, sampled) + : mode == "pressure-submit" ? slotPressureSubmits(context, sampled) + : samplersEvicted(context); + if (!ran) { std::printf("skipped, the recorder has no timeline\n"); return VulkanTestSkipped; } @@ -612,7 +733,7 @@ int main(int argc, char** argv) { device->WaitIdle(); } device.reset(); - std::cout << "the refused heap comes back once released slots leave room (" << mode << ")\n"; + std::cout << "the nearly full heap recovers once released slots leave room (" << mode << ")\n"; return 0; } { diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake index a9d4ef8d3cbb..955a5c1a4c82 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake @@ -5,4 +5,6 @@ if(BUILD_TESTING AND TARGET agc_driver_heap_compute_sample_tests) ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) agc_add_env_test(agc_driver_heap_compute_sample_full_heap agc_driver_heap_compute_sample_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=4) + agc_add_env_test(agc_driver_heap_compute_sample_full_heap_refusing agc_driver_heap_compute_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=4 APS5_NO_HEAP_EVICTION=1) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake index c468b0a1252b..6afbc7b9e520 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake @@ -2,9 +2,13 @@ if(BUILD_TESTING AND TARGET agc_driver_heap_draw_sample_tests) agc_add_env_test(agc_driver_heap_draw_sample_heap agc_driver_heap_draw_sample_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) agc_add_env_test(agc_driver_heap_draw_sample_full_heap agc_driver_heap_draw_sample_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=1) + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=1 APS5_NO_HEAP_EVICTION=1) + agc_add_env_test(agc_driver_heap_draw_sample_heap_pressure agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5) + agc_add_env_test(agc_driver_heap_draw_sample_heap_pressure_pipelined agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) agc_add_env_test(agc_driver_heap_draw_sample_full_heap_pipelined agc_driver_heap_draw_sample_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=1 APS5_NO_HEAP_EVICTION=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) agc_add_env_test(agc_driver_heap_draw_sample_nogpl agc_driver_heap_draw_sample_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_NO_GPL=1) agc_add_env_test(agc_driver_heap_draw_sample_nogpl_heap agc_driver_heap_draw_sample_tests diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake index 8b9e7cfee37b..555c98a6bed7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake @@ -24,7 +24,7 @@ if(BUILD_TESTING) ARGS ring-large-spans ENV ANYPS5_NO_SHADER_CACHE=1) agc_add_env_test(agc_driver_heap_slots_ring_busy_chunks agc_driver_heap_slots_tests ARGS ring-busy-chunks ENV ANYPS5_NO_SHADER_CACHE=1 TIMEOUT 60) - foreach(agcHeapSlotsMode IN ITEMS comes-back storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release idle-slots-evicted) + foreach(agcHeapSlotsMode IN ITEMS comes-back storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release idle-slots-evicted pressure-submit samplers-evicted no-timeline-refuses) string(REPLACE "-" "_" agcHeapSlotsName "${agcHeapSlotsMode}") agc_add_env_test(agc_driver_heap_slots_${agcHeapSlotsName} agc_driver_heap_slots_tests ARGS ${agcHeapSlotsMode} ENV ANYPS5_NO_SHADER_CACHE=1) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake index f91b6a53e8c2..f2f85643cdcb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake @@ -60,7 +60,9 @@ if(BUILD_TESTING) add_test(NAME agc_driver_image_table_vouch_queued_draws COMMAND agc_driver_image_table_cache_bounds_tests --queued-draws) set_tests_properties(agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) agc_add_env_test(agc_driver_image_table_cache_bounds_heap_small agc_driver_image_table_cache_bounds_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=1 TIMEOUT 60) + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=1 APS5_NO_HEAP_EVICTION=1 TIMEOUT 60) + agc_add_env_test(agc_driver_image_table_cache_bounds_heap_pressure agc_driver_image_table_cache_bounds_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=8 TIMEOUT 60) if(WIN32) set_tests_properties(agc_shader_table_snapshot_reuse agc_shader_table_snapshot_reuse_unmasked agc_driver_image_table_vouched_lookups agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp index d9e3e2aa3178..82c4de523a0f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp @@ -91,12 +91,19 @@ void DriverSample(bool heap) { void FullHeapSample() { Outputs[0].fill(-1.0f); + const auto stagesBefore = AgcDriver::Graphics::HeapComputeStages(); + const auto submitsBefore = AgcDriver::Graphics::SlotPressureSubmits(); std::vector words; for (std::size_t index = 0; index < FullHeapTextures; ++index) Sample(words, ManyTextures[index].data(), Outputs[0].data() + 4u * index); Submit(words); for (std::size_t index = 0; index < FullHeapTextures; ++index) RequireSampled(Outputs[0].data() + 4u * index, SampleTexel, "texture " + std::to_string(index) + " of a heap with too few image slots", true); - Require(AgcDriver::Graphics::BindlessHeap::NearlyFull(), "the capped heap never ran short of image slots"); + if (!AgcDriver::Graphics::BindlessHeap::WaitsWhenFull()) { + Require(AgcDriver::Graphics::BindlessHeap::NearlyFull(), "the capped heap never ran short of image slots"); + return; + } + Require(AgcDriver::Graphics::SlotPressureSubmits() > submitsBefore, "the capped heap never submitted a batch early to free image slots"); + Require(AgcDriver::Graphics::HeapComputeStages() - stagesBefore == FullHeapTextures, "a compute stage left the heap while it ran short of image slots"); } void DeviceSample(AgcDriver::VulkanDevice& device, bool heap) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index 18a0cfa6b566..ae94c31a62f5 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -379,7 +379,7 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { std::to_string(StorageMemory[channel]) + ", expected the sampled " + std::to_string(Texel[channel]) + (heap ? " through the heap" : "")); } - if (!heap || std::getenv("APS5_HEAP_SLOT_CAP") != nullptr) return; + if (!heap || (std::getenv("APS5_HEAP_SLOT_CAP") != nullptr && !AgcDriver::Graphics::BindlessHeap::WaitsWhenFull())) return; if (mode == Mode::Vertex || mode == Mode::VertexTable) Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, "the heap did not take the sampling vertex stage with descriptor memory"); @@ -465,7 +465,10 @@ int main() { DrawSamplesTheTexture(heap, mode); const bool capped = heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr; if (heap && !capped) MixedDrawTakesThePerDrawPath(); - if (capped) + if (capped && AgcDriver::Graphics::BindlessHeap::WaitsWhenFull()) + Require(AgcDriver::Graphics::HeapSlotEvictions() != 0u && !AgcDriver::DriverDetail::HeapRefused(), + "the capped heap refused draws instead of evicting image slots"); + else if (capped) Require(AgcDriver::DriverDetail::HeapRefused(), "a draw found the capped heap full and the heap was not refused"); AgcDriverShutdown_nid_postfix(); if (heap && !capped) diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index d78ba15c582b..736eb28c8803 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -203,9 +203,9 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_HEAP_MIRROR_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 24576 | budget in MiB for the heap mirrors held for registered allocations | | `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first | | `APS5_HEAP_WALK_MEMO_MB` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | 256 | MiB each thread's GPU heap walk memo may hold across both its generations before the previous generation and then the oldest walks are dropped (0 keeps them until the 16,384-key cap rotates them out) | -| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a stage needing more image slots than this takes the per-draw path | +| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a nearly full heap submits the open batch at the next draw or dispatch and evicts the slots that batch no longer uses (see `APS5_NO_HEAP_EVICTION`) | | `APS5_HEAP_RING_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 16 | MiB of the GPU heap's per-draw buffer descriptor ring inside the resource heap, between 4 and 64, in whole 2 MiB chunks and within the device's heap size; one draw's descriptors may take at most a quarter of the ring, and a batch is submitted early once it holds half the ring (shader data lives in a data pool that grows instead) | -| `APS5_NO_HEAP_EVICTION` | flag | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | unset | set: a nearly full GPU heap no longer evicts image slots no draw used for two submissions, so draws take the per-draw path until owners release slots | +| `APS5_NO_HEAP_EVICTION` | flag | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | unset | set: a nearly full GPU heap neither evicts image or sampler slots nor submits the open batch early to free them; draws and dispatches take the per-draw path until owners release slots | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | | `APS5_HOOK_LOCKED_WAIT` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | keeps the flush hook's pending-write wait under the GpuMutex | From 77b55d6c83bf2cd3546752acb6a9b8741f680b10 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 6 Nov 2026 13:04:41 +0530 Subject: [PATCH 127/269] refactor(agc): drop the GPU heap's kill switches for finished features APS5_NO_EMBEDDED_SAMPLERS, APS5_NO_HEAP_PUSHED_DATA, APS5_NO_HEAP_DEVICE_DESCRIPTORS and APS5_NO_HEAP_EVICTION only switched back to older behaviour that the heap no longer needs. Constant samplers are always embedded, heap stages always push their hottest shader data, the heap and data pool are always tried in device-local host-visible memory first, and a nearly full heap always evicts. Only a heap whose recorder has no timeline still refuses draws when full. The capped-heap test variants now run the eviction path (draws at five image slots, image tables at eight) instead of the refusal path. --- .../Graphics/include/BindlessHeap.hpp | 2 - .../Graphics/src/BindlessHeap.cpp | 41 ++++++------------- .../tests/BindlessHeapSlots.cpp | 1 - ...agc_driver_heap_compute_sample_tests.cmake | 2 - .../agc_driver_heap_draw_sample_tests.cmake | 6 +-- ...c_driver_heap_embedded_sampler_tests.cmake | 2 - .../tests/cmake/agc_shader_memory_tests.cmake | 2 - .../tests/execution/HeapComputeSample.cpp | 4 -- .../tests/execution/HeapDrawSample.cpp | 8 ++-- .../tests/execution/HeapEmbeddedSampler.cpp | 2 +- .../Optimization/src/BindingAllocator.cpp | 8 +--- .../Optimization/src/ShaderInfoCollector.cpp | 8 +--- docs/dev/ENVIRONMENT.md | 6 +-- 13 files changed, 20 insertions(+), 72 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index a6bfd442698c..ffe323844474 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -74,7 +74,6 @@ class BindlessHeap { std::uint32_t AbsentSlot(std::uint32_t kind, VkImageView view); static bool NearlyFull(); static bool RefusesDraws(); - static bool WaitsWhenFull(); static std::uint32_t ImageSlotCapacity(); std::uint32_t ImageSlots() const { return slotCap; } std::uint32_t TouchSlots(std::span> slots, std::span samplerSlots, std::uint32_t touched) const; @@ -166,7 +165,6 @@ class BindlessHeap { std::vector poolBlocks; std::size_t poolCurrent = ~std::size_t{0}; std::uint32_t poolAlignment = 256; - bool poolDeviceLocal = true; std::size_t poolBatchBytes = 0; std::size_t takePoolBlockLocked(std::size_t bytes); bool poolBlockDoneLocked(PoolBlock& block); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index d145f461bce7..4cb46d4b4f84 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -257,14 +257,11 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { meshWindowHeapOffset = sizes.meshWindowOffset; samplerHeapUsed = sizes.samplerUsed; Require(Fits(heapProperties), "the GPU heap's slots exceed the device's descriptor heap sizes"); - static const bool hostDescriptors = std::getenv("APS5_NO_HEAP_DEVICE_DESCRIPTORS") != nullptr; constexpr VkMemoryPropertyFlags deviceVisible = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - const auto makeBuffer = [&](std::size_t bytes, VkBufferUsageFlags usage, bool deviceLocal) { - if (deviceLocal) { - try { - return std::make_unique(context, bytes, usage, deviceVisible); - } catch (const std::exception&) { - } + const auto makeBuffer = [&](std::size_t bytes, VkBufferUsageFlags usage) { + try { + return std::make_unique(context, bytes, usage, deviceVisible); + } catch (const std::exception&) { } return std::make_unique(context, bytes, usage); }; @@ -274,8 +271,8 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { ringInHeap = sizes.ringBytes != 0u; const auto resourceBytes = ringInHeap ? static_cast(sizes.ringOffset) + sizes.ringBytes : static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange); - resourceHeap = makeBuffer(resourceBytes, ringInHeap ? heapUsage | ringUsage : heapUsage, ringInHeap || !hostDescriptors); - samplerHeap = makeBuffer(static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage, !hostDescriptors); + resourceHeap = makeBuffer(resourceBytes, ringInHeap ? heapUsage | ringUsage : heapUsage); + samplerHeap = makeBuffer(static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage); std::fill(resourceHeap->Bytes().begin(), resourceHeap->Bytes().end(), std::byte{0}); std::fill(samplerHeap->Bytes().begin(), samplerHeap->Bytes().end(), std::byte{0}); if (ringInHeap) { @@ -287,7 +284,6 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { } ringAlignment = static_cast(std::max(BufferSlotBytes, heapProperties.bufferDescriptorAlignment)); poolAlignment = static_cast(std::max({context.limits.minStorageBufferOffsetAlignment, context.limits.minUniformBufferOffsetAlignment, RingSpanAlignment})); - poolDeviceLocal = !hostDescriptors; ringChunks.resize(ringBytes / RingChunkBytes); slotCap = configuredSlotCap(sizes.imageSlots); deviceImageSlots.store(slotCap, std::memory_order_relaxed); @@ -306,11 +302,6 @@ constexpr std::uint32_t SamplerSlotMargin = Abi::GpuSamplerHeapSlots / 4u; std::atomic refusedHeaps{0}; std::atomic refusingHeaps{0}; -bool waitsWhenFull() { - static const bool waits = std::getenv("APS5_NO_HEAP_EVICTION") == nullptr; - return waits; -} - } BindlessHeap::~BindlessHeap() { @@ -482,10 +473,6 @@ bool BindlessHeap::NearlyFull() { return refusedHeaps.load(std::memory_order_relaxed) != 0u; } -bool BindlessHeap::WaitsWhenFull() { - return waitsWhenFull(); -} - bool BindlessHeap::RefusesDraws() { return refusingHeaps.load(std::memory_order_relaxed) != 0u; } @@ -509,7 +496,7 @@ void BindlessHeap::noteRefusedLocked(const char* what, std::uint32_t margin) { if (refused) return; refused = true; refusedHeaps.fetch_add(1, std::memory_order_relaxed); - if (waitsWhenFull() && (submitter == nullptr || submitter->HasTimeline())) { + if (submitter == nullptr || submitter->HasTimeline()) { pressured.store(true, std::memory_order_relaxed); std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; the next draw or dispatch submits its batch so idle slots can be evicted\n", margin, what); return; @@ -549,9 +536,8 @@ std::uint32_t BindlessHeap::TouchSlots(std::spanHasTimeline() || !GuestMemory::GpuMutex().HeldByThisThread()) return; + if (submitter == nullptr || !submitter->HasTimeline() || !GuestMemory::GpuMutex().HeldByThisThread()) return; if (idleSubmissions != 0u && evictScanEpoch == epoch) return; if (idleSubmissions != 0u) evictScanEpoch = epoch; std::vector> idle; @@ -583,9 +569,8 @@ void BindlessHeap::evictLocked(std::uint32_t idleSubmissions) { } void BindlessHeap::evictSamplersLocked(std::uint32_t idleSubmissions) { - static const bool disabled = std::getenv("APS5_NO_HEAP_EVICTION") != nullptr; const auto epoch = useEpoch.load(std::memory_order_relaxed); - if (disabled || submitter == nullptr || !submitter->HasTimeline() || !GuestMemory::GpuMutex().HeldByThisThread()) return; + if (submitter == nullptr || !submitter->HasTimeline() || !GuestMemory::GpuMutex().HeldByThisThread()) return; if (idleSubmissions != 0u && samplerEvictScanEpoch == epoch) return; if (idleSubmissions != 0u) samplerEvictScanEpoch = epoch; std::vector> idle; @@ -822,11 +807,9 @@ std::size_t BindlessHeap::takePoolBlockLocked(std::size_t bytes) { constexpr VkBufferUsageFlags usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; constexpr VkMemoryPropertyFlags deviceVisible = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; std::unique_ptr buffer; - if (poolDeviceLocal) { - try { - buffer = std::make_unique(context, size, usage, deviceVisible); - } catch (const std::exception&) { - } + try { + buffer = std::make_unique(context, size, usage, deviceVisible); + } catch (const std::exception&) { } if (buffer == nullptr) buffer = std::make_unique(context, size, usage); if (vacant == poolBlocks.size()) poolBlocks.emplace_back(); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index a42e4c1ba4f9..f93e5743b531 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -554,7 +554,6 @@ bool slotPressureSubmits(const Context& context, VkImageView view) { static_cast(recorder.Commands()); recorder.Submit(); }; - require(BindlessHeap::WaitsWhenFull(), "a nearly full heap waits by default instead of refusing draws"); std::vector> held; std::vector slots; for (std::size_t index = 0; index < 7u; ++index) { diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake index 955a5c1a4c82..a9d4ef8d3cbb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_compute_sample_tests.cmake @@ -5,6 +5,4 @@ if(BUILD_TESTING AND TARGET agc_driver_heap_compute_sample_tests) ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) agc_add_env_test(agc_driver_heap_compute_sample_full_heap agc_driver_heap_compute_sample_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=4) - agc_add_env_test(agc_driver_heap_compute_sample_full_heap_refusing agc_driver_heap_compute_sample_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=4 APS5_NO_HEAP_EVICTION=1) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake index 6afbc7b9e520..41c40714b403 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake @@ -2,13 +2,9 @@ if(BUILD_TESTING AND TARGET agc_driver_heap_draw_sample_tests) agc_add_env_test(agc_driver_heap_draw_sample_heap agc_driver_heap_draw_sample_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) agc_add_env_test(agc_driver_heap_draw_sample_full_heap agc_driver_heap_draw_sample_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=1 APS5_NO_HEAP_EVICTION=1) - agc_add_env_test(agc_driver_heap_draw_sample_heap_pressure agc_driver_heap_draw_sample_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5) - agc_add_env_test(agc_driver_heap_draw_sample_heap_pressure_pipelined agc_driver_heap_draw_sample_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) agc_add_env_test(agc_driver_heap_draw_sample_full_heap_pipelined agc_driver_heap_draw_sample_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=1 APS5_NO_HEAP_EVICTION=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) agc_add_env_test(agc_driver_heap_draw_sample_nogpl agc_driver_heap_draw_sample_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_NO_GPL=1) agc_add_env_test(agc_driver_heap_draw_sample_nogpl_heap agc_driver_heap_draw_sample_tests diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_embedded_sampler_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_embedded_sampler_tests.cmake index bb87173efadf..d87a35c63b02 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_embedded_sampler_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_embedded_sampler_tests.cmake @@ -1,8 +1,6 @@ if(BUILD_TESTING AND TARGET agc_driver_heap_embedded_sampler_tests) agc_add_env_test(agc_driver_heap_embedded_sampler_heap agc_driver_heap_embedded_sampler_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) - agc_add_env_test(agc_driver_heap_embedded_sampler_heap_off agc_driver_heap_embedded_sampler_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_NO_EMBEDDED_SAMPLERS=1) agc_add_env_test(agc_driver_heap_embedded_sampler_heap_capped agc_driver_heap_embedded_sampler_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_EMBEDDED_SAMPLER_CAP=0) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake index f2f85643cdcb..8b41089c2380 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake @@ -60,8 +60,6 @@ if(BUILD_TESTING) add_test(NAME agc_driver_image_table_vouch_queued_draws COMMAND agc_driver_image_table_cache_bounds_tests --queued-draws) set_tests_properties(agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) agc_add_env_test(agc_driver_image_table_cache_bounds_heap_small agc_driver_image_table_cache_bounds_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=1 APS5_NO_HEAP_EVICTION=1 TIMEOUT 60) - agc_add_env_test(agc_driver_image_table_cache_bounds_heap_pressure agc_driver_image_table_cache_bounds_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=8 TIMEOUT 60) if(WIN32) set_tests_properties(agc_shader_table_snapshot_reuse agc_shader_table_snapshot_reuse_unmasked agc_driver_image_table_vouched_lookups agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp index 82c4de523a0f..36545a22c68d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp @@ -98,10 +98,6 @@ void FullHeapSample() { Submit(words); for (std::size_t index = 0; index < FullHeapTextures; ++index) RequireSampled(Outputs[0].data() + 4u * index, SampleTexel, "texture " + std::to_string(index) + " of a heap with too few image slots", true); - if (!AgcDriver::Graphics::BindlessHeap::WaitsWhenFull()) { - Require(AgcDriver::Graphics::BindlessHeap::NearlyFull(), "the capped heap never ran short of image slots"); - return; - } Require(AgcDriver::Graphics::SlotPressureSubmits() > submitsBefore, "the capped heap never submitted a batch early to free image slots"); Require(AgcDriver::Graphics::HeapComputeStages() - stagesBefore == FullHeapTextures, "a compute stage left the heap while it ran short of image slots"); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index ae94c31a62f5..bc6685f52562 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -379,7 +379,7 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { std::to_string(StorageMemory[channel]) + ", expected the sampled " + std::to_string(Texel[channel]) + (heap ? " through the heap" : "")); } - if (!heap || (std::getenv("APS5_HEAP_SLOT_CAP") != nullptr && !AgcDriver::Graphics::BindlessHeap::WaitsWhenFull())) return; + if (!heap) return; if (mode == Mode::Vertex || mode == Mode::VertexTable) Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, "the heap did not take the sampling vertex stage with descriptor memory"); @@ -388,7 +388,7 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { std::string("the heap did not take the fragment stage") + TakenWhat(mode, buffer)); Require(AgcDriver::Graphics::DataAddressPushes() > pushesBefore, "the heap stages did not read their shader data through pushed addresses"); - if (mode == Mode::ConstantSampler && std::getenv("APS5_NO_EMBEDDED_SAMPLERS") == nullptr) + if (mode == Mode::ConstantSampler) Require(AgcDriver::Graphics::EmbeddedSamplerMappings() > embeddedBefore, "the fragment stage's constant sampler was not embedded in its pipeline"); } @@ -465,11 +465,9 @@ int main() { DrawSamplesTheTexture(heap, mode); const bool capped = heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr; if (heap && !capped) MixedDrawTakesThePerDrawPath(); - if (capped && AgcDriver::Graphics::BindlessHeap::WaitsWhenFull()) + if (capped) Require(AgcDriver::Graphics::HeapSlotEvictions() != 0u && !AgcDriver::DriverDetail::HeapRefused(), "the capped heap refused draws instead of evicting image slots"); - else if (capped) - Require(AgcDriver::DriverDetail::HeapRefused(), "a draw found the capped heap full and the heap was not refused"); AgcDriverShutdown_nid_postfix(); if (heap && !capped) Require(AgcDriver::Graphics::EmptyResourceSets() != 0, "no heap draw bound without a per-draw resource set"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp index 732de6b2c626..28f495e8aaeb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp @@ -78,7 +78,7 @@ int main() { if (!device) return VulkanTestSkipped; const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; if (heap && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; - const bool embedding = heap && std::getenv("APS5_NO_EMBEDDED_SAMPLERS") == nullptr; + const bool embedding = heap; FillTexels(TextureMemory, SampleTexel); for (auto& output : Outputs) output.fill(-1.0f); const auto constant = Compile(*device, Outputs[0].data(), ConstantSamplerCode, false); diff --git a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp index 42da8b0e968c..6a1ad6b729b2 100644 --- a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp +++ b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp @@ -2,7 +2,6 @@ #include "Optimization/ResourceMaterializer.hpp" #include #include -#include #include #include #include @@ -14,11 +13,6 @@ namespace { throw std::runtime_error(message); } -bool PushHeapData() { - static const bool enabled = std::getenv("APS5_NO_HEAP_PUSHED_DATA") == nullptr; - return enabled; -} - void placePushedData(IrBindingLayout& layout) { const auto capacity = RuntimeAbi::PushedDataWantedLimit; const auto take = [&](std::uint32_t dword) { @@ -184,7 +178,7 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin } } if (descriptorMemory && gpuResolvedImages) next.bufferAddressDwords = static_cast(info.buffers.size()) * RuntimeAbi::BufferAddressWords; - if (next.UsesDataAddress() && PushHeapData()) placePushedData(next); + if (next.UsesDataAddress()) placePushedData(next); std::vector samplers; for (std::uint32_t i = 0; i < info.samplers.size(); i++) { diff --git a/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp b/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp index 4d02efe571c7..00fc073dadce 100644 --- a/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp +++ b/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp @@ -3,7 +3,6 @@ #include #include #include -#include #include #include #include @@ -579,16 +578,11 @@ void AddTargetMerge(const ShaderPixelInputInfo& pixel, ShaderInfo& info) { if (pixel.mergeSamples > 1u) AddInput(info, StageInputKind::SampleId, 0, 1, "gl_SampleID"); } -bool embeddedSamplersEnabled() { - static const bool enabled = std::getenv("APS5_NO_EMBEDDED_SAMPLERS") == nullptr; - return enabled; -} - void collectConstantSampler(const IrProgram& program, SamplerResource& sampler) { sampler.constant = false; sampler.constantWords = {}; const auto& sources = program.Resources().descriptorSources; - if (!embeddedSamplersEnabled() || sampler.table != NoTable || sampler.source >= sources.size()) return; + if (sampler.table != NoTable || sampler.source >= sources.size()) return; const auto& source = sources[sampler.source]; if (source.dwordCount != 4u) return; for (std::uint32_t index = 0; index < 4u; ++index) { diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 736eb28c8803..98c03a87aa5b 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -48,7 +48,6 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_CODE_HASH_KEY` | presence | `core/shader/recompiler/CacheKey.hpp` | | appends every code word to the cache key instead of hashing the code | | `APS5_NO_FAILURE_MEMO` | presence | `core/shader/recompiler/Recompiler.cpp` | | rebuilds a program whose compilation failed instead of reusing the memoized failure | | `APS5_NO_FAULT_CHECK_DEDUP` | presence | `core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp` | | emits every invalid-descriptor fault check of a GPU-descriptor buffer access instead of skipping one that an identical check on the same descriptor under the same execution guard already covers in the same IR block or a dominating block; read once per program | -| `APS5_NO_HEAP_PUSHED_DATA` | presence | `core/shader/recompiler/Optimization/src/BindingAllocator.cpp` | | reads all of a descriptor-heap stage's shader data from the ring instead of pushing its heap slot indices and then its user data (each pipeline packs its stages' root items and pushed dwords into the 64 push dwords) | | `APS5_NO_IMAGE_TABLES` | presence | `core/shader/recompiler/Optimization/src/ResourceTracker.cpp` | | disables image tables, leaving table-loaded descriptors unplanned | | `APS5_NO_MASKED_RESULT_MEMO` | presence | `core/shader/recompiler/Recompiler.cpp` | | materializes every result memo miss instead of patching the buffer descriptors, user data and flattened SRT of a cached result whose snapshot differs only in those words | | `APS5_NO_PERF_DISK_PLANS` | presence | `core/shader/recompiler/Recompiler.cpp` | | disables the disk cache of planning results | @@ -203,9 +202,8 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_HEAP_MIRROR_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 24576 | budget in MiB for the heap mirrors held for registered allocations | | `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first | | `APS5_HEAP_WALK_MEMO_MB` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | 256 | MiB each thread's GPU heap walk memo may hold across both its generations before the previous generation and then the oldest walks are dropped (0 keeps them until the 16,384-key cap rotates them out) | -| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a nearly full heap submits the open batch at the next draw or dispatch and evicts the slots that batch no longer uses (see `APS5_NO_HEAP_EVICTION`) | +| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a nearly full heap submits the open batch at the next draw or dispatch and evicts the slots that batch no longer uses | | `APS5_HEAP_RING_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 16 | MiB of the GPU heap's per-draw buffer descriptor ring inside the resource heap, between 4 and 64, in whole 2 MiB chunks and within the device's heap size; one draw's descriptors may take at most a quarter of the ring, and a batch is submitted early once it holds half the ring (shader data lives in a data pool that grows instead) | -| `APS5_NO_HEAP_EVICTION` | flag | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | unset | set: a nearly full GPU heap neither evicts image or sampler slots nor submits the open batch early to free them; draws and dispatches take the per-draw path until owners release slots | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | | `APS5_HOOK_LOCKED_WAIT` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | keeps the flush hook's pending-write wait under the GpuMutex | @@ -266,7 +264,6 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_DEFERRED_DESTRUCTION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | on MoltenVK, destroys buffers and frees device memory as soon as the driver releases them, instead of while the graphics queue is idle (KhronosGroup/MoltenVK#2876) | | `APS5_NO_DCC_WORD_SCAN` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp` | | restores the byte-by-byte DCC key scan instead of the word-at-a-time compare | | `APS5_EMBEDDED_SAMPLER_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device limit | caps the samplers the GPU heap embeds in pipelines below the device's maxDescriptorHeapEmbeddedSamplers; constant samplers past it read a sampler heap slot at a fixed offset (testing) | -| `APS5_NO_EMBEDDED_SAMPLERS` | presence | `core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp` | | GPU heap stages fetch samplers whose four descriptor words are constants in the shader code from the sampler heap, like every other sampler, instead of as samplers embedded in the pipeline's descriptor mapping (vkd3d-proton's static samplers) | | `APS5_NO_DEFERRED_EVICTION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | destroys displaced resource-cache entries under the mutex instead of deferring them to the open batch | | `APS5_NO_DEFERRED_SETTLES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | settles watched private host imports as they open instead of through the deferred block-settling path (Windows only) | | `APS5_NO_DEPTH_TRANSFER_PASS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp` | | copies a D32 depth plane into a 32-bit color storage image (one `vkCmdCopyImage` where `APS5_NO_DIRECT_DEPTH_COPY` allows it, else through the staging buffer) instead of reading it into the image in a compute pass (used when `VK_KHR_push_descriptor` is enabled); copies back into the depth plane never use the pass | @@ -700,7 +697,6 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_MIMALLOC` | presence | `core/libs/prx/libkernel/System/src/MimallocRestart.cpp` | | makes the process allocate through mimalloc instead of the system allocator: on Windows the entry stub (`core/relinker/elfpatcher/src/windows/WindowsEntryStubBuilder.cpp`) loads `mimalloc.dll`, on macOS libkernel restarts the title with `libmimalloc.dylib` in `DYLD_INSERT_LIBRARIES` and on Linux with `libmimalloc.so` in `LD_PRELOAD`; on macOS and Linux both variables stay set after the restart, so processes the title starts inherit them | | `APS5_MIMALLOC_RESTARTED` | presence | `core/libs/prx/libkernel/System/src/MimallocRestart.cpp` | | on macOS and Linux, set by libkernel for the restart that loads mimalloc and removed at start-up, so a restart that did not load it is not repeated | | `APS5_NO_DIRECT_MEMORY_SECTION_POOL` | presence | `core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp` | | on Windows, creates a section for every direct-memory allocation and closes it at release instead of reusing released sections that never held guest data | -| `APS5_NO_HEAP_DEVICE_DESCRIPTORS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | | allocates the GPU heap's resource and sampler heaps in host-visible memory instead of device-local host-visible memory (the resource heap stays device-local while it holds the shader-data ring) | | `APS5_NO_JOB_AFFINITY` | presence | `core/libs/prx/libkernel/Pthread/src/Thread.cpp` | | on Windows, disables pinning of job worker threads | | `APS5_NO_SLEEP_WAKE` | presence | `core/libs/prx/libkernel/Time/SleepWake.cpp` | | keeps every sleep of 1 ms or less in full instead of ending it at a GPU batch, batch completion action or flip completion | | `APS5_NO_TIMER_RESOLUTION` | presence | `core/libs/prx/libkernel/Time/Time.cpp` | | keeps the default 15.6 ms scheduler tick instead of raising it to 0.5 ms on Windows | From 8cc6dc23310fa5a926e198f37652e7c7c57c3441 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 6 Nov 2026 13:26:06 +0530 Subject: [PATCH 128/269] fix(agc): keep color target merges on the GPU heap A fragment stage that merges into its own color target (a partial write of a packed target, or blending unclamped normalized color) reads and writes the target as a storage image whose descriptor comes from the draw's color target state, not from guest memory. The heap template path built its key and per-draw binding words from the captured snapshot alone, which lacks that image, so every such draw on the heap threw an out-of-range error and failed. MaterializeHeap now appends the merge target descriptors the same way the per-draw path does, and keys the template on them only through the address-free binding plan words, so draws merging into different targets of one form share a template and carry their own target in the per-draw words. The heap walk memo keys and compares the merge descriptors too: it is keyed on the variant, which no longer names the target, and otherwise served the first target's words to a draw into another one, which then stored into the wrong image. The heap draw test gains an unclamped blend draw into two targets, which checks the blended texels, that the heap took the stage and that the second target reused the first one's template. --- .../include/Driver/Draw/HeapWalkMemo.hpp | 1 + .../Execution/src/Driver/Draw/HeapStages.cpp | 12 +++- .../tests/execution/HeapDrawSample.cpp | 59 ++++++++++++++++--- core/shader/recompiler/Recompiler.cpp | 11 ++-- 4 files changed, 70 insertions(+), 13 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp index da1ea6b54f6a..952b0228c8b3 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp @@ -16,6 +16,7 @@ struct HeapWalkEntry { std::uint64_t shaderBase = 0; std::uint32_t pushOffset = 0; std::vector userData; + std::vector merges; std::vector> ranges; std::vector values; std::vector> accessible; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 6b3a5c48280c..44ffa390d21d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -373,7 +373,7 @@ std::uint64_t HeapWalkWordsBytes(const ShaderRecompiler::HeapStageWords& words) std::uint64_t HeapWalkEntryOwnBytes(const HeapWalkEntry& entry) { return sizeof(HeapWalkEntry) + vectorBytes(entry.userData) + vectorBytes(entry.ranges) + vectorBytes(entry.values) + - vectorBytes(entry.accessible) + vectorBytes(entry.userDataUse.reads); + vectorBytes(entry.accessible) + vectorBytes(entry.userDataUse.reads) + vectorBytes(entry.merges); } std::uint64_t HeapWalkEntryBytes(const HeapWalkEntry& entry) { @@ -498,10 +498,17 @@ void guardRanges(const AddressRanges& ranges) { for (const auto& [begin, end] : ranges) GuestMemory::GuardRead(begin, static_cast(end - begin)); } +std::span targetMerges(const ShaderRecompiler::PreparedShaderInvocation& invocation) { + const auto& pixel = invocation.Request().context.pixel; + return pixel ? std::span(pixel->targetMerges) : std::span{}; +} + std::uint64_t walkMemoKey(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase) { auto key = (invocation.VariantId() * 0x9e3779b97f4a7c15ull ^ shaderBase) + invocation.Request().layout.pushConstantOffsetBytes; for (const auto word : userData) key = (key ^ word) * 0x100000001b3ull; + for (const auto& merge : targetMerges(invocation)) + for (const auto word : merge.descriptor) key = (key ^ word) * 0x100000001b3ull; return key; } @@ -510,6 +517,7 @@ bool sameWalkInputs(const HeapWalkEntry& entry, const ShaderRecompiler::Prepared const bool sameStage = entry.variant == invocation.VariantId() && entry.shaderBase == shaderBase && entry.pushOffset == invocation.Request().layout.pushConstantOffsetBytes; if (!sameStage || !std::equal(entry.userData.begin(), entry.userData.end(), userData.begin(), userData.end())) return false; + if (!std::ranges::equal(entry.merges, targetMerges(invocation))) return false; std::size_t cursor = 0; for (const auto& [begin, end] : entry.ranges) { const auto count = static_cast((end - begin) / WordBytes); @@ -537,6 +545,8 @@ void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderI entry.pushOffset = invocation.Request().layout.pushConstantOffsetBytes; entry.shaderBase = shaderBase; entry.userData.assign(userData.begin(), userData.end()); + const auto merges = targetMerges(invocation); + entry.merges.assign(merges.begin(), merges.end()); entry.ranges = ranges; entry.values = values; entry.accessible = accessible; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index bc6685f52562..cbb333465dc5 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -6,6 +6,8 @@ #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" #include "VulkanTestDevice.hpp" #include #include @@ -19,9 +21,15 @@ #include #include #include +#include #include #include #include +#ifdef _WIN32 +#include +#else +#include +#endif namespace { @@ -82,6 +90,28 @@ constexpr float SecondAlpha = 0.6f; constexpr std::uint8_t SecondAlphaByte = 153u; alignas(4096) std::array BufferMemory{}; alignas(256) std::array ColorMemory{}; + +std::span MergedTarget(std::size_t index) { + constexpr std::size_t Bytes = 65536; + static std::array data{}; + if (data.at(index) == nullptr) data[index] = [] { + std::byte* block = nullptr; +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Bytes, Bytes)); + GuestArena::GuestArenaCommit_nid_postfix(block, Bytes, PAGE_READWRITE, Bytes); +#else + void* raw = mmap(nullptr, 2u * Bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the merged color target"); + const auto begin = reinterpret_cast(raw); + block = reinterpret_cast((begin + Bytes - 1u) & ~static_cast(Bytes - 1u)); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Bytes); +#endif + GuestAllocations::Mutation mutation; + mutation.Add(block, Bytes, true, true, true); + return block; + }(); + return {data[index], ColorMemory.size()}; +} alignas(256) std::array TextureMemory{}; struct Header { @@ -108,7 +138,7 @@ void Append(std::vector& commands, std::uint32_t opcode, std::ini commands.insert(commands.end(), payload); } -enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds, ConstantSampler }; +enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds, ConstantSampler, MergedBlend, MergedBlendOther }; const std::uint32_t* VertexProgram(Mode mode) { if (mode == Mode::VertexTable) return TableVertexCode.data(); @@ -134,6 +164,7 @@ unsigned ExpectedChannel(Mode mode, bool buffer, std::size_t channel) { if (mode == Mode::MovedTexture) return 0x33u; if ((mode == Mode::Bda || mode == Mode::MovedBuffer) && channel == 3) return SecondAlphaByte; if (buffer && channel == 3) return BufferAlphaByte; + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return std::min(2u * Texel[channel] + static_cast(Kept), 0xffu); return Texel[channel]; } @@ -144,6 +175,8 @@ const char* DrawnWhat(Mode mode, bool buffer) { if (buffer) return " (texture and buffer)"; if (mode == Mode::Table) return " (image table)"; if (mode == Mode::ConstantSampler) return " (texture with a constant sampler)"; + if (mode == Mode::MergedBlend) return " (texture blended unclamped into the color target)"; + if (mode == Mode::MergedBlendOther) return " (texture blended unclamped into a second color target)"; return " (texture)"; } @@ -154,6 +187,7 @@ const char* TakenWhat(Mode mode, bool buffer) { if (mode == Mode::Table) return " reading an image table"; if (mode == Mode::VertexTable) return " (vertex stage reading an image table)"; if (mode == Mode::ConstantSampler) return " sampling with a constant sampler"; + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return " merging into its color target"; return ""; } @@ -179,7 +213,7 @@ std::vector Draw(const std::uint32_t* pixelCode, Mode mode, const const bool vertexSampling = mode == Mode::Vertex || mode == Mode::VertexTable; const auto vertex = reinterpret_cast(vertexCode != nullptr ? vertexCode : VertexProgram(mode)); const auto pixel = reinterpret_cast(pixelCode); - const auto color = reinterpret_cast(ColorMemory.data()); + const auto color = reinterpret_cast(mode == Mode::MergedBlend ? MergedTarget(0).data() : mode == Mode::MergedBlendOther ? MergedTarget(1).data() : ColorMemory.data()); std::array descriptors{}; const auto textureImage = ImageDescriptor(TextureMemory.data()); const auto bufferDescriptor = BufferDescriptor(BufferMemory.data() + 1, sizeof(BufferMemory) - sizeof(float)); @@ -278,6 +312,10 @@ std::vector Draw(const std::uint32_t* pixelCode, Mode mode, const std::vector commands; Append(commands, 0x79, {0x242, 4}); for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) { + Append(commands, 0x69, {0x1e0, (1u << 30u) | (1u << 8u) | 1u}); + Append(commands, 0x69, {0x31c, 0x28028u & ~0x8000u}); + } if (vertexSampling) { Append(commands, 0x69, {0x1b6, 1}); Append(commands, 0x69, {0x191, 1u << 10u}); @@ -325,7 +363,8 @@ std::span PixelProgram(Mode mode, bool buffer, bool vertexS void DrawSamplesTheTexture(bool heap, Mode mode) { const bool buffer = mode == Mode::Buffer || mode == Mode::Bda || mode == Mode::MovedBuffer; - ColorMemory.fill(Kept); + const auto colorMemory = mode == Mode::MergedBlend ? MergedTarget(0) : mode == Mode::MergedBlendOther ? MergedTarget(1) : std::span(ColorMemory); + std::ranges::fill(colorMemory, Kept); StorageMemory.fill(0u); BufferMemory.fill(0.0f); BufferMemory[1] = BufferAlpha; @@ -348,6 +387,7 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { const auto tablesBefore = AgcDriver::Graphics::ImageTableBuilds(); const auto pushesBefore = AgcDriver::Graphics::DataAddressPushes(); const auto embeddedBefore = AgcDriver::Graphics::EmbeddedSamplerMappings(); + const auto templatesBefore = ShaderRecompiler::HeapTemplateCounts().entries; auto* gdsCounter = reinterpret_cast(AgcDriver::Pm4::GdsAddress() + 0x10u); if (mode == Mode::Gds) *gdsCounter = 0u; auto commands = Draw(code, mode); @@ -355,12 +395,12 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); AgcDriverWaitIdle_nid_postfix(); std::size_t drawn = 0; - for (std::size_t offset = 0; offset < ColorMemory.size(); offset += 4) { - if (std::all_of(ColorMemory.begin() + static_cast(offset), - ColorMemory.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) + for (std::size_t offset = 0; offset < colorMemory.size(); offset += 4) { + if (std::all_of(colorMemory.begin() + static_cast(offset), + colorMemory.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) continue; for (std::size_t channel = 0; channel < 4; ++channel) { - const auto value = static_cast(ColorMemory[offset + channel]); + const auto value = static_cast(colorMemory[offset + channel]); const unsigned expected = ExpectedChannel(mode, buffer, channel); Require(value == expected, "pixel " + std::to_string(offset / 4) + " channel " + std::to_string(channel) + " is " + std::to_string(value) + ", expected " + std::to_string(expected) + DrawnWhat(mode, buffer) + @@ -390,6 +430,9 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { "the heap stages did not read their shader data through pushed addresses"); if (mode == Mode::ConstantSampler) Require(AgcDriver::Graphics::EmbeddedSamplerMappings() > embeddedBefore, "the fragment stage's constant sampler was not embedded in its pipeline"); + if (mode == Mode::MergedBlendOther) + Require(ShaderRecompiler::HeapTemplateCounts().entries == templatesBefore, + "merging into a second color target built another heap template instead of reusing the first target's"); } void MixedDrawTakesThePerDrawPath() { @@ -461,7 +504,7 @@ int main() { mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); } for (const auto mode : {Mode::Texture, Mode::Buffer, Mode::Storage, Mode::Gds, Mode::Vertex, Mode::Bda, Mode::Table, Mode::VertexTable, - Mode::MovedBuffer, Mode::MovedTexture, Mode::PixelLds, Mode::ConstantSampler, Mode::Texture}) + Mode::MovedBuffer, Mode::MovedTexture, Mode::PixelLds, Mode::ConstantSampler, Mode::MergedBlend, Mode::MergedBlendOther, Mode::Texture}) DrawSamplesTheTexture(heap, mode); const bool capped = heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr; if (heap && !capped) MixedDrawTakesThePerDrawPath(); diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 5e6d0e0297c2..fa5bb7abb02a 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -2061,7 +2061,8 @@ std::uint64_t snapshotHash(const RecompileRequest& request, const ResourceSnapsh mix(merge.target); mix(merge.mask); mix(merge.samples); - for (const auto word : merge.descriptor) mix(word); + if (scope.descriptors) + for (const auto word : merge.descriptor) mix(word); if (!merge.blend.enabled) continue; mix(merge.blend.snorm); mix(merge.blend.colorSource); @@ -2466,10 +2467,12 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap const bool perDrawBindings = (request.shader.stage == ShaderStage::Fragment || request.shader.stage == ShaderStage::Vertex) && !tables; auto& source = *handle->source; const auto substitutes = bufferSubstitutesEnabled() && variant->substitutes != nullptr ? variant->substitutes->Slots() : std::vector{}; - const std::uint64_t key = HeapTemplateKey(request, *variant, snapshot, perDrawBindings, substitutes); + ResourceSnapshot mergedStorage; + const auto& merged = mergeTargetImage(*variant, request, snapshot, false, mergedStorage); + const std::uint64_t key = HeapTemplateKey(request, *variant, merged, perDrawBindings, substitutes); const auto complete = [&](const std::shared_ptr& shared) { HeapVertexAttributes(request, *shared->result, words); - if (perDrawBindings) HeapBindingWords(request, *variant, snapshot, *shared, words); + if (perDrawBindings) HeapBindingWords(request, *variant, merged, *shared, words); CompleteHeapDataWords(*shared->result, words); }; std::shared_ptr hit; @@ -2488,7 +2491,7 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap built->cacheHit = true; for (const auto reg : layout.userDataRegisters) built->heapUserWords.push_back(reg - userDataBase); built->heapTemplateId = NextTemplateId(); - auto created = std::make_shared(HeapTemplate{std::move(built), std::move(usedPlan), perDrawBindings ? snapshot.buffers : std::vector{}, perDrawBindings ? snapshot.images : std::vector{}, perDrawBindings ? snapshot.samplers : std::vector{}}); + auto created = std::make_shared(HeapTemplate{std::move(built), std::move(usedPlan), perDrawBindings ? merged.buffers : std::vector{}, perDrawBindings ? merged.images : std::vector{}, perDrawBindings ? merged.samplers : std::vector{}}); created->bytes = HeapTemplateBytes(*created); std::shared_ptr shared = std::move(created); bool inserted = false; From 57108a082e4c969b7a4db23b2b22cc7142a02a6c Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 6 Nov 2026 14:27:27 +0530 Subject: [PATCH 129/269] test(agc): sample with constant samplers that share a pipeline identity Identity() keyed compute pipelines, graphics pipelines and pipeline libraries alike, so stages differing only in a constant sampler shared one pipeline on both paths. The compute heap test now dispatches the border clamp and wrap forms of the constant-sampler kernel and checks each one's sample, and requires the clamp, wrap and mirror forms to have distinct identities (wrap and mirror differ only in the first sampler word, since the recompiler clears the border color word of samplers that never clamp to the border). The heap draw test draws a border clamp and a wrap form of one fragment shader through PM4 and checks the pixels. Both fail in heap mode without the identity fix. --- .../tests/execution/HeapDrawSample.cpp | 21 +++++++++++++++---- .../tests/execution/HeapEmbeddedSampler.cpp | 17 ++++++++++++++- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index cbb333465dc5..32418e961b17 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -48,6 +48,12 @@ alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e alignas(256) constexpr std::array ConstantSamplerPixelCode{ 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array BorderSamplerPixelCode{ + 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array WrapSamplerPixelCode{ + 0xbe8803ffu, 0u, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; alignas(256) constexpr std::array BufferPixelCode{ 0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; @@ -138,7 +144,7 @@ void Append(std::vector& commands, std::uint32_t opcode, std::ini commands.insert(commands.end(), payload); } -enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds, ConstantSampler, MergedBlend, MergedBlendOther }; +enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds, ConstantSampler, BorderSampler, WrapSampler, MergedBlend, MergedBlendOther }; const std::uint32_t* VertexProgram(Mode mode) { if (mode == Mode::VertexTable) return TableVertexCode.data(); @@ -164,6 +170,7 @@ unsigned ExpectedChannel(Mode mode, bool buffer, std::size_t channel) { if (mode == Mode::MovedTexture) return 0x33u; if ((mode == Mode::Bda || mode == Mode::MovedBuffer) && channel == 3) return SecondAlphaByte; if (buffer && channel == 3) return BufferAlphaByte; + if (mode == Mode::BorderSampler) return 0xffu; if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return std::min(2u * Texel[channel] + static_cast(Kept), 0xffu); return Texel[channel]; } @@ -175,6 +182,8 @@ const char* DrawnWhat(Mode mode, bool buffer) { if (buffer) return " (texture and buffer)"; if (mode == Mode::Table) return " (image table)"; if (mode == Mode::ConstantSampler) return " (texture with a constant sampler)"; + if (mode == Mode::BorderSampler) return " (constant border-clamp sampler outside the texture)"; + if (mode == Mode::WrapSampler) return " (constant wrapping sampler outside the texture, after a border-clamp draw of the same shader)"; if (mode == Mode::MergedBlend) return " (texture blended unclamped into the color target)"; if (mode == Mode::MergedBlendOther) return " (texture blended unclamped into a second color target)"; return " (texture)"; @@ -186,7 +195,7 @@ const char* TakenWhat(Mode mode, bool buffer) { if (mode == Mode::Bda) return " loading through BDA"; if (mode == Mode::Table) return " reading an image table"; if (mode == Mode::VertexTable) return " (vertex stage reading an image table)"; - if (mode == Mode::ConstantSampler) return " sampling with a constant sampler"; + if (mode == Mode::ConstantSampler || mode == Mode::BorderSampler || mode == Mode::WrapSampler) return " sampling with a constant sampler"; if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return " merging into its color target"; return ""; } @@ -353,6 +362,10 @@ std::span PixelProgram(Mode mode, bool buffer, bool vertexS return BdaPixelCode; case Mode::ConstantSampler: return ConstantSamplerPixelCode; + case Mode::BorderSampler: + return BorderSamplerPixelCode; + case Mode::WrapSampler: + return WrapSamplerPixelCode; default: break; } @@ -428,7 +441,7 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { std::string("the heap did not take the fragment stage") + TakenWhat(mode, buffer)); Require(AgcDriver::Graphics::DataAddressPushes() > pushesBefore, "the heap stages did not read their shader data through pushed addresses"); - if (mode == Mode::ConstantSampler) + if (mode == Mode::ConstantSampler || mode == Mode::BorderSampler || mode == Mode::WrapSampler) Require(AgcDriver::Graphics::EmbeddedSamplerMappings() > embeddedBefore, "the fragment stage's constant sampler was not embedded in its pipeline"); if (mode == Mode::MergedBlendOther) Require(ShaderRecompiler::HeapTemplateCounts().entries == templatesBefore, @@ -504,7 +517,7 @@ int main() { mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); } for (const auto mode : {Mode::Texture, Mode::Buffer, Mode::Storage, Mode::Gds, Mode::Vertex, Mode::Bda, Mode::Table, Mode::VertexTable, - Mode::MovedBuffer, Mode::MovedTexture, Mode::PixelLds, Mode::ConstantSampler, Mode::MergedBlend, Mode::MergedBlendOther, Mode::Texture}) + Mode::MovedBuffer, Mode::MovedTexture, Mode::PixelLds, Mode::ConstantSampler, Mode::BorderSampler, Mode::WrapSampler, Mode::MergedBlend, Mode::MergedBlendOther, Mode::Texture}) DrawSamplesTheTexture(heap, mode); const bool capped = heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr; if (heap && !capped) MixedDrawTakesThePerDrawPath(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp index 28f495e8aaeb..8226351a9072 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp @@ -26,12 +26,18 @@ constexpr std::uint32_t OpaqueWhiteBorder = 2u << 30u; alignas(256) constexpr std::array ConstantSamplerCode{ 0xbe8803ffu, BorderClamp, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, OpaqueWhiteBorder, 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; +alignas(256) constexpr std::array WrapSamplerCode{ + 0xbe8803ffu, 0u, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, OpaqueWhiteBorder, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; +alignas(256) constexpr std::array MirrorSamplerCode{ + 0xbe8803ffu, 1u | (1u << 3u) | (1u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, OpaqueWhiteBorder, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; alignas(256) constexpr std::array UserSamplerCode{0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xe0780000u, 0x80030000u, 0xbf810000u}; constexpr std::array White{0xffu, 0xffu, 0xffu, 0xffu}; alignas(256) std::array TextureMemory{}; -alignas(4096) std::array, 2> Outputs{}; +alignas(4096) std::array, 3> Outputs{}; ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, float* output, std::span code, bool userSampler) { auto userData = SampleUserData(TextureMemory.data(), output); @@ -83,17 +89,26 @@ int main() { for (auto& output : Outputs) output.fill(-1.0f); const auto constant = Compile(*device, Outputs[0].data(), ConstantSamplerCode, false); const auto user = Compile(*device, Outputs[1].data(), UserSamplerCode, true); + const auto wrap = Compile(*device, Outputs[2].data(), WrapSamplerCode, false); + const auto mirror = Compile(*device, Outputs[2].data(), MirrorSamplerCode, false); Require(constant.gpuResolvedImages == heap, "the constant-sampler stage is not in the expected mode"); Require((EmbeddedElements(constant) != 0u) == embedding, embedding ? "a constant sampler was not embedded" : "a sampler was embedded outside heap mode"); Require(DecoratesEmbeddedSet(constant) == embedding, "the stage's SPIR-V does not match its embedded samplers"); Require(EmbeddedElements(user) == 0u && !DecoratesEmbeddedSet(user), "a sampler read from user data was embedded"); + Require((EmbeddedElements(wrap) != 0u) == embedding, "the wrapping constant sampler was not embedded like the clamping one"); + Require(!embedding || wrap.Identity() != constant.Identity(), + "two compute stages differing only in an embedded sampler share one pipeline identity"); + Require(!embedding || mirror.Identity() != wrap.Identity(), + "two compute stages whose embedded samplers differ only in their first word share one pipeline identity"); const auto* existing = AgcDriver::Graphics::BindlessHeap::Existing(device->graphicsContext()); const auto embeddedBefore = existing != nullptr ? existing->EmbeddedSamplerCount() : 0u; device->Dispatch(constant, 1u, 1u, 1u, {}, reinterpret_cast(ConstantSamplerCode.data())); device->Dispatch(user, 1u, 1u, 1u, {}, reinterpret_cast(UserSamplerCode.data())); + device->Dispatch(wrap, 1u, 1u, 1u, {}, reinterpret_cast(WrapSamplerCode.data())); device->WaitIdle(); RequireSampled(Outputs[0].data(), White, "the constant sampler's opaque white border", heap); RequireSampled(Outputs[1].data(), White, "the user-data sampler's opaque white border", heap); + RequireSampled(Outputs[2].data(), SampleTexel, "the wrapping constant sampler's texel", heap); if (embedding) { const bool capped = std::getenv("APS5_EMBEDDED_SAMPLER_CAP") != nullptr; const auto* heapObject = AgcDriver::Graphics::BindlessHeap::Existing(device->graphicsContext()); From 2415f0383dca5830a7373cd3bf379f23052500d0 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 6 Nov 2026 16:39:29 +0530 Subject: [PATCH 130/269] refactor(agc): remove the per-draw fallback from GPU heap mode Heap mode now decides every draw and dispatch before any stage is built, and a stage the heap cannot take is an error instead of a per-draw retry. - A draw takes the heap unless APS5_GPU_HEAP_EXCLUDE names one of its stages; image classes are read from each stage's resource plan, so the pre-raster stage no longer guesses whether its pixel stage will follow. - The mixed-draw retry, refused pairs, the remembered per-shader verdicts, the unmapped redo of draw and dispatch stages, and the heap's refuse-draws state are gone. - A stage needing more image slots than the heap holds, or keeping a binding the heap does not map, fails with the slot count or the binding. - The heap needs timeline semaphores: a heap batch from a recorder without one fails, and APS5_NO_TIMELINE with APS5_GPU_HEAP fails at device creation. - The unresolved image source gate (HeapFragmentEligible) is removed. - A draw now checks the guest memory its heap-direct stages read before recording, so a descriptor table changed after their capture is prepared again. The mixed-draw retry used to hide that these reads were missing. --- .../include/Driver/Draw/HeapStages.hpp | 40 +---- .../Execution/include/Driver/Driver.hpp | 7 +- .../include/Driver/Shaders/ShaderRegistry.hpp | 1 - .../src/Driver/Dispatch/Dispatch.cpp | 23 ++- .../Execution/src/Driver/Draw/Draw.cpp | 83 +++------- .../Execution/src/Driver/Draw/DrawCapture.cpp | 84 +++++----- .../Execution/src/Driver/Draw/DrawLookup.cpp | 4 +- .../Execution/src/Driver/Draw/HeapStages.cpp | 152 ++++++------------ .../src/Driver/Shaders/ShaderRegistry.cpp | 16 +- .../Execution/src/VulkanDevice.cpp | 5 +- .../Graphics/include/BindlessHeap.hpp | 20 +-- .../Graphics/src/BindlessHeap.cpp | 69 +++----- .../tests/BindlessHeapSlots.cpp | 34 ++-- .../agc_driver_draw_cache_reuse_tests.cmake | 3 + ...river_draw_recapture_on_change_tests.cmake | 2 + .../agc_driver_heap_draw_sample_tests.cmake | 6 + .../cmake/agc_driver_heap_slots_tests.cmake | 2 +- .../agc_driver_submit_progress_tests.cmake | 4 +- .../tests/cmake/agc_shader_memory_tests.cmake | 2 - .../tests/execution/HeapDrawSample.cpp | 134 +++++++++------ .../tests/execution/ImageTableCacheBounds.cpp | 4 +- .../tests/execution/LazyResolvedAbi.cpp | 2 +- .../tests/execution/PreparedGraphics.cpp | 2 +- core/shader/recompiler/CMakeLists.txt | 1 - .../include/Optimization/ResourceProgram.hpp | 1 - core/shader/recompiler/Recompiler.cpp | 8 - docs/dev/ENVIRONMENT.md | 4 +- docs/dev/debt/libSceAgcDriver.md | 2 +- 28 files changed, 289 insertions(+), 426 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index 0715d9dd663d..df5e25718dab 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -14,42 +14,14 @@ namespace AgcDriver::DriverDetail { -bool HeapFragmentsEnabled(); -bool HeapRefused(); bool HeapStageExcluded(ShaderRecompiler::ShaderStage stage); bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage); -Graphics::HeapStageReason HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, - bool heapVertex); -bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex); -enum class HeapKeyClass { Draw, Compute, HeapVertex }; - -constexpr std::size_t HeapFragmentKey(std::size_t codeOffset, HeapKeyClass keyClass) { - switch (keyClass) { - case HeapKeyClass::Compute: return codeOffset | std::size_t{1} << 61u; - case HeapKeyClass::HeapVertex: return codeOffset | std::size_t{1} << 62u; - case HeapKeyClass::Draw: break; - } - return codeOffset; -} - -std::optional HeapFragmentKnown(const void* snapshot, std::size_t codeOffset); -void NoteHeapFragment(const void* snapshot, std::size_t codeOffset, bool eligible); -bool HeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress = false); -void SetHeapStageUnmapped(std::optional stage); -bool HeapDrawStageMappable(const ShaderRecompiler::RecompileResult& result, ShaderRecompiler::ShaderStage stage); -bool HeapPairRefused(std::uint64_t pair); -void RefuseHeapPair(std::uint64_t pair); - -class HeapDrawOff { -public: - HeapDrawOff(); - ~HeapDrawOff(); - HeapDrawOff(const HeapDrawOff&) = delete; - HeapDrawOff& operator=(const HeapDrawOff&) = delete; - -private: - bool previous; -}; +const char* HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan); +bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan); +bool HeapPlanExcluded(const ShaderRecompiler::IrResourcePlan& plan); +bool HeapClassesExcluded(); +void RequireHeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress = false); +bool HeapStageFits(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress = false); bool SampleHeapStageVerify(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp index 9f97fe99e63f..a7c2b4b876a1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp @@ -245,9 +245,10 @@ class Driver { std::shared_ptr decodeDraw(const QueueState& queue, const Submission& submission, const Graphics::Context& context); void resolveDrawDecode(const QueueState& queue, const Submission& submission, const Graphics::Context& context, std::shared_ptr& decode, bool registerKey, std::uint64_t drawKey, bool profile); void lookupDraw(const Submission& submission, const std::shared_ptr& localDevice, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector& programs, const std::vector& roles, const std::vector>& vertexInfos, bool useDrawEntries, bool registerKey, bool profile, std::uint64_t& drawKey, std::shared_ptr& entry, std::vector>& matched, std::vector>& matchedRegions, bool& drawHit, bool& verifyHit, DrawPhaseTiming& phaseTiming, std::array& phaseMs, const std::shared_ptr& dataEntry, DrawDataCandidates& dataCandidates, std::vector& stageData); - enum class HeapDirect { Declined, Unmapped, Taken }; - std::shared_ptr materializeDrawStage(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters, bool heapPartners); - HeapDirect materializeHeapDirect(const DrawStageContext& context, std::size_t i, const ShaderRecompiler::PreparedShaderInvocation& invocation, const ShaderRecompiler::RecompileRequest& request, PerformanceTimer& timing); + ShaderRecompiler::RecompileRequest drawStageRequest(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters); + bool drawStageExcluded(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters); + std::shared_ptr materializeDrawStage(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters, bool heapDraw); + bool materializeHeapDirect(const DrawStageContext& context, std::size_t i, const ShaderRecompiler::PreparedShaderInvocation& invocation, const ShaderRecompiler::RecompileRequest& request, PerformanceTimer& timing); static std::runtime_error stageFailure(const DrawProgram& program, const ShaderRecompiler::RecompileRequest& request, const std::exception& error, std::span regions); static void recordStageDataPositions(DispatchVariant& variant, const ShaderRecompiler::ResourceCapture& capture, const std::vector& decodeReads); void cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawParameters& drawParameters, const std::optional& indirectCpu, const std::vector& programs, const std::vector& stageCaptures, const std::vector>& vertexInfos, const std::vector>& decodeReads, bool verifyHit, const std::vector>& matched, const std::vector& stageData, std::vector>& fresh, std::uint64_t drawKey, bool registerKey, const std::shared_ptr& decode, DrawPhaseTiming& phaseTiming, const std::vector& reused, const std::shared_ptr& entry, std::uint64_t shapeKey, bool shapeNeedsEntry = false); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp index f16e54280259..253d285864c0 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp @@ -349,7 +349,6 @@ ShaderRecompiler::RectListShaders DrawRectangle(const ShaderSnapshot& front, con std::shared_ptr SourceHandleFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request); ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request); std::shared_ptr CaptureInvocation(ShaderMemory& memory, const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request, ShaderRecompiler::PreparedShaderInvocation& invocation); -bool PreparedHeapStage(const ShaderSnapshot& snapshot, std::size_t codeOffset); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index f305f91578c1..49bbe44497fa 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -194,8 +194,16 @@ void Driver::dispatch(QueueState& queue, std::span packet, localDevice->ComputeTarget((packet[4] & 0x8000u) != 0 ? 32u : 64u), {0, 0, 0, threadGroup != std::array{} ? 0u : 128u} }; - const std::size_t computeHeapKey = HeapFragmentKey(codeOffset, HeapKeyClass::Compute); - if (request.target.gpuResolvedImages && (HeapRefused() || HeapStageExcluded(ShaderRecompiler::ShaderStage::Compute) || HeapFragmentKnown(&snapshot, computeHeapKey) == std::optional(false))) request.target.gpuResolvedImages = false; + if (request.target.gpuResolvedImages && HeapStageExcluded(ShaderRecompiler::ShaderStage::Compute)) request.target.gpuResolvedImages = false; + if (request.target.gpuResolvedImages && HeapClassesExcluded()) { + const auto invocation = InvocationFor(snapshot, codeOffset, request); + const auto plan = invocation.Plan() == nullptr ? invocation.LoadPlan() : invocation.Plan(); + require(plan != nullptr, "a GPU heap compute stage has no resource plan to apply APS5_GPU_HEAP_EXCLUDE to"); + if (HeapPlanExcluded(*plan)) { + Graphics::NoteHeapExcluded(Graphics::HeapExcluded::Dispatch); + request.target.gpuResolvedImages = false; + } + } static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; static std::atomic captureMs{0}, keyMs{0}, recompileMs{0}, deviceMs{0}; static std::atomic cacheHits{0}; @@ -405,16 +413,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, timing.Mark("capture_resources"); compiledResult = invocation.Materialize(*capture); - if (compiledResult->gpuResolvedImages && !HeapStageMappable(*compiledResult, compiledResult->workgroupMemoryDwords != 0)) { - Graphics::NoteHeapFallback(Graphics::HeapFallback::DispatchUnmapped); - NoteHeapFragment(&snapshot, computeHeapKey, false); - request.target.gpuResolvedImages = false; - invocation = InvocationFor(snapshot, codeOffset, request); - capture = shaderMemory->Capture(invocation); - captured = shaderMemory->Regions(); - request.context.memory = captured; - compiledResult = invocation.Materialize(*capture); - } + if (compiledResult->gpuResolvedImages) RequireHeapStageMappable(*compiledResult, compiledResult->workgroupMemoryDwords != 0); timing.Mark("materialize"); if (profile && compiledResult->cacheHit) cacheHits.fetch_add(1, std::memory_order_relaxed); const auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - started).count(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index d30db4ac2753..3ba4bb97c8f0 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -209,33 +209,6 @@ bool MixesHeapAndGuestStages(std::span stages, s return std::ranges::any_of(stages, [](const Graphics::CompiledShader& stage) { return stage.program->gpuResolvedImages; }) && std::ranges::any_of(stages, [&](const Graphics::CompiledShader& stage) { return guest(stage) && !stage.program->gpuResolvedImages; }); } -class DrawStageCheckpoint { -public: - DrawStageCheckpoint(std::vector& stages, std::vector>& compiledStages, std::uint32_t& pushCursorBytes, Pm4::DrawParameters& drawParameters, ShaderRecompiler::ShaderPixelStageInfo& pixel, bool keepCopies) - : stages(stages), compiledStages(compiledStages), pushCursorBytes(pushCursorBytes), drawParameters(drawParameters), pixel(pixel), stagesBefore(stages.size()), compiledBefore(compiledStages.size()), pushBefore(pushCursorBytes), - parametersBefore(keepCopies ? std::optional(drawParameters) : std::nullopt), pixelBefore(keepCopies ? std::optional(pixel) : std::nullopt) {} - - void Restore() { - stages.resize(stagesBefore); - compiledStages.resize(compiledBefore); - pushCursorBytes = pushBefore; - drawParameters = *parametersBefore; - pixel = *pixelBefore; - } - -private: - std::vector& stages; - std::vector>& compiledStages; - std::uint32_t& pushCursorBytes; - Pm4::DrawParameters& drawParameters; - ShaderRecompiler::ShaderPixelStageInfo& pixel; - std::size_t stagesBefore; - std::size_t compiledBefore; - std::uint32_t pushBefore; - std::optional parametersBefore; - std::optional pixelBefore; -}; - } namespace { @@ -1000,13 +973,23 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { std::optional meshBarycentrics; std::vector resultIndex(programs.size(), 0); const bool heapCheck = !drawHit && Graphics::DescriptorHeapEnabled(); - std::uint64_t heapPair = 0xcbf29ce484222325ull; - for (const auto& program : programs) heapPair = (heapPair ^ reinterpret_cast(program.snapshot.get()) ^ (static_cast(program.codeOffset) << 1u)) * 0x100000001b3ull; - const bool heapPairRefused = heapCheck && HeapPairRefused(heapPair); - bool heapRetry = false; const DrawStageContext stageContext{queue, submission, packetOffset, trace.token, programs, graphics, pixel, vertexInfos, memory, linked, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, meshBarycentrics}; - const auto candidateForStage = [&](std::size_t i, bool afterHeap) { - return std::find_if(dataCandidates[i].begin(), dataCandidates[i].end(), [&](const auto& kept) { return kept.first->pushOffset == pushCursorBytes && (!afterHeap || kept.first->compiled->gpuResolvedImages); }); + const bool heapMode = Graphics::DescriptorHeapEnabled(); + const bool heapDraw = heapMode && [&] { + std::uint32_t cursor = pushCursorBytes; + for (std::size_t i = 0; i < programs.size(); ++i) { + if (roles[i] == Role::GeometryBack) continue; + const auto stage = programs[i].binary.stage; + require(stage == Stage::Fragment || HeapPreRasterStage(stage), "a draw stage kind the GPU heap does not take"); + require(stage == Stage::Fragment || localDevice->Target().descriptorMemory, "a GPU heap draw on a device target without descriptor memory"); + cursor = Graphics::StagePushOffset(cursor, stage, localDevice->GraphicsPipelineLibraries()); + if (HeapStageExcluded(stage) || (HeapClassesExcluded() && drawStageExcluded(stageContext, i, cursor, drawParameters))) return false; + } + return true; + }(); + const auto fitsDraw = [&](const ShaderRecompiler::RecompileResult& compiled) { return !heapMode || compiled.gpuResolvedImages == heapDraw; }; + const auto candidateForStage = [&](std::size_t i) { + return std::find_if(dataCandidates[i].begin(), dataCandidates[i].end(), [&](const auto& kept) { return kept.first->pushOffset == pushCursorBytes && fitsDraw(*kept.first->compiled); }); }; const auto runStages = [&]() -> std::optional { for (std::size_t i = 0; i < programs.size(); ++i) { @@ -1020,13 +1003,12 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); ringWords(i); } else { - const bool afterHeap = heapRetry || std::any_of(programResults.begin(), programResults.begin() + static_cast(i), [](const ShaderRecompiler::RecompileResult* earlier) { return earlier != nullptr && earlier->gpuResolvedImages; }); - if (reused[i] && afterHeap && !matched[i]->compiled->gpuResolvedImages) { + if (reused[i] && !fitsDraw(*matched[i]->compiled)) { reused[i] = false; matched[i] = nullptr; matchedRegions[i].clear(); } - const auto candidate = reused[i] ? dataCandidates[i].end() : candidateForStage(i, afterHeap); + const auto candidate = reused[i] ? dataCandidates[i].end() : candidateForStage(i); if (reused[i]) { programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); @@ -1048,7 +1030,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { break; } } - compiledStages.push_back(materializeDrawStage(stageContext, i, pushCursorBytes, drawParameters, !heapPairRefused)); + compiledStages.push_back(materializeDrawStage(stageContext, i, pushCursorBytes, drawParameters, heapDraw)); if (!rejected.empty()) return DrawVerdict::Rejected; programResults[i] = compiledStages.back().get(); if (verifyHit && matched[i] != nullptr && matched[i]->ringTemplate != nullptr) VerifyRingWords(*matched[i]->compiled, *buildRingWords(i, *matched[i]), *programResults[i], stageCaptures[i].heapWords.get()); @@ -1078,25 +1060,10 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { } return std::nullopt; }; - DrawStageCheckpoint checkpoint(stages, compiledStages, pushCursorBytes, drawParameters, pixel, heapCheck); if (const auto verdict = runStages()) return *verdict; - for (std::uint32_t retry = 0; heapCheck && MixesHeapAndGuestStages(stages, programResults); ++retry) { - require(retry < 2u, "a draw mixes GPU-mode and per-draw stages after taking the per-draw path"); - Graphics::NoteHeapFallback(retry == 0u ? Graphics::HeapFallback::DrawMixedRetry : Graphics::HeapFallback::DrawRefusedPair); - if (retry == 1u) RefuseHeapPair(heapPair); - const auto reusedGuest = [&](std::size_t i) { return reused[i] && programResults[i] != nullptr && !programResults[i]->gpuResolvedImages; }; - if (std::ranges::any_of(std::views::iota(std::size_t{0}, programs.size()), reusedGuest)) Graphics::NoteHeapFallback(Graphics::HeapFallback::DrawMixedReused); - heapRetry = retry == 0u; - checkpoint.Restore(); - std::fill(programResults.begin(), programResults.end(), nullptr); - for (std::size_t i = 0; i < programs.size(); ++i) { - if (!reused[i]) stageCaptures[i] = {}; - } - dataStagesReused = dataStagesCompiled = dataVerified = stageDataVerified = 0; - indirectCpu.reset(); - std::optional heapOff; - if (retry == 1u) heapOff.emplace(); - if (const auto verdict = runStages()) return *verdict; + if (heapCheck) { + require(!MixesHeapAndGuestStages(stages, programResults), "a draw mixes GPU heap and per-draw stages"); + if (!heapDraw) Graphics::NoteHeapExcluded(Graphics::HeapExcluded::Draw); } if (stageDataVerified != 0) { @@ -1190,8 +1157,9 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { if (programResults[0]->meshBarycentrics != meshBarycentrics) { const auto pushBytes = programResults[0]->pushConstants.size(); const auto exports = programResults[0]->parameterExports; - compiledStages.push_back(materializeDrawStage(stageContext, 0, pushOffsets[0], drawParameters, !heapPairRefused)); + compiledStages.push_back(materializeDrawStage(stageContext, 0, pushOffsets[0], drawParameters, heapDraw)); if (!rejected.empty()) return DrawVerdict::Rejected; + require(fitsDraw(*compiledStages.back()), "a rebuilt mesh stage left the GPU heap mode of its draw"); programResults[0] = compiledStages.back().get(); stages[0].program = programResults[0]; stages[0].registeredImageViews = stageCaptures[0].registeredViews.get(); @@ -1312,10 +1280,11 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { auto& result = results[resultIndex[programIndex]]; const auto pushBytes = result.pushConstants.size(); decodeVertexInfo(programIndex); - result = *materializeDrawStage(stageContext, programIndex, pushOffsets[programIndex], programs[programIndex].binary.stage == Stage::TessellationControl || programs[programIndex].binary.stage == Stage::TessellationEvaluation ? direct : drawParameters, !heapPairRefused); + result = *materializeDrawStage(stageContext, programIndex, pushOffsets[programIndex], programs[programIndex].binary.stage == Stage::TessellationControl || programs[programIndex].binary.stage == Stage::TessellationEvaluation ? direct : drawParameters, heapDraw); for (auto& stage : stages) if (stage.program == &result) stage.registeredImageViews = stageCaptures[programIndex].registeredViews.get(); if (!rejected.empty()) return DrawVerdict::Rejected; require(result.pushConstants.size() == pushBytes, "patched program changed its push constant layout"); + require(fitsDraw(result), "a patched program left the GPU heap mode of its draw"); for (auto& stage : stages) { if (stage.program == &result) stage.heap = stageCaptures[programIndex].heapWords.get(); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index b38a841f0d1d..c14cfab4dd1c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -84,7 +84,7 @@ void TraceShaderRequestFailure(std::uint64_t token, const Submission& submission } -Driver::HeapDirect Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t i, const ShaderRecompiler::PreparedShaderInvocation& invocation, const ShaderRecompiler::RecompileRequest& request, PerformanceTimer& timing) { +bool Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t i, const ShaderRecompiler::PreparedShaderInvocation& invocation, const ShaderRecompiler::RecompileRequest& request, PerformanceTimer& timing) { const auto& program = context.programs[i]; auto& stageCapture = context.stageCaptures[i]; HeapStageMaterialized materialized; @@ -96,8 +96,8 @@ Driver::HeapDirect Driver::materializeHeapDirect(const DrawStageContext& context } callCost.Stop(); Graphics::HeapCostScope finishCost(Graphics::HeapCost::StageFinish); - if (materialized.result == nullptr) return HeapDirect::Declined; - if (!HeapDrawStageMappable(*materialized.result, program.binary.stage)) return HeapDirect::Unmapped; + if (materialized.result == nullptr) return false; + RequireHeapStageMappable(*materialized.result); NoteHeapDirect(); stageCapture.compiled = std::move(materialized.result); stageCapture.heapWords = stageCapture.compiled->heapTemplateId != 0 ? std::const_pointer_cast(std::move(materialized.words)) : nullptr; @@ -123,11 +123,12 @@ Driver::HeapDirect Driver::materializeHeapDirect(const DrawStageContext& context stageCapture.capture = std::move(reads.capture); stageCapture.userDataMask = UserDataMask(program, context.vertexInfos[i], reads.userDataUse.asValue | reads.userDataUse.asBase, *stageCapture.compiled); stageCapture.ring = true; + context.memory.insert(context.memory.end(), stageCapture.regions.begin(), stageCapture.regions.end()); } context.recompiled[i] = true; timing.Mark("heap_direct"); context.phaseTiming.Phase(DrawRowRecompile); - return HeapDirect::Taken; + return true; } std::runtime_error Driver::stageFailure(const DrawProgram& program, const ShaderRecompiler::RecompileRequest& request, const std::exception& error, std::span regions) { @@ -147,12 +148,9 @@ std::runtime_error Driver::stageFailure(const DrawProgram& program, const Shader return std::runtime_error(where.str() + error.what()); } -std::shared_ptr Driver::materializeDrawStage(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters, bool heapPartners) try { - PerformanceTimer timing("Shader.DrawStage"); +ShaderRecompiler::RecompileRequest Driver::drawStageRequest(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters) { using Stage = ShaderRecompiler::ShaderStage; - context.phaseTiming.Phase(DrawRowVectors); const auto& program = context.programs[i]; - Graphics::HeapCostScope prepareCost(Graphics::HeapCost::StagePrepare); const auto waveSize = Graphics::StageWaveSize(context.graphics.stages, program.binary.stage); ShaderRecompiler::RecompileRequest request{ program.binary, @@ -164,18 +162,29 @@ std::shared_ptr Driver::materializeDraw if (context.graphics.depthRemap.mode != 0u && pushOffset < Graphics::PipelinePushSlotBytes) { request.layout.pushConstantSizeBytes = std::min(request.layout.pushConstantSizeBytes, ShaderRecompiler::DepthRemapPushOffsetBytes - pushOffset); } + return request; +} + +bool Driver::drawStageExcluded(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters) { + const auto& program = context.programs[i]; + auto request = drawStageRequest(context, i, pushOffset, drawParameters); + request.target.gpuResolvedImages = true; + const auto invocation = InvocationFor(*program.snapshot, program.codeOffset, request); + const auto plan = invocation.Plan() == nullptr ? invocation.LoadPlan() : invocation.Plan(); + if (plan == nullptr) throw std::runtime_error("AGC graphics: a GPU heap stage has no resource plan to apply APS5_GPU_HEAP_EXCLUDE to"); + return HeapPlanExcluded(*plan); +} + +std::shared_ptr Driver::materializeDrawStage(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters, bool heapDraw) try { + PerformanceTimer timing("Shader.DrawStage"); + using Stage = ShaderRecompiler::ShaderStage; + context.phaseTiming.Phase(DrawRowVectors); + const auto& program = context.programs[i]; + Graphics::HeapCostScope prepareCost(Graphics::HeapCost::StagePrepare); + auto request = drawStageRequest(context, i, pushOffset, drawParameters); + const auto waitedBefore = traceCapSync() || context.profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0; - const bool heapCandidate = heapPartners && (program.binary.stage == Stage::Fragment || HeapPreRasterStage(program.binary.stage)) && !HeapStageExcluded(program.binary.stage) && HeapFragmentsEnabled(); - const auto fragmentOnHeap = [&] { - const auto fragment = std::find_if(context.programs.begin(), context.programs.end(), [](const DrawProgram& candidate) { return candidate.binary.stage == Stage::Fragment; }); - if (fragment == context.programs.end()) return true; - const auto known = HeapFragmentKnown(fragment->snapshot.get(), fragment->codeOffset); - return known.has_value() ? *known : PreparedHeapStage(*fragment->snapshot, fragment->codeOffset); - }; - const bool heapVertex = request.target.descriptorMemory && HeapPreRasterStage(program.binary.stage) && fragmentOnHeap(); - const auto heapKey = HeapFragmentKey(program.codeOffset, heapVertex ? HeapKeyClass::HeapVertex : HeapKeyClass::Draw); - const auto heapKnown = heapCandidate ? HeapFragmentKnown(program.snapshot.get(), heapKey) : std::nullopt; - if (heapKnown.value_or(false)) request.target.gpuResolvedImages = true; + if (heapDraw) request.target.gpuResolvedImages = true; const auto invocationFor = [&] { try { return InvocationFor(*program.snapshot, program.codeOffset, request); @@ -185,25 +194,12 @@ std::shared_ptr Driver::materializeDraw } }; auto invocation = invocationFor(); - const auto heapEligible = [&](const std::shared_ptr& plan) { return HeapStageEligible(program.binary.stage, plan.get(), heapVertex); }; - const auto plan = heapCandidate && invocation.Plan() == nullptr ? invocation.LoadPlan() : invocation.Plan(); using StageReason = Graphics::HeapStageReason; - StageReason stageReason = StageReason::Heap; - if (!heapCandidate) stageReason = !HeapFragmentsEnabled() ? StageReason::Disabled : !heapPartners ? StageReason::PairRefused : StageReason::StageKind; - else if (heapKnown == std::optional(false)) stageReason = StageReason::KnownIneligible; - if (heapKnown.value_or(false) && !heapEligible(plan)) { - stageReason = HeapStageIneligibility(program.binary.stage, plan.get(), heapVertex); - NoteHeapFragment(program.snapshot.get(), heapKey, false); - request.target.gpuResolvedImages = false; - invocation = invocationFor(); - } else if (heapCandidate && !heapKnown.has_value()) { - stageReason = HeapStageIneligibility(program.binary.stage, plan.get(), heapVertex); - const bool eligible = stageReason == StageReason::Heap; - NoteHeapFragment(program.snapshot.get(), heapKey, eligible); - if (eligible) { - request.target.gpuResolvedImages = true; - invocation = invocationFor(); - } + const StageReason stageReason = heapDraw ? StageReason::Heap : !Graphics::DescriptorHeapEnabled() ? StageReason::Disabled : StageReason::Excluded; + if (heapDraw) { + const auto plan = invocation.Plan() == nullptr ? invocation.LoadPlan() : invocation.Plan(); + if (const auto* ineligible = HeapStageIneligibility(program.binary.stage, plan.get())) + throw std::runtime_error(std::string("AGC graphics: a GPU heap stage cannot take the heap: ") + ineligible); } Graphics::NoteHeapStageReason(stageReason); prepareCost.Stop(); @@ -215,17 +211,8 @@ std::shared_ptr Driver::materializeDraw stageCapture.capture.reset(); stageCapture.forgetSerial = GuestMemory::ForgetSerial(); stageCapture.pushOffset = pushOffset; - const auto unmapped = [&] { - Graphics::NoteHeapFallback(Graphics::HeapFallback::DrawUnmapped); - NoteHeapFragment(program.snapshot.get(), heapKey, false); - return materializeDrawStage(context, i, pushOffset, drawParameters, heapPartners); - }; if (request.target.gpuResolvedImages) { - switch (materializeHeapDirect(context, i, invocation, request, timing)) { - case HeapDirect::Taken: return stageCapture.compiled; - case HeapDirect::Unmapped: return unmapped(); - case HeapDirect::Declined: break; - } + if (materializeHeapDirect(context, i, invocation, request, timing)) return stageCapture.compiled; } const auto capture = [&] { const SampledReadScope sampling(evidenceReads); @@ -245,6 +232,7 @@ std::shared_ptr Driver::materializeDraw for (std::size_t j = 0; j < context.programs.size(); ++j) { if (context.matched[j] != nullptr && !context.recompiled[j] && (context.drawHit || j < i)) context.memory.insert(context.memory.end(), context.matchedRegions[j].begin(), context.matchedRegions[j].end()); + if (j < i && context.recompiled[j] && context.stageCaptures[j].direct) context.memory.insert(context.memory.end(), context.stageCaptures[j].regions.begin(), context.stageCaptures[j].regions.end()); } request.context.memory = context.memory; if (traceCapSync()) traceCapture("draw-capture", program.binary.codeAddress, context.submission.queue, context.memory, Graphics::Recorder::ThreadWaitedMs() - waitedBefore); @@ -297,7 +285,7 @@ std::shared_ptr Driver::materializeDraw throw stageFailure(program, request, error, request.context.memory); } } - if (stageCapture.compiled->gpuResolvedImages && !HeapDrawStageMappable(*stageCapture.compiled, program.binary.stage)) return unmapped(); + if (stageCapture.compiled->gpuResolvedImages) RequireHeapStageMappable(*stageCapture.compiled); stageCapture.capture = capture; timing.Mark("materialize"); const auto walked = capture->userDataUse.asValue | capture->userDataUse.asBase; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp index b852725b4a35..2346e3b4f8c2 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp @@ -10,7 +10,6 @@ namespace AgcDriver::DriverDetail { void Driver::lookupDraw(const Submission& submission, const std::shared_ptr& localDevice, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector& programs, const std::vector& roles, const std::vector>& vertexInfos, bool useDrawEntries, bool registerKey, bool profile, std::uint64_t& drawKey, std::shared_ptr& entry, std::vector>& matched, std::vector>& matchedRegions, bool& drawHit, bool& verifyHit, DrawPhaseTiming& phaseTiming, std::array& phaseMs, const std::shared_ptr& dataEntry, DrawDataCandidates& dataCandidates, std::vector& stageData) { using Role = ShaderRecompiler::ProgramRole; - const bool heapRefused = HeapRefused(); if (useDrawEntries) { if (!registerKey) { drawKey = 0xcbf29ce484222325ull; @@ -146,7 +145,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptrregisteredViews != nullptr && !CaptureRegisteredViewsCurrent(*variant->registeredViews)) continue; - if (variant->pushOffset != cursor || (heapRefused && variant->compiled->gpuResolvedImages) || (heapMode && variant->compiled->gpuResolvedImages != *heapMode)) continue; + if (variant->pushOffset != cursor || (heapMode && variant->compiled->gpuResolvedImages != *heapMode)) continue; if (programs[i].binary.stage == ShaderRecompiler::ShaderStage::Mesh && !std::equal(variant->meshIndexDescriptor.begin(), variant->meshIndexDescriptor.end(), programs[i].userData.begin() + ShaderRecompiler::MeshIndexBufferUserWord)) { if (!anyLayout) outcome = EntryOutcome::Differing; anyLayout = true; @@ -256,7 +255,6 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptrstages[i]) { if (variant->registeredViews != nullptr && !CaptureRegisteredViewsCurrent(*variant->registeredViews)) continue; - if (heapRefused && variant->compiled->gpuResolvedImages) continue; bool usedEqual = true; for (std::size_t w = 0; w < now.size() && usedEqual; ++w) { if (now[w] != was[w] && (w >= 64u || ((variant->userDataMask >> w) & 1u) != 0)) usedEqual = false; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 44ffa390d21d..938b37129ce9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -111,70 +111,22 @@ VerifyCounts& verifyCounts() { } -bool HeapRefused() { - return Graphics::BindlessHeap::RefusesDraws(); -} - -namespace { - -bool& heapDrawOff() { - struct DrawOffStorage {}; - return HostThreadLocal(); -} - -} - -HeapDrawOff::HeapDrawOff() : previous(heapDrawOff()) { - heapDrawOff() = true; -} - -HeapDrawOff::~HeapDrawOff() { - heapDrawOff() = previous; -} - -bool HeapFragmentsEnabled() { - return Graphics::DescriptorHeapEnabled() && !HeapRefused() && !heapDrawOff(); -} - bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage) { using Stage = ShaderRecompiler::ShaderStage; return stage == Stage::Vertex || stage == Stage::Local || stage == Stage::TessellationControl || stage == Stage::TessellationEvaluation || stage == Stage::Mesh; } -Graphics::HeapStageReason HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, - bool heapVertex) { - using Reason = Graphics::HeapStageReason; - if (stage != ShaderRecompiler::ShaderStage::Fragment && !HeapPreRasterStage(stage)) return Reason::StageKind; - if (plan == nullptr) return Reason::NoPlan; - if (stage != ShaderRecompiler::ShaderStage::Fragment && !heapVertex) return Reason::FragmentOffHeap; +const char* HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan) { + if (stage != ShaderRecompiler::ShaderStage::Fragment && !HeapPreRasterStage(stage)) return "its stage kind does not take the heap"; + if (plan == nullptr) return "it has no resource plan"; if (plan->stage == ShaderRecompiler::IrShaderStage::Unknown || plan->stage == ShaderRecompiler::IrShaderStage::Fetch) - return Reason::PlanStage; - if (!ShaderRecompiler::HeapFragmentEligible(*plan)) return Reason::UnresolvedImageSource; - return Reason::Heap; -} - -bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan, bool heapVertex) { - return HeapStageIneligibility(stage, plan, heapVertex) == Graphics::HeapStageReason::Heap; -} - -namespace { - -std::unordered_set& refusedPairs() { - struct PairsStorage {}; - return HostThreadLocal, PairsStorage>(); -} - -} - -bool HeapPairRefused(std::uint64_t pair) { - return refusedPairs().contains(pair); + return "its resource plan has a fetch or unknown stage"; + return nullptr; } -void RefuseHeapPair(std::uint64_t pair) { - auto& refused = refusedPairs(); - if (refused.size() >= ThreadCacheLimit) refused.clear(); - refused.insert(pair); +bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan) { + return HeapStageIneligibility(stage, plan) == nullptr; } namespace { @@ -234,7 +186,7 @@ const HeapExclusions& heapExclusions() { return exclusions; } -bool heapClassesAllowed(const ShaderRecompiler::RecompileResult& result) { +std::string heapClassesFailure(const ShaderRecompiler::RecompileResult& result) { using Role = ShaderRecompiler::DescriptorRole; using Kind = ShaderRecompiler::DescriptorKind; const auto& exclusions = heapExclusions(); @@ -243,61 +195,64 @@ bool heapClassesAllowed(const ShaderRecompiler::RecompileResult& result) { const bool table = binding.role == Role::ImageTable || binding.role == Role::ImageStorageTable; const bool image = binding.role == Role::GuestImages && (binding.kind == Kind::SampledImage || binding.kind == Kind::StorageImage); if (table || image) demand += binding.count; - if (table && exclusions.tables) return false; - if (image && binding.kind == Kind::StorageImage && exclusions.storage) return false; - if (image && binding.kind == Kind::SampledImage && exclusions.sampled) return false; + if ((table && exclusions.tables) || (image && binding.kind == Kind::StorageImage && exclusions.storage) || + (image && binding.kind == Kind::SampledImage && exclusions.sampled)) + return "AGC graphics: a GPU heap stage uses an image class APS5_GPU_HEAP_EXCLUDE names, which its resource plan did not show"; } - return demand <= Graphics::BindlessHeap::ImageSlotCapacity(); + const auto capacity = Graphics::BindlessHeap::ImageSlotCapacity(); + if (demand > capacity) + return "AGC graphics: a GPU heap stage needs " + std::to_string(demand) + " image slots, more than the heap's " + std::to_string(capacity); + return {}; } +std::string heapStageFailure(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { + if (auto failure = heapClassesFailure(result); !failure.empty()) return failure; + std::pair refused{}; + if (!Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), workgroupAddress, result.dataAddressPush, + result.functionLdsBuffer, result.meshWindowBuffer, result.scratchPoolSlotDwords != 0u, &refused)) + return "AGC graphics: a GPU heap stage uses descriptor set " + std::to_string(refused.first) + " binding " + std::to_string(refused.second) + + ", which the heap cannot map"; + return {}; } -bool HeapStageExcluded(ShaderRecompiler::ShaderStage stage) { - return (heapExclusions().stages >> static_cast(stage) & 1u) != 0u; -} - -bool HeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { +const std::string& knownHeapStageFailure(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { struct MappableStorage {}; - auto& known = HostThreadLocal, MappableStorage>(); + auto& known = HostThreadLocal, MappableStorage>(); const auto key = result.variantId * 2u + (workgroupAddress ? 1u : 0u); if (const auto found = known.find(key); found != known.end()) return found->second; if (known.size() >= ThreadCacheLimit) known.clear(); - const bool mappable = heapClassesAllowed(result) && - Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), workgroupAddress, result.dataAddressPush, result.functionLdsBuffer, result.meshWindowBuffer, result.scratchPoolSlotDwords != 0u); - known.emplace(key, mappable); - return mappable; + return known.emplace(key, heapStageFailure(result, workgroupAddress)).first->second; } -namespace { - -struct HeapFragmentKey { - const void* snapshot; - std::size_t codeOffset; - bool operator==(const HeapFragmentKey&) const = default; -}; +} -struct HeapFragmentKeyHash { - std::size_t operator()(const HeapFragmentKey& key) const { - return std::hash{}(key.snapshot) ^ (key.codeOffset * 0x9e3779b97f4a7c15ull); - } -}; +void RequireHeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { + if (const auto& failure = knownHeapStageFailure(result, workgroupAddress); !failure.empty()) throw std::runtime_error(failure); +} -std::unordered_map& heapFragments() { - struct FragmentsStorage {}; - auto& value = HostThreadLocal, FragmentsStorage>(); - return value; +bool HeapStageFits(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { + return knownHeapStageFailure(result, workgroupAddress).empty(); } +bool HeapStageExcluded(ShaderRecompiler::ShaderStage stage) { + return (heapExclusions().stages >> static_cast(stage) & 1u) != 0u; } -std::optional HeapFragmentKnown(const void* snapshot, std::size_t codeOffset) { - const auto& known = heapFragments(); - const auto found = known.find({snapshot, codeOffset}); - return found == known.end() ? std::nullopt : std::optional(found->second); +bool HeapPlanExcluded(const ShaderRecompiler::IrResourcePlan& plan) { + using Class = ShaderRecompiler::ImageResourceClass; + const auto& exclusions = heapExclusions(); + if (exclusions.tables && std::ranges::any_of(plan.descriptorSources, [](const ShaderRecompiler::DescriptorSource& source) { return source.tableColumn.has_value(); })) + return true; + const auto excludedImage = [&](const ShaderRecompiler::ImageResource& image) { + return (exclusions.storage && image.resourceClass == Class::Storage) || (exclusions.sampled && image.resourceClass == Class::Sampled); + }; + if (std::ranges::any_of(plan.info.images, excludedImage)) return true; + return std::ranges::any_of(plan.info.runtimeImageModes, [&](const std::vector& modes) { return std::ranges::any_of(modes, excludedImage); }); } -void NoteHeapFragment(const void* snapshot, std::size_t codeOffset, bool eligible) { - heapFragments()[{snapshot, codeOffset}] = eligible; +bool HeapClassesExcluded() { + const auto& exclusions = heapExclusions(); + return exclusions.tables || exclusions.storage || exclusions.sampled; } bool SampleHeapStageVerify() { @@ -652,19 +607,6 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade return materialized; } -namespace { - -std::atomic unmappedStage{-1}; - -} - -void SetHeapStageUnmapped(std::optional stage) { - unmappedStage.store(stage.has_value() ? static_cast(*stage) : -1, std::memory_order_relaxed); -} - -bool HeapDrawStageMappable(const ShaderRecompiler::RecompileResult& result, ShaderRecompiler::ShaderStage stage) { - return unmappedStage.load(std::memory_order_relaxed) != static_cast(stage) && !HeapStageExcluded(stage) && HeapStageMappable(result); -} std::uint64_t HeapStagesTaken() { return heapStages().load(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp index 73050df7eb1a..62d63c69a90c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp @@ -1130,12 +1130,6 @@ std::shared_ptr LinkUserDataCallees(const S } -bool PreparedHeapStage(const ShaderSnapshot& snapshot, std::size_t codeOffset) { - if (snapshot.prepared == nullptr) return false; - std::lock_guard lock(snapshot.prepared->mutex); - return std::ranges::any_of(snapshot.prepared->entries, [&](const auto& entry) { return entry.codeOffset == codeOffset && entry.handle != nullptr && entry.handle->artifact != nullptr && ShaderRecompiler::GetPreparedArtifact(*entry.handle).gpuResolvedImages; }); -} - ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request) { require(codeOffset < snapshot.code.size(), "prepared shader code offset is outside the snapshot"); const auto code = std::span(snapshot.code).subspan(codeOffset); @@ -1425,7 +1419,7 @@ bool LibraryPrebuildDisabled() { void PrebuildStageLibrary(const std::shared_ptr& device, const Graphics::ShaderStages& stages, ShaderRecompiler::ShaderStage stage, std::shared_ptr result, std::uint32_t pushOffset, std::uint64_t program) { if (LibraryPrebuildDisabled() || result == nullptr || (stage != ShaderRecompiler::ShaderStage::Vertex && stage != ShaderRecompiler::ShaderStage::Fragment)) return; - if (result->gpuResolvedImages && !HeapStageMappable(*result)) return; + if (result->gpuResolvedImages && !HeapStageFits(*result)) return; SubmitLibraryPrebuild([device, stages, stage, result = std::move(result), pushOffset] { const std::array shaders{{{stage, result.get(), pushOffset}}}; try { @@ -1457,9 +1451,9 @@ std::vector PrepareRegistered(RegisteredPreparation& pla } }; bool heapPrebuilt = false; - if ((fragment || heapVertex) && !HeapStageExcluded(request.shader.stage) && HeapFragmentsEnabled()) { + if ((fragment || heapVertex) && !HeapStageExcluded(request.shader.stage) && Graphics::DescriptorHeapEnabled()) { const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, entries.front().handle); - if (invocation && HeapStageEligible(request.shader.stage, invocation->Plan().get(), heapVertex)) { + if (invocation && HeapStageEligible(request.shader.stage, invocation->Plan().get())) { auto heapRequest = request; heapRequest.target.gpuResolvedImages = true; PerformanceTimer timing("Shader.PrepareArtifact"); @@ -2043,13 +2037,13 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod requests.push_back(std::move(request)); pushOffset += bytes; } - if (HeapFragmentsEnabled()) { + if (Graphics::DescriptorHeapEnabled()) { std::vector heap; const auto addHeap = [&](std::size_t index, bool heapVertex) { const auto& stage = prepared[index]; if (stage.entry.handle == nullptr || !requests[index] || HeapStageExcluded(stage.stage)) return false; const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(*requests[index], stage.entry.handle); - if (!invocation || !HeapStageEligible(stage.stage, invocation->Plan().get(), heapVertex)) return false; + if (!invocation || !HeapStageEligible(stage.stage, invocation->Plan().get()) || (HeapPreRasterStage(stage.stage) && !heapVertex)) return false; auto request = *requests[index]; request.target.gpuResolvedImages = true; const auto handle = preparedHandle(*stage.snapshot, stage.entry.codeOffset, request); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index d3b45eee79e0..c573b3a627cc 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -2706,7 +2706,10 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : state->functionsReady = true; } Graphics::PrepareImportWatch(graphicsContext()); - Graphics::SetDescriptorHeapDevice(state->descriptorHeap && state->descriptorHeapProperties.maxPushDataSize >= Graphics::PipelinePushConstantBytes); + const bool heapDevice = state->descriptorHeap && state->descriptorHeapProperties.maxPushDataSize >= Graphics::PipelinePushConstantBytes; + if (heapDevice && Graphics::GpuHeapEnabled() && !state->timelineSemaphores) + throw std::runtime_error("AGC graphics: the GPU heap needs timeline semaphores to evict slots; APS5_NO_TIMELINE cannot be used with APS5_GPU_HEAP"); + Graphics::SetDescriptorHeapDevice(heapDevice); Graphics::BufferPool::SetForceAddresses(Graphics::DescriptorHeapEnabled()); state->bufferPool = std::make_shared(graphicsContext()); state->emptyBuffer = std::make_unique(graphicsContext(), Graphics::EmptyBufferBytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index ffe323844474..f518f371ab42 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -73,7 +73,6 @@ class BindlessHeap { std::span samplerSlots, std::span samplerGenerations) const; std::uint32_t AbsentSlot(std::uint32_t kind, VkImageView view); static bool NearlyFull(); - static bool RefusesDraws(); static std::uint32_t ImageSlotCapacity(); std::uint32_t ImageSlots() const { return slotCap; } std::uint32_t TouchSlots(std::span> slots, std::span samplerSlots, std::uint32_t touched) const; @@ -255,7 +254,6 @@ class BindlessHeap { std::unordered_map samplerSlots; std::unordered_set absentSlots; bool refused = false; - bool refusing = false; void noteRefusedLocked(const char* what, std::uint32_t margin); void noteTakenLocked(); void noteSamplerTakenLocked(); @@ -287,7 +285,8 @@ class HeapSlotOwner { bool GpuHeapEnabled(); void SetDescriptorHeapDevice(bool available); bool DescriptorHeapEnabled(); -bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds = false, bool meshWindow = false, bool scratchPool = false); +bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds = false, bool meshWindow = false, bool scratchPool = false, + std::pair* refused = nullptr); void NoteHeapComputeStage(); std::uint64_t HeapComputeStages(); void NoteImageTableBuild(); @@ -300,23 +299,18 @@ std::uint64_t EmbeddedSamplerMappings(); std::uint64_t SlotPressureSubmits(); std::uint64_t HeapSlotEvictions(); enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, DepthTransfer, StagedMerge, FirstSampleCopy, Count }; -enum class HeapFallback : std::uint8_t { DrawUnmapped, DrawMixedRetry, DrawRefusedPair, DrawMixedReused, DispatchUnmapped, Count }; +enum class HeapExcluded : std::uint8_t { Draw, Dispatch, Count }; enum class HeapStageReason : std::uint8_t { Heap, Disabled, - PairRefused, - FragmentOffHeap, - StageKind, - NoPlan, - PlanStage, - UnresolvedImageSource, - KnownIneligible, + Excluded, Count }; void NoteHeapStageReason(HeapStageReason reason); void NoteHeapRecord(bool compute, bool heap); -void NoteHeapFallback(HeapFallback reason); -std::uint64_t HeapFallbacks(HeapFallback reason); +void NoteHeapExcluded(HeapExcluded reason); +std::uint64_t HeapExcludedCount(HeapExcluded reason); +std::uint64_t HeapStageReasons(HeapStageReason reason); void NoteCpuBufferCopy(std::uint64_t bytes); enum class HeapCost : std::uint8_t { StagePrepare, diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 4cb46d4b4f84..61e607e7704d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -300,13 +300,11 @@ constexpr std::uint32_t ImageSlotMargin = 1024u; constexpr std::uint32_t EvictIdleSubmissions = 2u; constexpr std::uint32_t SamplerSlotMargin = Abi::GpuSamplerHeapSlots / 4u; std::atomic refusedHeaps{0}; -std::atomic refusingHeaps{0}; } BindlessHeap::~BindlessHeap() { if (refused) refusedHeaps.fetch_sub(1, std::memory_order_relaxed); - if (refusing) refusingHeaps.fetch_sub(1, std::memory_order_relaxed); } namespace { @@ -473,9 +471,6 @@ bool BindlessHeap::NearlyFull() { return refusedHeaps.load(std::memory_order_relaxed) != 0u; } -bool BindlessHeap::RefusesDraws() { - return refusingHeaps.load(std::memory_order_relaxed) != 0u; -} @@ -496,14 +491,8 @@ void BindlessHeap::noteRefusedLocked(const char* what, std::uint32_t margin) { if (refused) return; refused = true; refusedHeaps.fetch_add(1, std::memory_order_relaxed); - if (submitter == nullptr || submitter->HasTimeline()) { - pressured.store(true, std::memory_order_relaxed); - std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; the next draw or dispatch submits its batch so idle slots can be evicted\n", margin, what); - return; - } - refusing = true; - refusingHeaps.fetch_add(1, std::memory_order_relaxed); - std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; draws and dispatches take the per-draw path until released slots leave twice that many free\n", margin, what); + pressured.store(true, std::memory_order_relaxed); + std::fprintf(stderr, "[gpu-heap] fewer than %u %s slots are free; the next draw or dispatch submits its batch so idle slots can be evicted\n", margin, what); } void BindlessHeap::noteTakenLocked() { @@ -537,7 +526,7 @@ std::uint32_t BindlessHeap::TouchSlots(std::spanHasTimeline() || !GuestMemory::GpuMutex().HeldByThisThread()) return; + if (submitter == nullptr || !GuestMemory::GpuMutex().HeldByThisThread()) return; if (idleSubmissions != 0u && evictScanEpoch == epoch) return; if (idleSubmissions != 0u) evictScanEpoch = epoch; std::vector> idle; @@ -570,7 +559,7 @@ void BindlessHeap::evictLocked(std::uint32_t idleSubmissions) { void BindlessHeap::evictSamplersLocked(std::uint32_t idleSubmissions) { const auto epoch = useEpoch.load(std::memory_order_relaxed); - if (submitter == nullptr || !submitter->HasTimeline() || !GuestMemory::GpuMutex().HeldByThisThread()) return; + if (submitter == nullptr || !GuestMemory::GpuMutex().HeldByThisThread()) return; if (idleSubmissions != 0u && samplerEvictScanEpoch == epoch) return; if (idleSubmissions != 0u) samplerEvictScanEpoch = epoch; std::vector> idle; @@ -597,7 +586,7 @@ void BindlessHeap::evictSamplersLocked(std::uint32_t idleSubmissions) { bool BindlessHeap::reclaimLocked(bool wait) { bool reclaimed = false; - while (!retiring.empty() && retiring.front().serial != 0u && submitter != nullptr && submitter->HasTimeline()) { + while (!retiring.empty() && retiring.front().serial != 0u && submitter != nullptr) { const auto serial = retiring.front().serial; if (!submitter->WaitSerialFor(serial, 0u)) { if (!wait || reclaimed || serial > submitter->Submissions()) break; @@ -637,10 +626,6 @@ void BindlessHeap::noteReleasedLocked() { refused = false; refusedHeaps.fetch_sub(1, std::memory_order_relaxed); pressured.store(false, std::memory_order_relaxed); - if (!refusing) return; - refusing = false; - refusingHeaps.fetch_sub(1, std::memory_order_relaxed); - std::fprintf(stderr, "[gpu-heap] released slots left twice the margin free; draws take the heap again\n"); } std::uint32_t BindlessHeap::SamplerGeneration(std::uint32_t slot) const { @@ -777,7 +762,7 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) bool BindlessHeap::poolBlockDoneLocked(PoolBlock& block) { if (block.serial == 0u) return true; - if (block.recorder == nullptr || !block.recorder->HasTimeline() || !block.recorder->WaitSerialFor(block.serial, 0u)) return false; + if (block.recorder == nullptr || !block.recorder->WaitSerialFor(block.serial, 0u)) return false; block.serial = 0u; return true; } @@ -886,7 +871,7 @@ BindlessHeap::DataSpan BindlessHeap::RingAllocate(std::size_t words, SpanMark& m if (!skipBusy) return Taken::No; for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) { auto& entry = ringChunks[chunk]; - if (chunk == ringChunk || entry.serial == 0u || entry.recorder == nullptr || !entry.recorder->HasTimeline()) continue; + if (chunk == ringChunk || entry.serial == 0u || entry.recorder == nullptr) continue; if (!entry.recorder->WaitSerialFor(entry.serial, 0u)) return Taken::Busy; entry.serial = 0u; } @@ -950,8 +935,6 @@ void BindlessHeap::enterRingChunk(std::size_t index) { auto& chunk = ringChunks[index]; if (chunk.open) throw std::runtime_error("AGC bindless heap: one batch's buffer descriptors exceed the descriptor ring"); if (chunk.serial != 0u) { - if (!chunk.recorder->HasTimeline()) - throw std::runtime_error("AGC bindless heap: the descriptor ring needs the recorder timeline to wait for a batch"); if (!chunk.recorder->WaitSerialFor(chunk.serial, 0u)) { chunk.recorder->WaitSerial(chunk.serial); ++counts.ringWaits; @@ -1168,9 +1151,11 @@ VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, co } -bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds, bool meshWindow, bool scratchPool) { +bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds, bool meshWindow, bool scratchPool, + std::pair* refused) { HeapBindingUse use; const bool mappable = heapBindings(spirv, {.workgroupAddress = workgroupAddress, .gdsAddress = gdsAddress, .pixelLds = pixelLds, .meshWindow = meshWindow, .scratchPool = scratchPool}, use); + if (!mappable && refused != nullptr) *refused = use.refused; if (!mappable && pipelineStats()) { static std::mutex causesMutex; static std::map causes; @@ -1365,26 +1350,17 @@ std::atomic commandBuffersBegun{0}; std::atomic cpuBufferCopies{0}; std::atomic cpuBufferCopyBytes{0}; std::array, static_cast(SetBindSite::Count)> setBinds{}; -std::array, static_cast(HeapFallback::Count)> heapFallbacks{}; +std::array, static_cast(HeapExcluded::Count)> heapExcludedCounts{}; std::array, 4> heapRecords{}; std::size_t heapRecordIndex(bool compute, bool heap) { return (compute ? 2u : 0u) + (heap ? 1u : 0u); } std::array, static_cast(HeapStageReason::Count)> heapStageReasons{}; -constexpr std::array(HeapStageReason::Count)> HeapStageReasonNames{"heap", - "disabled", - "pair refused", - "fragment off heap", - "stage kind", - "no plan", - "plan stage", - "unresolved image source", - "known ineligible"}; +constexpr std::array(HeapStageReason::Count)> HeapStageReasonNames{"heap", "disabled", "excluded"}; constexpr std::array(SetBindSite::Count)> SetBindSiteNames{"draw", "dispatch", "detiler", "color transfer", "presentation", "depth transfer", "staged merge", "first-sample copy"}; -constexpr std::array(HeapFallback::Count)> HeapFallbackNames{ - "draw unmapped", "draw mixed retry", "draw refused pair", "draw mixed reused", "dispatch unmapped"}; +constexpr std::array(HeapExcluded::Count)> HeapExcludedNames{"draw excluded", "dispatch excluded"}; std::uint64_t takeCount(std::atomic& counter) { return counter.exchange(0, std::memory_order_relaxed); @@ -1419,7 +1395,7 @@ void reportHeapStatistics() { if (now - last < std::chrono::seconds(10)) return; last = now; const auto binds = takeNamedCounts(setBinds, SetBindSiteNames); - const auto fallbacks = takeNamedCounts(heapFallbacks, HeapFallbackNames); + const auto excluded = takeNamedCounts(heapExcludedCounts, HeapExcludedNames); const auto stageReasons = takeNamedCounts(heapStageReasons, HeapStageReasonNames); std::string costs; for (std::size_t i = 0; i < heapCostNs.size(); ++i) { @@ -1498,10 +1474,10 @@ void reportHeapStatistics() { const auto templates = ShaderRecompiler::HeapTemplateCounts(); std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " - "heap binds %llu over %llu command buffers; set binds:%s; fallbacks:%s; draw stages:%s; " + "heap binds %llu over %llu command buffers; set binds:%s; excluded:%s; draw stages:%s; " "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; descriptor ring %llu MiB, %llu waits, %llu busy chunks skipped, %llu early submits, since start at most %llu KiB per batch; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), - printed(commandBuffers), binds.c_str(), fallbacks.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), + printed(commandBuffers), binds.c_str(), excluded.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), printed(spansWritten), printed(spansKept), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(ringMiB), printed(ringWaits), printed(busySkips), printed(pressureSubmits), printed(totals.ringBatchPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } @@ -1537,12 +1513,16 @@ void NoteCpuBufferCopy(std::uint64_t bytes) { cpuBufferCopyBytes.fetch_add(bytes, std::memory_order_relaxed); } -void NoteHeapFallback(HeapFallback reason) { - heapFallbacks[static_cast(reason)].fetch_add(1, std::memory_order_relaxed); +void NoteHeapExcluded(HeapExcluded reason) { + heapExcludedCounts[static_cast(reason)].fetch_add(1, std::memory_order_relaxed); +} + +std::uint64_t HeapExcludedCount(HeapExcluded reason) { + return heapExcludedCounts[static_cast(reason)].load(std::memory_order_relaxed); } -std::uint64_t HeapFallbacks(HeapFallback reason) { - return heapFallbacks[static_cast(reason)].load(std::memory_order_relaxed); +std::uint64_t HeapStageReasons(HeapStageReason reason) { + return heapStageReasons[static_cast(reason)].load(std::memory_order_relaxed); } void NoteCommandBufferBegun(VkCommandBuffer commands) { @@ -1670,6 +1650,7 @@ void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { } void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { + if (!recorder.HasTimeline()) throw std::runtime_error("AGC bindless heap: a batch using the heap was submitted by a recorder without a timeline semaphore"); std::lock_guard lock(mutex); submitter = &recorder; useEpoch.fetch_add(1, std::memory_order_relaxed); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index f93e5743b531..e5758ccd5dc1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -214,7 +214,7 @@ void ringSpans(const Context& context) { require(counts.spansWritten == 3u && counts.spansKept == 3u, "three spans written and kept"); BindlessHeap::SpanMark third; static_cast(heap.RingAllocate(chunkWords, third)); - Recorder recorder(context); + Recorder recorder(context, true); heap.Submitted(recorder, 0u); require(heap.Held(first), "a span stays held after its batch is submitted while the ring has not come back to its chunk"); BindlessHeap::SpanMark fill; @@ -241,7 +241,7 @@ bool ringLargeSpans(const Context& context) { BindlessHeap::SpanMark large; const auto span = heap.RingAllocate(largeWords, large); require(span.words.size() == largeWords && heap.Held(large), "a span over two chunks is written and held"); - Recorder recorder(context); + Recorder recorder(context, true); BindlessHeap::SpanMark fill; const auto untilWrap = [&](const BindlessHeap::SpanMark& kept) { const auto wraps = heap.Statistics().ringWraps; @@ -271,7 +271,7 @@ bool ringPressure(const Context& context) { BindlessHeap heap(context); if (heap.RingChunkCount() < 4u) return false; constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); - Recorder recorder(context); + Recorder recorder(context, true); BindlessHeap::SpanMark fill; require(!heap.TakeRingPressure(), "an empty ring is under no pressure"); const auto half = heap.RingChunkCount() / 2u; @@ -295,7 +295,7 @@ bool ringPressure(const Context& context) { void ringCurrentChunk(const Context& context) { BindlessHeap heap(context); constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); - Recorder recorder(context); + Recorder recorder(context, true); std::vector pins(heap.RingChunkCount() - 1u); for (auto& pin : pins) { static_cast(heap.RingAllocate(chunkWords, pin)); @@ -562,7 +562,7 @@ bool slotPressureSubmits(const Context& context, VkImageView view) { require(slot.has_value(), "a texture takes one of the eight capped slots"); slots.push_back(*slot); } - require(BindlessHeap::NearlyFull() && !BindlessHeap::RefusesDraws(), "one free slot of eight marks the heap nearly full without refusing draws"); + require(BindlessHeap::NearlyFull(), "one free slot of eight marks the heap nearly full"); submit(); require(heap.Statistics().slotsEvicted == 0u && BindlessHeap::NearlyFull(), "a submission in the middle of a draw evicts no slot the draw took in the batch it submitted"); @@ -589,23 +589,21 @@ bool slotPressureSubmits(const Context& context, VkImageView view) { return true; } -void noTimelineRefuses(const Context& context, VkImageView view) { - auto& heap = BindlessHeap::For(context); - Recorder recorder(context, false); +void noTimelineFails(const Context& context) { + static_cast(BindlessHeap::For(context)); + Recorder recorder(context); recorder.Activate(); + bool failed = false; { std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); static_cast(recorder.Commands()); - recorder.Submit(); - } - std::vector> held; - for (std::size_t index = 0; index < 7u; ++index) { - held.push_back(fakeTexture(index)); - require(heap.TextureSlot(Abi::FirstImageBinding, held.back().get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture takes one of the eight capped slots"); + try { + recorder.Submit(); + } catch (const std::runtime_error& error) { + failed = std::string(error.what()).find("without a timeline semaphore") != std::string::npos; + } } - require(BindlessHeap::RefusesDraws() && !heap.TakeSlotPressure(), "a heap whose recorder has no timeline cannot evict, so it refuses draws instead of submitting early"); - for (const auto& texture : held) heap.ReleaseSlots(texture.get()); - require(!BindlessHeap::RefusesDraws(), "releasing the textures takes the heap again"); + require(failed, "a heap batch from a recorder without a timeline, which could not wait for its slots, was accepted"); BindlessHeap::Release(context.device); } @@ -717,8 +715,8 @@ int main(int argc, char** argv) { else if (mode == "views-come-back") viewsComeBack(context, storage); else if (mode == "two-heaps-come-back") twoHeapsComeBack(context, storage); else if (mode == "owner-views-release") ownerViewsRelease(context, storage); - else if (mode == "no-timeline-refuses") noTimelineRefuses(context, sampled); else if (mode == "shared-owner-release") sharedOwnerRelease(context, storage); + else if (mode == "no-timeline-fails") noTimelineFails(context); else if (mode == "idle-slots-evicted" || mode == "pressure-submit" || mode == "samplers-evicted") { const bool ran = mode == "idle-slots-evicted" ? idleSlotsEvicted(context, sampled) : mode == "pressure-submit" ? slotPressureSubmits(context, sampled) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_reuse_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_reuse_tests.cmake index c82d3ec00171..59eb9226d7e8 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_reuse_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_reuse_tests.cmake @@ -15,6 +15,9 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_draw_cache_reuse_inline PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_PIPELINED_DRAWS=0;APS5_VERIFY_DRAW_RECIPE=1;APS5_VERIFY_REGISTER_KEYS=1" SKIP_RETURN_CODE 77) add_test(NAME agc_driver_draw_cache_reuse_indirect COMMAND agc_driver_draw_cache_reuse_tests) set_tests_properties(agc_driver_draw_cache_reuse_indirect PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_CACHE_INDIRECT=1;APS5_PROFILE_DRAW=1" SKIP_RETURN_CODE 77) + agc_add_env_test(agc_driver_draw_cache_reuse_indirect_gpu_heap agc_driver_draw_cache_reuse_tests NO_WORKING_DIRECTORY + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_DRAW_CACHE_INDIRECT=1 APS5_PROFILE_DRAW=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) + set_tests_properties(agc_driver_draw_cache_reuse_indirect_gpu_heap PROPERTIES FAIL_REGULAR_EXPRESSION "FATAL:") set_tests_properties(agc_driver_draw_cache_reuse agc_driver_draw_cache_reuse_off agc_driver_draw_cache_reuse_verify agc_driver_draw_cache_reuse_inline agc_driver_draw_cache_reuse_indirect PROPERTIES FAIL_REGULAR_EXPRESSION "FATAL:") set_property(TEST agc_driver_draw_cache_reuse agc_driver_draw_cache_reuse_off APPEND PROPERTY ENVIRONMENT "APS5_VERIFY_DRAW_RECIPE=1" "APS5_VERIFY_REGISTER_KEYS=1") add_test(NAME agc_driver_draw_data_hit_user_words_verify COMMAND agc_driver_draw_data_hit_user_words_tests) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recapture_on_change_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recapture_on_change_tests.cmake index 2008fb08fbf2..fdef847968d0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recapture_on_change_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recapture_on_change_tests.cmake @@ -1,6 +1,8 @@ if(BUILD_TESTING) add_test(NAME agc_driver_draw_recapture_on_change_inline COMMAND agc_driver_draw_recapture_on_change_tests) set_tests_properties(agc_driver_draw_recapture_on_change_inline PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_PIPELINED_DRAWS=0" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + agc_add_env_test(agc_driver_draw_recapture_on_change_gpu_heap agc_driver_draw_recapture_on_change_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1) add_test(NAME agc_driver_dispatch_recapture_on_change_items COMMAND agc_driver_dispatch_recapture_on_change_tests) set_tests_properties(agc_driver_dispatch_recapture_on_change_items PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_PIPELINED_DRAWS=1;APS5_PIPELINE_DISPATCH=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") if(WIN32) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake index 41c40714b403..2c43f3600527 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake @@ -5,6 +5,12 @@ if(BUILD_TESTING AND TARGET agc_driver_heap_draw_sample_tests) ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5) agc_add_env_test(agc_driver_heap_draw_sample_full_heap_pipelined agc_driver_heap_draw_sample_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) + agc_add_env_test(agc_driver_heap_draw_sample_heap_excluded agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_GPU_HEAP_EXCLUDE=sampled) + agc_add_env_test(agc_driver_heap_draw_sample_no_timeline agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_NO_TIMELINE=1) + set_tests_properties(agc_driver_heap_draw_sample_no_timeline PROPERTIES PASS_REGULAR_EXPRESSION "APS5_NO_TIMELINE cannot be used with APS5_GPU_HEAP" + SKIP_REGULAR_EXPRESSION "skipped, the device lacks VK_EXT_descriptor_heap") agc_add_env_test(agc_driver_heap_draw_sample_nogpl agc_driver_heap_draw_sample_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_NO_GPL=1) agc_add_env_test(agc_driver_heap_draw_sample_nogpl_heap agc_driver_heap_draw_sample_tests diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake index 555c98a6bed7..dd23c75b8c2c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake @@ -24,7 +24,7 @@ if(BUILD_TESTING) ARGS ring-large-spans ENV ANYPS5_NO_SHADER_CACHE=1) agc_add_env_test(agc_driver_heap_slots_ring_busy_chunks agc_driver_heap_slots_tests ARGS ring-busy-chunks ENV ANYPS5_NO_SHADER_CACHE=1 TIMEOUT 60) - foreach(agcHeapSlotsMode IN ITEMS comes-back storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release idle-slots-evicted pressure-submit samplers-evicted no-timeline-refuses) + foreach(agcHeapSlotsMode IN ITEMS comes-back storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release idle-slots-evicted pressure-submit samplers-evicted no-timeline-fails) string(REPLACE "-" "_" agcHeapSlotsName "${agcHeapSlotsMode}") agc_add_env_test(agc_driver_heap_slots_${agcHeapSlotsName} agc_driver_heap_slots_tests ARGS ${agcHeapSlotsMode} ENV ANYPS5_NO_SHADER_CACHE=1) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_submit_progress_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_submit_progress_tests.cmake index eb7c0a6323a7..5553b418b7eb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_submit_progress_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_submit_progress_tests.cmake @@ -8,10 +8,10 @@ if(BUILD_TESTING) endif() add_test(NAME agc_submit_progress_no_timeline COMMAND agc_driver_submit_progress_tests --fallback-only) set_tests_properties(agc_submit_progress_no_timeline PROPERTIES - ENVIRONMENT "APS5_SUBMIT_PROGRESS=1;APS5_NO_TIMELINE=1" + ENVIRONMENT "APS5_SUBMIT_PROGRESS=1;APS5_NO_TIMELINE=1" ENVIRONMENT_MODIFICATION "APS5_GPU_HEAP=unset:" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") if(WIN32) set_tests_properties(agc_submit_progress_no_timeline PROPERTIES ENVIRONMENT_MODIFICATION - "PATH=path_list_prepend:$;PATH=path_list_prepend:$") + "APS5_GPU_HEAP=unset:;PATH=path_list_prepend:$;PATH=path_list_prepend:$") endif() endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake index 8b41089c2380..7fefd4c6499e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake @@ -59,8 +59,6 @@ if(BUILD_TESTING) ARGS --store-table ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 TIMEOUT 60) add_test(NAME agc_driver_image_table_vouch_queued_draws COMMAND agc_driver_image_table_cache_bounds_tests --queued-draws) set_tests_properties(agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) - agc_add_env_test(agc_driver_image_table_cache_bounds_heap_small agc_driver_image_table_cache_bounds_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=8 TIMEOUT 60) if(WIN32) set_tests_properties(agc_shader_table_snapshot_reuse agc_shader_table_snapshot_reuse_unmasked agc_driver_image_table_vouched_lookups agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index 32418e961b17..8912ece91469 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -86,8 +87,8 @@ alignas(256) constexpr std::array TableVertexCode{ 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, }; alignas(256) std::array TableMemory{}; -alignas(256) std::array MixedVertexCode{}; -alignas(256) std::array MixedPixelCode{}; +alignas(256) std::array FreshVertexCode{}; +alignas(256) std::array FreshPixelCode{}; alignas(256) std::array MaterialMemory{}; alignas(256) std::array OtherTextureMemory{}; constexpr float BufferAlpha = 0.2f; @@ -448,56 +449,74 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { "merging into a second color target built another heap template instead of reusing the first target's"); } -void MixedDrawTakesThePerDrawPath() { - using AgcDriver::Graphics::HeapFallback; - using AgcDriver::Graphics::HeapFallbacks; - MixedVertexCode = SamplingVertexCode; - MixedPixelCode = InterpolantPixelCode; +void UnpreparedPairTakesTheHeap() { + using AgcDriver::Graphics::HeapExcluded; + using AgcDriver::Graphics::HeapExcludedCount; + using AgcDriver::Graphics::HeapStageReason; + using AgcDriver::Graphics::HeapStageReasons; + FreshVertexCode = SamplingVertexCode; + FreshPixelCode = InterpolantPixelCode; for (std::size_t offset = 0; offset < TextureMemory.size(); offset += Texel.size()) std::memcpy(TextureMemory.data() + offset, Texel.data(), Texel.size()); - Registered(PixelHeader, MixedPixelCode.data(), sizeof(MixedPixelCode), 1); - { - Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); - auto commands = Draw(MixedPixelCode.data(), Mode::Texture); - Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; - Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw putting the fragment stage on the heap failed"); - AgcDriverWaitIdle_nid_postfix(); - Registered(VertexHeader, MixedVertexCode.data(), sizeof(MixedVertexCode), 2); + Registered(VertexHeader, FreshVertexCode.data(), sizeof(FreshVertexCode), 2); + Registered(PixelHeader, FreshPixelCode.data(), sizeof(FreshPixelCode), 1); + const auto heapBefore = HeapStageReasons(HeapStageReason::Heap); + const auto takenBefore = AgcDriver::DriverDetail::HeapStagesTaken(); + const auto offHeapBefore = HeapStageReasons(HeapStageReason::Disabled) + HeapStageReasons(HeapStageReason::Excluded); + const auto excludedBefore = HeapExcludedCount(HeapExcluded::Draw); + ColorMemory.fill(Kept); + auto commands = Draw(FreshPixelCode.data(), Mode::Vertex, FreshVertexCode.data()); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the unprepared pair's draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); + std::size_t drawn = 0; + for (std::size_t offset = 0; offset < ColorMemory.size(); offset += 4) { + if (std::all_of(ColorMemory.begin() + static_cast(offset), + ColorMemory.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) + continue; + for (std::size_t channel = 0; channel < 4; ++channel) + Require(static_cast(ColorMemory[offset + channel]) == Texel[channel], + "the unprepared pair: pixel " + std::to_string(offset / 4) + " channel " + std::to_string(channel) + " is " + + std::to_string(static_cast(ColorMemory[offset + channel])) + ", expected " + std::to_string(Texel[channel])); + ++drawn; } - AgcDriver::DriverDetail::SetHeapStageUnmapped(ShaderRecompiler::ShaderStage::Fragment); - for (const char* draw : {"first", "repeated"}) { - const auto takenBefore = AgcDriver::DriverDetail::HeapStagesTaken(); - const auto retriesBefore = HeapFallbacks(HeapFallback::DrawMixedRetry); - const auto refusedBefore = HeapFallbacks(HeapFallback::DrawRefusedPair); - ColorMemory.fill(Kept); - auto commands = Draw(MixedPixelCode.data(), Mode::Vertex, MixedVertexCode.data()); - Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; - Require(sceAgcDriverSubmitDcb(&packet) == 0, std::string("the ") + draw + " mixed draw submission failed"); - AgcDriverWaitIdle_nid_postfix(); - std::size_t drawn = 0; - for (std::size_t offset = 0; offset < ColorMemory.size(); offset += 4) { - if (std::all_of(ColorMemory.begin() + static_cast(offset), - ColorMemory.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) - continue; - for (std::size_t channel = 0; channel < 4; ++channel) - Require(static_cast(ColorMemory[offset + channel]) == Texel[channel], - std::string("the ") + draw + " mixed draw: pixel " + std::to_string(offset / 4) + " channel " + - std::to_string(channel) + " is " + std::to_string(static_cast(ColorMemory[offset + channel])) + - ", expected " + std::to_string(Texel[channel])); - ++drawn; - } - Require(drawn != 0, std::string("the ") + draw + " mixed draw covered no pixel"); - const bool first = std::strcmp(draw, "first") == 0; - if (first) - Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, "the heap did not take the vertex stage of the mixed draw"); - Require(HeapFallbacks(HeapFallback::DrawMixedRetry) - retriesBefore == (first ? 1u : 0u), - std::string("the ") + draw + " mixed draw retried on the per-draw path " + - std::to_string(HeapFallbacks(HeapFallback::DrawMixedRetry) - retriesBefore) + " times, expected " + - (first ? "once" : "never")); - Require(HeapFallbacks(HeapFallback::DrawRefusedPair) == refusedBefore, - std::string("the ") + draw + " mixed draw stayed mixed after its per-draw retry"); + Require(drawn != 0, "the unprepared pair's draw covered no pixel"); + Require(HeapStageReasons(HeapStageReason::Heap) - heapBefore >= 2u && AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, + "the first draw of an unprepared vertex and pixel pair did not put both stages on the heap"); + Require(HeapStageReasons(HeapStageReason::Disabled) + HeapStageReasons(HeapStageReason::Excluded) == offHeapBefore, + "a stage of the unprepared pair's first draw was decided off the heap"); + Require(HeapExcludedCount(HeapExcluded::Draw) == excludedBefore, "the unprepared pair's draw took the per-draw path"); +} + +void UnmappableStageFails() { + constexpr std::uint32_t Decorate = 4u << 16u | 71u; + ShaderRecompiler::RecompileResult result; + result.variantId = ~std::uint64_t{0} - 2u; + result.spirv = {0x07230203u, 0x00010000u, 0u, 2u, 0u, Decorate, 1u, 34u, 0u, Decorate, 1u, 33u, 4000u}; + try { + AgcDriver::DriverDetail::RequireHeapStageMappable(result); + } catch (const std::runtime_error& error) { + Require(std::string(error.what()).find("descriptor set 0 binding 4000") != std::string::npos, + std::string("an unmappable heap stage failed for another reason: ") + error.what()); + Require(!AgcDriver::DriverDetail::HeapStageFits(result), "an unmappable heap stage was reported as fitting"); + return; + } + Require(false, "a stage whose module keeps a binding the heap does not map was mapped onto the heap"); +} + +void OversizedStageFails() { + const auto capacity = AgcDriver::Graphics::BindlessHeap::ImageSlotCapacity(); + ShaderRecompiler::RecompileResult result; + result.variantId = ~std::uint64_t{0} - 1u; + result.bindings.push_back({ShaderRecompiler::DescriptorKind::SampledImage, ShaderRecompiler::DescriptorRole::GuestImages, 1u, 0u, capacity + 1u}); + try { + AgcDriver::DriverDetail::RequireHeapStageMappable(result); + } catch (const std::runtime_error& error) { + Require(std::string(error.what()).find("image slots") != std::string::npos, std::string("an oversized heap stage failed for another reason: ") + error.what()); + Require(!AgcDriver::DriverDetail::HeapStageFits(result), "an oversized heap stage was reported as fitting"); + return; } - AgcDriver::DriverDetail::SetHeapStageUnmapped(std::nullopt); + Require(false, "a stage needing more image slots than the heap holds was mapped onto the heap"); } } @@ -509,8 +528,10 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; } - const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; - if (heap && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; + const bool excluded = std::getenv("APS5_GPU_HEAP_EXCLUDE") != nullptr; + const bool heapMode = std::getenv("APS5_GPU_HEAP") != nullptr; + const bool heap = heapMode && !excluded; + if (heapMode && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; { GuestAllocations::Mutation mutation; mutation.Add(StorageMemory.data(), StorageMemory.size(), true, true, true); @@ -520,10 +541,17 @@ int main() { Mode::MovedBuffer, Mode::MovedTexture, Mode::PixelLds, Mode::ConstantSampler, Mode::BorderSampler, Mode::WrapSampler, Mode::MergedBlend, Mode::MergedBlendOther, Mode::Texture}) DrawSamplesTheTexture(heap, mode); const bool capped = heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr; - if (heap && !capped) MixedDrawTakesThePerDrawPath(); + if (heap && !capped) UnpreparedPairTakesTheHeap(); + if (heap) { + OversizedStageFails(); + UnmappableStageFails(); + } + if (excluded) + Require(AgcDriver::Graphics::HeapExcludedCount(AgcDriver::Graphics::HeapExcluded::Draw) != 0u, + "no draw took the per-draw path for its excluded heap class"); if (capped) - Require(AgcDriver::Graphics::HeapSlotEvictions() != 0u && !AgcDriver::DriverDetail::HeapRefused(), - "the capped heap refused draws instead of evicting image slots"); + Require(AgcDriver::Graphics::HeapSlotEvictions() != 0u, + "the capped heap evicted no image slot"); AgcDriverShutdown_nid_postfix(); if (heap && !capped) Require(AgcDriver::Graphics::EmptyResourceSets() != 0, "no heap draw bound without a per-draw resource set"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp index 15b6419520ca..55c8abadbc70 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp @@ -260,12 +260,10 @@ void TablesChangingPerDispatch(const GuestBlock& block) { Dispatch(block, 0); most = std::max(most, cache.TableElements()); } - const bool tableFitsHeap = AgcDriver::Graphics::BindlessHeap::ImageSlotCapacity() >= Elements + Spare; - if (AgcDriver::Graphics::DescriptorHeapEnabled() && tableFitsHeap) { + if (AgcDriver::Graphics::DescriptorHeapEnabled()) { Require(AgcDriver::Graphics::HeapComputeStages() > heapStages, "image table cache bounds: the dispatches did not take the descriptor heap"); return; } - if (AgcDriver::Graphics::DescriptorHeapEnabled()) Require(AgcDriver::Graphics::HeapComputeStages() == heapStages, "image table cache bounds: a table stage with more images than the heap's slots took the heap"); Require(most >= Elements, "image table cache bounds: no dispatch kept its table in the resource cache"); Require(most <= AgcDriver::Graphics::ResourceCache::TableElementBudget(), "image table cache bounds: tables that changed every dispatch kept " + std::to_string(most) + " table elements in the resource cache, over its budget of " + std::to_string(AgcDriver::Graphics::ResourceCache::TableElementBudget())); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp index a7785a3cd6be..d76c22181b04 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp @@ -557,7 +557,7 @@ void LazyResolution(const Layout& layout, const std::filesystem::path& reference Require(unmatched.firstUses - start.firstUses == Drawn && unmatched.own - start.own == Drawn && unmatched.found == start.found, "lazy resolved ABI: draws whose state differs from the resolved ABI did not count as preparing their own artifact (before: " + Uses(start) + "; after: " + Uses(unmatched) + ")"); Require(unmatched.entries > start.entries && unmatched.unmatchedEntries - start.unmatchedEntries == unmatched.entries - start.entries, "lazy resolved ABI: entries prepared for an ABI no draw used do not count as unmatched (before: " + Uses(start) + "; after: " + Uses(unmatched) + ")"); Require(matched.firstUses == unmatched.firstUses + 1 && matched.found == unmatched.found + 1 && matched.own == unmatched.own, "lazy resolved ABI: a draw whose state matches the resolved ABI did not count as finding its artifact (before: " + Uses(unmatched) + "; after: " + Uses(matched) + ")"); - const std::uint64_t usedVariants = AgcDriver::DriverDetail::HeapFragmentsEnabled() ? 2u : 1u; + const std::uint64_t usedVariants = AgcDriver::Graphics::DescriptorHeapEnabled() ? 2u : 1u; Require(matched.entries > unmatched.entries && matched.unmatchedEntries == unmatched.unmatchedEntries + (matched.entries - unmatched.entries) - usedVariants, "lazy resolved ABI: the entry a matching draw used still counts as unmatched (before: " + Uses(unmatched) + "; after: " + Uses(matched) + ")"); for (const auto index : {Matching, Twice, Replaced}) Require(eager.at("drawn " + std::to_string(index)) == eager.at("resolved " + std::to_string(index)), "lazy resolved ABI: shader " + std::to_string(index) + ", drawn with its resolved ABI's state, did not find the ABI's entries with eager preparation"); for (std::uint32_t index = 0; index < Drawn; ++index) Require(Count(eager.at("drawn " + std::to_string(index))) == Count(eager.at("resolved " + std::to_string(index))) + usedVariants, "lazy resolved ABI: a draw whose state differs from its resolved ABI did not prepare its own entry with eager preparation"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp index 627a934b4c77..761ff331f051 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp @@ -576,7 +576,7 @@ void CheckMergedHull(AgcDriver::VulkanDevice& device) { if (stage.heapVariant == heapVariant) set.push_back(&stage); } if (heapVariant && set.empty()) { - Require(!HeapFragmentsEnabled(), "the heap prepared no heap variants of the merged hull draw"); + Require(!AgcDriver::Graphics::DescriptorHeapEnabled(), "the heap prepared no heap variants of the merged hull draw"); continue; } const auto handleOf = [&](ShaderRecompiler::ShaderStage wanted) { diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index d4d719163fc2..2bac998556cd 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -250,7 +250,6 @@ function(add_shader_recompiler target runtimeTarget) FirstAtomicStorageImageBinding BuildBarycentricGeometryShader BuildBarycentricTessellationShaders - HeapFragmentEligible CompleteHeapDataWords HeapTemplateCounts BuildPreparedShaderKey diff --git a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp index 9d1af4624486..13bf947f1f99 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp @@ -77,7 +77,6 @@ class PreparedShaderInvocation { std::shared_ptr handle; }; [[nodiscard]] std::span GetPreparedCode(const SourceHandle& handle); -[[nodiscard]] bool HeapFragmentEligible(const IrResourcePlan& plan); void CompleteHeapDataWords(const RecompileResult& shared, HeapStageWords& words); [[nodiscard]] std::shared_ptr PrepareShader(const RecompileRequest& request); [[nodiscard]] std::shared_ptr PrepareShader(const RecompileRequest& request, ShaderPreparationContext* preparation); diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index b816ad259b38..6ea5047502eb 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -2553,14 +2553,6 @@ void CompleteHeapDataWords(const RecompileResult& shared, HeapStageWords& words) } } -bool HeapFragmentEligible(const IrResourcePlan& plan) { - if (plan.stage == IrShaderStage::Unknown || plan.stage == IrShaderStage::Fetch) return false; - for (const auto& image : plan.info.images) { - if (image.source >= plan.descriptorSources.size()) return false; - } - return true; -} - const CompiledShaderArtifact& GetPreparedArtifact(const SourceHandle& handle) { if (handle.artifact == nullptr) throw std::runtime_error("ShaderRecompiler: prepared artifact is missing"); return handle.artifact->artifact; diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index ad29b69d83d6..01d8c1fa9ce9 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -195,7 +195,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_GPU_CHECKPOINTS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | attaches device diagnostic checkpoints through VK_NV_device_diagnostic_checkpoints, or buffer markers through VK_AMD_buffer_marker on a device without it | | `APS5_GPU_COPY_MAX_KIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 1024 | size cap in KiB on a descriptor sub-range copied through the GPU path, larger ones staying on the CPU | | `APS5_GPU_HEAP` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | | binds the sampled and storage images and samplers of eligible stages through the device's VK_EXT_descriptor_heap heaps; without the extension it does nothing | -| `APS5_GPU_HEAP_EXCLUDE` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | | comma list of stage classes that take the per-draw path while the GPU heap stays on: stage names (compute, vertex, hull, domain, geometry, pixel, local, mesh), or tables, storage or sampled for stages with image tables, storage images or sampled images | +| `APS5_GPU_HEAP_EXCLUDE` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | | debug aid: comma list of stage classes that take the per-draw path while the GPU heap stays on: stage names (compute, vertex, hull, domain, geometry, pixel, local, mesh), or tables, storage or sampled for stages whose resource plan has image tables, storage images or sampled images; a draw with an excluded stage takes the per-draw path for all its stages, decided before any stage is built | | `APS5_GPU_NO_WRITEBACK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | skips writing GPU results back into guest memory | | `APS5_GPU_WAIT_TIMEOUT_MS` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp` | 1000 | milliseconds a GPU wait may run before a warning is printed | | `APS5_GROUP_CAPTURE_ALL_QUEUES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp` | | resolves group-ahead capture on queue 0 as well | @@ -396,7 +396,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_TEMPLATE_DATA_REFRESH` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | keys the ShaderData and FlattenedSrt words into compute keys instead of refreshing a template's data buffers | | `APS5_NO_TEXTURE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | builds every texture and storage-image object fresh instead of caching it | | `APS5_NO_TEXTURE_HASH` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | finds texture-cache entries by scanning the list instead of the hash index | -| `APS5_NO_TIMELINE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | leaves timeline semaphores off, so drains wait under the mutex | +| `APS5_NO_TIMELINE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | leaves timeline semaphores off, so drains wait under the mutex; device creation fails with `APS5_GPU_HEAP`, whose slot eviction needs them | | `APS5_NO_UNIT_SHADOW` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp` | | makes every unit shadow primitive inert | | `APS5_NO_UNLOCKED_DEVICE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp` | | loads the device and runs a dispatch under the GPU mutex instead of using an unlocked device | | `APS5_NO_UNLOCKED_DRAIN` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp` | | keeps the GPU mutex held while draining a packet instead of the unlocked drain | diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 93d848a7ea42..ea0811da4286 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -407,5 +407,5 @@ ### Opt-in draw paths - [Draw finisher](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp) (`APS5_DRAW_PIPELINE`) - opt-in. The Linux main-image page table it adds matches what Windows already does by default. -- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap`. A stage whose module keeps a set 0 binding the heap does not map (storage images of registration modules) takes the per-draw path, and so does every other stage of its draw. A stage that needs more image slots than the heap holds also takes the per-draw path; with `APS5_HEAP_SLOT_CAP` far below the default, stages that each fit can still exhaust the heap between their compile and their bind, because the nearly-full margin scales with the cap. Heap stages read guest memory in place and report no BDA fault per use, so the address draw reuse test skips its fault-per-use case with `--heap-stages`. A reused address-based draw whose moved read-only buffer cannot be viewed in place with the alignment offset its build baked into the shader data is built again. +- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap` and timeline semaphores. Heap mode has no per-draw path: every stage of every draw and dispatch takes the heap, and a stage that needs more image slots than the heap holds, or whose module keeps a binding the heap does not map, fails instead (only the `APS5_GPU_HEAP_EXCLUDE` debug aid sends stages per-draw); with `APS5_HEAP_SLOT_CAP` far below the default, stages that each fit can still exhaust the heap between their compile and their bind, because the nearly-full margin scales with the cap. Heap stages read guest memory in place and report no BDA fault per use, so the address draw reuse test skips its fault-per-use case with `--heap-stages`. A reused address-based draw whose moved read-only buffer cannot be viewed in place with the alignment offset its build baked into the shader data is built again. - [Multi-submit count overflow and buffer validation](../../../core/libs/prx/libSceAgcDriver/Submit/src/Dcb.cpp) (libSceAgcDriver) - whether the console driver imposes an architectural submission packet limit or allows null buffer pointers with non-zero sizes in multi-submit arrays is unmeasured; AgcDriver::SubmitMany validates count against 32-bit pointer array bounds overflow and rejects null addresses for non-empty command buffers with a runtime exception. From c008d51d1ba542f42a6c80d6f1eebbbc7f38a85c Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 6 Nov 2026 23:38:11 +0530 Subject: [PATCH 131/269] perf(agc): cut the per-draw cost of GPU heap mode Offline draw bench, 4000 draws, median us per draw: heap off 4.7-4.8 -> 4.4-4.5, heap on 5.4-5.5 -> 4.7-4.8. - Draws whose read-only buffers moved from their template's buffers now get draw recipes. The recipe redoes the moved-buffer check at each hit, so recipe hits in the bench go from 56% to nearly 100%. - A recipe hit re-touches its resource cache entry only after capacity/8 cache operations, instead of hashing the whole content key every draw. The first hit in each shrink window always touches, so the shrink statistics still see every live key. - A heap stage with no slots, data, tables or buffer ranges skips its per-draw rewrite while its heap template stays the same (bypassed by APS5_VERIFY_GPU_HEAP). - BindlessHeap::Existing and BindDescriptorHeaps use thread-local caches checked against an epoch, so draws no longer take the heap map and bound-command-buffer locks. - Heap data words are built in place, and the draw-key memo is kept only for long-lived shared words. - A pushed flattened SRT is read through the SRT address push item and bounds-checked against its dword count (runtime ABI 16). - The draw key memo of heap words is owned by the heap template id, not the program's address. - Add agc_driver_draw_recipe_moved_buffer, agc_driver_recipe_template_aging and the offline heap draw bench (agc_driver_heap_draw_bench). --- .../include/Driver/Draw/DrawCache.hpp | 2 +- .../Execution/include/Recipe.hpp | 1 + .../Execution/include/VulkanDevice.hpp | 2 + .../Execution/src/Driver/Draw/Draw.cpp | 45 ++- .../src/Driver/Draw/DrawRelocate.cpp | 21 +- .../Execution/src/VulkanDevice.cpp | 23 +- .../Graphics/include/BindlessHeap.hpp | 11 +- .../libSceAgcDriver/Graphics/include/Draw.hpp | 2 +- .../Graphics/include/ShaderResources.hpp | 18 +- .../Graphics/src/BindlessHeap.cpp | 152 +++++--- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 39 +- .../Graphics/src/ShaderResources.cpp | 142 +++++-- .../agc_driver_dispatch_overlap_tests.cmake | 4 + ...c_driver_draw_cache_relocation_tests.cmake | 4 + ...river_draw_recipe_moved_buffer_tests.cmake | 3 + .../tests/execution/DrawCacheRelocation.cpp | 8 +- .../tests/execution/DrawRecipeMovedBuffer.cpp | 369 ++++++++++++++++++ .../execution/DrawUnsupportedBufferType.cpp | 2 +- .../tests/execution/HeapDrawBench.cpp | 365 +++++++++++++++++ .../tests/execution/RecipeTemplateAging.cpp | 159 ++++++++ core/shader/recompiler/Recompiler.cpp | 10 +- core/shader/recompiler/Recompiler.hpp | 22 +- core/shader/recompiler/RuntimeAbi.hpp | 2 +- .../SpirvBackend/SpirvEmitterState.hpp | 1 + .../src/SpirvMemory/SpirvBufferAccess.cpp | 11 +- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 5 +- 26 files changed, 1294 insertions(+), 129 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/RecipeTemplateAging.cpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp index 95d465faf642..7a8afa9b1544 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp @@ -168,7 +168,7 @@ struct DrawRelocationTrial { }; struct DrawRelocationCounters { - std::uint64_t lookups = 0, donors = 0, refused = 0, hits = 0, evicted = 0; + std::uint64_t lookups = 0, donors = 0, refused = 0, hits = 0, evicted = 0, admitted = 0; }; bool DecodeProgramsCurrent(const DrawDecode& decode, const ShaderRegistry& registry); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Recipe.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Recipe.hpp index 3ab0d7e78df6..31fd44bddf69 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Recipe.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Recipe.hpp @@ -85,6 +85,7 @@ struct DrawRecipe { std::uint32_t fragmentOutputs = 0; VkPipelineStageFlags shaderStages = 0; bool hasDepth = false; + bool movedBuffers = false; }; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp index 7b189742b0a3..de7649c5d483 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp @@ -354,6 +354,8 @@ class VulkanDevice { static void NoteRecipe(RecipeEvent event, RecipeKind kind); enum class DrawRecipePrecheck : std::size_t { NoRecipe, Device }; static void NoteDrawRecipeMiss(DrawRecipePrecheck miss); + static std::uint64_t DrawRecipeHits(); + static std::uint64_t DispatchRecipeTemplatesGone(); using DrawTraceContext = Graphics::DrawTraceContext; // `recipe`, when given, receives the DrawRecipe a recorded, cacheable, reusable, direct draw // built for its draw-cache entry (design_cpu_final M8); null otherwise. diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 3ba4bb97c8f0..b4a8c06bc0ed 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -42,6 +42,26 @@ namespace AgcDriver::DriverDetail { namespace { +std::shared_ptr RecycledRingWords() { + constexpr std::size_t PoolSize = 1024, Probes = 16; + thread_local std::vector> pool; + thread_local std::size_t cursor = 0; + for (std::size_t probe = 0; probe < Probes && probe < pool.size(); ++probe) { + auto& candidate = pool[cursor]; + cursor = cursor + 1 == pool.size() ? 0 : cursor + 1; + if (candidate.use_count() != 1) continue; + std::atomic_thread_fence(std::memory_order_acquire); + candidate->userData.clear(); + candidate->drawKeyMemo.words.store(nullptr, std::memory_order_relaxed); + candidate->memoizeKey = false; + return candidate; + } + auto words = std::make_shared(); + words->memoizeKey = false; + if (pool.size() < PoolSize) pool.push_back(words); + return words; +} + bool TraceShaderCorrelation() { static const bool enabled = std::getenv("APS5_TRACE_SHADER_CORRELATION") != nullptr; return enabled && AgcDriver::CaptureTrace::Enabled(); @@ -676,11 +696,17 @@ DrawVerdict Driver::draw(QueueState& queue, std::span packe if (stageData[i].compiled != nullptr) stageData[i].compiled = patchDataWords(*matched[i], stageData[i].words); } const auto relocatedDecode = decode; + bool admitRelocated = false; if (!userPatches.empty()) { std::lock_guard cacheLock(drawCacheMutex); if (drawHit || verifyHit) { ++drawRelocationCounters.hits; ++drawRelocationTrials[drawIdentity].hits; + if (drawHit && drawKey != 0 && !drawCache.contains(drawKey)) { + if (!drawKeySightings) drawKeySightings.emplace(drawCacheEntries() * DrawKeySightings::Ways); + admitRelocated = drawKeySightings->SeenBefore(drawKey); + if (admitRelocated) ++drawRelocationCounters.admitted; + } if (const auto alias = drawAliases.find(drawAlias); alias != drawAliases.end()) { const auto donor = drawCache.find(alias->second); if (donor != drawCache.end() && drawCacheHits - donor->second->touched > drawCacheEntries() / 8) { @@ -697,6 +723,12 @@ DrawVerdict Driver::draw(QueueState& queue, std::span packe for (const auto& patch : userPatches) current->programs[patch.program].userData[patch.index] = patch.value; decode = std::move(current); } + if (admitRelocated && std::all_of(matched.begin(), matched.end(), [](const std::shared_ptr& variant) { return variant != nullptr; })) { + auto current = std::make_shared(*decode); + for (const auto& patch : userPatches) current->programs[patch.program].userData[patch.index] = patch.value; + std::vector> fresh(matched.begin(), matched.end()); + insertDrawEntry(drawKey, fresh, std::move(current), 0, false); + } tail.patchedStages = std::any_of(stageData.begin(), stageData.end(), [](const StageDataHit& hit) { return hit.compiled != nullptr; }); tail.relocatedDecode = relocatedDecode; std::uint64_t stageDataVerified = 0; @@ -892,7 +924,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { } }; const auto buildRingWords = [&](std::size_t i, const DispatchVariant& variant) { - auto words = std::make_shared(); + auto words = RecycledRingWords(); const auto& user = programs[i].userData; for (const auto index : variant.compiled->heapUserWords) { require(index < user.size(), "a ring vertex template reads a user word the draw does not have"); @@ -900,6 +932,8 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { } const auto& ringTemplate = *variant.ringTemplate; words->vertexAttributes = ringTemplate.vertexAttributes; + words->flattenedSrt.clear(); + words->bindings.clear(); if (!ringTemplate.flattenedSrt.empty()) { words->flattenedSrt = ringTemplate.flattenedSrt; if (&variant == matched[i].get() && stageData[i].compiled != nullptr) { @@ -951,8 +985,13 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { std::vector> runs; std::vector words; freshRuns(i, runs, words); - const auto& fresh = *stageCaptures[i].compiled; - const auto& patched = *hit.compiled; + std::shared_ptr effective = hit.compiled, expected = stageCaptures[i].compiled; + if (kept.ringTemplate != nullptr) { + effective = PatchedHeapResult(*hit.compiled, *buildRingWords(i, kept)); + if (stageCaptures[i].heapWords != nullptr) expected = PatchedHeapResult(*stageCaptures[i].compiled, *stageCaptures[i].heapWords); + } + const auto& fresh = *expected; + const auto& patched = *effective; const bool sameBindings = fresh.bindings.size() == patched.bindings.size() && std::equal(fresh.bindings.begin(), fresh.bindings.end(), patched.bindings.begin(), [](const auto& a, const auto& b) { return a.kind == b.kind && a.role == b.role && a.binding == b.binding && a.count == b.count && a.guestDescriptor == b.guestDescriptor; }); const char* what = runs != kept.runs ? "runs" : words != hit.words ? "words" : fresh.variantId != patched.variantId ? "variant" : fresh.pushConstants != patched.pushConstants ? "push constants" : !sameBindings ? "bindings" : nullptr; ++stageDataVerified; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp index 6c2e100c4f99..6ae1c84e17cb 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp @@ -359,6 +359,25 @@ void Driver::relocateDrawEntry(const QueueState& queue, std::uint64_t alias, std void Driver::applyShaderDataPatches(DispatchVariant& variant) { if (variant.shaderDataPatches.empty() && variant.descriptorPatches.empty()) return; + const bool templateOnly = variant.ringTemplate != nullptr && variant.shaderDataPatches.empty() && + std::all_of(variant.descriptorPatches.begin(), variant.descriptorPatches.end(), [&](const std::array& patch) { + if (patch[0] >= variant.compiled->bindings.size()) return true; + const auto role = variant.compiled->bindings[patch[0]].role; + return role != ShaderRecompiler::DescriptorRole::FlattenedSrt && role != ShaderRecompiler::DescriptorRole::ShaderData; + }); + if (templateOnly) { + auto ringTemplate = std::make_shared(*variant.ringTemplate); + if (ringTemplate->bindings.empty()) ringTemplate->bindings.resize(variant.compiled->bindings.size()); + for (const auto& [binding, word, value] : variant.descriptorPatches) { + if (binding >= ringTemplate->bindings.size()) continue; + auto& words = ringTemplate->bindings[binding]; + if (words.empty()) words = variant.compiled->bindings[binding].guestDescriptor; + if (word < words.size()) words[word] = value; + } + variant.ringTemplate = std::move(ringTemplate); + variant.descriptorPatches.clear(); + return; + } auto rebased = std::make_shared(*variant.compiled); for (const auto& [slot, value] : variant.shaderDataPatches) { const auto at = static_cast(slot) * sizeof(std::uint32_t); @@ -388,7 +407,7 @@ void Driver::applyShaderDataPatches(DispatchVariant& variant) { void Driver::reportDrawRelocation() { auto& counters = drawRelocationCounters; - AgcDriver::ProfilePrint_nid_no_patch("[draw-relocate] %llu alias lookups: %llu donors with moved user words, %llu refusals, %llu hits through a relocated entry; %zu shader sets learned, %zu aliases held (%llu dropped at the limit)\n", static_cast(counters.lookups), static_cast(counters.donors), static_cast(counters.refused), static_cast(counters.hits), drawRelocations.size(), drawAliases.size(), static_cast(counters.evicted)); + AgcDriver::ProfilePrint_nid_no_patch("[draw-relocate] %llu alias lookups: %llu donors with moved user words, %llu refusals, %llu hits through a relocated entry (%llu cached under their own key); %zu shader sets learned, %zu aliases held (%llu dropped at the limit)\n", static_cast(counters.lookups), static_cast(counters.donors), static_cast(counters.refused), static_cast(counters.hits), static_cast(counters.admitted), drawRelocations.size(), drawAliases.size(), static_cast(counters.evicted)); counters = {}; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index c573b3a627cc..51d9e2871b4b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -5229,11 +5229,11 @@ DispatchCounters& Dispatches() { // The [recipe] line (APS5_PROFILE_DRAW, every 10 s), dispatch and indirect rows apart. The // pre-check runs without the mutex, so the counters are atomic. -enum RecipeMiss : std::size_t { MissNoRecipe, MissDevice, MissTemplateGone, MissObjectsGone, MissNotRecordable, RecipeMissCount }; -constexpr std::array RecipeMissNames{"no recipe", "device", "template gone", "objects gone", "not recordable"}; +enum RecipeMiss : std::size_t { MissNoRecipe, MissDevice, MissTemplateGone, MissObjectsGone, MissNotRecordable, MissMoved, RecipeMissCount }; +constexpr std::array RecipeMissNames{"no recipe", "device", "template gone", "objects gone", "not recordable", "moved buffers refused"}; // The draw rows name the miss reasons of DrawWithRecipe (a target or a pipeline gone is the // objects-gone slot). -constexpr std::array DrawRecipeMissNames{"no recipe", "device", "template gone", "targets gone", "not recordable"}; +constexpr std::array DrawRecipeMissNames{"no recipe", "device", "template gone", "targets gone", "not recordable", "moved buffers refused"}; constexpr std::array(Graphics::ShaderResources::ProofPath::Count)> ProofPathNames{"fast", "T1 refreshed", "full"}; constexpr std::array(Graphics::ShaderResources::ProofFailure::Count)> ProofFailureNames{"none", "imports", "evicted", "pending", "changed", "keys", "other"}; @@ -5533,6 +5533,14 @@ void VulkanDevice::NoteDrawRecipeMiss(DrawRecipePrecheck miss) { counters.precheckMisses[miss == DrawRecipePrecheck::NoRecipe ? MissNoRecipe : MissDevice].fetch_add(1, std::memory_order_relaxed); } +std::uint64_t VulkanDevice::DispatchRecipeTemplatesGone() { + return Recipes().kinds[static_cast(RecipeKind::Dispatch)].precheckMisses[MissTemplateGone].load(std::memory_order_relaxed); +} + +std::uint64_t VulkanDevice::DrawRecipeHits() { + return Recipes().kinds[static_cast(RecipeKind::Draw)].hits.load(std::memory_order_relaxed); +} + RecipeOutcome VulkanDevice::DrawFromRecipe(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, const std::shared_ptr& recipe, const DrawTraceContext* trace) { PerformanceTimer timing("Vulkan.DrawFromRecipe"); static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; @@ -5551,6 +5559,7 @@ RecipeOutcome VulkanDevice::DrawFromRecipe(const Graphics::State& graphics, cons case Graphics::DrawRecipeMiss::TargetGone: case Graphics::DrawRecipeMiss::ObjectsGone: counters.precheckMisses[MissObjectsGone].fetch_add(1, std::memory_order_relaxed); break; case Graphics::DrawRecipeMiss::TemplateGone: counters.precheckMisses[MissTemplateGone].fetch_add(1, std::memory_order_relaxed); break; + case Graphics::DrawRecipeMiss::Moved: counters.precheckMisses[MissMoved].fetch_add(1, std::memory_order_relaxed); break; case Graphics::DrawRecipeMiss::Proof: counters.rebuilds[static_cast(outcome.proof.failure)].fetch_add(1, std::memory_order_relaxed); break; default: break; } @@ -5872,6 +5881,9 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { const bool overlapCapable = overlapQueue != 0 && Graphics::Recorder::DispatchOverlapEnabled() && arguments == 0 && argumentImport == nullptr && record.threadGroup == std::array{} && record.shader->program->workgroupMemoryDwords == 0 && state->checkpointMarker == nullptr && state->bufferMarker == nullptr && record.x <= groupLimit[0] && record.y <= groupLimit[1] && record.z <= groupLimit[2] && !resources.HasHostGpuCopies(); std::vector runAccesses; if (overlapCapable) resources.RunAccesses(runAccesses); + if (overlapCapable && record.bindings != nullptr) { + for (const auto& [begin, end] : record.bindings->movedReads) runAccesses.push_back({begin, end, 0u}); + } VkAccessFlags covered = 0; bool overlapped = false; const std::array runOwners{record.resources.get(), resources.MemoryOwner()}; @@ -6679,7 +6691,8 @@ RecipeOutcome VulkanDevice::DispatchRecipe(const ShaderRecompiler::RecompileResu } // A data-only hit's words are the shader's, not the recipe's: its hash decision is // computed from the shader, as the record below decides by words. - const bool byHash = TemplateDataRefresh() && hit->resources->DataWordsHash() != (refreshByWords ? Graphics::ShaderResources::DataWordsHash(shaders[0]) : recipe.dataWordsHash); + const bool byHash = TemplateDataRefresh() && !hit->resources->HeapStage() && + hit->resources->DataWordsHash() != (refreshByWords ? Graphics::ShaderResources::DataWordsHash(shaders[0]) : recipe.dataWordsHash); const bool byWords = TemplateDataRefresh() && hit->resources->DataWordsDiffer(shaders[0]); const char* disagreement = mapped != hit->objects ? "the pipeline objects" : byHash != byWords ? "the RefreshData decision" : nullptr; if (disagreement != nullptr) { @@ -6711,7 +6724,7 @@ RecipeOutcome VulkanDevice::DispatchRecipe(const ShaderRecompiler::RecompileResu } counters.proofPaths[static_cast(report.path)].fetch_add(1, std::memory_order_relaxed); ++d.cacheHits; - state->resourceCache.Touch(recipe.key); + state->resourceCache.TouchAging(recipe.key, hit->resources->CacheTouchedAt()); // The recipe's hash names the words it was attached with, not a data-only hit's: that hit // refreshes by the per-word compare (RefreshData keeps the template's own hash exact, so a // later exact hit of a sibling variant compares correctly against it). diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index f518f371ab42..93dc2501064e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -69,13 +69,13 @@ class BindlessHeap { std::optional PinnedSamplerSlot(const std::shared_ptr& sampler); std::uint32_t SamplerGeneration(std::uint32_t slot) const; std::uint64_t SlotSerial() const { return slotSerial.load(std::memory_order_acquire); } - bool GenerationsCurrent(std::span> slots, std::span slotGenerations, + bool GenerationsCurrent(std::span slots, std::span slotGenerations, std::span samplerSlots, std::span samplerGenerations) const; std::uint32_t AbsentSlot(std::uint32_t kind, VkImageView view); static bool NearlyFull(); static std::uint32_t ImageSlotCapacity(); std::uint32_t ImageSlots() const { return slotCap; } - std::uint32_t TouchSlots(std::span> slots, std::span samplerSlots, std::uint32_t touched) const; + std::uint32_t TouchSlots(std::span slots, std::span samplerSlots, std::uint32_t touched) const; struct DataSpan { std::uint32_t offset = 0; @@ -93,6 +93,7 @@ class BindlessHeap { DataSpan Allocate(std::size_t words, SpanMark& mark); DataSpan RingAllocate(std::size_t words, SpanMark& mark); bool Held(const SpanMark& mark); + std::optional KeepOrAllocate(std::size_t words, SpanMark& mark, bool same); std::uint32_t RingBufferDescriptors(std::span buffers, SpanMark& mark); static constexpr std::uint32_t BufferSlotBytes = 16u; @@ -166,6 +167,8 @@ class BindlessHeap { std::uint32_t poolAlignment = 256; std::size_t poolBatchBytes = 0; std::size_t takePoolBlockLocked(std::size_t bytes); + bool heldLocked(const SpanMark& mark); + DataSpan allocateLocked(std::size_t words, SpanMark& mark); bool poolBlockDoneLocked(PoolBlock& block); void trimPoolLocked(); std::uint32_t ringAlignment = 256; @@ -206,7 +209,9 @@ class BindlessHeap { std::uint32_t next = 0; std::uint32_t limit = 0; std::vector free; - std::vector generations; + std::unique_ptr[]> generations; + void Configure(std::uint32_t first, std::uint32_t slots); + void Retire(std::uint32_t slot); std::optional Take(bool& reused); void Free(std::uint32_t slot); std::size_t Unused() const; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp index 5376d833c610..505ff3890d8c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp @@ -99,7 +99,7 @@ MeshArguments ResolveMeshArguments(const Pm4::DrawArguments& record, const MeshA // storage cache, the template is gone, the pipeline is gone from the pipeline store, or the // template's proof failed (ShaderResources::ProveCurrent; the template is removed from the // resource cache and kept by the batch). -enum class DrawRecipeMiss : std::uint8_t { None, NotRecordable, TargetGone, TemplateGone, ObjectsGone, Proof, Count }; +enum class DrawRecipeMiss : std::uint8_t { None, NotRecordable, TargetGone, TemplateGone, ObjectsGone, Proof, Moved, Count }; const char* DrawRecipeMissName(DrawRecipeMiss miss); struct DrawRecipeOutcome { bool recorded = false; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index fbb2d9e67cfe..f9ff8e7beebd 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -202,10 +202,11 @@ class ShaderResources { bool SplitSets() const { return splitSets; } PipelineSetLayouts SetLayouts() const; bool HeapStage() const { return heapStage; } + std::atomic& CacheTouchedAt() const { return cacheTouchedAt; } void RefreshHeapStage(std::span shaders); void RequireGuestBuffers() const { requireGuestBuffers(); } void Bind(VkCommandBuffer commands, VkPipelineBindPoint bindPoint, VkPipelineLayout layout) const; - void BindDescriptorHeaps(VkCommandBuffer commands) const; + void BindDescriptorHeaps(VkCommandBuffer commands, bool guestBuffersChecked = false) const; struct DrawBindings { DrawBindings() = default; DrawBindings(const DrawBindings&) = delete; @@ -226,6 +227,7 @@ class ShaderResources { bool addressOffsets = false; std::array heapOffsets{}; std::vector addressOverrides; + std::vector> movedReads; ~DrawBindings(); }; void RefreshMovedAddresses(DrawBindings& rewritten) const; @@ -673,6 +675,7 @@ class ShaderResources { std::array heapOffsets{}; void writeHeapStage(const CompiledShader& shader); struct RingDescriptors { + VkDeviceAddressRangeEXT srt{}; std::vector ranges; BindlessHeap::SpanMark mark; std::uint32_t first = 0; @@ -680,6 +683,7 @@ class ShaderResources { struct HeapStageState { std::vector key; std::array, static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)> slots; + std::vector imageSlots; std::vector slotGenerations; std::vector samplerSlots; std::vector samplerGenerations; @@ -693,6 +697,7 @@ class ShaderResources { KeptSpan data, flat, map; std::vector dataInput; RingDescriptors descriptors; + std::uint64_t inertProgram = 0; }; std::array heapStages; std::uint64_t heapSpan(HeapStageState::KeptSpan& kept, std::span words); @@ -729,6 +734,8 @@ class ShaderResources { std::vector descriptorImages; std::vector descriptorWrites; bool addressedBuffers = false; + std::vector resolvedAddresses; + VkDeviceAddress emptyAddress = 0; std::size_t gdsAllocation = std::numeric_limits::max(); std::array, ShaderRecompiler::RuntimeAbi::StageCount> stageDataWords; std::array stageDataIndex{}; @@ -739,6 +746,9 @@ class ShaderResources { void writeBufferAddresses(std::span words, std::uint32_t dataStage, const std::vector* overrides, std::vector* ranges = nullptr) const; VkDeviceAddressRangeEXT srtRange(std::size_t stage) const; + bool stageReadsOverride(std::size_t stage, const std::vector& overrides) const; + VkDeviceAddressRangeEXT bufferAddress(const Allocation& allocation) const; + void resolveBufferAddresses(); std::uint32_t ringDescriptors(std::size_t stage, const std::vector* overrides, RingDescriptors& kept) const; std::array heapSrtOffsets{}; std::array ringDescriptorStages{}; @@ -804,6 +814,7 @@ class ShaderResources { bool importsReconcilable = false; // FNV-1a offset basis: the hash of no data buffers (DataWordsHash). std::uint64_t dataWordsHash = 14695981039346656037ull; + mutable std::atomic cacheTouchedAt{0}; void rehashDataWords(); std::vector> pushPatches; std::vector dataPatches; @@ -870,6 +881,7 @@ class ResourceCache { // Moves the entry to the front of the LRU (a recipe hit uses its template without Find, and a // hot template must not age out under the recipes that depend on it); false when no entry. bool Touch(const Key& key); + void TouchAging(const Key& key, std::atomic& touchedAt); // Find and Touch calls so far (the [rescache] line: a recipe hit touches instead of finding). static std::uint64_t Finds(); static std::uint64_t Touches(); @@ -928,6 +940,10 @@ class ResourceCache { static constexpr std::size_t InitialShrinkWindow = 8; static constexpr std::size_t MaximumShrinkWindow = 1024; std::size_t baseEntries = InitialEntries; + std::atomic operations{0}; + std::atomic usesWindowStart{0}; + std::atomic agingWindow{InitialEntries / 8u}; + void publishAgingWindow(); std::size_t baseShrinkWindow = InitialShrinkWindow; std::size_t shrinkWindow = InitialShrinkWindow; bool shrankLast = false; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 61e607e7704d..ad62ab076ace 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -279,6 +279,7 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { ringHeapOffset = sizes.ringOffset; ringBytes = sizes.ringBytes; ringData = resourceHeap->Bytes().data() + ringHeapOffset; + writeResourceDescriptors = context.Function("vkWriteResourceDescriptorsEXT"); } else { ringBytes = 0; } @@ -288,9 +289,8 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { slotCap = configuredSlotCap(sizes.imageSlots); deviceImageSlots.store(slotCap, std::memory_order_relaxed); slotUses = std::make_unique[]>(slotCap); - imagePool.next = SamplerKind; - imagePool.limit = slotCap; - samplerPool.limit = Abi::GpuSamplerHeapSlots; + imagePool.Configure(SamplerKind, slotCap); + samplerPool.Configure(0u, Abi::GpuSamplerHeapSlots); samplerUses = std::make_unique[]>(Abi::GpuSamplerHeapSlots); } @@ -323,13 +323,23 @@ std::atomic heapsEpoch{0}; } +namespace { + +struct CachedHeap { + VkDevice device = VK_NULL_HANDLE; + BindlessHeap* heap = nullptr; + std::uint64_t epoch = ~std::uint64_t{0}; +}; + +CachedHeap& ThreadCachedHeap() { + thread_local CachedHeap cached; + return cached; +} + +} + BindlessHeap& BindlessHeap::For(const Context& context) { - struct Cached { - VkDevice device = VK_NULL_HANDLE; - BindlessHeap* heap = nullptr; - std::uint64_t epoch = ~std::uint64_t{0}; - }; - thread_local Cached cached; + auto& cached = ThreadCachedHeap(); if (cached.heap != nullptr && cached.device == context.device && cached.epoch == heapsEpoch.load(std::memory_order_acquire)) { return *cached.heap; } @@ -356,9 +366,13 @@ void BindlessHeap::Release(VkDevice device) { } BindlessHeap* BindlessHeap::Existing(const Context& context) { + auto& cached = ThreadCachedHeap(); + if (cached.heap != nullptr && cached.device == context.device && cached.epoch == heapsEpoch.load(std::memory_order_acquire)) return cached.heap; std::lock_guard lock(heapsMutex()); const auto found = heaps().find(context.device); - return found == heaps().end() ? nullptr : found->second.get(); + if (found == heaps().end()) return nullptr; + cached = {context.device, found->second.get(), heapsEpoch.load(std::memory_order_acquire)}; + return found->second.get(); } std::optional BindlessHeap::TextureSlot(std::uint32_t kind, Texture* texture, VkImageView view, VkImageLayout layout) { @@ -449,13 +463,21 @@ std::optional BindlessHeap::SlotPool::Take(bool& reused) { return slot; } if (next >= limit) return std::nullopt; - const auto slot = next++; - if (generations.size() <= slot) generations.resize(static_cast(slot) + 1u, 0u); - return slot; + return next++; +} + +void BindlessHeap::SlotPool::Configure(std::uint32_t first, std::uint32_t slots) { + next = first; + limit = slots; + generations = std::make_unique[]>(slots); +} + +void BindlessHeap::SlotPool::Retire(std::uint32_t slot) { + generations[slot].fetch_add(1u, std::memory_order_release); } void BindlessHeap::SlotPool::Free(std::uint32_t slot) { - ++generations[slot]; + Retire(slot); free.push_back(slot); } @@ -464,7 +486,7 @@ std::size_t BindlessHeap::SlotPool::Unused() const { } std::uint32_t BindlessHeap::SlotPool::Generation(std::uint32_t slot) const { - return slot < generations.size() ? generations[slot] : 0u; + return slot < limit ? generations[slot].load(std::memory_order_acquire) : 0u; } bool BindlessHeap::NearlyFull() { @@ -510,13 +532,11 @@ void BindlessHeap::touchSamplerLocked(std::uint32_t slot) const { if (slot < Abi::GpuSamplerHeapSlots) samplerUses[slot].store(useEpoch.load(std::memory_order_relaxed), std::memory_order_relaxed); } -std::uint32_t BindlessHeap::TouchSlots(std::span> slots, std::span samplerSlots, std::uint32_t touched) const { +std::uint32_t BindlessHeap::TouchSlots(std::span slots, std::span samplerSlots, std::uint32_t touched) const { const auto epoch = useEpoch.load(std::memory_order_relaxed); if (touched == epoch) return epoch; - for (const auto& kindSlots : slots) { - for (const auto slot : kindSlots) { - if (slot < slotCap) slotUses[slot].store(epoch, std::memory_order_relaxed); - } + for (const auto slot : slots) { + if (slot < slotCap) slotUses[slot].store(epoch, std::memory_order_relaxed); } for (const auto slot : samplerSlots) { if (slot < Abi::GpuSamplerHeapSlots) samplerUses[slot].store(epoch, std::memory_order_relaxed); @@ -549,7 +569,7 @@ void BindlessHeap::evictLocked(std::uint32_t idleSubmissions) { } owner.texture = nullptr; owner.key = {}; - ++imagePool.generations[slot]; + imagePool.Retire(slot); retiring.push_back({slot, 0u}); ++counts.slotsEvicted; heapSlotEvictions.fetch_add(1, std::memory_order_relaxed); @@ -575,7 +595,7 @@ void BindlessHeap::evictSamplersLocked(std::uint32_t idleSubmissions) { const auto slot = idle[index].second; samplerSlots.erase(samplerOwners[slot]); samplerOwners[slot] = nullptr; - ++samplerPool.generations[slot]; + samplerPool.Retire(slot); retiring.push_back({slot, 0u, true}); ++retiringSamplers; ++counts.samplersEvicted; @@ -630,19 +650,15 @@ void BindlessHeap::noteReleasedLocked() { std::uint32_t BindlessHeap::SamplerGeneration(std::uint32_t slot) const { if (slot == Abi::NoEmbeddedSampler) return 0u; - std::lock_guard lock(mutex); return samplerPool.Generation(slot); } -bool BindlessHeap::GenerationsCurrent(std::span> slots, std::span slotGenerations, +bool BindlessHeap::GenerationsCurrent(std::span slots, std::span slotGenerations, std::span samplerSlots, std::span samplerGenerations) const { - std::lock_guard lock(mutex); - std::size_t generation = 0; - for (std::uint32_t kind = 0; kind < slots.size(); ++kind) { - for (const auto slot : slots[kind]) { - if (generation >= slotGenerations.size() || imagePool.Generation(slot) != slotGenerations[generation++]) return false; - } + if (slots.size() != slotGenerations.size()) return false; + for (std::size_t i = 0; i < slots.size(); ++i) { + if (imagePool.Generation(slots[i]) != slotGenerations[i]) return false; } for (std::size_t i = 0; i < samplerSlots.size(); ++i) { if (samplerSlots[i] == Abi::NoEmbeddedSampler) continue; @@ -652,7 +668,6 @@ bool BindlessHeap::GenerationsCurrent(std::span } std::uint32_t BindlessHeap::SlotGeneration(std::uint32_t slot) const { - std::lock_guard lock(mutex); return imagePool.Generation(slot); } @@ -715,9 +730,14 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words) { } bool BindlessHeap::Held(const SpanMark& mark) { + if (mark.entry == 0u || mark.words == 0u) return false; + std::lock_guard lock(mutex); + return heldLocked(mark); +} + +bool BindlessHeap::heldLocked(const SpanMark& mark) { if (mark.entry == 0u || mark.words == 0u) return false; if (mark.block != 0u) { - std::lock_guard lock(mutex); const auto index = mark.block - 1u; if (index >= poolBlocks.size() || poolBlocks[index].generation != mark.entry) { ++counts.spansExpired; @@ -729,7 +749,6 @@ bool BindlessHeap::Held(const SpanMark& mark) { } const auto first = chunkOf(mark.offset); const auto last = lastChunkOf(mark.offset, static_cast(mark.words) * sizeof(std::uint32_t)); - std::lock_guard lock(mutex); for (auto chunk = first; chunk <= last; ++chunk) { if (ringChunks[chunk].entered > mark.entry) { ++counts.spansExpired; @@ -745,8 +764,18 @@ bool BindlessHeap::Held(const SpanMark& mark) { } BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) { - const auto bytes = alignUp(std::max(words, 1u) * sizeof(std::uint32_t), RingSpanAlignment); std::lock_guard lock(mutex); + return allocateLocked(words, mark); +} + +std::optional BindlessHeap::KeepOrAllocate(std::size_t words, SpanMark& mark, bool same) { + std::lock_guard lock(mutex); + if (same && heldLocked(mark)) return std::nullopt; + return allocateLocked(words, mark); +} + +BindlessHeap::DataSpan BindlessHeap::allocateLocked(std::size_t words, SpanMark& mark) { + const auto bytes = alignUp(std::max(words, 1u) * sizeof(std::uint32_t), RingSpanAlignment); if (poolCurrent >= poolBlocks.size() || alignUp(poolBlocks[poolCurrent].cursor, poolAlignment) + bytes > poolBlocks[poolCurrent].bytes) poolCurrent = takePoolBlockLocked(bytes); auto& block = poolBlocks[poolCurrent]; const auto offset = static_cast(alignUp(block.cursor, poolAlignment)); @@ -1010,7 +1039,8 @@ struct HeapBindingUse { bool meshWindowMemory = false; bool scratchPoolMemory = false; std::vector dataUniforms; - std::vector ringDescriptors; + std::vector ringBuffers; + std::vector srtAddresses; std::vector embeddedSamplers; std::pair refused{~0u, ~0u}; }; @@ -1076,9 +1106,12 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& continue; } const bool stageBinding = binding / bindingCount < Abi::StageCount; - if (roots.gdsAddress && stageBinding && ((set == Abi::DescriptorSet && binding % bindingCount == static_cast(Abi::Binding::Buffers)) || - (set == Abi::GpuDataSet && binding % bindingCount == static_cast(Abi::Binding::FlattenedSrt)))) { - if (std::find(use.ringDescriptors.begin(), use.ringDescriptors.end(), entry) == use.ringDescriptors.end()) use.ringDescriptors.push_back(entry); + if (roots.gdsAddress && stageBinding && set == Abi::DescriptorSet && binding % bindingCount == static_cast(Abi::Binding::Buffers)) { + if (std::ranges::find(use.ringBuffers, binding) == use.ringBuffers.end()) use.ringBuffers.push_back(binding); + continue; + } + if (roots.gdsAddress && stageBinding && set == Abi::GpuDataSet && binding % bindingCount == static_cast(Abi::Binding::FlattenedSrt)) { + if (std::ranges::find(use.srtAddresses, binding) == use.srtAddresses.end()) use.srtAddresses.push_back(binding); continue; } const bool heapImageOrSampler = set == Abi::FragmentDescriptorSet && binding >= firstImage && binding <= samplers; @@ -1122,16 +1155,14 @@ std::uint32_t rootItemOffset(const ShaderRecompiler::StagePushPlacement* placeme return placement->Item(item) * static_cast(sizeof(std::uint32_t)); } -VkDescriptorSetAndBindingMappingEXT ringDescriptorMapping(std::uint32_t set, std::uint32_t binding, VkDeviceSize ringOffset, const ShaderRecompiler::StagePushPlacement* placement) { - constexpr auto bindingCount = static_cast(Abi::Binding::Count); - const bool buffers = binding % bindingCount == static_cast(Abi::Binding::Buffers); +VkDescriptorSetAndBindingMappingEXT ringBufferMapping(std::uint32_t binding, VkDeviceSize ringOffset, const ShaderRecompiler::StagePushPlacement* placement) { VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = set; + mapping.descriptorSet = Abi::DescriptorSet; mapping.firstBinding = binding; mapping.bindingCount = 1; mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; - mapping.sourceData.pushIndex.heapOffset = static_cast(ringOffset + (buffers ? BindlessHeap::BufferSlotBytes : 0u)); + mapping.sourceData.pushIndex.heapOffset = static_cast(ringOffset); mapping.sourceData.pushIndex.pushOffset = rootItemOffset(placement, Abi::RootItem::FlattenedSrt); mapping.sourceData.pushIndex.heapIndexStride = BindlessHeap::BufferSlotBytes; mapping.sourceData.pushIndex.heapArrayStride = BindlessHeap::BufferSlotBytes; @@ -1245,8 +1276,8 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, .workgroupAddress = workgroupAddressOffset != ~0u, .gdsAddress = rootGds, .faultAddress = rootFault, .pixelLds = pixelLds, .meshWindow = meshWindow, .scratchPool = scratchPool}; if (!heapBindings(spirv, roots, use)) return false; - if (!use.ringDescriptors.empty() && !ringInHeap) return false; - if (!use.ringDescriptors.empty() && context.descriptorHeapProperties.bufferDescriptorSize != BufferSlotBytes) return false; + if (!use.ringBuffers.empty() && !ringInHeap) return false; + if (!use.ringBuffers.empty() && context.descriptorHeapProperties.bufferDescriptorSize != BufferSlotBytes) return false; constexpr auto bindingCount = static_cast(Abi::Binding::Count); constexpr VkSpirvResourceTypeFlagsEXT imageResources = VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_IMAGE_BIT_EXT | @@ -1274,8 +1305,10 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, mappings.push_back(*mapping); } for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, placement)); - std::sort(use.ringDescriptors.begin(), use.ringDescriptors.end()); - for (const auto& [set, binding] : use.ringDescriptors) mappings.push_back(ringDescriptorMapping(set, binding, ringHeapOffset, placement)); + std::ranges::sort(use.ringBuffers); + for (const auto binding : use.ringBuffers) mappings.push_back(ringBufferMapping(binding, ringHeapOffset, placement)); + std::ranges::sort(use.srtAddresses); + for (const auto binding : use.srtAddresses) mappings.push_back(pushAddressMapping(Abi::GpuDataSet, binding, rootItemOffset(placement, Abi::RootItem::SrtAddress))); if (use.workgroupMemory) mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset)); if (use.scratchPoolMemory) @@ -1296,6 +1329,7 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::uint32_t BindlessHeap::RingBufferDescriptors(std::span buffers, SpanMark& mark) { Require(ringInHeap && context.descriptorHeapProperties.bufferDescriptorSize == BufferSlotBytes, "ring buffer descriptors need the descriptor ring inside the resource heap"); const auto span = RingAllocate(buffers.size() * (BufferSlotBytes / sizeof(std::uint32_t)), mark); + counts.bufferDescriptors += buffers.size(); Require(span.offset % BufferSlotBytes == 0u, "a ring buffer descriptor span is misaligned"); struct ResourcesStorage {}; struct RangesStorage {}; @@ -1309,14 +1343,7 @@ std::uint32_t BindlessHeap::RingBufferDescriptors(std::span("vkWriteResourceDescriptorsEXT"); - write = writeResourceDescriptors; - counts.bufferDescriptors += buffers.size(); - } - Check(write(context.device, static_cast(buffers.size()), resources.data(), ranges.data()), "vkWriteResourceDescriptorsEXT ring buffers"); + Check(writeResourceDescriptors(context.device, static_cast(buffers.size()), resources.data(), ranges.data()), "vkWriteResourceDescriptorsEXT ring buffers"); return static_cast(span.offset / BufferSlotBytes); } @@ -1344,6 +1371,7 @@ namespace { std::mutex boundHeapsMutex; std::unordered_set boundHeaps; +std::atomic boundHeapsEpoch{0}; std::atomic heapBinds{0}; std::atomic heapBindWindow{0}; std::atomic commandBuffersBegun{0}; @@ -1484,7 +1512,7 @@ void reportHeapStatistics() { void forgetHeapBinding(VkCommandBuffer commands) { if (!DescriptorHeapEnabled()) return; std::lock_guard lock(boundHeapsMutex); - boundHeaps.erase(commands); + if (boundHeaps.erase(commands) != 0) boundHeapsEpoch.fetch_add(1, std::memory_order_release); } } @@ -1631,9 +1659,19 @@ void CmdPushData(const Context& context, VkCommandBuffer commands, std::uint32_t void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { if (resourceHeap == nullptr) return; + struct LastBound { + VkCommandBuffer commands = VK_NULL_HANDLE; + const BindlessHeap* heap = nullptr; + std::uint64_t epoch = 0; + }; + thread_local LastBound last; + const auto epoch = boundHeapsEpoch.load(std::memory_order_acquire); + if (last.commands == commands && last.heap == this && last.epoch == epoch) return; { std::lock_guard lock(boundHeapsMutex); - if (!boundHeaps.insert(commands).second) return; + const bool inserted = boundHeaps.insert(commands).second; + last = {commands, this, epoch}; + if (!inserted) return; } heapBinds.fetch_add(1, std::memory_order_relaxed); heapBindWindow.fetch_add(1, std::memory_order_relaxed); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 4d6ce819d21e..3f05a9fec198 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1268,12 +1268,22 @@ ResourceCache::Key DrawResourceKey(const Context& context, std::spandrawKeyMemo.words; - if (auto words = memo.load(std::memory_order_acquire); words != nullptr && shader.heap == nullptr) { - key.insert(key.end(), words->begin(), words->end()); + auto& memo = shader.heap != nullptr ? shader.heap->drawKeyMemo.words : shader.program->drawKeyMemo.words; + const auto ownerId = shader.program->heapTemplateId != 0 ? shader.program->heapTemplateId : static_cast(reinterpret_cast(shader.program)); + const std::array owner{static_cast(ownerId), static_cast(ownerId >> 32u), + static_cast(shader.stage) | (shader.program->heapTemplateId != 0 ? 0x80000000u : 0u)}; + const std::size_t prefix = shader.heap != nullptr ? owner.size() : 0u; + const bool memoize = shader.heap == nullptr || shader.heap->memoizeKey; + const auto words = memoize ? memo.load(std::memory_order_acquire) : nullptr; + if (words != nullptr && words->size() >= prefix && std::equal(owner.begin(), owner.begin() + static_cast(prefix), words->begin())) { + key.insert(key.end(), words->begin() + static_cast(prefix), words->end()); } else { ShaderResources::AppendContentKey(shader, true, MovableBuffers(), key); - if (shader.heap == nullptr) memo.store(std::make_shared>(key.begin() + static_cast(sizeAt + 1u), key.end()), std::memory_order_release); + if (memoize) { + auto stored = std::make_shared>(owner.begin(), owner.begin() + static_cast(prefix)); + stored->insert(stored->end(), key.begin() + static_cast(sizeAt + 1u), key.end()); + memo.store(std::move(stored), std::memory_order_release); + } } key[sizeAt] = static_cast(key.size() - sizeAt - 1u); } @@ -1421,7 +1431,7 @@ bool DrawRecipes() { } const char* DrawRecipeMissName(DrawRecipeMiss miss) { - constexpr std::array(DrawRecipeMiss::Count)> names{"none", "not recordable", "target gone", "template gone", "objects gone", "proof"}; + constexpr std::array(DrawRecipeMiss::Count)> names{"none", "not recordable", "target gone", "template gone", "objects gone", "proof", "moved buffers refused"}; return names[static_cast(miss)]; } @@ -2880,7 +2890,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam const bool heapPipeline = record.pipeline->DescriptorHeap(); NoteHeapRecord(false, heapPipeline); if (heapPipeline) { - resources.BindDescriptorHeaps(commands); + resources.BindDescriptorHeaps(commands, true); NoteEmptyResourceSet(); } else if (drawBindings != nullptr) { Require(!resources.HeapStage(), "a GPU-mode draw needs a VK_EXT_descriptor_heap pipeline"); @@ -3256,7 +3266,6 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara } if (state.quadList || StripPatches(state, shaders)) recipeOut = nullptr; if (context.recorder != nullptr) context.recorder->BoundDrawBatch(); - if (AnyHeapShader(shaders)) recipeOut = nullptr; auto& timing = prepared.timing.emplace("Graphics.Draw"); // APS5_PROFILE_DRAW prints the time of each phase of the draw (microseconds) and the [draws] totals. static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; @@ -3747,7 +3756,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D // only a template the resource cache serves under this content key (reusable: no lease, // no copied writes, every direct region import- or mirror-served) of a direct draw, so a // hit's proof is the template's ProveCurrent and nothing needs completion work. - if (recipeOut != nullptr && DrawRecipes() && cacheable && !outcome.waited && args == nullptr && resources->Reusable() && !resources->SpaceReuse() && resolved.moved.empty() && !multisampled && !pipeline->ReordersSamples()) { + if (recipeOut != nullptr && DrawRecipes() && cacheable && !outcome.waited && args == nullptr && resources->Reusable() && !resources->SpaceReuse() && !multisampled && !pipeline->ReordersSamples()) { auto recipe = std::make_shared(); recipe->device = context.device; recipe->templateRef = resources; @@ -3767,6 +3776,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D recipe->fragmentOutputs = inputs.fragmentOutputs; recipe->shaderStages = inputs.shaderStages; recipe->hasDepth = state.depth.has_value(); + recipe->movedBuffers = !resolved.moved.empty(); *recipeOut = std::move(recipe); } timing.Mark("draw_and_resource_release"); @@ -4253,9 +4263,19 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con timer.phase(PhaseLookup); return miss(DrawRecipeMiss::Proof); } + std::vector moved; + if (recipe.movedBuffers) { + auto found = resources->MovedReadOnlyBuffers(shaders, *recorder, &state.color); + if (!found.has_value()) { + timer.phase(PhaseLookup); + return miss(DrawRecipeMiss::Moved); + } + moved = std::move(*found); + } CheckBufferAliases(shaders, state.color, draw.indexAddress, inputs.indexBytes); + if (resources->HeapStage()) resources->RefreshHeapStage(shaders); if (recipe.hasDepth && writesDepthTarget(state)) NoteDepthSurfaceWrite(context, *state.depth); - SharedResourceCache().Touch(recipe.key); + SharedResourceCache().TouchAging(recipe.key, resources->CacheTouchedAt()); countCache(&DrawProfile::cacheHits); timer.phase(PhaseLookup); outcome.completion = resources->ChecksFaults(); @@ -4281,6 +4301,7 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con record.framebuffer = std::move(framebuffer); record.targetViews = recipe.targetViews; record.targets = std::move(targets); + record.moved = moved; for (const auto& color : state.colors) record.targetSlices.emplace_back(color.arraySlice, color.arrayLastSlice != 0 ? color.layers : 1u); record.pushBytes = &recipe.pushBytes; record.pushStages = recipe.pushStages; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 18810deb8a10..7eaf469565e8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -4347,6 +4347,7 @@ bool chargeShaderKey(ChurnCounts& profile, const ResourceCache::Key& key, std::s std::shared_ptr ResourceCache::Find(const Key& key) { resourceCacheFinds.fetch_add(1, std::memory_order_relaxed); + operations.fetch_add(1, std::memory_order_relaxed); std::lock_guard lock(mutex); const auto found = index.find(key); if (found == index.end()) { @@ -4376,10 +4377,12 @@ void ResourceCache::noteEvicted(const Key& key) { if (!churning || capacity >= MaximumEntries) return; const auto previous = capacity; capacity = std::min(capacity * 2u, MaximumEntries); + publishAgingWindow(); if (shrankLast) shrinkWindow = std::min(shrinkWindow * 2u, MaximumShrinkWindow); shrankLast = false; usedKeys.clear(); usesSinceCheck = 0; + usesWindowStart.store(operations.load(std::memory_order_relaxed), std::memory_order_relaxed); std::fprintf(stderr, "[rescache] capacity %zu -> %zu entries: keys it evicted keep coming back\n", previous, capacity); } @@ -4391,9 +4394,11 @@ void ResourceCache::noteUse(const Key& key) { const auto uses = usesSinceCheck; usedKeys.clear(); usesSinceCheck = 0; + usesWindowStart.store(operations.load(std::memory_order_relaxed), std::memory_order_relaxed); if (used * 4u > capacity) return; const auto previous = capacity; capacity = std::max(capacity / 2u, baseEntries); + publishAgingWindow(); shrankLast = true; evictionsSinceCheck = 0; returnsSinceCheck = 0; @@ -4536,6 +4541,7 @@ void ResourceCache::noteMiss(const Key& key) { } void ResourceCache::Insert(const Key& key, std::shared_ptr resources, std::vector>* evicted) { + operations.fetch_add(1, std::memory_order_relaxed); std::lock_guard lock(mutex); dropReleasedTextures(evicted); if (!resources->HasCachedStorageImages() || resources->HoldsReleasedTexture()) return; @@ -4551,6 +4557,7 @@ void ResourceCache::Insert(const Key& key, std::shared_ptr reso const auto parsed = value ? std::strtoull(value, nullptr, 10) : 0ull; fixedCapacity = parsed != 0; capacity = fixedCapacity ? static_cast(parsed) : baseEntries; + publishAgingWindow(); } noteUse(key); while (entries.size() > capacity) { @@ -4621,8 +4628,21 @@ void ResourceCache::dropReleasedTextures(std::vector& touchedAt) { + const auto now = operations.load(std::memory_order_relaxed); + const auto last = touchedAt.load(std::memory_order_relaxed); + if (last != 0u && last >= usesWindowStart.load(std::memory_order_relaxed) && now - last < agingWindow.load(std::memory_order_relaxed)) return; + touchedAt.store(now == 0u ? 1u : now, std::memory_order_relaxed); + static_cast(Touch(key)); +} + +void ResourceCache::publishAgingWindow() { + agingWindow.store((capacity == 0 ? baseEntries : capacity) / 8u, std::memory_order_relaxed); +} + bool ResourceCache::Touch(const Key& key) { resourceCacheTouches.fetch_add(1, std::memory_order_relaxed); + operations.fetch_add(1, std::memory_order_relaxed); std::lock_guard lock(mutex); const auto found = index.find(key); if (found == index.end()) return false; @@ -4649,15 +4669,18 @@ void ResourceCache::Clear() { returnsSinceCheck = 0; usedKeys.clear(); usesSinceCheck = 0; + usesWindowStart.store(operations.load(std::memory_order_relaxed), std::memory_order_relaxed); shrinkWindow = baseShrinkWindow; shrankLast = false; if (!fixedCapacity) capacity = 0; + publishAgingWindow(); } void ResourceCache::SetBase(std::size_t entries, std::size_t window) { std::lock_guard lock(mutex); baseEntries = entries; baseShrinkWindow = window; + publishAgingWindow(); } std::size_t ResourceCache::Size() const { @@ -6390,6 +6413,7 @@ std::shared_ptr ShaderResources::PrepareDrawBindi for (std::size_t index = 0; index < allocations.size(); ++index) { const auto& item = allocations[index]; const auto override = std::find_if(moved.begin(), moved.end(), [&](const MovedBuffer& entry) { return entry.allocation == index; }); + if (override != moved.end() && override->words.empty()) result->movedReads.emplace_back(override->address, override->address + override->size); if (override != moved.end() && override->words.empty() && readsInPlace) { std::uint32_t adjustment = 0; inPlace.push_back({index, wholeDwordRange(guestMemory.Descriptor(override->address, override->size, adjustment))}); @@ -6601,11 +6625,22 @@ void ShaderResources::RefreshMovedAddresses(DrawBindings& rewritten) const { if (rewritten.addressOffsets) rewritten.heapOffsets = addressedOffsets(&rewritten.addressOverrides); } +bool ShaderResources::stageReadsOverride(std::size_t stage, const std::vector& overrides) const { + for (const auto& binding : bindings) { + if (!binding.addressed || binding.dataStage != stage) continue; + for (const auto index : binding.allocations) { + if (index < overrides.size() && overrides[index].buffer != VK_NULL_HANDLE) return true; + } + } + return false; +} + std::array ShaderResources::addressedOffsets(const std::vector* overrides) const { auto offsets = heapOffsets; auto& heap = BindlessHeap::For(context); + const auto moved = [&](std::size_t stage) { return overrides == nullptr || stageReadsOverride(stage, *overrides); }; for (std::size_t stage = 0; stage < stageDataWords.size(); ++stage) { - if (stageDataWords[stage].empty()) continue; + if (stageDataWords[stage].empty() || !moved(stage)) continue; auto words = stageDataWords[stage]; writeBufferAddresses(words, static_cast(stage), overrides); auto span = heap.Allocate(words.size()); @@ -6613,9 +6648,9 @@ std::array ShaderR offsets[stageDataIndex[stage]] = span.address; } for (std::size_t stage = 0; stage < ringDescriptorStages.size(); ++stage) { - if (!ringDescriptorStages[stage]) continue; - RingDescriptors moved; - offsets[DataOffsetIndex(stage, ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt)] = ringDescriptors(stage, overrides, moved); + if (!ringDescriptorStages[stage] || !moved(stage)) continue; + RingDescriptors fresh; + offsets[DataOffsetIndex(stage, ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt)] = ringDescriptors(stage, overrides, fresh); } return offsets; } @@ -6650,8 +6685,8 @@ void ShaderResources::requireGuestBuffers(std::span moved) co } } -void ShaderResources::BindDescriptorHeaps(VkCommandBuffer commands) const { - requireGuestBuffers(); +void ShaderResources::BindDescriptorHeaps(VkCommandBuffer commands, bool guestBuffersChecked) const { + if (!guestBuffersChecked) requireGuestBuffers(); prepareFaultSlot(); BindlessHeap::For(context).BindDescriptorHeaps(commands); } @@ -6669,13 +6704,38 @@ PipelineSetLayouts ShaderResources::SetLayouts() const { } void ShaderResources::RefreshHeapStage(std::span shaders) { + resolveBufferAddresses(); for (const auto& shader : shaders) { if (HeapShader(shader)) writeHeapStage(shader); } } +VkDeviceAddressRangeEXT ShaderResources::bufferAddress(const Allocation& allocation) const { + auto adjustment = allocation.adjustment; + auto info = descriptor(allocation, adjustment); + if (info.buffer == VK_NULL_HANDLE) info = {context.emptyBuffer, 0, EmptyBufferBytes}; + const auto base = BufferDeviceAddress(context, info.buffer); + Require(base != 0, "an addressed buffer has no device address"); + return {base + info.offset, info.range}; +} + +void ShaderResources::resolveBufferAddresses() { + if (!resolvedAddresses.empty()) return; + if (emptyAddress == 0) emptyAddress = BufferDeviceAddress(context, context.emptyBuffer); + if (!addressedBuffers) return; + resolvedAddresses.assign(allocations.size(), {}); + for (const auto& binding : bindings) { + if (!binding.addressed) continue; + for (const auto index : binding.allocations) { + const auto& allocation = allocations[index]; + if (allocation.guest || allocation.role == ShaderRecompiler::DescriptorRole::GuestBuffers) resolvedAddresses[index] = bufferAddress(allocation); + } + } +} + void ShaderResources::writeBufferAddresses(std::span words, std::uint32_t dataStage, const std::vector* overrides, std::vector* ranges) const { + static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; for (const auto& binding : bindings) { if (!binding.addressed || binding.dataStage != dataStage) continue; for (std::size_t element = 0; element < binding.allocations.size(); ++element) { @@ -6683,19 +6743,29 @@ void ShaderResources::writeBufferAddresses(std::span words, std:: const auto& allocation = allocations[index]; const bool overridden = overrides != nullptr && (*overrides)[index].buffer != VK_NULL_HANDLE; const bool owned = !overridden && !allocation.guest && allocation.buffer != nullptr && allocation.role != ShaderRecompiler::DescriptorRole::GuestBuffers && allocation.role != ShaderRecompiler::DescriptorRole::BdaPagetable && allocation.role != ShaderRecompiler::DescriptorRole::FaultBuffer; + const bool resolved = !overridden && index < resolvedAddresses.size() && resolvedAddresses[index].address != 0; VkDeviceAddress address = 0; VkDeviceSize range = 0; if (owned) { address = allocation.buffer->DeviceAddress(); range = allocation.size; - } else { - auto adjustment = allocation.adjustment; - auto info = overridden ? (*overrides)[index] : descriptor(allocation, adjustment); - if (info.buffer == VK_NULL_HANDLE) info = {context.emptyBuffer, 0, EmptyBufferBytes}; + } else if (resolved) { + address = resolvedAddresses[index].address; + range = resolvedAddresses[index].size; + if (verify) { + const auto fresh = bufferAddress(allocation); + if (fresh.address != address || fresh.size != range) throw std::runtime_error("AGC graphics: a GPU heap buffer address resolved when the draw's resources were built changed"); + } + } else if (overridden) { + const auto& info = (*overrides)[index]; const auto base = BufferDeviceAddress(context, info.buffer); Require(base != 0, "an addressed buffer has no device address"); address = base + info.offset; range = info.range; + } else { + const auto fresh = bufferAddress(allocation); + address = fresh.address; + range = fresh.size; } if (ranges != nullptr) ranges->push_back({address, std::min(range, context.limits.maxStorageBufferRange)}); if (words.empty()) continue; @@ -6712,7 +6782,7 @@ void ShaderResources::writeBufferAddresses(std::span words, std:: VkDeviceAddressRangeEXT ShaderResources::srtRange(std::size_t stage) const { const auto bytes = static_cast(heapSrtDwords[stage]) * sizeof(std::uint32_t); if (bytes == 0u || bytes > context.limits.maxStorageBufferRange) { - const auto empty = BufferDeviceAddress(context, context.emptyBuffer); + const auto empty = emptyAddress != 0 ? emptyAddress : BufferDeviceAddress(context, context.emptyBuffer); Require(empty != 0, "the empty buffer has no device address"); return {empty, EmptyBufferBytes}; } @@ -6723,8 +6793,13 @@ std::uint32_t ShaderResources::ringDescriptors(std::size_t stage, const std::vec struct RangeStorage {}; auto& ranges = HostThreadLocal, RangeStorage>(); ranges.clear(); - ranges.push_back(srtRange(stage)); writeBufferAddresses({}, static_cast(stage), overrides, &ranges); + if (ranges.empty()) { + kept.ranges.clear(); + kept.mark = {}; + kept.first = 0u; + return 0u; + } auto& heap = BindlessHeap::For(context); const auto equal = [](const VkDeviceAddressRangeEXT& a, const VkDeviceAddressRangeEXT& b) { return a.address == b.address && a.size == b.size; }; if (!std::ranges::equal(ranges, kept.ranges, equal) || !heap.Held(kept.mark)) { @@ -6802,8 +6877,10 @@ void ShaderResources::PatchDataAddresses(std::span(offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)])); - putAddress(Abi::RootItem::SrtAddress, offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)]); - put(Abi::RootItem::SrtDwords, 0u, heapSrtDwords[stage]); + const bool ringStage = ringDescriptorStages[stage]; + const auto srt = ringStage ? srtRange(stage) : VkDeviceAddressRangeEXT{}; + putAddress(Abi::RootItem::SrtAddress, ringStage ? srt.address : offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)]); + put(Abi::RootItem::SrtDwords, 0u, ringStage ? static_cast(std::min(heapSrtDwords[stage], srt.size / sizeof(std::uint32_t))) : heapSrtDwords[stage]); putAddress(Abi::RootItem::TableMap, heapTableMapSet[stage] ? heapTableMaps[stage] : offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); writePushedData(bytes, shader, placement.pushed); rooted = true; @@ -6919,11 +6996,11 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ std::uint64_t ShaderResources::heapSpan(HeapStageState::KeptSpan& kept, std::span words) { auto& heap = BindlessHeap::For(context); - if (std::ranges::equal(kept.words, words) && heap.Held(kept.mark)) return kept.mark.address; - auto span = heap.Allocate(words.size(), kept.mark); - std::memcpy(span.words.data(), words.data(), words.size() * sizeof(std::uint32_t)); + const auto span = heap.KeepOrAllocate(words.size(), kept.mark, std::ranges::equal(kept.words, words)); + if (!span) return kept.mark.address; + std::memcpy(span->words.data(), words.data(), words.size() * sizeof(std::uint32_t)); kept.words.assign(words.begin(), words.end()); - return span.address; + return span->address; } bool ShaderResources::ownsHeapBinding(const Binding& binding, VkShaderStageFlags stageBit) const { @@ -7041,9 +7118,13 @@ void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, V } void ShaderResources::noteHeapSlotGenerations(const BindlessHeap& heap, HeapStageState& state) { + state.imageSlots.clear(); state.slotGenerations.clear(); - for (std::uint32_t kind = 0; kind < state.slots.size(); ++kind) { - for (const auto slot : state.slots[kind]) state.slotGenerations.push_back(heap.SlotGeneration(slot)); + for (const auto& kindSlots : state.slots) { + for (const auto slot : kindSlots) { + state.imageSlots.push_back(slot); + state.slotGenerations.push_back(heap.SlotGeneration(slot)); + } } state.samplerGenerations.clear(); for (const auto slot : state.samplerSlots) state.samplerGenerations.push_back(heap.SamplerGeneration(slot)); @@ -7152,6 +7233,10 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { const VkShaderStageFlags stageBit = VulkanStage(shader.stage); const auto stageIndex = HeapStageIndex(shader.stage); auto& stageState = heapStages[stageIndex]; + static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + const auto programIdentity = shader.program->heapTemplateId; + if (programIdentity != 0 && stageState.inertProgram == programIdentity && !verifySlots) return; + stageState.inertProgram = 0; struct HeapKeyStorage {}; auto& key = HostThreadLocal, HeapKeyStorage>(); appendHeapSlotKey(stageBit, key); @@ -7160,16 +7245,15 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { const bool unmoved = current && EpochProofs() && stageState.slotSerial == slotSerial; if (!unmoved && current) current = - heap.GenerationsCurrent(stageState.slots, stageState.slotGenerations, stageState.samplerSlots, stageState.samplerGenerations); + heap.GenerationsCurrent(stageState.imageSlots, stageState.slotGenerations, stageState.samplerSlots, stageState.samplerGenerations); if (!current) { stageState.key = key; takeHeapSlots(heap, stageState, stageBit, key); noteHeapSlotGenerations(heap, stageState); } else { - stageState.touchedEpoch = heap.TouchSlots(stageState.slots, stageState.samplerSlots, stageState.touchedEpoch); + stageState.touchedEpoch = heap.TouchSlots(stageState.imageSlots, stageState.samplerSlots, stageState.touchedEpoch); } stageState.slotSerial = slotSerial; - static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; if (verifySlots) verifyHeapSlots(heap, stageState, stageBit); slotsCost.Stop(); @@ -7184,9 +7268,11 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { bool dataKept = false; bool inputsKept = false; bool flattened = false; + bool dataBindings = false; for (const auto& binding : program.bindings) { const bool shaderData = binding.role == ShaderRecompiler::DescriptorRole::ShaderData; if (!shaderData && binding.role != ShaderRecompiler::DescriptorRole::FlattenedSrt) continue; + dataBindings = true; const bool heapFlattened = !shaderData && shader.heap != nullptr && !shader.heap->flattenedSrt.empty(); const auto& words = heapFlattened ? shader.heap->flattenedSrt : DrawGuestWords(shader, binding); const auto userData = @@ -7235,17 +7321,23 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { stageState.dataInput.assign(words.begin(), words.end()); stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); } - if (!ringStage) return; + const bool unbound = key.empty() && !dataBindings && !heapTableMapSet[stageIndex] && stageState.imageSlots.empty() && stageState.samplerSlots.empty(); + if (!ringStage) { + if (unbound && !addressedBuffers) stageState.inertProgram = programIdentity; + return; + } if (!flattened) heapSrtDwords[stageIndex] = 0u; auto& kept = stageState.descriptors; const auto srt = srtRange(stageIndex); - const bool keepable = !kept.ranges.empty() && kept.ranges.front().address == srt.address && kept.ranges.front().size == srt.size && heap.Held(kept.mark); + const bool keepable = kept.srt.address == srt.address && kept.srt.size == srt.size && (kept.ranges.empty() || heap.Held(kept.mark)); + kept.srt = srt; if (dataKept && keepable) { heapOffsets[flatIndex] = kept.first; return; } if (!(inputsKept && keepable)) { heapOffsets[flatIndex] = ringDescriptors(stageIndex, nullptr, kept); + if (unbound && kept.ranges.empty() && heapOffsets[flatIndex] == 0u) stageState.inertProgram = programIdentity; return; } const std::vector before(kept.ranges.begin(), kept.ranges.end()); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_overlap_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_overlap_tests.cmake index 669a81003495..bd369d9903f7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_overlap_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_dispatch_overlap_tests.cmake @@ -6,4 +6,8 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_dispatch_overlap_off PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + agc_add_env_test(agc_driver_dispatch_overlap_recipe_verify agc_driver_dispatch_overlap_tests TIMEOUT 60 + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_VERIFY_RECIPE=1) + agc_add_env_test(agc_driver_dispatch_overlap_recipe_verify_gpu_heap agc_driver_dispatch_overlap_tests TIMEOUT 60 + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_VERIFY_RECIPE=1) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_relocation_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_relocation_tests.cmake index d146ab39b559..2c9c94b4c881 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_relocation_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_cache_relocation_tests.cmake @@ -17,4 +17,8 @@ endif() if(BUILD_TESTING) agc_add_gpu_heap_test(agc_driver_draw_cache_relocation) + agc_add_env_test(agc_driver_draw_cache_relocation_entries_verify agc_driver_draw_cache_relocation_tests TIMEOUT 60 + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_VERIFY_DRAW_ENTRIES=1) + agc_add_env_test(agc_driver_draw_cache_relocation_data_hits_verify_gpu_heap agc_driver_draw_cache_relocation_tests TIMEOUT 60 + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_VERIFY_DRAW_DATA_HITS=1) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake new file mode 100644 index 000000000000..0a4f4a8bccc8 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_draw_recipe_moved_buffer) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp index cff3638ece7e..67e564771cef 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp @@ -111,6 +111,10 @@ std::vector DrawFrom(std::initializer_list sources, return commands; } +std::uint64_t EntryInserts(const AgcDriver::DriverDetail::DrawEntryCounters& counters) { + return counters.inserts - (std::getenv("APS5_VERIFY_DRAW_ENTRIES") != nullptr ? counters.verifyHits : 0u); +} + void MovedDataHitsTheCache(bool libraries) { Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); Registered(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1); @@ -128,7 +132,7 @@ void MovedDataHitsTheCache(bool libraries) { for (std::size_t i = 0; i < 4; ++i) counters = draw({same[i].data()}); Require(counters.lookups == 4 && counters.hits == 0 && counters.inserts == 2, mode + ": the draws that teach the moved pointer and its contents made " + std::to_string(counters.hits) + " hits and " + std::to_string(counters.inserts) + " inserts, expected 0 and 2"); for (std::size_t i = 4; i < same.size(); ++i) counters = draw({same[i].data()}); - Require(counters.lookups == 8 && counters.hits == 4 && counters.inserts == 2, mode + ": draws whose data moved again did not reuse the cached draw (" + std::to_string(counters.hits) + " hits in " + std::to_string(counters.lookups) + " lookups)"); + Require(counters.lookups == 8 && counters.hits == 4 && EntryInserts(counters) == 2 && counters.verifyMismatches == 0, mode + ": draws whose data moved again did not reuse the cached draw (" + std::to_string(counters.hits) + " hits in " + std::to_string(counters.lookups) + " lookups)"); const auto other = draw({Other.data()}); Require(other.lookups == 9 && other.hits == 4, mode + ": a draw whose moved data holds another value reused the cached draw"); const auto again = draw({same[0].data()}); @@ -242,7 +246,7 @@ void UnrelocatedAliasesStayOut(bool libraries) { for (const auto& entry : pair) draw(entry.data()); counters = draw(repeated.data()); } - const auto inserts = counters.inserts - start.inserts; + const auto inserts = EntryInserts(counters) - EntryInserts(start); Require(inserts <= AgcDriver::DriverDetail::DrawRelocationTrial::ProbationAdmissions, mode + ": draws whose alias repeats but never relocates were cached (" + std::to_string(inserts) + " inserts for " + std::to_string(twice.size()) + " aliases)"); Require(counters.hits - start.hits == twice.size(), mode + ": the exact key of a repeated draw lost its hits next to draws whose alias never relocates (" + std::to_string(counters.hits - start.hits) + " hits in " + std::to_string(twice.size()) + " draws)"); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp new file mode 100644 index 000000000000..e792fdf79bf6 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp @@ -0,0 +1,369 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::byte Kept{0x40}; +constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, + 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array ConstantSamplerPixelCode{ + 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array BorderSamplerPixelCode{ + 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array WrapSamplerPixelCode{ + 0xbe8803ffu, 0u, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array BufferPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array GdsPixelCode{ + 0xbefc03ffu, 0x0000ffffu, 0x7e0002f0u, 0x7e0202f0u, 0xd8fa0010u, 0x04000000u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array StoragePixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e100280u, 0x7e120280u, 0xf0201f08u, + 0x00040008u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array LdsPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e080280u, 0xd8344400u, 0x00000004u, + 0xbf8cc07fu, 0xd8d84400u, 0x00000004u, 0xbf8cc07fu, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(4096) std::array StorageMemory{}; +alignas(256) constexpr std::array SamplingVertexCode{ + 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00820c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, + 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, + 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array InterpolantPixelCode{0xc8020002u, 0xc8060102u, 0xc80a0202u, 0xc80e0302u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array BdaPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0x7e08020cu, 0x7e0a020du, 0xdc308000u, 0x067d0004u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0x7e060306u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TablePixelCode{ + 0xf4200404u, 0xfa000000u, 0xbf8cc07fu, 0x8f108510u, 0xf42c0500u, 0x20000000u, 0xbf8cc07fu, 0x7e0002f0u, + 0x7e0202f0u, 0xf09c0f08u, 0x00250000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TableVertexCode{ + 0xf4200508u, 0xfa000000u, 0xbf8cc07fu, 0x8f148514u, 0xf42c0604u, 0x28000000u, 0xbf8cc07fu, 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, + 0x00660c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, + 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) std::array TableMemory{}; +alignas(256) std::array FreshVertexCode{}; +alignas(256) std::array FreshPixelCode{}; +alignas(256) std::array MaterialMemory{}; +alignas(256) std::array OtherTextureMemory{}; +constexpr float BufferAlpha = 0.2f; +constexpr std::uint8_t BufferAlphaByte = 51u; +constexpr float SecondAlpha = 0.6f; +constexpr std::uint8_t SecondAlphaByte = 153u; +alignas(4096) std::array BufferMemory{}; +alignas(256) std::array ColorMemory{}; + +std::span MergedTarget(std::size_t index) { + constexpr std::size_t Bytes = 65536; + static std::array data{}; + if (data.at(index) == nullptr) data[index] = [] { + std::byte* block = nullptr; +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Bytes, Bytes)); + GuestArena::GuestArenaCommit_nid_postfix(block, Bytes, PAGE_READWRITE, Bytes); +#else + void* raw = mmap(nullptr, 2u * Bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the merged color target"); + const auto begin = reinterpret_cast(raw); + block = reinterpret_cast((begin + Bytes - 1u) & ~static_cast(Bytes - 1u)); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Bytes); +#endif + GuestAllocations::Mutation mutation; + mutation.Add(block, Bytes, true, true, true); + return block; + }(); + return {data[index], ColorMemory.size()}; +} +alignas(256) std::array TextureMemory{}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(Header& header, const std::uint32_t* code, std::size_t bytes, std::uint8_t type) { + header.shader.file_header = 0x34333231u; + header.shader.version = 0x18u; + header.shader.header_size = sizeof(Header); + header.shader.shader_size = static_cast(bytes); + header.shader.code = code; + header.shader.type = type; + header.shader.user_data = &header.userData; + AgcDriverRegisterShader_nid_postfix(&header.shader); +} + +void Append(std::vector& commands, std::uint32_t opcode, std::initializer_list payload) { + commands.push_back(0xc0000000u | (static_cast(payload.size() - 1) << 16u) | (opcode << 8u)); + commands.insert(commands.end(), payload); +} + +enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds, ConstantSampler, BorderSampler, WrapSampler, MergedBlend, MergedBlendOther }; + +const std::uint32_t* VertexProgram(Mode mode) { + if (mode == Mode::VertexTable) return TableVertexCode.data(); + if (mode == Mode::Vertex) return SamplingVertexCode.data(); + return VertexCode.data(); +} + +std::uint32_t PixelUserWords(Mode mode, bool vertexSampling) { + switch (mode) { + case Mode::Storage: + return 24u; + case Mode::Buffer: + case Mode::MovedBuffer: + return 16u; + case Mode::Bda: + return 14u; + default: + return vertexSampling ? 0u : 12u; + } +} + +unsigned ExpectedChannel(Mode mode, bool buffer, std::size_t channel) { + if (mode == Mode::MovedTexture) return 0x33u; + if ((mode == Mode::Bda || mode == Mode::MovedBuffer) && channel == 3) return SecondAlphaByte; + if (buffer && channel == 3) return BufferAlphaByte; + if (mode == Mode::BorderSampler) return 0xffu; + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return std::min(2u * Texel[channel] + static_cast(Kept), 0xffu); + return Texel[channel]; +} + +const char* DrawnWhat(Mode mode, bool buffer) { + if (mode == Mode::Bda) return " (texture and BDA)"; + if (mode == Mode::MovedBuffer) return " (texture and a buffer moved between two draws)"; + if (mode == Mode::MovedTexture) return " (a texture changed between two draws)"; + if (buffer) return " (texture and buffer)"; + if (mode == Mode::Table) return " (image table)"; + if (mode == Mode::ConstantSampler) return " (texture with a constant sampler)"; + if (mode == Mode::BorderSampler) return " (constant border-clamp sampler outside the texture)"; + if (mode == Mode::WrapSampler) return " (constant wrapping sampler outside the texture, after a border-clamp draw of the same shader)"; + if (mode == Mode::MergedBlend) return " (texture blended unclamped into the color target)"; + if (mode == Mode::MergedBlendOther) return " (texture blended unclamped into a second color target)"; + return " (texture)"; +} + +const char* TakenWhat(Mode mode, bool buffer) { + if (buffer) return " reading a buffer"; + if (mode == Mode::Vertex) return " (vertex stage)"; + if (mode == Mode::Bda) return " loading through BDA"; + if (mode == Mode::Table) return " reading an image table"; + if (mode == Mode::VertexTable) return " (vertex stage reading an image table)"; + if (mode == Mode::ConstantSampler || mode == Mode::BorderSampler || mode == Mode::WrapSampler) return " sampling with a constant sampler"; + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return " merging into its color target"; + return ""; +} + +std::array ImageDescriptor(const void* memory) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u}; +} + +std::array BufferDescriptor(const void* memory, std::size_t bytes) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), static_cast(bytes), + 0xfacu}; +} + + +alignas(256) std::array SampledTexture{}; + +std::vector Frame(std::span slices) { + const auto color = reinterpret_cast(MergedTarget(0).data()); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, + {0x207, 0}, + {0x200, 0}, + {0x203, 0x800}, + {0x2dc, 0xaa00}, + {0x2f8, 0}, + {0x293, 0}, + {0x80, 0}, + {0x8d, 0}, + {0x83, 0xffff}, + {0x8c, 0xa}, + {0x2f9, 0x2d}, + {0x313, 0x6000}, + {0x30e, 0xffffffff}, + {0x30f, 0xffffffff}, + {0x206, 0x43f}, + {0x204, 0x80000}, + {0x205, 0x240}, + {0x8e, 0xf}, + {0x8f, 0xf}, + {0x202, 0xcc0010}, + {0x1c4, 0}, + {0x1c5, 9}, + {0x1c3, 4}, + {0x31c, 0x28028}, + {0x31b, 0}, + {0x31d, 0}, + {0x3b0, (63u << 14u) | 3u}, + {0x3b8, 0x9000000}, + {0x1e0, 0}, + {0xc, 0}, + {0xd, 0x40040}, + {0x81, 0x80000000}, + {0x82, 0x40040}, + {0x90, 0x80000000}, + {0x91, 0x40040}, + {0x94, 0x80000000}, + {0x95, 0x40040}, + {0x10f, std::bit_cast(32.0f)}, + {0x110, std::bit_cast(32.0f)}, + {0x111, std::bit_cast(-2.0f)}, + {0x112, std::bit_cast(2.0f)}, + {0x113, std::bit_cast(1.0f)}, + {0x114, 0}, + {0xb4, 0}, + {0xb5, std::bit_cast(1.0f)}, + {0x2fe, 0}, + {0x302, 0}, + {0x306, 0}, + {0x30a, 0}, + {0x318, static_cast(color >> 8u)}, + {0x390, static_cast(color >> 40u)}, + {0x292, 2}, + }; + + std::vector commands; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + const auto vertex = reinterpret_cast(VertexCode.data()); + Append(commands, 0x76, {0xc8, static_cast(vertex >> 8u)}); + Append(commands, 0x76, {0xc9, static_cast(vertex >> 40u)}); + Append(commands, 0x76, {0x8b, 1u << 1u}); + Append(commands, 0x76, {0x8c, 0}); + const auto pixel = reinterpret_cast(BufferPixelCode.data()); + for (const auto slice : slices) { + std::array words{}; + const auto image = ImageDescriptor(SampledTexture.data()); + std::copy(image.begin(), image.end(), words.begin()); + const auto descriptor = BufferDescriptor(BufferMemory.data() + slice, sizeof(BufferMemory) - slice * sizeof(float)); + std::copy(descriptor.begin(), descriptor.end(), words.begin() + 12); + Append(commands, 0x76, {0x008, static_cast(pixel >> 8u)}); + Append(commands, 0x76, {0x009, static_cast(pixel >> 40u)}); + Append(commands, 0x76, {0x00b, 16u << 1u}); + for (std::uint32_t index = 0; index < 16u; ++index) Append(commands, 0x76, {0x00cu + index, words[index]}); + Append(commands, 0x2d, {3, 2}); + } + return commands; +} + +unsigned DrawnAlpha() { + const auto color = MergedTarget(0); + for (std::size_t offset = 0; offset < color.size(); offset += 4) { + if (std::all_of(color.begin() + static_cast(offset), color.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) continue; + return static_cast(color[offset + 3]); + } + throw std::runtime_error("the draws covered no pixel"); +} + +unsigned Submit(std::span slices) { + std::ranges::fill(MergedTarget(0), Kept); + auto commands = Frame(slices); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); + return DrawnAlpha(); +} + +} + +int main() { + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + { + GuestAllocations::Mutation mutation; + mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); + } + for (std::size_t offset = 0; offset < SampledTexture.size(); offset += Texel.size()) std::memcpy(SampledTexture.data() + offset, Texel.data(), Texel.size()); + BufferMemory.fill(0.0f); + constexpr std::size_t First = 1, Moved = 9; + BufferMemory[First] = BufferAlpha; + BufferMemory[Moved] = SecondAlpha; + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + Registered(PixelHeader, BufferPixelCode.data(), sizeof(BufferPixelCode), 1); + const std::array slices{First, Moved}; + for (int round = 0; round < 2; ++round) Require(Submit(slices) == SecondAlphaByte, "the draw of the moved buffer did not read it"); + const auto hitsBefore = AgcDriver::VulkanDevice::DrawRecipeHits(); + Require(Submit(slices) == SecondAlphaByte, "the repeated draw of the moved buffer did not read it"); + const auto hits = AgcDriver::VulkanDevice::DrawRecipeHits() - hitsBefore; + if (AgcDriver::Graphics::DrawRecipes() && std::getenv("APS5_VERIFY_DRAW_ENTRIES") == nullptr) Require(hits == slices.size(), "a repeated draw whose read-only buffer moved from its template's did not replay a recipe (" + std::to_string(hits) + " recipe hits for " + std::to_string(slices.size()) + " draws)"); + BufferMemory[Moved] = BufferAlpha; + Require(Submit(slices) == BufferAlphaByte, "a recipe over a moved buffer drew the buffer's old contents after they changed"); + BufferMemory[Moved] = SecondAlpha; + const std::array unmoved{First}; + for (int round = 0; round < 3; ++round) Require(Submit(unmoved) == BufferAlphaByte, "the draw of the template's own buffer did not read it"); + const std::array movedOnly{Moved}; + for (int round = 0; round < 3; ++round) Require(Submit(movedOnly) == SecondAlphaByte, "a draw whose buffer moved after a recipe without moves was recorded did not read the moved buffer"); + std::puts("draws whose read-only buffer moved from their template's replayed recipes that read the buffer's current contents"); + AgcDriverShutdown_nid_postfix(); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawUnsupportedBufferType.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawUnsupportedBufferType.cpp index 61a0e679ee22..ceb237477d67 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawUnsupportedBufferType.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawUnsupportedBufferType.cpp @@ -93,7 +93,7 @@ void NamesShaderAndDescriptor() { Require(message.find("buffer descriptor uses an unsupported type") != std::string::npos, "draw failed for another reason: " + message); Require(message.find(shader) != std::string::npos, std::string("draw error does not name ") + shader + ": " + message); Require(message.find(words) != std::string::npos, std::string("draw error does not name ") + words + ": " + message); - if (std::getenv("APS5_DRAW_PIPELINE") != nullptr) Require(message.find("draw at submission ") != std::string::npos && message.find("(finished on the draw finisher)") != std::string::npos, "a draw finished on the draw finisher does not name its submission and offset: " + message); + if (std::getenv("APS5_DRAW_PIPELINE") != nullptr && std::getenv("APS5_VERIFY_DRAW_DATA_HITS") == nullptr) Require(message.find("draw at submission ") != std::string::npos && message.find("(finished on the draw finisher)") != std::string::npos, "a draw finished on the draw finisher does not name its submission and offset: " + message); return; } throw std::runtime_error("a pixel shader read a buffer through a descriptor of type 2"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp new file mode 100644 index 000000000000..33c43c64bf1e --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp @@ -0,0 +1,365 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::byte Kept{0x40}; +constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, + 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array ConstantSamplerPixelCode{ + 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array BorderSamplerPixelCode{ + 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array WrapSamplerPixelCode{ + 0xbe8803ffu, 0u, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array BufferPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array GdsPixelCode{ + 0xbefc03ffu, 0x0000ffffu, 0x7e0002f0u, 0x7e0202f0u, 0xd8fa0010u, 0x04000000u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array StoragePixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e100280u, 0x7e120280u, 0xf0201f08u, + 0x00040008u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array LdsPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e080280u, 0xd8344400u, 0x00000004u, + 0xbf8cc07fu, 0xd8d84400u, 0x00000004u, 0xbf8cc07fu, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(4096) std::array StorageMemory{}; +alignas(256) constexpr std::array SamplingVertexCode{ + 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00820c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, + 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, + 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array InterpolantPixelCode{0xc8020002u, 0xc8060102u, 0xc80a0202u, 0xc80e0302u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array BdaPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0x7e08020cu, 0x7e0a020du, 0xdc308000u, 0x067d0004u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0x7e060306u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TablePixelCode{ + 0xf4200404u, 0xfa000000u, 0xbf8cc07fu, 0x8f108510u, 0xf42c0500u, 0x20000000u, 0xbf8cc07fu, 0x7e0002f0u, + 0x7e0202f0u, 0xf09c0f08u, 0x00250000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TableVertexCode{ + 0xf4200508u, 0xfa000000u, 0xbf8cc07fu, 0x8f148514u, 0xf42c0604u, 0x28000000u, 0xbf8cc07fu, 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, + 0x00660c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, + 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) std::array TableMemory{}; +alignas(256) std::array FreshVertexCode{}; +alignas(256) std::array FreshPixelCode{}; +alignas(256) std::array MaterialMemory{}; +alignas(256) std::array OtherTextureMemory{}; +constexpr float BufferAlpha = 0.2f; +constexpr std::uint8_t BufferAlphaByte = 51u; +constexpr float SecondAlpha = 0.6f; +constexpr std::uint8_t SecondAlphaByte = 153u; +alignas(4096) std::array BufferMemory{}; +alignas(256) std::array ColorMemory{}; + +std::span MergedTarget(std::size_t index) { + constexpr std::size_t Bytes = 65536; + static std::array data{}; + if (data.at(index) == nullptr) data[index] = [] { + std::byte* block = nullptr; +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Bytes, Bytes)); + GuestArena::GuestArenaCommit_nid_postfix(block, Bytes, PAGE_READWRITE, Bytes); +#else + void* raw = mmap(nullptr, 2u * Bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the merged color target"); + const auto begin = reinterpret_cast(raw); + block = reinterpret_cast((begin + Bytes - 1u) & ~static_cast(Bytes - 1u)); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Bytes); +#endif + GuestAllocations::Mutation mutation; + mutation.Add(block, Bytes, true, true, true); + return block; + }(); + return {data[index], ColorMemory.size()}; +} +alignas(256) std::array TextureMemory{}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(Header& header, const std::uint32_t* code, std::size_t bytes, std::uint8_t type) { + header.shader.file_header = 0x34333231u; + header.shader.version = 0x18u; + header.shader.header_size = sizeof(Header); + header.shader.shader_size = static_cast(bytes); + header.shader.code = code; + header.shader.type = type; + header.shader.user_data = &header.userData; + AgcDriverRegisterShader_nid_postfix(&header.shader); +} + +void Append(std::vector& commands, std::uint32_t opcode, std::initializer_list payload) { + commands.push_back(0xc0000000u | (static_cast(payload.size() - 1) << 16u) | (opcode << 8u)); + commands.insert(commands.end(), payload); +} + +enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds, ConstantSampler, BorderSampler, WrapSampler, MergedBlend, MergedBlendOther }; + +const std::uint32_t* VertexProgram(Mode mode) { + if (mode == Mode::VertexTable) return TableVertexCode.data(); + if (mode == Mode::Vertex) return SamplingVertexCode.data(); + return VertexCode.data(); +} + +std::uint32_t PixelUserWords(Mode mode, bool vertexSampling) { + switch (mode) { + case Mode::Storage: + return 24u; + case Mode::Buffer: + case Mode::MovedBuffer: + return 16u; + case Mode::Bda: + return 14u; + default: + return vertexSampling ? 0u : 12u; + } +} + +unsigned ExpectedChannel(Mode mode, bool buffer, std::size_t channel) { + if (mode == Mode::MovedTexture) return 0x33u; + if ((mode == Mode::Bda || mode == Mode::MovedBuffer) && channel == 3) return SecondAlphaByte; + if (buffer && channel == 3) return BufferAlphaByte; + if (mode == Mode::BorderSampler) return 0xffu; + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return std::min(2u * Texel[channel] + static_cast(Kept), 0xffu); + return Texel[channel]; +} + +const char* DrawnWhat(Mode mode, bool buffer) { + if (mode == Mode::Bda) return " (texture and BDA)"; + if (mode == Mode::MovedBuffer) return " (texture and a buffer moved between two draws)"; + if (mode == Mode::MovedTexture) return " (a texture changed between two draws)"; + if (buffer) return " (texture and buffer)"; + if (mode == Mode::Table) return " (image table)"; + if (mode == Mode::ConstantSampler) return " (texture with a constant sampler)"; + if (mode == Mode::BorderSampler) return " (constant border-clamp sampler outside the texture)"; + if (mode == Mode::WrapSampler) return " (constant wrapping sampler outside the texture, after a border-clamp draw of the same shader)"; + if (mode == Mode::MergedBlend) return " (texture blended unclamped into the color target)"; + if (mode == Mode::MergedBlendOther) return " (texture blended unclamped into a second color target)"; + return " (texture)"; +} + +const char* TakenWhat(Mode mode, bool buffer) { + if (buffer) return " reading a buffer"; + if (mode == Mode::Vertex) return " (vertex stage)"; + if (mode == Mode::Bda) return " loading through BDA"; + if (mode == Mode::Table) return " reading an image table"; + if (mode == Mode::VertexTable) return " (vertex stage reading an image table)"; + if (mode == Mode::ConstantSampler || mode == Mode::BorderSampler || mode == Mode::WrapSampler) return " sampling with a constant sampler"; + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return " merging into its color target"; + return ""; +} + +std::array ImageDescriptor(const void* memory) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u}; +} + +std::array BufferDescriptor(const void* memory, std::size_t bytes) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), static_cast(bytes), + 0xfacu}; +} + + +constexpr std::size_t Textures = 16; +constexpr std::size_t Buffers = 32; +alignas(256) std::array, Textures> BenchTextures{}; + +std::vector Frame(std::size_t draws, std::size_t salt) { + const auto color = reinterpret_cast(MergedTarget(0).data()); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, + {0x207, 0}, + {0x200, 0}, + {0x203, 0x800}, + {0x2dc, 0xaa00}, + {0x2f8, 0}, + {0x293, 0}, + {0x80, 0}, + {0x8d, 0}, + {0x83, 0xffff}, + {0x8c, 0xa}, + {0x2f9, 0x2d}, + {0x313, 0x6000}, + {0x30e, 0xffffffff}, + {0x30f, 0xffffffff}, + {0x206, 0x43f}, + {0x204, 0x80000}, + {0x205, 0x240}, + {0x8e, 0xf}, + {0x8f, 0xf}, + {0x202, 0xcc0010}, + {0x1c4, 0}, + {0x1c5, 9}, + {0x1c3, 4}, + {0x31c, 0x28028}, + {0x31b, 0}, + {0x31d, 0}, + {0x3b0, (63u << 14u) | 3u}, + {0x3b8, 0x9000000}, + {0x1e0, 0}, + {0xc, 0}, + {0xd, 0x40040}, + {0x81, 0x80000000}, + {0x82, 0x40040}, + {0x90, 0x80000000}, + {0x91, 0x40040}, + {0x94, 0x80000000}, + {0x95, 0x40040}, + {0x10f, std::bit_cast(32.0f)}, + {0x110, std::bit_cast(32.0f)}, + {0x111, std::bit_cast(-2.0f)}, + {0x112, std::bit_cast(2.0f)}, + {0x113, std::bit_cast(1.0f)}, + {0x114, 0}, + {0xb4, 0}, + {0xb5, std::bit_cast(1.0f)}, + {0x2fe, 0}, + {0x302, 0}, + {0x306, 0}, + {0x30a, 0}, + {0x318, static_cast(color >> 8u)}, + {0x390, static_cast(color >> 40u)}, + {0x292, 2}, + }; + + std::vector commands; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + const auto vertex = reinterpret_cast(VertexCode.data()); + Append(commands, 0x76, {0xc8, static_cast(vertex >> 8u)}); + Append(commands, 0x76, {0xc9, static_cast(vertex >> 40u)}); + Append(commands, 0x76, {0x8b, 1u << 1u}); + Append(commands, 0x76, {0x8c, 0}); + for (std::size_t draw = 0; draw < draws; ++draw) { + const bool buffer = draw % 2u == 1u; + const auto pixel = reinterpret_cast(buffer ? BufferPixelCode.data() : PixelCode.data()); + std::array words{}; + const auto image = ImageDescriptor(BenchTextures[(draw + salt) % Textures].data()); + std::copy(image.begin(), image.end(), words.begin()); + const auto slice = 1u + (draw * 7u + salt) % Buffers; + const auto descriptor = BufferDescriptor(BufferMemory.data() + slice, sizeof(BufferMemory) - slice * sizeof(float)); + std::copy(descriptor.begin(), descriptor.end(), words.begin() + 12); + const std::uint32_t userWords = buffer ? 16u : 12u; + Append(commands, 0x76, {0x008, static_cast(pixel >> 8u)}); + Append(commands, 0x76, {0x009, static_cast(pixel >> 40u)}); + Append(commands, 0x76, {0x00b, userWords << 1u}); + for (std::uint32_t index = 0; index < userWords; ++index) Append(commands, 0x76, {0x00cu + index, words[index]}); + Append(commands, 0x2d, {3, 2}); + } + return commands; +} + +} + +int main(int argc, char** argv) { + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; + const std::size_t draws = argc > 1 ? std::strtoull(argv[1], nullptr, 10) : 4000u; + const std::size_t rounds = argc > 2 ? std::strtoull(argv[2], nullptr, 10) : 12u; + { + GuestAllocations::Mutation mutation; + mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); + } + for (auto& texture : BenchTextures) + for (std::size_t offset = 0; offset < texture.size(); offset += Texel.size()) std::memcpy(texture.data() + offset, Texel.data(), Texel.size()); + BufferMemory.fill(BufferAlpha); + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + static Header TexturePixel{}, BufferPixel{}; + Registered(TexturePixel, PixelCode.data(), sizeof(PixelCode), 1); + Registered(BufferPixel, BufferPixelCode.data(), sizeof(BufferPixelCode), 1); + const auto takenBefore = AgcDriver::DriverDetail::HeapStagesTaken(); + const auto hitsBefore = AgcDriver::VulkanDevice::DrawRecipeHits(); + std::vector perDraw; + for (std::size_t round = 0; round < rounds; ++round) { + auto commands = Frame(draws, round); + const auto start = std::chrono::steady_clock::now(); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the bench submission failed"); + AgcDriverWaitIdle_nid_postfix(); + const auto us = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + if (round >= 2) perDraw.push_back(us / static_cast(draws)); + } + std::sort(perDraw.begin(), perDraw.end()); + const bool tookHeap = AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore; + Require(tookHeap == heap, heap ? "the bench draws did not take the GPU heap" : "the bench draws took the GPU heap with it off"); + const auto hits = AgcDriver::VulkanDevice::DrawRecipeHits() - hitsBefore; + if (rounds > 2 && AgcDriver::Graphics::DrawRecipes() && std::getenv("APS5_VERIFY_DRAW_ENTRIES") == nullptr) + Require(hits >= (rounds - 2) * draws, "the bench's repeated draws replayed " + std::to_string(hits) + " recipes, fewer than the " + std::to_string((rounds - 2) * draws) + " draws of its repeated rounds"); + std::printf("bench %s: %zu draws x %zu rounds: min %.3f us/draw, median %.3f us/draw, heap stages taken %s\n", heap ? "heap" : "per-draw", draws, + perDraw.size(), perDraw.front(), perDraw[perDraw.size() / 2], tookHeap ? "yes" : "no"); + AgcDriverShutdown_nid_postfix(); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/RecipeTemplateAging.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/RecipeTemplateAging.cpp new file mode 100644 index 000000000000..10e32a1b72cc --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/RecipeTemplateAging.cpp @@ -0,0 +1,159 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::size_t Entries = 16; +constexpr std::uint32_t Dispatches = 40; +constexpr std::size_t SrtBytes = 64; +constexpr std::size_t OutputBytes = 256; +constexpr std::size_t SrtOffset = 4096; +constexpr std::size_t OutputOffset = SrtOffset + static_cast(Dispatches) * SrtBytes; +constexpr std::size_t BlockBytes = (OutputOffset + static_cast(Dispatches) * OutputBytes + 65535) & ~static_cast(65535); + +constexpr std::array StoreCode{0xf4080100u, 0xfa000000u, 0xbf8c0000u, 0x7e020281u, 0xe0700000u, 0x80010100u, 0xbf810000u}; + +class GuestBlock { +public: + GuestBlock() { +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(BlockBytes, 65536)); + if (block != nullptr) GuestArena::GuestArenaCommit_nid_postfix(block, BlockBytes, PAGE_READWRITE, BlockBytes); +#else + constexpr std::uintptr_t alignment = 65536; + void* mapped = mmap(nullptr, BlockBytes + alignment, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (mapped != MAP_FAILED) { + const auto begin = reinterpret_cast(mapped); + const auto aligned = (begin + alignment - 1) & ~(alignment - 1); + if (aligned != begin) munmap(mapped, aligned - begin); + if (aligned + BlockBytes != begin + BlockBytes + alignment) munmap(reinterpret_cast(aligned + BlockBytes), begin + alignment - aligned); + block = reinterpret_cast(aligned); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, BlockBytes); + } +#endif + Require(block != nullptr, "recipe template aging: cannot allocate the guest block"); + GuestAllocations::Mutation().Add(block, BlockBytes, true, true, true); + } + + GuestBlock(const GuestBlock&) = delete; + GuestBlock& operator=(const GuestBlock&) = delete; + + std::uint64_t At(std::size_t offset) const { return static_cast(reinterpret_cast(block + offset)); } + std::uint8_t* Bytes(std::size_t offset) const { return block + offset; } + +private: + std::uint8_t* block = nullptr; +}; + +std::vector Pm4(std::uint32_t opcode, std::initializer_list body) { + std::vector words{0xc0000000u | (static_cast(body.size() - 1) << 16u) | (opcode << 8u)}; + words.insert(words.end(), body); + return words; +} + +void Prepare(const GuestBlock& block) { + std::memcpy(block.Bytes(0), StoreCode.data(), sizeof(StoreCode)); + for (std::uint32_t dispatch = 0; dispatch < Dispatches; ++dispatch) { + const auto output = block.At(OutputOffset + static_cast(dispatch) * OutputBytes); + const std::array descriptor{static_cast(output), static_cast((output >> 32u) & 0xffffu), static_cast(OutputBytes), 0x31016facu}; + std::memcpy(block.Bytes(SrtOffset + static_cast(dispatch) * SrtBytes), descriptor.data(), sizeof(descriptor)); + } + std::memset(block.Bytes(OutputOffset), 0, static_cast(Dispatches) * OutputBytes); +} + +void Run(const GuestBlock& block, std::span order) { + const auto kernel = block.At(0); + std::vector words; + for (const auto dispatch : order) { + const auto srt = block.At(SrtOffset + static_cast(dispatch) * SrtBytes); + for (const auto& packet : {Pm4(0x76, {0x20c, static_cast(kernel >> 8u)}), Pm4(0x76, {0x20d, static_cast(kernel >> 40u) & 0xffu}), Pm4(0x76, {0x207, 64}), Pm4(0x76, {0x208, 1}), Pm4(0x76, {0x209, 1}), Pm4(0x76, {0x213, 2u << 1u}), Pm4(0x76, {0x240, static_cast(srt)}), Pm4(0x76, {0x241, static_cast(srt >> 32u)}), Pm4(0x15, {1, 1, 1, 0x41})}) { + words.insert(words.end(), packet.begin(), packet.end()); + } + } + Packet dcb{words.data(), static_cast(words.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&dcb) == 0, "recipe template aging: the dispatch submission failed"); + AgcDriverWaitIdle_nid_postfix(); +} + +void HotTemplateOutlivesChurn(const GuestBlock& block) { + std::vector warm{0, 0, 0}; + Run(block, warm); + std::vector order; + for (std::uint32_t cold = 1; cold < Dispatches; ++cold) { + order.push_back(0); + order.push_back(cold); + } + const auto hot = static_cast(std::count(order.begin(), order.end(), 0u)); + const auto restarts = AgcDriver::VulkanDevice::DispatchRecipeTemplatesGone(); + const auto touches = AgcDriver::Graphics::ResourceCache::Touches(); + for (std::size_t at = 0; at < order.size(); at += 2) Run(block, std::span(order).subspan(at, 2)); + const auto touched = AgcDriver::Graphics::ResourceCache::Touches() - touches; + const auto restarted = AgcDriver::VulkanDevice::DispatchRecipeTemplatesGone() - restarts; + if (!AgcDriver::VulkanDevice::VerifyRecipes()) Require(touched > 0 && touched < hot, "recipe template aging: " + std::to_string(hot) + " recipe hits on the hot dispatch made " + std::to_string(touched) + " cache touches; expected some, and fewer than one per hit"); + Require(restarted == 0, "recipe template aging: the hot dispatch's template aged out of a " + std::to_string(Entries) + "-entry cache under cold dispatches, so " + std::to_string(restarted) + " of its " + std::to_string(hot) + " recipe hits rebuilt"); + for (std::uint32_t dispatch = 0; dispatch < Dispatches; ++dispatch) { + std::uint32_t stored = 0; + AgcDriver::GuestMemory::Read(block.At(OutputOffset + static_cast(dispatch) * OutputBytes), std::as_writable_bytes(std::span(&stored, 1)), 4); + Require(stored == 1u, "recipe template aging: dispatch " + std::to_string(dispatch) + " stored " + std::to_string(stored) + ", expected 1"); + } +} + +} + +int main() { +#ifdef _WIN32 + _putenv_s("APS5_RESOURCE_CACHE_ENTRIES", "16"); +#else + setenv("APS5_RESOURCE_CACHE_ENTRIES", "16", 1); +#endif + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + if (!AgcDriver::VulkanDevice::DispatchRecipes()) { + std::puts("skipped, dispatch recipes are off"); + return VulkanTestSkipped; + } + auto& cache = AgcDriver::Graphics::SharedResourceCache(); + cache.Clear(); + GuestBlock block; + Prepare(block); + HotTemplateOutlivesChurn(block); + AgcDriverShutdown_nid_postfix(); + std::puts("a hot dispatch served by recipes kept its template in a churning resource cache with fewer touches than hits"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + AgcDriverShutdown_nid_postfix(); + return 1; + } +} diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 6ea5047502eb..d2b173f342f2 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -2538,18 +2538,18 @@ void CompleteHeapDataWords(const RecompileResult& shared, HeapStageWords& words) const auto& binding = shared.bindings[index]; if (binding.role != DescriptorRole::ShaderData && binding.role != DescriptorRole::FlattenedSrt) continue; if (!words.bindings.empty() && !words.bindings[index].empty()) continue; - std::vector descriptor; if (binding.role == DescriptorRole::FlattenedSrt) { if (words.flattenedSrt.empty() || words.flattenedSrt == binding.guestDescriptor) continue; - descriptor = words.flattenedSrt; + if (words.bindings.empty()) words.bindings.resize(count); + words.bindings[index].assign(words.flattenedSrt.begin(), words.flattenedSrt.end()); } else { const auto patched = std::min(words.userData.size(), binding.guestDescriptor.size()); if (std::equal(words.userData.begin(), words.userData.begin() + static_cast(patched), binding.guestDescriptor.begin())) continue; - descriptor = binding.guestDescriptor; + if (words.bindings.empty()) words.bindings.resize(count); + auto& descriptor = words.bindings[index]; + descriptor.assign(binding.guestDescriptor.begin(), binding.guestDescriptor.end()); std::copy_n(words.userData.begin(), patched, descriptor.begin()); } - if (words.bindings.empty()) words.bindings.assign(count, {}); - words.bindings[index] = std::move(descriptor); } } diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 85d0af27a19e..7cfd27754039 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -499,11 +499,23 @@ struct HeapTemplateCacheCounts { }; HeapTemplateCacheCounts HeapTemplateCounts(); +struct ResultKeyMemo { + mutable AtomicSharedPtr> words; + ResultKeyMemo() = default; + ResultKeyMemo(const ResultKeyMemo&) {} + ResultKeyMemo& operator=(const ResultKeyMemo&) { + words.store(nullptr, std::memory_order_relaxed); + return *this; + } +}; + struct HeapStageWords { std::vector userData; std::vector flattenedSrt; std::vector vertexAttributes; std::vector> bindings; + ResultKeyMemo drawKeyMemo; + bool memoizeKey = true; }; struct RecompileRequest { @@ -849,16 +861,6 @@ struct PipelineIdentity { auto operator<=>(const PipelineIdentity&) const = default; }; -struct ResultKeyMemo { - mutable AtomicSharedPtr> words; - ResultKeyMemo() = default; - ResultKeyMemo(const ResultKeyMemo&) {} - ResultKeyMemo& operator=(const ResultKeyMemo&) { - words.store(nullptr, std::memory_order_relaxed); - return *this; - } -}; - struct RecompileResult : CompiledShaderArtifact, ShaderInvocation { std::uint64_t heapTemplateId = 0; std::vector heapUserWords; diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index 276795b47417..df5f32138f37 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -9,7 +9,7 @@ namespace ShaderRecompiler::RuntimeAbi { -inline constexpr std::uint32_t Version = 15u; +inline constexpr std::uint32_t Version = 16u; inline constexpr std::uint32_t DescriptorSet = 0u; inline constexpr std::uint32_t FragmentDescriptorSet = 1u; inline constexpr std::uint32_t StageCount = 4u; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index b809cc263b38..17653b7cadce 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -240,6 +240,7 @@ struct SpirvEmitterState { std::unordered_map heapSlotVariables; std::uint32_t flattenedSrtVariable = 0; bool flattenedSrtAddressed = false; + bool flattenedSrtPushed = false; std::uint32_t ldsVariable = 0; std::uint32_t ldsBufferVariable = 0; std::uint32_t ldsBufferU64Variable = 0; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 84a74cfe9799..192b88ea93bc 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -167,11 +167,18 @@ std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index return Select(state, u32, inBounds, dataAddressLoad(state, RuntimeAbi::RootItem::SrtAddress, clamped), ConstantU32(state, 0u)); } if (state.flattenedSrtVariable == 0) FailEmit("the flattened SRT descriptor is missing"); + const auto u32 = TypeU32(state); + std::uint32_t inBounds = 0; + if (state.flattenedSrtPushed) { + const auto dwords = EmitRootItemDword(state, RuntimeAbi::RootItem::SrtDwords, 0u); + inBounds = Binary(state, spv::OpULessThan, TypeBool(state), index, dwords); + index = Select(state, u32, inBounds, index, ConstantU32(state, 0u)); + } const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.flattenedSrtVariable, ConstantU32(state, 0u), index); const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); - return value; + state.module.AddFunction(spv::OpLoad, u32, value, pointer); + return inBounds != 0 ? Select(state, u32, inBounds, value, ConstantU32(state, 0u)) : value; } std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dwordIndex) { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index ee376662ce47..9d6e683a435a 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -560,8 +560,9 @@ void DefineDescriptors(SpirvEmitterState& state) { if (layout.UsesDataAddress() && !state.heapBufferDescriptors) state.flattenedSrtAddressed = true; else { state.flattenedSrtVariable = Define(StorageBufferBlockType(state), "flattened_srt"); - if (layout.UsesDataAddress()) state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::FlattenedSrt); - if (!layout.UsesDataAddress()) state.module.AddAnnotation(spv::OpDecorate, state.flattenedSrtVariable, spv::DecorationNonWritable); + state.flattenedSrtPushed = layout.UsesDataAddress(); + if (state.flattenedSrtPushed) state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::SrtAddress); + else state.module.AddAnnotation(spv::OpDecorate, state.flattenedSrtVariable, spv::DecorationNonWritable); } break; case DescriptorBindingKind::Samplers: From b181b635f9d18c3d6b8222d83e7edd9b58e10980 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 6 Nov 2026 23:38:11 +0530 Subject: [PATCH 132/269] test(agc): fix the AGC tests that fail with APS5_GPU_HEAP set - The image memory, multisampled pass order, pass break reason and HTILE mask lifetime tests create their own recorders. They now create them with a timeline semaphore, which the GPU heap requires. - agc_driver_lazy_resolved_abi expected a heap-mode draw to use and prepare two shader variants. Without the per-draw fallback a draw uses only its heap variant, in both modes one entry. --- .../tests/execution/DepthFastClearSubmit.cpp | 18 +++++++++--------- .../tests/execution/ImageMemory.cpp | 2 +- .../tests/execution/LazyResolvedAbi.cpp | 8 ++++---- .../tests/execution/MultisampledPassOrder.cpp | 2 +- .../tests/execution/PassBreakReasons.cpp | 2 +- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp index 07073f1b706e..d275bec8559b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp @@ -365,14 +365,14 @@ void RecreatedRecorderReadsHtile(AgcDriver::VulkanDevice& device, bool clearSurf auto& htile = NewBlock(); const DepthTarget target{NewBlock().Address(), 0, {64, 32}, VK_FORMAT_D32_SFLOAT, 1.0f, 0, htile.Address(), false}; std::optional recorder; - recorder.emplace(context); + recorder.emplace(context, true); const auto* address = &*recorder; RecordHtileWords(context, *recorder, htile, 0xf0u); const auto note = recorder->NewestWriteNote(htile.Address(), HtileBytes); NoteHtileMaskOnGpu(context, {htile.Address(), HtileBytes, 0x3f0u, 0u}); recorder.reset(); if (clearSurfaces) ClearDepthSurfaces(context.device); - recorder.emplace(context); + recorder.emplace(context, true); Require(&*recorder == address, "the replacement recorder did not reuse the original storage"); RecordHtileWords(context, *recorder, htile, 0xfu); Require(recorder->NewestWriteNote(htile.Address(), HtileBytes) == note, "the replacement recorder did not reuse the original note"); @@ -411,8 +411,8 @@ void LiveRecorderMaskIsolation(AgcDriver::VulkanDevice& device) { auto* previous = Recorder::Active(); { auto& htile = NewBlock(); - Recorder first(context); - Recorder second(context); + Recorder first(context, true); + Recorder second(context, true); RecordHtileWords(context, first, htile, 0xf0u); NoteHtileMaskOnGpu(context, {htile.Address(), HtileBytes, 0x3f0u, 0u}); RecordHtileWords(context, second, htile, 0xfu); @@ -437,8 +437,8 @@ void MaskCleanupIsolation(AgcDriver::VulkanDevice& device, AgcDriver::VulkanDevi auto& firstHtile = NewBlock(); auto& secondHtile = NewBlock(); std::optional first; - first.emplace(context); - Recorder second(context); + first.emplace(context, true); + Recorder second(context, true); RecordHtileWords(context, *first, firstHtile, 0xf0u); NoteHtileMaskOnGpu(context, {firstHtile.Address(), HtileBytes, 0x3f0u, 0u}); RecordHtileWords(context, second, secondHtile, 0xf0u); @@ -450,9 +450,9 @@ void MaskCleanupIsolation(AgcDriver::VulkanDevice& device, AgcDriver::VulkanDevi auto& firstHtile = NewBlock(); auto& secondHtile = NewBlock(); auto& otherHtile = NewBlock(); - Recorder first(context); - Recorder second(context); - Recorder other(otherContext); + Recorder first(context, true); + Recorder second(context, true); + Recorder other(otherContext, true); RecordHtileWords(context, first, firstHtile, 0xf0u); NoteHtileMaskOnGpu(context, {firstHtile.Address(), HtileBytes, 0x3f0u, 0u}); RecordHtileWords(context, second, secondHtile, 0xf0u); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageMemory.cpp index cebd944bc215..1c6971e819a6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageMemory.cpp @@ -352,7 +352,7 @@ bool SampledImages(const Context& context, TextureDetiler& detiler, Hooks& nativ std::vector> textures; bool covered = true; { - Recorder recorder(context); + Recorder recorder(context, true); recorder.Activate(); for (std::size_t i = 0; i < ImageCount; ++i) { auto texture = std::make_unique(context, detiler, resource, identity, snapshot); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp index d76c22181b04..391b5b35a275 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/LazyResolvedAbi.cpp @@ -557,11 +557,11 @@ void LazyResolution(const Layout& layout, const std::filesystem::path& reference Require(unmatched.firstUses - start.firstUses == Drawn && unmatched.own - start.own == Drawn && unmatched.found == start.found, "lazy resolved ABI: draws whose state differs from the resolved ABI did not count as preparing their own artifact (before: " + Uses(start) + "; after: " + Uses(unmatched) + ")"); Require(unmatched.entries > start.entries && unmatched.unmatchedEntries - start.unmatchedEntries == unmatched.entries - start.entries, "lazy resolved ABI: entries prepared for an ABI no draw used do not count as unmatched (before: " + Uses(start) + "; after: " + Uses(unmatched) + ")"); Require(matched.firstUses == unmatched.firstUses + 1 && matched.found == unmatched.found + 1 && matched.own == unmatched.own, "lazy resolved ABI: a draw whose state matches the resolved ABI did not count as finding its artifact (before: " + Uses(unmatched) + "; after: " + Uses(matched) + ")"); - const std::uint64_t usedVariants = AgcDriver::Graphics::DescriptorHeapEnabled() ? 2u : 1u; - Require(matched.entries > unmatched.entries && matched.unmatchedEntries == unmatched.unmatchedEntries + (matched.entries - unmatched.entries) - usedVariants, "lazy resolved ABI: the entry a matching draw used still counts as unmatched (before: " + Uses(unmatched) + "; after: " + Uses(matched) + ")"); + constexpr std::uint64_t drawVariants = 1u; + Require(matched.entries > unmatched.entries && matched.unmatchedEntries == unmatched.unmatchedEntries + (matched.entries - unmatched.entries) - drawVariants, "lazy resolved ABI: the entry a matching draw used still counts as unmatched (before: " + Uses(unmatched) + "; after: " + Uses(matched) + ")"); for (const auto index : {Matching, Twice, Replaced}) Require(eager.at("drawn " + std::to_string(index)) == eager.at("resolved " + std::to_string(index)), "lazy resolved ABI: shader " + std::to_string(index) + ", drawn with its resolved ABI's state, did not find the ABI's entries with eager preparation"); - for (std::uint32_t index = 0; index < Drawn; ++index) Require(Count(eager.at("drawn " + std::to_string(index))) == Count(eager.at("resolved " + std::to_string(index))) + usedVariants, "lazy resolved ABI: a draw whose state differs from its resolved ABI did not prepare its own entry with eager preparation"); - Require(Count(eager.at("drawn " + std::to_string(Replacement))) == Count(eager.at("registered " + std::to_string(Replacement))) + usedVariants, "lazy resolved ABI: the header registered over a resolved one did not prepare its own entry at its draw with eager preparation"); + for (std::uint32_t index = 0; index < Drawn; ++index) Require(Count(eager.at("drawn " + std::to_string(index))) == Count(eager.at("resolved " + std::to_string(index))) + drawVariants, "lazy resolved ABI: a draw whose state differs from its resolved ABI did not prepare its own entry with eager preparation (shader " + std::to_string(index) + ": drawn " + std::to_string(Count(eager.at("drawn " + std::to_string(index)))) + ", resolved " + std::to_string(Count(eager.at("resolved " + std::to_string(index)))) + ", expected " + std::to_string(drawVariants) + " more)"); + Require(Count(eager.at("drawn " + std::to_string(Replacement))) == Count(eager.at("registered " + std::to_string(Replacement))) + drawVariants, "lazy resolved ABI: the header registered over a resolved one did not prepare its own entry at its draw with eager preparation"); Require(lazy.at("libraries drawn") == eager.at("libraries drawn"), "lazy resolved ABI: the pipeline libraries built differ from eager preparation (eager " + eager.at("libraries drawn") + "; lazy " + lazy.at("libraries drawn") + ")"); Require(first == expected, "lazy resolved ABI: the shader prepared at its first draw drew other bytes than with eager preparation"); AgcDriverWaitIdle_nid_postfix(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampledPassOrder.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampledPassOrder.cpp index 2075a2e2c8d6..ed6b55087c09 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampledPassOrder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampledPassOrder.cpp @@ -128,7 +128,7 @@ int main() { device->WaitIdle(); std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); const auto captured = Capture::Install(base); - Recorder recorder(captured); + Recorder recorder(captured, true); recorder.Activate(); const auto depthA = reinterpret_cast(DepthA.data()); const auto depthB = reinterpret_cast(DepthB.data()); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PassBreakReasons.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PassBreakReasons.cpp index 91a050e46947..85b3e6f20424 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PassBreakReasons.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PassBreakReasons.cpp @@ -119,7 +119,7 @@ int main() { const auto shaders = Compile(*device); device->WaitIdle(); std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); - Recorder recorder(context); + Recorder recorder(context, true); recorder.Activate(); const auto depthA = reinterpret_cast(DepthA.data()); const auto depthB = reinterpret_cast(DepthB.data()); From 165df4827a476c603500b8d21e9b9dc2abf931b7 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 7 Nov 2026 11:07:53 +0530 Subject: [PATCH 133/269] fix(agc): read dynamic-resolution variants from the stage's own image table words A GPU-heap stage built from a shared heap template resolves its image table from the stage's own words (DrawGuestWords), but the variant families, the chosen representative and the words bound for a borrowing entry were read from binding.guestDescriptor, the words of the draw that built the template. Entries that were variants in this stage were not merged, and entries the template saw as variants borrowed another surface's texture. variantRepresentatives now reads the table's image words, the substitution binds the representative's words from them, and heap tables get no capacity limit, as in the rest of resolveImageTables. The surface presync fallback for a compute stage whose image records were not collected also decodes the stage's own image and image table words instead of the template's. agc_driver_image_table_variants runs in GPU heap mode too and builds a heap stage from a template whose table words differ from the stage's, both ways round. Reported by muhmuhkuh on #9508. --- .../Graphics/src/ShaderResources.cpp | 24 ++++++----- ...gc_driver_image_table_variants_tests.cmake | 3 ++ .../tests/execution/ImageTableVariants.cpp | 42 ++++++++++++++++++- 3 files changed, 56 insertions(+), 13 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_variants_tests.cmake diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 7eaf469565e8..897d84739e75 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -5260,12 +5260,13 @@ namespace { // Calls `visit(binding, element, words)` for every sampled and storage image element of a compiled // shader's bindings, in plan order (the order addImageBinding and resolveImageBinding walk). template -void forEachImageElement(const ShaderRecompiler::RecompileResult& program, Visit&& visit) { - for (const auto& binding : program.bindings) { +void forEachImageElement(const CompiledShader& shader, Visit&& visit) { + for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages || binding.count == 0) continue; if (binding.kind != ShaderRecompiler::DescriptorKind::SampledImage && binding.kind != ShaderRecompiler::DescriptorKind::StorageImage) continue; - const auto elementWords = binding.guestDescriptor.size() / binding.count; - for (std::uint32_t element = 0; element < binding.count; ++element) visit(binding, element, std::span(binding.guestDescriptor).subspan(static_cast(element) * elementWords, elementWords)); + const auto& words = DrawGuestWords(shader, binding); + const auto elementWords = words.size() / binding.count; + for (std::uint32_t element = 0; element < binding.count; ++element) visit(binding, element, std::span(words).subspan(static_cast(element) * elementWords, elementWords)); } } @@ -5731,7 +5732,7 @@ void noteVariantSurface(std::uint64_t address, std::size_t members, const GuestT std::fprintf(stderr, "[textures] surface 0x%llx has %zu dynamic-resolution variants in one image table; they share the %ux%u texture (chosen by %s)\n", static_cast(address), members, chosen.width, chosen.height, rule); } -std::vector variantRepresentatives(VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, std::uint64_t elementBase, std::uint64_t capacity) { +std::vector variantRepresentatives(VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, std::span imageWords, std::uint64_t elementBase, std::uint64_t capacity) { struct Member { std::uint32_t element; GuestTextureResource resource; @@ -5740,7 +5741,7 @@ std::vector variantRepresentatives(VkDevice device, const ShaderR std::map> families; for (std::uint32_t element = 0; element < binding.count && elementBase + element < capacity; ++element) { if (element < binding.imageWritten.size() && binding.imageWritten[element]) continue; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(element) * 8u, 8u); + const auto words = imageWords.subspan(static_cast(element) * 8u, 8u); GuestTextureResource resource{}; try { if (IsNullTextureResource(words)) continue; @@ -5883,7 +5884,7 @@ void ShaderResources::resolveImageTables() { ReusedTable fresh; fresh.bound.assign(binding.count, {}); bool reusable = state.epoch != 0; - const auto representatives = binding.count > 1 ? variantRepresentatives(context.device, binding, table.elementBase, context.imageTableCapacity) : std::vector{}; + const auto representatives = binding.count > 1 ? variantRepresentatives(context.device, binding, table.imageWords, table.elementBase, table.heap ? std::numeric_limits::max() : context.imageTableCapacity) : std::vector{}; std::vector representativeNeeded(representatives.size(), false); for (const auto representative : representatives) { if (representative != NoRepresentative) representativeNeeded[representative] = true; @@ -5997,7 +5998,7 @@ void ShaderResources::resolveImageTables() { } for (const auto element : substitutes) { const auto representative = representatives[element]; - const auto words = std::span(binding.guestDescriptor).subspan(static_cast(representative) * 8u, 8u); + const auto words = table.imageWords.subspan(static_cast(representative) * 8u, 8u); const auto index = table.elementTextures[representative]; const auto source = representativeSources.find(representative); if (index == std::numeric_limits::max() || source == representativeSources.end()) { @@ -6148,7 +6149,7 @@ std::vector ShaderResources::PresyncSurfaces() const { } // Stage A has not run (an address-based build, or the pass is off): decoded from the shader. if (deferredCompute.program == nullptr) return surfaces; - forEachImageElement(*deferredCompute.program, [&](const ShaderRecompiler::DescriptorBinding& binding, std::uint32_t, std::span words) { + forEachImageElement(deferredCompute, [&](const ShaderRecompiler::DescriptorBinding& binding, std::uint32_t, std::span words) { if (IsNullTextureResource(words)) return; const auto resource = DecodeTextureResource(words); const auto guestBytes = DescribeSurface(resource).guestBytes; @@ -6157,9 +6158,10 @@ std::vector ShaderResources::PresyncSurfaces() const { }); for (const auto& binding : deferredCompute.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::ImageTable) continue; - for (std::size_t element = 0; element < binding.guestDescriptor.size() / 8u; ++element) { + const auto& words = DrawGuestWords(deferredCompute, binding); + for (std::size_t element = 0; element < words.size() / 8u; ++element) { try { - const auto resource = DecodeTextureResource(std::span(binding.guestDescriptor).subspan(element * 8u, 8u)); + const auto resource = DecodeTextureResource(std::span(words).subspan(element * 8u, 8u)); const auto guestBytes = DescribeSurface(resource).guestBytes; consider(resource.format, resource.baseAddress, guestBytes, true); considerKeys(resource.dccAddress, guestBytes); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_variants_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_variants_tests.cmake new file mode 100644 index 000000000000..ef34a6f33f6d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_variants_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_image_table_variants) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableVariants.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableVariants.cpp index 6a45ae427280..8c31dafe553d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableVariants.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableVariants.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" @@ -176,7 +177,7 @@ void FillTable(const GuestBlock& block) { } } -ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const GuestBlock& table, std::span code = TableCode) { +ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const GuestBlock& table, std::span code = TableCode, bool heap = false) { const auto srtAddress = AddressOf(Srt.data()); const std::array userData{static_cast(srtAddress), static_cast(srtAddress >> 32u)}; const std::span words(table.Table(), Records * Stride / 4u); @@ -187,12 +188,16 @@ ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const {AddressOf(Keys.data()), std::as_bytes(std::span(Keys))}, }}; const ShaderRecompiler::ShaderComputeStageInfo compute{{Lanes, 1, 1}, 0u, {true, false, false}, false, 1}; - const ShaderRecompiler::RecompileRequest request{ + ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, AddressOf(code.data()), code, 0, {}}, {64, 0, userData, compute, std::nullopt, std::nullopt, memory}, device.Target(), {0, 0, 0, 128} }; + if (heap) { + request.target.gpuResolvedImages = true; + request.useCache = false; + } auto result = ShaderRecompiler::Recompile(request); const auto binding = std::find_if(result.bindings.begin(), result.bindings.end(), [](const ShaderRecompiler::DescriptorBinding& candidate) { return candidate.role == ShaderRecompiler::DescriptorRole::ImageTable; }); Require(binding != result.bindings.end() && binding->guestDescriptor.size() == static_cast(Records) * 8u, "image table variants: the shader does not bind the whole table"); @@ -349,6 +354,38 @@ void RunRejected(AgcDriver::VulkanDevice& device, const GuestBlock& block) { AgcDriver::Graphics::ClearDepthSurfaces(device.Device()); } +const std::vector& TableWords(const ShaderRecompiler::RecompileResult& result) { + const auto binding = std::find_if(result.bindings.begin(), result.bindings.end(), [](const ShaderRecompiler::DescriptorBinding& candidate) { return candidate.role == ShaderRecompiler::DescriptorRole::ImageTable; }); + return binding->guestDescriptor; +} + +void HeapStageWithOtherWords(AgcDriver::VulkanDevice& device, const GuestBlock& block, bool templateVariants, std::uint64_t substituted, const std::string& what) { + Prepare(block); + SetRecord(block, 1, templateVariants ? block.Texels(0) : block.Texels(1), templateVariants ? Narrow : Wide); + const auto shared = Compile(device, block, TableCode, true); + Require(shared.gpuResolvedImages, "image table variants: the heap compile did not make a GPU-mode program"); + SetRecord(block, 1, templateVariants ? block.Texels(1) : block.Texels(0), templateVariants ? Wide : Narrow); + const auto own = Compile(device, block); + Require(TableWords(shared) != TableWords(own), "image table variants: the template and the stage read the same image table words"); + ShaderRecompiler::HeapStageWords words; + words.bindings.resize(shared.bindings.size()); + const auto table = std::find_if(shared.bindings.begin(), shared.bindings.end(), [](const ShaderRecompiler::DescriptorBinding& candidate) { return candidate.role == ShaderRecompiler::DescriptorRole::ImageTable; }); + words.bindings[static_cast(table - shared.bindings.begin())] = TableWords(own); + const AgcDriver::Graphics::CompiledShader stage{ShaderStage::Compute, &shared, 0, nullptr, &words}; + AgcDriver::GuestMemory::BumpCollectEpoch(); + const auto before = AgcDriver::Graphics::ImageTableReuses(); + { + AgcDriver::Graphics::ShaderResources resources(device.graphicsContext(), stage); + } + Expect(before, substituted, substituted, 0, what); +} + +void RunHeapWords(AgcDriver::VulkanDevice& device, const GuestBlock& block) { + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) return; + HeapStageWithOtherWords(device, block, false, 1, "a heap stage whose own image table words make an entry a variant, built from a template whose words keep them apart"); + HeapStageWithOtherWords(device, block, true, 0, "a heap stage whose own image table words keep two entries apart, built from a template whose words made one a variant"); +} + void RunTests(AgcDriver::VulkanDevice& device, const GuestBlock& block) { RunLargest(device, block); RunWritten(device, block); @@ -356,6 +393,7 @@ void RunTests(AgcDriver::VulkanDevice& device, const GuestBlock& block) { RunSize(device, block); RunDepth(device, block); RunRejected(device, block); + RunHeapWords(device, block); } } From c07611f18dc1984df845e714542502b5a5a71d83 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 7 Nov 2026 12:37:49 +0530 Subject: [PATCH 134/269] perf(agc): write GPU heap data spans with sequential stores The GPU heap's shader data pool sits in device-local host-visible memory, as vkd3d-proton places its upload and descriptor memory on a large BAR. std::memcpy writes small spans there with overlapping unaligned stores, which the CPU's write-combining buffers flush as partial lines. Spans are now written with sequential 16-byte stores (BindlessHeap::Write). Offline draw bench with GTA V-shaped draws (a local variant), heap mode, median of five interleaved runs: 6.68 -> 6.25 us per draw. --- .../Graphics/include/BindlessHeap.hpp | 1 + .../Graphics/src/BindlessHeap.cpp | 17 +++++++++++++++++ .../Graphics/src/ShaderResources.cpp | 4 ++-- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 93dc2501064e..cdfabd7d3e58 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -92,6 +92,7 @@ class BindlessHeap { }; DataSpan Allocate(std::size_t words, SpanMark& mark); DataSpan RingAllocate(std::size_t words, SpanMark& mark); + static void Write(const DataSpan& span, std::span words); bool Held(const SpanMark& mark); std::optional KeepOrAllocate(std::size_t words, SpanMark& mark, bool same); std::uint32_t RingBufferDescriptors(std::span buffers, SpanMark& mark); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index ad62ab076ace..30b97dfb189b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -27,6 +27,10 @@ #include #include +#if defined(__SSE2__) || defined(_M_X64) +#include +#endif + namespace AgcDriver::Graphics { namespace { @@ -763,6 +767,19 @@ bool BindlessHeap::heldLocked(const SpanMark& mark) { return true; } +void BindlessHeap::Write(const DataSpan& span, std::span words) { + Require(words.size() <= span.words.size(), "the words written to a GPU heap span exceed it"); +#if defined(__SSE2__) || defined(_M_X64) + std::size_t index = 0; + for (; index + 4u <= words.size(); index += 4u) + _mm_storeu_si128(reinterpret_cast<__m128i*>(span.words.data() + index), _mm_loadu_si128(reinterpret_cast(words.data() + index))); + auto* tail = reinterpret_cast(span.words.data()); + for (; index < words.size(); ++index) tail[index] = words[index]; +#else + std::memcpy(span.words.data(), words.data(), words.size() * sizeof(std::uint32_t)); +#endif +} + BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) { std::lock_guard lock(mutex); return allocateLocked(words, mark); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 897d84739e75..c59178228e69 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6646,7 +6646,7 @@ std::array ShaderR auto words = stageDataWords[stage]; writeBufferAddresses(words, static_cast(stage), overrides); auto span = heap.Allocate(words.size()); - std::memcpy(span.words.data(), words.data(), words.size() * sizeof(std::uint32_t)); + BindlessHeap::Write(span, words); offsets[stageDataIndex[stage]] = span.address; } for (std::size_t stage = 0; stage < ringDescriptorStages.size(); ++stage) { @@ -7000,7 +7000,7 @@ std::uint64_t ShaderResources::heapSpan(HeapStageState::KeptSpan& kept, std::spa auto& heap = BindlessHeap::For(context); const auto span = heap.KeepOrAllocate(words.size(), kept.mark, std::ranges::equal(kept.words, words)); if (!span) return kept.mark.address; - std::memcpy(span->words.data(), words.data(), words.size() * sizeof(std::uint32_t)); + BindlessHeap::Write(*span, words); kept.words.assign(words.begin(), words.end()); return span->address; } From b3faf282fa58613793222186f2973d60148cf2ba Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 7 Nov 2026 13:04:06 +0530 Subject: [PATCH 135/269] perf(agc): hold the GPU heap span allocator for a whole stage write Each data span and descriptor run a heap stage wrote took and released the heap mutex, a locked instruction right after write-combined stores into the BAR-mapped heap. A locked instruction waits for those stores to drain, so every span paid the PCIe write latency on the committer: with the lock made a no-op the GTA V-shaped offline bench got 0.42 us/draw faster, and a full fence after each span write (no lock) made it 0.65 us slower than that. The data pool and descriptor ring now have their own mutex, held through BindlessHeap::SpanScope for a whole heap stage refresh or moved-buffer rewrite, the way a vkd3d-proton command list owns its allocator while it records. Span calls inside the scope check the owning thread and take no lock; outside a scope they lock as before. Slot state keeps the old mutex, and Submitted() takes the two in turn, never nested. Offline draw bench with GTA V-shaped draws (a local variant), heap mode, median of four interleaved runs: 6.09 -> 5.78 us per draw (the no-lock bound is 5.63). --- .../Graphics/include/BindlessHeap.hpp | 14 +++++ .../Graphics/src/BindlessHeap.cpp | 53 ++++++++++++------- .../Graphics/src/ShaderResources.cpp | 7 ++- .../tests/BindlessHeapSlots.cpp | 44 +++++++++++++++ 4 files changed, 99 insertions(+), 19 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index cdfabd7d3e58..a9c25a5fb338 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -94,6 +95,17 @@ class BindlessHeap { DataSpan RingAllocate(std::size_t words, SpanMark& mark); static void Write(const DataSpan& span, std::span words); bool Held(const SpanMark& mark); + class SpanScope { + public: + explicit SpanScope(const BindlessHeap& heap); + ~SpanScope(); + SpanScope(const SpanScope&) = delete; + SpanScope& operator=(const SpanScope&) = delete; + + private: + const BindlessHeap& heap; + bool acquired; + }; std::optional KeepOrAllocate(std::size_t words, SpanMark& mark, bool same); std::uint32_t RingBufferDescriptors(std::span buffers, SpanMark& mark); static constexpr std::uint32_t BufferSlotBytes = 16u; @@ -174,6 +186,8 @@ class BindlessHeap { void trimPoolLocked(); std::uint32_t ringAlignment = 256; mutable std::mutex mutex; + mutable std::mutex spanMutex; + mutable std::atomic spanOwner{}; struct EmbeddedSampler { VkSamplerCreateInfo info{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; VkSamplerReductionModeCreateInfoEXT reduction{VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 30b97dfb189b..d28569b81115 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -733,9 +733,21 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words) { return Allocate(words, mark); } +BindlessHeap::SpanScope::SpanScope(const BindlessHeap& heap) : heap(heap), acquired(heap.spanOwner.load(std::memory_order_relaxed) != std::this_thread::get_id()) { + if (!acquired) return; + heap.spanMutex.lock(); + heap.spanOwner.store(std::this_thread::get_id(), std::memory_order_relaxed); +} + +BindlessHeap::SpanScope::~SpanScope() { + if (!acquired) return; + heap.spanOwner.store(std::thread::id{}, std::memory_order_relaxed); + heap.spanMutex.unlock(); +} + bool BindlessHeap::Held(const SpanMark& mark) { if (mark.entry == 0u || mark.words == 0u) return false; - std::lock_guard lock(mutex); + SpanScope scope(*this); return heldLocked(mark); } @@ -781,12 +793,12 @@ void BindlessHeap::Write(const DataSpan& span, std::span wo } BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) { - std::lock_guard lock(mutex); + SpanScope scope(*this); return allocateLocked(words, mark); } std::optional BindlessHeap::KeepOrAllocate(std::size_t words, SpanMark& mark, bool same) { - std::lock_guard lock(mutex); + SpanScope scope(*this); if (same && heldLocked(mark)) return std::nullopt; return allocateLocked(words, mark); } @@ -890,13 +902,13 @@ bool BindlessHeap::TakeSlotPressure() { bool BindlessHeap::TakeRingPressure() { if (ringChunks.empty() || ringOpenChunks.load(std::memory_order_relaxed) < std::max(2u, ringChunks.size() / 2u)) return false; - std::lock_guard lock(mutex); + SpanScope scope(*this); ++counts.ringPressureSubmits; return true; } std::pair BindlessHeap::DataLocation(VkDeviceAddress address) const { - std::lock_guard lock(mutex); + SpanScope scope(*this); for (const auto& block : poolBlocks) { if (block.buffer != nullptr && address >= block.address && address < block.address + block.bytes) return {block.buffer->Handle(), address - block.address}; } @@ -907,7 +919,7 @@ BindlessHeap::DataSpan BindlessHeap::RingAllocate(std::size_t words, SpanMark& m Require(ringInHeap, "the GPU heap has no descriptor ring"); const auto bytes = alignUp(words * sizeof(std::uint32_t), RingSpanAlignment); if (bytes > ringBytes / 4u) throw std::runtime_error("AGC bindless heap: one draw's buffer descriptors exceed a quarter of the descriptor ring"); - std::lock_guard lock(mutex); + SpanScope scope(*this); auto offset = wrapRingOffset(alignUp(ringCursor, ringAlignment), bytes); enum class Taken { No, Kept, Busy }; const auto taken = [&](bool skipBusy) { @@ -1345,6 +1357,7 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::uint32_t BindlessHeap::RingBufferDescriptors(std::span buffers, SpanMark& mark) { Require(ringInHeap && context.descriptorHeapProperties.bufferDescriptorSize == BufferSlotBytes, "ring buffer descriptors need the descriptor ring inside the resource heap"); + SpanScope scope(*this); const auto span = RingAllocate(buffers.size() * (BufferSlotBytes / sizeof(std::uint32_t)), mark); counts.bufferDescriptors += buffers.size(); Require(span.offset % BufferSlotBytes == 0u, "a ring buffer descriptor span is misaligned"); @@ -1706,20 +1719,23 @@ void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { if (!recorder.HasTimeline()) throw std::runtime_error("AGC bindless heap: a batch using the heap was submitted by a recorder without a timeline semaphore"); - std::lock_guard lock(mutex); - submitter = &recorder; - useEpoch.fetch_add(1, std::memory_order_relaxed); + { + std::lock_guard lock(mutex); + submitter = &recorder; + useEpoch.fetch_add(1, std::memory_order_relaxed); + if (refused && imagePool.Unused() + imageRetiring() < 2u * static_cast(imageMargin())) evictLocked(EvictIdleSubmissions); + if (refused && samplerPool.Unused() + retiringSamplers < 2u * SamplerSlotMargin) evictSamplersLocked(EvictIdleSubmissions); + for (auto entry = retiring.rbegin(); entry != retiring.rend() && entry->serial == 0u; ++entry) { + entry->serial = serial; + if (entry->sampler) ++samplerRetiringAssigned; + else ++retiringAssigned; + } + if (!retiring.empty()) reclaimLocked(false); + noteReleasedLocked(); + } + SpanScope scope(*this); counts.ringBatchPeakBytes = std::max(counts.ringBatchPeakBytes, ringBatchBytes); ringBatchBytes = 0; - if (refused && imagePool.Unused() + imageRetiring() < 2u * static_cast(imageMargin())) evictLocked(EvictIdleSubmissions); - if (refused && samplerPool.Unused() + retiringSamplers < 2u * SamplerSlotMargin) evictSamplersLocked(EvictIdleSubmissions); - for (auto entry = retiring.rbegin(); entry != retiring.rend() && entry->serial == 0u; ++entry) { - entry->serial = serial; - if (entry->sampler) ++samplerRetiringAssigned; - else ++retiringAssigned; - } - if (!retiring.empty()) reclaimLocked(false); - noteReleasedLocked(); for (std::size_t index = 0; index < ringChunks.size(); ++index) { if (!ringChunks[index].open && index != ringChunk) continue; ringChunks[index].recorder = &recorder; @@ -1740,6 +1756,7 @@ void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { } BindlessHeap::Counts BindlessHeap::Statistics() const { + SpanScope scope(*this); std::lock_guard lock(mutex); auto snapshot = counts; for (const auto& block : poolBlocks) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index c59178228e69..ea2500261eb2 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6640,6 +6640,7 @@ bool ShaderResources::stageReadsOverride(std::size_t stage, const std::vector ShaderResources::addressedOffsets(const std::vector* overrides) const { auto offsets = heapOffsets; auto& heap = BindlessHeap::For(context); + const BindlessHeap::SpanScope spans(heap); const auto moved = [&](std::size_t stage) { return overrides == nullptr || stageReadsOverride(stage, *overrides); }; for (std::size_t stage = 0; stage < stageDataWords.size(); ++stage) { if (stageDataWords[stage].empty() || !moved(stage)) continue; @@ -6707,8 +6708,11 @@ PipelineSetLayouts ShaderResources::SetLayouts() const { void ShaderResources::RefreshHeapStage(std::span shaders) { resolveBufferAddresses(); + std::optional spans; for (const auto& shader : shaders) { - if (HeapShader(shader)) writeHeapStage(shader); + if (!HeapShader(shader)) continue; + if (!spans) spans.emplace(BindlessHeap::For(context)); + writeHeapStage(shader); } } @@ -7232,6 +7236,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { namespace Abi = ShaderRecompiler::RuntimeAbi; HeapCostScope slotsCost(HeapCost::Slots); auto& heap = BindlessHeap::For(context); + const BindlessHeap::SpanScope spans(heap); const VkShaderStageFlags stageBit = VulkanStage(shader.stage); const auto stageIndex = HeapStageIndex(shader.stage); auto& stageState = heapStages[stageIndex]; diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index e5758ccd5dc1..6a8c1001b648 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -9,12 +9,15 @@ #include "RuntimeAbi.hpp" #include #include +#include +#include #include #include #include #include #include #include +#include #include namespace { @@ -292,6 +295,45 @@ bool ringPressure(const Context& context) { return true; } +void writeTails(const Context& context) { + BindlessHeap heap(context); + for (const std::size_t count : {0u, 1u, 3u, 4u, 5u, 7u, 9u}) { + std::vector words(count); + for (std::size_t index = 0; index < count; ++index) words[index] = 0x1000u * static_cast(count) + static_cast(index) + 1u; + BindlessHeap::SpanMark mark; + const auto span = heap.Allocate(count + 1u, mark); + span.words[count] = 0xdeadbeefu; + BindlessHeap::Write(span, words); + require(std::equal(words.begin(), words.end(), span.words.begin()), "a GPU heap span holds other words than were written"); + require(span.words[count] == 0xdeadbeefu, "writing a GPU heap span wrote past its words"); + } +} + +void spanScope(const Context& context) { + BindlessHeap heap(context); + BindlessHeap::SpanMark first; + std::atomic allocated{false}; + std::thread other; + bool waited = false; + { + const BindlessHeap::SpanScope outer(heap); + const BindlessHeap::SpanScope inner(heap); + static_cast(heap.Allocate(16u, first)); + require(heap.Held(first) && !heap.KeepOrAllocate(16u, first, true), "spans are allocated and kept inside nested scopes"); + other = std::thread([&] { + BindlessHeap::SpanMark mark; + static_cast(heap.Allocate(16u, mark)); + allocated.store(true, std::memory_order_release); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + waited = !allocated.load(std::memory_order_acquire); + } + other.join(); + require(waited, "another thread's span waits while a scope holds the allocator"); + require(allocated.load(std::memory_order_acquire) && heap.Held(first), "the other thread allocates once the scope ends"); + require(heap.Statistics().spansWritten == 2u, "both spans are counted"); +} + void ringCurrentChunk(const Context& context) { BindlessHeap heap(context); constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); @@ -740,6 +782,8 @@ int main(int argc, char** argv) { samplerSlots(context); if (!ringPressure(context)) std::printf("the ring pressure test needs at least four chunks\n"); if (!dataPool(context)) std::printf("the data pool tests need the recorder timeline\n"); + spanScope(context); + writeTails(context); if (BindlessHeap(context).RingChunkCount() != 0u) { ringSpans(context); ringCurrentChunk(context); From 27808af0c2bc2179cbacd0ef2c8f583280dda8cb Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 7 Nov 2026 13:14:39 +0530 Subject: [PATCH 136/269] perf(agc): let heap ring hits share their template's resource words Every ring hit copied its ring template's whole per-binding word lists into fresh per-draw words on the decoder, then patched only the shader data binding. HeapStageWords now carries a shared pointer to the immutable template, and a resource binding without per-draw words reads the template's (DrawGuestWords, PatchedHeapResult). Shader data and the flattened SRT never fall back to the template: they always come from the draw. A template built from a hit's words resolves the shared words first. Decoder time in the ring-word build fell from 0.29 to 0.16 us per draw in a frame-pointer profile of the GTA V-shaped offline bench. The bench itself is still bound by the committer, so its median does not move yet. PatchedHeapResult checks the template's words have the program's size, as it does for per-draw words (agc_driver_heap_stage_words). --- .../Execution/src/Driver/Draw/Draw.cpp | 21 +++--- .../Execution/src/Driver/Draw/DrawCapture.cpp | 8 +++ .../Execution/src/Driver/Draw/HeapStages.cpp | 11 +++ .../Graphics/include/Shaders.hpp | 7 +- .../tests/HeapStageWordsBase.cpp | 69 +++++++++++++++++++ .../agc_driver_heap_stage_words_tests.cmake | 13 ++++ core/shader/recompiler/Recompiler.hpp | 1 + 7 files changed, 120 insertions(+), 10 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/HeapStageWordsBase.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_stage_words_tests.cmake diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index b4a8c06bc0ed..ba56d6fa511d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -933,7 +933,8 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { const auto& ringTemplate = *variant.ringTemplate; words->vertexAttributes = ringTemplate.vertexAttributes; words->flattenedSrt.clear(); - words->bindings.clear(); + for (auto& descriptor : words->bindings) descriptor.clear(); + words->base = nullptr; if (!ringTemplate.flattenedSrt.empty()) { words->flattenedSrt = ringTemplate.flattenedSrt; if (&variant == matched[i].get() && stageData[i].compiled != nullptr) { @@ -943,16 +944,20 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { } } if (!ringTemplate.bindings.empty()) { - words->bindings = ringTemplate.bindings; - require(words->bindings.size() == variant.compiled->bindings.size(), "a ring vertex hit's bindings differ in number from its template"); - for (std::size_t index = 0; index < words->bindings.size(); ++index) { - const auto role = variant.compiled->bindings[index].role; + const auto& program = variant.compiled->bindings; + require(ringTemplate.bindings.size() == program.size(), "a ring vertex hit's bindings differ in number from its template"); + words->base = variant.ringTemplate; + words->bindings.resize(program.size()); + for (std::size_t index = 0; index < program.size(); ++index) { + const auto& shared = ringTemplate.bindings[index]; + if (program[index].role != ShaderRecompiler::DescriptorRole::ShaderData || shared.empty()) continue; auto& descriptor = words->bindings[index]; - if (role == ShaderRecompiler::DescriptorRole::FlattenedSrt) descriptor.clear(); - if (role != ShaderRecompiler::DescriptorRole::ShaderData || descriptor.empty()) continue; + descriptor.assign(shared.begin(), shared.end()); std::copy_n(words->userData.begin(), std::min(words->userData.size(), descriptor.size()), descriptor.begin()); - if (descriptor == variant.compiled->bindings[index].guestDescriptor) descriptor.clear(); + if (descriptor == program[index].guestDescriptor) descriptor.clear(); } + } else { + words->bindings.clear(); } ShaderRecompiler::CompleteHeapDataWords(*variant.compiled, *words); if (words->vertexAttributes.empty()) return words; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index c14cfab4dd1c..da48fafaa3a2 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -359,6 +359,14 @@ void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawP ringTemplate->vertexAttributes = stageCapture.heapWords->vertexAttributes; ringTemplate->flattenedSrt = stageCapture.heapWords->flattenedSrt; ringTemplate->bindings = stageCapture.heapWords->bindings; + if (const auto& base = stageCapture.heapWords->base; base != nullptr && !base->bindings.empty()) { + const auto& program = stageCapture.compiled->bindings; + ringTemplate->bindings.resize(program.size()); + for (std::size_t index = 0; index < program.size(); ++index) { + if (ringTemplate->bindings[index].empty()) ringTemplate->bindings[index] = Graphics::DrawGuestWords(*stageCapture.compiled, stageCapture.heapWords.get(), program[index]); + if (ringTemplate->bindings[index] == program[index].guestDescriptor) ringTemplate->bindings[index].clear(); + } + } variant->ringTemplate = std::move(ringTemplate); } if (vertexInfos[i]) variant->vertexInfo = std::make_shared(*vertexInfos[i]); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 938b37129ce9..1d8e9c15d221 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -630,6 +630,17 @@ std::shared_ptr PatchedHeapResult(const std::copy_n(words.userData.begin(), std::min(words.userData.size(), binding.guestDescriptor.size()), binding.guestDescriptor.begin()); } + if (words.base != nullptr && !words.base->bindings.empty()) { + if (words.base->bindings.size() != result->bindings.size()) + throw std::runtime_error("a heap stage's ring template bindings differ in number from its program"); + for (std::size_t index = 0; index < words.base->bindings.size(); ++index) { + const auto role = result->bindings[index].role; + if (role == ShaderRecompiler::DescriptorRole::ShaderData || role == ShaderRecompiler::DescriptorRole::FlattenedSrt || words.base->bindings[index].empty()) continue; + if (words.base->bindings[index].size() != result->bindings[index].guestDescriptor.size()) + throw std::runtime_error("a heap stage's ring template descriptor words differ in size from its program"); + result->bindings[index].guestDescriptor = words.base->bindings[index]; + } + } if (!words.bindings.empty()) { if (words.bindings.size() != result->bindings.size()) throw std::runtime_error("a heap stage's per-draw bindings differ in number from its template"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp index eab75a0ccf7d..423a4bb5cb2a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp @@ -89,9 +89,12 @@ inline std::vector PushDataPlacements(std: } inline const std::vector& DrawGuestWords(const ShaderRecompiler::RecompileResult& program, const ShaderRecompiler::HeapStageWords* heap, const ShaderRecompiler::DescriptorBinding& binding) { - if (heap == nullptr || heap->bindings.empty()) return binding.guestDescriptor; + if (heap == nullptr) return binding.guestDescriptor; const auto index = static_cast(&binding - program.bindings.data()); - return index < heap->bindings.size() && !heap->bindings[index].empty() ? heap->bindings[index] : binding.guestDescriptor; + if (index < heap->bindings.size() && !heap->bindings[index].empty()) return heap->bindings[index]; + const auto* base = heap->base.get(); + const bool shared = binding.role != ShaderRecompiler::DescriptorRole::ShaderData && binding.role != ShaderRecompiler::DescriptorRole::FlattenedSrt; + return shared && base != nullptr && index < base->bindings.size() && !base->bindings[index].empty() ? base->bindings[index] : binding.guestDescriptor; } inline const std::vector& DrawGuestWords(const CompiledShader& shader, const ShaderRecompiler::DescriptorBinding& binding) { diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapStageWordsBase.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapStageWordsBase.cpp new file mode 100644 index 000000000000..ebec477bc580 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/HeapStageWordsBase.cpp @@ -0,0 +1,69 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" +#include "Recompiler.hpp" +#include +#include +#include +#include + +namespace { + +using ShaderRecompiler::DescriptorRole; + +void Check(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +ShaderRecompiler::DescriptorBinding Binding(DescriptorRole role, std::vector words) { + ShaderRecompiler::DescriptorBinding binding{}; + binding.role = role; + binding.count = 1; + binding.guestDescriptor = std::move(words); + return binding; +} + +void TestTemplateWords() { + ShaderRecompiler::RecompileResult program; + program.bindings = {Binding(DescriptorRole::ShaderData, {1, 2, 3, 4}), Binding(DescriptorRole::GuestImages, {10, 11, 12, 13, 14, 15, 16, 17}), + Binding(DescriptorRole::FlattenedSrt, {20, 21}), Binding(DescriptorRole::GuestSamplers, {30, 31, 32, 33})}; + auto shared = std::make_shared(); + shared->bindings = {{9, 9, 9, 9}, {40, 41, 42, 43, 44, 45, 46, 47}, {50, 51}, {}}; + ShaderRecompiler::HeapStageWords words; + words.base = shared; + words.userData = {7}; + words.bindings.resize(program.bindings.size()); + const auto& b = program.bindings; + Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[1]) == shared->bindings[1], "a resource binding without per-draw words does not read its template's"); + Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[3]) == b[3].guestDescriptor, "a binding the template does not hold does not read the program's words"); + Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[0]) == b[0].guestDescriptor, "shader data fell back to the template"); + Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[2]) == b[2].guestDescriptor, "the flattened SRT fell back to the template"); + words.bindings[1] = {60, 61, 62, 63, 64, 65, 66, 67}; + Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[1]) == words.bindings[1], "per-draw words do not override the template's"); + words.bindings[1].clear(); + const auto patched = AgcDriver::DriverDetail::PatchedHeapResult(program, words); + Check(patched->bindings[0].guestDescriptor == std::vector({7, 2, 3, 4}), "the patched shader data does not take the draw's user data over the program's"); + Check(patched->bindings[1].guestDescriptor == shared->bindings[1], "the patched result does not take the template's resource words"); + Check(patched->bindings[2].guestDescriptor == b[2].guestDescriptor, "the patched flattened SRT took the template's words"); + Check(patched->bindings[3].guestDescriptor == b[3].guestDescriptor, "the patched result lost the program's words"); + shared->bindings[3] = {1}; + bool refused = false; + try { + static_cast(AgcDriver::DriverDetail::PatchedHeapResult(program, words)); + } catch (const std::runtime_error&) { + refused = true; + } + Check(refused, "template words of another size than the program's were taken"); +} + +} + +int main() { + try { + TestTemplateWords(); + std::cout << "heap stage template word tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "heap stage template word tests failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_stage_words_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_stage_words_tests.cmake new file mode 100644 index 000000000000..74d19394d62f --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_stage_words_tests.cmake @@ -0,0 +1,13 @@ +if(BUILD_TESTING) + add_test_executable(agc_driver_heap_stage_words_tests tests/HeapStageWordsBase.cpp) + target_include_directories(agc_driver_heap_stage_words_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(agc_driver_heap_stage_words_tests PRIVATE libSceAgcDriver) + set_target_properties(agc_driver_heap_stage_words_tests PROPERTIES CXX_EXTENSIONS OFF) + configure_windows_unwind(agc_driver_heap_stage_words_tests) + add_test(NAME agc_driver_heap_stage_words COMMAND agc_driver_heap_stage_words_tests) + set_tests_properties(agc_driver_heap_stage_words PROPERTIES TIMEOUT 20) + if(WIN32) + set_tests_properties(agc_driver_heap_stage_words PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 7cfd27754039..b6360ea88385 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -514,6 +514,7 @@ struct HeapStageWords { std::vector flattenedSrt; std::vector vertexAttributes; std::vector> bindings; + std::shared_ptr base; ResultKeyMemo drawKeyMemo; bool memoizeKey = true; }; From f4e7be1ac89db0e83937946fc86b5ee001826589 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 7 Nov 2026 13:33:31 +0530 Subject: [PATCH 137/269] perf(agc): write a heap stage's template descriptor run only when the draw binds it A ring stage's refresh resolved its template buffer ranges and kept or wrote their descriptor run, then a draw with moved read-only buffers wrote a second run with the moved ones and never bound the first. The refresh now leaves the run pending; PatchDataAddresses writes it when the draw pushes the stage's own offsets, and addressedOffsets writes it only for stages the moved buffers do not rewrite, so each draw writes its stage's buffer descriptor table once, as vkd3d-proton flushes dirty descriptor state at the draw. A refresh that finds the previous run still pending does not trust its kept run (that run is older than the previous refresh's inputs) and resolves the ranges again. PatchDataAddresses throws if a draw with rewritten offsets leaves a pending stage its moved buffers do not cover. Offline draw bench with GTA V-shaped draws (a local variant), heap mode, median of five interleaved runs: 5.83 -> 5.75 us per draw. Dropping the write at PatchDataAddresses fails 63 of the 207 heap and recipe tests. --- .../Graphics/include/ShaderResources.hpp | 6 ++-- .../Graphics/src/ShaderResources.cpp | 32 +++++++++++++++++-- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index f9ff8e7beebd..5596e6219c61 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -672,7 +672,9 @@ class ShaderResources { }; bool splitSets = false; bool heapStage = false; - std::array heapOffsets{}; + mutable std::array heapOffsets{}; + mutable std::array ringRunPending{}; + void settleRingRuns() const; void writeHeapStage(const CompiledShader& shader); struct RingDescriptors { VkDeviceAddressRangeEXT srt{}; @@ -696,7 +698,7 @@ class ShaderResources { }; KeptSpan data, flat, map; std::vector dataInput; - RingDescriptors descriptors; + mutable RingDescriptors descriptors; std::uint64_t inertProgram = 0; }; std::array heapStages; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index ea2500261eb2..5b6975fc3c17 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6637,11 +6637,26 @@ bool ShaderResources::stageReadsOverride(std::size_t stage, const std::vector ShaderResources::addressedOffsets(const std::vector* overrides) const { - auto offsets = heapOffsets; auto& heap = BindlessHeap::For(context); const BindlessHeap::SpanScope spans(heap); const auto moved = [&](std::size_t stage) { return overrides == nullptr || stageReadsOverride(stage, *overrides); }; + for (std::size_t stage = 0; stage < ringRunPending.size(); ++stage) { + if (!ringRunPending[stage] || (ringDescriptorStages[stage] && moved(stage))) continue; + ringRunPending[stage] = false; + heapOffsets[DataOffsetIndex(stage, ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt)] = ringDescriptors(stage, nullptr, heapStages[stage].descriptors); + } + auto offsets = heapOffsets; for (std::size_t stage = 0; stage < stageDataWords.size(); ++stage) { if (stageDataWords[stage].empty() || !moved(stage)) continue; auto words = stageDataWords[stage]; @@ -6824,7 +6839,13 @@ std::pair ShaderResources::shaderDataLocation(const Comp void ShaderResources::PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const { namespace Abi = ShaderRecompiler::RuntimeAbi; if (!heapStage) return; - const auto& offsets = rewritten != nullptr && rewritten->addressOffsets ? rewritten->heapOffsets : heapOffsets; + const bool addressed = rewritten != nullptr && rewritten->addressOffsets; + if (!addressed) settleRingRuns(); + for (std::size_t stage = 0; addressed && stage < ringRunPending.size(); ++stage) { + if (ringRunPending[stage] && !stageReadsOverride(stage, rewritten->addressOverrides)) + throw std::runtime_error("AGC graphics: a GPU-mode stage's descriptor run was never written although the draw's moved buffers do not rewrite it"); + } + const auto& offsets = addressed ? rewritten->heapOffsets : heapOffsets; VkDeviceAddress table = 0; VkDeviceAddress fault = 0; std::uint32_t tableDwords = 0; @@ -7240,6 +7261,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { const VkShaderStageFlags stageBit = VulkanStage(shader.stage); const auto stageIndex = HeapStageIndex(shader.stage); auto& stageState = heapStages[stageIndex]; + const bool skipped = std::exchange(ringRunPending[stageIndex], false); static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; const auto programIdentity = shader.program->heapTemplateId; if (programIdentity != 0 && stageState.inertProgram == programIdentity && !verifySlots) return; @@ -7336,13 +7358,17 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { if (!flattened) heapSrtDwords[stageIndex] = 0u; auto& kept = stageState.descriptors; const auto srt = srtRange(stageIndex); - const bool keepable = kept.srt.address == srt.address && kept.srt.size == srt.size && (kept.ranges.empty() || heap.Held(kept.mark)); + const bool keepable = !skipped && kept.srt.address == srt.address && kept.srt.size == srt.size && (kept.ranges.empty() || heap.Held(kept.mark)); kept.srt = srt; if (dataKept && keepable) { heapOffsets[flatIndex] = kept.first; return; } if (!(inputsKept && keepable)) { + if (!unbound) { + ringRunPending[stageIndex] = true; + return; + } heapOffsets[flatIndex] = ringDescriptors(stageIndex, nullptr, kept); if (unbound && kept.ranges.empty() && heapOffsets[flatIndex] == 0u) stageState.inertProgram = programIdentity; return; From 9086da6e03d3c366e0971af867c8104ea6ee6eb9 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 7 Nov 2026 16:31:44 +0530 Subject: [PATCH 138/269] perf(agc): wake a full draw queue's producer at half depth, after a spin When the committer is the slower side the draw queue stays full, and the producer slept until one item retired (resumeAt = depth - 1). Every retired draw then cost the committer a futex wake (pthread_cond_broadcast and futex_wake, 0.18 us per draw in a profile of the GTA V-shaped offline bench in heap mode). The producer now spins for room for the handoff spin window first, then sleeps until half the queue has drained. Offline draw bench with GTA V-shaped draws (a local variant), median of five interleaved runs: heap mode 5.70 -> 5.63 us per draw; heap off 4.86 -> 4.81 (six runs, within noise). A producer waiting for room now also wakes when the pipeline stops and runs its draw itself, where it used to wait for the committer to drain and then start a committer nobody joins (agc_driver_pipeline_stop). The half-depth resume point is reset only when the last such producer leaves. --- .../include/Driver/Draw/DrawPipeline.hpp | 1 + .../src/Driver/Draw/DrawPipeline.cpp | 22 +++++-- .../tests/DrawPipelineStop.cpp | 60 +++++++++++++++++++ .../agc_driver_pipeline_stop_tests.cmake | 13 ++++ 4 files changed, 91 insertions(+), 5 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/DrawPipelineStop.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_stop_tests.cmake diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp index fa4c0aa99831..67d316e4d318 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp @@ -94,6 +94,7 @@ class DrawPipeline { std::atomic decodeDrains{0}; std::uint64_t reportedDecodeDrains = 0; std::uint32_t idleWaiters = 0; + std::uint32_t fullWaiters = 0; std::size_t resumeAt = 0; bool committerWaiting = false; bool stopped = false; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp index c6deb7beedaf..7daa5393fa36 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp @@ -324,13 +324,24 @@ void DrawPipeline::enqueue(Item item) { if (items.size() >= Depth()) { if (GuestMemory::GpuMutex().HeldByThisThread()) throw std::runtime_error("draw pipeline full while the enqueuing thread holds the GPU lock"); const auto start = std::chrono::steady_clock::now(); - resumeAt = Depth() - 1; - ++idleWaiters; - idle.wait(lock, [&] { return items.size() <= resumeAt; }); - --idleWaiters; - resumeAt = 0; + lock.unlock(); + static_cast(SpinUntil(HandoffSpinWindow(), [&] { return outstanding.load(std::memory_order_acquire) < Depth(); })); + lock.lock(); + if (items.size() >= Depth() && !closing) { + resumeAt = Depth() / 2; + ++idleWaiters; + ++fullWaiters; + idle.wait(lock, [&] { return items.size() <= resumeAt || closing; }); + --idleWaiters; + if (--fullWaiters == 0) resumeAt = 0; + } fullWaitNs += elapsedNs(start); rethrowFailure(); + if (closing) { + lock.unlock(); + item.commit(); + return; + } } depthSum += items.size(); ++enqueued; @@ -447,6 +458,7 @@ void DrawPipeline::Stop() { committer = std::move(thread); } wake.notify_all(); + idle.notify_all(); if (!committer.joinable()) return; if (committer.get_id() == std::this_thread::get_id()) committer.detach(); else committer.join(); diff --git a/core/libs/prx/libSceAgcDriver/tests/DrawPipelineStop.cpp b/core/libs/prx/libSceAgcDriver/tests/DrawPipelineStop.cpp new file mode 100644 index 000000000000..74656deafbcb --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/DrawPipelineStop.cpp @@ -0,0 +1,60 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include +#include +#include +#include +#include +#include + +namespace { + +void Check(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +void TestStopReleasesFullProducer() { + using AgcDriver::DriverDetail::DrawPipeline; + auto& pipeline = DrawPipeline::Queue0(); + const auto depth = DrawPipeline::Depth(); + Check(depth >= 2, "test requires at least two pipeline slots"); + std::binary_semaphore release{0}; + std::atomic started{false}; + pipeline.Enqueue([&] { + started.store(true, std::memory_order_release); + release.acquire(); + }, {}, 0, {}, {}, true); + while (!started.load(std::memory_order_acquire)) std::this_thread::yield(); + for (std::size_t index = 1; index < depth; ++index) pipeline.Enqueue([] {}, {}, 0, {}, {}, true); + std::atomic returned{false}; + std::thread::id ranOn; + std::thread producer([&] { + pipeline.Enqueue([&] { ranOn = std::this_thread::get_id(); }, {}, 0, {}, {}, true); + returned.store(true, std::memory_order_release); + }); + const auto producerId = producer.get_id(); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + const bool waitedForRoom = !returned.load(std::memory_order_acquire); + std::thread stopper([&] { pipeline.Stop(); }); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + while (!returned.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < deadline) std::this_thread::sleep_for(std::chrono::milliseconds(1)); + const bool releasedByStop = returned.load(std::memory_order_acquire); + release.release(); + producer.join(); + stopper.join(); + Check(waitedForRoom, "the producer did not wait for room in a full queue"); + Check(releasedByStop, "stopping the pipeline left a producer waiting for room until the committer drained"); + Check(ranOn == producerId, "a draw enqueued while the pipeline stopped did not run on its producer"); +} + +} + +int main() { + try { + TestStopReleasesFullProducer(); + std::cout << "draw pipeline stop tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "draw pipeline stop tests failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_stop_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_stop_tests.cmake new file mode 100644 index 000000000000..f89abafd2978 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_pipeline_stop_tests.cmake @@ -0,0 +1,13 @@ +if(BUILD_TESTING) + add_test_executable(agc_driver_pipeline_stop_tests tests/DrawPipelineStop.cpp) + target_include_directories(agc_driver_pipeline_stop_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(agc_driver_pipeline_stop_tests PRIVATE libSceAgcDriver) + set_target_properties(agc_driver_pipeline_stop_tests PROPERTIES CXX_EXTENSIONS OFF) + configure_windows_unwind(agc_driver_pipeline_stop_tests) + add_test(NAME agc_driver_pipeline_stop COMMAND agc_driver_pipeline_stop_tests) + set_tests_properties(agc_driver_pipeline_stop PROPERTIES TIMEOUT 20 ENVIRONMENT "APS5_PIPELINED_DRAWS=4") + if(WIN32) + set_tests_properties(agc_driver_pipeline_stop PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() From e48ec7acb05c7ec19e3d2de87e64e215ecc94149 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 7 Nov 2026 19:08:10 +0530 Subject: [PATCH 139/269] test(agc): build the heap stage words test and merged targets on Windows agc_driver_heap_stage_words_tests includes Context.hpp through HeapStages.hpp, so it needs the configured Vulkan headers like the other driver tests, and libc's directory on PATH to start. The merged color target fixtures of the heap draw sample and bench ask the guest write tracker whether it watches the arena before they allocate, and require the target to be watched afterwards, so a Windows run stops at the allocation with a clear message instead of a draw that never becomes resident. --- .../tests/cmake/agc_driver_heap_stage_words_tests.cmake | 4 ++-- .../prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp | 2 ++ .../prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp | 2 ++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_stage_words_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_stage_words_tests.cmake index 74d19394d62f..6def7e94b48c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_stage_words_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_stage_words_tests.cmake @@ -1,6 +1,6 @@ if(BUILD_TESTING) add_test_executable(agc_driver_heap_stage_words_tests tests/HeapStageWordsBase.cpp) - target_include_directories(agc_driver_heap_stage_words_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_include_directories(agc_driver_heap_stage_words_tests PRIVATE ${LIBS_INCLUDE_DIR} ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR}) target_link_libraries(agc_driver_heap_stage_words_tests PRIVATE libSceAgcDriver) set_target_properties(agc_driver_heap_stage_words_tests PROPERTIES CXX_EXTENSIONS OFF) configure_windows_unwind(agc_driver_heap_stage_words_tests) @@ -8,6 +8,6 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_heap_stage_words PROPERTIES TIMEOUT 20) if(WIN32) set_tests_properties(agc_driver_heap_stage_words PROPERTIES ENVIRONMENT_MODIFICATION - "PATH=path_list_prepend:$") + "PATH=path_list_prepend:$;PATH=path_list_prepend:$") endif() endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp index 33c43c64bf1e..0f13c5957b36 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp @@ -107,6 +107,7 @@ std::span MergedTarget(std::size_t index) { static std::array data{}; if (data.at(index) == nullptr) data[index] = [] { std::byte* block = nullptr; + const bool watched = AgcDriver::GuestMemory::WriteWatched(); #ifdef _WIN32 block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Bytes, Bytes)); GuestArena::GuestArenaCommit_nid_postfix(block, Bytes, PAGE_READWRITE, Bytes); @@ -117,6 +118,7 @@ std::span MergedTarget(std::size_t index) { block = reinterpret_cast((begin + Bytes - 1u) & ~static_cast(Bytes - 1u)); GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Bytes); #endif + Require(!watched || AgcDriver::GuestMemory::Watched(reinterpret_cast(block), Bytes), "the merged color target is not write-watched"); GuestAllocations::Mutation mutation; mutation.Add(block, Bytes, true, true, true); return block; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index 8912ece91469..af50fd9632ee 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -103,6 +103,7 @@ std::span MergedTarget(std::size_t index) { static std::array data{}; if (data.at(index) == nullptr) data[index] = [] { std::byte* block = nullptr; + const bool watched = AgcDriver::GuestMemory::WriteWatched(); #ifdef _WIN32 block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Bytes, Bytes)); GuestArena::GuestArenaCommit_nid_postfix(block, Bytes, PAGE_READWRITE, Bytes); @@ -113,6 +114,7 @@ std::span MergedTarget(std::size_t index) { block = reinterpret_cast((begin + Bytes - 1u) & ~static_cast(Bytes - 1u)); GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Bytes); #endif + Require(!watched || AgcDriver::GuestMemory::Watched(reinterpret_cast(block), Bytes), "the merged color target is not write-watched"); GuestAllocations::Mutation mutation; mutation.Add(block, Bytes, true, true, true); return block; From a06a3bcc0f0e584e3311ae7503d8428b05137ac3 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 7 Nov 2026 19:15:24 +0530 Subject: [PATCH 140/269] test(agc): give the nonuniform initial lifetime test's own recorder a timeline Under APS5_GPU_HEAP=1 the multisampled target's initial upload is submitted on the test's own Recorder, which the heap refuses without a timeline semaphore. Construct it with one, as the device does. --- .../libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp index 288cc0b567a0..0bd196619bb0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/SampleMultisampleTarget.cpp @@ -1069,7 +1069,7 @@ int NonuniformInitialLifetime(AgcDriver::VulkanDevice& device) { { auto recorded = context; recorded.bufferPool = std::make_shared(context); - Recorder recorder(recorded); + Recorder recorder(recorded, true); std::shared_ptr owner; VkImageView view = VK_NULL_HANDLE; std::size_t initialBytes = 0; From 78d2e5b08475e6e1698fd1f09e5880386999621a Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 8 Nov 2026 03:20:18 +0530 Subject: [PATCH 141/269] fix(agc): leave a heap stage whose walk cannot capture to the synchronized capture The heap walk reads guest memory without waiting for pending writes, and only checks that the words it read were settled after the capture returns. The capture validates the descriptors it reads, so a walk that read a descriptor before its writer finished threw, and the draw failed instead of taking the synchronized ShaderMemory capture, which waits for the writer. An unsynchronized read cannot show that a descriptor is invalid, so a walk whose capture throws now declines the stage like an unsettled walk does. A descriptor that really is invalid still throws on the synchronized capture. Reported, with the fix and test design, by @muhmuhkuh in #9508. --- .../Execution/src/Driver/Draw/HeapStages.cpp | 8 +- ...iver_heap_walk_capture_failure_tests.cmake | 4 + .../execution/HeapWalkCaptureFailure.cpp | 104 ++++++++++++++++++ 3 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_capture_failure_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 1d8e9c15d221..ab10c939f703 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -580,7 +581,12 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade memoCost.Stop(); Graphics::HeapCostScope walkCost(Graphics::HeapCost::Walk); - auto capture = captureWalk(invocation, userData, shaderBase, reads); + std::shared_ptr capture; + try { + capture = captureWalk(invocation, userData, shaderBase, reads); + } catch (const std::exception&) { + return {}; + } coalesceWords(reads.words, ranges); auto& values = HostThreadLocal, ValuesStorage>(); if (!reads.failed) copyRangeValues(ranges, values); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_capture_failure_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_capture_failure_tests.cmake new file mode 100644 index 000000000000..e990f737fb33 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_capture_failure_tests.cmake @@ -0,0 +1,4 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_heap_walk_capture_failure) +endif() + diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp new file mode 100644 index 000000000000..0306094eb38d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp @@ -0,0 +1,104 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "Optimization/RequestMemoryView.hpp" +#include "Optimization/ResourceProgram.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Lanes = 32; +constexpr std::uint32_t Format32UInt = 20; +alignas(256) std::array Input{}; +alignas(256) std::array Output{}; +alignas(256) constexpr std::array Code{0x34020082u, 0xe0001000u, 0x80000201u, 0xe0301000u, 0x80000301u, 0xbf8c0000u, + 0xe0101000u, 0x80000201u, 0xe0701000u, 0x80000301u, + 0xe0701000u, 0x80010201u, 0xe0701080u, 0x80010301u, 0xbf800000u, 0xbf810000u}; + +std::array Descriptor(const void* data, std::uint32_t bytes, std::uint32_t type) { + const auto address = reinterpret_cast(data); + const auto word3 = (((0x01016facu & ~(0x7fu << 12u)) | (Format32UInt << 12u) | (3u << 28u)) & ~(3u << 30u)) | (type << 30u); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, word3}; +} + +ShaderRecompiler::RecompileRequest Request(AgcDriver::VulkanDevice& device, std::vector& userData) { + static const std::array memory{{{reinterpret_cast(Code.data()), std::as_bytes(std::span(Code))}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Lanes, 1, 1}, 0u, {false, false, false}, false, 1}; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, reinterpret_cast(Code.data()), Code, 0, {}}, + {Lanes, 0, userData, compute, std::nullopt, std::nullopt, memory}, + device.Target(), + {0, 0, 0, 128} + }; + return request; +} + +std::vector UserData(std::uint32_t inputType) { + std::vector userData; + const auto input = Descriptor(Input.data(), sizeof(Input), inputType); + const auto output = Descriptor(Output.data(), sizeof(Output), 0u); + userData.insert(userData.end(), input.begin(), input.end()); + userData.insert(userData.end(), output.begin(), output.end()); + return userData; +} + +void UnsupportedTypeDeclines(AgcDriver::VulkanDevice& device) { + auto userData = UserData(2u); + const auto request = Request(device, userData); + const auto handle = ShaderRecompiler::PrepareShader(request); + const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, handle); + Require(invocation.has_value(), "the prepared shader refused its own request"); + AgcDriver::DriverDetail::HeapStageMaterialized materialized; + try { + materialized = AgcDriver::DriverDetail::MaterializeHeapStage(*invocation, userData, request.shader.codeAddress); + } catch (const std::exception& error) { + Require(false, std::string("a heap walk that read words it cannot capture threw instead of leaving the stage to the synchronized capture: ") + error.what()); + } + Require(materialized.result == nullptr, "a heap walk over an unsupported buffer type produced a stage"); + ShaderRecompiler::RequestMemoryView memoryView(request.context.memory); + const auto runtime = memoryView.MakeRuntime(request.context.userData, request.shader.codeAddress); + std::string message; + try { + static_cast(invocation->Materialize(*invocation->Capture(runtime))); + } catch (const std::exception& error) { + message = error.what(); + } + Require(message.find("buffer descriptor uses an unsupported type") != std::string::npos, "the synchronized capture of an unsupported buffer type did not reject it: " + message); +} + +void ValidTypeYieldsStage(AgcDriver::VulkanDevice& device) { + auto userData = UserData(0u); + const auto request = Request(device, userData); + const auto handle = ShaderRecompiler::PrepareShader(request); + const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, handle); + Require(invocation.has_value(), "the prepared shader refused its own request"); + const auto materialized = AgcDriver::DriverDetail::MaterializeHeapStage(*invocation, userData, request.shader.codeAddress); + Require(materialized.result != nullptr, "a heap walk over valid buffer descriptors declined its stage"); +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + UnsupportedTypeDeclines(*device); + ValidTypeYieldsStage(*device); + std::puts("heap walk capture failure tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} From 67b971f0860518730e63b723730851b2667d8173 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 8 Nov 2026 03:20:30 +0530 Subject: [PATCH 142/269] perf(agc): pass heap stages' guest buffer addresses in push data on NVIDIA With the GPU descriptor heap, a heap stage reads its guest buffers through a run of buffer descriptors the driver writes into the shader-data ring for each draw whose buffers differ from the stage's last run. In GTA V nearly every cached draw re-points its constant buffers: about 692K runs (1.9M buffer descriptors) per 10 s, 99.4% of them for moved buffers on recipe hits. On NVIDIA a stage now reads each guest buffer's address and size from push data instead, the way vkd3d-proton passes root descriptors as raw addresses. Up to four records of three dwords sit in the stage's push layout; the rest go to a small per-draw overflow block whose address is pushed. Loads keep the size check a PS5 buffer descriptor makes, so a read past the end still returns 0. A repeated draw whose buffers moved then only rewrites push bytes. The push layout places every stage's root items and overflow address before any buffer record, so a pipeline whose stages hold every root item still fits; records that find no room go to the overflow block. Other vendors keep the ring descriptors: on a fake RX 6800 (RADV) the pushed path compiles MCD2's shaders to 11-16% more instructions than the ring, from 64-bit address math in place of bounds-checked buffer loads, while NVIDIA handles raw addresses natively. APS5_PUSHED_BUFFERS=0|1 forces either path, and APS5_PUSHED_BUFFER_RECORDS caps the pushed records for tests. Request serialization version 57, shader disk cache format 63. --- .../Execution/src/VulkanDevice.cpp | 3 + .../Graphics/include/BindlessHeap.hpp | 2 + .../include/PipelineSpecialization.hpp | 2 + .../Graphics/include/ShaderResources.hpp | 7 ++ .../Graphics/include/Shaders.hpp | 5 +- .../Graphics/src/BindlessHeap.cpp | 26 +++++++ .../Graphics/src/ShaderResources.cpp | 54 +++++++++++++- .../tests/PushDataPlacements.cpp | 70 ++++++++++++++++++ .../libSceAgcDriver/tests/ShaderMemory.cpp | 14 ++-- ...river_draw_recipe_moved_buffer_tests.cmake | 7 ++ .../tests/execution/DrawRecipeMovedBuffer.cpp | 14 +++- core/shader/recompiler/CacheKey.hpp | 1 + .../ControlFlow/src/RequestSerializer.cpp | 6 +- .../IrMetadata/DescriptorBinding.hpp | 1 + .../include/Optimization/BindingAllocator.hpp | 1 + .../Optimization/src/BindingAllocator.cpp | 3 +- .../recompiler/PipelineSpecialization.hpp | 5 +- core/shader/recompiler/PushDataLayout.hpp | 60 ++++++++++++++-- core/shader/recompiler/Recompiler.cpp | 6 +- core/shader/recompiler/Recompiler.hpp | 2 + core/shader/recompiler/RuntimeAbi.hpp | 3 + core/shader/recompiler/ShaderDiskCache.cpp | 8 ++- core/shader/recompiler/ShaderDiskCache.hpp | 2 +- .../SpirvMemory/SpirvBufferAccess.hpp | 1 + .../SpirvBackend/src/SpirvEmitter.cpp | 2 +- .../src/SpirvMemory/SpirvBufferAccess.cpp | 36 ++++++++++ .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 6 +- .../tests/RequestSerializerTests.cpp | 71 ++++++++++++------- docs/dev/ENVIRONMENT.md | 2 + 29 files changed, 365 insertions(+), 55 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 3571e449e262..7d42693bc9ea 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -749,6 +749,7 @@ struct VulkanDevice::State { VkPhysicalDeviceDescriptorHeapPropertiesEXT descriptorHeapProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_PROPERTIES_EXT}; std::uint32_t heapDataUniformDwords = 0; bool heapBufferDescriptors = false; + bool pushedBufferAddresses = false; std::unique_ptr recorder; // Device-local buffers of a repeated 16-byte fill pattern (FillBuffer), most recently used // last; each is filled once by a doubling chain in device memory. @@ -2286,6 +2287,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : state->heapDataUniformDwords = std::min(HeapDataUniformDwordCap, state->properties.limits.maxUniformBufferRange / 4u); if (Graphics::BindlessHeap::RingInResourceHeap(state->descriptorHeapProperties, state->properties.limits.minUniformBufferOffsetAlignment)) state->heapBufferDescriptors = state->descriptorHeapProperties.bufferDescriptorSize == Graphics::BindlessHeap::BufferSlotBytes; + state->pushedBufferAddresses = Graphics::ChoosePushedBufferAddresses(state->properties.vendorID); deviceExtensions.push_back(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME); for (const char* required : {VK_KHR_MAINTENANCE_5_EXTENSION_NAME, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME}) { if (std::find_if(deviceExtensions.begin(), deviceExtensions.end(), [&](const char* name) { return std::strcmp(name, required) == 0; }) == deviceExtensions.end()) deviceExtensions.push_back(required); @@ -4689,6 +4691,7 @@ ShaderRecompiler::SpirvTarget VulkanDevice::Target() const { target.descriptorMemory = Graphics::DescriptorHeapEnabled(); target.heapDataUniformDwords = target.descriptorMemory ? state->heapDataUniformDwords : 0u; target.heapBufferDescriptors = target.descriptorMemory && state->heapBufferDescriptors; + target.pushedBufferAddresses = target.descriptorMemory && state->pushedBufferAddresses; target.float16WidenNans = state->float16WidenNans; target.float16NarrowNans = state->float16NarrowNans; return target; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index a9c25a5fb338..96cd1bf9c12a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -305,6 +305,8 @@ class HeapSlotOwner { bool GpuHeapEnabled(); void SetDescriptorHeapDevice(bool available); bool DescriptorHeapEnabled(); +bool ChoosePushedBufferAddresses(std::uint32_t vendorId); +bool PushedBufferAddressesEnabled(); bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds = false, bool meshWindow = false, bool scratchPool = false, std::pair* refused = nullptr); void NoteHeapComputeStage(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp index 3d9a7b194390..b6cdb622bd40 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp @@ -90,6 +90,8 @@ class PipelineSpecialization { for (auto& constant : values) { if (constant.id == Ids::PushedDataBase) constant.value = placement.pushed.base; if (constant.id == Ids::PushedDataCount) constant.value = placement.pushed.count; + if (constant.id >= Ids::BufferRootPosition && constant.id < Ids::BufferRootPosition + Ids::BufferRootCount) constant.value = placement.bufferRoots[constant.id - Ids::BufferRootPosition]; + if (constant.id == Ids::BufferOverflowPosition) constant.value = placement.bufferOverflow; if (constant.id >= Ids::RootItemPositionBase && constant.id < Ids::RootItemPositionBase + ShaderRecompiler::RuntimeAbi::RootItemCount) { constant.value = placement.items[constant.id - Ids::RootItemPositionBase]; Require(constant.value != ShaderRecompiler::RuntimeAbi::NoPushPosition, "a stage reads a root item its pipeline's push layout does not hold"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 012e88374a79..cab5e0254a71 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -167,6 +167,12 @@ struct ImageTableReuseCounts { std::uint64_t variantRejected = 0; }; ImageTableReuseCounts ImageTableReuses(); +struct HeapBufferPathCounts { + std::uint64_t ringRuns = 0; + std::uint64_t pushedStages = 0; + std::uint64_t overflowStages = 0; +}; +HeapBufferPathCounts HeapBufferPaths(); std::uint64_t SampledTexturesCleared(); std::uint64_t SampledLookupKeyScans(); std::uint64_t SampledLookupKeyProofs(); @@ -372,6 +378,7 @@ class ShaderResources { } void PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const; void writePushedData(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const; + void writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides) const; // Whether RefreshData would record anything for `shader` (the per-word compare; verification). bool DataWordsDiffer(const CompiledShader& shader) const; std::size_t BindingCount() const { return bindings.size(); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp index 423a4bb5cb2a..b347be9c6972 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp @@ -67,6 +67,8 @@ inline bool PushesGeneratedFaultAddress(const CompiledShader& shader, bool roote return std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer; }); } +std::uint32_t PushedBufferRecordCap(); + inline std::vector PushDataPlacements(std::span shaders) { namespace Abi = ShaderRecompiler::RuntimeAbi; std::vector stages(shaders.size()); @@ -80,12 +82,13 @@ inline std::vector PushDataPlacements(std: if (program->dataAddressPush) { stages[index].items = program->pushItems & ShaderRecompiler::RootItemMask; stages[index].pushedWanted = static_cast(program->pushedData.size()); + stages[index].pushedBuffers = program->pushedBufferCount; continue; } if (!program->pushConstants.empty()) occupied |= ShaderRecompiler::PushBytesMask(shaders[index].pushConstantOffset, static_cast(program->pushConstants.size())); if (PushesGeneratedFaultAddress(shaders[index], rooted)) stages[index].items = Abi::RootItemBit(Abi::RootItem::FaultAddress); } - return ShaderRecompiler::PlacePushData(stages, occupied); + return ShaderRecompiler::PlacePushData(stages, occupied, PushedBufferRecordCap()); } inline const std::vector& DrawGuestWords(const ShaderRecompiler::RecompileResult& program, const ShaderRecompiler::HeapStageWords* heap, const ShaderRecompiler::DescriptorBinding& binding) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index d28569b81115..56d10e7a780b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -151,6 +151,32 @@ bool DescriptorHeapEnabled() { namespace { +constexpr std::uint32_t NvidiaVendorId = 0x10deu; +std::atomic pushedBufferAddresses{false}; + +} + +bool ChoosePushedBufferAddresses(std::uint32_t vendorId) { + const char* forced = std::getenv("APS5_PUSHED_BUFFERS"); + const bool chosen = forced != nullptr && *forced != '\0' ? std::strcmp(forced, "0") != 0 : vendorId == NvidiaVendorId; + pushedBufferAddresses.store(chosen, std::memory_order_relaxed); + return chosen; +} + +std::uint32_t PushedBufferRecordCap() { + static const std::uint32_t cap = [] { + const char* value = std::getenv("APS5_PUSHED_BUFFER_RECORDS"); + return value != nullptr && *value != '\0' ? static_cast(std::strtoul(value, nullptr, 10)) : ShaderRecompiler::RuntimeAbi::PushedBufferLimit; + }(); + return cap; +} + +bool PushedBufferAddressesEnabled() { + return DescriptorHeapEnabled() && pushedBufferAddresses.load(std::memory_order_relaxed); +} + +namespace { + struct HeapSizes { std::uint32_t imageSlots = 0; VkDeviceSize imageStride = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 2a999ae32c1b..5c067d5c289d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6069,6 +6069,18 @@ std::uint64_t SampledTexturesCleared() { return TextureCounts().cleared.load(std::memory_order_relaxed); } +namespace { + +std::atomic heapRingRuns{0}; +std::atomic heapPushedStages{0}; +std::atomic heapOverflowStages{0}; + +} + +HeapBufferPathCounts HeapBufferPaths() { + return {heapRingRuns.load(std::memory_order_relaxed), heapPushedStages.load(std::memory_order_relaxed), heapOverflowStages.load(std::memory_order_relaxed)}; +} + ImageTableReuseCounts ImageTableReuses() { const auto& counters = TextureCounts(); return {counters.tablesReused.load(std::memory_order_relaxed) + counters.tablesReplayed.load(std::memory_order_relaxed), counters.tablesResolved.load(std::memory_order_relaxed), counters.tablesReplayed.load(std::memory_order_relaxed), counters.tableWritesKept.load(std::memory_order_relaxed), counters.tableWritesMade.load(std::memory_order_relaxed), counters.variantSurfaces.load(std::memory_order_relaxed), counters.variantSubstituted.load(std::memory_order_relaxed), counters.variantRejected.load(std::memory_order_relaxed)}; @@ -6846,6 +6858,7 @@ std::uint32_t ShaderResources::ringDescriptors(std::size_t stage, const std::vec auto& heap = BindlessHeap::For(context); const auto equal = [](const VkDeviceAddressRangeEXT& a, const VkDeviceAddressRangeEXT& b) { return a.address == b.address && a.size == b.size; }; if (!std::ranges::equal(ranges, kept.ranges, equal) || !heap.Held(kept.mark)) { + heapRingRuns.fetch_add(1, std::memory_order_relaxed); kept.first = heap.RingBufferDescriptors(ranges, kept.mark); kept.ranges.assign(ranges.begin(), ranges.end()); } @@ -6932,11 +6945,48 @@ void ShaderResources::PatchDataAddresses(std::span(std::min(heapSrtDwords[stage], srt.size / sizeof(std::uint32_t))) : heapSrtDwords[stage]); putAddress(Abi::RootItem::TableMap, heapTableMapSet[stage] ? heapTableMaps[stage] : offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); writePushedData(bytes, shader, placement.pushed); + if (shader.program->pushedBufferCount != 0u) writePushedBuffers(bytes, stage, placement, addressed ? &rewritten->addressOverrides : nullptr); rooted = true; } if (rooted) NoteDataAddressPush(); } +void ShaderResources::writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides) const { + namespace Abi = ShaderRecompiler::RuntimeAbi; + struct RangeStorage {}; + auto& ranges = HostThreadLocal, RangeStorage>(); + ranges.clear(); + writeBufferAddresses({}, static_cast(stage), overrides, &ranges); + Require(ranges.size() == placement.pushedBuffers, "a stage's buffer addresses do not match its push layout's buffer count"); + heapPushedStages.fetch_add(1, std::memory_order_relaxed); + const auto record = [&](std::size_t index) { + return std::array{static_cast(ranges[index].address), static_cast(ranges[index].address >> 32u), static_cast(std::min(ranges[index].size, 0xffffffffu)), 0u}; + }; + const auto put = [&](std::uint32_t position, std::span words) { + Require(position != Abi::NoPushPosition && (position + words.size()) * sizeof(std::uint32_t) <= bytes.size(), "a stage's pushed buffer words lie outside the push data"); + std::memcpy(bytes.data() + position * sizeof(std::uint32_t), words.data(), words.size_bytes()); + }; + bool overflowed = false; + for (std::size_t index = 0; index < ranges.size(); ++index) { + const auto root = index < Abi::PushedBufferLimit ? placement.bufferRoots[index] : Abi::NoPushPosition; + if (root == Abi::NoPushPosition) { + overflowed = true; + continue; + } + const auto words = record(index); + put(root, std::span(words).first(Abi::PushedBufferWords)); + } + if (!overflowed) return; + heapOverflowStages.fetch_add(1, std::memory_order_relaxed); + const auto span = BindlessHeap::For(context).Allocate(ranges.size() * Abi::OverflowRecordWords); + for (std::size_t index = 0; index < ranges.size(); ++index) { + const auto words = record(index); + std::copy(words.begin(), words.end(), span.words.begin() + static_cast(index * Abi::OverflowRecordWords)); + } + const std::array address{static_cast(span.address), static_cast(span.address >> 32u)}; + put(placement.bufferOverflow, address); +} + void ShaderResources::writePushedData(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const { const auto& program = *shader.program; if (placement.count == 0u) return; @@ -7313,7 +7363,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { const std::size_t flatIndex = DataOffsetIndex(stageIndex, Abi::Binding::FlattenedSrt); const auto& program = *shader.program; if (program.dataAddressPush) writeHeapTableMap(shader, stageIndex); - const bool ringStage = context.heapBufferDescriptors && program.dataAddressPush; + const bool ringStage = context.heapBufferDescriptors && program.dataAddressPush && program.pushedBufferCount == 0u; ringDescriptorStages[stageIndex] = ringStage; if (ringStage) stageDataWords[stageIndex].clear(); bool dataKept = false; @@ -7359,7 +7409,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { reinterpret_cast(patched.data())[byte] = static_cast(adjustment); } patchHeapSlotWords(shader, stageState, patched, current); - if (addressedBuffers && !ringStage) { + if (addressedBuffers && !ringStage && program.pushedBufferCount == 0u) { HeapCostScope bufferCost(HeapCost::BufferAddresses); writeBufferAddresses(patched, static_cast(stageIndex), nullptr); bufferCost.Stop(); diff --git a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp index 945800920555..e5804fb28a0c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp @@ -26,6 +26,7 @@ struct Stage { ShaderStage stage; std::uint32_t items; std::size_t pushed; + std::uint32_t buffers = 0; }; std::uint32_t bits(std::initializer_list items) { @@ -43,6 +44,7 @@ std::vector place(const std::vector& stages) { programs[index].gpuResolvedImages = true; programs[index].pushItems = stages[index].items; programs[index].pushedData.resize(stages[index].pushed); + programs[index].pushedBufferCount = stages[index].buffers; for (std::size_t dword = 0; dword < stages[index].pushed; ++dword) programs[index].pushedData[dword] = static_cast(dword); shaders.push_back({stages[index].stage, &programs[index], 0u}); } @@ -72,6 +74,22 @@ void disjoint(const std::vector& stages, const std::vector(kind) < static_cast(Abi::RootItem::ShaderData)); } + const auto& placement = placements[index]; + require(placement.pushedBuffers == stages[index].buffers, std::string("a stage's placement does not count its buffers: ") + what); + bool overflowed = stages[index].buffers > Abi::PushedBufferLimit; + for (std::uint32_t buffer = 0; buffer < Abi::PushedBufferLimit; ++buffer) { + const auto root = placement.bufferRoots[buffer]; + if (buffer >= stages[index].buffers) require(root == Abi::NoPushPosition, std::string("a buffer the stage does not read has a root: ") + what); + overflowed = overflowed || (buffer < stages[index].buffers && root == Abi::NoPushPosition); + if (root == Abi::NoPushPosition) continue; + require(root % 2u == 0u, std::string("a pushed buffer address is not 8-byte aligned: ") + what); + claim(root, Abi::PushedBufferWords, false); + } + require(overflowed == (placement.bufferOverflow != Abi::NoPushPosition), std::string("a stage's overflow address and its unplaced buffers disagree: ") + what); + if (placement.bufferOverflow != Abi::NoPushPosition) { + require(placement.bufferOverflow % 2u == 0u, std::string("a buffer overflow address is not 8-byte aligned: ") + what); + claim(placement.bufferOverflow, 2u, false); + } claim(placements[index].pushed.base, placements[index].pushed.count, false); require(placements[index].pushed.count <= stages[index].pushed, std::string("a stage pushes more than it asked for: ") + what); } @@ -81,6 +99,7 @@ void disjoint(const std::vector& stages, const std::vector stages{{ShaderStage::Vertex, (all & ~stencil) | Abi::DepthRemapPushBit, 48, Abi::PushedBufferLimit}, {ShaderStage::Geometry, 0u, 0}, {ShaderStage::Fragment, all, 48, Abi::PushedBufferLimit}}; + const auto placements = place(stages); + disjoint(stages, placements, ShaderRecompiler::PushFeatureDwords(true, false, true), "vertex and pixel stages with every root item and the most pushed buffers"); + require(place({stages[2]})[0].bufferRoots == placements[2].bufferRoots, "a pixel stage's buffer root is placed as it is alone, so its fragment library is shared"); + } + { + const auto all = (1u << Abi::RootItemCount) - 1u; + const auto stencil = Abi::RootItemBit(Item::StencilReference); + const std::vector stages{{ShaderStage::Local, all & ~stencil, 4}, {ShaderStage::TessellationControl, all & ~stencil, 3}, {ShaderStage::TessellationEvaluation, (all & ~stencil) | Abi::DepthRemapPushBit, 10}, {ShaderStage::Fragment, all, 48, Abi::PushedBufferLimit}}; + disjoint(stages, place(stages), ShaderRecompiler::PushFeatureDwords(false, true, true), "a tessellation pipeline whose stages hold every root item and whose pixel stage pushes the most buffers"); + } + { + const auto all = (1u << Abi::RootItemCount) - 1u; + const std::vector stages{{ShaderStage::Compute, all & ~Abi::RootItemBit(Item::StencilReference), 60, Abi::PushedBufferLimit}}; + const auto placements = place(stages); + disjoint(stages, placements, ShaderRecompiler::StagePushFeatures(ShaderStage::Compute, 0u), "a compute stage with every root item and the most pushed buffers"); + require(!defaultCap || placements[0] == ShaderRecompiler::StandalonePushPlacement(ShaderStage::Compute, stages[0].items, stages[0].pushed, stages[0].buffers), "the compiler's standalone compute placement with pushed buffers is the driver's"); + } + { + namespace Ids = ShaderRecompiler::PipelineSpecialization; + for (std::uint32_t buffer = 0; buffer <= Ids::BufferRootCount; ++buffer) { + const auto id = Ids::BufferRootPosition + buffer; + require(id >= Ids::SamplerLodBiasBase + Abi::SamplerHeapCapacity && id < Ids::ImageComponentBase, "a buffer root specialization id lies inside another constant's range"); + require(Ids::IsPushPlacement(id), "a buffer root specialization id is not a push placement"); + } + for (std::uint32_t id = Ids::StoreQuantizeBase; id < Ids::DescriptorIndexBase; ++id) require(!Ids::IsPushPlacement(id), "a store quantization specialization id counts as a push placement"); + } + { + const auto all = (1u << Abi::RootItemCount) - 1u; + const auto stencil = Abi::RootItemBit(Item::StencilReference); + for (const std::uint32_t buffers : {1u, 4u, 5u, 9u, 40u}) { + const std::vector worst{{ShaderStage::Vertex, (all & ~stencil) | Abi::DepthRemapPushBit, 48, buffers}, {ShaderStage::Geometry, all & ~stencil, 8, buffers}, {ShaderStage::Fragment, all, 48, buffers}}; + const auto placements = place(worst); + disjoint(worst, placements, ShaderRecompiler::PushFeatureDwords(true, false, true), ("stages with every root item and " + std::to_string(buffers) + " buffers each").c_str()); + const std::vector typical{{ShaderStage::Vertex, vertexItems, 6, buffers}, {ShaderStage::Fragment, pixelItems, 20, buffers}}; + const auto roomy = place(typical); + disjoint(typical, roomy, 0, ("typical stages with " + std::to_string(buffers) + " buffers each").c_str()); + require(!defaultCap || (buffers > Abi::PushedBufferLimit) == (roomy[1].bufferOverflow != Abi::NoPushPosition), "a typical pixel stage overflows only buffers past the push limit"); + const auto alone = place({typical[1]})[0]; + require(alone.items == roomy[1].items && alone.bufferRoots == roomy[1].bufferRoots && alone.bufferOverflow == roomy[1].bufferOverflow, "a typical pixel stage with buffers is placed as it is alone, so its fragment library is shared"); + const std::vector tessellation{{ShaderStage::Local, all & ~stencil, 4, buffers}, {ShaderStage::TessellationControl, all & ~stencil, 3, buffers}, {ShaderStage::TessellationEvaluation, (all & ~stencil) | Abi::DepthRemapPushBit, 10, buffers}, {ShaderStage::Fragment, all, 48, buffers}}; + disjoint(tessellation, place(tessellation), ShaderRecompiler::PushFeatureDwords(false, true, true), ("a tessellation pipeline with " + std::to_string(buffers) + " buffers per stage").c_str()); + const std::vector compute{{ShaderStage::Compute, all & ~stencil, 60, buffers}}; + const auto computed = place(compute); + disjoint(compute, computed, ShaderRecompiler::StagePushFeatures(ShaderStage::Compute, 0u), ("a compute stage with " + std::to_string(buffers) + " buffers").c_str()); + require(!defaultCap || computed[0] == ShaderRecompiler::StandalonePushPlacement(ShaderStage::Compute, compute[0].items, compute[0].pushed, buffers), "the compiler's standalone compute placement with overflowing buffers is the driver's"); + } + } std::puts("push data placements passed"); return 0; } catch (const std::exception& error) { diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 38fe9b7bcfb2..5799aef15002 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -8264,7 +8264,7 @@ void verifyPixelRequestSerialization() { minimal.context.pixel->layerExported = true; minimal.context.pixel->ditheredAlphaToCoverage = true; const auto encoded = serializer.Serialize(minimal); - require(requestPrefix(encoded, 8u) == "NVNQQTgAAAA=", "new requests did not use serialization version 56"); + require(requestPrefix(encoded, 8u) == "NVNQQTkAAAA=", "new requests did not use serialization version 57"); auto withBarycentric = minimal; withBarycentric.target.fragmentBarycentricBuiltins = true; require(serializer.Deserialize(serializer.Serialize(withBarycentric)).request.target.fragmentBarycentricBuiltins && !serializer.Deserialize(encoded).request.target.fragmentBarycentricBuiltins, "barycentric built-ins were lost in serialization"); @@ -8385,7 +8385,7 @@ void verifyPixelRequestSerialization() { for (std::size_t bytes = 0; bytes < 45u; ++bytes) { expectFailure([&] { static_cast(serializer.Deserialize(requestPrefix(encoded, mappingOffset + bytes))); }, "truncated data", "a truncated pixel mapping, packing, dual-source, alpha-to-coverage, stencil reference export flag, primitive class, layer export, dither or front-face flag, quad pixel mask or quad sample mask was accepted"); } - for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQTkAAAA="}) { + for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQToAAAA="}) { expectFailure([&] { static_cast(serializer.Deserialize(unsupported)); }, "serialization version", "an unsupported request version was accepted"); } static constexpr std::string_view version18Request{ @@ -8439,9 +8439,9 @@ std::vector decodeBase64(std::string_view text) { bytes.push_back(static_cast((chunk >> bits) & 0xffu)); } } - if (bytes.size() > 13u && bytes[4] == 56u) { - require(std::all_of(bytes.end() - 13, bytes.end(), [](std::uint8_t value) { return value == 0u; }), "a version 56 request in these checks set a GPU heap target field"); - bytes.resize(bytes.size() - 13u); + if (bytes.size() > 14u && bytes[4] == 57u) { + require(std::all_of(bytes.end() - 14, bytes.end(), [](std::uint8_t value) { return value == 0u; }), "a version 57 request in these checks set a GPU heap target field"); + bytes.resize(bytes.size() - 14u); bytes[4] = 55u; } return bytes; @@ -8449,8 +8449,8 @@ std::vector decodeBase64(std::string_view text) { std::string encodeBase64(std::vector bytes) { if (bytes.size() > 4u && bytes[4] == 55u) { - bytes[4] = 56u; - bytes.insert(bytes.end(), 13u, 0u); + bytes[4] = 57u; + bytes.insert(bytes.end(), 14u, 0u); } constexpr std::string_view alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string text; diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake index 0a4f4a8bccc8..2cd0da54e09d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake @@ -1,3 +1,10 @@ if(BUILD_TESTING) agc_add_gpu_heap_test(agc_driver_draw_recipe_moved_buffer) + agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_descriptors agc_driver_draw_recipe_moved_buffer_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_PUSHED_BUFFERS=0) + agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_pushed agc_driver_draw_recipe_moved_buffer_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_PUSHED_BUFFERS=1) + agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_overflow agc_driver_draw_recipe_moved_buffer_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_PUSHED_BUFFERS=1 APS5_PUSHED_BUFFER_RECORDS=0) endif() + diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp index e792fdf79bf6..cb8cd89f4dba 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp @@ -5,6 +5,7 @@ #include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libc/include/GuestAllocations.hpp" @@ -349,9 +350,20 @@ int main() { const std::array slices{First, Moved}; for (int round = 0; round < 2; ++round) Require(Submit(slices) == SecondAlphaByte, "the draw of the moved buffer did not read it"); const auto hitsBefore = AgcDriver::VulkanDevice::DrawRecipeHits(); + const auto pathsBefore = AgcDriver::Graphics::HeapBufferPaths(); Require(Submit(slices) == SecondAlphaByte, "the repeated draw of the moved buffer did not read it"); const auto hits = AgcDriver::VulkanDevice::DrawRecipeHits() - hitsBefore; - if (AgcDriver::Graphics::DrawRecipes() && std::getenv("APS5_VERIFY_DRAW_ENTRIES") == nullptr) Require(hits == slices.size(), "a repeated draw whose read-only buffer moved from its template's did not replay a recipe (" + std::to_string(hits) + " recipe hits for " + std::to_string(slices.size()) + " draws)"); + const auto paths = AgcDriver::Graphics::HeapBufferPaths(); + if (AgcDriver::Graphics::DrawRecipes() && std::getenv("APS5_VERIFY_DRAW_ENTRIES") == nullptr) { + Require(hits == slices.size(), "a repeated draw whose read-only buffer moved from its template's did not replay a recipe (" + std::to_string(hits) + " recipe hits for " + std::to_string(slices.size()) + " draws)"); + if (AgcDriver::Graphics::PushedBufferAddressesEnabled()) { + Require(paths.ringRuns == pathsBefore.ringRuns, "a recipe hit whose moved buffer the stage reads through its push data wrote " + std::to_string(paths.ringRuns - pathsBefore.ringRuns) + " heap descriptor runs"); + Require(paths.pushedStages - pathsBefore.pushedStages >= hits, "recipe hits over a moved buffer pushed the buffer addresses of " + std::to_string(paths.pushedStages - pathsBefore.pushedStages) + " stages for " + std::to_string(hits) + " hits"); + if (AgcDriver::Graphics::PushedBufferRecordCap() == 0u) Require(paths.overflowStages - pathsBefore.overflowStages >= hits, "recipe hits whose buffers all overflow the push data wrote the overflow block of " + std::to_string(paths.overflowStages - pathsBefore.overflowStages) + " stages for " + std::to_string(hits) + " hits"); + } else { + Require(paths.pushedStages == pathsBefore.pushedStages, "a stage pushed its buffer addresses although the device reads guest buffers through heap descriptors"); + } + } BufferMemory[Moved] = BufferAlpha; Require(Submit(slices) == BufferAlphaByte, "a recipe over a moved buffer drew the buffer's old contents after they changed"); BufferMemory[Moved] = SecondAlpha; diff --git a/core/shader/recompiler/CacheKey.hpp b/core/shader/recompiler/CacheKey.hpp index 227b8d60771e..b698f99a3f31 100644 --- a/core/shader/recompiler/CacheKey.hpp +++ b/core/shader/recompiler/CacheKey.hpp @@ -387,6 +387,7 @@ class RecompileCacheKey { append(key, value.descriptorMemory); append(key, value.heapDataUniformDwords); append(key, value.heapBufferDescriptors); + append(key, value.pushedBufferAddresses); append(key, value.ldsLockFences); append(key, value.meshWindowBuffer); append(key, value.hostInterpolationFirst); diff --git a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp index 7b26e8fc8591..43d6a36d4e81 100644 --- a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp +++ b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp @@ -916,7 +916,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const std::string buffer; Writer writer(buffer); writer.WriteU32(0x41505335u); - writer.WriteU32(56u); + writer.WriteU32(57u); writeShaderBinary(writer, request.shader); writeGuestContext(writer, request.context); writeSpirvTarget(writer, request.target); @@ -973,6 +973,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const writer.WriteBool(request.target.exactRobustLoads); writer.WriteBool(request.target.robustBufferAccess2); writer.WriteBool(request.target.heapBufferDescriptors); + writer.WriteBool(request.target.pushedBufferAddresses); return base64Encode(buffer); } @@ -981,7 +982,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const Reader reader(decoded); if (reader.ReadU32() != 0x41505335u) throw std::runtime_error("invalid recompile request signature"); const auto version = reader.ReadU32(); - if (version < 1u || version > 56u || version == 50u) throw std::runtime_error("unsupported recompile request serialization version"); + if (version < 1u || version > 57u || version == 50u) throw std::runtime_error("unsupported recompile request serialization version"); DeserializedRequest result{}; result.request.shader = readShaderBinary(reader, result.shaderCode, result.shaderHeader); result.request.context = readGuestContext(reader, result, version); @@ -1060,6 +1061,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const result.request.target.robustBufferAccess2 = reader.ReadBool(); result.request.target.heapBufferDescriptors = reader.ReadBool(); } + if (version >= 57u) result.request.target.pushedBufferAddresses = reader.ReadBool(); if (version >= 21u && reader.Remaining() != 0u) throw std::runtime_error("RequestSerializer: unexpected trailing data"); return result; } diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp index 40215a9ce071..c67f2168ae20 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp @@ -49,6 +49,7 @@ struct IrBindingLayout { std::uint32_t samplerSlotDwords = 0; std::uint32_t imageSlotDwords = 0; std::uint32_t bufferAddressDwords = 0; + bool pushedBuffers = false; std::vector pushedData; bool gpuResolvedImages = false; bool heapStorageImages = false; diff --git a/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp b/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp index 0710b88619b9..5170e981edef 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp @@ -27,6 +27,7 @@ struct AllocationOptions { bool stencilReplay = false; bool gpuResolvedImages = false; bool descriptorMemory = false; + bool pushedBufferAddresses = false; }; class BindingAllocator { diff --git a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp index 6a1ad6b729b2..1cfcabe1a47c 100644 --- a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp +++ b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp @@ -81,7 +81,7 @@ bool usesGds(const IrProgram& program) { } BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const BindingLayout& layout, const AllocationOptions& options) const { - const auto [registrationModules, stencilReplay, gpuResolvedImages, descriptorMemory] = options; + const auto [registrationModules, stencilReplay, gpuResolvedImages, descriptorMemory, pushedBufferAddresses] = options; IrProgramMetadata& metadata = program.Metadata(); if (!metadata.shaderInfoComplete || metadata.bindingLayoutComplete) { fail(metadata.shaderInfoComplete ? "shader binding layout failed: binding layout already allocated" @@ -178,6 +178,7 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin } } if (descriptorMemory && gpuResolvedImages) next.bufferAddressDwords = static_cast(info.buffers.size()) * RuntimeAbi::BufferAddressWords; + next.pushedBuffers = pushedBufferAddresses && next.bufferAddressDwords != 0u; if (next.UsesDataAddress()) placePushedData(next); std::vector samplers; diff --git a/core/shader/recompiler/PipelineSpecialization.hpp b/core/shader/recompiler/PipelineSpecialization.hpp index 5cc9f8e9a36c..ff934c14df74 100644 --- a/core/shader/recompiler/PipelineSpecialization.hpp +++ b/core/shader/recompiler/PipelineSpecialization.hpp @@ -47,6 +47,9 @@ inline constexpr std::uint32_t HeapCountBase = 8256u; inline constexpr std::uint32_t MipCountBase = 8320u; inline constexpr std::uint32_t StoreQuantizeBase = 12288u; inline constexpr std::uint32_t StoreQuantizeWords = 4u; +inline constexpr std::uint32_t BufferRootPosition = 57856u; +inline constexpr std::uint32_t BufferRootCount = 4u; +inline constexpr std::uint32_t BufferOverflowPosition = BufferRootPosition + BufferRootCount; inline constexpr std::uint32_t DescriptorIndexBase = 16384u; inline constexpr std::uint32_t DescriptorIndexStride = 128u; inline constexpr std::uint32_t FoldOffsetBase = 57344u; @@ -63,7 +66,7 @@ inline constexpr std::uint32_t DescriptorIndex(std::uint32_t binding, std::uint3 } inline constexpr bool IsPushPlacement(std::uint32_t id) { - return id == PushedDataBase || id == PushedDataCount || (id >= RootItemPositionBase && id < HeapCountBase); + return id == PushedDataBase || id == PushedDataCount || (id >= BufferRootPosition && id <= BufferOverflowPosition) || (id >= RootItemPositionBase && id < HeapCountBase); } inline constexpr bool IsWorkgroupOffset(std::uint32_t id) { diff --git a/core/shader/recompiler/PushDataLayout.hpp b/core/shader/recompiler/PushDataLayout.hpp index 0bccc9015eee..3c7f0914811d 100644 --- a/core/shader/recompiler/PushDataLayout.hpp +++ b/core/shader/recompiler/PushDataLayout.hpp @@ -25,11 +25,23 @@ struct PushStage { PushPart part = PushPart::PreRasterization; std::uint32_t items = 0; std::uint32_t pushedWanted = 0; + std::uint32_t pushedBuffers = 0; }; +static_assert(RuntimeAbi::PushedBufferLimit == PipelineSpecialization::BufferRootCount); + +constexpr std::array MakeBufferRoots() { + std::array roots{}; + roots.fill(RuntimeAbi::NoPushPosition); + return roots; +} + struct StagePushPlacement { std::array items{}; RuntimeAbi::PushedPlacement pushed; + std::array bufferRoots = MakeBufferRoots(); + std::uint32_t bufferOverflow = RuntimeAbi::NoPushPosition; + std::uint32_t pushedBuffers = 0; [[nodiscard]] std::uint32_t Item(RuntimeAbi::RootItem item) const { return items[static_cast(item)]; } bool operator==(const StagePushPlacement&) const = default; @@ -58,7 +70,7 @@ constexpr std::uint64_t StagePushFeatures(ShaderStage stage, std::uint32_t pushI return mask; } -inline std::vector PlacePushData(std::span stages, std::uint64_t occupied) { +inline std::vector PlacePushData(std::span stages, std::uint64_t occupied, std::uint32_t pushedRecords = RuntimeAbi::PushedBufferLimit) { namespace Abi = RuntimeAbi; constexpr std::uint32_t total = Abi::PushDataDwords; std::vector placements(stages.size()); @@ -70,14 +82,19 @@ inline std::vector PlacePushData(std::span } return true; }; - const auto take = [&](std::uint32_t width, bool aligned, bool top) { + const auto tryTake = [&](std::uint32_t width, bool aligned, bool top) { for (std::uint32_t step = 0; step + width <= total; ++step) { const auto first = top ? total - width - step : step; if ((aligned && first % 2u != 0u) || !isFree(first, width)) continue; for (auto dword = first; dword < first + width; ++dword) used |= 1ull << dword; return first; } - throw std::runtime_error("the push data has no room for a pipeline's root"); + return Abi::NoPushPosition; + }; + const auto take = [&](std::uint32_t width, bool aligned, bool top) { + const auto first = tryTake(width, aligned, top); + if (first == Abi::NoPushPosition) throw std::runtime_error("the push data has no room for a pipeline's root"); + return first; }; const auto placeRoot = [&](std::uint32_t items, bool top, std::array& positions) { for (const bool addresses : {true, false}) { @@ -89,7 +106,9 @@ inline std::vector PlacePushData(std::span } }; constexpr auto globalItems = Abi::RootItemBit(Abi::RootItem::ShaderData) - 1u; - for (const auto part : {PushPart::Fragment, PushPart::Compute, PushPart::PreRasterization}) { + constexpr std::array parts{PushPart::Fragment, PushPart::Compute, PushPart::PreRasterization}; + std::vector overflows(stages.size(), Abi::NoPushPosition); + for (const auto part : parts) { const bool top = part != PushPart::PreRasterization; std::uint32_t globals = 0; for (const auto& stage : stages) { @@ -104,8 +123,35 @@ inline std::vector PlacePushData(std::span if ((stages[index].items & globalItems & (1u << item)) != 0u) placements[index].items[item] = shared[item]; } placeRoot(stages[index].items & ~globalItems, top, placements[index].items); + placements[index].pushedBuffers = stages[index].pushedBuffers; } } + const auto recordsOf = [&](std::size_t index) { return std::min({stages[index].pushedBuffers, pushedRecords, Abi::PushedBufferLimit}); }; + for (const auto part : parts) { + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part == part && stages[index].pushedBuffers != 0u) overflows[index] = tryTake(2u, true, part != PushPart::PreRasterization); + } + } + for (const auto part : parts) { + const bool top = part != PushPart::PreRasterization; + const auto reserved = part == PushPart::Fragment ? PushFeatureDwords(true, true, true) & ~used : 0u; + used |= reserved; + for (std::size_t index = 0; index < stages.size(); ++index) { + const auto buffers = stages[index].pushedBuffers; + if (stages[index].part != part || buffers == 0u) continue; + const auto records = recordsOf(index); + bool overflowed = buffers > records; + for (std::uint32_t buffer = 0; buffer < records; ++buffer) { + placements[index].bufferRoots[buffer] = tryTake(Abi::PushedBufferWords, true, top); + overflowed = overflowed || placements[index].bufferRoots[buffer] == Abi::NoPushPosition; + } + if (overflowed && overflows[index] == Abi::NoPushPosition) throw std::runtime_error("the push data has no room for a stage's buffer addresses"); + if (overflowed) placements[index].bufferOverflow = overflows[index]; + else if (overflows[index] != Abi::NoPushPosition) used &= ~(3ull << overflows[index]); + } + used &= ~reserved; + } + std::vector> runs; for (std::uint32_t dword = 0; dword < total;) { if ((used >> dword & 1ull) != 0u) { @@ -183,8 +229,8 @@ inline std::vector PlacePushData(std::span return placements; } -inline StagePushPlacement StandalonePushPlacement(ShaderStage stage, std::uint32_t pushItems, std::size_t pushedWanted) { - const PushStage pushStage{PushPartOf(stage), pushItems & RootItemMask, static_cast(pushedWanted)}; +inline StagePushPlacement StandalonePushPlacement(ShaderStage stage, std::uint32_t pushItems, std::size_t pushedWanted, std::uint32_t pushedBuffers = 0u) { + const PushStage pushStage{PushPartOf(stage), pushItems & RootItemMask, static_cast(pushedWanted), pushedBuffers}; return PlacePushData(std::span(&pushStage, 1), StagePushFeatures(stage, pushItems)).front(); } @@ -192,6 +238,8 @@ inline void AppendPushSpecialization(std::vector for (std::uint32_t item = 0; item < RuntimeAbi::RootItemCount; ++item) { if (placement.items[item] != RuntimeAbi::NoPushPosition) constants.push_back({PipelineSpecialization::RootItemPositionBase + item, placement.items[item]}); } + for (std::uint32_t buffer = 0; buffer < std::min(placement.pushedBuffers, RuntimeAbi::PushedBufferLimit); ++buffer) constants.push_back({PipelineSpecialization::BufferRootPosition + buffer, placement.bufferRoots[buffer]}); + if (placement.pushedBuffers != 0u) constants.push_back({PipelineSpecialization::BufferOverflowPosition, placement.bufferOverflow}); constants.push_back({PipelineSpecialization::PushedDataBase, placement.pushed.base}); constants.push_back({PipelineSpecialization::PushedDataCount, placement.pushed.count}); } diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 5c774505e018..7e04a32e27e9 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -729,7 +729,7 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) bool registration = request.target.registrationModules && (request.shader.stage == ShaderStage::Fragment || heapVertex); program.Metadata().bindingLayoutComplete = false; const bool stencilReplay = request.shader.stage == ShaderStage::Fragment && std::ranges::any_of(program.Info().outputs, [](const StageOutput& output) { return output.kind == StageOutputKind::StencilRef; }) && std::ranges::find(request.target.supportedCapabilities, static_cast(spv::CapabilityStencilExportEXT)) == request.target.supportedCapabilities.end(); - AllocationOptions allocation {.registrationModules = registration, .stencilReplay = stencilReplay, .gpuResolvedImages = request.target.gpuResolvedImages, .descriptorMemory = request.target.descriptorMemory}; + AllocationOptions allocation {.registrationModules = registration, .stencilReplay = stencilReplay, .gpuResolvedImages = request.target.gpuResolvedImages, .descriptorMemory = request.target.descriptorMemory, .pushedBufferAddresses = request.target.descriptorMemory && request.target.pushedBufferAddresses}; auto bindings = bindingAllocator.Allocate(program, request.layout, allocation); SpirvTargetOptions targetOptions {}; @@ -830,6 +830,7 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) result.samplerSlotDword = result.gpuResolvedImages ? bindings.layout.SamplerSlotDword() : 0u; result.bufferAddressDword = bindings.layout.bufferAddressDwords != 0u ? bindings.layout.BufferAddressDword() : 0u; result.bufferAddressCount = bindings.layout.bufferAddressDwords / RuntimeAbi::BufferAddressWords; + result.pushedBufferCount = bindings.layout.pushedBuffers ? result.bufferAddressCount : 0u; result.dataAddressPush = bindings.layout.UsesDataAddress(); result.pushedData = bindings.layout.pushedData; result.bdaStores = emitted.bdaStores; @@ -1292,6 +1293,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil .samplerSlotDword = artifact.samplerSlotDword, .bufferAddressDword = artifact.bufferAddressDword, .bufferAddressCount = artifact.bufferAddressCount, + .pushedBufferCount = artifact.pushedBufferCount, .pushedData = artifact.pushedData, .pushItems = artifact.pushItems, .dataAddressPush = artifact.dataAddressPush, @@ -1398,7 +1400,7 @@ RecompileResult materializeResult(const CompiledVariant& variant, const Recompil constants.push_back({PipelineSpecialization::MeshLayerBase, 0u}); constants.push_back({PipelineSpecialization::MeshLayerCount, 0xffffffffu}); constants.push_back({PipelineSpecialization::HeapImageSlots, RuntimeAbi::GpuImageHeapSlots}); - if (artifact.dataAddressPush) AppendPushSpecialization(constants, StandalonePushPlacement(request.shader.stage, artifact.pushItems, artifact.pushedData.size())); + if (artifact.dataAddressPush) AppendPushSpecialization(constants, StandalonePushPlacement(request.shader.stage, artifact.pushItems, artifact.pushedData.size(), artifact.pushedBufferCount)); std::size_t index = 0; if (variant.bindings.layout.UsesPushData()) constants.push_back({PipelineSpecialization::PushDataOffset, moduleKey[index++]}); if (StencilInPush(artifact, variant.bindings.layout)) constants.push_back({PipelineSpecialization::StencilReferenceOffset, moduleKey[index++]}); diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index cc232e97e9e0..e0950c6194b8 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -366,6 +366,7 @@ struct SpirvTarget { bool descriptorMemory = false; std::uint32_t heapDataUniformDwords = 0; bool heapBufferDescriptors = false; + bool pushedBufferAddresses = false; bool ldsLockFences = false; bool fragmentBarycentricBuiltins = false; bool meshWindowBuffer = false; @@ -804,6 +805,7 @@ struct CompiledShaderArtifact { std::uint32_t samplerSlotDword = 0; std::uint32_t bufferAddressDword = 0; std::uint32_t bufferAddressCount = 0; + std::uint32_t pushedBufferCount = 0; std::vector pushedData; std::uint32_t pushItems = 0; bool dataAddressPush = false; diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index df5f32138f37..4cdc4cf0cba0 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -25,6 +25,9 @@ inline constexpr std::uint32_t FirstAtomicImageBinding = FirstStorageImageBindin inline constexpr std::uint32_t FirstAtomic64ImageBinding = FirstStorageImageBinding + 3u * StorageKindStride; inline constexpr std::uint32_t SamplerSlotWords = 2u; inline constexpr std::uint32_t BufferAddressWords = 4u; +inline constexpr std::uint32_t PushedBufferWords = 3u; +inline constexpr std::uint32_t PushedBufferLimit = 4u; +inline constexpr std::uint32_t OverflowRecordWords = 4u; inline constexpr bool AtomicImageKind(std::uint32_t kind) { return kind >= FirstAtomicImageBinding && kind < FirstAtomic64ImageBinding; } inline constexpr bool Atomic64ImageKind(std::uint32_t kind) { return kind >= FirstAtomic64ImageBinding && kind < FirstImageBinding + ImageBindingCount; } inline constexpr bool UintStorageImageKind(std::uint32_t kind) { return kind >= FirstUintStorageImageBinding && kind < FirstAtomicImageBinding; } diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index 705a719c3ca7..3403fa0ba697 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -85,10 +85,10 @@ std::filesystem::path ShaderCacheDirectory() { namespace ShaderRecompiler::ShaderDiskCache { #if defined(__linux__) && defined(__x86_64__) && defined(__GLIBCXX__) -static_assert(sizeof(CompiledShaderArtifact) == 328, "CompiledShaderArtifact changed: update the artifact encoder"); +static_assert(sizeof(CompiledShaderArtifact) == 336, "CompiledShaderArtifact changed: update the artifact encoder"); static_assert(sizeof(ShaderInvocation) == 240, "ShaderInvocation changed: update the invocation encoder"); #if defined(__cpp_lib_atomic_shared_ptr) -static_assert(sizeof(RecompileResult) == 648, "RecompileResult changed: update EncodeResult and DecodeResult"); +static_assert(sizeof(RecompileResult) == 656, "RecompileResult changed: update EncodeResult and DecodeResult"); #endif static_assert(sizeof(DescriptorBinding) == 704, "DescriptorBinding changed: update the binding encoder"); static_assert(sizeof(VertexAttribute) == 32, "VertexAttribute changed: update the attribute encoder"); @@ -532,6 +532,7 @@ void encodeArtifact(Writer& writer, const CompiledShaderArtifact& result) { writer.Value(result.samplerSlotDword); writer.Value(result.bufferAddressDword); writer.Value(result.bufferAddressCount); + writer.Value(result.pushedBufferCount); writer.Values(std::span(result.pushedData)); writer.Value(result.pushItems); writer.Value(result.dataAddressPush); @@ -607,6 +608,7 @@ void decodeArtifact(Reader& reader, CompiledShaderArtifact& result) { reader.Value(result.samplerSlotDword); reader.Value(result.bufferAddressDword); reader.Value(result.bufferAddressCount); + reader.Value(result.pushedBufferCount); reader.Values(result.pushedData); reader.Value(result.pushItems); reader.Value(result.dataAddressPush); @@ -772,6 +774,7 @@ void encodeLayout(Writer& writer, const IrBindingLayout& layout) { writer.Value(layout.samplerSlotDwords); writer.Value(layout.imageSlotDwords); writer.Value(layout.bufferAddressDwords); + writer.Value(layout.pushedBuffers); writer.Values(std::span(layout.pushedData)); writer.Value(layout.heapStorageImages); writer.Value(layout.gpuResolvedImages); @@ -794,6 +797,7 @@ void decodeLayout(Reader& reader, IrBindingLayout& layout) { reader.Value(layout.samplerSlotDwords); reader.Value(layout.imageSlotDwords); reader.Value(layout.bufferAddressDwords); + reader.Value(layout.pushedBuffers); reader.Values(layout.pushedData); reader.Value(layout.heapStorageImages); reader.Value(layout.gpuResolvedImages); diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index 0d5dbc7b8201..cebadf9d7e69 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -13,7 +13,7 @@ namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 61; +inline constexpr std::uint32_t FormatVersion = 63; enum class LoadStatus { Loaded, diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp index 6f4363820763..eda4baeedfb5 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp @@ -14,6 +14,7 @@ std::uint32_t EmitShaderDataWordLoad(SpirvEmitterState& state, std::uint32_t ind std::uint32_t ComposeAddress64(SpirvEmitterState& state, const std::function& loadLow, const std::function& loadHigh); std::uint32_t EmitAlignedLoadU32(SpirvEmitterState& state, std::uint32_t pointer); std::uint32_t EmitRootItemDword(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t word); +std::uint32_t EmitBufferRootDword(SpirvEmitterState& state, std::uint32_t buffer, std::uint32_t word); std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); std::uint32_t EmitRootAddress(SpirvEmitterState& state, RuntimeAbi::RootItem item); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp index e5e0d43e50e8..dbc92e3f1a08 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp @@ -282,7 +282,7 @@ std::vector SpirvEmitter::Emit(const IrProgram& program, const Sh state.registrationModules = target.registrationModules; state.gpuResolvedImages = target.gpuResolvedImages; state.heapDataUniformDwords = target.heapDataUniformDwords; - state.heapBufferDescriptors = target.heapBufferDescriptors; + state.heapBufferDescriptors = target.heapBufferDescriptors && !program.Metadata().bindings.pushedBuffers; state.fragmentDescriptorSet = target.fragmentDescriptorSet; state.meshBarycentricPixel = target.meshBarycentricPixel; state.meshBarycentricVertex = target.meshBarycentricVertex; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 192b88ea93bc..d9cdc08186df 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -40,6 +40,42 @@ std::uint32_t EmitAlignedLoadU32(SpirvEmitterState& state, std::uint32_t pointer return value; } +namespace { + +std::uint32_t placedPushDword(SpirvEmitterState& state, std::uint32_t specialization, std::uint32_t word) { + const auto u32 = TypeU32(state); + const auto position = state.module.SpecializationConstant(u32, specialization, RuntimeAbi::NoPushPosition); + const auto placed = Binary(state, spv::OpINotEqual, TypeBool(state), position, ConstantU32(state, RuntimeAbi::NoPushPosition)); + const auto index = Select(state, u32, placed, Binary(state, spv::OpIAdd, u32, position, ConstantU32(state, word)), ConstantU32(state, 0u)); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), index); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, u32, value, pointer); + return value; +} + +std::uint32_t overflowDword(SpirvEmitterState& state, std::uint32_t buffer, std::uint32_t word) { + const auto address = ComposeAddress64(state, [&] { return placedPushDword(state, PipelineSpecialization::BufferOverflowPosition, 0u); }, [&] { return placedPushDword(state, PipelineSpecialization::BufferOverflowPosition, 1u); }); + const auto words = ReadOnlyStorageBufferType(state, TypeU32(state), 4u); + const auto block = state.module.AllocateId(); + state.module.AddFunction(spv::OpConvertUToPtr, TypePointer(state, spv::StorageClassPhysicalStorageBuffer, words), block, address); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePhysicalU32Pointer(state), pointer, block, ConstantU32(state, 0u), ConstantU32(state, buffer * RuntimeAbi::OverflowRecordWords + word)); + return EmitAlignedLoadU32(state, pointer); +} + +} + +std::uint32_t EmitBufferRootDword(SpirvEmitterState& state, std::uint32_t buffer, std::uint32_t word) { + if (!state.program.Metadata().bindings.pushedBuffers) FailEmit("only a stage with pushed buffer addresses reads the buffer root"); + if (word >= RuntimeAbi::PushedBufferWords) FailEmit("a pushed buffer record has no such word"); + if (buffer >= RuntimeAbi::PushedBufferLimit) return overflowDword(state, buffer, word); + const auto u32 = TypeU32(state); + const auto position = state.module.SpecializationConstant(u32, PipelineSpecialization::BufferRootPosition + buffer, RuntimeAbi::NoPushPosition); + const auto placed = Binary(state, spv::OpINotEqual, TypeBool(state), position, ConstantU32(state, RuntimeAbi::NoPushPosition)); + return EmitValueIfElse(state, placed, u32, [&] { return placedPushDword(state, PipelineSpecialization::BufferRootPosition + buffer, word); }, [&] { return overflowDword(state, buffer, word); }); +} + std::uint32_t EmitRootItemDword(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t word) { if (!state.program.Metadata().bindings.UsesDataAddress()) FailEmit("the root is read only by stages that take their data through it"); state.pushItems |= RuntimeAbi::RootItemBit(item); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index d91059161cd9..4090d5b7db9f 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -233,12 +233,14 @@ MemoryResourceAccess directAccess(SpirvValueEmitContext& context, const IrValue& if (state.addressedBuffers) { const auto element = ResourceForDescriptor(state, DescriptorBindingKind::Buffers, memory.resource); const auto dword = state.program.Metadata().bindings.BufferAddressDword() + element * RuntimeAbi::BufferAddressWords; + const bool pushed = state.program.Metadata().bindings.pushedBuffers; + const auto word = [&](std::uint32_t index) { return pushed ? EmitBufferRootDword(state, element, index) : EmitShaderDataDwordLoad(state, dword + index); }; const auto u64 = TypeScalarU64(state); - auto address = ComposeAddress64(state, [&] { return EmitShaderDataDwordLoad(state, dword); }, [&] { return EmitShaderDataDwordLoad(state, dword + 1u); }); + auto address = ComposeAddress64(state, [&] { return word(0u); }, [&] { return word(1u); }); MemoryResourceAccess access; access.kind = memory.kind; access.physical = true; - access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), EmitShaderDataDwordLoad(state, dword + 2u), ConstantU32(state, wide ? 3u : 2u)); + access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), word(2u), ConstantU32(state, wide ? 3u : 2u)); if (state.program.Metadata().bindings.UsesDataAddress()) { const auto empty = Binary(state, spv::OpIEqual, TypeBool(state), access.length, ConstantU32(state, 0u)); address = Select(state, u64, empty, EmitRootAddress(state, RuntimeAbi::RootItem::ShaderData), address); diff --git a/core/shader/recompiler/tests/RequestSerializerTests.cpp b/core/shader/recompiler/tests/RequestSerializerTests.cpp index 260237a59f3e..64e9d8565e85 100644 --- a/core/shader/recompiler/tests/RequestSerializerTests.cpp +++ b/core/shader/recompiler/tests/RequestSerializerTests.cpp @@ -180,16 +180,16 @@ std::string EncodeBase64(const std::vector& bytes) { return text; } std::vector AtVersion55(std::vector bytes) { - Require(bytes.size() > 21u && bytes[4] == 56u && std::all_of(bytes.end() - 13, bytes.end(), [](std::uint8_t value) { return value == 0u; })); - bytes.resize(bytes.size() - 13u); + Require(bytes.size() > 22u && bytes[4] == 57u && std::all_of(bytes.end() - 14, bytes.end(), [](std::uint8_t value) { return value == 0u; })); + bytes.resize(bytes.size() - 14u); bytes[4] = 55u; return bytes; } -std::string EncodeAtVersion56(std::vector bytes) { +std::string EncodeAtWriterVersion(std::vector bytes) { Require(bytes.size() > 8u && bytes[4] == 55u); - bytes[4] = 56u; - bytes.insert(bytes.end(), 13u, 0u); + bytes[4] = 57u; + bytes.insert(bytes.end(), 14u, 0u); return EncodeBase64(bytes); } @@ -212,8 +212,8 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { Require(replay.request.target.heapDataUniformDwords == profile.heapDataUniformDwords); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 56u && bytes.size() > 13u); - bytes.resize(bytes.size() - 13u); + Require(bytes[4] == 57u && bytes.size() > 14u); + bytes.resize(bytes.size() - 14u); for (const std::uint8_t version : {55u, 54u, 53u, 52u}) { if (version == 53u) bytes.resize(bytes.size() - 2u); if (version == 52u) bytes.pop_back(); @@ -222,7 +222,7 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { Require(!older.gpuResolvedImages && !older.descriptorMemory && older.heapDataUniformDwords == 0u); } bytes.push_back(0u); - bytes[4] = 56u; + bytes[4] = 57u; bool truncated = false; try { static_cast(serializer.Deserialize(EncodeBase64(bytes))); @@ -254,15 +254,33 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { Require(serializer.Deserialize(encoded).request.target.heapBufferDescriptors == descriptors); Require((encoded == serializer.Serialize(limits)) == !descriptors); auto bytes = DecodeBase64(encoded); - bytes.resize(bytes.size() - 13u); + bytes.resize(bytes.size() - 14u); bytes[4] = 55u; Require(!serializer.Deserialize(EncodeBase64(bytes)).request.target.heapBufferDescriptors); } } +void VerifyPushedBufferAddresses(const ShaderRecompiler::RequestSerializer& serializer) { + for (const bool pushed : {false, true}) { + ShaderRecompiler::RecompileRequest request{}; + request.target.gpuResolvedImages = true; + request.target.descriptorMemory = true; + request.target.heapBufferDescriptors = true; + request.target.pushedBufferAddresses = pushed; + const auto encoded = serializer.Serialize(request); + Require(serializer.Deserialize(encoded).request.target.pushedBufferAddresses == pushed && serializer.Serialize(serializer.Deserialize(encoded).request) == encoded); + auto bytes = DecodeBase64(encoded); + Require(bytes[4] == 57u && bytes.back() == (pushed ? 1u : 0u)); + bytes.pop_back(); + bytes[4] = 56u; + const auto older = serializer.Deserialize(EncodeBase64(bytes)).request.target; + Require(!older.pushedBufferAddresses && older.gpuResolvedImages && older.descriptorMemory && older.heapBufferDescriptors); + } +} + void VerifyKeyedTargetFields(const ShaderRecompiler::RequestSerializer& serializer) { using Field = bool ShaderRecompiler::SpirvTarget::*; - constexpr std::array fields{&ShaderRecompiler::SpirvTarget::ldsLockFences, &ShaderRecompiler::SpirvTarget::meshWindowBuffer, &ShaderRecompiler::SpirvTarget::waveLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::deviceScopeLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::exactRobustLoads, &ShaderRecompiler::SpirvTarget::robustBufferAccess2}; + constexpr std::array fields{&ShaderRecompiler::SpirvTarget::ldsLockFences, &ShaderRecompiler::SpirvTarget::meshWindowBuffer, &ShaderRecompiler::SpirvTarget::waveLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::deviceScopeLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::exactRobustLoads, &ShaderRecompiler::SpirvTarget::robustBufferAccess2, &ShaderRecompiler::SpirvTarget::pushedBufferAddresses}; const ShaderRecompiler::RecompileRequest defaults{}; const auto defaultEncoded = serializer.Serialize(defaults); for (std::size_t chosen = 0; chosen <= fields.size(); ++chosen) { @@ -274,8 +292,8 @@ void VerifyKeyedTargetFields(const ShaderRecompiler::RequestSerializer& serializ for (std::size_t index = 0; index < fields.size(); ++index) Require(replay.request.target.*fields[index] == (chosen == fields.size() || index == chosen)); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 56u && bytes.size() > 13u); - bytes.resize(bytes.size() - 13u); + Require(bytes[4] == 57u && bytes.size() > 14u); + bytes.resize(bytes.size() - 14u); for (const std::uint8_t version : {55u, 54u, 53u, 52u}) { if (version == 53u) bytes.resize(bytes.size() - 2u); if (version == 52u) bytes.pop_back(); @@ -449,7 +467,7 @@ int main() { upgraded.push_back(0u); upgraded.push_back(0u); upgraded.push_back(0u); - Require(serializer.Serialize(request) == EncodeAtVersion56(upgraded)); + Require(serializer.Serialize(request) == EncodeAtWriterVersion(upgraded)); auto truncated = bytes; truncated.pop_back(); bool rejected = false; @@ -463,7 +481,7 @@ int main() { auto vertex23 = bytes; vertex23[4] = 23u; const auto vertexReplay = serializer.Deserialize(EncodeBase64(vertex23)); - Require(serializer.Serialize(vertexReplay.request) == EncodeAtVersion56(upgraded)); + Require(serializer.Serialize(vertexReplay.request) == EncodeAtWriterVersion(upgraded)); continue; } for (const bool layer : {false, true}) { @@ -498,7 +516,7 @@ int main() { layered.push_back(0u); layered.push_back(0u); layered.push_back(0u); - Require(serializer.Serialize(layerReplay.request) == EncodeAtVersion56(layered)); + Require(serializer.Serialize(layerReplay.request) == EncodeAtWriterVersion(layered)); } } } @@ -532,7 +550,7 @@ int main() { bytes.push_back(0u); bytes.push_back(0u); bytes.push_back(0u); - Require(serializer.Serialize(replay.request) == EncodeAtVersion56(bytes)); + Require(serializer.Serialize(replay.request) == EncodeAtWriterVersion(bytes)); auto truncated23 = DecodeBase64(encoded23); truncated23.pop_back(); @@ -674,13 +692,13 @@ int main() { upgraded.push_back(0u); upgraded.push_back(0u); upgraded.push_back(0u); - Require(serializer.Serialize(request) == EncodeAtVersion56(upgraded)); + Require(serializer.Serialize(request) == EncodeAtWriterVersion(upgraded)); const auto replay38 = serializer.Deserialize(EncodeBase64(main38)); Require(replay38.request.graphics.has_value() && replay38.request.graphics->tessellation.has_value() == fixture.tessellation); Require(!fixture.tessellation || (!replay38.request.graphics->tessellation->mergedHull && replay38.request.graphics->tessellation->primitiveGroupSize == 37u && replay38.request.graphics->tessellation->breakAtInstance)); Require(replay38.request.graphics->draw.indexAddress == 0xabcdef3400u && replay38.request.graphics->draw.indexCount == 57u && replay38.request.graphics->draw.indexElementBytes == 4u && replay38.request.graphics->draw.instanceCount == 9u); Require(replay38.request.target.float16DenormPreserve == preserve); - Require(serializer.Serialize(replay38.request) == EncodeAtVersion56(upgraded)); + Require(serializer.Serialize(replay38.request) == EncodeAtWriterVersion(upgraded)); if (fixture.tessellation) { for (const bool merged : {false, true}) { auto pointed = request; @@ -697,13 +715,13 @@ int main() { if (fixture.pixel) EraseTargetMergeVersion55Fields(version54, 333); version54[4] = 54u; const auto replay54 = serializer.Deserialize(EncodeBase64(version54)); - Require(serializer.Serialize(replay54.request) == EncodeAtVersion56(version55)); + Require(serializer.Serialize(replay54.request) == EncodeAtWriterVersion(version55)); auto version53 = version54; version53.resize(version53.size() - 2u); version53[4] = 53u; const auto replay53 = serializer.Deserialize(EncodeBase64(version53)); Require(replay53.request.graphics->tessellation->mergedHull == merged && replay53.request.context.vertex->pointList && !replay53.request.target.float16WidenNans && !replay53.request.target.float16NarrowNans); - Require(serializer.Serialize(replay53.request) == EncodeAtVersion56(version55)); + Require(serializer.Serialize(replay53.request) == EncodeAtWriterVersion(version55)); auto version52 = version53; version52.pop_back(); version52[4] = 52u; @@ -711,7 +729,7 @@ int main() { version51.pop_back(); version51[4] = 51u; const auto replay51 = serializer.Deserialize(EncodeBase64(version51)); - Require(serializer.Serialize(replay51.request) == EncodeAtVersion56(version55)); + Require(serializer.Serialize(replay51.request) == EncodeAtWriterVersion(version55)); auto version48 = version51; version48.pop_back(); version48[4] = 48u; @@ -719,7 +737,7 @@ int main() { version46.pop_back(); version46[4] = 46u; const auto replay46 = serializer.Deserialize(EncodeBase64(version46)); - Require(serializer.Serialize(replay46.request) == EncodeAtVersion56(version55)); + Require(serializer.Serialize(replay46.request) == EncodeAtWriterVersion(version55)); auto version45 = version55; version45.resize(version45.size() - 6u); if (fixture.pixel) EraseDefaultTargetMerge(version45, 333); @@ -732,7 +750,7 @@ int main() { version43.pop_back(); version43[4] = 43u; const auto replay43 = serializer.Deserialize(EncodeBase64(version43)); - Require(serializer.Serialize(replay43.request) == EncodeAtVersion56(version55)); + Require(serializer.Serialize(replay43.request) == EncodeAtWriterVersion(version55)); Require(replay43.request.graphics->tessellation->mergedHull == merged && replay43.request.context.vertex->pointList && replay43.request.context.vertex->pointSize == 3.0f && replay43.request.context.vertex->pointSizeMin == 1.0f && replay43.request.context.vertex->pointSizeMax == 8.0f); auto version42 = version43; version42.resize(version42.size() - 13u); @@ -776,7 +794,7 @@ int main() { main25.push_back(0u); main25.push_back(0u); main25.push_back(0u); - Require(serializer.Serialize(replay25.request) == EncodeAtVersion56(main25)); + Require(serializer.Serialize(replay25.request) == EncodeAtWriterVersion(main25)); } } } @@ -809,7 +827,7 @@ int main() { const auto replay40 = serializer.Deserialize(EncodeBase64(version40)); Require(!replay40.request.target.float32DenormPreserve && replay40.request.target.float32FlushToZero == !preserve); auto future = bytes; - future[4] = 57u; + future[4] = 58u; bool futureRejected = false; try { static_cast(serializer.Deserialize(EncodeBase64(future))); @@ -1092,7 +1110,7 @@ int main() { upgraded.push_back(0u); upgraded.push_back(0u); upgraded.push_back(0u); - Require(serializer.Serialize(replay49.request) == EncodeAtVersion56(upgraded)); + Require(serializer.Serialize(replay49.request) == EncodeAtWriterVersion(upgraded)); for (auto skipped : {bytes, upgraded}) { skipped[4] = 50u; bool skippedRejected = false; @@ -1168,6 +1186,7 @@ int main() { VerifyHeapProfile(serializer); VerifyKeyedTargetFields(serializer); + VerifyPushedBufferAddresses(serializer); return 0; } diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 3e47a5aba0ed..8894752d003b 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -437,6 +437,8 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_PROFILE_DRAW` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp` | | prints the per-phase driver and draw timing totals | | `APS5_PROFILE_GPU` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records the GPU time of recorded work by key from batch timestamps | | `APS5_PROFILE_GPU_DRAWS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp`, `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | with APS5_PROFILE_GPU, records the GPU time of each recorded draw by its fragment program's variant id and prints a [drawvariant] line with the code address behind each variant id once (draws that do not use a recipe only; the [gputime] line labels each `draw 0x`, the id [drawvariant] prints, and the ranges share the batch's query cap) | +| `APS5_PUSHED_BUFFER_RECORDS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 4 | test cap on the guest buffer records a heap stage keeps in its push data; the rest go to its per-draw overflow block | +| `APS5_PUSHED_BUFFERS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | NVIDIA 1, other vendors 0 | with `APS5_GPU_HEAP`, `1` passes every heap stage's guest buffer addresses and sizes in its push data (four records, the rest in a per-draw overflow block) and `0` reads them through heap buffer descriptors written per draw | | `APS5_REAP_EACH_PACKET` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/DeferredLabels.cpp` | | reaps deferred labels after every packet | | `APS5_REGISTRATION_PREPARE_COMMIT_GB` | number | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp` | half of physical RAM | stops preparing newly registered shaders ahead of use when process-private memory reaches this GiB budget; `0` disables registration-time preparation | | `APS5_RELEASE_ON_UNLOCK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | destroys deferred batches on the unlocking thread instead of a release thread | From 56ec7ed986b8ce0e0879059b270ac4d22064144d Mon Sep 17 00:00:00 2001 From: Dean Galvin Date: Sun, 8 Nov 2026 21:10:12 +1300 Subject: [PATCH 143/269] fix(agc): keep the ring words pool in HostThreadLocal The Windows prx_thread_local_destructors check flagged libSceAgcDriver: the thread_local vector of shared_ptr in RecycledRingWords registers a destructor that runs after the emulated TLS is freed. Move the pool and its cursor into HostThreadLocal, as the other draw-path buffers already are. Apply review request from 2026-11-08. --- .../Execution/src/Driver/Draw/Draw.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index ba56d6fa511d..3e74b943a989 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -42,10 +42,18 @@ namespace AgcDriver::DriverDetail { namespace { +struct RecycledRingWordsPool { + std::vector> words; + std::size_t cursor = 0; +}; + +struct RecycledRingWordsStorage {}; + std::shared_ptr RecycledRingWords() { constexpr std::size_t PoolSize = 1024, Probes = 16; - thread_local std::vector> pool; - thread_local std::size_t cursor = 0; + auto& state = HostThreadLocal(); + auto& pool = state.words; + auto& cursor = state.cursor; for (std::size_t probe = 0; probe < Probes && probe < pool.size(); ++probe) { auto& candidate = pool[cursor]; cursor = cursor + 1 == pool.size() ? 0 : cursor + 1; From 15c9133cbabbb929bce5e30f954266581480a634 Mon Sep 17 00:00:00 2001 From: Dean Galvin Date: Sun, 8 Nov 2026 22:06:14 +1300 Subject: [PATCH 144/269] fix(agc): size ElementFlags in the heap budget helpers Main turned the DescriptorBinding flag vectors into ElementFlags; the PR's OwnedBytes and vectorBytes helpers only had std::vector overloads. ElementFlags keeps up to 64 flags inline and spills larger sets into a std::vector, so count heap bytes only past 64. --- .../libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp | 5 +++++ core/shader/recompiler/HeapTemplateBudget.hpp | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index ab10c939f703..5892f5e2b9d0 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -279,6 +279,11 @@ std::uint64_t vectorBytes(const std::vector& values) { return static_cast(values.capacity() + 7u) / 8u; } +// ElementFlags keeps up to 64 flags inline; larger sets spill every flag into a std::vector. +std::uint64_t vectorBytes(const ShaderRecompiler::ElementFlags& flags) { + return flags.size() > 64u ? (static_cast(flags.size()) + 7u) / 8u : 0u; +} + template std::uint64_t sharedBytes(const ShaderRecompiler::SharedValues& values) { return static_cast(values.size()) * sizeof(TValue); diff --git a/core/shader/recompiler/HeapTemplateBudget.hpp b/core/shader/recompiler/HeapTemplateBudget.hpp index ee94bc9741d0..8ba16fcfbd8b 100644 --- a/core/shader/recompiler/HeapTemplateBudget.hpp +++ b/core/shader/recompiler/HeapTemplateBudget.hpp @@ -20,6 +20,11 @@ template return (static_cast(values.capacity()) + 7u) / 8u; } +// ElementFlags keeps up to 64 flags inline; larger sets spill every flag into a std::vector. +[[nodiscard]] inline std::uint64_t OwnedBytes(const ElementFlags& flags) { + return flags.size() > 64u ? (static_cast(flags.size()) + 7u) / 8u : 0u; +} + [[nodiscard]] inline std::uint64_t OwnedBytes(const DescriptorBinding& binding) { return OwnedBytes(binding.guestDescriptor) + OwnedBytes(binding.samplerDepthCompare) + OwnedBytes(binding.imageWritten) + OwnedBytes(binding.imageDepthCompare) + OwnedBytes(binding.imageAtomic) + OwnedBytes(binding.imageAtomic64) + OwnedBytes(binding.imageShapes) + OwnedBytes(binding.bufferAtomic) + OwnedBytes(binding.bufferWritten) + OwnedBytes(binding.samplerUnnormalized) + OwnedBytes(binding.samplerIntegerBorder) + From 7cf815cdd4c896c9dca17e3a4b3c4292fd51dc95 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 8 Nov 2026 14:57:46 +0530 Subject: [PATCH 145/269] perf(agc): read pushed guest buffers as storage and uniform buffers Heap stages read the guest buffer addresses in their push data through raw pointers. vkd3d-proton's heap mode passes root descriptors the same way but declares each one as a real buffer mapped to its pushed address: root SRVs and UAVs as storage buffers, root CBVs as uniform buffers (dxil.c heap lowering), with raw pointers only as its alignment fallback. Heap stages now do the same: - Each pushed guest buffer is a storage buffer on a new descriptor set, mapped PUSH_ADDRESS to its record in push data, or INDIRECT_ADDRESS into the per-draw overflow block. The size check a PS5 buffer descriptor makes stays in the shader, since an address mapping has no range. An empty or null buffer points at the stage's shader data with size 0. - A buffer a stage only reads with scalar loads at constant offsets, within 64 KiB, is a uniform buffer instead (a block of dwords, which needs VK_KHR_uniform_buffer_standard_layout). Guest buffer views and the copies standing in for them start on the uniform offset alignment while this is on. Both are now the default on every vendor, as in vkd3d's heap mode; APS5_PUSHED_BUFFERS=0 brings back the ring descriptors and APS5_UNIFORM_CONSTANT_BUFFERS=0 keeps constant buffers storage buffers. On a fake RX 6800 (RADV) replay of 29 vertex, 101 pixel and 190 compute MCD2 shaders, the raw-pointer path cost +15.6/+12.1/+11.1% shader instructions against the ring; the mapped buffers cost -0.3/+4.3/+1.0%, with fewer waits in every stage and 64% fewer vector memory loads in compute. RADV compiles the uniform and storage forms identically. Request serialization goes to 58 and the shader disk cache format to 65. --- .../Execution/src/VulkanDevice.cpp | 18 ++++- .../Graphics/include/BindlessHeap.hpp | 4 +- .../Graphics/include/GuestBufferMemory.hpp | 5 ++ .../Graphics/include/ShaderResources.hpp | 2 +- .../Graphics/src/BindlessHeap.cpp | 57 ++++++++++++++- .../Graphics/src/GuestBufferMemory.cpp | 17 +++-- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 4 +- .../Graphics/src/ShaderResources.cpp | 10 ++- .../Graphics/src/ShaderValidation.cpp | 6 ++ .../libSceAgcDriver/tests/ShaderMemory.cpp | 14 ++-- core/shader/recompiler/CacheKey.hpp | 1 + .../ControlFlow/src/RequestSerializer.cpp | 6 +- core/shader/recompiler/Recompiler.cpp | 3 +- core/shader/recompiler/Recompiler.hpp | 1 + core/shader/recompiler/RuntimeAbi.hpp | 6 ++ core/shader/recompiler/ShaderDiskCache.hpp | 2 +- .../include/SpirvBackend/SpirvEmitter.hpp | 1 + .../SpirvBackend/SpirvEmitterState.hpp | 7 ++ .../SpirvBackend/src/SpirvEmitter.cpp | 1 + .../src/SpirvMemory/SpirvBufferAccess.cpp | 10 ++- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 71 +++++++++++++++++++ .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 28 +++++++- .../tests/RequestSerializerTests.cpp | 58 ++++++++------- docs/dev/ENVIRONMENT.md | 3 +- 24 files changed, 280 insertions(+), 55 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 601fbb766a4d..f47de5ef0618 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -753,6 +753,7 @@ struct VulkanDevice::State { std::uint32_t heapDataUniformDwords = 0; bool heapBufferDescriptors = false; bool pushedBufferAddresses = false; + bool uniformConstantBuffers = false; std::unique_ptr recorder; // Device-local buffers of a repeated 16-byte fill pattern (FillBuffer), most recently used // last; each is filled once by a doubling chain in device memory. @@ -1719,6 +1720,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : const std::array meshExtensions{VK_EXT_MESH_SHADER_EXTENSION_NAME, VK_KHR_SPIRV_1_4_EXTENSION_NAME}; const bool meshAvailable = std::all_of(meshExtensions.begin(), meshExtensions.end(), hasExtension); VkPhysicalDeviceMeshShaderFeaturesEXT meshFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; + VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR standardLayout{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES_KHR}; if (meshAvailable) { VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &meshFeatures}; state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &features); @@ -2293,7 +2295,16 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : state->heapDataUniformDwords = std::min(HeapDataUniformDwordCap, state->properties.limits.maxUniformBufferRange / 4u); if (Graphics::BindlessHeap::RingInResourceHeap(state->descriptorHeapProperties, state->properties.limits.minUniformBufferOffsetAlignment)) state->heapBufferDescriptors = state->descriptorHeapProperties.bufferDescriptorSize == Graphics::BindlessHeap::BufferSlotBytes; - state->pushedBufferAddresses = Graphics::ChoosePushedBufferAddresses(state->properties.vendorID); + state->pushedBufferAddresses = Graphics::ChoosePushedBufferAddresses(); + // A pushed constant buffer is a uniform block of dwords (array stride 4), which needs the + // standard (std430) uniform buffer layout. + if (hasExtension(VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME)) { + VkPhysicalDeviceFeatures2 layoutFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &standardLayout}; + state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &layoutFeatures); + standardLayout.pNext = nullptr; + } + state->uniformConstantBuffers = Graphics::ChooseUniformConstantBuffers(state->pushedBufferAddresses && standardLayout.uniformBufferStandardLayout == VK_TRUE, state->properties.limits); + if (state->uniformConstantBuffers) deviceExtensions.push_back(VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME); deviceExtensions.push_back(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME); for (const char* required : {VK_KHR_MAINTENANCE_5_EXTENSION_NAME, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME}) { if (std::find_if(deviceExtensions.begin(), deviceExtensions.end(), [&](const char* name) { return std::strcmp(name, required) == 0; }) == deviceExtensions.end()) deviceExtensions.push_back(required); @@ -2332,6 +2343,10 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : meshFeatures.pNext = const_cast(deviceInfo.pNext); deviceInfo.pNext = &meshFeatures; } + if (state->uniformConstantBuffers) { + standardLayout = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES_KHR, const_cast(deviceInfo.pNext), VK_TRUE}; + deviceInfo.pNext = &standardLayout; + } if (state->descriptorHeap) { descriptorHeapFeatures.pNext = const_cast(deviceInfo.pNext); deviceInfo.pNext = &descriptorHeapFeatures; @@ -4723,6 +4738,7 @@ ShaderRecompiler::SpirvTarget VulkanDevice::Target() const { target.heapDataUniformDwords = target.descriptorMemory ? state->heapDataUniformDwords : 0u; target.heapBufferDescriptors = target.descriptorMemory && state->heapBufferDescriptors; target.pushedBufferAddresses = target.descriptorMemory && state->pushedBufferAddresses; + target.uniformConstantBuffers = target.pushedBufferAddresses && state->uniformConstantBuffers; target.float16WidenNans = state->float16WidenNans; target.float16NarrowNans = state->float16NarrowNans; return target; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 96cd1bf9c12a..32d6182a1944 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -305,8 +305,10 @@ class HeapSlotOwner { bool GpuHeapEnabled(); void SetDescriptorHeapDevice(bool available); bool DescriptorHeapEnabled(); -bool ChoosePushedBufferAddresses(std::uint32_t vendorId); +bool ChoosePushedBufferAddresses(); bool PushedBufferAddressesEnabled(); +bool ChooseUniformConstantBuffers(bool pushed, const VkPhysicalDeviceLimits& limits); +bool UniformConstantBuffersEnabled(); bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds = false, bool meshWindow = false, bool scratchPool = false, std::pair* refused = nullptr); void NoteHeapComputeStage(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index 31b0ab131006..90b935f22d57 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -315,6 +315,10 @@ struct AddressCopy { }; std::string AddressCopyOverflow(std::vector copies, std::uint64_t limit); +// The start alignment of a guest buffer view and of every copy that stands in for one: storage buffer +// offset alignment, and the uniform one too while pushed buffers may be read as uniform buffers. +VkDeviceSize GuestBufferViewAlignment(const VkPhysicalDeviceLimits& limits); + class AddressCopyCounters { public: struct Totals { @@ -578,6 +582,7 @@ class GuestBufferMemory { bool overlayCandidate(const Region& inside, bool readOnly) const; void resolveOverlays(); bool bindableInPlace(std::uint64_t offset, bool addressable) const; + VkDeviceSize viewAlignment() const; // Records the import-to-buffer copies of the given gpuCopy regions into the open batch, with // the barriers that order them after earlier recorded writes and before the shaders reading them. void recordGpuCopies(std::span copies, bool addressable); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index cab5e0254a71..6877eb529bab 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -378,7 +378,7 @@ class ShaderResources { } void PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const; void writePushedData(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const; - void writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides) const; + void writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const; // Whether RefreshData would record anything for `shader` (the per-word compare; verification). bool DataWordsDiffer(const CompiledShader& shader) const; std::size_t BindingCount() const { return bindings.size(); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 56d10e7a780b..27379308321a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -151,14 +151,16 @@ bool DescriptorHeapEnabled() { namespace { -constexpr std::uint32_t NvidiaVendorId = 0x10deu; std::atomic pushedBufferAddresses{false}; } -bool ChoosePushedBufferAddresses(std::uint32_t vendorId) { +// vkd3d-proton's heap mode passes root descriptors as addresses in push data on every vendor and maps +// them as real buffers (dxil.c heap lowering). Heap stages do the same with their guest buffers; +// APS5_PUSHED_BUFFERS=0 reads them through heap buffer descriptors written per draw instead. +bool ChoosePushedBufferAddresses() { const char* forced = std::getenv("APS5_PUSHED_BUFFERS"); - const bool chosen = forced != nullptr && *forced != '\0' ? std::strcmp(forced, "0") != 0 : vendorId == NvidiaVendorId; + const bool chosen = forced == nullptr || *forced == '\0' || std::strcmp(forced, "0") != 0; pushedBufferAddresses.store(chosen, std::memory_order_relaxed); return chosen; } @@ -177,6 +179,28 @@ bool PushedBufferAddressesEnabled() { namespace { +std::atomic uniformConstantBuffers{false}; + +} + +// vkd3d-proton's heap mode maps every root constant buffer as a uniform buffer, on every vendor. +// Pushed guest buffers that a stage only reads with scalar loads at constant offsets follow it; +// APS5_UNIFORM_CONSTANT_BUFFERS=0 keeps them storage buffers. +bool ChooseUniformConstantBuffers(bool pushed, const VkPhysicalDeviceLimits& limits) { + const char* forced = std::getenv("APS5_UNIFORM_CONSTANT_BUFFERS"); + const bool wanted = forced == nullptr || *forced == '\0' || std::strcmp(forced, "0") != 0; + const bool chosen = wanted && pushed && limits.maxUniformBufferRange >= ShaderRecompiler::RuntimeAbi::UniformConstantBufferBytes && + limits.minUniformBufferOffsetAlignment <= ShaderRecompiler::RuntimeAbi::UniformViewAdjustmentLimit + 1u; + uniformConstantBuffers.store(chosen, std::memory_order_relaxed); + return chosen; +} + +bool UniformConstantBuffersEnabled() { + return PushedBufferAddressesEnabled() && uniformConstantBuffers.load(std::memory_order_relaxed); +} + +namespace { + struct HeapSizes { std::uint32_t imageSlots = 0; VkDeviceSize imageStride = 0; @@ -1097,6 +1121,7 @@ struct HeapBindingUse { std::vector ringBuffers; std::vector srtAddresses; std::vector embeddedSamplers; + std::vector pushedBuffers; std::pair refused{~0u, ~0u}; }; @@ -1160,6 +1185,10 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& use.embeddedSamplers.push_back(binding); continue; } + if (set == Abi::PushedBufferSet) { + if (std::ranges::find(use.pushedBuffers, binding) == use.pushedBuffers.end()) use.pushedBuffers.push_back(binding); + continue; + } const bool stageBinding = binding / bindingCount < Abi::StageCount; if (roots.gdsAddress && stageBinding && set == Abi::DescriptorSet && binding % bindingCount == static_cast(Abi::Binding::Buffers)) { if (std::ranges::find(use.ringBuffers, binding) == use.ringBuffers.end()) use.ringBuffers.push_back(binding); @@ -1224,6 +1253,26 @@ VkDescriptorSetAndBindingMappingEXT ringBufferMapping(std::uint32_t binding, VkD return mapping; } +VkDescriptorSetAndBindingMappingEXT pushedBufferMapping(std::uint32_t binding, const ShaderRecompiler::StagePushPlacement* placement) { + Require(placement != nullptr && binding < placement->pushedBuffers, "a heap mapping reads a pushed buffer its pipeline's push layout does not count"); + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.descriptorSet = Abi::PushedBufferSet; + mapping.firstBinding = binding; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; + const auto root = binding < Abi::PushedBufferLimit ? placement->bufferRoots[binding] : Abi::NoPushPosition; + if (root != Abi::NoPushPosition) { + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; + mapping.sourceData.pushAddressOffset = root * static_cast(sizeof(std::uint32_t)); + return mapping; + } + Require(placement->bufferOverflow != Abi::NoPushPosition, "a pushed buffer outside the push data has no overflow block"); + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_INDIRECT_ADDRESS_EXT; + mapping.sourceData.indirectAddress.pushOffset = placement->bufferOverflow * static_cast(sizeof(std::uint32_t)); + mapping.sourceData.indirectAddress.addressOffset = binding * Abi::OverflowRecordWords * static_cast(sizeof(std::uint32_t)); + return mapping; +} + VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, const ShaderRecompiler::StagePushPlacement* placement) { VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; mapping.descriptorSet = Abi::GpuDataSet; @@ -1360,6 +1409,8 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, mappings.push_back(*mapping); } for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, placement)); + std::ranges::sort(use.pushedBuffers); + for (const auto binding : use.pushedBuffers) mappings.push_back(pushedBufferMapping(binding, placement)); std::ranges::sort(use.ringBuffers); for (const auto binding : use.ringBuffers) mappings.push_back(ringBufferMapping(binding, ringHeapOffset, placement)); std::ranges::sort(use.srtAddresses); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index c24c378aa3c9..07f0003ccb1a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -5400,7 +5400,7 @@ bool GuestBufferMemory::bindSparseMirror(Region& region, const GuestAllocations: refreshHeapMirrors(whole, blocks); } compareBlocks(blocks); - if (mirror == nullptr || !mirror->heap || region.begin < mirror->base || (region.begin - mirrorStart(*mirror)) % context.limits.minStorageBufferOffsetAlignment != 0) return false; + if (mirror == nullptr || !mirror->heap || region.begin < mirror->base || (region.begin - mirrorStart(*mirror)) % viewAlignment() != 0) return false; region.mirror = std::move(mirror); if (!servesView(region, std::max(region.lastView, region.begin))) { region.mirror = nullptr; @@ -5942,7 +5942,17 @@ bool GuestBufferMemory::gpuCopyEligible(const Region& region) const { bool GuestBufferMemory::bindableInPlace(std::uint64_t offset, bool addressable) const { if (adjustedRegions && !addressable) return offset % 4 == 0; - return offset % context.limits.minStorageBufferOffsetAlignment == 0; + return offset % viewAlignment() == 0; +} + +VkDeviceSize GuestBufferViewAlignment(const VkPhysicalDeviceLimits& limits) { + Require(limits.minStorageBufferOffsetAlignment != 0, "no storage buffer offset alignment"); + const auto storage = std::max(limits.minStorageBufferOffsetAlignment, 4); + return UniformConstantBuffersEnabled() ? std::max(storage, limits.minUniformBufferOffsetAlignment) : storage; +} + +VkDeviceSize GuestBufferMemory::viewAlignment() const { + return GuestBufferViewAlignment(context.limits); } bool GuestBufferMemory::stagingEligible(const Region& region, bool addressable) const { @@ -6822,9 +6832,8 @@ std::optional GuestBufferMemory::TryDescriptor(std::uint if (!(address >= region.begin && address + bytes <= region.end && (region.buffer != nullptr || region.direct != nullptr || region.mirror != nullptr))) return fail(describe("exceeds")); const auto base = region.direct != nullptr ? region.direct->base - region.direct->lead : region.mirror != nullptr ? mirrorStart(*region.mirror) : region.begin; const auto offset = address - base; - Require(context.limits.minStorageBufferOffsetAlignment != 0, "no storage buffer offset alignment"); if (base % 4 != 0) return fail("a guest buffer view in a GPU owner that does not start at a DWORD boundary is not implemented"); - adjustment = static_cast(offset % std::max(context.limits.minStorageBufferOffsetAlignment, 4)); + adjustment = static_cast(offset % viewAlignment()); if (bytes / 4 + adjustment / 4 + 2 > std::numeric_limits::max() / 4) return fail("guest buffer view range overflow"); auto range = ViewBytes(bytes, adjustment); const auto end = region.direct != nullptr ? region.direct->base + region.direct->bytes : servedEnd(region); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 04f7e6923493..e66745ca3f46 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -3326,7 +3326,7 @@ void Recorder::eraseDrawSnapshot(std::map::iterat } Recorder::UploadSlice Recorder::DrawUpload(std::size_t bytes) { - const VkDeviceSize alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 16); + const VkDeviceSize alignment = std::max(GuestBufferViewAlignment(context.limits), 16); auto offset = (drawUploadUsed + alignment - 1) & ~(alignment - 1); if (drawUpload == nullptr || offset + bytes > drawUpload->Bytes().size()) { drawUpload = std::make_shared(context, std::max(DrawUploadChunk, bytes), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); @@ -3385,7 +3385,7 @@ std::shared_ptr Recorder::ReusableDrawSnapshot(std::uint64_t address, st } std::shared_ptr Recorder::containingDrawSnapshot(std::uint64_t address, std::size_t bytes, VkDeviceSize* offset) { - const VkDeviceSize alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); + const VkDeviceSize alignment = GuestBufferViewAlignment(context.limits); const auto registry = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); auto entry = drawSnapshots.upper_bound({address, SnapshotUse::Storage, std::numeric_limits::max()}); for (std::size_t probe = 0; probe < ContainingSnapshotProbes && entry != drawSnapshots.begin(); ++probe) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 80bff419f94c..68b110eeeea9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6945,13 +6945,13 @@ void ShaderResources::PatchDataAddresses(std::span(std::min(heapSrtDwords[stage], srt.size / sizeof(std::uint32_t))) : heapSrtDwords[stage]); putAddress(Abi::RootItem::TableMap, heapTableMapSet[stage] ? heapTableMaps[stage] : offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); writePushedData(bytes, shader, placement.pushed); - if (shader.program->pushedBufferCount != 0u) writePushedBuffers(bytes, stage, placement, addressed ? &rewritten->addressOverrides : nullptr); + if (shader.program->pushedBufferCount != 0u) writePushedBuffers(bytes, stage, placement, addressed ? &rewritten->addressOverrides : nullptr, offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); rooted = true; } if (rooted) NoteDataAddressPush(); } -void ShaderResources::writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides) const { +void ShaderResources::writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const { namespace Abi = ShaderRecompiler::RuntimeAbi; struct RangeStorage {}; auto& ranges = HostThreadLocal, RangeStorage>(); @@ -6959,8 +6959,12 @@ void ShaderResources::writePushedBuffers(std::span(stage), overrides, &ranges); Require(ranges.size() == placement.pushedBuffers, "a stage's buffer addresses do not match its push layout's buffer count"); heapPushedStages.fetch_add(1, std::memory_order_relaxed); + Require(empty != 0u, "a stage with pushed buffers has no shader data to stand in for an empty buffer"); const auto record = [&](std::size_t index) { - return std::array{static_cast(ranges[index].address), static_cast(ranges[index].address >> 32u), static_cast(std::min(ranges[index].size, 0xffffffffu)), 0u}; + const auto size = static_cast(std::min(ranges[index].size, 0xffffffffu)); + const auto address = size != 0u && ranges[index].address != 0u ? ranges[index].address : empty; + Require(!UniformConstantBuffersEnabled() || address % context.limits.minUniformBufferOffsetAlignment == 0, "a pushed buffer address is off the uniform buffer offset alignment"); + return std::array{static_cast(address), static_cast(address >> 32u), address == empty ? 0u : size, 0u}; }; const auto put = [&](std::uint32_t position, std::span words) { Require(position != Abi::NoPushPosition && (position + words.size()) * sizeof(std::uint32_t) <= bytes.size(), "a stage's pushed buffer words lie outside the push data"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index 724d80b1e353..89047dd069b3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -642,6 +642,8 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi } else { Require(binding->count != 0u && binding->count <= capacity && count != module.constants.end() && count->second == binding->count, "typed heap array length disagrees with compact binding"); } + } else if (variable.storage == spv::StorageClassUniform && decoration.set && *decoration.set == ShaderRecompiler::RuntimeAbi::PushedBufferSet) { + Require(shader.gpuResolvedImages && shader.dataAddressPush, "a pushed constant buffer outside a heap stage"); } else if (variable.storage == spv::StorageClassUniform) { namespace Abi = ShaderRecompiler::RuntimeAbi; constexpr auto bindingCount = static_cast(Abi::Binding::Count); @@ -655,6 +657,10 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi Require(mesh && *decoration.binding == 0u, "mesh window buffer binding is wrong"); continue; } + if (*decoration.set == ShaderRecompiler::RuntimeAbi::PushedBufferSet) { + Require(shader.gpuResolvedImages && shader.dataAddressPush, "a pushed buffer outside a heap stage"); + continue; + } const bool gpuData = shader.gpuResolvedImages && key.first == ShaderRecompiler::RuntimeAbi::GpuDataSet && std::any_of(shader.bindings.begin(), shader.bindings.end(), [&](const auto& item) { return item.binding == key.second && (item.role == ShaderRecompiler::DescriptorRole::ShaderData || item.role == ShaderRecompiler::DescriptorRole::FlattenedSrt); }); if (!gpuData && *decoration.set == ShaderRecompiler::PixelFunctionLdsDescriptorSet) { diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index ce3aa72b1f3b..8a5b11e09a15 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -8273,7 +8273,7 @@ void verifyPixelRequestSerialization() { minimal.context.pixel->layerExported = true; minimal.context.pixel->ditheredAlphaToCoverage = true; const auto encoded = serializer.Serialize(minimal); - require(requestPrefix(encoded, 8u) == "NVNQQTkAAAA=", "new requests did not use serialization version 57"); + require(requestPrefix(encoded, 8u) == "NVNQQToAAAA=", "new requests did not use serialization version 58"); auto withBarycentric = minimal; withBarycentric.target.fragmentBarycentricBuiltins = true; require(serializer.Deserialize(serializer.Serialize(withBarycentric)).request.target.fragmentBarycentricBuiltins && !serializer.Deserialize(encoded).request.target.fragmentBarycentricBuiltins, "barycentric built-ins were lost in serialization"); @@ -8394,7 +8394,7 @@ void verifyPixelRequestSerialization() { for (std::size_t bytes = 0; bytes < 45u; ++bytes) { expectFailure([&] { static_cast(serializer.Deserialize(requestPrefix(encoded, mappingOffset + bytes))); }, "truncated data", "a truncated pixel mapping, packing, dual-source, alpha-to-coverage, stencil reference export flag, primitive class, layer export, dither or front-face flag, quad pixel mask or quad sample mask was accepted"); } - for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQToAAAA="}) { + for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQTsAAAA="}) { expectFailure([&] { static_cast(serializer.Deserialize(unsupported)); }, "serialization version", "an unsupported request version was accepted"); } static constexpr std::string_view version18Request{ @@ -8448,9 +8448,9 @@ std::vector decodeBase64(std::string_view text) { bytes.push_back(static_cast((chunk >> bits) & 0xffu)); } } - if (bytes.size() > 14u && bytes[4] == 57u) { - require(std::all_of(bytes.end() - 14, bytes.end(), [](std::uint8_t value) { return value == 0u; }), "a version 57 request in these checks set a GPU heap target field"); - bytes.resize(bytes.size() - 14u); + if (bytes.size() > 15u && bytes[4] == 58u) { + require(std::all_of(bytes.end() - 15, bytes.end(), [](std::uint8_t value) { return value == 0u; }), "a version 58 request in these checks set a GPU heap target field"); + bytes.resize(bytes.size() - 15u); bytes[4] = 55u; } return bytes; @@ -8458,8 +8458,8 @@ std::vector decodeBase64(std::string_view text) { std::string encodeBase64(std::vector bytes) { if (bytes.size() > 4u && bytes[4] == 55u) { - bytes[4] = 57u; - bytes.insert(bytes.end(), 14u, 0u); + bytes[4] = 58u; + bytes.insert(bytes.end(), 15u, 0u); } constexpr std::string_view alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string text; diff --git a/core/shader/recompiler/CacheKey.hpp b/core/shader/recompiler/CacheKey.hpp index b698f99a3f31..3943c286e0e4 100644 --- a/core/shader/recompiler/CacheKey.hpp +++ b/core/shader/recompiler/CacheKey.hpp @@ -388,6 +388,7 @@ class RecompileCacheKey { append(key, value.heapDataUniformDwords); append(key, value.heapBufferDescriptors); append(key, value.pushedBufferAddresses); + append(key, value.uniformConstantBuffers); append(key, value.ldsLockFences); append(key, value.meshWindowBuffer); append(key, value.hostInterpolationFirst); diff --git a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp index 43d6a36d4e81..916bf2b7704b 100644 --- a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp +++ b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp @@ -916,7 +916,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const std::string buffer; Writer writer(buffer); writer.WriteU32(0x41505335u); - writer.WriteU32(57u); + writer.WriteU32(58u); writeShaderBinary(writer, request.shader); writeGuestContext(writer, request.context); writeSpirvTarget(writer, request.target); @@ -974,6 +974,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const writer.WriteBool(request.target.robustBufferAccess2); writer.WriteBool(request.target.heapBufferDescriptors); writer.WriteBool(request.target.pushedBufferAddresses); + writer.WriteBool(request.target.uniformConstantBuffers); return base64Encode(buffer); } @@ -982,7 +983,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const Reader reader(decoded); if (reader.ReadU32() != 0x41505335u) throw std::runtime_error("invalid recompile request signature"); const auto version = reader.ReadU32(); - if (version < 1u || version > 57u || version == 50u) throw std::runtime_error("unsupported recompile request serialization version"); + if (version < 1u || version > 58u || version == 50u) throw std::runtime_error("unsupported recompile request serialization version"); DeserializedRequest result{}; result.request.shader = readShaderBinary(reader, result.shaderCode, result.shaderHeader); result.request.context = readGuestContext(reader, result, version); @@ -1062,6 +1063,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const result.request.target.heapBufferDescriptors = reader.ReadBool(); } if (version >= 57u) result.request.target.pushedBufferAddresses = reader.ReadBool(); + if (version >= 58u) result.request.target.uniformConstantBuffers = reader.ReadBool(); if (version >= 21u && reader.Remaining() != 0u) throw std::runtime_error("RequestSerializer: unexpected trailing data"); return result; } diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 005a3d4ce7f0..1f950fe82b12 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -792,6 +792,7 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) targetOptions.deviceScopeLdsMemoryBarriers = request.target.deviceScopeLdsMemoryBarriers; targetOptions.gpuResolvedImages = allocation.gpuResolvedImages; targetOptions.heapDataUniformDwords = request.target.heapDataUniformDwords; + targetOptions.uniformConstantBuffers = request.target.uniformConstantBuffers; targetOptions.heapBufferDescriptors = request.target.descriptorMemory && request.target.heapBufferDescriptors; targetOptions.ldsLockFences = request.target.ldsLockFences; targetOptions.meshWindowBuffer = request.target.meshWindowBuffer; @@ -1043,7 +1044,7 @@ SpecializedSpirv buildSpecializedModule(const CompiledShaderArtifact& artifact, const auto op = static_cast(materialized[cursor] & 0xffffu); if (op == spv::OpEntryPoint && count >= 2u) compute = materialized[cursor + 1u] == spv::ExecutionModelGLCompute; if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationBinding) bindingNumbers.emplace(materialized[cursor + 1u], materialized[cursor + 3u]); - if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationDescriptorSet && (materialized[cursor + 3u] == PixelFunctionLdsDescriptorSet || materialized[cursor + 3u] == MeshWindowDescriptorSet || materialized[cursor + 3u] == RuntimeAbi::EmbeddedSamplerSet || (compute && !target.gpuResolvedImages && materialized[cursor + 3u] == WorkgroupMemoryDescriptorSet))) ldsBuffers.insert(materialized[cursor + 1u]); + if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationDescriptorSet && (materialized[cursor + 3u] == PixelFunctionLdsDescriptorSet || materialized[cursor + 3u] == MeshWindowDescriptorSet || materialized[cursor + 3u] == RuntimeAbi::EmbeddedSamplerSet || materialized[cursor + 3u] == RuntimeAbi::PushedBufferSet || (compute && !target.gpuResolvedImages && materialized[cursor + 3u] == WorkgroupMemoryDescriptorSet))) ldsBuffers.insert(materialized[cursor + 1u]); if (op == spv::OpDecorate && count == 4u && materialized[cursor + 2u] == spv::DecorationSpecId) { const auto id = materialized[cursor + 3u]; if (!PipelineSpecialization::IsWorkgroupOffset(id)) module->specialization.push_back({id, supplied.at(id)}); diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index d4af67fe0bf6..9225e3059794 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -369,6 +369,7 @@ struct SpirvTarget { std::uint32_t heapDataUniformDwords = 0; bool heapBufferDescriptors = false; bool pushedBufferAddresses = false; + bool uniformConstantBuffers = false; bool ldsLockFences = false; bool fragmentBarycentricBuiltins = false; bool meshWindowBuffer = false; diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index 4cdc4cf0cba0..4e823239bdc6 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -90,6 +90,12 @@ inline constexpr std::uint32_t GpuSamplerHeapSlots = 2048u; inline constexpr std::uint32_t GpuDataSet = 2u; inline constexpr std::uint32_t GpuGdsSet = 4u; inline constexpr std::uint32_t EmbeddedSamplerSet = 6u; +inline constexpr std::uint32_t PushedBufferSet = 7u; +// A pushed buffer read as a uniform buffer: the largest view (maxUniformBufferRange's guaranteed +// minimum) and the most its start may sit below the guest address (minUniformBufferOffsetAlignment +// is at most 256 by the Vulkan limits; NVIDIA reports 64). +inline constexpr std::uint32_t UniformConstantBufferBytes = 65536u; +inline constexpr std::uint32_t UniformViewAdjustmentLimit = 255u; inline constexpr std::uint32_t NoEmbeddedSampler = ~0u; inline constexpr std::uint32_t GdsBytes = 0x10000u; inline constexpr std::uint32_t PushDataDwords = 64u; diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index cebadf9d7e69..e45e69d31688 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -13,7 +13,7 @@ namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 63; +inline constexpr std::uint32_t FormatVersion = 65; enum class LoadStatus { Loaded, diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp index f4c037ab3a62..ad61cd013aad 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp @@ -46,6 +46,7 @@ struct SpirvTargetOptions { bool deviceScopeLdsMemoryBarriers = false; bool gpuResolvedImages = false; std::uint32_t heapDataUniformDwords = 0; + bool uniformConstantBuffers = false; bool heapBufferDescriptors = false; bool ldsLockFences = false; bool meshWindowBuffer = false; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index 45863ad585b1..aa70184a2ab5 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -73,6 +73,8 @@ struct MemoryResourceAccess { std::uint32_t misalignment = 0; bool physical = false; bool clampedPhysical = false; + bool softwareBounds = false; + bool uniform = false; }; struct SpirvTableImageVariable { @@ -118,8 +120,13 @@ struct SpirvEmitterState { bool registrationModules = false; bool gpuResolvedImages = false; std::uint32_t heapDataUniformDwords = 0; + bool uniformConstantBuffers = false; bool heapBufferDescriptors = false; bool addressedBuffers = false; + std::vector pushedBufferVariables; + std::vector pushedBufferCoherentVariables; + std::vector pushedBufferU64Variables; + std::vector pushedBufferUniformVariables; std::optional guestBuffersWritten; bool fragmentDescriptorSet = false; bool float16DenormPreserve = false; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp index dbc92e3f1a08..1473ce37b1fb 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp @@ -282,6 +282,7 @@ std::vector SpirvEmitter::Emit(const IrProgram& program, const Sh state.registrationModules = target.registrationModules; state.gpuResolvedImages = target.gpuResolvedImages; state.heapDataUniformDwords = target.heapDataUniformDwords; + state.uniformConstantBuffers = target.uniformConstantBuffers; state.heapBufferDescriptors = target.heapBufferDescriptors && !program.Metadata().bindings.pushedBuffers; state.fragmentDescriptorSet = target.fragmentDescriptorSet; state.meshBarycentricPixel = target.meshBarycentricPixel; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index d9cdc08186df..6c0d198dab6b 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -463,13 +463,14 @@ std::uint32_t LdsStorageDwords(const SpirvEmitterState& state) { bool LoadsSelectable(const SpirvEmitterState& state, const MemoryResourceAccess& access) { if (access.kind == ResourceKind::Scratch) return true; if (access.physical) return access.clampedPhysical; + if (access.softwareBounds) return true; if (access.kind == ResourceKind::Lds) return false; return state.robustBufferAccess2; } std::uint32_t GuardedElementIndex(SpirvEmitterState& state, const MemoryResourceAccess& access, std::uint32_t condition, std::uint32_t index) { if (access.kind == ResourceKind::Lds) FailEmit("LDS loads keep their branch and have no guarded element"); - const auto fallback = access.kind == ResourceKind::Scratch || access.physical ? 0u : 0xfffffffeu; + const auto fallback = access.kind == ResourceKind::Scratch || access.physical || access.softwareBounds ? 0u : 0xfffffffeu; return Select(state, TypeU32(state), condition, index, ConstantU32(state, fallback)); } @@ -493,6 +494,13 @@ std::uint32_t EmitMemoryElementPointer(SpirvEmitterState& state, const MemoryRes } std::uint32_t EmitStorageBufferElementPointer(SpirvEmitterState& state, const MemoryResourceAccess& access, std::uint32_t index, std::uint32_t pointerType) { + if (access.uniform) { + if (pointerType != TypeStorageBufferElementPointer(state)) FailEmit("a pushed constant buffer is read wider than a dword"); + const auto u32 = TypeU32(state); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassUniform, u32), pointer, access.objectPointer, ConstantU32(state, 0), index); + return pointer; + } if (access.physical) { if (pointerType == TypeStorageBufferU64ElementPointer(state)) pointerType = TypePointer(state, spv::StorageClassPhysicalStorageBuffer, TypeScalarU64(state)); else pointerType = TypePhysicalU32Pointer(state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index 718e0dfac1ad..8db7b49b433a 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -512,6 +512,77 @@ void DefineDescriptors(SpirvEmitterState& state) { case DescriptorBindingKind::Buffers: { if (layout.bufferAddressDwords != 0u && !state.heapBufferDescriptors) { state.addressedBuffers = true; + if (!layout.pushedBuffers) break; + const auto count = layout.bufferAddressDwords / RuntimeAbi::BufferAddressWords; + const auto pushedBuffer = [&](std::uint32_t type, std::uint32_t element, const char* name) { + const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassStorageBuffer, type), spv::StorageClassStorageBuffer); + state.module.AddName(variable, (std::string(name) + "_" + std::to_string(element)).c_str()); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, RuntimeAbi::PushedBufferSet); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, element); + return variable; + }; + const bool aliased = state.requirements.coherentBufferAlias || state.requirements.bufferU64View; + // vkd3d-proton's heap mode maps root constant buffers as uniform buffers, which NVIDIA + // reads through its constant path. A guest buffer qualifies when every access is + // a non-coherent scalar load at a constant offset, so its highest word is known here; the + // view's start adjustment (below the uniform offset alignment, at most 63 bytes) and a + // misaligned base's second word are added to that bound. + std::vector uniformWords(count, 0u); + if (state.uniformConstantBuffers) { + std::vector eligible(count, true); + std::vector end(count, 0u); + const auto& memory = state.program.Resources().memoryInfo; + for (const auto& block : state.program.Blocks()) { + for (const IrValue* inst : block->Instructions()) { + const auto op = inst->Opcode(); + if (op != IrOpcode::ReadConstBuffer && BufferAccessOf(op) == BufferAccess::None) continue; + const auto index = inst->Flags().index; + if (index >= memory.size()) continue; + const auto& info = memory[index]; + if (info.gpuDescriptor || info.planningOnly || (info.kind != ResourceKind::Buffer && info.kind != ResourceKind::ScalarBuffer)) continue; + const auto element = ResourceForDescriptor(state, DescriptorBindingKind::Buffers, info.resource); + if (element >= count) continue; + const auto* offset = inst->ArgumentCount() > 1u ? inst->Argument(1u) : nullptr; + if (op != IrOpcode::ReadConstBuffer || info.coherent || offset == nullptr || !offset->HasImmediate()) { + eligible[element] = false; + continue; + } + const auto byte = static_cast(offset->ImmediateU32()) + info.offset; + end[element] = std::max(end[element], static_cast(std::min((byte & ~std::uint64_t{3u}) + 8u, 0xffffffffu))); + } + } + for (std::uint32_t element = 0; element < count; ++element) { + const auto bytes = static_cast(end[element]) + RuntimeAbi::UniformViewAdjustmentLimit; + if (eligible[element] && end[element] != 0u && bytes <= RuntimeAbi::UniformConstantBufferBytes) uniformWords[element] = static_cast((bytes + 3u) / 4u); + } + } + for (std::uint32_t element = 0; element < count; ++element) { + if (uniformWords[element] != 0u) { + // A block of dwords (std430 uniform layout, uniformBufferStandardLayout). + const auto array = state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4u}}}, TypeU32(state), ConstantU32(state, uniformWords[element])); + const auto block = state.module.DecoratedType(spv::OpTypeStruct, {{spv::OpDecorate, {spv::DecorationBlock}}, {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}}, array); + const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniform, block), spv::StorageClassUniform); + state.module.AddName(variable, ("pushed_constant_buffer_" + std::to_string(element)).c_str()); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, RuntimeAbi::PushedBufferSet); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, element); + state.pushedBufferUniformVariables.push_back(variable); + state.pushedBufferVariables.push_back(0u); + state.pushedBufferCoherentVariables.push_back(0u); + state.pushedBufferU64Variables.push_back(0u); + continue; + } + state.pushedBufferUniformVariables.push_back(0u); + state.pushedBufferVariables.push_back(pushedBuffer(StorageBufferBlockType(state), element, "pushed_buffer")); + state.pushedBufferCoherentVariables.push_back(state.requirements.coherentBufferAlias ? pushedBuffer(StorageBufferBlockType(state), element, "pushed_buffer_coherent") : 0u); + state.pushedBufferU64Variables.push_back(state.requirements.bufferU64View ? pushedBuffer(StorageBufferU64BlockType(state), element, "pushed_buffer_u64") : 0u); + for (const auto variable : {state.pushedBufferVariables.back(), state.pushedBufferCoherentVariables.back(), state.pushedBufferU64Variables.back()}) { + if (variable != 0u && aliased) state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationAliased); + } + if (state.requirements.coherentBuffers) { + state.module.AddAnnotation(spv::OpDecorate, state.pushedBufferCoherentVariables.back() != 0u ? state.pushedBufferCoherentVariables.back() : state.pushedBufferVariables.back(), spv::DecorationCoherent); + if (state.pushedBufferU64Variables.back() != 0u) state.module.AddAnnotation(spv::OpDecorate, state.pushedBufferU64Variables.back(), spv::DecorationCoherent); + } + } break; } state.storageBufferVariable = Define(ArrayType(StorageBufferBlockType(state)), "buffers"); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index 4090d5b7db9f..4745d41af742 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -235,6 +235,30 @@ MemoryResourceAccess directAccess(SpirvValueEmitContext& context, const IrValue& const auto dword = state.program.Metadata().bindings.BufferAddressDword() + element * RuntimeAbi::BufferAddressWords; const bool pushed = state.program.Metadata().bindings.pushedBuffers; const auto word = [&](std::uint32_t index) { return pushed ? EmitBufferRootDword(state, element, index) : EmitShaderDataDwordLoad(state, dword + index); }; + if (pushed) { + if (element >= state.pushedBufferVariables.size()) context.Fail(instruction, "a pushed buffer has no storage buffer variable"); + if (state.pushedBufferUniformVariables[element] != 0u) { + if (instruction.Opcode() != IrOpcode::ReadConstBuffer || wide) context.Fail(instruction, "a pushed constant buffer is read by an access other than a scalar load"); + MemoryResourceAccess access; + access.kind = memory.kind; + access.objectPointer = state.pushedBufferUniformVariables[element]; + access.softwareBounds = true; + access.uniform = true; + access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), word(2u), ConstantU32(state, 2u)); + access.byteOffset = state.memoryByteOffsets.at(element); + return access; + } + const auto variable = wide ? state.pushedBufferU64Variables[element] : plainLoad || state.pushedBufferCoherentVariables[element] == 0u ? state.pushedBufferVariables[element] : state.pushedBufferCoherentVariables[element]; + if (variable == 0u) context.Fail(instruction, "a pushed buffer lacks the view this access needs"); + MemoryResourceAccess access; + access.kind = memory.kind; + access.objectPointer = variable; + access.softwareBounds = true; + access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), word(2u), ConstantU32(state, wide ? 3u : 2u)); + access.byteOffset = state.memoryByteOffsets.at(element); + access.memoryAccess = memory.coherent ? spv::MemoryAccessVolatileMask : 0u; + return access; + } const auto u64 = TypeScalarU64(state); auto address = ComposeAddress64(state, [&] { return word(0u); }, [&] { return word(1u); }); MemoryResourceAccess access; @@ -305,7 +329,7 @@ std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruct const auto unaligned = nonzero(state, misalignment); const auto next = EmitAddU32(state, index, ConstantU32(state, 1u)); const auto last = Select(state, TypeU32(state), unaligned, next, index); - const bool exact = state.exactRobustLoads && !access.physical && LoadsSelectable(state, access); + const bool exact = state.exactRobustLoads && !access.physical && !access.softwareBounds && LoadsSelectable(state, access); if (!exact && boundedEnable != 0u) enable = boundedEnable; const auto bounds = exact ? 0u : EmitMemoryElementInBounds(state, access, last); const auto inBounds = exact ? 0u : (enable != 0u ? both(state, enable, bounds) : bounds); @@ -352,7 +376,7 @@ std::uint32_t readBuffer(SpirvValueEmitContext& context, const IrValue& instruct const auto low = Binary(state, spv::OpShiftRightLogical, TypeU32(state), load(lowIndex), shift); const auto high = EmitValueOrZero(state, unaligned, Binary(state, spv::OpShiftLeftLogical, TypeU32(state), load(highIndex), highShift)); const auto value = combine(low, high); - const bool robustZero = !access.physical && ((access.memoryAccess & spv::MemoryAccessVolatileMask) != 0u || (state.requirements.readOnlyStorage && access.memoryAccess == 0u)); + const bool robustZero = !access.physical && !access.softwareBounds && ((access.memoryAccess & spv::MemoryAccessVolatileMask) != 0u || (state.requirements.readOnlyStorage && access.memoryAccess == 0u)); return robustZero ? value : EmitValueOrZero(state, inBounds, value); } diff --git a/core/shader/recompiler/tests/RequestSerializerTests.cpp b/core/shader/recompiler/tests/RequestSerializerTests.cpp index 64e9d8565e85..771c3bd732e3 100644 --- a/core/shader/recompiler/tests/RequestSerializerTests.cpp +++ b/core/shader/recompiler/tests/RequestSerializerTests.cpp @@ -180,16 +180,16 @@ std::string EncodeBase64(const std::vector& bytes) { return text; } std::vector AtVersion55(std::vector bytes) { - Require(bytes.size() > 22u && bytes[4] == 57u && std::all_of(bytes.end() - 14, bytes.end(), [](std::uint8_t value) { return value == 0u; })); - bytes.resize(bytes.size() - 14u); + Require(bytes.size() > 23u && bytes[4] == 58u && std::all_of(bytes.end() - 15, bytes.end(), [](std::uint8_t value) { return value == 0u; })); + bytes.resize(bytes.size() - 15u); bytes[4] = 55u; return bytes; } std::string EncodeAtWriterVersion(std::vector bytes) { Require(bytes.size() > 8u && bytes[4] == 55u); - bytes[4] = 57u; - bytes.insert(bytes.end(), 14u, 0u); + bytes[4] = 58u; + bytes.insert(bytes.end(), 15u, 0u); return EncodeBase64(bytes); } @@ -212,8 +212,8 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { Require(replay.request.target.heapDataUniformDwords == profile.heapDataUniformDwords); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 57u && bytes.size() > 14u); - bytes.resize(bytes.size() - 14u); + Require(bytes[4] == 58u && bytes.size() > 15u); + bytes.resize(bytes.size() - 15u); for (const std::uint8_t version : {55u, 54u, 53u, 52u}) { if (version == 53u) bytes.resize(bytes.size() - 2u); if (version == 52u) bytes.pop_back(); @@ -222,7 +222,7 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { Require(!older.gpuResolvedImages && !older.descriptorMemory && older.heapDataUniformDwords == 0u); } bytes.push_back(0u); - bytes[4] = 57u; + bytes[4] = 58u; bool truncated = false; try { static_cast(serializer.Deserialize(EncodeBase64(bytes))); @@ -254,7 +254,7 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { Require(serializer.Deserialize(encoded).request.target.heapBufferDescriptors == descriptors); Require((encoded == serializer.Serialize(limits)) == !descriptors); auto bytes = DecodeBase64(encoded); - bytes.resize(bytes.size() - 14u); + bytes.resize(bytes.size() - 15u); bytes[4] = 55u; Require(!serializer.Deserialize(EncodeBase64(bytes)).request.target.heapBufferDescriptors); } @@ -262,25 +262,33 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { void VerifyPushedBufferAddresses(const ShaderRecompiler::RequestSerializer& serializer) { for (const bool pushed : {false, true}) { - ShaderRecompiler::RecompileRequest request{}; - request.target.gpuResolvedImages = true; - request.target.descriptorMemory = true; - request.target.heapBufferDescriptors = true; - request.target.pushedBufferAddresses = pushed; - const auto encoded = serializer.Serialize(request); - Require(serializer.Deserialize(encoded).request.target.pushedBufferAddresses == pushed && serializer.Serialize(serializer.Deserialize(encoded).request) == encoded); - auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 57u && bytes.back() == (pushed ? 1u : 0u)); - bytes.pop_back(); - bytes[4] = 56u; - const auto older = serializer.Deserialize(EncodeBase64(bytes)).request.target; - Require(!older.pushedBufferAddresses && older.gpuResolvedImages && older.descriptorMemory && older.heapBufferDescriptors); + for (const bool uniform : {false, true}) { + ShaderRecompiler::RecompileRequest request{}; + request.target.gpuResolvedImages = true; + request.target.descriptorMemory = true; + request.target.heapBufferDescriptors = true; + request.target.pushedBufferAddresses = pushed; + request.target.uniformConstantBuffers = uniform; + const auto encoded = serializer.Serialize(request); + const auto replay = serializer.Deserialize(encoded).request.target; + Require(replay.pushedBufferAddresses == pushed && replay.uniformConstantBuffers == uniform && serializer.Serialize(serializer.Deserialize(encoded).request) == encoded); + auto bytes = DecodeBase64(encoded); + Require(bytes[4] == 58u && bytes.back() == (uniform ? 1u : 0u) && bytes[bytes.size() - 2u] == (pushed ? 1u : 0u)); + bytes.pop_back(); + bytes[4] = 57u; + const auto version57 = serializer.Deserialize(EncodeBase64(bytes)).request.target; + Require(version57.pushedBufferAddresses == pushed && !version57.uniformConstantBuffers); + bytes.pop_back(); + bytes[4] = 56u; + const auto older = serializer.Deserialize(EncodeBase64(bytes)).request.target; + Require(!older.pushedBufferAddresses && !older.uniformConstantBuffers && older.gpuResolvedImages && older.descriptorMemory && older.heapBufferDescriptors); + } } } void VerifyKeyedTargetFields(const ShaderRecompiler::RequestSerializer& serializer) { using Field = bool ShaderRecompiler::SpirvTarget::*; - constexpr std::array fields{&ShaderRecompiler::SpirvTarget::ldsLockFences, &ShaderRecompiler::SpirvTarget::meshWindowBuffer, &ShaderRecompiler::SpirvTarget::waveLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::deviceScopeLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::exactRobustLoads, &ShaderRecompiler::SpirvTarget::robustBufferAccess2, &ShaderRecompiler::SpirvTarget::pushedBufferAddresses}; + constexpr std::array fields{&ShaderRecompiler::SpirvTarget::ldsLockFences, &ShaderRecompiler::SpirvTarget::meshWindowBuffer, &ShaderRecompiler::SpirvTarget::waveLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::deviceScopeLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::exactRobustLoads, &ShaderRecompiler::SpirvTarget::robustBufferAccess2, &ShaderRecompiler::SpirvTarget::pushedBufferAddresses, &ShaderRecompiler::SpirvTarget::uniformConstantBuffers}; const ShaderRecompiler::RecompileRequest defaults{}; const auto defaultEncoded = serializer.Serialize(defaults); for (std::size_t chosen = 0; chosen <= fields.size(); ++chosen) { @@ -292,8 +300,8 @@ void VerifyKeyedTargetFields(const ShaderRecompiler::RequestSerializer& serializ for (std::size_t index = 0; index < fields.size(); ++index) Require(replay.request.target.*fields[index] == (chosen == fields.size() || index == chosen)); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 57u && bytes.size() > 14u); - bytes.resize(bytes.size() - 14u); + Require(bytes[4] == 58u && bytes.size() > 15u); + bytes.resize(bytes.size() - 15u); for (const std::uint8_t version : {55u, 54u, 53u, 52u}) { if (version == 53u) bytes.resize(bytes.size() - 2u); if (version == 52u) bytes.pop_back(); @@ -827,7 +835,7 @@ int main() { const auto replay40 = serializer.Deserialize(EncodeBase64(version40)); Require(!replay40.request.target.float32DenormPreserve && replay40.request.target.float32FlushToZero == !preserve); auto future = bytes; - future[4] = 58u; + future[4] = 59u; bool futureRejected = false; try { static_cast(serializer.Deserialize(EncodeBase64(future))); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 3efda498630c..e5cdaae48a9b 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -441,7 +441,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_PROFILE_GPU` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records the GPU time of recorded work by key from batch timestamps | | `APS5_PROFILE_GPU_DRAWS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp`, `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | with APS5_PROFILE_GPU, records the GPU time of each recorded draw by its fragment program's variant id and prints a [drawvariant] line with the code address behind each variant id once (draws that do not use a recipe only; the [gputime] line labels each `draw 0x`, the id [drawvariant] prints, and the ranges share the batch's query cap) | | `APS5_PUSHED_BUFFER_RECORDS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 4 | test cap on the guest buffer records a heap stage keeps in its push data; the rest go to its per-draw overflow block | -| `APS5_PUSHED_BUFFERS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | NVIDIA 1, other vendors 0 | with `APS5_GPU_HEAP`, `1` passes every heap stage's guest buffer addresses and sizes in its push data (four records, the rest in a per-draw overflow block) and `0` reads them through heap buffer descriptors written per draw | +| `APS5_PUSHED_BUFFERS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 1 | with `APS5_GPU_HEAP`, `1` passes every heap stage's guest buffer addresses and sizes in its push data (four records, the rest in a per-draw overflow block), read as storage buffers mapped to those addresses, and `0` reads them through heap buffer descriptors written per draw | | `APS5_REAP_EACH_PACKET` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/DeferredLabels.cpp` | | reaps deferred labels after every packet | | `APS5_REGISTRATION_PREPARE_COMMIT_GB` | number | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp` | half of physical RAM | stops preparing newly registered shaders ahead of use when process-private memory reaches this GiB budget; `0` disables registration-time preparation | | `APS5_RELEASE_ON_UNLOCK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | destroys deferred batches on the unlocking thread instead of a release thread | @@ -531,6 +531,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_TRACE_TEXTURES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | prints a sampled texture's address, dimensions, format, tile mode, and how many of the bytes at offsets 0, 64, 128 and so on are nonzero | | `APS5_TRACE_UNREADABLE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp` | | names the code that checked an inaccessible range | | `APS5_TRACE_UPLOAD` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | names why a storage image is uploaded again | +| `APS5_UNIFORM_CONSTANT_BUFFERS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 1 | with pushed buffers, `1` reads a guest buffer that a heap stage only loads with scalar loads at constant offsets (within 64 KiB) as a uniform buffer, and `0` keeps it a storage buffer; needs `VK_KHR_uniform_buffer_standard_layout` | | `APS5_UNIT_SHADOW_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp` | 1/8 of the device-local heap budget the first context reports, 128-1024 | budget in MiB of the unit shadow's slabs; the default was measured only on a card with a 6.5 GiB device-local budget | | `APS5_UNIT_SHADOW_SLAB_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp` | 8 | size in MiB of one unit-shadow slab | | `APS5_VALIDATE_LEGACY` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WriteEvidence.cpp` | | uses the legacy snapshot and full-compare path for pending-write validation | From a9728e4dd44cecebe21132bb1fde1a7f45bed8af Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 8 Nov 2026 15:31:46 +0530 Subject: [PATCH 146/269] fix(agc): bind guest buffers in place at the storage buffer alignment Pushed constant buffers read as uniform buffers need a view start on the uniform offset alignment, which the start adjustment of every guest buffer view and of the copies standing in for one already gives. The checks deciding whether a buffer is bound in place inside a host import or an image mirror had been raised to that alignment too, so many more buffers were copied out of imports on the GPU (0.67 copies per buffer upload in GTA V against 0.48). They go back to the storage buffer offset alignment; the adjustment, measured from the start of the import or mirror, still gives a uniform-aligned address. --- .../prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 07f0003ccb1a..31b154553776 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -5400,7 +5400,7 @@ bool GuestBufferMemory::bindSparseMirror(Region& region, const GuestAllocations: refreshHeapMirrors(whole, blocks); } compareBlocks(blocks); - if (mirror == nullptr || !mirror->heap || region.begin < mirror->base || (region.begin - mirrorStart(*mirror)) % viewAlignment() != 0) return false; + if (mirror == nullptr || !mirror->heap || region.begin < mirror->base || (region.begin - mirrorStart(*mirror)) % context.limits.minStorageBufferOffsetAlignment != 0) return false; region.mirror = std::move(mirror); if (!servesView(region, std::max(region.lastView, region.begin))) { region.mirror = nullptr; @@ -5942,7 +5942,7 @@ bool GuestBufferMemory::gpuCopyEligible(const Region& region) const { bool GuestBufferMemory::bindableInPlace(std::uint64_t offset, bool addressable) const { if (adjustedRegions && !addressable) return offset % 4 == 0; - return offset % viewAlignment() == 0; + return offset % context.limits.minStorageBufferOffsetAlignment == 0; } VkDeviceSize GuestBufferViewAlignment(const VkPhysicalDeviceLimits& limits) { From 10d2e59d25efd92bbb905bb56797b8afa82489a7 Mon Sep 17 00:00:00 2001 From: Dean Galvin Date: Sun, 8 Nov 2026 23:24:05 +1300 Subject: [PATCH 147/269] test(agc): expect no recipe draws for relocated hits under entry verification APS5_VERIFY_DRAW_ENTRIES records every draw-cache hit afresh to compare it, so the relocated-recipe check from main cannot see recipe draws in the entries_verify run this branch adds. --- .../libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp index e6289206660d..701bc613af49 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp @@ -294,6 +294,11 @@ void RelocatedDrawsReuseTheirRecipe(bool libraries) { const auto recipeHits = AgcDriver::VulkanDevice::DrawRecipeHits() - recipesBefore; const auto hits = counters.hits - start.hits; Require(hits == moved.size() - 4, mode + ": draws whose data moved again made " + std::to_string(hits) + " draw-cache hits, expected " + std::to_string(moved.size() - 4)); + // Entry verification (APS5_VERIFY_DRAW_ENTRIES) records every hit afresh to compare it, so no hit is drawn from a recipe. + if (std::getenv("APS5_VERIFY_DRAW_ENTRIES") != nullptr) { + Require(recipeHits == 0, mode + ": " + std::to_string(recipeHits) + " draws served by a relocated entry were recorded from a recipe while entry verification records every hit afresh"); + return; + } Require(recipeHits == hits, mode + ": " + std::to_string(recipeHits) + " of " + std::to_string(hits) + " draws served by a relocated entry were recorded from the cached draw's recipe, expected all"); } From 32dec134b4427be0344ea1629c78e3c56aa5aa8c Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 8 Nov 2026 17:04:40 +0530 Subject: [PATCH 148/269] refactor(agc): drop the heap's buffer descriptor ring path and its switches Heap stages read their guest buffers through pushed addresses on every vendor (vkd3d-proton's root descriptors), and read-only constant buffers as uniform buffers wherever the device allows it. The code only the switches still reached goes: - APS5_PUSHED_BUFFERS and APS5_UNIFORM_CONSTANT_BUFFERS are removed. APS5_PUSHED_BUFFER_RECORDS stays as the test cap that drives the overflow block. - The ring buffer descriptors (RingBufferDescriptors, each stage's descriptor run with its pending and settle state, the push-index ring mapping) and the shader-data copy of buffer addresses are removed. A heap stage without guest buffers now reads its flattened SRT through the pushed SRT address like every other heap stage. - The recompiler drops SpirvTarget::heapBufferDescriptors and pushedBufferAddresses, IrBindingLayout::pushedBuffers (a heap stage with buffer address words always pushes them) and the physical-address path for those buffers. Request serialization version 59 drops both target fields; versions 56 to 58 still read. Shader disk cache format 66. - Tests: the moved-buffer test's ring-descriptor and forced-push variants and ShaderMemory's addressed coherent-buffer check (it covered the removed physical-address path) are removed; serializer fixtures move to version 59. --- .../Execution/src/VulkanDevice.cpp | 14 +- .../Graphics/include/BindlessHeap.hpp | 9 +- .../Graphics/include/Context.hpp | 1 - .../Graphics/include/ShaderResources.hpp | 21 +-- .../Graphics/src/BindlessHeap.cpp | 95 +---------- .../Graphics/src/ShaderResources.cpp | 156 ++---------------- .../libSceAgcDriver/tests/ShaderMemory.cpp | 66 +------- ...river_draw_recipe_moved_buffer_tests.cmake | 6 +- .../tests/execution/DrawRecipeMovedBuffer.cpp | 5 +- core/shader/recompiler/CacheKey.hpp | 2 - .../ControlFlow/src/RequestSerializer.cpp | 10 +- .../IrMetadata/DescriptorBinding.hpp | 1 - .../include/Optimization/BindingAllocator.hpp | 1 - .../Optimization/src/BindingAllocator.cpp | 3 +- core/shader/recompiler/Recompiler.cpp | 5 +- core/shader/recompiler/Recompiler.hpp | 2 - core/shader/recompiler/ShaderDiskCache.cpp | 2 - core/shader/recompiler/ShaderDiskCache.hpp | 2 +- .../include/SpirvBackend/SpirvEmitter.hpp | 1 - .../SpirvBackend/SpirvEmitterState.hpp | 2 - .../SpirvBackend/src/SpirvEmitter.cpp | 1 - .../src/SpirvMemory/SpirvBufferAccess.cpp | 10 +- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 9 +- .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 42 ++--- .../tests/RequestSerializerTests.cpp | 79 ++++----- docs/dev/ENVIRONMENT.md | 2 - 26 files changed, 89 insertions(+), 458 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index a886753f31b7..41f427636236 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -751,8 +751,6 @@ struct VulkanDevice::State { bool descriptorHeap = false; VkPhysicalDeviceDescriptorHeapPropertiesEXT descriptorHeapProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_PROPERTIES_EXT}; std::uint32_t heapDataUniformDwords = 0; - bool heapBufferDescriptors = false; - bool pushedBufferAddresses = false; bool uniformConstantBuffers = false; std::unique_ptr recorder; // Device-local buffers of a repeated 16-byte fill pattern (FillBuffer), most recently used @@ -2296,17 +2294,12 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : state->descriptorHeap = true; state->maintenance5 = true; state->heapDataUniformDwords = std::min(HeapDataUniformDwordCap, state->properties.limits.maxUniformBufferRange / 4u); - if (Graphics::BindlessHeap::RingInResourceHeap(state->descriptorHeapProperties, state->properties.limits.minUniformBufferOffsetAlignment)) - state->heapBufferDescriptors = state->descriptorHeapProperties.bufferDescriptorSize == Graphics::BindlessHeap::BufferSlotBytes; - state->pushedBufferAddresses = Graphics::ChoosePushedBufferAddresses(); - // A pushed constant buffer is a uniform block of dwords (array stride 4), which needs the - // standard (std430) uniform buffer layout. if (hasExtension(VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 layoutFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &standardLayout}; state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &layoutFeatures); standardLayout.pNext = nullptr; } - state->uniformConstantBuffers = Graphics::ChooseUniformConstantBuffers(state->pushedBufferAddresses && standardLayout.uniformBufferStandardLayout == VK_TRUE, state->properties.limits); + state->uniformConstantBuffers = Graphics::ChooseUniformConstantBuffers(standardLayout.uniformBufferStandardLayout == VK_TRUE, state->properties.limits); if (state->uniformConstantBuffers) deviceExtensions.push_back(VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME); deviceExtensions.push_back(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME); for (const char* required : {VK_KHR_MAINTENANCE_5_EXTENSION_NAME, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_DEPTH_STENCIL_RESOLVE_EXTENSION_NAME, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME}) { @@ -4739,9 +4732,7 @@ ShaderRecompiler::SpirvTarget VulkanDevice::Target() const { target.float32DenormPreserve = state->float32DenormPreserve; target.descriptorMemory = Graphics::DescriptorHeapEnabled(); target.heapDataUniformDwords = target.descriptorMemory ? state->heapDataUniformDwords : 0u; - target.heapBufferDescriptors = target.descriptorMemory && state->heapBufferDescriptors; - target.pushedBufferAddresses = target.descriptorMemory && state->pushedBufferAddresses; - target.uniformConstantBuffers = target.pushedBufferAddresses && state->uniformConstantBuffers; + target.uniformConstantBuffers = target.descriptorMemory && state->uniformConstantBuffers; target.float16WidenNans = state->float16WidenNans; target.float16NarrowNans = state->float16NarrowNans; return target; @@ -4895,7 +4886,6 @@ Graphics::Context VulkanDevice::buildContext() const { context.recorder = state->recorder.get(); context.descriptorHeap = state->descriptorHeap; context.descriptorHeapProperties = state->descriptorHeapProperties; - context.heapBufferDescriptors = state->heapBufferDescriptors; context.descriptorCache = state->descriptorCache.get(); context.vertexInputs = state->vertexInputs.get(); context.vertexFormats = &state->vertexFormats; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 32d6182a1944..38ccb0369494 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -44,7 +44,6 @@ class BindlessHeap { static BindlessHeap* Existing(const Context& context); static void Release(VkDevice device); static bool Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties); - static bool RingInResourceHeap(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, VkDeviceSize uniformAlignment); bool DescriptorHeapMode() const { return resourceHeap != nullptr; } VkDeviceSize ImageHeapStride() const { return imageHeapStride; } @@ -107,7 +106,6 @@ class BindlessHeap { bool acquired; }; std::optional KeepOrAllocate(std::size_t words, SpanMark& mark, bool same); - std::uint32_t RingBufferDescriptors(std::span buffers, SpanMark& mark); static constexpr std::uint32_t BufferSlotBytes = 16u; static constexpr std::uint32_t SamplerKind = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Samplers); @@ -119,7 +117,7 @@ class BindlessHeap { std::uint64_t ringWraps = 0, encodes = 0, encodedCopies = 0; std::uint64_t slotsFreed = 0, slotsReused = 0, slotsEvicted = 0, evictionWaits = 0; std::uint64_t ringWaits = 0, ringBatchPeakBytes = 0, ringSpanPeakBytes = 0, ringBytes = 0, imageSlotsHeld = 0; - std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0, busyChunksSkipped = 0, bufferDescriptors = 0; + std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0, busyChunksSkipped = 0; std::uint64_t ringPressureSubmits = 0, slotPressureSubmits = 0, samplersEvicted = 0; std::uint64_t poolBytes = 0, poolBatchPeakBytes = 0, poolBlocksMade = 0, poolBlocksRecycled = 0, poolBlocksFreed = 0, poolBlocksHeld = 0, poolBlockBytes = 0; }; @@ -305,9 +303,7 @@ class HeapSlotOwner { bool GpuHeapEnabled(); void SetDescriptorHeapDevice(bool available); bool DescriptorHeapEnabled(); -bool ChoosePushedBufferAddresses(); -bool PushedBufferAddressesEnabled(); -bool ChooseUniformConstantBuffers(bool pushed, const VkPhysicalDeviceLimits& limits); +bool ChooseUniformConstantBuffers(bool standardLayout, const VkPhysicalDeviceLimits& limits); bool UniformConstantBuffersEnabled(); bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds = false, bool meshWindow = false, bool scratchPool = false, std::pair* refused = nullptr); @@ -347,7 +343,6 @@ enum class HeapCost : std::uint8_t { TemplateBuild, Slots, StageData, - BufferAddresses, MemoInsert, Guards, Count diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index a66632a727b8..60f232a6119a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -247,7 +247,6 @@ struct Context { // Batches GPU work across guest commands (see Recorder); null before the device finished setup. Recorder* recorder = nullptr; bool descriptorHeap = false; - bool heapBufferDescriptors = false; VkPhysicalDeviceDescriptorHeapPropertiesEXT descriptorHeapProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_PROPERTIES_EXT}; // Per-device caches of the immutable descriptor objects a ShaderResources build needs (set // layouts, descriptor pools, samplers); null (tests) means every build makes and destroys its own. diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 6877eb529bab..25e8f5d48563 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -168,7 +168,6 @@ struct ImageTableReuseCounts { }; ImageTableReuseCounts ImageTableReuses(); struct HeapBufferPathCounts { - std::uint64_t ringRuns = 0; std::uint64_t pushedStages = 0; std::uint64_t overflowStages = 0; }; @@ -681,15 +680,7 @@ class ShaderResources { bool splitSets = false; bool heapStage = false; mutable std::array heapOffsets{}; - mutable std::array ringRunPending{}; - void settleRingRuns() const; void writeHeapStage(const CompiledShader& shader); - struct RingDescriptors { - VkDeviceAddressRangeEXT srt{}; - std::vector ranges; - BindlessHeap::SpanMark mark; - std::uint32_t first = 0; - }; struct HeapStageState { std::vector key; std::array, static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)> slots; @@ -706,7 +697,6 @@ class ShaderResources { }; KeptSpan data, flat, map; std::vector dataInput; - mutable RingDescriptors descriptors; std::uint64_t inertProgram = 0; }; std::array heapStages; @@ -747,22 +737,13 @@ class ShaderResources { std::vector resolvedAddresses; VkDeviceAddress emptyAddress = 0; std::size_t gdsAllocation = std::numeric_limits::max(); - std::array, ShaderRecompiler::RuntimeAbi::StageCount> stageDataWords; - std::array stageDataIndex{}; std::array heapSrtDwords{}; std::array heapTableMaps{}; std::array heapTableMapSet{}; void writeHeapTableMap(const CompiledShader& shader, std::size_t stageIndex); - void writeBufferAddresses(std::span words, std::uint32_t dataStage, const std::vector* overrides, - std::vector* ranges = nullptr) const; - VkDeviceAddressRangeEXT srtRange(std::size_t stage) const; - bool stageReadsOverride(std::size_t stage, const std::vector& overrides) const; + void bufferRanges(std::uint32_t dataStage, const std::vector* overrides, std::vector& ranges) const; VkDeviceAddressRangeEXT bufferAddress(const Allocation& allocation) const; void resolveBufferAddresses(); - std::uint32_t ringDescriptors(std::size_t stage, const std::vector* overrides, RingDescriptors& kept) const; - std::array heapSrtOffsets{}; - std::array ringDescriptorStages{}; - std::array addressedOffsets(const std::vector* overrides) const; struct FaultDescriptor { std::size_t write; std::size_t buffer; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 27379308321a..eaeda9525af8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -149,22 +149,6 @@ bool DescriptorHeapEnabled() { return GpuHeapEnabled() && descriptorHeapDevice.load(std::memory_order_relaxed); } -namespace { - -std::atomic pushedBufferAddresses{false}; - -} - -// vkd3d-proton's heap mode passes root descriptors as addresses in push data on every vendor and maps -// them as real buffers (dxil.c heap lowering). Heap stages do the same with their guest buffers; -// APS5_PUSHED_BUFFERS=0 reads them through heap buffer descriptors written per draw instead. -bool ChoosePushedBufferAddresses() { - const char* forced = std::getenv("APS5_PUSHED_BUFFERS"); - const bool chosen = forced == nullptr || *forced == '\0' || std::strcmp(forced, "0") != 0; - pushedBufferAddresses.store(chosen, std::memory_order_relaxed); - return chosen; -} - std::uint32_t PushedBufferRecordCap() { static const std::uint32_t cap = [] { const char* value = std::getenv("APS5_PUSHED_BUFFER_RECORDS"); @@ -173,30 +157,21 @@ std::uint32_t PushedBufferRecordCap() { return cap; } -bool PushedBufferAddressesEnabled() { - return DescriptorHeapEnabled() && pushedBufferAddresses.load(std::memory_order_relaxed); -} - namespace { std::atomic uniformConstantBuffers{false}; } -// vkd3d-proton's heap mode maps every root constant buffer as a uniform buffer, on every vendor. -// Pushed guest buffers that a stage only reads with scalar loads at constant offsets follow it; -// APS5_UNIFORM_CONSTANT_BUFFERS=0 keeps them storage buffers. -bool ChooseUniformConstantBuffers(bool pushed, const VkPhysicalDeviceLimits& limits) { - const char* forced = std::getenv("APS5_UNIFORM_CONSTANT_BUFFERS"); - const bool wanted = forced == nullptr || *forced == '\0' || std::strcmp(forced, "0") != 0; - const bool chosen = wanted && pushed && limits.maxUniformBufferRange >= ShaderRecompiler::RuntimeAbi::UniformConstantBufferBytes && +bool ChooseUniformConstantBuffers(bool standardLayout, const VkPhysicalDeviceLimits& limits) { + const bool chosen = standardLayout && limits.maxUniformBufferRange >= ShaderRecompiler::RuntimeAbi::UniformConstantBufferBytes && limits.minUniformBufferOffsetAlignment <= ShaderRecompiler::RuntimeAbi::UniformViewAdjustmentLimit + 1u; uniformConstantBuffers.store(chosen, std::memory_order_relaxed); return chosen; } bool UniformConstantBuffersEnabled() { - return PushedBufferAddressesEnabled() && uniformConstantBuffers.load(std::memory_order_relaxed); + return DescriptorHeapEnabled() && uniformConstantBuffers.load(std::memory_order_relaxed); } namespace { @@ -273,10 +248,6 @@ HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& propertie } -bool BindlessHeap::RingInResourceHeap(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, VkDeviceSize uniformAlignment) { - return heapSizes(properties, uniformAlignment).ringBytes != 0u; -} - bool BindlessHeap::Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { const auto sizes = heapLayout(properties, Abi::GpuImageHeapSlots, 0u); const bool resourcesFit = sizes.resourceUsed + properties.minResourceHeapReservedRange <= properties.maxResourceHeapSize; @@ -1118,8 +1089,6 @@ struct HeapBindingUse { bool meshWindowMemory = false; bool scratchPoolMemory = false; std::vector dataUniforms; - std::vector ringBuffers; - std::vector srtAddresses; std::vector embeddedSamplers; std::vector pushedBuffers; std::pair refused{~0u, ~0u}; @@ -1190,14 +1159,6 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& continue; } const bool stageBinding = binding / bindingCount < Abi::StageCount; - if (roots.gdsAddress && stageBinding && set == Abi::DescriptorSet && binding % bindingCount == static_cast(Abi::Binding::Buffers)) { - if (std::ranges::find(use.ringBuffers, binding) == use.ringBuffers.end()) use.ringBuffers.push_back(binding); - continue; - } - if (roots.gdsAddress && stageBinding && set == Abi::GpuDataSet && binding % bindingCount == static_cast(Abi::Binding::FlattenedSrt)) { - if (std::ranges::find(use.srtAddresses, binding) == use.srtAddresses.end()) use.srtAddresses.push_back(binding); - continue; - } const bool heapImageOrSampler = set == Abi::FragmentDescriptorSet && binding >= firstImage && binding <= samplers; if (!heapImageOrSampler) { use.refused = entry; @@ -1239,20 +1200,6 @@ std::uint32_t rootItemOffset(const ShaderRecompiler::StagePushPlacement* placeme return placement->Item(item) * static_cast(sizeof(std::uint32_t)); } -VkDescriptorSetAndBindingMappingEXT ringBufferMapping(std::uint32_t binding, VkDeviceSize ringOffset, const ShaderRecompiler::StagePushPlacement* placement) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = Abi::DescriptorSet; - mapping.firstBinding = binding; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; - mapping.sourceData.pushIndex.heapOffset = static_cast(ringOffset); - mapping.sourceData.pushIndex.pushOffset = rootItemOffset(placement, Abi::RootItem::FlattenedSrt); - mapping.sourceData.pushIndex.heapIndexStride = BindlessHeap::BufferSlotBytes; - mapping.sourceData.pushIndex.heapArrayStride = BindlessHeap::BufferSlotBytes; - return mapping; -} - VkDescriptorSetAndBindingMappingEXT pushedBufferMapping(std::uint32_t binding, const ShaderRecompiler::StagePushPlacement* placement) { Require(placement != nullptr && binding < placement->pushedBuffers, "a heap mapping reads a pushed buffer its pipeline's push layout does not count"); VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; @@ -1380,8 +1327,6 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, .workgroupAddress = workgroupAddressOffset != ~0u, .gdsAddress = rootGds, .faultAddress = rootFault, .pixelLds = pixelLds, .meshWindow = meshWindow, .scratchPool = scratchPool}; if (!heapBindings(spirv, roots, use)) return false; - if (!use.ringBuffers.empty() && !ringInHeap) return false; - if (!use.ringBuffers.empty() && context.descriptorHeapProperties.bufferDescriptorSize != BufferSlotBytes) return false; constexpr auto bindingCount = static_cast(Abi::Binding::Count); constexpr VkSpirvResourceTypeFlagsEXT imageResources = VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_IMAGE_BIT_EXT | @@ -1411,10 +1356,6 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, placement)); std::ranges::sort(use.pushedBuffers); for (const auto binding : use.pushedBuffers) mappings.push_back(pushedBufferMapping(binding, placement)); - std::ranges::sort(use.ringBuffers); - for (const auto binding : use.ringBuffers) mappings.push_back(ringBufferMapping(binding, ringHeapOffset, placement)); - std::ranges::sort(use.srtAddresses); - for (const auto binding : use.srtAddresses) mappings.push_back(pushAddressMapping(Abi::GpuDataSet, binding, rootItemOffset(placement, Abi::RootItem::SrtAddress))); if (use.workgroupMemory) mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset)); if (use.scratchPoolMemory) @@ -1432,28 +1373,6 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, return true; } -std::uint32_t BindlessHeap::RingBufferDescriptors(std::span buffers, SpanMark& mark) { - Require(ringInHeap && context.descriptorHeapProperties.bufferDescriptorSize == BufferSlotBytes, "ring buffer descriptors need the descriptor ring inside the resource heap"); - SpanScope scope(*this); - const auto span = RingAllocate(buffers.size() * (BufferSlotBytes / sizeof(std::uint32_t)), mark); - counts.bufferDescriptors += buffers.size(); - Require(span.offset % BufferSlotBytes == 0u, "a ring buffer descriptor span is misaligned"); - struct ResourcesStorage {}; - struct RangesStorage {}; - auto& resources = HostThreadLocal, ResourcesStorage>(); - auto& ranges = HostThreadLocal, RangesStorage>(); - resources.assign(buffers.size(), {VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT}); - ranges.resize(buffers.size()); - auto* bytes = reinterpret_cast(span.words.data()); - for (std::size_t index = 0; index < buffers.size(); ++index) { - resources[index].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - resources[index].data.pAddressRange = &buffers[index]; - ranges[index] = {bytes + index * BufferSlotBytes, BufferSlotBytes}; - } - Check(writeResourceDescriptors(context.device, static_cast(buffers.size()), resources.data(), ranges.data()), "vkWriteResourceDescriptorsEXT ring buffers"); - return static_cast(span.offset / BufferSlotBytes); -} - void BindlessHeap::writeBufferDescriptor(VkDeviceSize offset, VkDeviceAddress address, VkDeviceSize bytes, const char* what) { const auto& properties = context.descriptorHeapProperties; Require(offset + properties.bufferDescriptorSize <= resourceHeapUsed, std::string("the ") + what + " descriptor lies outside the resource heap"); @@ -1516,7 +1435,7 @@ std::array, static_cast(HeapCost::Count) std::array, static_cast(HeapCost::Count)> heapCostCalls{}; constexpr std::array(HeapCost::Count)> HeapCostNames{ "stage prepare", "heap stage call", "stage finish", "walk memo", "walk", "materialize", "template find", - "template build", "slots", "stage data", "buffer addresses", "memo insert", "guards"}; + "template build", "slots", "stage data", "memo insert", "guards"}; void reportHeapStatistics() { if (!pipelineStats()) return; @@ -1565,7 +1484,6 @@ void reportHeapStatistics() { totals.spansExpired += counts.spansExpired; totals.encodes += counts.encodes; totals.encodedCopies += counts.encodedCopies; - totals.bufferDescriptors += counts.bufferDescriptors; totals.slotsEvicted += counts.slotsEvicted; totals.evictionWaits += counts.evictionWaits; totals.ringWaits += counts.ringWaits; @@ -1592,7 +1510,6 @@ void reportHeapStatistics() { const auto spansExpired = windowDelta(totals.spansExpired, lastTotals.spansExpired); const auto imageEncodes = windowDelta(totals.encodes, lastTotals.encodes); const auto imageCopies = windowDelta(totals.encodedCopies, lastTotals.encodedCopies); - const auto bufferDescriptors = windowDelta(totals.bufferDescriptors, lastTotals.bufferDescriptors); const auto slotsEvicted = windowDelta(totals.slotsEvicted, lastTotals.slotsEvicted); const auto evictionWaits = windowDelta(totals.evictionWaits, lastTotals.evictionWaits); const auto ringWaits = windowDelta(totals.ringWaits, lastTotals.ringWaits); @@ -1610,10 +1527,10 @@ void reportHeapStatistics() { std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; excluded:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; descriptor ring %llu MiB, %llu waits, %llu busy chunks skipped, %llu early submits, since start at most %llu KiB per batch; image descriptors %llu encoded / %llu copied; buffer descriptors %llu; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; descriptor ring %llu MiB, %llu waits, %llu busy chunks skipped, %llu early submits, since start at most %llu KiB per batch; image descriptors %llu encoded / %llu copied; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), excluded.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(ringMiB), printed(ringWaits), printed(busySkips), printed(pressureSubmits), printed(totals.ringBatchPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(bufferDescriptors), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(ringMiB), printed(ringWaits), printed(busySkips), printed(pressureSubmits), printed(totals.ringBatchPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 68b110eeeea9..6b122b78b877 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6071,14 +6071,13 @@ std::uint64_t SampledTexturesCleared() { namespace { -std::atomic heapRingRuns{0}; std::atomic heapPushedStages{0}; std::atomic heapOverflowStages{0}; } HeapBufferPathCounts HeapBufferPaths() { - return {heapRingRuns.load(std::memory_order_relaxed), heapPushedStages.load(std::memory_order_relaxed), heapOverflowStages.load(std::memory_order_relaxed)}; + return {heapPushedStages.load(std::memory_order_relaxed), heapOverflowStages.load(std::memory_order_relaxed)}; } ImageTableReuseCounts ImageTableReuses() { @@ -6605,7 +6604,7 @@ void ShaderResources::writeDrawSets(DrawBindings& result, std::span& overrides) const { - for (const auto& binding : bindings) { - if (!binding.addressed || binding.dataStage != stage) continue; - for (const auto index : binding.allocations) { - if (index < overrides.size() && overrides[index].buffer != VK_NULL_HANDLE) return true; - } - } - return false; -} - -void ShaderResources::settleRingRuns() const { - if (std::ranges::none_of(ringRunPending, [](bool pending) { return pending; })) return; - const BindlessHeap::SpanScope spans(BindlessHeap::For(context)); - for (std::size_t stage = 0; stage < ringRunPending.size(); ++stage) { - if (!ringRunPending[stage]) continue; - ringRunPending[stage] = false; - heapOffsets[DataOffsetIndex(stage, ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt)] = ringDescriptors(stage, nullptr, heapStages[stage].descriptors); - } -} - -std::array ShaderResources::addressedOffsets(const std::vector* overrides) const { - auto& heap = BindlessHeap::For(context); - const BindlessHeap::SpanScope spans(heap); - const auto moved = [&](std::size_t stage) { return overrides == nullptr || stageReadsOverride(stage, *overrides); }; - for (std::size_t stage = 0; stage < ringRunPending.size(); ++stage) { - if (!ringRunPending[stage] || (ringDescriptorStages[stage] && moved(stage))) continue; - ringRunPending[stage] = false; - heapOffsets[DataOffsetIndex(stage, ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt)] = ringDescriptors(stage, nullptr, heapStages[stage].descriptors); - } - auto offsets = heapOffsets; - for (std::size_t stage = 0; stage < stageDataWords.size(); ++stage) { - if (stageDataWords[stage].empty() || !moved(stage)) continue; - auto words = stageDataWords[stage]; - writeBufferAddresses(words, static_cast(stage), overrides); - auto span = heap.Allocate(words.size()); - BindlessHeap::Write(span, words); - offsets[stageDataIndex[stage]] = span.address; - } - for (std::size_t stage = 0; stage < ringDescriptorStages.size(); ++stage) { - if (!ringDescriptorStages[stage] || !moved(stage)) continue; - RingDescriptors fresh; - offsets[DataOffsetIndex(stage, ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt)] = ringDescriptors(stage, overrides, fresh); - } - return offsets; + if (rewritten.addressOffsets) rewritten.heapOffsets = heapOffsets; } void ShaderResources::prepareFaultSlot() const { @@ -6788,8 +6741,7 @@ void ShaderResources::resolveBufferAddresses() { } } -void ShaderResources::writeBufferAddresses(std::span words, std::uint32_t dataStage, const std::vector* overrides, - std::vector* ranges) const { +void ShaderResources::bufferRanges(std::uint32_t dataStage, const std::vector* overrides, std::vector& ranges) const { static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; for (const auto& binding : bindings) { if (!binding.addressed || binding.dataStage != dataStage) continue; @@ -6822,49 +6774,11 @@ void ShaderResources::writeBufferAddresses(std::span words, std:: address = fresh.address; range = fresh.size; } - if (ranges != nullptr) ranges->push_back({address, std::min(range, context.limits.maxStorageBufferRange)}); - if (words.empty()) continue; - const auto at = static_cast(binding.addressDword) + element * 4u; - Require(at + 3u < words.size(), "buffer address words lie outside the shader data"); - words[at] = static_cast(address); - words[at + 1u] = static_cast(address >> 32u); - words[at + 2u] = static_cast(std::min(range, 0xffffffffu)); - words[at + 3u] = 0u; + ranges.push_back({address, std::min(range, context.limits.maxStorageBufferRange)}); } } } -VkDeviceAddressRangeEXT ShaderResources::srtRange(std::size_t stage) const { - const auto bytes = static_cast(heapSrtDwords[stage]) * sizeof(std::uint32_t); - if (bytes == 0u || bytes > context.limits.maxStorageBufferRange) { - const auto empty = emptyAddress != 0 ? emptyAddress : BufferDeviceAddress(context, context.emptyBuffer); - Require(empty != 0, "the empty buffer has no device address"); - return {empty, EmptyBufferBytes}; - } - return {heapSrtOffsets[stage], bytes}; -} - -std::uint32_t ShaderResources::ringDescriptors(std::size_t stage, const std::vector* overrides, RingDescriptors& kept) const { - struct RangeStorage {}; - auto& ranges = HostThreadLocal, RangeStorage>(); - ranges.clear(); - writeBufferAddresses({}, static_cast(stage), overrides, &ranges); - if (ranges.empty()) { - kept.ranges.clear(); - kept.mark = {}; - kept.first = 0u; - return 0u; - } - auto& heap = BindlessHeap::For(context); - const auto equal = [](const VkDeviceAddressRangeEXT& a, const VkDeviceAddressRangeEXT& b) { return a.address == b.address && a.size == b.size; }; - if (!std::ranges::equal(ranges, kept.ranges, equal) || !heap.Held(kept.mark)) { - heapRingRuns.fetch_add(1, std::memory_order_relaxed); - kept.first = heap.RingBufferDescriptors(ranges, kept.mark); - kept.ranges.assign(ranges.begin(), ranges.end()); - } - return kept.first; -} - std::pair ShaderResources::shaderDataLocation(const CompiledShader& shader, const DrawBindings* rewritten) const { if (!heapStage || !HeapShader(shader)) return {shaderDataBuffer(shader), 0}; const auto& offsets = rewritten != nullptr && rewritten->addressOffsets ? rewritten->heapOffsets : heapOffsets; @@ -6875,11 +6789,6 @@ void ShaderResources::PatchDataAddresses(std::spanaddressOffsets; - if (!addressed) settleRingRuns(); - for (std::size_t stage = 0; addressed && stage < ringRunPending.size(); ++stage) { - if (ringRunPending[stage] && !stageReadsOverride(stage, rewritten->addressOverrides)) - throw std::runtime_error("AGC graphics: a GPU-mode stage's descriptor run was never written although the draw's moved buffers do not rewrite it"); - } const auto& offsets = addressed ? rewritten->heapOffsets : heapOffsets; VkDeviceAddress table = 0; VkDeviceAddress fault = 0; @@ -6939,10 +6848,8 @@ void ShaderResources::PatchDataAddresses(std::span(offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)])); - const bool ringStage = ringDescriptorStages[stage]; - const auto srt = ringStage ? srtRange(stage) : VkDeviceAddressRangeEXT{}; - putAddress(Abi::RootItem::SrtAddress, ringStage ? srt.address : offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)]); - put(Abi::RootItem::SrtDwords, 0u, ringStage ? static_cast(std::min(heapSrtDwords[stage], srt.size / sizeof(std::uint32_t))) : heapSrtDwords[stage]); + putAddress(Abi::RootItem::SrtAddress, offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)]); + put(Abi::RootItem::SrtDwords, 0u, heapSrtDwords[stage]); putAddress(Abi::RootItem::TableMap, heapTableMapSet[stage] ? heapTableMaps[stage] : offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); writePushedData(bytes, shader, placement.pushed); if (shader.program->pushedBufferCount != 0u) writePushedBuffers(bytes, stage, placement, addressed ? &rewritten->addressOverrides : nullptr, offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); @@ -6956,7 +6863,7 @@ void ShaderResources::writePushedBuffers(std::span, RangeStorage>(); ranges.clear(); - writeBufferAddresses({}, static_cast(stage), overrides, &ranges); + bufferRanges(static_cast(stage), overrides, ranges); Require(ranges.size() == placement.pushedBuffers, "a stage's buffer addresses do not match its push layout's buffer count"); heapPushedStages.fetch_add(1, std::memory_order_relaxed); Require(empty != 0u, "a stage with pushed buffers has no shader data to stand in for an empty buffer"); @@ -7337,7 +7244,6 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { const VkShaderStageFlags stageBit = VulkanStage(shader.stage); const auto stageIndex = HeapStageIndex(shader.stage); auto& stageState = heapStages[stageIndex]; - const bool skipped = std::exchange(ringRunPending[stageIndex], false); static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; const auto programIdentity = shader.program->heapTemplateId; if (programIdentity != 0 && stageState.inertProgram == programIdentity && !verifySlots) return; @@ -7367,12 +7273,6 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { const std::size_t flatIndex = DataOffsetIndex(stageIndex, Abi::Binding::FlattenedSrt); const auto& program = *shader.program; if (program.dataAddressPush) writeHeapTableMap(shader, stageIndex); - const bool ringStage = context.heapBufferDescriptors && program.dataAddressPush && program.pushedBufferCount == 0u; - ringDescriptorStages[stageIndex] = ringStage; - if (ringStage) stageDataWords[stageIndex].clear(); - bool dataKept = false; - bool inputsKept = false; - bool flattened = false; bool dataBindings = false; for (const auto& binding : program.bindings) { const bool shaderData = binding.role == ShaderRecompiler::DescriptorRole::ShaderData; @@ -7387,19 +7287,16 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { stageState.dataInput.size() == words.size() + userData.size() && std::equal(words.begin(), words.end(), stageState.dataInput.begin()) && std::equal(userData.begin(), userData.end(), stageState.dataInput.begin() + static_cast(words.size())); - if (sameInput && verifySlots && heap.Held(stageState.data.mark)) inputsKept = true; if (sameInput && !verifySlots) { if (heap.Held(stageState.data.mark)) { heapOffsets[dataIndex] = stageState.data.mark.address; - dataKept = true; continue; } stageState.data.mark.entry = 0; } if (!shaderData) { - (ringStage ? heapSrtOffsets[stageIndex] : heapOffsets[flatIndex]) = heapSpan(stageState.flat, words); + heapOffsets[flatIndex] = heapSpan(stageState.flat, words); heapSrtDwords[stageIndex] = static_cast(words.size()); - flattened = true; continue; } ValidateRuntimeResources(shader, words); @@ -7413,13 +7310,6 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { reinterpret_cast(patched.data())[byte] = static_cast(adjustment); } patchHeapSlotWords(shader, stageState, patched, current); - if (addressedBuffers && !ringStage && program.pushedBufferCount == 0u) { - HeapCostScope bufferCost(HeapCost::BufferAddresses); - writeBufferAddresses(patched, static_cast(stageIndex), nullptr); - bufferCost.Stop(); - stageDataWords[stageIndex].assign(patched.begin(), patched.end()); - stageDataIndex[stageIndex] = dataIndex; - } if (verifySlots && sameInput && !std::ranges::equal(stageState.data.words, patched)) throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its inputs and slots did not"); heapOffsets[dataIndex] = heapSpan(stageState.data, patched); @@ -7427,33 +7317,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); } const bool unbound = key.empty() && !dataBindings && !heapTableMapSet[stageIndex] && stageState.imageSlots.empty() && stageState.samplerSlots.empty(); - if (!ringStage) { - if (unbound && !addressedBuffers) stageState.inertProgram = programIdentity; - return; - } - if (!flattened) heapSrtDwords[stageIndex] = 0u; - auto& kept = stageState.descriptors; - const auto srt = srtRange(stageIndex); - const bool keepable = !skipped && kept.srt.address == srt.address && kept.srt.size == srt.size && (kept.ranges.empty() || heap.Held(kept.mark)); - kept.srt = srt; - if (dataKept && keepable) { - heapOffsets[flatIndex] = kept.first; - return; - } - if (!(inputsKept && keepable)) { - if (!unbound) { - ringRunPending[stageIndex] = true; - return; - } - heapOffsets[flatIndex] = ringDescriptors(stageIndex, nullptr, kept); - if (unbound && kept.ranges.empty() && heapOffsets[flatIndex] == 0u) stageState.inertProgram = programIdentity; - return; - } - const std::vector before(kept.ranges.begin(), kept.ranges.end()); - const auto first = kept.first; - heapOffsets[flatIndex] = ringDescriptors(stageIndex, nullptr, kept); - if (kept.first != first || !std::ranges::equal(before, kept.ranges, [](const auto& a, const auto& b) { return a.address == b.address && a.size == b.size; })) - throw std::runtime_error("AGC graphics: a GPU-mode stage's kept buffer descriptor run would bind other buffers although its inputs did not change"); + if (unbound && !addressedBuffers) stageState.inertProgram = programIdentity; } namespace { diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 9318e33417da..17e8f96c0cbf 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -8273,7 +8273,7 @@ void verifyPixelRequestSerialization() { minimal.context.pixel->layerExported = true; minimal.context.pixel->ditheredAlphaToCoverage = true; const auto encoded = serializer.Serialize(minimal); - require(requestPrefix(encoded, 8u) == "NVNQQToAAAA=", "new requests did not use serialization version 58"); + require(requestPrefix(encoded, 8u) == "NVNQQTsAAAA=", "new requests did not use serialization version 59"); auto withBarycentric = minimal; withBarycentric.target.fragmentBarycentricBuiltins = true; require(serializer.Deserialize(serializer.Serialize(withBarycentric)).request.target.fragmentBarycentricBuiltins && !serializer.Deserialize(encoded).request.target.fragmentBarycentricBuiltins, "barycentric built-ins were lost in serialization"); @@ -8394,7 +8394,7 @@ void verifyPixelRequestSerialization() { for (std::size_t bytes = 0; bytes < 45u; ++bytes) { expectFailure([&] { static_cast(serializer.Deserialize(requestPrefix(encoded, mappingOffset + bytes))); }, "truncated data", "a truncated pixel mapping, packing, dual-source, alpha-to-coverage, stencil reference export flag, primitive class, layer export, dither or front-face flag, quad pixel mask or quad sample mask was accepted"); } - for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQTsAAAA="}) { + for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQTwAAAA="}) { expectFailure([&] { static_cast(serializer.Deserialize(unsupported)); }, "serialization version", "an unsupported request version was accepted"); } static constexpr std::string_view version18Request{ @@ -8448,9 +8448,9 @@ std::vector decodeBase64(std::string_view text) { bytes.push_back(static_cast((chunk >> bits) & 0xffu)); } } - if (bytes.size() > 15u && bytes[4] == 58u) { - require(std::all_of(bytes.end() - 15, bytes.end(), [](std::uint8_t value) { return value == 0u; }), "a version 58 request in these checks set a GPU heap target field"); - bytes.resize(bytes.size() - 15u); + if (bytes.size() > 13u && bytes[4] == 59u) { + require(std::all_of(bytes.end() - 13, bytes.end(), [](std::uint8_t value) { return value == 0u; }), "a version 59 request in these checks set a GPU heap target field"); + bytes.resize(bytes.size() - 13u); bytes[4] = 55u; } return bytes; @@ -8458,8 +8458,8 @@ std::vector decodeBase64(std::string_view text) { std::string encodeBase64(std::vector bytes) { if (bytes.size() > 4u && bytes[4] == 55u) { - bytes[4] = 58u; - bytes.insert(bytes.end(), 15u, 0u); + bytes[4] = 59u; + bytes.insert(bytes.end(), 13u, 0u); } constexpr std::string_view alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string text; @@ -9708,7 +9708,7 @@ void verifyCoherentGds() { require(std::ranges::find(decorations[gds], static_cast(spv::DecorationCoherent)) != decorations[gds].end(), "coherent GDS: the gds buffer is not Coherent"); } -auto recompileCoherent(const std::vector& code, std::uint32_t address, std::span capabilities, bool addressed) { +auto recompileCoherent(const std::vector& code, std::uint32_t address, std::span capabilities) { using namespace ShaderRecompiler; alignas(256) static std::array input{}; alignas(256) static std::array output{}; @@ -9731,8 +9731,6 @@ auto recompileCoherent(const std::vector& code, std::uint32_t add request.target.supportedCapabilities = capabilities; request.target.supportedExtensions = extensions; request.target.fragmentShaderBarycentricEnabled = false; - request.target.gpuResolvedImages = addressed; - request.target.descriptorMemory = addressed; request.layout.pushConstantSizeBytes = 128; request.useCache = false; return Recompile(request).spirv; @@ -9751,7 +9749,7 @@ void verifyCoherentBufferAccesses() { std::vector code{0x34020082u}; if (invalidate) code.insert(code.end(), {0xe1c40000u, 0u}); code.insert(code.end(), {0xe0301000u | (glcLoad ? 0x4000u : 0u), 0x80000201u, 0xbf8c3f70u, 0xe0701000u | (glcStore ? 0x4000u : 0u), 0x80010201u, 0xbf810000u}); - const auto words = recompileCoherent(code, 0x5a000u, capabilities, false); + const auto words = recompileCoherent(code, 0x5a000u, capabilities); Module module; std::map bases; const auto base = [&](std::uint32_t pointer) { @@ -9811,51 +9809,6 @@ void verifyCoherentBufferAccesses() { require(only(invalidated.loads, "buffers") && only(invalidated.stores, "buffers"), "coherent buffers: a program that invalidates the vector caches does not use the coherent buffer array"); } -void verifyAddressedCoherentBufferAccesses() { - using namespace ShaderRecompiler; - const std::array capabilities{spv::CapabilityInt64, spv::CapabilityInt64Atomics, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess}; - struct Counts { - std::uint32_t loads = 0, stores = 0, wideLoads = 0; - }; - const auto compile = [&](bool glcLoad, bool glcStore, bool pair, bool invalidate) { - const std::uint32_t loadOp = pair ? 0xe0341000u : 0xe0301000u; - const std::uint32_t storeOp = pair ? 0xe0741000u : 0xe0701000u; - std::vector code{0x34020082u}; - if (invalidate) code.insert(code.end(), {0xe1c40000u, 0u}); - code.insert(code.end(), {loadOp | (glcLoad ? 0x4000u : 0u), 0x80000201u, 0xbf8c3f70u, storeOp | (glcStore ? 0x4000u : 0u), 0x80010201u, 0xbf810000u}); - const auto words = recompileCoherent(code, 0x5b000u, capabilities, true); - std::set wideTypes; - Counts counts; - for (std::size_t cursor = 5; cursor < words.size();) { - const auto count = words[cursor] >> 16u; - const auto opcode = words[cursor] & 0xffffu; - require(count != 0 && count <= words.size() - cursor, "addressed coherent buffers: truncated SPIR-V instruction"); - if (opcode == spv::OpTypeInt && words[cursor + 2] == 64u) wideTypes.insert(words[cursor + 1]); - if (opcode == spv::OpAtomicLoad) ++(wideTypes.contains(words[cursor + 1]) ? counts.wideLoads : counts.loads); - if (opcode == spv::OpAtomicStore) ++counts.stores; - cursor += count; - } - return counts; - }; - - const auto plain = compile(false, false, false, false); - require(plain.loads == 0u && plain.stores == 0u && plain.wideLoads == 0u, "addressed coherent buffers: accesses without GLC became atomics"); - - const auto single = compile(true, true, false, false); - require(single.loads != 0u, "addressed coherent buffers: a GLC load through a buffer address is not an atomic load"); - require(single.stores != 0u, "addressed coherent buffers: a GLC store through a buffer address is not an atomic store"); - - const auto wide = compile(true, true, true, false); - require(wide.wideLoads != 0u, "addressed coherent buffers: a GLC two-dword load through a buffer address is not one 64-bit atomic load"); - require(wide.stores != 0u, "addressed coherent buffers: a GLC two-dword store through a buffer address is not an atomic store"); - - const auto invalidated = compile(false, true, false, true); - require(invalidated.loads != 0u, "addressed coherent buffers: a load without GLC in a program that invalidates the vector caches is not an atomic load"); - - const auto invalidatedPlain = compile(false, false, false, true); - require(invalidatedPlain.loads == 0u && invalidatedPlain.stores == 0u, "addressed coherent buffers: a program that invalidates the vector caches without GLC or DLC accesses made its accesses atomic"); -} - void verifyUnnormalizedSamplers() { using namespace ShaderRecompiler; constexpr std::uint32_t Format8888UNorm = 56; @@ -12097,7 +12050,6 @@ int main(int argc, char** argv) { verifyInt64AtomicCapabilities(); verifySpecializedBufferAtomicBindings(); verifyCoherentBufferAccesses(); - verifyAddressedCoherentBufferAccesses(); verifyUnnormalizedSamplers(); verifyUnusedUnnormalizedSampler(); verifyNullVolumeUnnormalizedSampler(); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake index 2cd0da54e09d..eca349833621 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake @@ -1,10 +1,6 @@ if(BUILD_TESTING) agc_add_gpu_heap_test(agc_driver_draw_recipe_moved_buffer) - agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_descriptors agc_driver_draw_recipe_moved_buffer_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_PUSHED_BUFFERS=0) - agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_pushed agc_driver_draw_recipe_moved_buffer_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_PUSHED_BUFFERS=1) agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_overflow agc_driver_draw_recipe_moved_buffer_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_PUSHED_BUFFERS=1 APS5_PUSHED_BUFFER_RECORDS=0) + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_PUSHED_BUFFER_RECORDS=0) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp index cb8cd89f4dba..302358a365d7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp @@ -356,12 +356,9 @@ int main() { const auto paths = AgcDriver::Graphics::HeapBufferPaths(); if (AgcDriver::Graphics::DrawRecipes() && std::getenv("APS5_VERIFY_DRAW_ENTRIES") == nullptr) { Require(hits == slices.size(), "a repeated draw whose read-only buffer moved from its template's did not replay a recipe (" + std::to_string(hits) + " recipe hits for " + std::to_string(slices.size()) + " draws)"); - if (AgcDriver::Graphics::PushedBufferAddressesEnabled()) { - Require(paths.ringRuns == pathsBefore.ringRuns, "a recipe hit whose moved buffer the stage reads through its push data wrote " + std::to_string(paths.ringRuns - pathsBefore.ringRuns) + " heap descriptor runs"); + if (AgcDriver::Graphics::DescriptorHeapEnabled()) { Require(paths.pushedStages - pathsBefore.pushedStages >= hits, "recipe hits over a moved buffer pushed the buffer addresses of " + std::to_string(paths.pushedStages - pathsBefore.pushedStages) + " stages for " + std::to_string(hits) + " hits"); if (AgcDriver::Graphics::PushedBufferRecordCap() == 0u) Require(paths.overflowStages - pathsBefore.overflowStages >= hits, "recipe hits whose buffers all overflow the push data wrote the overflow block of " + std::to_string(paths.overflowStages - pathsBefore.overflowStages) + " stages for " + std::to_string(hits) + " hits"); - } else { - Require(paths.pushedStages == pathsBefore.pushedStages, "a stage pushed its buffer addresses although the device reads guest buffers through heap descriptors"); } } BufferMemory[Moved] = BufferAlpha; diff --git a/core/shader/recompiler/CacheKey.hpp b/core/shader/recompiler/CacheKey.hpp index 3943c286e0e4..d2b8d60607f3 100644 --- a/core/shader/recompiler/CacheKey.hpp +++ b/core/shader/recompiler/CacheKey.hpp @@ -386,8 +386,6 @@ class RecompileCacheKey { append(key, value.gpuResolvedImages); append(key, value.descriptorMemory); append(key, value.heapDataUniformDwords); - append(key, value.heapBufferDescriptors); - append(key, value.pushedBufferAddresses); append(key, value.uniformConstantBuffers); append(key, value.ldsLockFences); append(key, value.meshWindowBuffer); diff --git a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp index 916bf2b7704b..1b9c51470014 100644 --- a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp +++ b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp @@ -916,7 +916,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const std::string buffer; Writer writer(buffer); writer.WriteU32(0x41505335u); - writer.WriteU32(58u); + writer.WriteU32(59u); writeShaderBinary(writer, request.shader); writeGuestContext(writer, request.context); writeSpirvTarget(writer, request.target); @@ -972,8 +972,6 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const writer.WriteBool(request.target.deviceScopeLdsMemoryBarriers); writer.WriteBool(request.target.exactRobustLoads); writer.WriteBool(request.target.robustBufferAccess2); - writer.WriteBool(request.target.heapBufferDescriptors); - writer.WriteBool(request.target.pushedBufferAddresses); writer.WriteBool(request.target.uniformConstantBuffers); return base64Encode(buffer); } @@ -983,7 +981,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const Reader reader(decoded); if (reader.ReadU32() != 0x41505335u) throw std::runtime_error("invalid recompile request signature"); const auto version = reader.ReadU32(); - if (version < 1u || version > 58u || version == 50u) throw std::runtime_error("unsupported recompile request serialization version"); + if (version < 1u || version > 59u || version == 50u) throw std::runtime_error("unsupported recompile request serialization version"); DeserializedRequest result{}; result.request.shader = readShaderBinary(reader, result.shaderCode, result.shaderHeader); result.request.context = readGuestContext(reader, result, version); @@ -1060,9 +1058,9 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const result.request.target.deviceScopeLdsMemoryBarriers = reader.ReadBool(); result.request.target.exactRobustLoads = reader.ReadBool(); result.request.target.robustBufferAccess2 = reader.ReadBool(); - result.request.target.heapBufferDescriptors = reader.ReadBool(); + if (version < 59u) reader.ReadBool(); } - if (version >= 57u) result.request.target.pushedBufferAddresses = reader.ReadBool(); + if (version >= 57u && version < 59u) reader.ReadBool(); if (version >= 58u) result.request.target.uniformConstantBuffers = reader.ReadBool(); if (version >= 21u && reader.Remaining() != 0u) throw std::runtime_error("RequestSerializer: unexpected trailing data"); return result; diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp index c67f2168ae20..40215a9ce071 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp @@ -49,7 +49,6 @@ struct IrBindingLayout { std::uint32_t samplerSlotDwords = 0; std::uint32_t imageSlotDwords = 0; std::uint32_t bufferAddressDwords = 0; - bool pushedBuffers = false; std::vector pushedData; bool gpuResolvedImages = false; bool heapStorageImages = false; diff --git a/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp b/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp index 5170e981edef..0710b88619b9 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/BindingAllocator.hpp @@ -27,7 +27,6 @@ struct AllocationOptions { bool stencilReplay = false; bool gpuResolvedImages = false; bool descriptorMemory = false; - bool pushedBufferAddresses = false; }; class BindingAllocator { diff --git a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp index 1cfcabe1a47c..6a1ad6b729b2 100644 --- a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp +++ b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp @@ -81,7 +81,7 @@ bool usesGds(const IrProgram& program) { } BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const BindingLayout& layout, const AllocationOptions& options) const { - const auto [registrationModules, stencilReplay, gpuResolvedImages, descriptorMemory, pushedBufferAddresses] = options; + const auto [registrationModules, stencilReplay, gpuResolvedImages, descriptorMemory] = options; IrProgramMetadata& metadata = program.Metadata(); if (!metadata.shaderInfoComplete || metadata.bindingLayoutComplete) { fail(metadata.shaderInfoComplete ? "shader binding layout failed: binding layout already allocated" @@ -178,7 +178,6 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin } } if (descriptorMemory && gpuResolvedImages) next.bufferAddressDwords = static_cast(info.buffers.size()) * RuntimeAbi::BufferAddressWords; - next.pushedBuffers = pushedBufferAddresses && next.bufferAddressDwords != 0u; if (next.UsesDataAddress()) placePushedData(next); std::vector samplers; diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 1da5ef1f8119..7ad08738c5fb 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -729,7 +729,7 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) bool registration = request.target.registrationModules && (request.shader.stage == ShaderStage::Fragment || heapVertex); program.Metadata().bindingLayoutComplete = false; const bool stencilReplay = request.shader.stage == ShaderStage::Fragment && std::ranges::any_of(program.Info().outputs, [](const StageOutput& output) { return output.kind == StageOutputKind::StencilRef; }) && std::ranges::find(request.target.supportedCapabilities, static_cast(spv::CapabilityStencilExportEXT)) == request.target.supportedCapabilities.end(); - AllocationOptions allocation {.registrationModules = registration, .stencilReplay = stencilReplay, .gpuResolvedImages = request.target.gpuResolvedImages, .descriptorMemory = request.target.descriptorMemory, .pushedBufferAddresses = request.target.descriptorMemory && request.target.pushedBufferAddresses}; + AllocationOptions allocation {.registrationModules = registration, .stencilReplay = stencilReplay, .gpuResolvedImages = request.target.gpuResolvedImages, .descriptorMemory = request.target.descriptorMemory}; auto bindings = bindingAllocator.Allocate(program, request.layout, allocation); SpirvTargetOptions targetOptions {}; @@ -793,7 +793,6 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) targetOptions.gpuResolvedImages = allocation.gpuResolvedImages; targetOptions.heapDataUniformDwords = request.target.heapDataUniformDwords; targetOptions.uniformConstantBuffers = request.target.uniformConstantBuffers; - targetOptions.heapBufferDescriptors = request.target.descriptorMemory && request.target.heapBufferDescriptors; targetOptions.ldsLockFences = request.target.ldsLockFences; targetOptions.meshWindowBuffer = request.target.meshWindowBuffer; targetOptions.float16WidenNans = request.target.float16WidenNans; @@ -831,7 +830,7 @@ CompiledVariant emitVariant(const RecompileRequest& request, IrProgram& program) result.samplerSlotDword = result.gpuResolvedImages ? bindings.layout.SamplerSlotDword() : 0u; result.bufferAddressDword = bindings.layout.bufferAddressDwords != 0u ? bindings.layout.BufferAddressDword() : 0u; result.bufferAddressCount = bindings.layout.bufferAddressDwords / RuntimeAbi::BufferAddressWords; - result.pushedBufferCount = bindings.layout.pushedBuffers ? result.bufferAddressCount : 0u; + result.pushedBufferCount = result.bufferAddressCount; result.dataAddressPush = bindings.layout.UsesDataAddress(); result.pushedData = bindings.layout.pushedData; result.bdaStores = emitted.bdaStores; diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 9225e3059794..c45a8390d9fe 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -367,8 +367,6 @@ struct SpirvTarget { bool gpuResolvedImages = false; bool descriptorMemory = false; std::uint32_t heapDataUniformDwords = 0; - bool heapBufferDescriptors = false; - bool pushedBufferAddresses = false; bool uniformConstantBuffers = false; bool ldsLockFences = false; bool fragmentBarycentricBuiltins = false; diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index 7390b80cbcf0..2c03f037b0c6 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -774,7 +774,6 @@ void encodeLayout(Writer& writer, const IrBindingLayout& layout) { writer.Value(layout.samplerSlotDwords); writer.Value(layout.imageSlotDwords); writer.Value(layout.bufferAddressDwords); - writer.Value(layout.pushedBuffers); writer.Values(std::span(layout.pushedData)); writer.Value(layout.heapStorageImages); writer.Value(layout.gpuResolvedImages); @@ -797,7 +796,6 @@ void decodeLayout(Reader& reader, IrBindingLayout& layout) { reader.Value(layout.samplerSlotDwords); reader.Value(layout.imageSlotDwords); reader.Value(layout.bufferAddressDwords); - reader.Value(layout.pushedBuffers); reader.Values(layout.pushedData); reader.Value(layout.heapStorageImages); reader.Value(layout.gpuResolvedImages); diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index e45e69d31688..d9798e5a9413 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -13,7 +13,7 @@ namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 65; +inline constexpr std::uint32_t FormatVersion = 66; enum class LoadStatus { Loaded, diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp index ad61cd013aad..8ddb6106c04b 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp @@ -47,7 +47,6 @@ struct SpirvTargetOptions { bool gpuResolvedImages = false; std::uint32_t heapDataUniformDwords = 0; bool uniformConstantBuffers = false; - bool heapBufferDescriptors = false; bool ldsLockFences = false; bool meshWindowBuffer = false; bool float16WidenNans = false; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index aa70184a2ab5..a4f712db0fe5 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -121,7 +121,6 @@ struct SpirvEmitterState { bool gpuResolvedImages = false; std::uint32_t heapDataUniformDwords = 0; bool uniformConstantBuffers = false; - bool heapBufferDescriptors = false; bool addressedBuffers = false; std::vector pushedBufferVariables; std::vector pushedBufferCoherentVariables; @@ -248,7 +247,6 @@ struct SpirvEmitterState { std::unordered_map heapSlotVariables; std::uint32_t flattenedSrtVariable = 0; bool flattenedSrtAddressed = false; - bool flattenedSrtPushed = false; std::uint32_t ldsVariable = 0; std::uint32_t ldsBufferVariable = 0; std::uint32_t ldsBufferU64Variable = 0; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp index 1473ce37b1fb..26393f82dec6 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp @@ -283,7 +283,6 @@ std::vector SpirvEmitter::Emit(const IrProgram& program, const Sh state.gpuResolvedImages = target.gpuResolvedImages; state.heapDataUniformDwords = target.heapDataUniformDwords; state.uniformConstantBuffers = target.uniformConstantBuffers; - state.heapBufferDescriptors = target.heapBufferDescriptors && !program.Metadata().bindings.pushedBuffers; state.fragmentDescriptorSet = target.fragmentDescriptorSet; state.meshBarycentricPixel = target.meshBarycentricPixel; state.meshBarycentricVertex = target.meshBarycentricVertex; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 6c0d198dab6b..9915df597c44 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -67,7 +67,7 @@ std::uint32_t overflowDword(SpirvEmitterState& state, std::uint32_t buffer, std: } std::uint32_t EmitBufferRootDword(SpirvEmitterState& state, std::uint32_t buffer, std::uint32_t word) { - if (!state.program.Metadata().bindings.pushedBuffers) FailEmit("only a stage with pushed buffer addresses reads the buffer root"); + if (state.program.Metadata().bindings.bufferAddressDwords == 0u) FailEmit("only a stage with pushed buffer addresses reads the buffer root"); if (word >= RuntimeAbi::PushedBufferWords) FailEmit("a pushed buffer record has no such word"); if (buffer >= RuntimeAbi::PushedBufferLimit) return overflowDword(state, buffer, word); const auto u32 = TypeU32(state); @@ -204,17 +204,11 @@ std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index } if (state.flattenedSrtVariable == 0) FailEmit("the flattened SRT descriptor is missing"); const auto u32 = TypeU32(state); - std::uint32_t inBounds = 0; - if (state.flattenedSrtPushed) { - const auto dwords = EmitRootItemDword(state, RuntimeAbi::RootItem::SrtDwords, 0u); - inBounds = Binary(state, spv::OpULessThan, TypeBool(state), index, dwords); - index = Select(state, u32, inBounds, index, ConstantU32(state, 0u)); - } const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.flattenedSrtVariable, ConstantU32(state, 0u), index); const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, u32, value, pointer); - return inBounds != 0 ? Select(state, u32, inBounds, value, ConstantU32(state, 0u)) : value; + return value; } std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dwordIndex) { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index 8db7b49b433a..2cf7464e229d 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -510,9 +510,8 @@ void DefineDescriptors(SpirvEmitterState& state) { }; switch (binding.kind) { case DescriptorBindingKind::Buffers: { - if (layout.bufferAddressDwords != 0u && !state.heapBufferDescriptors) { + if (layout.bufferAddressDwords != 0u) { state.addressedBuffers = true; - if (!layout.pushedBuffers) break; const auto count = layout.bufferAddressDwords / RuntimeAbi::BufferAddressWords; const auto pushedBuffer = [&](std::uint32_t type, std::uint32_t element, const char* name) { const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassStorageBuffer, type), spv::StorageClassStorageBuffer); @@ -628,12 +627,10 @@ void DefineDescriptors(SpirvEmitterState& state) { } break; case DescriptorBindingKind::FlattenedSrt: - if (layout.UsesDataAddress() && !state.heapBufferDescriptors) state.flattenedSrtAddressed = true; + if (layout.UsesDataAddress()) state.flattenedSrtAddressed = true; else { state.flattenedSrtVariable = Define(StorageBufferBlockType(state), "flattened_srt"); - state.flattenedSrtPushed = layout.UsesDataAddress(); - if (state.flattenedSrtPushed) state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::SrtAddress); - else state.module.AddAnnotation(spv::OpDecorate, state.flattenedSrtVariable, spv::DecorationNonWritable); + state.module.AddAnnotation(spv::OpDecorate, state.flattenedSrtVariable, spv::DecorationNonWritable); } break; case DescriptorBindingKind::Samplers: diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index 4745d41af742..191b2dfee7a3 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -232,46 +232,26 @@ MemoryResourceAccess directAccess(SpirvValueEmitContext& context, const IrValue& const auto& memory = context.Memory(instruction); if (state.addressedBuffers) { const auto element = ResourceForDescriptor(state, DescriptorBindingKind::Buffers, memory.resource); - const auto dword = state.program.Metadata().bindings.BufferAddressDword() + element * RuntimeAbi::BufferAddressWords; - const bool pushed = state.program.Metadata().bindings.pushedBuffers; - const auto word = [&](std::uint32_t index) { return pushed ? EmitBufferRootDword(state, element, index) : EmitShaderDataDwordLoad(state, dword + index); }; - if (pushed) { - if (element >= state.pushedBufferVariables.size()) context.Fail(instruction, "a pushed buffer has no storage buffer variable"); - if (state.pushedBufferUniformVariables[element] != 0u) { - if (instruction.Opcode() != IrOpcode::ReadConstBuffer || wide) context.Fail(instruction, "a pushed constant buffer is read by an access other than a scalar load"); - MemoryResourceAccess access; - access.kind = memory.kind; - access.objectPointer = state.pushedBufferUniformVariables[element]; - access.softwareBounds = true; - access.uniform = true; - access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), word(2u), ConstantU32(state, 2u)); - access.byteOffset = state.memoryByteOffsets.at(element); - return access; - } - const auto variable = wide ? state.pushedBufferU64Variables[element] : plainLoad || state.pushedBufferCoherentVariables[element] == 0u ? state.pushedBufferVariables[element] : state.pushedBufferCoherentVariables[element]; - if (variable == 0u) context.Fail(instruction, "a pushed buffer lacks the view this access needs"); + const auto word = [&](std::uint32_t index) { return EmitBufferRootDword(state, element, index); }; + if (element >= state.pushedBufferVariables.size()) context.Fail(instruction, "a pushed buffer has no storage buffer variable"); + if (state.pushedBufferUniformVariables[element] != 0u) { + if (instruction.Opcode() != IrOpcode::ReadConstBuffer || wide) context.Fail(instruction, "a pushed constant buffer is read by an access other than a scalar load"); MemoryResourceAccess access; access.kind = memory.kind; - access.objectPointer = variable; + access.objectPointer = state.pushedBufferUniformVariables[element]; access.softwareBounds = true; - access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), word(2u), ConstantU32(state, wide ? 3u : 2u)); + access.uniform = true; + access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), word(2u), ConstantU32(state, 2u)); access.byteOffset = state.memoryByteOffsets.at(element); - access.memoryAccess = memory.coherent ? spv::MemoryAccessVolatileMask : 0u; return access; } - const auto u64 = TypeScalarU64(state); - auto address = ComposeAddress64(state, [&] { return word(0u); }, [&] { return word(1u); }); + const auto variable = wide ? state.pushedBufferU64Variables[element] : plainLoad || state.pushedBufferCoherentVariables[element] == 0u ? state.pushedBufferVariables[element] : state.pushedBufferCoherentVariables[element]; + if (variable == 0u) context.Fail(instruction, "a pushed buffer lacks the view this access needs"); MemoryResourceAccess access; access.kind = memory.kind; - access.physical = true; + access.objectPointer = variable; + access.softwareBounds = true; access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), word(2u), ConstantU32(state, wide ? 3u : 2u)); - if (state.program.Metadata().bindings.UsesDataAddress()) { - const auto empty = Binary(state, spv::OpIEqual, TypeBool(state), access.length, ConstantU32(state, 0u)); - address = Select(state, u64, empty, EmitRootAddress(state, RuntimeAbi::RootItem::ShaderData), address); - access.clampedPhysical = true; - } - access.objectPointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpConvertUToPtr, readOnly ? TypePhysicalReadOnlyBufferPointer(state, wide) : TypePhysicalBufferPointer(state, wide), access.objectPointer, address); access.byteOffset = state.memoryByteOffsets.at(element); access.memoryAccess = memory.coherent ? spv::MemoryAccessVolatileMask : 0u; return access; diff --git a/core/shader/recompiler/tests/RequestSerializerTests.cpp b/core/shader/recompiler/tests/RequestSerializerTests.cpp index 771c3bd732e3..195f28a49113 100644 --- a/core/shader/recompiler/tests/RequestSerializerTests.cpp +++ b/core/shader/recompiler/tests/RequestSerializerTests.cpp @@ -180,16 +180,16 @@ std::string EncodeBase64(const std::vector& bytes) { return text; } std::vector AtVersion55(std::vector bytes) { - Require(bytes.size() > 23u && bytes[4] == 58u && std::all_of(bytes.end() - 15, bytes.end(), [](std::uint8_t value) { return value == 0u; })); - bytes.resize(bytes.size() - 15u); + Require(bytes.size() > 23u && bytes[4] == 59u && std::all_of(bytes.end() - 13, bytes.end(), [](std::uint8_t value) { return value == 0u; })); + bytes.resize(bytes.size() - 13u); bytes[4] = 55u; return bytes; } std::string EncodeAtWriterVersion(std::vector bytes) { Require(bytes.size() > 8u && bytes[4] == 55u); - bytes[4] = 58u; - bytes.insert(bytes.end(), 15u, 0u); + bytes[4] = 59u; + bytes.insert(bytes.end(), 13u, 0u); return EncodeBase64(bytes); } @@ -212,8 +212,8 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { Require(replay.request.target.heapDataUniformDwords == profile.heapDataUniformDwords); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 58u && bytes.size() > 15u); - bytes.resize(bytes.size() - 15u); + Require(bytes[4] == 59u && bytes.size() > 13u); + bytes.resize(bytes.size() - 13u); for (const std::uint8_t version : {55u, 54u, 53u, 52u}) { if (version == 53u) bytes.resize(bytes.size() - 2u); if (version == 52u) bytes.pop_back(); @@ -222,7 +222,7 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { Require(!older.gpuResolvedImages && !older.descriptorMemory && older.heapDataUniformDwords == 0u); } bytes.push_back(0u); - bytes[4] = 58u; + bytes[4] = 59u; bool truncated = false; try { static_cast(serializer.Deserialize(EncodeBase64(bytes))); @@ -247,48 +247,35 @@ void VerifyHeapProfile(const ShaderRecompiler::RequestSerializer& serializer) { ShaderRecompiler::RecompileRequest addressed = limits; addressed.target.heapDataUniformDwords = 0u; Require(serializer.Serialize(limits) != serializer.Serialize(addressed)); - for (const bool descriptors : {false, true}) { - auto request = limits; - request.target.heapBufferDescriptors = descriptors; - const auto encoded = serializer.Serialize(request); - Require(serializer.Deserialize(encoded).request.target.heapBufferDescriptors == descriptors); - Require((encoded == serializer.Serialize(limits)) == !descriptors); - auto bytes = DecodeBase64(encoded); - bytes.resize(bytes.size() - 15u); - bytes[4] = 55u; - Require(!serializer.Deserialize(EncodeBase64(bytes)).request.target.heapBufferDescriptors); - } } -void VerifyPushedBufferAddresses(const ShaderRecompiler::RequestSerializer& serializer) { - for (const bool pushed : {false, true}) { - for (const bool uniform : {false, true}) { - ShaderRecompiler::RecompileRequest request{}; - request.target.gpuResolvedImages = true; - request.target.descriptorMemory = true; - request.target.heapBufferDescriptors = true; - request.target.pushedBufferAddresses = pushed; - request.target.uniformConstantBuffers = uniform; - const auto encoded = serializer.Serialize(request); - const auto replay = serializer.Deserialize(encoded).request.target; - Require(replay.pushedBufferAddresses == pushed && replay.uniformConstantBuffers == uniform && serializer.Serialize(serializer.Deserialize(encoded).request) == encoded); - auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 58u && bytes.back() == (uniform ? 1u : 0u) && bytes[bytes.size() - 2u] == (pushed ? 1u : 0u)); - bytes.pop_back(); - bytes[4] = 57u; - const auto version57 = serializer.Deserialize(EncodeBase64(bytes)).request.target; - Require(version57.pushedBufferAddresses == pushed && !version57.uniformConstantBuffers); - bytes.pop_back(); - bytes[4] = 56u; - const auto older = serializer.Deserialize(EncodeBase64(bytes)).request.target; - Require(!older.pushedBufferAddresses && !older.uniformConstantBuffers && older.gpuResolvedImages && older.descriptorMemory && older.heapBufferDescriptors); - } +void VerifyRetiredHeapTargetFields(const ShaderRecompiler::RequestSerializer& serializer) { + for (const bool uniform : {false, true}) { + ShaderRecompiler::RecompileRequest request{}; + request.target.gpuResolvedImages = true; + request.target.descriptorMemory = true; + request.target.uniformConstantBuffers = uniform; + const auto encoded = serializer.Serialize(request); + Require(serializer.Deserialize(encoded).request.target.uniformConstantBuffers == uniform); + auto bytes = DecodeBase64(encoded); + Require(bytes[4] == 59u && bytes.back() == (uniform ? 1u : 0u)); + bytes.insert(bytes.end() - 1, 2u, 1u); + bytes[4] = 58u; + Require(serializer.Serialize(serializer.Deserialize(EncodeBase64(bytes)).request) == encoded); + bytes.pop_back(); + bytes[4] = 57u; + auto plain = request; + plain.target.uniformConstantBuffers = false; + Require(serializer.Serialize(serializer.Deserialize(EncodeBase64(bytes)).request) == serializer.Serialize(plain)); + bytes.pop_back(); + bytes[4] = 56u; + Require(serializer.Serialize(serializer.Deserialize(EncodeBase64(bytes)).request) == serializer.Serialize(plain)); } } void VerifyKeyedTargetFields(const ShaderRecompiler::RequestSerializer& serializer) { using Field = bool ShaderRecompiler::SpirvTarget::*; - constexpr std::array fields{&ShaderRecompiler::SpirvTarget::ldsLockFences, &ShaderRecompiler::SpirvTarget::meshWindowBuffer, &ShaderRecompiler::SpirvTarget::waveLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::deviceScopeLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::exactRobustLoads, &ShaderRecompiler::SpirvTarget::robustBufferAccess2, &ShaderRecompiler::SpirvTarget::pushedBufferAddresses, &ShaderRecompiler::SpirvTarget::uniformConstantBuffers}; + constexpr std::array fields{&ShaderRecompiler::SpirvTarget::ldsLockFences, &ShaderRecompiler::SpirvTarget::meshWindowBuffer, &ShaderRecompiler::SpirvTarget::waveLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::deviceScopeLdsMemoryBarriers, &ShaderRecompiler::SpirvTarget::exactRobustLoads, &ShaderRecompiler::SpirvTarget::robustBufferAccess2, &ShaderRecompiler::SpirvTarget::uniformConstantBuffers}; const ShaderRecompiler::RecompileRequest defaults{}; const auto defaultEncoded = serializer.Serialize(defaults); for (std::size_t chosen = 0; chosen <= fields.size(); ++chosen) { @@ -300,8 +287,8 @@ void VerifyKeyedTargetFields(const ShaderRecompiler::RequestSerializer& serializ for (std::size_t index = 0; index < fields.size(); ++index) Require(replay.request.target.*fields[index] == (chosen == fields.size() || index == chosen)); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 58u && bytes.size() > 15u); - bytes.resize(bytes.size() - 15u); + Require(bytes[4] == 59u && bytes.size() > 13u); + bytes.resize(bytes.size() - 13u); for (const std::uint8_t version : {55u, 54u, 53u, 52u}) { if (version == 53u) bytes.resize(bytes.size() - 2u); if (version == 52u) bytes.pop_back(); @@ -835,7 +822,7 @@ int main() { const auto replay40 = serializer.Deserialize(EncodeBase64(version40)); Require(!replay40.request.target.float32DenormPreserve && replay40.request.target.float32FlushToZero == !preserve); auto future = bytes; - future[4] = 59u; + future[4] = 60u; bool futureRejected = false; try { static_cast(serializer.Deserialize(EncodeBase64(future))); @@ -1194,7 +1181,7 @@ int main() { VerifyHeapProfile(serializer); VerifyKeyedTargetFields(serializer); - VerifyPushedBufferAddresses(serializer); + VerifyRetiredHeapTargetFields(serializer); return 0; } diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index e5cdaae48a9b..c7a342c247dd 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -441,7 +441,6 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_PROFILE_GPU` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records the GPU time of recorded work by key from batch timestamps | | `APS5_PROFILE_GPU_DRAWS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp`, `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | with APS5_PROFILE_GPU, records the GPU time of each recorded draw by its fragment program's variant id and prints a [drawvariant] line with the code address behind each variant id once (draws that do not use a recipe only; the [gputime] line labels each `draw 0x`, the id [drawvariant] prints, and the ranges share the batch's query cap) | | `APS5_PUSHED_BUFFER_RECORDS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 4 | test cap on the guest buffer records a heap stage keeps in its push data; the rest go to its per-draw overflow block | -| `APS5_PUSHED_BUFFERS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 1 | with `APS5_GPU_HEAP`, `1` passes every heap stage's guest buffer addresses and sizes in its push data (four records, the rest in a per-draw overflow block), read as storage buffers mapped to those addresses, and `0` reads them through heap buffer descriptors written per draw | | `APS5_REAP_EACH_PACKET` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/DeferredLabels.cpp` | | reaps deferred labels after every packet | | `APS5_REGISTRATION_PREPARE_COMMIT_GB` | number | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp` | half of physical RAM | stops preparing newly registered shaders ahead of use when process-private memory reaches this GiB budget; `0` disables registration-time preparation | | `APS5_RELEASE_ON_UNLOCK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | destroys deferred batches on the unlocking thread instead of a release thread | @@ -531,7 +530,6 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_TRACE_TEXTURES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | prints a sampled texture's address, dimensions, format, tile mode, and how many of the bytes at offsets 0, 64, 128 and so on are nonzero | | `APS5_TRACE_UNREADABLE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp` | | names the code that checked an inaccessible range | | `APS5_TRACE_UPLOAD` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | names why a storage image is uploaded again | -| `APS5_UNIFORM_CONSTANT_BUFFERS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 1 | with pushed buffers, `1` reads a guest buffer that a heap stage only loads with scalar loads at constant offsets (within 64 KiB) as a uniform buffer, and `0` keeps it a storage buffer; needs `VK_KHR_uniform_buffer_standard_layout` | | `APS5_UNIT_SHADOW_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp` | 1/8 of the device-local heap budget the first context reports, 128-1024 | budget in MiB of the unit shadow's slabs; the default was measured only on a card with a 6.5 GiB device-local budget | | `APS5_UNIT_SHADOW_SLAB_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp` | 8 | size in MiB of one unit-shadow slab | | `APS5_VALIDATE_LEGACY` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WriteEvidence.cpp` | | uses the legacy snapshot and full-compare path for pending-write validation | From 810824f132666bcc8d40d84f2a5be479b3150798 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 8 Nov 2026 17:04:40 +0530 Subject: [PATCH 149/269] refactor(agc): drop the GPU heap's descriptor ring The ring at the end of the resource heap only held the per-draw buffer descriptors the previous commit removed; shader data, flattened SRTs and table maps already live in the data pool. The resource heap now ends at its reserved range, which frees the 16 MiB ring and leaves its room to image slots on devices whose maximum heap size bounded them. - RingAllocate, the ring chunks with their wait, skip and pressure-submit logic, APS5_HEAP_RING_MIB and the ring counters and [gpu-heap] fields are removed. The span peak counter keeps counting data pool spans. - The heap slot tests drop the ring span, large span, pressure, current chunk and busy chunk cases and their two ctest modes. - ARCHITECTURE.md describes the data pool and the pushed buffer records instead of the ring and the shader-data buffer addresses. --- .../Graphics/include/BindlessHeap.hpp | 34 +-- .../Graphics/src/BindlessHeap.cpp | 210 ++---------------- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 2 +- .../tests/BindlessHeapSlots.cpp | 192 +--------------- .../cmake/agc_driver_heap_slots_tests.cmake | 4 - docs/dev/ARCHITECTURE.md | 2 +- docs/dev/ENVIRONMENT.md | 1 - 7 files changed, 27 insertions(+), 418 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 38ccb0369494..9d6db694421c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -91,7 +91,6 @@ class BindlessHeap { VkDeviceAddress address = 0; }; DataSpan Allocate(std::size_t words, SpanMark& mark); - DataSpan RingAllocate(std::size_t words, SpanMark& mark); static void Write(const DataSpan& span, std::span words); bool Held(const SpanMark& mark); class SpanScope { @@ -106,36 +105,26 @@ class BindlessHeap { bool acquired; }; std::optional KeepOrAllocate(std::size_t words, SpanMark& mark, bool same); - static constexpr std::uint32_t BufferSlotBytes = 16u; static constexpr std::uint32_t SamplerKind = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Samplers); void Submitted(Recorder& recorder, std::uint64_t serial); - bool TakeRingPressure(); bool TakeSlotPressure(); struct Counts { - std::uint64_t ringWraps = 0, encodes = 0, encodedCopies = 0; + std::uint64_t encodes = 0, encodedCopies = 0; std::uint64_t slotsFreed = 0, slotsReused = 0, slotsEvicted = 0, evictionWaits = 0; - std::uint64_t ringWaits = 0, ringBatchPeakBytes = 0, ringSpanPeakBytes = 0, ringBytes = 0, imageSlotsHeld = 0; - std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0, keptChunksSkipped = 0, busyChunksSkipped = 0; - std::uint64_t ringPressureSubmits = 0, slotPressureSubmits = 0, samplersEvicted = 0; + std::uint64_t spanPeakBytes = 0, imageSlotsHeld = 0; + std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0; + std::uint64_t slotPressureSubmits = 0, samplersEvicted = 0; std::uint64_t poolBytes = 0, poolBatchPeakBytes = 0, poolBlocksMade = 0, poolBlocksRecycled = 0, poolBlocksFreed = 0, poolBlocksHeld = 0, poolBlockBytes = 0; }; Counts Statistics() const; - std::size_t RingChunkCount() const { return ringChunks.size(); } - static constexpr std::size_t RingBytes = 64u << 20u; - static constexpr std::size_t DefaultRingBytes = 16u << 20u; static constexpr std::size_t PoolBlockBytes = 2u << 20u; static constexpr std::size_t PoolIdleBytes = 32u << 20u; - static constexpr std::size_t RingChunkBytes = 2u << 20u; private: Context context; - std::byte* ringData = nullptr; - std::size_t ringBytes = 0; - VkDeviceSize ringHeapOffset = 0; - bool ringInHeap = false; std::unique_ptr resourceHeap; std::unique_ptr samplerHeap; VkDeviceSize imageHeapStride = 0; @@ -150,18 +139,6 @@ class BindlessHeap { void writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImageView view, VkImageLayout layout); void writeSamplerSlot(std::uint32_t slot, VkSampler sampler); void writeBufferDescriptor(VkDeviceSize offset, VkDeviceAddress address, VkDeviceSize bytes, const char* what); - struct Chunk { - Recorder* recorder = nullptr; - std::uint64_t serial = 0; - bool open = false; - std::uint64_t entered = 0; - }; - std::vector ringChunks; - std::uint64_t ringEntries = 0; - std::size_t ringChunk = ~std::size_t{0}; - void enterRingChunk(std::size_t index); - std::size_t wrapRingOffset(std::size_t offset, std::size_t bytes); - std::size_t ringCursor = 0; struct PoolBlock { std::unique_ptr buffer; std::byte* data = nullptr; @@ -182,7 +159,6 @@ class BindlessHeap { DataSpan allocateLocked(std::size_t words, SpanMark& mark); bool poolBlockDoneLocked(PoolBlock& block); void trimPoolLocked(); - std::uint32_t ringAlignment = 256; mutable std::mutex mutex; mutable std::mutex spanMutex; mutable std::atomic spanOwner{}; @@ -246,8 +222,6 @@ class BindlessHeap { bool sampler = false; }; std::deque retiring; - std::size_t ringBatchBytes = 0; - std::atomic ringOpenChunks{0}; std::size_t retiringAssigned = 0; std::size_t retiringSamplers = 0; std::size_t samplerRetiringAssigned = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index eaeda9525af8..b56b9b6e8111 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -58,7 +58,7 @@ namespace { namespace Abi = ShaderRecompiler::RuntimeAbi; -constexpr std::size_t RingSpanAlignment = 16u; +constexpr std::size_t SpanAlignment = 16u; bool pipelineStats() { static const bool enabled = std::getenv("APS5_PIPELINE_STATS") != nullptr; @@ -73,13 +73,6 @@ bool isImageKind(std::uint32_t kind) { return kind >= Abi::FirstImageBinding && kind < BindlessHeap::SamplerKind; } -std::size_t chunkOf(std::size_t offset) { - return offset / BindlessHeap::RingChunkBytes; -} - -std::size_t lastChunkOf(std::size_t offset, std::size_t bytes) { - return chunkOf(offset + std::max(bytes, 1u) - 1u); -} std::atomic heapComputeStages{0}; std::atomic descriptorHeapDevice{false}; @@ -184,29 +177,15 @@ struct HeapSizes { VkDeviceSize meshWindowOffset = 0; VkDeviceSize resourceUsed = 0; VkDeviceSize samplerUsed = 0; - VkDeviceSize ringOffset = 0; - std::size_t ringBytes = 0; }; -std::size_t ringTargetBytes() { - static const std::size_t bytes = [] { - std::size_t target = BindlessHeap::DefaultRingBytes; - if (const char* value = std::getenv("APS5_HEAP_RING_MIB")) { - const auto mib = std::strtoull(value, nullptr, 10); - if (mib != 0u) target = static_cast(std::clamp(mib, (2u * BindlessHeap::RingChunkBytes) >> 20u, BindlessHeap::RingBytes >> 20u)) << 20u; - } - return target / BindlessHeap::RingChunkBytes * BindlessHeap::RingChunkBytes; - }(); - return bytes; -} - VkDeviceSize alignUp(VkDeviceSize value, VkDeviceSize alignment) { return alignment == 0 ? value : (value + alignment - 1) / alignment * alignment; } constexpr std::uint32_t MaximumImageSlots = 1u << 19u; -HeapSizes heapLayout(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, std::uint32_t slots, VkDeviceSize uniformAlignment) { +HeapSizes heapLayout(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, std::uint32_t slots) { HeapSizes sizes; sizes.imageSlots = slots; sizes.imageStride = alignUp(properties.imageDescriptorSize, properties.imageDescriptorAlignment); @@ -216,30 +195,23 @@ HeapSizes heapLayout(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properti sizes.meshWindowOffset = alignUp(sizes.pixelLdsOffset + properties.bufferDescriptorSize, properties.bufferDescriptorAlignment); sizes.resourceUsed = alignUp(sizes.meshWindowOffset + properties.bufferDescriptorSize, properties.resourceHeapAlignment); sizes.samplerUsed = alignUp(static_cast(Abi::GpuSamplerHeapSlots) * sizes.samplerStride, properties.samplerHeapAlignment); - const auto offset = alignUp(sizes.resourceUsed + properties.minResourceHeapReservedRange, std::max(uniformAlignment, properties.resourceHeapAlignment)); - if (offset >= properties.maxResourceHeapSize) return sizes; - const auto room = static_cast(properties.maxResourceHeapSize - offset) / BindlessHeap::RingChunkBytes * BindlessHeap::RingChunkBytes; - const auto bytes = std::min(room, ringTargetBytes()); - if (bytes < 2u * BindlessHeap::RingChunkBytes) return sizes; - sizes.ringOffset = offset; - sizes.ringBytes = bytes; return sizes; } VkDeviceSize layoutEnd(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, const HeapSizes& sizes) { - return sizes.ringBytes != 0u ? sizes.ringOffset + sizes.ringBytes : sizes.resourceUsed + properties.minResourceHeapReservedRange; + return sizes.resourceUsed + properties.minResourceHeapReservedRange; } -HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties, VkDeviceSize uniformAlignment) { - const auto base = heapLayout(properties, Abi::GpuImageHeapSlots, uniformAlignment); +HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { + const auto base = heapLayout(properties, Abi::GpuImageHeapSlots); const auto end = layoutEnd(properties, base); if (end >= properties.maxResourceHeapSize || base.imageStride == 0u) return base; auto slots = static_cast(std::min(MaximumImageSlots, Abi::GpuImageHeapSlots + (properties.maxResourceHeapSize - end) / base.imageStride)); while (slots > Abi::GpuImageHeapSlots) { - const auto grown = heapLayout(properties, slots, uniformAlignment); + const auto grown = heapLayout(properties, slots); const auto grownEnd = layoutEnd(properties, grown); - if (grown.ringBytes == base.ringBytes && grownEnd <= properties.maxResourceHeapSize) return grown; - const auto over = grown.ringBytes == base.ringBytes ? grownEnd - properties.maxResourceHeapSize : static_cast(BindlessHeap::RingChunkBytes); + if (grownEnd <= properties.maxResourceHeapSize) return grown; + const auto over = grownEnd - properties.maxResourceHeapSize; const auto step = static_cast(std::min(slots, over / base.imageStride + 1u)); slots = slots - step > Abi::GpuImageHeapSlots ? slots - step : Abi::GpuImageHeapSlots; } @@ -249,7 +221,7 @@ HeapSizes heapSizes(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& propertie } bool BindlessHeap::Fits(const VkPhysicalDeviceDescriptorHeapPropertiesEXT& properties) { - const auto sizes = heapLayout(properties, Abi::GpuImageHeapSlots, 0u); + const auto sizes = heapLayout(properties, Abi::GpuImageHeapSlots); const bool resourcesFit = sizes.resourceUsed + properties.minResourceHeapReservedRange <= properties.maxResourceHeapSize; const bool samplersFit = sizes.samplerUsed + properties.minSamplerHeapReservedRangeWithEmbedded <= properties.maxSamplerHeapSize; return resourcesFit && samplersFit; @@ -274,7 +246,7 @@ std::atomic deviceImageSlots{Abi::GpuImageHeapSlots}; BindlessHeap::BindlessHeap(const Context& context) : context(context) { Require(context.descriptorHeap, "the GPU heap needs VK_EXT_descriptor_heap"); const auto& heapProperties = context.descriptorHeapProperties; - const auto sizes = heapSizes(heapProperties, context.limits.minUniformBufferOffsetAlignment); + const auto sizes = heapSizes(heapProperties); imageHeapStride = sizes.imageStride; samplerHeapStride = sizes.samplerStride; resourceHeapUsed = sizes.resourceUsed; @@ -290,27 +262,13 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { } return std::make_unique(context, bytes, usage); }; - constexpr VkBufferUsageFlags ringUsage = - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; constexpr VkBufferUsageFlags heapUsage = VK_BUFFER_USAGE_DESCRIPTOR_HEAP_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - ringInHeap = sizes.ringBytes != 0u; - const auto resourceBytes = ringInHeap ? static_cast(sizes.ringOffset) + sizes.ringBytes - : static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange); - resourceHeap = makeBuffer(resourceBytes, ringInHeap ? heapUsage | ringUsage : heapUsage); + resourceHeap = makeBuffer(static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange), heapUsage); samplerHeap = makeBuffer(static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage); std::fill(resourceHeap->Bytes().begin(), resourceHeap->Bytes().end(), std::byte{0}); std::fill(samplerHeap->Bytes().begin(), samplerHeap->Bytes().end(), std::byte{0}); - if (ringInHeap) { - ringHeapOffset = sizes.ringOffset; - ringBytes = sizes.ringBytes; - ringData = resourceHeap->Bytes().data() + ringHeapOffset; - writeResourceDescriptors = context.Function("vkWriteResourceDescriptorsEXT"); - } else { - ringBytes = 0; - } - ringAlignment = static_cast(std::max(BufferSlotBytes, heapProperties.bufferDescriptorAlignment)); - poolAlignment = static_cast(std::max({context.limits.minStorageBufferOffsetAlignment, context.limits.minUniformBufferOffsetAlignment, RingSpanAlignment})); - ringChunks.resize(ringBytes / RingChunkBytes); + writeResourceDescriptors = context.Function("vkWriteResourceDescriptorsEXT"); + poolAlignment = static_cast(std::max({context.limits.minStorageBufferOffsetAlignment, context.limits.minUniformBufferOffsetAlignment, SpanAlignment})); slotCap = configuredSlotCap(sizes.imageSlots); deviceImageSlots.store(slotCap, std::memory_order_relaxed); slotUses = std::make_unique[]>(slotCap); @@ -784,20 +742,7 @@ bool BindlessHeap::heldLocked(const SpanMark& mark) { ++counts.spansKept; return true; } - const auto first = chunkOf(mark.offset); - const auto last = lastChunkOf(mark.offset, static_cast(mark.words) * sizeof(std::uint32_t)); - for (auto chunk = first; chunk <= last; ++chunk) { - if (ringChunks[chunk].entered > mark.entry) { - ++counts.spansExpired; - return false; - } - } - for (auto chunk = first; chunk <= last; ++chunk) { - if (!ringChunks[chunk].open) ringOpenChunks.fetch_add(1u, std::memory_order_relaxed); - ringChunks[chunk].open = true; - } - ++counts.spansKept; - return true; + return false; } void BindlessHeap::Write(const DataSpan& span, std::span words) { @@ -825,7 +770,7 @@ std::optional BindlessHeap::KeepOrAllocate(std::size_t w } BindlessHeap::DataSpan BindlessHeap::allocateLocked(std::size_t words, SpanMark& mark) { - const auto bytes = alignUp(std::max(words, 1u) * sizeof(std::uint32_t), RingSpanAlignment); + const auto bytes = alignUp(std::max(words, 1u) * sizeof(std::uint32_t), SpanAlignment); if (poolCurrent >= poolBlocks.size() || alignUp(poolBlocks[poolCurrent].cursor, poolAlignment) + bytes > poolBlocks[poolCurrent].bytes) poolCurrent = takePoolBlockLocked(bytes); auto& block = poolBlocks[poolCurrent]; const auto offset = static_cast(alignUp(block.cursor, poolAlignment)); @@ -833,7 +778,7 @@ BindlessHeap::DataSpan BindlessHeap::allocateLocked(std::size_t words, SpanMark& block.open = true; ++counts.spansWritten; counts.poolBytes += bytes; - counts.ringSpanPeakBytes = std::max(counts.ringSpanPeakBytes, bytes); + counts.spanPeakBytes = std::max(counts.spanPeakBytes, bytes); poolBatchBytes += bytes; mark = {static_cast(offset), static_cast(words), block.generation, static_cast(poolCurrent + 1u), block.address + offset}; return {static_cast(offset), std::span(reinterpret_cast(block.data + offset), words), mark.address}; @@ -921,13 +866,6 @@ bool BindlessHeap::TakeSlotPressure() { return true; } -bool BindlessHeap::TakeRingPressure() { - if (ringChunks.empty() || ringOpenChunks.load(std::memory_order_relaxed) < std::max(2u, ringChunks.size() / 2u)) return false; - SpanScope scope(*this); - ++counts.ringPressureSubmits; - return true; -} - std::pair BindlessHeap::DataLocation(VkDeviceAddress address) const { SpanScope scope(*this); for (const auto& block : poolBlocks) { @@ -936,95 +874,6 @@ std::pair BindlessHeap::DataLocation(VkDeviceAddress add throw std::runtime_error("AGC bindless heap: shader data lies outside every data pool block"); } -BindlessHeap::DataSpan BindlessHeap::RingAllocate(std::size_t words, SpanMark& mark) { - Require(ringInHeap, "the GPU heap has no descriptor ring"); - const auto bytes = alignUp(words * sizeof(std::uint32_t), RingSpanAlignment); - if (bytes > ringBytes / 4u) throw std::runtime_error("AGC bindless heap: one draw's buffer descriptors exceed a quarter of the descriptor ring"); - SpanScope scope(*this); - auto offset = wrapRingOffset(alignUp(ringCursor, ringAlignment), bytes); - enum class Taken { No, Kept, Busy }; - const auto taken = [&](bool skipBusy) { - for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) { - if (chunk == ringChunk ? offset < ringCursor : ringChunks[chunk].open) return Taken::Kept; - } - if (!skipBusy) return Taken::No; - for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) { - auto& entry = ringChunks[chunk]; - if (chunk == ringChunk || entry.serial == 0u || entry.recorder == nullptr) continue; - if (!entry.recorder->WaitSerialFor(entry.serial, 0u)) return Taken::Busy; - entry.serial = 0u; - } - return Taken::No; - }; - const auto start = offset; - const auto wraps = counts.ringWraps; - const auto keptSkips = counts.keptChunksSkipped; - const auto busySkips = counts.busyChunksSkipped; - auto reason = taken(true); - for (std::size_t skipped = 0; reason != Taken::No && skipped < ringChunks.size(); ++skipped) { - offset = wrapRingOffset((chunkOf(offset) + 1u) * RingChunkBytes, bytes); - ++(reason == Taken::Busy ? counts.busyChunksSkipped : counts.keptChunksSkipped); - reason = taken(true); - } - if (reason != Taken::No) { - counts.ringWraps = wraps; - counts.keptChunksSkipped = keptSkips; - counts.busyChunksSkipped = busySkips; - std::optional oldest; - std::uint64_t oldestSerial = ~std::uint64_t{0}; - offset = start; - for (std::size_t step = 0; step < ringChunks.size(); ++step) { - if (taken(false) == Taken::No) { - std::uint64_t serial = 0; - for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) { - if (chunk != ringChunk) serial = std::max(serial, ringChunks[chunk].serial); - } - if (serial < oldestSerial) { - oldest = offset; - oldestSerial = serial; - } - } - offset = wrapRingOffset((chunkOf(offset) + 1u) * RingChunkBytes, bytes); - } - counts.ringWraps = wraps; - if (!oldest) throw std::runtime_error("AGC bindless heap: one batch's buffer descriptors exceed the descriptor ring"); - offset = *oldest; - if (offset < start) ++counts.ringWraps; - } - const auto consumed = bytes + (offset >= ringCursor ? offset - ringCursor : ringBytes - ringCursor + offset); - ringBatchBytes += consumed; - counts.ringBytes += consumed; - ringCursor = offset + bytes; - for (auto chunk = chunkOf(offset); chunk <= lastChunkOf(offset, bytes); ++chunk) enterRingChunk(chunk); - auto* base = reinterpret_cast(ringData + offset); - ++counts.spansWritten; - mark = {static_cast(offset), static_cast(words), ringEntries, 0u, resourceHeap->DeviceAddress() + ringHeapOffset + offset}; - return {static_cast(offset), std::span(base, words), mark.address}; -} - -std::size_t BindlessHeap::wrapRingOffset(std::size_t offset, std::size_t bytes) { - if (offset + bytes <= ringBytes) return offset; - ++counts.ringWraps; - return 0; -} - -void BindlessHeap::enterRingChunk(std::size_t index) { - if (index == ringChunk) return; - ringChunk = index; - auto& chunk = ringChunks[index]; - if (chunk.open) throw std::runtime_error("AGC bindless heap: one batch's buffer descriptors exceed the descriptor ring"); - if (chunk.serial != 0u) { - if (!chunk.recorder->WaitSerialFor(chunk.serial, 0u)) { - chunk.recorder->WaitSerial(chunk.serial); - ++counts.ringWaits; - } - chunk.serial = 0u; - } - chunk.open = true; - ringOpenChunks.fetch_add(1u, std::memory_order_relaxed); - chunk.entered = ++ringEntries; -} - void BindlessHeap::writeSamplerSlot(std::uint32_t slot, VkSampler sampler) { auto record = FindSampler(sampler); Require(record.has_value(), "a GPU heap sampler has no recorded create info"); @@ -1158,7 +1007,6 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& if (std::ranges::find(use.pushedBuffers, binding) == use.pushedBuffers.end()) use.pushedBuffers.push_back(binding); continue; } - const bool stageBinding = binding / bindingCount < Abi::StageCount; const bool heapImageOrSampler = set == Abi::FragmentDescriptorSet && binding >= firstImage && binding <= samplers; if (!heapImageOrSampler) { use.refused = entry; @@ -1486,14 +1334,9 @@ void reportHeapStatistics() { totals.encodedCopies += counts.encodedCopies; totals.slotsEvicted += counts.slotsEvicted; totals.evictionWaits += counts.evictionWaits; - totals.ringWaits += counts.ringWaits; - totals.busyChunksSkipped += counts.busyChunksSkipped; - totals.ringBytes += counts.ringBytes; totals.imageSlotsHeld += counts.imageSlotsHeld; - totals.ringBatchPeakBytes = std::max(totals.ringBatchPeakBytes, counts.ringBatchPeakBytes); - totals.ringSpanPeakBytes = std::max(totals.ringSpanPeakBytes, counts.ringSpanPeakBytes); + totals.spanPeakBytes = std::max(totals.spanPeakBytes, counts.spanPeakBytes); totals.poolBytes += counts.poolBytes; - totals.ringPressureSubmits += counts.ringPressureSubmits; totals.slotPressureSubmits += counts.slotPressureSubmits; totals.samplersEvicted += counts.samplersEvicted; totals.poolBlocksMade += counts.poolBlocksMade; @@ -1512,11 +1355,7 @@ void reportHeapStatistics() { const auto imageCopies = windowDelta(totals.encodedCopies, lastTotals.encodedCopies); const auto slotsEvicted = windowDelta(totals.slotsEvicted, lastTotals.slotsEvicted); const auto evictionWaits = windowDelta(totals.evictionWaits, lastTotals.evictionWaits); - const auto ringWaits = windowDelta(totals.ringWaits, lastTotals.ringWaits); - const auto busySkips = windowDelta(totals.busyChunksSkipped, lastTotals.busyChunksSkipped); - const auto ringMiB = windowDelta(totals.ringBytes, lastTotals.ringBytes) >> 20u; const auto poolMiB = windowDelta(totals.poolBytes, lastTotals.poolBytes) >> 20u; - const auto pressureSubmits = windowDelta(totals.ringPressureSubmits, lastTotals.ringPressureSubmits); const auto slotPressureSubmits = windowDelta(totals.slotPressureSubmits, lastTotals.slotPressureSubmits); const auto samplersEvicted = windowDelta(totals.samplersEvicted, lastTotals.samplersEvicted); const auto poolMade = windowDelta(totals.poolBlocksMade, lastTotals.poolBlocksMade); @@ -1527,10 +1366,10 @@ void reportHeapStatistics() { std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; excluded:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; descriptor ring %llu MiB, %llu waits, %llu busy chunks skipped, %llu early submits, since start at most %llu KiB per batch; image descriptors %llu encoded / %llu copied; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; image descriptors %llu encoded / %llu copied; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), excluded.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.ringSpanPeakBytes >> 10u), printed(ringMiB), printed(ringWaits), printed(busySkips), printed(pressureSubmits), printed(totals.ringBatchPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.spanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { @@ -1700,7 +1539,7 @@ void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { heapBinds.fetch_add(1, std::memory_order_relaxed); heapBindWindow.fetch_add(1, std::memory_order_relaxed); VkBindHeapInfoEXT info{VK_STRUCTURE_TYPE_BIND_HEAP_INFO_EXT}; - info.heapRange = {resourceHeap->DeviceAddress(), ringInHeap ? ringHeapOffset + ringBytes : resourceHeapUsed + context.descriptorHeapProperties.minResourceHeapReservedRange}; + info.heapRange = {resourceHeap->DeviceAddress(), resourceHeapUsed + context.descriptorHeapProperties.minResourceHeapReservedRange}; info.reservedRangeOffset = resourceHeapUsed; info.reservedRangeSize = context.descriptorHeapProperties.minResourceHeapReservedRange; context.Function("vkCmdBindResourceHeapEXT")(commands, &info); @@ -1728,15 +1567,6 @@ void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { noteReleasedLocked(); } SpanScope scope(*this); - counts.ringBatchPeakBytes = std::max(counts.ringBatchPeakBytes, ringBatchBytes); - ringBatchBytes = 0; - for (std::size_t index = 0; index < ringChunks.size(); ++index) { - if (!ringChunks[index].open && index != ringChunk) continue; - ringChunks[index].recorder = &recorder; - ringChunks[index].serial = serial; - ringChunks[index].open = index == ringChunk; - } - ringOpenChunks.store(ringChunk < ringChunks.size() && ringChunks[ringChunk].open ? 1u : 0u, std::memory_order_relaxed); counts.poolBatchPeakBytes = std::max(counts.poolBatchPeakBytes, poolBatchBytes); poolBatchBytes = 0; for (std::size_t index = 0; index < poolBlocks.size(); ++index) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index e66745ca3f46..8421aa7d0ae3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -3298,7 +3298,7 @@ void Recorder::KeepBytes(const void* owner, std::size_t bytes) { void Recorder::BoundDrawBatch() { BoundKeptBytes(); if (open == nullptr || !DescriptorHeapEnabled() || !GuestMemory::GpuMutex().HeldByThisThread()) return; - if (auto* heap = BindlessHeap::Existing(context); heap != nullptr && (heap->TakeRingPressure() || heap->TakeSlotPressure())) Submit(); + if (auto* heap = BindlessHeap::Existing(context); heap != nullptr && heap->TakeSlotPressure()) Submit(); } void Recorder::BoundKeptBytes() { diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 6a8c1001b648..7695c6303132 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -29,11 +29,6 @@ void require(bool condition, const std::string& what) { if (!condition) throw std::runtime_error(what); } -BindlessHeap::DataSpan ringAllocate(BindlessHeap& heap, std::size_t words) { - BindlessHeap::SpanMark mark; - return heap.RingAllocate(words, mark); -} - struct FakeOwner : HeapSlotOwner { FakeOwner() = default; }; @@ -199,102 +194,6 @@ void sharedOwnerRelease(const Context& context, VkImageView view) { "destroying an owner behind another base did not free its slot"); } -void ringSpans(const Context& context) { - BindlessHeap heap(context); - BindlessHeap::SpanMark unwritten; - require(!heap.Held(unwritten), "a span never written is not held"); - BindlessHeap::SpanMark first; - const auto span = heap.RingAllocate(16u, first); - require(first.offset == span.offset && first.words == 16u && heap.Held(first), "a span written in the open chunk is held"); - constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); - BindlessHeap::SpanMark filler; - static_cast(heap.RingAllocate(chunkWords - 1024u, filler)); - BindlessHeap::SpanMark crossing; - static_cast(heap.RingAllocate(4096u, crossing)); - require(heap.Held(crossing), "a span over two chunks is kept"); - require(heap.Held(first), "a span stays held while its batch keeps the chunk open"); - const auto counts = heap.Statistics(); - require(counts.spansWritten == 3u && counts.spansKept == 3u, "three spans written and kept"); - BindlessHeap::SpanMark third; - static_cast(heap.RingAllocate(chunkWords, third)); - Recorder recorder(context, true); - heap.Submitted(recorder, 0u); - require(heap.Held(first), "a span stays held after its batch is submitted while the ring has not come back to its chunk"); - BindlessHeap::SpanMark fill; - const auto untilWrap = [&] { - const auto wraps = heap.Statistics().ringWraps; - BindlessHeap::DataSpan last{}; - while (heap.Statistics().ringWraps == wraps) last = heap.RingAllocate(chunkWords, fill); - return last.offset; - }; - require(untilWrap() == AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips a chunk a later batch still reads kept spans from"); - require(heap.Held(first), "the skipped chunk's kept span is still held"); - require(heap.Statistics().keptChunksSkipped == 1u, "one kept chunk skipped"); - heap.Submitted(recorder, 0u); - require(untilWrap() == 0u && !heap.Held(first) && heap.Statistics().spansExpired == 1u, "a span the ring wrote over has expired"); -} - -bool ringLargeSpans(const Context& context) { - BindlessHeap heap(context); - if (heap.RingChunkCount() < 5u) return false; - constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); - constexpr std::size_t largeWords = chunkWords + 1024u; - BindlessHeap::SpanMark pin; - static_cast(heap.RingAllocate(16u, pin)); - BindlessHeap::SpanMark large; - const auto span = heap.RingAllocate(largeWords, large); - require(span.words.size() == largeWords && heap.Held(large), "a span over two chunks is written and held"); - Recorder recorder(context, true); - BindlessHeap::SpanMark fill; - const auto untilWrap = [&](const BindlessHeap::SpanMark& kept) { - const auto wraps = heap.Statistics().ringWraps; - BindlessHeap::DataSpan last{}; - while (heap.Statistics().ringWraps == wraps) { - heap.Submitted(recorder, 0u); - require(heap.Held(kept), "a kept span stays held while later batches fill the ring"); - last = heap.RingAllocate(chunkWords, fill); - } - return last.offset; - }; - require(untilWrap(large) == 2u * AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips every chunk a kept large span covers"); - require(untilWrap(pin) == AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips only the pinned first chunk"); - require(!heap.Held(large), "a large span expires once the ring writes over one of its later chunks"); - require(heap.Held(pin), "the pinned span outlives the large span"); - bool refused = false; - try { - static_cast(ringAllocate(heap, heap.RingChunkCount() * AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t) / 4u + 1u)); - } catch (const std::runtime_error&) { - refused = true; - } - require(refused, "a span over a quarter of the ring is refused"); - return true; -} - -bool ringPressure(const Context& context) { - BindlessHeap heap(context); - if (heap.RingChunkCount() < 4u) return false; - constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); - Recorder recorder(context, true); - BindlessHeap::SpanMark fill; - require(!heap.TakeRingPressure(), "an empty ring is under no pressure"); - const auto half = heap.RingChunkCount() / 2u; - for (std::size_t chunk = 1; chunk < half; ++chunk) static_cast(heap.RingAllocate(chunkWords, fill)); - require(!heap.TakeRingPressure(), "a batch below half the ring's chunks is under no pressure"); - static_cast(heap.RingAllocate(chunkWords, fill)); - require(heap.TakeRingPressure() && heap.Statistics().ringPressureSubmits == 1u, "a batch holding half the ring's chunks asks for a submit"); - heap.Submitted(recorder, 0u); - require(!heap.TakeRingPressure(), "a submit relieves the pressure"); - BindlessHeap::SpanMark kept; - static_cast(heap.RingAllocate(16u, kept)); - for (std::size_t chunk = 1; chunk < half; ++chunk) { - heap.Submitted(recorder, 0u); - static_cast(heap.RingAllocate(chunkWords, fill)); - } - heap.Submitted(recorder, 0u); - require(heap.Held(kept) && !heap.TakeRingPressure(), "chunks of earlier batches do not count"); - return true; -} - void writeTails(const Context& context) { BindlessHeap heap(context); for (const std::size_t count : {0u, 1u, 3u, 4u, 5u, 7u, 9u}) { @@ -334,56 +233,6 @@ void spanScope(const Context& context) { require(heap.Statistics().spansWritten == 2u, "both spans are counted"); } -void ringCurrentChunk(const Context& context) { - BindlessHeap heap(context); - constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); - Recorder recorder(context, true); - std::vector pins(heap.RingChunkCount() - 1u); - for (auto& pin : pins) { - static_cast(heap.RingAllocate(chunkWords, pin)); - heap.Submitted(recorder, 0u); - for (const auto& kept : pins) { - if (kept.entry != 0u) require(heap.Held(kept), "every pinned chunk stays held"); - } - } - BindlessHeap::SpanMark live; - static_cast(heap.RingAllocate(16u, live)); - bool refused = false; - try { - static_cast(ringAllocate(heap, chunkWords)); - } catch (const std::runtime_error&) { - refused = true; - } - require(refused, "a span never wraps onto the current chunk behind data this batch already wrote"); - require(heap.Held(live), "the current chunk's span is still held"); -} - -bool ringBusyChunks(const Context& context) { - BindlessHeap heap(context); - if (heap.RingChunkCount() < 3u) return false; - Recorder recorder(context, true); - if (!recorder.HasTimeline()) return false; - constexpr std::size_t chunkWords = AgcDriver::Graphics::BindlessHeap::RingChunkBytes / sizeof(std::uint32_t); - const auto unreached = recorder.Submissions() + (1ull << 40u); - BindlessHeap::SpanMark busy; - static_cast(heap.RingAllocate(16u, busy)); - static_cast(ringAllocate(heap, chunkWords)); - heap.Submitted(recorder, unreached); - heap.Submitted(recorder, 0u); - BindlessHeap::SpanMark fill; - const auto wraps = heap.Statistics().ringWraps; - BindlessHeap::DataSpan last{}; - while (heap.Statistics().ringWraps == wraps) { - last = heap.RingAllocate(chunkWords, fill); - heap.Submitted(recorder, 0u); - } - require(last.offset >= AgcDriver::Graphics::BindlessHeap::RingChunkBytes, "the ring skips the chunk a batch still in flight reads"); - const auto counts = heap.Statistics(); - require(counts.busyChunksSkipped >= 1u && counts.ringWaits == 0u, "the busy chunk is skipped without a wait"); - require(heap.Held(busy), "a span in the skipped busy chunk is still held"); - return true; -} - bool dataPool(const Context& context) { Recorder recorder(context, true); if (!recorder.HasTimeline()) return false; @@ -702,9 +551,7 @@ bool samplersEvicted(const Context& context) { int main(int argc, char** argv) { const std::string mode = argc > 1 ? argv[1] : ""; - const bool largeSpans = mode == "ring-large-spans"; - const bool busyChunks = mode == "ring-busy-chunks"; - const bool comesBack = !mode.empty() && !largeSpans && !busyChunks; + const bool comesBack = !mode.empty(); try { SetTestEnvironment("APS5_GPU_HEAP", "1"); SetTestEnvironment("APS5_HEAP_SLOT_CAP", comesBack ? "8" : "1"); @@ -714,36 +561,6 @@ int main(int argc, char** argv) { std::printf("skipped, the device has no VK_EXT_descriptor_heap\n"); return VulkanTestSkipped; } - if (busyChunks) { - bool ran = false; - { - const auto context = device->graphicsContext(); - ran = ringBusyChunks(context); - device->WaitIdle(); - } - device.reset(); - if (!ran) { - std::printf("skipped, the heap ring has fewer than three chunks or the recorder no timeline\n"); - return VulkanTestSkipped; - } - std::cout << "bindless heap ring busy chunk tests passed\n"; - return 0; - } - if (largeSpans) { - bool ran = false; - { - const auto context = device->graphicsContext(); - ran = ringLargeSpans(context); - device->WaitIdle(); - } - device.reset(); - if (!ran) { - std::printf("skipped, the heap ring has fewer than five chunks\n"); - return VulkanTestSkipped; - } - std::cout << "bindless heap ring large span tests passed\n"; - return 0; - } if (comesBack) { { const auto context = device->graphicsContext(); @@ -780,16 +597,9 @@ int main(int argc, char** argv) { const PlaceholderImages placeholders(context); textureSlots(context, placeholders.View(Abi::FirstImageBinding)); samplerSlots(context); - if (!ringPressure(context)) std::printf("the ring pressure test needs at least four chunks\n"); if (!dataPool(context)) std::printf("the data pool tests need the recorder timeline\n"); spanScope(context); writeTails(context); - if (BindlessHeap(context).RingChunkCount() != 0u) { - ringSpans(context); - ringCurrentChunk(context); - } else { - std::printf("the device's resource heap holds no descriptor ring\n"); - } viewSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); encodedViews(context); ownerSlots(context, placeholders.View(Abi::FirstStorageImageBinding)); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake index dd23c75b8c2c..1d23196afc8e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_slots_tests.cmake @@ -20,10 +20,6 @@ configure_windows_unwind(agc_driver_heap_slots_tests) if(BUILD_TESTING) agc_add_default_test(agc_driver_heap_slots_tests) - agc_add_env_test(agc_driver_heap_slots_ring_large_spans agc_driver_heap_slots_tests - ARGS ring-large-spans ENV ANYPS5_NO_SHADER_CACHE=1) - agc_add_env_test(agc_driver_heap_slots_ring_busy_chunks agc_driver_heap_slots_tests - ARGS ring-busy-chunks ENV ANYPS5_NO_SHADER_CACHE=1 TIMEOUT 60) foreach(agcHeapSlotsMode IN ITEMS comes-back storage-comes-back storage-views-come-back mixed-comes-back views-come-back two-heaps-come-back owner-views-release shared-owner-release idle-slots-evicted pressure-submit samplers-evicted no-timeline-fails) string(REPLACE "-" "_" agcHeapSlotsName "${agcHeapSlotsMode}") agc_add_env_test(agc_driver_heap_slots_${agcHeapSlotsName} agc_driver_heap_slots_tests diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index bdac99b15cb7..791fc4068c84 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -148,7 +148,7 @@ flowchart LR - Queue 0's packet worker decodes, captures and prepares a draw and hands its recording (`Graphics::Draw` under the GPU lock) to a committer thread in [`DrawPipeline.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp), so the next packet is decoded while the previous draw is recorded. Each queued item carries the guest ranges it will write (`DrawWriteRanges`: written buffers and storage images, color targets with their DCC and CMASK, depth and stencil). A later packet that reads or writes one of those ranges, or that the pipeline can't order, drains it first; labels, submission ends, buffer fills and DMA packets are queued as items instead. With `APS5_PIPELINE_DISPATCH=1` (off by default), a `DISPATCH_DIRECT` whose dispatch-cache entry hits with a recipe is queued as an item too, carrying the dispatch's written buffers and storage images (`DispatchWriteRanges`); the capture and the cache lookup stay on the worker and the recipe is recorded on the committer. A dispatch still drains when its lookup misses, when what it reads overlaps a write still pending, when the hit is verified against data or when its writes cannot be ranged (bindless access, GDS, fault buffer). An indirect draw resolved on the CPU (its records read by the worker) drains only when its records or its count overlap a queued write; the records it draws inline drain first, and its last drawn record is queued like a direct draw (`APS5_NO_PIPELINED_INDIRECT=1` drains at every indirect draw). An exception thrown by a commit is rethrown on the worker at its next enqueue or drain, as an inline draw error would be. On by default; `APS5_PIPELINED_DRAWS=0` records every draw inline, and `APS5_EXACT_DRAW_WRITES=0` widens the color and depth ranges to estimates. - A dispatch's resource build runs stage A (binding plan, buffers, descriptor set) without the GPU lock and stage B (image lookups) under it. Between them `VulkanDevice::presync` waits, still without the lock, for recorded work that writes a surface stage B would read on the CPU and for recorded work that writes the DCC keys of an image the dispatch binds (`ShaderResources::PresyncSurfaces`), so the locked `WaitForKeyWriters` finds nothing pending to synchronize with. A key range is waited for only when recorded work writes it, the key-store memo does not give its value (`DccKeyWritersPending`, without the mutex) and the pending stores do not give it either (`DccKeyWriterNeedsSync`, under the mutex, the same test `WaitForKeyWriters` makes before it synchronizes). Stage A's own key scan runs before that wait, and stage B compares it with the keys it reads under the lock as before. `APS5_NO_DCC_PRESYNC=1` leaves the key ranges out; `APS5_NO_PRESYNC=1` disables the whole pre-sync. - `APS5_DRAW_PIPELINE` (any value turns it on, even `0`; off by default, meant with `APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1`) takes more of a draw off the worker. A `DrawFinisher` thread runs the second half of a direct pipelined draw (stage materialization, the draw cache insert and the hand-off to the committer) while the worker reads the next packets; the worker drains it before the next draw's cache lookup, before packets other than register writes and draws, and before guest reads, and finishes in place a draw whose stages may write memory (`ProgramWritesMemory`) or write through the BDA page table. The committer skips the fragment-output validation and storage-image layer scans whose inputs match its last commit (`CommitTrims`), and a resource or storage image proved current keeps its proof for the rest of the collect epoch until `GuestMemory::BreakProofs` (a CPU write, a write-back, a recorded write) moves `ProofSerial`. Color metadata passes go through the pipeline with their write ranges (`PipelinedColorMetadataPassWrites`) instead of draining it. A data-only hit whose shape entry belongs to an older draw replaces that entry in place at the second sight of the same read user words. On Linux the main image's pages get a page table entry, and capture pages are pooled across threads. `APS5_VERIFY_DRAW_PIPELINE=1` runs a full check next to 1 in 64 reused proofs and prints `[epoch-proofs]` counts. -- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 233472 image slots that every image binding kind shares, the first 57 holding each kind's absent descriptor, and 2048 sampler slots, per-draw shader data and flattened SRT in a ring the shaders reach by address) instead of per-draw descriptor sets. Without the extension, or when the device's heaps cannot hold those slots, every stage takes the per-draw path. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; a stage stays GPU-mode only if its compiled module maps onto the heap and every stage of its draw is GPU-mode too; otherwise it is rebuilt on the per-draw path. A draw whose stages come out mixed is rebuilt once with what the first pass learned, and a stage pair that is still mixed takes the per-draw path from then on. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A heap slot holds no reference to its texture, storage image, view or sampler: the owner frees its slots when it is destroyed, and every batch that reads a slot keeps the owner alive through its draw's or dispatch's resources, so a slot is never reused while a batch can still read it. With fewer free image or sampler slots than the margin, stages take the per-draw path until released slots leave twice the margin free. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the heap ring and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap is recompiled on the per-dispatch path. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the heap ring per draw with its address in two more pushed dwords. Tables with image atomics index the heap too. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers by device address (`addressedBuffers`: four shader data words per buffer, 64-bit address and byte size, after the slot words) instead of storage buffer descriptors; a draw whose buffers are snapshotted gets its own copy of the words with the snapshot addresses. +- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 233472 image slots that every image binding kind shares, the first 57 holding each kind's absent descriptor, and 2048 sampler slots, per-draw shader data and flattened SRT in a host-visible data pool the shaders reach by address) instead of per-draw descriptor sets. Without the extension, or when the device's heaps cannot hold those slots, every stage takes the per-draw path. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; a stage stays GPU-mode only if its compiled module maps onto the heap and every stage of its draw is GPU-mode too; otherwise it is rebuilt on the per-draw path. A draw whose stages come out mixed is rebuilt once with what the first pass learned, and a stage pair that is still mixed takes the per-draw path from then on. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A heap slot holds no reference to its texture, storage image, view or sampler: the owner frees its slots when it is destroyed, and every batch that reads a slot keeps the owner alive through its draw's or dispatch's resources, so a slot is never reused while a batch can still read it. With fewer free image or sampler slots than the margin, stages take the per-draw path until released slots leave twice the margin free. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the data pool and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap is recompiled on the per-dispatch path. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the data pool per draw with its address in two more pushed dwords. Tables with image atomics index the heap too. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers through addresses in its push data instead of storage buffer descriptors, like vkd3d-proton's root descriptors: up to four records of 64-bit address and byte size map as storage buffers (or as uniform buffers when every access is a scalar load at a constant offset), the rest go to a per-draw overflow block; a draw whose buffers are snapshotted pushes the snapshot addresses. - The shader registry maps a code address to every header registered for that code, in registration order. Static, graphics and rectangle ABI resolution pick the header at the bound address (or one equal to it, `SameHeader`, which also takes a hull header fused by `sceAgcFuseShaderHalves` (type 3) as the registered back half (type 7) it copies, the fused registers aside; graphics ABI resolution then uses the fused header's shader registers); draws and dispatches pick the program by the stage's binary type (`RegisteredProgram`), and a front entry matching both type 2 and type 4 throws. Within a type the last registration wins; re-registering an identical earlier header makes its snapshot current again without preparing it again, and changed code drops the older headers. - The snapshot is published as pending. `SourceHandleFor`, `InvocationFor` and `ShaderPreparationTransaction::Edit` / `Read` wait for the pending job before reading `PreparedShaders`, and rethrow its failure. `APS5_SYNC_SHADER_PREPARE=1` prepares on the registering thread instead. - `APS5_LAZY_SHADER_PREPARE=1` retains registration validation and decoding but discards the temporary plan without queueing preparation. The snapshot is deferred, not pending; draws and dispatches prepare and cache it on first use. A compute or pixel stage's explicit ABI resolution (`ResolveShaderAbi`) plans the stage with the ABI's state, records the ABI and leaves its preparation to the shader's first use, which prepares it with that state (`PreparedShaders::deferredAbis`), so a shader that never draws or dispatches stays unprepared; a graphics-stage ABI is still prepared when it is resolved. This opt-in mode takes precedence over synchronous registration preparation and trades background CPU/memory use for possible first-use stalls; disk caches and shader output are unchanged. diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index c7a342c247dd..aef822172e05 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -207,7 +207,6 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first | | `APS5_HEAP_WALK_MEMO_MB` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | 256 | MiB each thread's GPU heap walk memo may hold across both its generations before the previous generation and then the oldest walks are dropped (0 keeps them until the 16,384-key cap rotates them out) | | `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a nearly full heap submits the open batch at the next draw or dispatch and evicts the slots that batch no longer uses | -| `APS5_HEAP_RING_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 16 | MiB of the GPU heap's per-draw buffer descriptor ring inside the resource heap, between 4 and 64, in whole 2 MiB chunks and within the device's heap size; one draw's descriptors may take at most a quarter of the ring, and a batch is submitted early once it holds half the ring (shader data lives in a data pool that grows instead) | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | | `APS5_HOOK_LOCKED_WAIT` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | keeps the flush hook's pending-write wait under the GpuMutex | From 94af8cbe39e09019c924c9fdeb435bfffe1cd7fb Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 8 Nov 2026 17:07:34 +0530 Subject: [PATCH 150/269] style(agc): drop the comments added with the pushed buffers --- .../libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp | 2 -- core/shader/recompiler/RuntimeAbi.hpp | 3 --- .../SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp | 6 ------ 3 files changed, 11 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index 90b935f22d57..f12da1804e24 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -315,8 +315,6 @@ struct AddressCopy { }; std::string AddressCopyOverflow(std::vector copies, std::uint64_t limit); -// The start alignment of a guest buffer view and of every copy that stands in for one: storage buffer -// offset alignment, and the uniform one too while pushed buffers may be read as uniform buffers. VkDeviceSize GuestBufferViewAlignment(const VkPhysicalDeviceLimits& limits); class AddressCopyCounters { diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index 4e823239bdc6..0622c8a0e0f2 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -91,9 +91,6 @@ inline constexpr std::uint32_t GpuDataSet = 2u; inline constexpr std::uint32_t GpuGdsSet = 4u; inline constexpr std::uint32_t EmbeddedSamplerSet = 6u; inline constexpr std::uint32_t PushedBufferSet = 7u; -// A pushed buffer read as a uniform buffer: the largest view (maxUniformBufferRange's guaranteed -// minimum) and the most its start may sit below the guest address (minUniformBufferOffsetAlignment -// is at most 256 by the Vulkan limits; NVIDIA reports 64). inline constexpr std::uint32_t UniformConstantBufferBytes = 65536u; inline constexpr std::uint32_t UniformViewAdjustmentLimit = 255u; inline constexpr std::uint32_t NoEmbeddedSampler = ~0u; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index 2cf7464e229d..dad909447bf3 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -521,11 +521,6 @@ void DefineDescriptors(SpirvEmitterState& state) { return variable; }; const bool aliased = state.requirements.coherentBufferAlias || state.requirements.bufferU64View; - // vkd3d-proton's heap mode maps root constant buffers as uniform buffers, which NVIDIA - // reads through its constant path. A guest buffer qualifies when every access is - // a non-coherent scalar load at a constant offset, so its highest word is known here; the - // view's start adjustment (below the uniform offset alignment, at most 63 bytes) and a - // misaligned base's second word are added to that bound. std::vector uniformWords(count, 0u); if (state.uniformConstantBuffers) { std::vector eligible(count, true); @@ -557,7 +552,6 @@ void DefineDescriptors(SpirvEmitterState& state) { } for (std::uint32_t element = 0; element < count; ++element) { if (uniformWords[element] != 0u) { - // A block of dwords (std430 uniform layout, uniformBufferStandardLayout). const auto array = state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4u}}}, TypeU32(state), ConstantU32(state, uniformWords[element])); const auto block = state.module.DecoratedType(spv::OpTypeStruct, {{spv::OpDecorate, {spv::DecorationBlock}}, {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}}, array); const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniform, block), spv::StorageClassUniform); From d943ee902e53ebfbb3369bab1b7aac8dcd5c8627 Mon Sep 17 00:00:00 2001 From: Dean Galvin Date: Mon, 9 Nov 2026 01:18:58 +1300 Subject: [PATCH 151/269] fix(shader): move the disk cache format to 64 Another open pull request (#8939) also sets FormatVersion to 66 for a different cache layout. Two branches changing that line to the same value merge without a conflict, so the second to land would reuse 66 and read the other's cache files as its own. 64 is not set by any open pull request or by main (57), and it is still above every format main has written. Fix-up on top of Raghav314's branch; the pushed-buffer change itself is theirs. --- core/shader/recompiler/ShaderDiskCache.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index d9798e5a9413..22c63c39f82c 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -13,7 +13,7 @@ namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 66; +inline constexpr std::uint32_t FormatVersion = 64; enum class LoadStatus { Loaded, From b385f6bd79e4989382381db9105a0e8dee23a913 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 8 Nov 2026 18:54:18 +0530 Subject: [PATCH 152/269] perf(agc): lay out a GPU heap stage's bindings when its resources are built A heap stage refresh scanned every binding of the draw's resources on each draw to find the ones its stage owns, rebuilt the stage's slot key into a vector just to compare it with the last one, and walked every binding again to find the stage's pushed buffers. The bindings each stage owns and each stage's addressed buffer elements are now listed once, when the resources are built, and a refresh walks only those; the slot key is compared against the kept one while it is walked and rebuilt only on a change, and the stage's spans reuse the heap lock and heap the refresh already holds. This is how vkd3d-proton handles root parameters: it records which parameters are root descriptors and descriptor tables in root_descriptor_raw_va_mask and descriptor_table_mask when the root signature is created, and each draw's d3d12_command_list_update_root_descriptors and update_descriptor_table_offsets walk only those masks. --- .../Graphics/include/BindlessHeap.hpp | 3 +- .../Graphics/include/ShaderResources.hpp | 16 +- .../Graphics/src/BindlessHeap.cpp | 4 +- .../Graphics/src/ShaderResources.cpp | 183 +++++++++++------- .../tests/BindlessHeapSlots.cpp | 2 +- 5 files changed, 127 insertions(+), 81 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 9d6db694421c..5e71d9307a49 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -101,10 +101,11 @@ class BindlessHeap { SpanScope& operator=(const SpanScope&) = delete; private: + friend class BindlessHeap; const BindlessHeap& heap; bool acquired; }; - std::optional KeepOrAllocate(std::size_t words, SpanMark& mark, bool same); + std::optional KeepOrAllocate(const SpanScope& held, std::size_t words, SpanMark& mark, bool same); static constexpr std::uint32_t SamplerKind = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Samplers); void Submitted(Recorder& recorder, std::uint64_t serial); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 25e8f5d48563..5fa6bb46b4f2 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -680,7 +680,7 @@ class ShaderResources { bool splitSets = false; bool heapStage = false; mutable std::array heapOffsets{}; - void writeHeapStage(const CompiledShader& shader); + void writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader); struct HeapStageState { std::vector key; std::array, static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)> slots; @@ -698,17 +698,22 @@ class ShaderResources { KeptSpan data, flat, map; std::vector dataInput; std::uint64_t inertProgram = 0; + std::vector owned; + VkShaderStageFlags laidOutFor = 0; }; std::array heapStages; - std::uint64_t heapSpan(HeapStageState::KeptSpan& kept, std::span words); + std::uint64_t heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words); bool ownsHeapBinding(const Binding& binding, VkShaderStageFlags stageBit) const; VkImageView heapPlaceholderView(std::uint32_t kind) const; VkImageView heapSampledView(std::size_t index) const; VkImageView heapStorageView(std::size_t index, std::uint32_t binding) const; VkImageView heapMultisampleStorageView(std::size_t index) const; const HeapSlotOwner* heapMultisampleStorageOwner(std::size_t index) const; - void appendHeapSlotKey(VkShaderStageFlags stageBit, std::vector& key) const; - void takeHeapSlots(BindlessHeap& heap, HeapStageState& state, VkShaderStageFlags stageBit, std::span key); + void layOutHeapStages(std::span shaders); + template void visitHeapSlotKey(std::span owned, Emit&& emit) const; + void appendHeapSlotKey(std::span owned, std::vector& key) const; + bool heapSlotKeySame(std::span owned, std::span key) const; + void takeHeapSlots(BindlessHeap& heap, HeapStageState& state, std::span owned, std::span key); static void noteHeapSlotGenerations(const BindlessHeap& heap, HeapStageState& state); void verifyHeapSlots(const BindlessHeap& heap, const HeapStageState& state, VkShaderStageFlags stageBit) const; void patchHeapSlotWords(const CompiledShader& shader, const HeapStageState& stageState, std::vector& patched, bool current) const; @@ -735,12 +740,13 @@ class ShaderResources { std::vector descriptorWrites; bool addressedBuffers = false; std::vector resolvedAddresses; + std::array, ShaderRecompiler::RuntimeAbi::StageCount> addressedElements; VkDeviceAddress emptyAddress = 0; std::size_t gdsAllocation = std::numeric_limits::max(); std::array heapSrtDwords{}; std::array heapTableMaps{}; std::array heapTableMapSet{}; - void writeHeapTableMap(const CompiledShader& shader, std::size_t stageIndex); + void writeHeapTableMap(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, std::size_t stageIndex); void bufferRanges(std::uint32_t dataStage, const std::vector* overrides, std::vector& ranges) const; VkDeviceAddressRangeEXT bufferAddress(const Allocation& allocation) const; void resolveBufferAddresses(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index b56b9b6e8111..b847ed5ae4d4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -763,8 +763,8 @@ BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) return allocateLocked(words, mark); } -std::optional BindlessHeap::KeepOrAllocate(std::size_t words, SpanMark& mark, bool same) { - SpanScope scope(*this); +std::optional BindlessHeap::KeepOrAllocate(const SpanScope& held, std::size_t words, SpanMark& mark, bool same) { + Require(&held.heap == this, "a heap span was kept or allocated under another heap's lock"); if (same && heldLocked(mark)) return std::nullopt; return allocateLocked(words, mark); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 6b122b78b877..fa10557dbf04 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -1866,7 +1866,10 @@ void ShaderResources::Complete() { buildPrepare(shaders, nullptr, 0, 0, 0); } buildComplete(); - if (heapStage) RefreshHeapStage(shaders); + if (heapStage) { + layOutHeapStages(shaders); + RefreshHeapStage(shaders); + } forgetDeferredInputs(); } @@ -1881,7 +1884,10 @@ void ShaderResources::forgetDeferredInputs() { void ShaderResources::build(std::span shaders, const ColorTarget* target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::size_t indexBytes) { buildPrepare(shaders, target, colorAttachments, indexAddress, indexBytes); buildComplete(); - if (heapStage) RefreshHeapStage(shaders); + if (heapStage) { + layOutHeapStages(shaders); + RefreshHeapStage(shaders); + } } namespace { @@ -6710,11 +6716,15 @@ PipelineSetLayouts ShaderResources::SetLayouts() const { void ShaderResources::RefreshHeapStage(std::span shaders) { resolveBufferAddresses(); + BindlessHeap* heap = nullptr; std::optional spans; for (const auto& shader : shaders) { if (!HeapShader(shader)) continue; - if (!spans) spans.emplace(BindlessHeap::For(context)); - writeHeapStage(shader); + if (!spans) { + heap = &BindlessHeap::For(context); + spans.emplace(*heap); + } + writeHeapStage(*spans, *heap, shader); } } @@ -6743,39 +6753,36 @@ void ShaderResources::resolveBufferAddresses() { void ShaderResources::bufferRanges(std::uint32_t dataStage, const std::vector* overrides, std::vector& ranges) const { static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; - for (const auto& binding : bindings) { - if (!binding.addressed || binding.dataStage != dataStage) continue; - for (std::size_t element = 0; element < binding.allocations.size(); ++element) { - const auto index = binding.allocations[element]; - const auto& allocation = allocations[index]; - const bool overridden = overrides != nullptr && (*overrides)[index].buffer != VK_NULL_HANDLE; - const bool owned = !overridden && !allocation.guest && allocation.buffer != nullptr && allocation.role != ShaderRecompiler::DescriptorRole::GuestBuffers && allocation.role != ShaderRecompiler::DescriptorRole::BdaPagetable && allocation.role != ShaderRecompiler::DescriptorRole::FaultBuffer; - const bool resolved = !overridden && index < resolvedAddresses.size() && resolvedAddresses[index].address != 0; - VkDeviceAddress address = 0; - VkDeviceSize range = 0; - if (owned) { - address = allocation.buffer->DeviceAddress(); - range = allocation.size; - } else if (resolved) { - address = resolvedAddresses[index].address; - range = resolvedAddresses[index].size; - if (verify) { - const auto fresh = bufferAddress(allocation); - if (fresh.address != address || fresh.size != range) throw std::runtime_error("AGC graphics: a GPU heap buffer address resolved when the draw's resources were built changed"); - } - } else if (overridden) { - const auto& info = (*overrides)[index]; - const auto base = BufferDeviceAddress(context, info.buffer); - Require(base != 0, "an addressed buffer has no device address"); - address = base + info.offset; - range = info.range; - } else { + if (dataStage >= addressedElements.size()) return; + for (const auto index : addressedElements[dataStage]) { + const auto& allocation = allocations[index]; + const bool overridden = overrides != nullptr && (*overrides)[index].buffer != VK_NULL_HANDLE; + const bool owned = !overridden && !allocation.guest && allocation.buffer != nullptr && allocation.role != ShaderRecompiler::DescriptorRole::GuestBuffers && allocation.role != ShaderRecompiler::DescriptorRole::BdaPagetable && allocation.role != ShaderRecompiler::DescriptorRole::FaultBuffer; + const bool resolved = !overridden && index < resolvedAddresses.size() && resolvedAddresses[index].address != 0; + VkDeviceAddress address = 0; + VkDeviceSize range = 0; + if (owned) { + address = allocation.buffer->DeviceAddress(); + range = allocation.size; + } else if (resolved) { + address = resolvedAddresses[index].address; + range = resolvedAddresses[index].size; + if (verify) { const auto fresh = bufferAddress(allocation); - address = fresh.address; - range = fresh.size; + if (fresh.address != address || fresh.size != range) throw std::runtime_error("AGC graphics: a GPU heap buffer address resolved when the draw's resources were built changed"); } - ranges.push_back({address, std::min(range, context.limits.maxStorageBufferRange)}); + } else if (overridden) { + const auto& info = (*overrides)[index]; + const auto base = BufferDeviceAddress(context, info.buffer); + Require(base != 0, "an addressed buffer has no device address"); + address = base + info.offset; + range = info.range; + } else { + const auto fresh = bufferAddress(allocation); + address = fresh.address; + range = fresh.size; } + ranges.push_back({address, std::min(range, context.limits.maxStorageBufferRange)}); } } @@ -6867,10 +6874,11 @@ void ShaderResources::writePushedBuffers(std::span(std::min(ranges[index].size, 0xffffffffu)); const auto address = size != 0u && ranges[index].address != 0u ? ranges[index].address : empty; - Require(!UniformConstantBuffersEnabled() || address % context.limits.minUniformBufferOffsetAlignment == 0, "a pushed buffer address is off the uniform buffer offset alignment"); + Require(address % uniformAlignment == 0, "a pushed buffer address is off the uniform buffer offset alignment"); return std::array{static_cast(address), static_cast(address >> 32u), address == empty ? 0u : size, 0u}; }; const auto put = [&](std::uint32_t position, std::span words) { @@ -6914,7 +6922,7 @@ VkImageView ShaderResources::heapPlaceholderView(std::uint32_t kind) const { return context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(kind); } -void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_t stageIndex) { +void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, std::size_t stageIndex) { constexpr auto noElement = std::numeric_limits::max(); namespace Abi = ShaderRecompiler::RuntimeAbi; namespace TableAbi = ShaderRecompiler::ImageTableAbi; @@ -6927,7 +6935,6 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable) images = &binding; } - auto& heap = BindlessHeap::For(context); struct MapStorage {}; auto& map = HostThreadLocal, MapStorage>(); map.assign(table->map.begin(), table->map.end()); @@ -7000,13 +7007,12 @@ void ShaderResources::writeHeapTableMap(const CompiledShader& shader, std::size_ [&](StorageTexture& image, std::size_t index) { return image.UintStorageViewOrDefault(storageMips[index], storageFirstLayer[index]); }); } if (map.size() == base) map.push_back(sampledAbsent); - heapTableMaps[stageIndex] = heapSpan(heapStages[stageIndex].map, map); + heapTableMaps[stageIndex] = heapSpan(spans, heap, heapStages[stageIndex].map, map); heapTableMapSet[stageIndex] = true; } -std::uint64_t ShaderResources::heapSpan(HeapStageState::KeptSpan& kept, std::span words) { - auto& heap = BindlessHeap::For(context); - const auto span = heap.KeepOrAllocate(words.size(), kept.mark, std::ranges::equal(kept.words, words)); +std::uint64_t ShaderResources::heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words) { + const auto span = heap.KeepOrAllocate(spans, words.size(), kept.mark, std::ranges::equal(kept.words, words)); if (!span) return kept.mark.address; BindlessHeap::Write(*span, words); kept.words.assign(words.begin(), words.end()); @@ -7040,43 +7046,79 @@ VkImageView ShaderResources::heapStorageView(std::size_t index, std::uint32_t bi return texture->StorageView(storageMips[index], storageFirstLayer[index], UintStorageBinding(binding)); } -void ShaderResources::appendHeapSlotKey(VkShaderStageFlags stageBit, std::vector& key) const { - constexpr auto absent = std::numeric_limits::max(); - key.clear(); +void ShaderResources::layOutHeapStages(std::span shaders) { + for (const auto& shader : shaders) { + if (!HeapShader(shader)) continue; + const VkShaderStageFlags stageBit = VulkanStage(shader.stage); + auto& state = heapStages[HeapStageIndex(shader.stage)]; + state.owned.clear(); + for (std::size_t index = 0; index < bindings.size(); ++index) { + if (ownsHeapBinding(bindings[index], stageBit)) state.owned.push_back(static_cast(index)); + } + state.laidOutFor = stageBit; + } + for (auto& elements : addressedElements) elements.clear(); for (const auto& binding : bindings) { - if (!ownsHeapBinding(binding, stageBit)) continue; + if (!binding.addressed) continue; + Require(binding.dataStage < addressedElements.size(), "an addressed buffer binding names no data stage"); + for (const auto index : binding.allocations) addressedElements[binding.dataStage].push_back(static_cast(index)); + } +} + +template +void ShaderResources::visitHeapSlotKey(std::span owned, Emit&& emit) const { + constexpr auto absent = std::numeric_limits::max(); + const auto put = [&](std::uintptr_t first, std::uintptr_t view, std::uintptr_t layout) { return emit(first) && emit(view) && emit(layout); }; + for (const auto bindingIndex : owned) { + const auto& binding = bindings[bindingIndex]; if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) { for (const auto index : binding.imageAllocations) { if (index == absent) { - key.push_back(0u); + if (!emit(0u)) return; continue; } - key.insert(key.end(), {reinterpret_cast(textures[index].get()), - reinterpret_cast(heapSampledView(index)), - static_cast(textures[index]->Layout())}); + if (!put(reinterpret_cast(textures[index].get()), reinterpret_cast(heapSampledView(index)), static_cast(textures[index]->Layout()))) return; } } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { for (const auto index : binding.imageAllocations) { if (index != absent && storageTextures[index] == nullptr && heapMultisampleStorageView(index) != VK_NULL_HANDLE) { - key.insert(key.end(), {reinterpret_cast(heapMultisampleStorageOwner(index)), reinterpret_cast(heapMultisampleStorageView(index)), - static_cast(VK_IMAGE_LAYOUT_GENERAL)}); + if (!put(reinterpret_cast(heapMultisampleStorageOwner(index)), reinterpret_cast(heapMultisampleStorageView(index)), static_cast(VK_IMAGE_LAYOUT_GENERAL))) return; continue; } if (index == absent || storageTextures[index] == nullptr) { - key.push_back(0u); + if (!emit(0u)) return; continue; } - key.insert(key.end(), {reinterpret_cast(storageTextures[index].get()), - reinterpret_cast(heapStorageView(index, binding.layout.binding)), - static_cast(VK_IMAGE_LAYOUT_GENERAL)}); + if (!put(reinterpret_cast(storageTextures[index].get()), reinterpret_cast(heapStorageView(index, binding.layout.binding)), static_cast(VK_IMAGE_LAYOUT_GENERAL))) return; } } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { - for (const auto index : binding.imageAllocations) key.push_back(reinterpret_cast(samplers[index].get())); + for (const auto index : binding.imageAllocations) { + if (!emit(reinterpret_cast(samplers[index].get()))) return; + } } } } -void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, VkShaderStageFlags stageBit, +void ShaderResources::appendHeapSlotKey(std::span owned, std::vector& key) const { + key.clear(); + visitHeapSlotKey(owned, [&](std::uintptr_t word) { + key.push_back(word); + return true; + }); +} + +bool ShaderResources::heapSlotKeySame(std::span owned, std::span key) const { + std::size_t cursor = 0; + bool same = true; + visitHeapSlotKey(owned, [&](std::uintptr_t word) { + same = cursor < key.size() && key[cursor] == word; + ++cursor; + return same; + }); + return same && cursor == key.size(); +} + +void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, std::span owned, std::span key) { namespace Abi = ShaderRecompiler::RuntimeAbi; constexpr auto bindingCount = static_cast(Abi::Binding::Count); @@ -7084,8 +7126,8 @@ void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, V for (auto& kindSlots : state.slots) kindSlots.clear(); state.samplerSlots.clear(); std::size_t cursor = 0; - for (const auto& binding : bindings) { - if (!ownsHeapBinding(binding, stageBit)) continue; + for (const auto bindingIndex : owned) { + const auto& binding = bindings[bindingIndex]; const auto kind = binding.layout.binding % bindingCount; if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) { auto& kindSlots = state.slots[kind]; @@ -7236,11 +7278,9 @@ void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const Hea if (!slotWords) std::copy(samplerSlots.begin(), samplerSlots.end(), patched.begin() + program.samplerSlotDword); } -void ShaderResources::writeHeapStage(const CompiledShader& shader) { +void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader) { namespace Abi = ShaderRecompiler::RuntimeAbi; HeapCostScope slotsCost(HeapCost::Slots); - auto& heap = BindlessHeap::For(context); - const BindlessHeap::SpanScope spans(heap); const VkShaderStageFlags stageBit = VulkanStage(shader.stage); const auto stageIndex = HeapStageIndex(shader.stage); auto& stageState = heapStages[stageIndex]; @@ -7248,18 +7288,17 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { const auto programIdentity = shader.program->heapTemplateId; if (programIdentity != 0 && stageState.inertProgram == programIdentity && !verifySlots) return; stageState.inertProgram = 0; - struct HeapKeyStorage {}; - auto& key = HostThreadLocal, HeapKeyStorage>(); - appendHeapSlotKey(stageBit, key); - bool current = key == stageState.key; + Require(stageState.laidOutFor == stageBit, "a GPU heap stage was refreshed for a stage its resources were not laid out for"); + const auto& owned = stageState.owned; + bool current = heapSlotKeySame(owned, stageState.key); const auto slotSerial = heap.SlotSerial(); const bool unmoved = current && EpochProofs() && stageState.slotSerial == slotSerial; if (!unmoved && current) current = heap.GenerationsCurrent(stageState.imageSlots, stageState.slotGenerations, stageState.samplerSlots, stageState.samplerGenerations); if (!current) { - stageState.key = key; - takeHeapSlots(heap, stageState, stageBit, key); + appendHeapSlotKey(owned, stageState.key); + takeHeapSlots(heap, stageState, owned, stageState.key); noteHeapSlotGenerations(heap, stageState); } else { stageState.touchedEpoch = heap.TouchSlots(stageState.imageSlots, stageState.samplerSlots, stageState.touchedEpoch); @@ -7272,7 +7311,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { const std::size_t dataIndex = DataOffsetIndex(stageIndex, Abi::Binding::ShaderData); const std::size_t flatIndex = DataOffsetIndex(stageIndex, Abi::Binding::FlattenedSrt); const auto& program = *shader.program; - if (program.dataAddressPush) writeHeapTableMap(shader, stageIndex); + if (program.dataAddressPush) writeHeapTableMap(spans, heap, shader, stageIndex); bool dataBindings = false; for (const auto& binding : program.bindings) { const bool shaderData = binding.role == ShaderRecompiler::DescriptorRole::ShaderData; @@ -7295,7 +7334,7 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { stageState.data.mark.entry = 0; } if (!shaderData) { - heapOffsets[flatIndex] = heapSpan(stageState.flat, words); + heapOffsets[flatIndex] = heapSpan(spans, heap, stageState.flat, words); heapSrtDwords[stageIndex] = static_cast(words.size()); continue; } @@ -7312,11 +7351,11 @@ void ShaderResources::writeHeapStage(const CompiledShader& shader) { patchHeapSlotWords(shader, stageState, patched, current); if (verifySlots && sameInput && !std::ranges::equal(stageState.data.words, patched)) throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its inputs and slots did not"); - heapOffsets[dataIndex] = heapSpan(stageState.data, patched); + heapOffsets[dataIndex] = heapSpan(spans, heap, stageState.data, patched); stageState.dataInput.assign(words.begin(), words.end()); stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); } - const bool unbound = key.empty() && !dataBindings && !heapTableMapSet[stageIndex] && stageState.imageSlots.empty() && stageState.samplerSlots.empty(); + const bool unbound = stageState.key.empty() && !dataBindings && !heapTableMapSet[stageIndex] && stageState.imageSlots.empty() && stageState.samplerSlots.empty(); if (unbound && !addressedBuffers) stageState.inertProgram = programIdentity; } diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 7695c6303132..342b978fd40d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -218,7 +218,7 @@ void spanScope(const Context& context) { const BindlessHeap::SpanScope outer(heap); const BindlessHeap::SpanScope inner(heap); static_cast(heap.Allocate(16u, first)); - require(heap.Held(first) && !heap.KeepOrAllocate(16u, first, true), "spans are allocated and kept inside nested scopes"); + require(heap.Held(first) && !heap.KeepOrAllocate(inner, 16u, first, true), "spans are allocated and kept inside nested scopes"); other = std::thread([&] { BindlessHeap::SpanMark mark; static_cast(heap.Allocate(16u, mark)); From 0c27c510e5535b9c46692f09aff0f9dedf3b7f35 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 8 Nov 2026 19:42:38 +0530 Subject: [PATCH 153/269] perf(agc): carry GPU heap buffer addresses from where the buffers are made Building a heap draw's push data asked the Vulkan driver for a buffer's device address on every draw: for each moved buffer, for the BDA page table and fault slot, and for GDS. Each of those buffers already holds its address from when it was created or imported, so a moved buffer's override now carries the address of its upload slice or of the guest memory it is read from in place, the page table and fault slot come with their buffers' addresses, and GDS is resolved once with the stage's other guest buffers. This follows vkd3d-proton, which takes a buffer's address from vkd3d_get_buffer_device_address when the resource is created and keeps it in res.va, so GetGPUVirtualAddress and root descriptors never ask the driver again. --- .../Graphics/include/BdaResources.hpp | 2 + .../Graphics/include/GuestBufferMemory.hpp | 4 +- .../Graphics/include/ResidentMirror.hpp | 1 + .../Graphics/include/ShaderResources.hpp | 9 +-- .../Graphics/src/BdaResources.cpp | 9 +++ .../Graphics/src/GuestBufferMemory.cpp | 11 +++- .../Graphics/src/ShaderResources.cpp | 66 ++++++++++--------- 7 files changed, 63 insertions(+), 39 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BdaResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BdaResources.hpp index 8a3cb853da14..cd010a921eaa 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BdaResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BdaResources.hpp @@ -28,6 +28,8 @@ class BdaResources { std::span TableBytes() const; bool TableGuardCurrent(VkDevice device, std::span ranges); VkDescriptorBufferInfo Fault() const; + VkDeviceAddress TableAddress() const; + VkDeviceAddress FaultAddress() const; void CheckFault() const; void CheckUse(const BdaResources* record) const; void NoteUse(std::uint64_t serial); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index f12da1804e24..f428cc463e92 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -382,8 +382,8 @@ class GuestBufferMemory { void Upload(bool addressable); void UploadPrepare(bool addressable); void UploadFinish(bool addressable, std::optional> htileClear = std::nullopt); - VkDescriptorBufferInfo Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment) const; - std::optional TryDescriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, std::string* failure = nullptr) const; + VkDescriptorBufferInfo Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, VkDeviceAddress* handleAddress = nullptr) const; + std::optional TryDescriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, std::string* failure = nullptr, VkDeviceAddress* handleAddress = nullptr) const; static std::uint64_t ViewBytes(std::uint64_t bytes, std::uint32_t adjustment); std::vector AddressRanges() const; // The BDA table of the cached address space when it serves this upload alone (an address-based diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ResidentMirror.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ResidentMirror.hpp index 87e0619b8ba3..76500a103ec7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ResidentMirror.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ResidentMirror.hpp @@ -34,6 +34,7 @@ class ResidentBuffer : public std::enable_shared_from_this { VkBuffer Handle() const { return buffer; } VkDeviceAddress DeviceAddress() const { return address + lead; } + VkDeviceAddress HandleAddress() const { return address; } std::uint64_t Origin() const { return origin; } std::uint64_t BoundBytes() const { return bound * BlockBytes; } std::uint32_t MemoryType() const { return type; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 5fa6bb46b4f2..934b5889c770 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -231,7 +231,7 @@ class ShaderResources { std::vector snapshots; bool addressOffsets = false; std::array heapOffsets{}; - std::vector addressOverrides; + std::vector addressOverrides; std::vector> movedReads; ~DrawBindings(); }; @@ -377,7 +377,7 @@ class ShaderResources { } void PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const; void writePushedData(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const; - void writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const; + void writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const; // Whether RefreshData would record anything for `shader` (the per-word compare; verification). bool DataWordsDiffer(const CompiledShader& shader) const; std::size_t BindingCount() const { return bindings.size(); } @@ -742,12 +742,13 @@ class ShaderResources { std::vector resolvedAddresses; std::array, ShaderRecompiler::RuntimeAbi::StageCount> addressedElements; VkDeviceAddress emptyAddress = 0; + VkDeviceAddress resolvedGds = 0; std::size_t gdsAllocation = std::numeric_limits::max(); std::array heapSrtDwords{}; std::array heapTableMaps{}; std::array heapTableMapSet{}; void writeHeapTableMap(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, std::size_t stageIndex); - void bufferRanges(std::uint32_t dataStage, const std::vector* overrides, std::vector& ranges) const; + void bufferRanges(std::uint32_t dataStage, const std::vector* overrides, std::vector& ranges) const; VkDeviceAddressRangeEXT bufferAddress(const Allocation& allocation) const; void resolveBufferAddresses(); struct FaultDescriptor { @@ -757,7 +758,7 @@ class ShaderResources { }; std::vector faultDescriptors; void prepareFaultSlot() const; - void writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord, std::span> inPlace = {}) const; + void writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord, std::span> inPlace = {}) const; std::shared_ptr> ownRecordBusy = std::make_shared>(false); mutable std::vector drawPoolSizes; // Guest buffer elements bound read-only: each use of this object skips that many pending-write diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp index 5919a6f94115..78f4317ceb70 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp @@ -452,6 +452,15 @@ VkDescriptorBufferInfo BdaResources::Fault() const { return {faultChunk->buffer->Handle(), faultOffset, faultChunk->slotBytes}; } +VkDeviceAddress BdaResources::TableAddress() const { + Require(table != nullptr, "BDA page table was not requested"); + return table->DeviceAddress(); +} + +VkDeviceAddress BdaResources::FaultAddress() const { + return faultChunk->buffer->DeviceAddress() + faultOffset; +} + namespace { std::atomic loopGuardTripped{false}; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 859154e3119f..9b042750850a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -2913,6 +2913,10 @@ VkDeviceAddress mirrorAddress(const ImageMirror& mirror) { return mirror.resident != nullptr ? mirror.resident->DeviceAddress() : mirror.buffer->DeviceAddress(); } +VkDeviceAddress mirrorHandleAddress(const ImageMirror& mirror) { + return mirror.resident != nullptr ? mirror.resident->HandleAddress() : mirror.buffer->DeviceAddress(); +} + bool sameRange(const std::weak_ptr& mirrored, const std::shared_ptr& range) { return !mirrored.owner_before(range) && !range.owner_before(mirrored); } @@ -6806,14 +6810,14 @@ void GuestBufferMemory::RecordCopyBacks(Recorder& recorder) { recorder.EndGpuTiming(timing, copiedBytes); } -VkDescriptorBufferInfo GuestBufferMemory::Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment) const { +VkDescriptorBufferInfo GuestBufferMemory::Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, VkDeviceAddress* handleAddress) const { std::string failure; - const auto info = TryDescriptor(address, bytes, adjustment, &failure); + const auto info = TryDescriptor(address, bytes, adjustment, &failure, handleAddress); if (!info.has_value()) Require(false, failure); return *info; } -std::optional GuestBufferMemory::TryDescriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, std::string* failure) const { +std::optional GuestBufferMemory::TryDescriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, std::string* failure, VkDeviceAddress* handleAddress) const { const auto fail = [failure](std::string text) -> std::optional { if (failure != nullptr) *failure = std::move(text); return std::nullopt; @@ -6846,6 +6850,7 @@ std::optional GuestBufferMemory::TryDescriptor(std::uint if (address - adjustment + range > end) return fail(describe("rounded up to its view range exceeds")); if (range > context.limits.maxStorageBufferRange) return fail("guest buffer view exceeds descriptor range limit"); const auto handle = region.direct != nullptr ? region.direct->buffer : region.mirror != nullptr ? mirrorHandle(*region.mirror) : region.buffer->Handle(); + if (handleAddress != nullptr) *handleAddress = region.direct != nullptr ? region.direct->address - region.direct->lead : region.mirror != nullptr ? mirrorHandleAddress(*region.mirror) : region.buffer->DeviceAddress(); return VkDescriptorBufferInfo{handle, offset - adjustment, range}; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index fa10557dbf04..65bc426e4451 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6431,7 +6431,7 @@ std::shared_ptr ShaderResources::PrepareDrawBindi if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE && !heapStage) || (usesBda && !spaceReuse)) return {}; const bool readsInPlace = usesBda && heapStage; movedOnly = movedOnly || readsInPlace; - thread_local std::vector>* inPlaceSlot = nullptr; + thread_local std::vector>* inPlaceSlot = nullptr; auto& inPlace = ShaderRecompiler::ThreadOwned(inPlaceSlot); inPlace.clear(); prepareFaultSlot(); @@ -6457,7 +6457,10 @@ std::shared_ptr ShaderResources::PrepareDrawBindi if (override != moved.end() && override->words.empty()) result->movedReads.emplace_back(override->address, override->address + override->size); if (override != moved.end() && override->words.empty() && readsInPlace) { std::uint32_t adjustment = 0; - inPlace.push_back({index, wholeDwordRange(guestMemory.Descriptor(override->address, override->size, adjustment))}); + VkDeviceAddress handle = 0; + const auto info = wholeDwordRange(guestMemory.Descriptor(override->address, override->size, adjustment, &handle)); + Require(handle != 0, "a moved buffer read in place has no device address"); + inPlace.push_back({index, {handle + info.offset, info.range}}); Require(adjustment == item.adjustment, "a moved buffer read in place lost its view's alignment"); continue; } @@ -6534,7 +6537,7 @@ std::shared_ptr ShaderResources::PrepareDrawBindi return result; } -void ShaderResources::writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord, std::span> inPlace) const { +void ShaderResources::writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord, std::span> inPlace) const { Require(context.descriptorCache != nullptr, "draw snapshots require a descriptor cache"); std::array described{}; thread_local std::array, 2>* countsSlot = nullptr; @@ -6598,16 +6601,16 @@ void ShaderResources::writeDrawSets(DrawBindings& result, std::span overrides(allocations.size(), VkDescriptorBufferInfo{VK_NULL_HANDLE, 0, 0}); + std::vector overrides(allocations.size(), VkDeviceAddressRangeEXT{0, 0}); bool overridden = false; for (std::size_t index = 0; index < selected.size(); ++index) { const auto& snapshot = result.snapshots[index]; - overrides[selected[index]] = {snapshot.buffer->Handle(), snapshot.offset, snapshot.bytes}; + overrides[selected[index]] = {snapshot.buffer->DeviceAddress() + snapshot.offset, snapshot.bytes}; } - for (const auto& [index, info] : inPlace) overrides[index] = info; + for (const auto& [index, range] : inPlace) overrides[index] = range; for (const auto& binding : bindings) { if (!binding.addressed) continue; - for (const auto allocation : binding.allocations) overridden = overridden || overrides[allocation].buffer != VK_NULL_HANDLE; + for (const auto allocation : binding.allocations) overridden = overridden || overrides[allocation].address != 0; } if (overridden) { result.heapOffsets = heapOffsets; @@ -6730,6 +6733,18 @@ void ShaderResources::RefreshHeapStage(std::span shaders) VkDeviceAddressRangeEXT ShaderResources::bufferAddress(const Allocation& allocation) const { auto adjustment = allocation.adjustment; + if (allocation.guest) { + VkDeviceAddress handle = 0; + const auto info = wholeDwordRange(guestMemory.Descriptor(allocation.address, allocation.size, adjustment, &handle)); + Require(handle != 0, "an addressed guest buffer has no device address"); + return {handle + info.offset, info.range}; + } + if (allocation.role == ShaderRecompiler::DescriptorRole::BdaPagetable || allocation.role == ShaderRecompiler::DescriptorRole::FaultBuffer) { + Require(bda != nullptr, "BDA descriptors have no memory owner"); + if (allocation.role == ShaderRecompiler::DescriptorRole::BdaPagetable) return {bda->TableAddress(), bda->Table().range}; + return {bda->FaultAddress(), bda->Fault().range}; + } + if (allocation.role != ShaderRecompiler::DescriptorRole::GuestBuffers && allocation.buffer != nullptr) return {allocation.buffer->DeviceAddress(), allocation.size}; auto info = descriptor(allocation, adjustment); if (info.buffer == VK_NULL_HANDLE) info = {context.emptyBuffer, 0, EmptyBufferBytes}; const auto base = BufferDeviceAddress(context, info.buffer); @@ -6740,6 +6755,7 @@ VkDeviceAddressRangeEXT ShaderResources::bufferAddress(const Allocation& allocat void ShaderResources::resolveBufferAddresses() { if (!resolvedAddresses.empty()) return; if (emptyAddress == 0) emptyAddress = BufferDeviceAddress(context, context.emptyBuffer); + if (gdsAllocation != std::numeric_limits::max() && resolvedGds == 0) resolvedGds = bufferAddress(allocations[gdsAllocation]).address; if (!addressedBuffers) return; resolvedAddresses.assign(allocations.size(), {}); for (const auto& binding : bindings) { @@ -6751,12 +6767,12 @@ void ShaderResources::resolveBufferAddresses() { } } -void ShaderResources::bufferRanges(std::uint32_t dataStage, const std::vector* overrides, std::vector& ranges) const { +void ShaderResources::bufferRanges(std::uint32_t dataStage, const std::vector* overrides, std::vector& ranges) const { static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; if (dataStage >= addressedElements.size()) return; for (const auto index : addressedElements[dataStage]) { const auto& allocation = allocations[index]; - const bool overridden = overrides != nullptr && (*overrides)[index].buffer != VK_NULL_HANDLE; + const bool overridden = overrides != nullptr && (*overrides)[index].address != 0; const bool owned = !overridden && !allocation.guest && allocation.buffer != nullptr && allocation.role != ShaderRecompiler::DescriptorRole::GuestBuffers && allocation.role != ShaderRecompiler::DescriptorRole::BdaPagetable && allocation.role != ShaderRecompiler::DescriptorRole::FaultBuffer; const bool resolved = !overridden && index < resolvedAddresses.size() && resolvedAddresses[index].address != 0; VkDeviceAddress address = 0; @@ -6772,11 +6788,8 @@ void ShaderResources::bufferRanges(std::uint32_t dataStage, const std::vectorTable(); - table = of(tableInfo); - tableDwords = static_cast(tableInfo.range / sizeof(std::uint32_t)); + table = bda->TableAddress(); + tableDwords = static_cast(bda->Table().range / sizeof(std::uint32_t)); } - if (faultBound) fault = of(bda->Fault()); + if (faultBound) fault = bda->FaultAddress(); } Require(placements.size() == shaders.size(), "the push layout does not describe the draw's stages"); std::optional gds; @@ -6825,12 +6832,11 @@ void ShaderResources::PatchDataAddresses(std::span::max()) return *gds; const auto* overrides = rewritten != nullptr && rewritten->addressOffsets ? &rewritten->addressOverrides : nullptr; - auto adjustment = allocations[gdsAllocation].adjustment; - const auto info = overrides != nullptr && (*overrides)[gdsAllocation].buffer != VK_NULL_HANDLE ? (*overrides)[gdsAllocation] : descriptor(allocations[gdsAllocation], adjustment); - Require(info.buffer != VK_NULL_HANDLE, "the GDS buffer is missing"); - const auto base = BufferDeviceAddress(context, info.buffer); - Require(base != 0, "the GDS buffer has no device address"); - gds = base + info.offset; + const bool overridden = overrides != nullptr && (*overrides)[gdsAllocation].address != 0; + gds = overridden ? (*overrides)[gdsAllocation].address : resolvedGds; + Require(*gds != 0, "the GDS buffer has no device address"); + static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + if (verify && !overridden && bufferAddress(allocations[gdsAllocation]).address != *gds) throw std::runtime_error("AGC graphics: the GDS address resolved when the draw's resources were built changed"); return *gds; }; bool rooted = false; @@ -6865,7 +6871,7 @@ void ShaderResources::PatchDataAddresses(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const { +void ShaderResources::writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const { namespace Abi = ShaderRecompiler::RuntimeAbi; struct RangeStorage {}; auto& ranges = HostThreadLocal, RangeStorage>(); From 23da959d7e63643296eeab2707fead3041238e27 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 9 Nov 2026 00:53:46 +0530 Subject: [PATCH 154/269] fix(agc): check a heap draw recipe's buffers for moves on every hit A draw found through relocation shares its donor's recipe even when a buffer descriptor in its user data moved (relocateDrawEntry patches the descriptor as a value word). A recipe recorded without moved buffers skipped MovedReadOnlyBuffers on its hits, so in GPU heap mode the relocated draw replayed the donor's buffer: a buffer moved by 256 bytes drew the old buffer's contents. In heap mode a recipe hit now proves its read-only buffers where they are, as a template hit does, and replays them moved when they moved. --- core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp | 2 +- .../tests/execution/DrawRecipeMovedBuffer.cpp | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 2cdc38751a46..74ed4b455a14 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -4358,7 +4358,7 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con return miss(DrawRecipeMiss::Proof); } std::vector moved; - if (recipe.movedBuffers) { + if (recipe.movedBuffers || resources->HeapStage()) { auto found = resources->MovedReadOnlyBuffers(shaders, *recorder, &state.color); if (!found.has_value()) { timer.phase(PhaseLookup); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp index 302358a365d7..d3b518b95cb2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp @@ -368,6 +368,12 @@ int main() { for (int round = 0; round < 3; ++round) Require(Submit(unmoved) == BufferAlphaByte, "the draw of the template's own buffer did not read it"); const std::array movedOnly{Moved}; for (int round = 0; round < 3; ++round) Require(Submit(movedOnly) == SecondAlphaByte, "a draw whose buffer moved after a recipe without moves was recorded did not read the moved buffer"); + constexpr std::size_t Aligned = First + 64; + const std::array alignedSlices{First, Aligned}; + BufferMemory[Aligned] = SecondAlpha; + const auto alignedAlpha = Submit(alignedSlices); + Require(alignedAlpha == SecondAlphaByte, "a draw whose buffer moved by a whole number of 256-byte blocks drew another buffer's contents (alpha " + std::to_string(alignedAlpha) + ")"); + BufferMemory[Aligned] = 0.0f; std::puts("draws whose read-only buffer moved from their template's replayed recipes that read the buffer's current contents"); AgcDriverShutdown_nid_postfix(); return 0; From 219fb46961350100e2b4e4d5a64b8586b422c812 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 9 Nov 2026 00:54:40 +0530 Subject: [PATCH 155/269] perf(agc): read a heap draw's moved buffer in place behind a pending GPU write A template hit or recipe hit whose read-only buffer moved onto a range with a pending GPU write refused the move, so the draw rebuilt its template from scratch. GTA V hits this about 7,400 times per 10 s in heap mode, nearly always with the buffer moved into guest memory its template does not own (heap off keys its templates per buffer address and never moves). In heap mode such a buffer is read in place through its device address, as a freshly built template reads the same memory, when its alignment adjustment is the template's: through the host import that holds the range (GuestBufferMemory::ImportedView, as in-place vertex inputs are read), which is the live guest memory the pending write lands in. The moved ranges join the draw pass's reads, so the read is ordered after the write, and its pending reads, and queued key, label and linear storage stores over them land before the draw. Draws whose buffer is copied (heap off, or a copied writer over the range) still refuse. --- .../Graphics/include/GuestBufferMemory.hpp | 1 + .../Graphics/include/ShaderResources.hpp | 3 ++ .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 5 +- .../Graphics/src/GuestBufferMemory.cpp | 15 ++++++ .../Graphics/src/ShaderResources.cpp | 48 +++++++++++++---- .../tests/execution/DrawRecipeMovedBuffer.cpp | 53 ++++++++++++++++--- 6 files changed, 109 insertions(+), 16 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index f428cc463e92..a521e565d4a6 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -384,6 +384,7 @@ class GuestBufferMemory { void UploadFinish(bool addressable, std::optional> htileClear = std::nullopt); VkDescriptorBufferInfo Descriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, VkDeviceAddress* handleAddress = nullptr) const; std::optional TryDescriptor(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment, std::string* failure = nullptr, VkDeviceAddress* handleAddress = nullptr) const; + std::optional ImportedView(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment) const; static std::uint64_t ViewBytes(std::uint64_t bytes, std::uint32_t adjustment); std::vector AddressRanges() const; // The BDA table of the cached address space when it serves this upload alone (an address-based diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 934b5889c770..dbb4fa52af2d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -241,6 +241,8 @@ class ShaderResources { std::uint64_t address; std::size_t size; std::span words; + bool inPlace = false; + VkDeviceAddressRangeEXT view{}; }; struct DrawUse { DrawUse() = default; @@ -346,6 +348,7 @@ class ShaderResources { const std::vector& MultisampleSources() const { return multisampleSources; } static bool NeverReusable(std::span shaders); static std::uint64_t DepthGuardRefusals(); + static std::uint64_t MovedBehindGpuWrites(); const std::vector>& SampledTextures() const { return textures; } static std::size_t LookupLogCapacity(); bool ChecksFaults() const { return bda != nullptr; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 74ed4b455a14..e0eb2b8de4b3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -2826,6 +2826,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam const auto touches = [&](std::uint64_t begin, std::uint64_t end) { const auto bytes = static_cast(end - begin); if (resources.WritesOverlap(begin, bytes) || resources.ReadsOverlap(begin, bytes)) return true; + if (std::any_of(record.moved.begin(), record.moved.end(), [&](const ShaderResources::MovedBuffer& moved) { return moved.words.empty() && moved.address < end && begin < moved.address + moved.size; })) return true; if (!gpuIndirect) return false; return (begin < args->arguments + args->RangeBytes() && args->arguments < end) || (args->countIndirect && begin < args->countAddress + 4 && args->countAddress < end); }; @@ -2860,9 +2861,10 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam } for (const auto image : record.multisampleImages) passAttachments.emplace_back(image, true); const bool unknownMemory = addressBased || resources.UsesAddressTable() || resources.HasCopiedWrites(); - static_cast(StorageTexture::StoreDrawnLinearTouching("draw access", [&](std::uint64_t begin, std::uint64_t end) { return std::any_of(passReads.begin(), passReads.end(), [&](const auto& read) { return read.first < end && begin < read.second; }) || resources.WritesOverlap(begin, static_cast(end - begin)); }, unknownMemory)); + static_cast(StorageTexture::StoreDrawnLinearTouching("draw access", [&](std::uint64_t begin, std::uint64_t end) { return std::any_of(passReads.begin(), passReads.end(), [&](const auto& read) { return read.first < end && begin < read.second; }) || resources.WritesOverlap(begin, static_cast(end - begin)) || std::any_of(record.moved.begin(), record.moved.end(), [&](const ShaderResources::MovedBuffer& moved) { return moved.words.empty() && moved.address < end && begin < moved.address + moved.size; }); }, unknownMemory)); const auto drawUse = resources.BeginDrawUse(*recorder); const auto drawBindings = resources.PrepareDrawBindings(*recorder, record.moved, false, drawUse != nullptr ? drawUse->record.get() : nullptr); + if (drawBindings != nullptr) passReads.insert(passReads.end(), drawBindings->movedReads.begin(), drawBindings->movedReads.end()); static const bool addressReadPasses = std::getenv("APS5_NO_ADDRESS_READ_PASSES") == nullptr; const bool readOnlyBda = addressReadPasses && resources.BdaReadOnly(); outcome.addressDraw = addressBased; @@ -3044,6 +3046,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam recorder->LeaveRenderPassOpen(passKey, drawTiming, fenced, passAccess, std::move(storeProxies)); timer.phase(PhaseRecord); keepRecordedDraw(*recorder, record.resources, std::move(record.pipeline), std::move(record.framebuffer), inputs, std::move(record.targets), std::move(record.targetSlices), state.scissor, std::move(scratch), std::move(checkRecords), record.listed, record.completion, outcome, drawUse, record.spaceKeep != nullptr && *record.spaceKeep != nullptr ? record.spaceKeep->get() : nullptr); + if (drawBindings != nullptr && !drawBindings->movedReads.empty()) recorder->NotePendingReads(drawBindings->movedReads, Recorder::ReadKind::DrawInput); timer.phase(PhaseKeep); if (!record.staged.empty()) { const auto merged = recorder->Commands(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 9b042750850a..3bc1f4e88ab0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -6854,6 +6854,21 @@ std::optional GuestBufferMemory::TryDescriptor(std::uint return VkDescriptorBufferInfo{handle, offset - adjustment, range}; } +std::optional GuestBufferMemory::ImportedView(std::uint64_t address, std::size_t bytes, std::uint32_t& adjustment) const { + if (bytes == 0 || bytes > std::numeric_limits::max() - address) return std::nullopt; + const auto* import = ExistingHostImportFor(context, address, bytes); + if (import == nullptr || import->address == 0) return std::nullopt; + const auto offset = HostImportOffset(*import, address); + adjustment = static_cast(offset % viewAlignment()); + const auto start = offset - adjustment; + const auto end = import->lead + import->bytes; + auto range = (ViewBytes(bytes, adjustment) + 3u) & ~std::uint64_t{3}; + if (bytes <= context.limits.maxStorageBufferRange) range = std::min(range, context.limits.maxStorageBufferRange & ~std::uint64_t{3}); + range = std::min(range, end - start); + if (range < adjustment + bytes || range > context.limits.maxStorageBufferRange) return std::nullopt; + return VkDeviceAddressRangeEXT{import->address - import->lead + start, range}; +} + std::uint64_t GuestBufferMemory::ViewBytes(std::uint64_t bytes, std::uint32_t adjustment) { if (adjustment % 4 == 0) return bytes + adjustment; const auto dwords = adjustment / 4 + bytes / 4 + (adjustment % 4 + bytes % 4 + 3) / 4; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 65bc426e4451..5e3d1ad63cea 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -3012,6 +3012,14 @@ void ShaderResources::noteReusable() { reusable = true; } +namespace { +std::atomic movedBehindGpuWrites{0}; +} + +std::uint64_t ShaderResources::MovedBehindGpuWrites() { + return movedBehindGpuWrites.load(std::memory_order_relaxed); +} + std::uint64_t ShaderResources::DepthGuardRefusals() { return depthGuardRefusals.load(std::memory_order_relaxed); } @@ -6335,19 +6343,36 @@ std::optional> ShaderResources::MovedR if (written || empty || item.written || size > context.limits.maxStorageBufferRange) return std::nullopt; const auto begin = address - item.adjustment; const auto bytes = static_cast(GuestBufferMemory::ViewBytes(size, item.adjustment)); - const bool copied = !(usesBda && heapStage); - if (copied && bytes > maxDrawSnapshotBytes - movedBytes) return std::nullopt; + const bool behind = recorder.PendingWriteOverlaps(begin, bytes); + const bool inPlace = (usesBda && heapStage) || (behind && heapShader && addressedBuffers); + if (behind && !inPlace) return std::nullopt; + if (!inPlace && bytes > maxDrawSnapshotBytes - movedBytes) return std::nullopt; if (!GuestMemory::Accessible(reinterpret_cast(begin), bytes)) return std::nullopt; - if (guestMemory.WritesOverlap(begin, bytes) || recorder.PendingWriteOverlaps(begin, bytes) || PendingStorageOverlaps(begin, bytes, nullptr) || AnyShadowedOverlaps(begin, bytes)) return std::nullopt; - if (usesBda && heapStage) { + if (guestMemory.WritesOverlap(begin, bytes) || PendingStorageOverlaps(begin, bytes, nullptr) || AnyShadowedOverlaps(begin, bytes)) return std::nullopt; + if (behind) { + const auto overlaps = [&](const std::shared_ptr& writer) { return writer != nullptr && writer->WritesOverlap(begin, bytes); }; + if (context.copiedWriters != nullptr && std::any_of(context.copiedWriters->begin(), context.copiedWriters->end(), overlaps)) return std::nullopt; + const auto drawWriters = DrawCopiedWriters(); + if (std::any_of(drawWriters->begin(), drawWriters->end(), overlaps)) return std::nullopt; + } + VkDeviceAddressRangeEXT view{}; + if (inPlace) { std::uint32_t adjustment = 0; - const auto inPlace = guestMemory.TryDescriptor(address, static_cast(size), adjustment); + bool found = false; + if (behind) { + const auto imported = guestMemory.ImportedView(address, static_cast(size), adjustment); + if (imported.has_value()) view = *imported; + found = view.address != 0; + } else { + VkDeviceAddress handle = 0; + found = guestMemory.TryDescriptor(address, static_cast(size), adjustment, nullptr, &handle).has_value() && handle != 0; + } const bool classic = std::any_of(bindings.begin(), bindings.end(), [&](const Binding& other) { return !(other.heap && other.addressed) && std::find(other.allocations.begin(), other.allocations.end(), index) != other.allocations.end(); }); - if (!inPlace.has_value() || adjustment != item.adjustment || classic) return std::nullopt; + if (!found || adjustment != item.adjustment || classic) return std::nullopt; } if (moved.empty()) moved.reserve(allocations.size()); - moved.push_back({index, address, static_cast(size)}); - if (copied) movedBytes += bytes; + moved.push_back({index, address, static_cast(size), {}, inPlace, view}); + if (!inPlace) movedBytes += bytes; } } } @@ -6455,7 +6480,12 @@ std::shared_ptr ShaderResources::PrepareDrawBindi const auto& item = allocations[index]; const auto override = std::find_if(moved.begin(), moved.end(), [&](const MovedBuffer& entry) { return entry.allocation == index; }); if (override != moved.end() && override->words.empty()) result->movedReads.emplace_back(override->address, override->address + override->size); - if (override != moved.end() && override->words.empty() && readsInPlace) { + if (override != moved.end() && override->words.empty() && (readsInPlace || override->inPlace)) { + if (!readsInPlace || override->view.address != 0) movedBehindGpuWrites.fetch_add(1, std::memory_order_relaxed); + if (override->view.address != 0) { + inPlace.push_back({index, override->view}); + continue; + } std::uint32_t adjustment = 0; VkDeviceAddress handle = 0; const auto info = wholeDwordRange(guestMemory.Descriptor(override->address, override->size, adjustment, &handle)); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp index d3b518b95cb2..4ef52e65f769 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp @@ -100,7 +100,20 @@ constexpr float BufferAlpha = 0.2f; constexpr std::uint8_t BufferAlphaByte = 51u; constexpr float SecondAlpha = 0.6f; constexpr std::uint8_t SecondAlphaByte = 153u; +constexpr float FilledAlpha = 0.8f; +constexpr std::uint8_t FilledAlphaByte = 204u; +constexpr std::size_t FillSource = 512; alignas(4096) std::array BufferMemory{}; +alignas(4096) std::array OtherMemory{}; +constexpr std::size_t OtherSlices = 1024; + +float* SliceAt(std::size_t slice) { + return slice >= OtherSlices ? OtherMemory.data() + (slice - OtherSlices) : BufferMemory.data() + slice; +} + +std::size_t SliceBytes(std::size_t slice) { + return (slice >= OtherSlices ? sizeof(OtherMemory) - (slice - OtherSlices) * sizeof(float) : sizeof(BufferMemory) - slice * sizeof(float)); +} alignas(256) std::array ColorMemory{}; std::span MergedTarget(std::size_t index) { @@ -227,7 +240,7 @@ std::array BufferDescriptor(const void* memory, std::size_t by alignas(256) std::array SampledTexture{}; -std::vector Frame(std::span slices) { +std::vector Frame(std::span slices, std::optional filled = std::nullopt) { const auto color = reinterpret_cast(MergedTarget(0).data()); const std::vector> context{ {0x2d5, 0x2000}, @@ -296,10 +309,15 @@ std::vector Frame(std::span slices) { Append(commands, 0x76, {0x8c, 0}); const auto pixel = reinterpret_cast(BufferPixelCode.data()); for (const auto slice : slices) { + if (filled.has_value() && slice == *filled) { + const auto source = reinterpret_cast(BufferMemory.data() + FillSource); + const auto destination = reinterpret_cast(SliceAt(slice)); + Append(commands, 0x50, {0u, static_cast(source), static_cast(source >> 32u), static_cast(destination), static_cast(destination >> 32u), 16u}); + } std::array words{}; const auto image = ImageDescriptor(SampledTexture.data()); std::copy(image.begin(), image.end(), words.begin()); - const auto descriptor = BufferDescriptor(BufferMemory.data() + slice, sizeof(BufferMemory) - slice * sizeof(float)); + const auto descriptor = BufferDescriptor(SliceAt(slice), SliceBytes(slice)); std::copy(descriptor.begin(), descriptor.end(), words.begin() + 12); Append(commands, 0x76, {0x008, static_cast(pixel >> 8u)}); Append(commands, 0x76, {0x009, static_cast(pixel >> 40u)}); @@ -319,9 +337,9 @@ unsigned DrawnAlpha() { throw std::runtime_error("the draws covered no pixel"); } -unsigned Submit(std::span slices) { +unsigned Submit(std::span slices, std::optional filled = std::nullopt) { std::ranges::fill(MergedTarget(0), Kept); - auto commands = Frame(slices); + auto commands = Frame(slices, filled); Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); AgcDriverWaitIdle_nid_postfix(); @@ -339,6 +357,7 @@ int main() { { GuestAllocations::Mutation mutation; mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); + mutation.Add(OtherMemory.data(), sizeof(OtherMemory), true, true, true); } for (std::size_t offset = 0; offset < SampledTexture.size(); offset += Texel.size()) std::memcpy(SampledTexture.data() + offset, Texel.data(), Texel.size()); BufferMemory.fill(0.0f); @@ -368,12 +387,34 @@ int main() { for (int round = 0; round < 3; ++round) Require(Submit(unmoved) == BufferAlphaByte, "the draw of the template's own buffer did not read it"); const std::array movedOnly{Moved}; for (int round = 0; round < 3; ++round) Require(Submit(movedOnly) == SecondAlphaByte, "a draw whose buffer moved after a recipe without moves was recorded did not read the moved buffer"); + std::fill(BufferMemory.begin() + FillSource, BufferMemory.begin() + FillSource + 4, FilledAlpha); + const auto behindBefore = AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites(); constexpr std::size_t Aligned = First + 64; const std::array alignedSlices{First, Aligned}; BufferMemory[Aligned] = SecondAlpha; - const auto alignedAlpha = Submit(alignedSlices); - Require(alignedAlpha == SecondAlphaByte, "a draw whose buffer moved by a whole number of 256-byte blocks drew another buffer's contents (alpha " + std::to_string(alignedAlpha) + ")"); + const auto cpuAlpha = Submit(alignedSlices); + Require(cpuAlpha == SecondAlphaByte, "a draw whose buffer moved by a whole number of 256-byte blocks drew another buffer's contents (alpha " + std::to_string(cpuAlpha) + ")"); BufferMemory[Aligned] = 0.0f; + const auto alignedAlpha = Submit(alignedSlices, Aligned); + Require(alignedAlpha == FilledAlphaByte, "a draw whose buffer moved onto a range a GPU copy wrote earlier in its batch did not read the copied value (alpha " + std::to_string(alignedAlpha) + ")"); + if (AgcDriver::Graphics::DescriptorHeapEnabled()) + Require(AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites() > behindBefore, "a heap draw whose buffer moved onto a range with a pending GPU write did not reuse its template by reading the buffer in place"); + std::fill(BufferMemory.begin() + Aligned, BufferMemory.begin() + Aligned + 4, 0.0f); + constexpr std::size_t Elsewhere = OtherSlices + First; + const std::array elsewhereSlices{First, Elsewhere}; + const auto elsewhereBefore = AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites(); + const auto elsewhereAlpha = Submit(elsewhereSlices, Elsewhere); + Require(elsewhereAlpha == FilledAlphaByte, "a draw whose buffer moved into other guest memory a GPU copy wrote earlier in its batch did not read the copied value (alpha " + std::to_string(elsewhereAlpha) + ")"); + if (AgcDriver::Graphics::DescriptorHeapEnabled()) + Require(AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites() > elsewhereBefore, "a heap draw whose buffer moved into other guest memory with a pending GPU write did not reuse its template by reading the buffer in place"); + OtherMemory.fill(0.0f); + constexpr std::size_t Shifted = Elsewhere + 1; + const std::array shiftedSlices{First, Shifted}; + const auto shiftedBefore = AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites(); + const auto shiftedAlpha = Submit(shiftedSlices, Shifted); + Require(shiftedAlpha == FilledAlphaByte, "a draw whose buffer moved to another view alignment behind a GPU copy did not read the copied value (alpha " + std::to_string(shiftedAlpha) + ")"); + Require(AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites() == shiftedBefore, "a draw whose buffer moved to another view alignment was read in place through its template's view"); + OtherMemory.fill(0.0f); std::puts("draws whose read-only buffer moved from their template's replayed recipes that read the buffer's current contents"); AgcDriverShutdown_nid_postfix(); return 0; From 9c788bbfcbab11a7f45bd96c02e7cfb3d353487c Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 9 Nov 2026 02:12:50 +0530 Subject: [PATCH 156/269] perf(agc): trim per-draw bookkeeping on the heap draw paths - The resource cache counts the entries a window used with a stamp on each entry instead of hashing the whole key on every lookup. - Push data keeps which BDA roots a stage set binds, and the pushed buffer ranges of a stage whose addresses cannot change, instead of rebuilding them per draw. - The pending GPU write snapshot is reloaded only after a publish, so a reader takes no lock while none ran. - A heap stage's read ranges check their stamps under one tracker lock, and a walk memo hit shares its read values instead of copying them. - The heap mappability check keeps its recent answers in a small array in front of its map. --- .../include/Driver/Draw/HeapStages.hpp | 2 +- .../include/Driver/Draw/HeapWalkMemo.hpp | 2 +- .../Execution/include/GuestMemory.hpp | 1 + .../Execution/src/Driver/Draw/DrawCapture.cpp | 2 +- .../Execution/src/Driver/Draw/HeapStages.cpp | 39 ++++++--- .../Execution/src/GuestMemory.cpp | 8 ++ .../Graphics/include/ShaderResources.hpp | 27 +++++- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 27 ++++-- .../Graphics/src/ShaderResources.cpp | 85 ++++++++++++++----- .../tests/CollectMemoGeneration.cpp | 16 ++++ .../libSceAgcDriver/tests/HeapWalkMemo.cpp | 7 +- 11 files changed, 167 insertions(+), 49 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index df5e25718dab..d6c1eea65869 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -27,7 +27,7 @@ bool SampleHeapStageVerify(); struct HeapStageReads { std::vector> ranges; - std::vector values; + std::shared_ptr> values; ShaderRecompiler::SrtUserDataUse userDataUse; std::shared_ptr capture; bool complete = false; diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp index 952b0228c8b3..fbc7d4addaa3 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp @@ -18,7 +18,7 @@ struct HeapWalkEntry { std::vector userData; std::vector merges; std::vector> ranges; - std::vector values; + std::shared_ptr> values; std::vector> accessible; ShaderRecompiler::SrtUserDataUse userDataUse; std::shared_ptr capture; diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp index 52ee2f11d9cc..37eab2507038 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp @@ -132,6 +132,7 @@ std::uint64_t CollectWritesUncached(std::uint64_t address, std::size_t bytes); std::uint64_t TrackerGeneration(); void AdvanceTrackerGenerationForTest(std::uint64_t generation); std::uint64_t NewestStamp(std::uint64_t address, std::size_t bytes); +bool NoStampAfter(std::span> ranges, std::uint64_t generation); std::uint64_t UntrackedHint(std::uint64_t address, std::size_t bytes); // Whether no CPU write touched the range since `generation`: an uncached resetting collect of the // range's pages first (a game store not collected yet becomes a block stamp), then the compare over diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 6ce5a73e4caf..884703374b69 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -111,7 +111,7 @@ bool Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t stageCapture.direct = true; auto& reads = materialized.reads; if (reads.complete) { - auto owned = std::make_shared>(std::move(reads.values)); + auto owned = std::move(reads.values); std::size_t cursor = 0; for (const auto& [begin, end] : reads.ranges) { const auto count = static_cast((end - begin) / sizeof(std::uint32_t)); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 5892f5e2b9d0..67a813c4da40 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -8,6 +8,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include "prx/libc/include/HostThreadLocal.hpp" #include +#include #include #include #include @@ -218,11 +219,27 @@ std::string heapStageFailure(const ShaderRecompiler::RecompileResult& result, bo const std::string& knownHeapStageFailure(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { struct MappableStorage {}; + struct RecentStorage {}; + struct Recent { + std::uint64_t key = 0; + const std::string* failure = nullptr; + }; + constexpr std::size_t RecentSlots = 64; auto& known = HostThreadLocal, MappableStorage>(); + auto& recent = HostThreadLocal, RecentStorage>(); const auto key = result.variantId * 2u + (workgroupAddress ? 1u : 0u); - if (const auto found = known.find(key); found != known.end()) return found->second; - if (known.size() >= ThreadCacheLimit) known.clear(); - return known.emplace(key, heapStageFailure(result, workgroupAddress)).first->second; + auto& slot = recent[(key ^ (key >> 17u)) % RecentSlots]; + if (slot.failure != nullptr && slot.key == key) return *slot.failure; + auto found = known.find(key); + if (found == known.end()) { + if (known.size() >= ThreadCacheLimit) { + known.clear(); + recent.fill({}); + } + found = known.emplace(key, heapStageFailure(result, workgroupAddress)).first; + } + slot = {key, &found->second}; + return found->second; } } @@ -333,7 +350,7 @@ std::uint64_t HeapWalkWordsBytes(const ShaderRecompiler::HeapStageWords& words) } std::uint64_t HeapWalkEntryOwnBytes(const HeapWalkEntry& entry) { - return sizeof(HeapWalkEntry) + vectorBytes(entry.userData) + vectorBytes(entry.ranges) + vectorBytes(entry.values) + + return sizeof(HeapWalkEntry) + vectorBytes(entry.userData) + vectorBytes(entry.ranges) + (entry.values != nullptr ? vectorBytes(*entry.values) : 0u) + vectorBytes(entry.accessible) + vectorBytes(entry.userDataUse.reads) + vectorBytes(entry.merges); } @@ -449,10 +466,7 @@ void copyRangeValues(const AddressRanges& ranges, std::vector& va bool rangesSettled(const AddressRanges& ranges, const Graphics::Recorder::WriteRanges* before, std::uint64_t generation) { const bool queuedWrite = DrawPipeline::Active() && DrawPipeline::Queue0().Busy() && DrawPipeline::Queue0().OverlapsAny(ranges); if (queuedWrite || !Graphics::Recorder::ReadsSettled(ranges, before)) return false; - for (const auto& [begin, end] : ranges) { - if (GuestMemory::NewestStamp(begin, static_cast(end - begin)) > generation) return false; - } - return true; + return GuestMemory::NoStampAfter(ranges, generation); } void guardRanges(const AddressRanges& ranges) { @@ -482,7 +496,7 @@ bool sameWalkInputs(const HeapWalkEntry& entry, const ShaderRecompiler::Prepared std::size_t cursor = 0; for (const auto& [begin, end] : entry.ranges) { const auto count = static_cast((end - begin) / WordBytes); - if (GuestMemory::CompareMapped(begin, std::as_bytes(std::span(entry.values.data() + cursor, count))) != GuestMemory::Compare::Equal) + if (GuestMemory::CompareMapped(begin, std::as_bytes(std::span(entry.values->data() + cursor, count))) != GuestMemory::Compare::Equal) return false; cursor += count; } @@ -498,7 +512,7 @@ void noteMemoBytes(const HeapWalkMemo& memo, std::uint64_t heldBefore) { void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase, const AddressRanges& ranges, - const std::vector& values, const AddressRanges& accessible, + const std::shared_ptr>& values, const AddressRanges& accessible, const std::shared_ptr& capture, const std::shared_ptr& result, const ShaderRecompiler::HeapStageWords& words) { HeapWalkEntry entry; @@ -609,10 +623,11 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade materializeCost.Stop(); const bool complete = !reads.failed && result != nullptr; HeapStageMaterialized materialized; - if (complete) materialized.reads = {ranges, values, capture->userDataUse, capture, true}; + auto shared = complete ? std::make_shared>(values) : nullptr; + if (complete) materialized.reads = {ranges, shared, capture->userDataUse, capture, true}; Graphics::HeapCostScope insertCost(Graphics::HeapCost::MemoInsert); if (memoOn && complete && (memoKnown || heapWalkMemo().admit(memoKey))) - rememberWalk(memoKey, invocation, userData, shaderBase, ranges, values, reads.accessible, capture, result, *words); + rememberWalk(memoKey, invocation, userData, shaderBase, ranges, shared, reads.accessible, capture, result, *words); materialized.result = std::move(result); materialized.words = std::move(words); return materialized; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp index 0040aa5cdb2e..177da93342cf 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp @@ -2413,6 +2413,14 @@ std::uint64_t NewestStamp(std::uint64_t address, std::size_t bytes) { return bytes == 0 ? 0 : tracker.newestStamp(address, address + bytes); } +bool NoStampAfter(std::span> ranges, std::uint64_t generation) { + if (ranges.empty()) return true; + auto& tracker = Tracker(); + const auto lock = lockTracker(tracker); + tracker.initialize(); + return std::none_of(ranges.begin(), ranges.end(), [&](const auto& range) { return range.second > range.first && tracker.newestStamp(range.first, range.second) > generation; }); +} + #ifdef _WIN32 namespace { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index dbb4fa52af2d..2d39f3765b3c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -381,6 +381,20 @@ class ShaderResources { void PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const; void writePushedData(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const; void writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const; + bool constantBufferRanges(std::uint32_t dataStage) const; + struct PushedRanges { + bool built = false; + bool constant = false; + std::vector ranges; + }; + mutable std::array pushedRanges; + struct RootRoles { + std::array programs{}; + std::size_t count = std::numeric_limits::max(); + bool table = false; + bool fault = false; + }; + mutable RootRoles rootRoles; // Whether RefreshData would record anything for `shader` (the per-word compare; verification). bool DataWordsDiffer(const CompiledShader& shader) const; std::size_t BindingCount() const { return bindings.size(); } @@ -901,7 +915,13 @@ class ResourceCache { void dropReleasedTextures(std::vector>* evicted); void noteEvicted(const Key& key); void noteReturn(const Key& key); - void noteUse(const Key& key); + struct Entry { + Key first; + std::shared_ptr second; + std::uint64_t usedWindow = 0; + }; + void noteUse(Entry& entry); + void resetUses(); void removeImage(const StorageTexture* image, std::vector>* evicted); struct KeyHash { std::size_t operator()(const Key& key) const noexcept { @@ -928,7 +948,7 @@ class ResourceCache { } }; mutable AgcDriver::Mutex mutex; - std::list>> entries; + std::list entries; std::unordered_map index; std::size_t capacity = 0; bool fixedCapacity = false; @@ -936,7 +956,8 @@ class ResourceCache { std::unordered_map evictedKeys; std::size_t evictionsSinceCheck = 0; std::size_t returnsSinceCheck = 0; - std::unordered_set usedKeys; + std::uint64_t useWindow = 1; + std::size_t usedEntries = 0; std::size_t usesSinceCheck = 0; static constexpr std::size_t InitialShrinkWindow = 8; static constexpr std::size_t MaximumShrinkWindow = 1024; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 8421aa7d0ae3..4420430f819c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -670,6 +670,21 @@ using WriteRanges = Recorder::WriteRanges; // GPU) or follows the write-back. AtomicSharedPtr pendingWrites; +struct PendingWritesSeen { + std::uint64_t generation = std::numeric_limits::max(); + std::shared_ptr ranges; +}; + +const std::shared_ptr& currentPendingWrites() { + auto& seen = HostThreadLocal(); + const auto generation = publishGeneration.load(std::memory_order_acquire); + if (generation != seen.generation) { + seen.ranges = pendingWrites.load(std::memory_order_acquire); + seen.generation = generation; + } + return seen.ranges; +} + bool HookSnapshotEnabled() { // Debug aid: APS5_NO_HOOK_SNAPSHOT=1 takes the GpuMutex on every access as before. static const bool enabled = std::getenv("APS5_NO_HOOK_SNAPSHOT") == nullptr; @@ -685,8 +700,7 @@ bool SnapshotOverlaps(const WriteRanges* snapshot, std::uint64_t address, std::s bool SnapshotOverlaps(std::uint64_t address, std::size_t bytes) { if (bytes == 0) return false; - const auto snapshot = pendingWrites.load(std::memory_order_acquire); - return SnapshotOverlaps(snapshot.get(), address, bytes); + return SnapshotOverlaps(currentPendingWrites().get(), address, bytes); } } @@ -694,11 +708,11 @@ bool SnapshotOverlaps(std::uint64_t address, std::size_t bytes) { bool Recorder::ReadsSettled(std::span> ranges, const WriteRanges* before) { if (!HookSnapshotEnabled()) return false; const bool labels = !QueuedLabelRanges().empty(); - const auto now = pendingWrites.load(std::memory_order_acquire); + const auto* now = currentPendingWrites().get(); for (const auto& [begin, end] : ranges) { const auto bytes = static_cast(end - begin); if (labels && QueuedLabelOverlaps(begin, bytes)) return false; - if (AgcDriver::Graphics::SnapshotOverlaps(before, begin, bytes) || AgcDriver::Graphics::SnapshotOverlaps(now.get(), begin, bytes)) return false; + if (AgcDriver::Graphics::SnapshotOverlaps(before, begin, bytes) || AgcDriver::Graphics::SnapshotOverlaps(now, begin, bytes)) return false; } return !StorageTexture::AnyPendingOverlaps(ranges) && !AnyShadowedOverlaps(ranges); } @@ -713,8 +727,7 @@ bool SnapshotCovers(const WriteRanges* snapshot, std::uint64_t address, std::uin } bool SnapshotCovers(std::uint64_t address, std::uint64_t end) { - const auto snapshot = pendingWrites.load(std::memory_order_acquire); - return SnapshotCovers(snapshot.get(), address, end); + return SnapshotCovers(currentPendingWrites().get(), address, end); } // Attribution of the pending-write syncs the hook makes (the [hooksync] line every 10 s, under @@ -1809,7 +1822,7 @@ bool Recorder::SnapshotWriteOverlaps(std::uint64_t address, std::size_t bytes) { } std::shared_ptr Recorder::PendingWriteSnapshot() { - return pendingWrites.load(std::memory_order_acquire); + return currentPendingWrites(); } bool Recorder::SnapshotOverlaps(const WriteRanges* snapshot, std::uint64_t address, std::size_t bytes) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 5e3d1ad63cea..29f96657bf46 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -4377,7 +4377,7 @@ std::shared_ptr ResourceCache::Find(const Key& key) { return nullptr; } entries.splice(entries.begin(), entries, found->second); - noteUse(key); + noteUse(*found->second); return found->second->second; } @@ -4401,20 +4401,27 @@ void ResourceCache::noteEvicted(const Key& key) { publishAgingWindow(); if (shrankLast) shrinkWindow = std::min(shrinkWindow * 2u, MaximumShrinkWindow); shrankLast = false; - usedKeys.clear(); - usesSinceCheck = 0; + resetUses(); usesWindowStart.store(operations.load(std::memory_order_relaxed), std::memory_order_relaxed); std::fprintf(stderr, "[rescache] capacity %zu -> %zu entries: keys it evicted keep coming back\n", previous, capacity); } -void ResourceCache::noteUse(const Key& key) { +void ResourceCache::resetUses() { + ++useWindow; + usedEntries = 0; + usesSinceCheck = 0; +} + +void ResourceCache::noteUse(Entry& entry) { if (fixedCapacity || capacity <= baseEntries) return; - usedKeys.insert(KeyHash{}(key)); + if (entry.usedWindow != useWindow) { + entry.usedWindow = useWindow; + ++usedEntries; + } if (++usesSinceCheck < capacity * shrinkWindow) return; - const auto used = usedKeys.size(); + const auto used = usedEntries; const auto uses = usesSinceCheck; - usedKeys.clear(); - usesSinceCheck = 0; + resetUses(); usesWindowStart.store(operations.load(std::memory_order_relaxed), std::memory_order_relaxed); if (used * 4u > capacity) return; const auto previous = capacity; @@ -4571,7 +4578,7 @@ void ResourceCache::Insert(const Key& key, std::shared_ptr reso entries.erase(found->second); index.erase(found); } - entries.emplace_front(key, std::move(resources)); + entries.push_front({key, std::move(resources)}); index.emplace(key, entries.begin()); if (capacity == 0) { const char* value = std::getenv("APS5_RESOURCE_CACHE_ENTRIES"); @@ -4580,7 +4587,7 @@ void ResourceCache::Insert(const Key& key, std::shared_ptr reso capacity = fixedCapacity ? static_cast(parsed) : baseEntries; publishAgingWindow(); } - noteUse(key); + noteUse(entries.front()); while (entries.size() > capacity) { noteEvicted(entries.back().first); if (evicted != nullptr) evicted->push_back(std::move(entries.back().second)); @@ -4668,7 +4675,7 @@ bool ResourceCache::Touch(const Key& key) { const auto found = index.find(key); if (found == index.end()) return false; entries.splice(entries.begin(), entries, found->second); - noteUse(key); + noteUse(*found->second); return true; } @@ -4688,8 +4695,7 @@ void ResourceCache::Clear() { evictedOrder.clear(); evictionsSinceCheck = 0; returnsSinceCheck = 0; - usedKeys.clear(); - usesSinceCheck = 0; + resetUses(); usesWindowStart.store(operations.load(std::memory_order_relaxed), std::memory_order_relaxed); shrinkWindow = baseShrinkWindow; shrankLast = false; @@ -6829,6 +6835,15 @@ void ShaderResources::bufferRanges(std::uint32_t dataStage, const std::vector= addressedElements.size()) return true; + return std::all_of(addressedElements[dataStage].begin(), addressedElements[dataStage].end(), [&](std::size_t index) { + const auto& allocation = allocations[index]; + const bool owned = !allocation.guest && allocation.buffer != nullptr && allocation.role != ShaderRecompiler::DescriptorRole::GuestBuffers && allocation.role != ShaderRecompiler::DescriptorRole::BdaPagetable && allocation.role != ShaderRecompiler::DescriptorRole::FaultBuffer; + return owned || (index < resolvedAddresses.size() && resolvedAddresses[index].address != 0); + }); +} + std::pair ShaderResources::shaderDataLocation(const CompiledShader& shader, const DrawBindings* rewritten) const { if (!heapStage || !HeapShader(shader)) return {shaderDataBuffer(shader), 0}; const auto& offsets = rewritten != nullptr && rewritten->addressOffsets ? rewritten->heapOffsets : heapOffsets; @@ -6843,11 +6858,25 @@ void ShaderResources::PatchDataAddresses(std::spanbindings.begin(), shader.program->bindings.end(), [&](const auto& binding) { return binding.role == role; }); }); - }; - const bool tableBound = binds(ShaderRecompiler::DescriptorRole::BdaPagetable); - const bool faultBound = binds(ShaderRecompiler::DescriptorRole::FaultBuffer); + const bool sameStages = rootRoles.count == shaders.size() && std::equal(shaders.begin(), shaders.end(), rootRoles.programs.begin(), [](const CompiledShader& shader, const ShaderRecompiler::RecompileResult* program) { return shader.program == program; }); + if (!sameStages) { + const auto binds = [&](ShaderRecompiler::DescriptorRole role) { + return std::any_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [&](const auto& binding) { return binding.role == role; }); }); + }; + rootRoles.table = binds(ShaderRecompiler::DescriptorRole::BdaPagetable); + rootRoles.fault = binds(ShaderRecompiler::DescriptorRole::FaultBuffer); + rootRoles.count = shaders.size() <= rootRoles.programs.size() ? shaders.size() : std::numeric_limits::max(); + for (std::size_t index = 0; index < shaders.size() && index < rootRoles.programs.size(); ++index) rootRoles.programs[index] = shaders[index].program; + } + static const bool verifyRoles = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + if (verifyRoles && sameStages) { + const auto binds = [&](ShaderRecompiler::DescriptorRole role) { + return std::any_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [&](const auto& binding) { return binding.role == role; }); }); + }; + if (binds(ShaderRecompiler::DescriptorRole::BdaPagetable) != rootRoles.table || binds(ShaderRecompiler::DescriptorRole::FaultBuffer) != rootRoles.fault) throw std::runtime_error("AGC graphics: the BDA roots kept for a GPU heap draw's stages differ from their bindings"); + } + const bool tableBound = rootRoles.table; + const bool faultBound = rootRoles.fault; if (bda != nullptr && (tableBound || faultBound)) { if (tableBound) { table = bda->TableAddress(); @@ -6903,10 +6932,24 @@ void ShaderResources::PatchDataAddresses(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const { namespace Abi = ShaderRecompiler::RuntimeAbi; + static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + const std::vector* kept = nullptr; + if (overrides == nullptr && !verify) { + auto& cached = pushedRanges[stage]; + if (!cached.built) { + cached.constant = constantBufferRanges(static_cast(stage)); + cached.built = cached.constant || !resolvedAddresses.empty(); + if (cached.constant) bufferRanges(static_cast(stage), nullptr, cached.ranges); + } + if (cached.constant) kept = &cached.ranges; + } struct RangeStorage {}; - auto& ranges = HostThreadLocal, RangeStorage>(); - ranges.clear(); - bufferRanges(static_cast(stage), overrides, ranges); + auto& scratch = HostThreadLocal, RangeStorage>(); + if (kept == nullptr) { + scratch.clear(); + bufferRanges(static_cast(stage), overrides, scratch); + } + const auto& ranges = kept != nullptr ? *kept : scratch; Require(ranges.size() == placement.pushedBuffers, "a stage's buffer addresses do not match its push layout's buffer count"); heapPushedStages.fetch_add(1, std::memory_order_relaxed); Require(empty != 0u, "a stage with pushed buffers has no shader data to stand in for an empty buffer"); diff --git a/core/libs/prx/libSceAgcDriver/tests/CollectMemoGeneration.cpp b/core/libs/prx/libSceAgcDriver/tests/CollectMemoGeneration.cpp index 3c03b56d15b5..292c9eff925c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/CollectMemoGeneration.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/CollectMemoGeneration.cpp @@ -2,6 +2,7 @@ #include "prx/libc/include/GuestArena.hpp" #include "prx/libc/include/GuestWriteWatch.hpp" #include +#include #include #include #include @@ -240,6 +241,20 @@ void CheckThreadWithoutEpochWalksEveryTime() { Require(first && second, "a thread that never bumped its epoch reused an entry"); } +void CheckNoStampAfterCoversEveryRange() { + BumpCollectEpoch(); + const auto probe = Base + 11 * Page + 16; + const auto before = TrackerGeneration(); + Store(probe); + Require(CollectWrites(probe & ~(Page - 1), Page) != 0, "a collect failed"); + Require(NewestStamp(probe, 4) > before, "a collected store left no stamp after the generation"); + const std::array, 2> stored{{{Base + 12 * Page, Base + 12 * Page}, {probe, probe + 4}}}; + Require(!NoStampAfter(stored, before), "a range stored after the generation counted as settled"); + const std::array, 2> quiet{{{probe, probe}, {Base + 100 * Block, Base + 100 * Block + 4}}}; + Require(NoStampAfter(quiet, before), "an empty or untouched range counted as stored after the generation"); + Require(NoStampAfter({}, before), "no ranges counted as stored after the generation"); +} + void CheckStoreInNewEpochIsFound() { BumpCollectEpoch(); const auto address = Base + 7 * Page + 8; @@ -267,6 +282,7 @@ int main() { CheckNeighbouringBlockStoreIsFound(); CheckInvalidationReachesBlockKeyedEntry(); CheckThreadWithoutEpochWalksEveryTime(); + CheckNoStampAfterCoversEveryRange(); CheckStoreInNewEpochIsFound(); } catch (const std::exception& error) { std::cerr << "collect memo generation test failed: " << error.what() << "\n"; diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp index a1cd55a36bee..1ff947209baf 100644 --- a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp @@ -22,8 +22,9 @@ void require(bool condition, const std::string& message) { HeapWalkEntry sizedEntry(std::size_t words, std::shared_ptr result = nullptr) { HeapWalkEntry entry; - entry.values.resize(words); - entry.values.shrink_to_fit(); + std::vector values(words); + values.shrink_to_fit(); + entry.values = std::make_shared>(std::move(values)); entry.result = std::move(result); return entry; } @@ -68,7 +69,7 @@ void oldestEntriesDroppedTests() { require(memo.find(1) == nullptr && memo.find(keys / 2) == nullptr, "the oldest heap walk entries stayed past the budget"); require(results.front().expired() && results[keys / 2 - 1].expired(), "a heap walk entry the budget dropped still holds its result"); const auto* newest = memo.find(keys); - require(newest != nullptr && newest->size() == 1 && newest->front().values.size() == words, "the newest heap walk entry is not findable under the budget"); + require(newest != nullptr && newest->size() == 1 && newest->front().values->size() == words, "the newest heap walk entry is not findable under the budget"); require(!results.back().expired(), "the newest heap walk entry lost its result"); std::cout << "the heap walk memo keeps " << memo.current.size() << " of " << keys << " entries within its budget of " << memo.budget << " bytes\n"; } From e62ad06063e6e8ff4123165a7f295eb213e8ceac Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 9 Nov 2026 02:18:35 +0530 Subject: [PATCH 157/269] perf(agc): share a heap walk's read ranges between the memo and the draw A walk memo hit copied the walk's read ranges into the draw's reads; the memo and the draw now hold the same ranges, as they hold its values. --- .../Execution/include/Driver/Draw/HeapStages.hpp | 2 +- .../include/Driver/Draw/HeapWalkMemo.hpp | 2 +- .../Execution/src/Driver/Draw/DrawCapture.cpp | 2 +- .../Execution/src/Driver/Draw/HeapStages.cpp | 15 ++++++++------- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index d6c1eea65869..89fbf66b86b7 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -26,7 +26,7 @@ bool HeapStageFits(const ShaderRecompiler::RecompileResult& result, bool workgro bool SampleHeapStageVerify(); struct HeapStageReads { - std::vector> ranges; + std::shared_ptr>> ranges; std::shared_ptr> values; ShaderRecompiler::SrtUserDataUse userDataUse; std::shared_ptr capture; diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp index fbc7d4addaa3..c70fb8154ed3 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp @@ -17,7 +17,7 @@ struct HeapWalkEntry { std::uint32_t pushOffset = 0; std::vector userData; std::vector merges; - std::vector> ranges; + std::shared_ptr>> ranges; std::shared_ptr> values; std::vector> accessible; ShaderRecompiler::SrtUserDataUse userDataUse; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 884703374b69..22aa983526bb 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -113,7 +113,7 @@ bool Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t if (reads.complete) { auto owned = std::move(reads.values); std::size_t cursor = 0; - for (const auto& [begin, end] : reads.ranges) { + for (const auto& [begin, end] : *reads.ranges) { const auto count = static_cast((end - begin) / sizeof(std::uint32_t)); stageCapture.regions.push_back({begin, std::as_bytes(std::span(owned->data() + cursor, count))}); cursor += count; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 67a813c4da40..e02b2c3b6f3f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -350,7 +350,7 @@ std::uint64_t HeapWalkWordsBytes(const ShaderRecompiler::HeapStageWords& words) } std::uint64_t HeapWalkEntryOwnBytes(const HeapWalkEntry& entry) { - return sizeof(HeapWalkEntry) + vectorBytes(entry.userData) + vectorBytes(entry.ranges) + (entry.values != nullptr ? vectorBytes(*entry.values) : 0u) + + return sizeof(HeapWalkEntry) + vectorBytes(entry.userData) + (entry.ranges != nullptr ? vectorBytes(*entry.ranges) : 0u) + (entry.values != nullptr ? vectorBytes(*entry.values) : 0u) + vectorBytes(entry.accessible) + vectorBytes(entry.userDataUse.reads) + vectorBytes(entry.merges); } @@ -494,7 +494,7 @@ bool sameWalkInputs(const HeapWalkEntry& entry, const ShaderRecompiler::Prepared if (!sameStage || !std::equal(entry.userData.begin(), entry.userData.end(), userData.begin(), userData.end())) return false; if (!std::ranges::equal(entry.merges, targetMerges(invocation))) return false; std::size_t cursor = 0; - for (const auto& [begin, end] : entry.ranges) { + for (const auto& [begin, end] : *entry.ranges) { const auto count = static_cast((end - begin) / WordBytes); if (GuestMemory::CompareMapped(begin, std::as_bytes(std::span(entry.values->data() + cursor, count))) != GuestMemory::Compare::Equal) return false; @@ -511,7 +511,7 @@ void noteMemoBytes(const HeapWalkMemo& memo, std::uint64_t heldBefore) { } void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderInvocation& invocation, - std::span userData, std::uint64_t shaderBase, const AddressRanges& ranges, + std::span userData, std::uint64_t shaderBase, const std::shared_ptr& ranges, const std::shared_ptr>& values, const AddressRanges& accessible, const std::shared_ptr& capture, const std::shared_ptr& result, const ShaderRecompiler::HeapStageWords& words) { @@ -546,9 +546,9 @@ bool adoptWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderInvo for (std::size_t way = 0; found != nullptr && way < found->size(); ++way) { auto& entry = (*found)[way]; if (!sameWalkInputs(entry, invocation, userData, shaderBase)) continue; - if (!rangesSettled(entry.ranges, before, generation)) break; + if (!rangesSettled(*entry.ranges, before, generation)) break; memo.touch(entry); - guardRanges(entry.ranges); + guardRanges(*entry.ranges); adopted.words = entry.words; adopted.reads = {entry.ranges, entry.values, entry.userDataUse, entry.capture, true}; adopted.result = entry.result; @@ -624,10 +624,11 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade const bool complete = !reads.failed && result != nullptr; HeapStageMaterialized materialized; auto shared = complete ? std::make_shared>(values) : nullptr; - if (complete) materialized.reads = {ranges, shared, capture->userDataUse, capture, true}; + auto sharedRanges = complete ? std::make_shared(ranges) : nullptr; + if (complete) materialized.reads = {sharedRanges, shared, capture->userDataUse, capture, true}; Graphics::HeapCostScope insertCost(Graphics::HeapCost::MemoInsert); if (memoOn && complete && (memoKnown || heapWalkMemo().admit(memoKey))) - rememberWalk(memoKey, invocation, userData, shaderBase, ranges, shared, reads.accessible, capture, result, *words); + rememberWalk(memoKey, invocation, userData, shaderBase, sharedRanges, shared, reads.accessible, capture, result, *words); materialized.result = std::move(result); materialized.words = std::move(words); return materialized; From 295b7466926e06f586e5c71cd12293c758228669 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 9 Nov 2026 17:53:09 +0530 Subject: [PATCH 158/269] fix(agc): time the GPU heap's phases only under APS5_PIPELINE_STATS=2 APS5_PIPELINE_STATS=1 timed every heap stage phase with two clock reads, about 8 million timers per 10 s in GTA V. Heap off has no such timers, so every heap on/off pair run with stats charged the heap side about 1 ms per frame of timer overhead (0.4 ms of it on the committer). --- .../libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp | 7 ++++++- docs/dev/ENVIRONMENT.md | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index b847ed5ae4d4..d43bf4511043 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -1391,7 +1392,11 @@ void NoteHeapStageReason(HeapStageReason reason) { } bool HeapCostTimed() { - return pipelineStats(); + static const bool timed = [] { + const char* stats = std::getenv("APS5_PIPELINE_STATS"); + return stats != nullptr && std::string_view(stats) == "2"; + }(); + return timed; } void NoteHeapCost(HeapCost cost, std::uint64_t nanoseconds) { diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index f9c70c4935f5..a2a4bea4bf75 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -431,7 +431,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_PIPELINE_JOURNAL_ENTRIES` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp` | 4096 | number of graphics pipelines a replay builds at most, the last recorded; a log line names how many of each kind were left out | | `APS5_PIPELINE_JOURNAL_MAX_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp` | 1024 | size cap in MiB on the pipeline journal; the file is rewritten down to three quarters of the cap when it is reached, keeping the newest pipelines and the modules they name and leaving room for later records | | `APS5_PIPELINE_JOURNAL_THREADS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp` | | threads that replay the journal's pipelines, 0 disables the replay; unset uses half the hardware threads, at least one | -| `APS5_PIPELINE_STATS` | string | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | captures and prints driver statistics for each new pipeline, requiring `VK_KHR_pipeline_executable_properties`; `1` enables | +| `APS5_PIPELINE_STATS` | string | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | captures and prints driver statistics for each new pipeline, requiring `VK_KHR_pipeline_executable_properties`; `1` enables, and `2` also times the GPU heap's per-stage phases in the 10 s `[gpu-heap] cost` line | | `APS5_PIPELINE_STORE_ENTRIES` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp` | adaptive | fixes the LRU bound on the entries of the pipeline store, which otherwise starts at 1024 and doubles up to 4096 for a journal replay that does not fit and while evicted pipelines keep coming back; an entry is evicted only once no recorded draw holds it | | `APS5_PM4_RING` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Queues/SubmissionRing.cpp` | 16 | number of submissions the PM4 ring keeps for dumps, from 0 to 4096; 0 disables the ring | | `APS5_POLL_REAP` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp` | | reaps completions on every poll tick | From c21bf27f5b32903d1ed0dfa71db4b0be9141a290 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 9 Nov 2026 23:13:37 +0530 Subject: [PATCH 159/269] perf(agc): key a heap ring stage's resource-cache entry from its ring template A heap stage built from a ring template (a stage-data hit) gets a pooled, per-draw HeapStageWords that never memoizes its resource-cache content key, so DrawResourceKey rebuilt the key from the stage's words on every draw that missed its recipe. The heap part of that key holds only the program's template id and its GuestImages and GuestSamplers words, and a ring stage takes those from its ring template (buildRingWords copies only shader-data words per draw). The key is therefore the template's, and is now memoized on the template, the way a non-heap stage memoizes it on its program. Ring stages whose own words override an image or sampler binding still build the key per draw. Heap off is unchanged. Tested: agc_driver_heap_ring_draw_key (default, draw pipeline, plan verify and heap variants) repeats the bench's SRT draws with recipes off and requires the repeated heap draws to build almost no content keys; with the template memo disabled they built 1024 keys for 512 draws. --- .../libSceAgcDriver/Graphics/include/Draw.hpp | 1 + .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 34 +- .../agc_driver_heap_ring_draw_key_tests.cmake | 4 + .../tests/execution/HeapRingDrawKey.cpp | 394 ++++++++++++++++++ 4 files changed, 429 insertions(+), 4 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_ring_draw_key_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp index f4c584c2fe7b..f16410ee3180 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Draw.hpp @@ -127,6 +127,7 @@ struct DrawRecipeOutcome { DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, std::span snapshots, const DrawRecipe& recipe, const DrawTraceContext* trace = nullptr); // Whether recorded draws build recipes and draw-cache hits use them (APS5_NO_DRAW_RECIPE unset). bool DrawRecipes(); +std::uint64_t DrawContentKeysBuilt(); // How an indirect draw's records were read, for the [draws] line (APS5_PROFILE_DRAW): Gpu is // vkCmdDrawIndirect from the host import; every other value names why the CPU read them instead, diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 89493a82c53e..7f0ba502802f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1269,6 +1269,23 @@ bool MovableBuffers() { return enabled; } +std::atomic& drawContentKeysBuilt() { + static std::atomic built{0}; + return built; +} + +bool TemplateKeyWords(const CompiledShader& shader) { + const auto* heap = shader.heap; + if (heap == nullptr || heap->base == nullptr || shader.program->heapTemplateId == 0) return false; + const auto& bindings = shader.program->bindings; + for (std::size_t index = 0; index < bindings.size(); ++index) { + const auto role = bindings[index].role; + if (role != ShaderRecompiler::DescriptorRole::GuestImages && role != ShaderRecompiler::DescriptorRole::GuestSamplers) continue; + if (index < heap->bindings.size() && !heap->bindings[index].empty()) return false; + } + return true; +} + ResourceCache::Key DrawResourceKey(const Context& context, std::span shaders, const ColorTarget& target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::uint64_t indexBytes, bool ranges) { ResourceCache::Key key; key.reserve(256); @@ -1282,16 +1299,21 @@ ResourceCache::Key DrawResourceKey(const Context& context, std::spandrawKeyMemo.words : shader.program->drawKeyMemo.words; + const ShaderRecompiler::HeapStageWords* memoOwner = shader.heap; + if (memoOwner != nullptr && !memoOwner->memoizeKey && TemplateKeyWords(shader)) memoOwner = memoOwner->base.get(); + auto& memo = memoOwner != nullptr ? memoOwner->drawKeyMemo.words : shader.program->drawKeyMemo.words; const auto ownerId = shader.program->heapTemplateId != 0 ? shader.program->heapTemplateId : static_cast(reinterpret_cast(shader.program)); - const std::array owner{static_cast(ownerId), static_cast(ownerId >> 32u), - static_cast(shader.stage) | (shader.program->heapTemplateId != 0 ? 0x80000000u : 0u)}; + const auto variant = shader.program->PipelineVariantId(); + const std::array owner{static_cast(ownerId), static_cast(ownerId >> 32u), + static_cast(shader.stage) | (shader.program->heapTemplateId != 0 ? 0x80000000u : 0u), + static_cast(variant), static_cast(variant >> 32u)}; const std::size_t prefix = shader.heap != nullptr ? owner.size() : 0u; - const bool memoize = shader.heap == nullptr || shader.heap->memoizeKey; + const bool memoize = memoOwner == nullptr || memoOwner->memoizeKey; const auto words = memoize ? memo.load(std::memory_order_acquire) : nullptr; if (words != nullptr && words->size() >= prefix && std::equal(owner.begin(), owner.begin() + static_cast(prefix), words->begin())) { key.insert(key.end(), words->begin() + static_cast(prefix), words->end()); } else { + drawContentKeysBuilt().fetch_add(1, std::memory_order_relaxed); ShaderResources::AppendContentKey(shader, true, MovableBuffers(), key); if (memoize) { auto stored = std::make_shared>(owner.begin(), owner.begin() + static_cast(prefix)); @@ -1439,6 +1461,10 @@ void CountDrawSkip(DrawSkip kind, double us) { } +std::uint64_t DrawContentKeysBuilt() { + return drawContentKeysBuilt().load(std::memory_order_relaxed); +} + bool DrawRecipes() { static const bool noDrawRecipe = std::getenv("APS5_NO_DRAW_RECIPE") != nullptr; return !noDrawRecipe; diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_ring_draw_key_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_ring_draw_key_tests.cmake new file mode 100644 index 000000000000..5b04523b2510 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_ring_draw_key_tests.cmake @@ -0,0 +1,4 @@ +if(BUILD_TESTING) + agc_add_draw_pipeline_test(agc_driver_heap_ring_draw_key) + agc_add_gpu_heap_test(agc_driver_heap_ring_draw_key) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp new file mode 100644 index 000000000000..46a373e2ab6d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp @@ -0,0 +1,394 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::byte Kept{0x40}; +constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, + 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array ConstantSamplerPixelCode{ + 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array BorderSamplerPixelCode{ + 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array WrapSamplerPixelCode{ + 0xbe8803ffu, 0u, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, + 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; +alignas(256) constexpr std::array BufferPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array GdsPixelCode{ + 0xbefc03ffu, 0x0000ffffu, 0x7e0002f0u, 0x7e0202f0u, 0xd8fa0010u, 0x04000000u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array StoragePixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e100280u, 0x7e120280u, 0xf0201f08u, + 0x00040008u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array LdsPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e080280u, 0xd8344400u, 0x00000004u, + 0xbf8cc07fu, 0xd8d84400u, 0x00000004u, 0xbf8cc07fu, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(4096) std::array StorageMemory{}; +alignas(256) constexpr std::array SamplingVertexCode{ + 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00820c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, + 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, + 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array InterpolantPixelCode{0xc8020002u, 0xc8060102u, 0xc80a0202u, 0xc80e0302u, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array BdaPixelCode{ + 0x7e0002f0u, 0x7e0202f0u, 0x7e08020cu, 0x7e0a020du, 0xdc308000u, 0x067d0004u, 0xf09c0f08u, 0x00400000u, + 0xbf8c0000u, 0x7e060306u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TablePixelCode{ + 0xf4200404u, 0xfa000000u, 0xbf8cc07fu, 0x8f108510u, 0xf42c0500u, 0x20000000u, 0xbf8cc07fu, 0x7e0002f0u, + 0x7e0202f0u, 0xf09c0f08u, 0x00250000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array TableVertexCode{ + 0xf4200508u, 0xfa000000u, 0xbf8cc07fu, 0x8f148514u, 0xf42c0604u, 0x28000000u, 0xbf8cc07fu, 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, + 0x00660c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, + 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array SrtPixelCode{ + 0xf40c0506u, 0xfa000000u, 0xf40c0706u, 0xfa000020u, 0xbf8cc07fu, 0xf420090au, 0xfa000000u, 0xf420094cu, + 0xfa000000u, 0xf420098eu, 0xfa000000u, 0xf42009d0u, 0xfa000000u, 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, + 0x00400000u, 0xbf8c0000u, 0x06060624u, 0x06060625u, 0x06060626u, 0x06060627u, 0xf800180fu, 0x03020100u, + 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; +alignas(256) constexpr std::array SrtVertexCode{ + 0xf40c0504u, 0xfa000000u, 0xf40c0704u, 0xfa000020u, 0xbf8cc07fu, 0xf420090au, 0xfa000000u, 0xf420094cu, + 0xfa000000u, 0xf420098eu, 0xfa000000u, 0xf42009d0u, 0xfa000000u, 0xbf8cc07fu, 0x7e000d05u, 0x080200f4u, + 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, + 0x06060624u, 0x06060625u, 0x06060626u, 0x06060627u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u}; +alignas(256) std::array TableMemory{}; +alignas(256) std::array FreshVertexCode{}; +alignas(256) std::array FreshPixelCode{}; +alignas(256) std::array MaterialMemory{}; +alignas(256) std::array OtherTextureMemory{}; +constexpr float BufferAlpha = 0.2f; +constexpr std::uint8_t BufferAlphaByte = 51u; +constexpr float SecondAlpha = 0.6f; +constexpr std::uint8_t SecondAlphaByte = 153u; +alignas(4096) std::array BufferMemory{}; +alignas(256) std::array ColorMemory{}; + +std::span MergedTarget(std::size_t index) { + constexpr std::size_t Bytes = 65536; + static std::array data{}; + if (data.at(index) == nullptr) data[index] = [] { + std::byte* block = nullptr; + const bool watched = AgcDriver::GuestMemory::WriteWatched(); +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Bytes, Bytes)); + GuestArena::GuestArenaCommit_nid_postfix(block, Bytes, PAGE_READWRITE, Bytes); +#else + void* raw = mmap(nullptr, 2u * Bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the merged color target"); + const auto begin = reinterpret_cast(raw); + block = reinterpret_cast((begin + Bytes - 1u) & ~static_cast(Bytes - 1u)); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Bytes); +#endif + Require(!watched || AgcDriver::GuestMemory::Watched(reinterpret_cast(block), Bytes), "the merged color target is not write-watched"); + GuestAllocations::Mutation mutation; + mutation.Add(block, Bytes, true, true, true); + return block; + }(); + return {data[index], ColorMemory.size()}; +} +alignas(256) std::array TextureMemory{}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(Header& header, const std::uint32_t* code, std::size_t bytes, std::uint8_t type) { + header.shader.file_header = 0x34333231u; + header.shader.version = 0x18u; + header.shader.header_size = sizeof(Header); + header.shader.shader_size = static_cast(bytes); + header.shader.code = code; + header.shader.type = type; + header.shader.user_data = &header.userData; + AgcDriverRegisterShader_nid_postfix(&header.shader); +} + +void Append(std::vector& commands, std::uint32_t opcode, std::initializer_list payload) { + commands.push_back(0xc0000000u | (static_cast(payload.size() - 1) << 16u) | (opcode << 8u)); + commands.insert(commands.end(), payload); +} + +enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds, ConstantSampler, BorderSampler, WrapSampler, MergedBlend, MergedBlendOther }; + +const std::uint32_t* VertexProgram(Mode mode) { + if (mode == Mode::VertexTable) return TableVertexCode.data(); + if (mode == Mode::Vertex) return SamplingVertexCode.data(); + return VertexCode.data(); +} + +std::uint32_t PixelUserWords(Mode mode, bool vertexSampling) { + switch (mode) { + case Mode::Storage: + return 24u; + case Mode::Buffer: + case Mode::MovedBuffer: + return 16u; + case Mode::Bda: + return 14u; + default: + return vertexSampling ? 0u : 12u; + } +} + +unsigned ExpectedChannel(Mode mode, bool buffer, std::size_t channel) { + if (mode == Mode::MovedTexture) return 0x33u; + if ((mode == Mode::Bda || mode == Mode::MovedBuffer) && channel == 3) return SecondAlphaByte; + if (buffer && channel == 3) return BufferAlphaByte; + if (mode == Mode::BorderSampler) return 0xffu; + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return std::min(2u * Texel[channel] + static_cast(Kept), 0xffu); + return Texel[channel]; +} + +const char* DrawnWhat(Mode mode, bool buffer) { + if (mode == Mode::Bda) return " (texture and BDA)"; + if (mode == Mode::MovedBuffer) return " (texture and a buffer moved between two draws)"; + if (mode == Mode::MovedTexture) return " (a texture changed between two draws)"; + if (buffer) return " (texture and buffer)"; + if (mode == Mode::Table) return " (image table)"; + if (mode == Mode::ConstantSampler) return " (texture with a constant sampler)"; + if (mode == Mode::BorderSampler) return " (constant border-clamp sampler outside the texture)"; + if (mode == Mode::WrapSampler) return " (constant wrapping sampler outside the texture, after a border-clamp draw of the same shader)"; + if (mode == Mode::MergedBlend) return " (texture blended unclamped into the color target)"; + if (mode == Mode::MergedBlendOther) return " (texture blended unclamped into a second color target)"; + return " (texture)"; +} + +const char* TakenWhat(Mode mode, bool buffer) { + if (buffer) return " reading a buffer"; + if (mode == Mode::Vertex) return " (vertex stage)"; + if (mode == Mode::Bda) return " loading through BDA"; + if (mode == Mode::Table) return " reading an image table"; + if (mode == Mode::VertexTable) return " (vertex stage reading an image table)"; + if (mode == Mode::ConstantSampler || mode == Mode::BorderSampler || mode == Mode::WrapSampler) return " sampling with a constant sampler"; + if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return " merging into its color target"; + return ""; +} + +std::array ImageDescriptor(const void* memory) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (3u << 30u), + 3u << 14u, + 0xfacu | (9u << 28u), + 0u, + 0u, + 0u, + 0u}; +} + +std::array BufferDescriptor(const void* memory, std::size_t bytes) { + const auto address = static_cast(reinterpret_cast(memory)); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), static_cast(bytes), + 0xfacu}; +} + + +constexpr std::size_t Textures = 16; +constexpr std::size_t Buffers = 32; +constexpr std::size_t SrtTables = 256; +alignas(256) std::array, Textures> BenchTextures{}; +alignas(4096) std::array, SrtTables> SrtTableMemory{}; + +void FillSrtTables(std::size_t salt = 0) { + for (std::size_t table = 0; table < SrtTables; ++table) + for (std::size_t entry = 0; entry < 4u; ++entry) { + const auto slice = 1u + (table * 5u + entry * 11u + salt) % Buffers; + const auto descriptor = BufferDescriptor(BufferMemory.data() + slice, sizeof(BufferMemory) - slice * sizeof(float)); + std::copy(descriptor.begin(), descriptor.end(), SrtTableMemory[table].begin() + static_cast(entry * 4u)); + } +} + +std::vector Frame(std::size_t draws, std::size_t salt, bool srt) { + const auto color = reinterpret_cast(MergedTarget(0).data()); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, + {0x207, 0}, + {0x200, 0}, + {0x203, 0x800}, + {0x2dc, 0xaa00}, + {0x2f8, 0}, + {0x293, 0}, + {0x80, 0}, + {0x8d, 0}, + {0x83, 0xffff}, + {0x8c, 0xa}, + {0x2f9, 0x2d}, + {0x313, 0x6000}, + {0x30e, 0xffffffff}, + {0x30f, 0xffffffff}, + {0x206, 0x43f}, + {0x204, 0x80000}, + {0x205, 0x240}, + {0x8e, 0xf}, + {0x8f, 0xf}, + {0x202, 0xcc0010}, + {0x1c4, 0}, + {0x1c5, 9}, + {0x1c3, 4}, + {0x31c, 0x28028}, + {0x31b, 0}, + {0x31d, 0}, + {0x3b0, (63u << 14u) | 3u}, + {0x3b8, 0x9000000}, + {0x1e0, 0}, + {0xc, 0}, + {0xd, 0x40040}, + {0x81, 0x80000000}, + {0x82, 0x40040}, + {0x90, 0x80000000}, + {0x91, 0x40040}, + {0x94, 0x80000000}, + {0x95, 0x40040}, + {0x10f, std::bit_cast(32.0f)}, + {0x110, std::bit_cast(32.0f)}, + {0x111, std::bit_cast(-2.0f)}, + {0x112, std::bit_cast(2.0f)}, + {0x113, std::bit_cast(1.0f)}, + {0x114, 0}, + {0xb4, 0}, + {0xb5, std::bit_cast(1.0f)}, + {0x2fe, 0}, + {0x302, 0}, + {0x306, 0}, + {0x30a, 0}, + {0x318, static_cast(color >> 8u)}, + {0x390, static_cast(color >> 40u)}, + {0x292, 2}, + }; + + std::vector commands; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + const auto vertex = reinterpret_cast(srt ? SrtVertexCode.data() : VertexCode.data()); + Append(commands, 0x76, {0xc8, static_cast(vertex >> 8u)}); + Append(commands, 0x76, {0xc9, static_cast(vertex >> 40u)}); + Append(commands, 0x76, {0x8b, (srt ? 2u : 1u) << 1u}); + Append(commands, 0x76, {0x8c, 0}); + for (std::size_t draw = 0; draw < draws; ++draw) { + const bool buffer = !srt && draw % 2u == 1u; + const auto pixel = reinterpret_cast(srt ? SrtPixelCode.data() : buffer ? BufferPixelCode.data() : PixelCode.data()); + std::array words{}; + const auto image = ImageDescriptor(BenchTextures[(draw + salt) % Textures].data()); + std::copy(image.begin(), image.end(), words.begin()); + const auto slice = 1u + (draw * 7u + salt) % Buffers; + const auto descriptor = BufferDescriptor(BufferMemory.data() + slice, sizeof(BufferMemory) - slice * sizeof(float)); + std::copy(descriptor.begin(), descriptor.end(), words.begin() + 12); + if (srt) { + const auto table = reinterpret_cast(SrtTableMemory[(draw + salt) % SrtTables].data()); + words[12] = static_cast(table); + words[13] = static_cast(static_cast(table) >> 32u); + const auto vertexTable = reinterpret_cast(SrtTableMemory[((draw + salt) * 3u + 1u) % SrtTables].data()); + Append(commands, 0x76, {0x8c, static_cast(vertexTable)}); + Append(commands, 0x76, {0x8d, static_cast(static_cast(vertexTable) >> 32u)}); + } + const std::uint32_t userWords = srt ? 14u : buffer ? 16u : 12u; + Append(commands, 0x76, {0x008, static_cast(pixel >> 8u)}); + Append(commands, 0x76, {0x009, static_cast(pixel >> 40u)}); + Append(commands, 0x76, {0x00b, userWords << 1u}); + for (std::uint32_t index = 0; index < userWords; ++index) Append(commands, 0x76, {0x00cu + index, words[index]}); + Append(commands, 0x2d, {3, 2}); + } + return commands; +} + +} + +int main() { + SetTestEnvironment("APS5_NO_DRAW_RECIPE", "1"); + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; + constexpr std::size_t Draws = 256, Rounds = 4; + { + GuestAllocations::Mutation mutation; + mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); + mutation.Add(SrtTableMemory.data(), sizeof(SrtTableMemory), true, true, true); + } + FillSrtTables(); + for (auto& texture : BenchTextures) + for (std::size_t offset = 0; offset < texture.size(); offset += Texel.size()) std::memcpy(texture.data() + offset, Texel.data(), Texel.size()); + BufferMemory.fill(BufferAlpha); + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + static Header TexturePixel{}, BufferPixel{}; + Registered(TexturePixel, PixelCode.data(), sizeof(PixelCode), 1); + Registered(BufferPixel, BufferPixelCode.data(), sizeof(BufferPixelCode), 1); + static Header SrtPixel{}, SrtVertex{}; + Registered(SrtPixel, SrtPixelCode.data(), sizeof(SrtPixelCode), 1); + Registered(SrtVertex, SrtVertexCode.data(), sizeof(SrtVertexCode), 2); + std::uint64_t keysBefore = 0; + for (std::size_t round = 0; round < Rounds; ++round) { + if (round == 2) keysBefore = AgcDriver::Graphics::DrawContentKeysBuilt(); + auto commands = Frame(Draws, round, true); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); + } + const auto built = AgcDriver::Graphics::DrawContentKeysBuilt() - keysBefore; + const auto repeated = (Rounds - 2) * Draws; + if (heap && AgcDriver::Graphics::DescriptorHeapEnabled()) + Require(built * 8u < repeated, "repeated heap draws built " + std::to_string(built) + " resource-cache content keys over " + std::to_string(repeated) + " draws instead of reusing their stages' keys"); + std::printf("repeated draws built %llu content keys over %zu draws\n", static_cast(built), repeated); + AgcDriverShutdown_nid_postfix(); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} From cd6f534029905b378f350dd710ea3dbbd5b09580 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 9 Nov 2026 23:23:05 +0530 Subject: [PATCH 160/269] perf(agc): share a heap walk memo hit's stage words instead of copying them rememberWalk copied the walked HeapStageWords into a new shared object for the memo, so the walk returned one object and every memo hit returned another. The stage words are immutable once built, so the memo now keeps the walk's own pointer: one fewer allocation and copy per remembered walk, and repeated walks of one stage yield the same words object, which lets identity-keyed caches downstream (the stage's draw-key memo, the committer's stage refresh) hit across draws. Tested: agc_driver_heap_walk_capture_failure requires two memo hits of one stage to return the walk's words object; without this change it fails on the copy. --- .../Execution/src/Driver/Draw/HeapStages.cpp | 6 +++--- .../tests/execution/HeapWalkCaptureFailure.cpp | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index e02b2c3b6f3f..25efa39458fe 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -514,7 +514,7 @@ void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderI std::span userData, std::uint64_t shaderBase, const std::shared_ptr& ranges, const std::shared_ptr>& values, const AddressRanges& accessible, const std::shared_ptr& capture, - const std::shared_ptr& result, const ShaderRecompiler::HeapStageWords& words) { + const std::shared_ptr& result, std::shared_ptr words) { HeapWalkEntry entry; entry.variant = invocation.VariantId(); entry.pushOffset = invocation.Request().layout.pushConstantOffsetBytes; @@ -528,7 +528,7 @@ void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderI entry.userDataUse = capture->userDataUse; entry.capture = capture; entry.result = result; - entry.words = std::make_shared(words); + entry.words = std::move(words); auto& memo = heapWalkMemo(); const auto heldBefore = memo.heldBytes; memo.remember(memoKey, std::move(entry)); @@ -628,7 +628,7 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade if (complete) materialized.reads = {sharedRanges, shared, capture->userDataUse, capture, true}; Graphics::HeapCostScope insertCost(Graphics::HeapCost::MemoInsert); if (memoOn && complete && (memoKnown || heapWalkMemo().admit(memoKey))) - rememberWalk(memoKey, invocation, userData, shaderBase, sharedRanges, shared, reads.accessible, capture, result, *words); + rememberWalk(memoKey, invocation, userData, shaderBase, sharedRanges, shared, reads.accessible, capture, result, words); materialized.result = std::move(result); materialized.words = std::move(words); return materialized; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp index 0306094eb38d..e9107f4da25a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp @@ -87,6 +87,21 @@ void ValidTypeYieldsStage(AgcDriver::VulkanDevice& device) { Require(materialized.result != nullptr, "a heap walk over valid buffer descriptors declined its stage"); } +void MemoHitSharesWalkedWords(AgcDriver::VulkanDevice& device) { + auto userData = UserData(0u); + userData[6] -= 16u; + const auto request = Request(device, userData); + const auto handle = ShaderRecompiler::PrepareShader(request); + const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, handle); + Require(invocation.has_value(), "the prepared shader refused its own request"); + std::array walks; + for (auto& walk : walks) { + walk = AgcDriver::DriverDetail::MaterializeHeapStage(*invocation, userData, request.shader.codeAddress); + Require(walk.result != nullptr && walk.words != nullptr, "a repeated heap walk over valid buffer descriptors declined its stage"); + } + Require(walks[2].words == walks[1].words, "a heap walk memo hit returned a copy of the walked words instead of the words its walk stored"); +} + } int main() { @@ -95,6 +110,7 @@ int main() { if (!device) return VulkanTestSkipped; UnsupportedTypeDeclines(*device); ValidTypeYieldsStage(*device); + MemoHitSharesWalkedWords(*device); std::puts("heap walk capture failure tests passed"); return 0; } catch (const std::exception& error) { From 113b6927eb143bf045940aa686f1f977175047b4 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 9 Nov 2026 23:44:29 +0530 Subject: [PATCH 161/269] perf(agc): relocate a heap draw's buffers without a rewritten descriptor set A draw whose buffers moved gets per-draw DrawBindings: snapshot buffers, address overrides and a rewritten descriptor set. A heap stage's pipeline binds from the descriptor heap and never binds that set (recordDraw and the dispatch record take BindDescriptorHeaps for a heap pipeline), and its moved buffer addresses reach the shader through the pushed buffer roots built from the overrides. Yet every relocated heap draw still took a set from the descriptor cache under its mutex and wrote it with vkUpdateDescriptorSets. writeDrawSets now builds the rewritten set only for a non-heap stage (writeRewrittenSets); a heap stage gets only its address overrides. Heap off is unchanged. Tested: agc_driver_heap_ring_draw_key walks the bench's SRT tables so its heap draws relocate, and requires them to take no rewritten sets (DescriptorCache::RewrittenSets, a process-wide count bumped under the cache's lock without a locked add). With the set still written it counted 1024 for 512 heap draws; heap off keeps its 2048. --- .../Graphics/include/ShaderResources.hpp | 2 + .../Graphics/src/ShaderResources.cpp | 52 ++++++--- .../tests/execution/HeapRingDrawKey.cpp | 105 +++--------------- 3 files changed, 51 insertions(+), 108 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 2d39f3765b3c..7c73617f8260 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -130,6 +130,7 @@ class DescriptorCache { std::uint64_t reusedSets = 0; }; Stats Counters() const; + static std::uint64_t RewrittenSets(); private: Context context; @@ -776,6 +777,7 @@ class ShaderResources { std::vector faultDescriptors; void prepareFaultSlot() const; void writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord, std::span> inPlace = {}) const; + void writeRewrittenSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord) const; std::shared_ptr> ownRecordBusy = std::make_shared>(false); mutable std::vector drawPoolSizes; // Guest buffer elements bound read-only: each use of this object skips that many pending-write diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index a54953bca33f..83fb59932f3e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -4907,9 +4907,21 @@ DescriptorCache::SetAllocation DescriptorCache::Allocate(VkDescriptorSetLayout l return {set, pool, chain.size() - 1, updateAfterBind, VK_NULL_HANDLE, {}, variableCount, {}}; } +namespace { +std::atomic& rewrittenSets() { + static std::atomic sets{0}; + return sets; +} +} + +std::uint64_t DescriptorCache::RewrittenSets() { + return rewrittenSets().load(std::memory_order_relaxed); +} + DescriptorCache::SetAllocation DescriptorCache::AllocateRewritten(VkDescriptorSetLayout layout, std::span sizes, bool updateAfterBind, std::optional variableCount) { { std::lock_guard lock(mutex); + rewrittenSets().store(rewrittenSets().load(std::memory_order_relaxed) + 1u, std::memory_order_relaxed); if (const auto found = recycled.find({layout, variableCount.value_or(0u)}); found != recycled.end() && !found->second.empty()) { const auto allocation = found->second.back(); found->second.pop_back(); @@ -6637,6 +6649,28 @@ std::shared_ptr ShaderResources::PrepareDrawBindi } void ShaderResources::writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord, std::span> inPlace) const { + if (!heapStage) writeRewrittenSets(result, selected, faultRecord); + if (addressedBuffers) { + std::vector overrides(allocations.size(), VkDeviceAddressRangeEXT{0, 0}); + bool overridden = false; + for (std::size_t index = 0; index < selected.size(); ++index) { + const auto& snapshot = result.snapshots[index]; + overrides[selected[index]] = {snapshot.buffer->DeviceAddress() + snapshot.offset, snapshot.bytes}; + } + for (const auto& [index, range] : inPlace) overrides[index] = range; + for (const auto& binding : bindings) { + if (!binding.addressed) continue; + for (const auto allocation : binding.allocations) overridden = overridden || overrides[allocation].address != 0; + } + if (overridden) { + result.heapOffsets = heapOffsets; + result.addressOffsets = true; + result.addressOverrides = std::move(overrides); + } + } +} + +void ShaderResources::writeRewrittenSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord) const { Require(context.descriptorCache != nullptr, "draw snapshots require a descriptor cache"); std::array described{}; thread_local std::array, 2>* countsSlot = nullptr; @@ -6699,24 +6733,6 @@ void ShaderResources::writeDrawSets(DrawBindings& result, std::span overrides(allocations.size(), VkDeviceAddressRangeEXT{0, 0}); - bool overridden = false; - for (std::size_t index = 0; index < selected.size(); ++index) { - const auto& snapshot = result.snapshots[index]; - overrides[selected[index]] = {snapshot.buffer->DeviceAddress() + snapshot.offset, snapshot.bytes}; - } - for (const auto& [index, range] : inPlace) overrides[index] = range; - for (const auto& binding : bindings) { - if (!binding.addressed) continue; - for (const auto allocation : binding.allocations) overridden = overridden || overrides[allocation].address != 0; - } - if (overridden) { - result.heapOffsets = heapOffsets; - result.addressOffsets = true; - result.addressOverrides = std::move(overrides); - } - } context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp index 46a373e2ab6d..4add88aa29bc 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp @@ -40,7 +40,6 @@ namespace { using AgcDriver::Graphics::Require; -constexpr std::byte Kept{0x40}; constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; alignas(256) constexpr std::array VertexCode{ @@ -50,41 +49,14 @@ alignas(256) constexpr std::array VertexCode{ alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array ConstantSamplerPixelCode{ - 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, - 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; -alignas(256) constexpr std::array BorderSamplerPixelCode{ - 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, - 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; -alignas(256) constexpr std::array WrapSamplerPixelCode{ - 0xbe8803ffu, 0u, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, - 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; alignas(256) constexpr std::array BufferPixelCode{ 0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array GdsPixelCode{ - 0xbefc03ffu, 0x0000ffffu, 0x7e0002f0u, 0x7e0202f0u, 0xd8fa0010u, 0x04000000u, 0xf09c0f08u, 0x00400000u, - 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array StoragePixelCode{ - 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e100280u, 0x7e120280u, 0xf0201f08u, - 0x00040008u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array LdsPixelCode{ - 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e080280u, 0xd8344400u, 0x00000004u, - 0xbf8cc07fu, 0xd8d84400u, 0x00000004u, 0xbf8cc07fu, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; -alignas(4096) std::array StorageMemory{}; alignas(256) constexpr std::array SamplingVertexCode{ 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00820c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, }; -alignas(256) constexpr std::array InterpolantPixelCode{0xc8020002u, 0xc8060102u, 0xc80a0202u, 0xc80e0302u, - 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array BdaPixelCode{ - 0x7e0002f0u, 0x7e0202f0u, 0x7e08020cu, 0x7e0a020du, 0xdc308000u, 0x067d0004u, 0xf09c0f08u, 0x00400000u, - 0xbf8c0000u, 0x7e060306u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array TablePixelCode{ - 0xf4200404u, 0xfa000000u, 0xbf8cc07fu, 0x8f108510u, 0xf42c0500u, 0x20000000u, 0xbf8cc07fu, 0x7e0002f0u, - 0x7e0202f0u, 0xf09c0f08u, 0x00250000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; alignas(256) constexpr std::array TableVertexCode{ 0xf4200508u, 0xfa000000u, 0xbf8cc07fu, 0x8f148514u, 0xf42c0604u, 0x28000000u, 0xbf8cc07fu, 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00660c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, @@ -100,15 +72,7 @@ alignas(256) constexpr std::array SrtVertexCode{ 0xfa000000u, 0xf420098eu, 0xfa000000u, 0xf42009d0u, 0xfa000000u, 0xbf8cc07fu, 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, 0x06060624u, 0x06060625u, 0x06060626u, 0x06060627u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u}; -alignas(256) std::array TableMemory{}; -alignas(256) std::array FreshVertexCode{}; -alignas(256) std::array FreshPixelCode{}; -alignas(256) std::array MaterialMemory{}; -alignas(256) std::array OtherTextureMemory{}; constexpr float BufferAlpha = 0.2f; -constexpr std::uint8_t BufferAlphaByte = 51u; -constexpr float SecondAlpha = 0.6f; -constexpr std::uint8_t SecondAlphaByte = 153u; alignas(4096) std::array BufferMemory{}; alignas(256) std::array ColorMemory{}; @@ -135,7 +99,6 @@ std::span MergedTarget(std::size_t index) { }(); return {data[index], ColorMemory.size()}; } -alignas(256) std::array TextureMemory{}; struct Header { Shader shader{}; @@ -143,7 +106,6 @@ struct Header { }; alignas(8) Header VertexHeader{}; -alignas(8) Header PixelHeader{}; void Registered(Header& header, const std::uint32_t* code, std::size_t bytes, std::uint8_t type) { header.shader.file_header = 0x34333231u; @@ -169,54 +131,6 @@ const std::uint32_t* VertexProgram(Mode mode) { return VertexCode.data(); } -std::uint32_t PixelUserWords(Mode mode, bool vertexSampling) { - switch (mode) { - case Mode::Storage: - return 24u; - case Mode::Buffer: - case Mode::MovedBuffer: - return 16u; - case Mode::Bda: - return 14u; - default: - return vertexSampling ? 0u : 12u; - } -} - -unsigned ExpectedChannel(Mode mode, bool buffer, std::size_t channel) { - if (mode == Mode::MovedTexture) return 0x33u; - if ((mode == Mode::Bda || mode == Mode::MovedBuffer) && channel == 3) return SecondAlphaByte; - if (buffer && channel == 3) return BufferAlphaByte; - if (mode == Mode::BorderSampler) return 0xffu; - if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return std::min(2u * Texel[channel] + static_cast(Kept), 0xffu); - return Texel[channel]; -} - -const char* DrawnWhat(Mode mode, bool buffer) { - if (mode == Mode::Bda) return " (texture and BDA)"; - if (mode == Mode::MovedBuffer) return " (texture and a buffer moved between two draws)"; - if (mode == Mode::MovedTexture) return " (a texture changed between two draws)"; - if (buffer) return " (texture and buffer)"; - if (mode == Mode::Table) return " (image table)"; - if (mode == Mode::ConstantSampler) return " (texture with a constant sampler)"; - if (mode == Mode::BorderSampler) return " (constant border-clamp sampler outside the texture)"; - if (mode == Mode::WrapSampler) return " (constant wrapping sampler outside the texture, after a border-clamp draw of the same shader)"; - if (mode == Mode::MergedBlend) return " (texture blended unclamped into the color target)"; - if (mode == Mode::MergedBlendOther) return " (texture blended unclamped into a second color target)"; - return " (texture)"; -} - -const char* TakenWhat(Mode mode, bool buffer) { - if (buffer) return " reading a buffer"; - if (mode == Mode::Vertex) return " (vertex stage)"; - if (mode == Mode::Bda) return " loading through BDA"; - if (mode == Mode::Table) return " reading an image table"; - if (mode == Mode::VertexTable) return " (vertex stage reading an image table)"; - if (mode == Mode::ConstantSampler || mode == Mode::BorderSampler || mode == Mode::WrapSampler) return " sampling with a constant sampler"; - if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return " merging into its color target"; - return ""; -} - std::array ImageDescriptor(const void* memory) { const auto address = static_cast(reinterpret_cast(memory)); return {static_cast(address >> 8u), @@ -355,7 +269,7 @@ int main() { if (!device) return VulkanTestSkipped; } const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; - constexpr std::size_t Draws = 256, Rounds = 4; + constexpr std::size_t Draws = 256, Rounds = 8; { GuestAllocations::Mutation mutation; mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); @@ -372,16 +286,27 @@ int main() { static Header SrtPixel{}, SrtVertex{}; Registered(SrtPixel, SrtPixelCode.data(), sizeof(SrtPixelCode), 1); Registered(SrtVertex, SrtVertexCode.data(), sizeof(SrtVertexCode), 2); - std::uint64_t keysBefore = 0; + std::uint64_t keysBefore = 0, keysBuilt = 0, setsBefore = 0; for (std::size_t round = 0; round < Rounds; ++round) { if (round == 2) keysBefore = AgcDriver::Graphics::DrawContentKeysBuilt(); + if (round == 4) { + keysBuilt = AgcDriver::Graphics::DrawContentKeysBuilt() - keysBefore; + setsBefore = AgcDriver::Graphics::DescriptorCache::RewrittenSets(); + } auto commands = Frame(Draws, round, true); + if (round >= 4) FillSrtTables(round); Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); AgcDriverWaitIdle_nid_postfix(); } - const auto built = AgcDriver::Graphics::DrawContentKeysBuilt() - keysBefore; - const auto repeated = (Rounds - 2) * Draws; + const auto built = keysBuilt; + const auto repeated = 2u * Draws; + const auto sets = AgcDriver::Graphics::DescriptorCache::RewrittenSets() - setsBefore; + const bool heapDraws = heap && AgcDriver::Graphics::DescriptorHeapEnabled(); + Require(heapDraws || sets != 0, "walked draws without the heap allocated no rewritten descriptor sets, so they did not relocate"); + if (heapDraws) + Require(sets == 0, "walked heap draws allocated " + std::to_string(sets) + " rewritten descriptor sets that a descriptor heap pipeline never binds"); + std::printf("walked draws allocated %llu rewritten descriptor sets\n", static_cast(sets)); if (heap && AgcDriver::Graphics::DescriptorHeapEnabled()) Require(built * 8u < repeated, "repeated heap draws built " + std::to_string(built) + " resource-cache content keys over " + std::to_string(repeated) + " draws instead of reusing their stages' keys"); std::printf("repeated draws built %llu content keys over %zu draws\n", static_cast(built), repeated); From d98c07517cef293160be5747d6417c35111f04ad Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 9 Nov 2026 17:07:47 +0530 Subject: [PATCH 162/269] perf(agc): keep a heap stage's data block when only pushed user data changed A heap stage reads every user-data word its pipeline places in push data from the push block, the way vkd3d-proton reads root constants (d3d12_root_signature_init_push_constants); the copy of those words in the stage's shader-data block is never read. The block was still rewritten whenever any user-data word changed, so a draw that only moved a value word wrote a new block. layOutHeapStages now records, per stage, which user-data dwords the pipeline's push placement covers (PushDataPlacements, once per resources build). writeHeapStage keeps the stage's block when the walked words and slots are unchanged and only covered user-data words differ, updating the words writePushedData pushes; heapSpan applies the same rule when the patched words differ only in covered dwords. writePushedData requires the pipeline to push at least the dwords the keep assumed. APS5_NO_PUSHED_USER_DATA_KEEP=1 writes a new block as before. The [gpu-heap] line counts the kept blocks. Tested: agc_driver_draw_recipe_moved_buffer (heap, overflow and keep-off variants) asserts the keep on draws whose moved buffer changes only pushed user words and that they still read the moved buffer; a mutant that keeps the block without updating the pushed words fails it. --- .../Graphics/include/BindlessHeap.hpp | 2 + .../Graphics/include/ShaderResources.hpp | 4 +- .../Graphics/src/BindlessHeap.cpp | 17 ++++- .../Graphics/src/ShaderResources.cpp | 63 ++++++++++++++++--- ...river_draw_recipe_moved_buffer_tests.cmake | 5 +- .../tests/execution/DrawRecipeMovedBuffer.cpp | 4 ++ docs/dev/ENVIRONMENT.md | 1 + 7 files changed, 83 insertions(+), 13 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 5e71d9307a49..ed92dca8e172 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -287,6 +287,8 @@ std::uint64_t HeapComputeStages(); void NoteImageTableBuild(); std::uint64_t ImageTableBuilds(); void NoteDataAddressPush(); +void NotePushedUserDataKeep(); +std::uint64_t PushedUserDataKeeps(); void NoteEmptyResourceSet(); std::uint64_t EmptyResourceSets(); std::uint64_t DataAddressPushes(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 7c73617f8260..f059aced8c3b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -718,9 +718,11 @@ class ShaderResources { std::uint64_t inertProgram = 0; std::vector owned; VkShaderStageFlags laidOutFor = 0; + std::uint64_t pushedUserWords = 0; + std::uint32_t pushedPlaced = 0; }; std::array heapStages; - std::uint64_t heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words); + std::uint64_t heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words, std::uint64_t pushed = 0); bool ownsHeapBinding(const Binding& binding, VkShaderStageFlags stageBit) const; VkImageView heapPlaceholderView(std::uint32_t kind) const; VkImageView heapSampledView(std::size_t index) const; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index d43bf4511043..17125e56559a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -79,6 +79,7 @@ std::atomic heapComputeStages{0}; std::atomic descriptorHeapDevice{false}; std::atomic imageTableBuilds{0}; std::atomic dataAddressPushes{0}; +std::atomic pushedUserDataKeeps{0}; std::atomic embeddedSamplerMappings{0}; std::atomic slotPressureSubmits{0}; std::atomic heapSlotEvictions{0}; @@ -107,6 +108,14 @@ std::uint64_t DataAddressPushes() { return dataAddressPushes.load(std::memory_order_relaxed); } +void NotePushedUserDataKeep() { + pushedUserDataKeeps.fetch_add(1, std::memory_order_relaxed); +} + +std::uint64_t PushedUserDataKeeps() { + return pushedUserDataKeeps.load(std::memory_order_relaxed); +} + std::uint64_t EmbeddedSamplerMappings() { return embeddedSamplerMappings.load(std::memory_order_relaxed); } @@ -1363,14 +1372,18 @@ void reportHeapStatistics() { const auto poolRecycled = windowDelta(totals.poolBlocksRecycled, lastTotals.poolBlocksRecycled); const auto poolFreed = windowDelta(totals.poolBlocksFreed, lastTotals.poolBlocksFreed); lastTotals = totals; + static std::uint64_t lastPushedKeeps = 0; + const auto pushedKeepsTotal = PushedUserDataKeeps(); + const auto pushedKeeps = windowDelta(pushedKeepsTotal, lastPushedKeeps); + lastPushedKeeps = pushedKeepsTotal; const auto templates = ShaderRecompiler::HeapTemplateCounts(); std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; excluded:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; image descriptors %llu encoded / %llu copied; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept (%llu for pushed user data only) / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; image descriptors %llu encoded / %llu copied; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), excluded.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.spanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(pushedKeeps), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.spanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 83fb59932f3e..14d13c94d454 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -7067,7 +7067,9 @@ void ShaderResources::writePushedBuffers(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const { const auto& program = *shader.program; if (placement.count == 0u) return; - const auto& words = heapStages[HeapStageIndex(shader.stage)].data.words; + const auto& stageState = heapStages[HeapStageIndex(shader.stage)]; + const auto& words = stageState.data.words; + Require(stageState.pushedUserWords == 0u || placement.count >= stageState.pushedPlaced, "a stage's shader data was kept for user data its pipeline does not push"); Require(placement.count <= program.pushedData.size() && (placement.base + placement.count) * sizeof(std::uint32_t) <= bytes.size(), "a stage's pushed shader data does not fit"); for (std::uint32_t index = 0; index < placement.count; ++index) { const auto dword = program.pushedData[index]; @@ -7169,9 +7171,22 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi heapTableMapSet[stageIndex] = true; } -std::uint64_t ShaderResources::heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words) { - const auto span = heap.KeepOrAllocate(spans, words.size(), kept.mark, std::ranges::equal(kept.words, words)); - if (!span) return kept.mark.address; +std::uint64_t ShaderResources::heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words, std::uint64_t pushed) { + const bool same = std::ranges::equal(kept.words, words); + bool pushedOnly = false; + if (!same && pushed != 0u && kept.words.size() == words.size()) { + const auto prefix = std::min(words.size(), 64u); + pushedOnly = std::equal(words.begin() + static_cast(prefix), words.end(), kept.words.begin() + static_cast(prefix)); + for (std::size_t index = 0; pushedOnly && index < prefix; ++index) pushedOnly = kept.words[index] == words[index] || ((pushed >> index) & 1u) != 0u; + } + const auto span = heap.KeepOrAllocate(spans, words.size(), kept.mark, same || pushedOnly); + if (!span) { + if (pushedOnly) { + std::copy(words.begin(), words.end(), kept.words.begin()); + NotePushedUserDataKeep(); + } + return kept.mark.address; + } BindlessHeap::Write(*span, words); kept.words.assign(words.begin(), words.end()); return span->address; @@ -7205,7 +7220,11 @@ VkImageView ShaderResources::heapStorageView(std::size_t index, std::uint32_t bi } void ShaderResources::layOutHeapStages(std::span shaders) { - for (const auto& shader : shaders) { + static const bool keepPushedUserData = std::getenv("APS5_NO_PUSHED_USER_DATA_KEEP") == nullptr; + const bool addressed = keepPushedUserData && std::ranges::any_of(shaders, [](const CompiledShader& shader) { return HeapShader(shader) && shader.program->dataAddressPush; }); + const auto placements = addressed ? PushDataPlacements(shaders) : std::vector{}; + for (std::size_t shaderIndex = 0; shaderIndex < shaders.size(); ++shaderIndex) { + const auto& shader = shaders[shaderIndex]; if (!HeapShader(shader)) continue; const VkShaderStageFlags stageBit = VulkanStage(shader.stage); auto& state = heapStages[HeapStageIndex(shader.stage)]; @@ -7214,6 +7233,17 @@ void ShaderResources::layOutHeapStages(std::span shaders) if (ownsHeapBinding(bindings[index], stageBit)) state.owned.push_back(static_cast(index)); } state.laidOutFor = stageBit; + state.pushedUserWords = 0; + state.pushedPlaced = 0; + if (placements.empty() || !shader.program->dataAddressPush) continue; + const auto& program = *shader.program; + const auto placed = std::min(placements[shaderIndex].pushed.count, program.pushedData.size()); + const auto userWords = std::max(program.heapUserWords.size(), program.shaderDataUserWords.size()); + for (std::size_t item = 0; item < placed; ++item) { + const auto dword = program.pushedData[item]; + if (dword < userWords && dword < 64u) state.pushedUserWords |= std::uint64_t{1} << dword; + } + state.pushedPlaced = static_cast(placed); } for (auto& elements : addressedElements) elements.clear(); for (const auto& binding : bindings) { @@ -7479,11 +7509,13 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl const auto& words = heapFlattened ? shader.heap->flattenedSrt : DrawGuestWords(shader, binding); const auto userData = shader.heap != nullptr ? std::span(shader.heap->userData) : std::span{}; - const bool sameInput = + const auto userFront = static_cast(std::min(userData.size(), words.size())); + const bool sameWords = binding.role == ShaderRecompiler::DescriptorRole::ShaderData && current && stageState.dataInput.size() == words.size() + userData.size() && - std::equal(words.begin(), words.end(), stageState.dataInput.begin()) && - std::equal(userData.begin(), userData.end(), stageState.dataInput.begin() + static_cast(words.size())); + std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront); + const auto userInput = stageState.dataInput.begin() + static_cast(words.size()); + const bool sameInput = sameWords && std::equal(userData.begin(), userData.end(), userInput); if (sameInput && !verifySlots) { if (heap.Held(stageState.data.mark)) { heapOffsets[dataIndex] = stageState.data.mark.address; @@ -7491,6 +7523,17 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl } stageState.data.mark.entry = 0; } + if (sameWords && !sameInput && !verifySlots && stageState.pushedUserWords != 0u && userData.size() <= 64u && stageState.data.words.size() >= userData.size()) { + bool pushedOnly = std::ranges::none_of(stageState.dataPatches, [&](const auto& patch) { return patch.first < userData.size() * sizeof(std::uint32_t); }); + for (std::size_t index = 0; pushedOnly && index < userData.size(); ++index) pushedOnly = userData[index] == userInput[static_cast(index)] || ((stageState.pushedUserWords >> index) & 1u) != 0u; + if (pushedOnly && heap.Held(stageState.data.mark)) { + std::copy(userData.begin(), userData.end(), stageState.data.words.begin()); + std::copy(userData.begin(), userData.end(), userInput); + heapOffsets[dataIndex] = stageState.data.mark.address; + NotePushedUserDataKeep(); + continue; + } + } if (!shaderData) { heapOffsets[flatIndex] = heapSpan(spans, heap, stageState.flat, words); heapSrtDwords[stageIndex] = static_cast(words.size()); @@ -7509,7 +7552,9 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl patchHeapSlotWords(shader, stageState, patched, current); if (verifySlots && sameInput && !std::ranges::equal(stageState.data.words, patched)) throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its inputs and slots did not"); - heapOffsets[dataIndex] = heapSpan(spans, heap, stageState.data, patched); + const auto userWords = std::min(userData.size(), 64u); + const auto pushedUser = stageState.pushedUserWords & (userWords == 64u ? ~std::uint64_t{0} : (std::uint64_t{1} << userWords) - 1u); + heapOffsets[dataIndex] = heapSpan(spans, heap, stageState.data, patched, pushedUser); stageState.dataInput.assign(words.begin(), words.end()); stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); } diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake index eca349833621..63716809287f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake @@ -2,5 +2,8 @@ if(BUILD_TESTING) agc_add_gpu_heap_test(agc_driver_draw_recipe_moved_buffer) agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_overflow agc_driver_draw_recipe_moved_buffer_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_PUSHED_BUFFER_RECORDS=0) + agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_no_pushed_keep agc_driver_draw_recipe_moved_buffer_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_NO_PUSHED_USER_DATA_KEEP=1) + agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_unverified agc_driver_draw_recipe_moved_buffer_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32) endif() - diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp index 4ef52e65f769..673300598a77 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp @@ -367,7 +367,11 @@ int main() { Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); Registered(PixelHeader, BufferPixelCode.data(), sizeof(BufferPixelCode), 1); const std::array slices{First, Moved}; + const auto keepsBefore = AgcDriver::Graphics::PushedUserDataKeeps(); for (int round = 0; round < 2; ++round) Require(Submit(slices) == SecondAlphaByte, "the draw of the moved buffer did not read it"); + const auto keeps = AgcDriver::Graphics::PushedUserDataKeeps() - keepsBefore; + if (!AgcDriver::Graphics::DescriptorHeapEnabled() || std::getenv("APS5_NO_PUSHED_USER_DATA_KEEP") != nullptr) Require(keeps == 0u, "draws kept a shader-data block for pushed user data " + std::to_string(keeps) + " times with the keep off"); + else Require(keeps >= 2u, "heap draws whose only change was the moved buffer's pushed user words kept their shader-data block " + std::to_string(keeps) + " times, expected at least 2"); const auto hitsBefore = AgcDriver::VulkanDevice::DrawRecipeHits(); const auto pathsBefore = AgcDriver::Graphics::HeapBufferPaths(); Require(Submit(slices) == SecondAlphaByte, "the repeated draw of the moved buffer did not read it"); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index a2a4bea4bf75..2c30e31248f9 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -362,6 +362,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_PRESENT_EPOCH` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | keeps the presenter at collect epoch 0 instead of adopting the newest epoch a worker started | | `APS5_NO_PRESYNC` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | disables the stage-A pre-sync of pending writes | | `APS5_NO_PROC_TABLE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | resolves the device's Vulkan entry points per call instead of filling the function table once | +| `APS5_NO_PUSHED_USER_DATA_KEEP` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | writes a new heap shader-data block when only user-data words the pipeline pushes changed, instead of keeping the stage's block and pushing the new words | | `APS5_NO_QUEUED_DRAW_READ_ORDER` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp` | | stops queued draws and DMA copies from holding back write-backs over the guest memory they read at commit | | `APS5_NO_QUEUED_LABELS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/DeferredLabels.cpp` | | disables the queued-label table | | `APS5_NO_READS_OVERLAP_WALK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | builds the list of in-place reads for each read-overlap test instead of walking the regions to the first overlap | From 1981c5609df553fe0b32f0d24df8091a77c9d8dd Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 9 Nov 2026 18:23:35 +0530 Subject: [PATCH 163/269] perf(agc): drain the draw finisher on a lookup only for held draws that may insert its key A draw-cache lookup drained the draw finisher whenever a draw it held had the same draw key (or, for a key the cache lacks, the same shape), so the lookup would see the entry that draw inserts. Only a draw that missed the cache inserts anything: the finisher writes the draw cache in cacheDrawStages, which runs only when the decoder's lookup missed. A held draw that hit the cache changes nothing the lookup reads, yet every repeat of a hit draw within the finisher's depth drained it. Held draws now carry their key and shape only when they missed. In GTA V lookup drains ran about 3x as often with the GPU heap as without (563 vs 169 per 10 s), and heap on's frame time was spikier. Tested: agc_driver_finisher_hit_lookup (draw pipeline, plan verify and heap variants) repeats a cached draw 64 times and requires no lookup drain; it failed with 10 lookup drains before the fix. --- .../Execution/src/Driver/Draw/Draw.cpp | 6 +- .../src/Driver/Draw/DrawPipeline.cpp | 2 +- ...agc_driver_finisher_hit_lookup_tests.cmake | 4 + .../tests/execution/FinisherHitLookup.cpp | 147 ++++++++++++++++++ 4 files changed, 156 insertions(+), 3 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_hit_lookup_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/FinisherHitLookup.cpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index d4c558b10407..9b380505e59e 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -281,8 +281,10 @@ std::optional writesBeyondTargets(const ShaderRecompiler::RecompileR DrawFinisher::Pending heldWrites(const DrawTail& tail) { DrawFinisher::Pending held; - held.key = tail.drawKey; - held.shape = tail.shapeKey; + if (!tail.drawHit) { + held.key = tail.drawKey; + held.shape = tail.shapeKey; + } if (tail.decode == nullptr) { noteHeld(HeldReason::NoDecode); return held; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp index 035d19344f13..79795ba47f85 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp @@ -128,7 +128,7 @@ bool DrawFinisher::PendingOverlapsAny(std::span ranges) { bool DrawFinisher::PendingKey(std::uint64_t key, std::uint64_t shape) { if (!Busy() || !finisherProducer) return false; std::lock_guard lock(mutex); - return std::any_of(pending.begin(), pending.end(), [&](const Pending& held) { return held.key == key || (shape != 0 && held.shape == shape); }); + return std::any_of(pending.begin(), pending.end(), [&](const Pending& held) { return (held.key != 0 && held.key == key) || (shape != 0 && held.shape == shape); }); } namespace { diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_hit_lookup_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_hit_lookup_tests.cmake new file mode 100644 index 000000000000..e5b9cccef45e --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_hit_lookup_tests.cmake @@ -0,0 +1,4 @@ +if(BUILD_TESTING) + agc_add_draw_pipeline_test(agc_driver_finisher_hit_lookup) + agc_add_gpu_heap_test(agc_driver_finisher_hit_lookup) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/FinisherHitLookup.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherHitLookup.cpp new file mode 100644 index 000000000000..7402a8e6c9a9 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherHitLookup.cpp @@ -0,0 +1,147 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, +}; +alignas(256) constexpr std::array PixelCode{0xf4000100u, 0xfa000000u, 0xbf8cc07fu, 0x7e000204u, 0x06000002u, 0x7e020280u, 0xf800180fu, 0x00010100u, 0xbf810000u, 0xbf810000u}; +alignas(256) std::array PixelConstant{}; +alignas(256) std::array ColorMemory{}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(Header& header, const std::uint32_t* code, std::size_t bytes, std::uint8_t type) { + header.shader.file_header = 0x34333231u; + header.shader.version = 0x18u; + header.shader.header_size = sizeof(Header); + header.shader.shader_size = static_cast(bytes); + header.shader.code = code; + header.shader.type = type; + header.shader.user_data = &header.userData; + AgcDriverRegisterShader_nid_postfix(&header.shader); +} + +void Append(std::vector& commands, std::uint32_t opcode, std::initializer_list payload) { + commands.push_back(0xc0000000u | (static_cast(payload.size() - 1) << 16u) | (opcode << 8u)); + commands.insert(commands.end(), payload); +} + +std::vector Setup() { + const auto color = reinterpret_cast(ColorMemory.data()); + const auto vertex = reinterpret_cast(VertexCode.data()); + const auto pixel = reinterpret_cast(PixelCode.data()); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, {0x207, 0}, {0x200, 0}, {0x203, 0x800}, + {0x2dc, 0xaa00}, {0x2f8, 0}, {0x292, 2}, {0x293, 0}, + {0x80, 0}, {0x8d, 0}, {0x83, 0xffff}, {0x8c, 0xa}, + {0x2f9, 0x2d}, {0x313, 0x6000}, {0x30e, 0xffffffff}, {0x30f, 0xffffffff}, + {0x206, 0x43f}, {0x204, 0x80000}, {0x205, 0x240}, + {0x8e, 0xf}, {0x8f, 0xf}, {0x202, 0xcc0010}, + {0x1c4, 0}, {0x1c5, 9}, {0x1c3, 4}, {0x31c, 0x28028}, + {0x31b, 0}, {0x31d, 0}, {0x3b0, (63u << 14u) | 3u}, + {0x3b8, 0x9000000}, {0x1e0, 0}, + {0xc, 0}, {0xd, 0x40040}, + {0x81, 0x80000000}, {0x82, 0x40040}, + {0x90, 0x80000000}, {0x91, 0x40040}, + {0x94, 0x80000000}, {0x95, 0x40040}, + {0x318, static_cast(color >> 8u)}, {0x390, static_cast(color >> 40u)}, + {0x10f, std::bit_cast(32.0f)}, {0x110, std::bit_cast(32.0f)}, + {0x111, std::bit_cast(-2.0f)}, {0x112, std::bit_cast(2.0f)}, + {0x113, std::bit_cast(1.0f)}, {0x114, 0}, + {0xb4, 0}, {0xb5, std::bit_cast(1.0f)}, + {0x2fe, 0}, {0x302, 0}, {0x306, 0}, {0x30a, 0}, + }; + const std::vector> shader{ + {0xc8, static_cast(vertex >> 8u)}, {0xc9, static_cast(vertex >> 40u)}, {0x8b, 0}, {0x8c, 0}, + {0x008, static_cast(pixel >> 8u)}, {0x009, static_cast(pixel >> 40u)}, {0x00b, 3u << 1u}, + }; + std::vector commands; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + for (const auto& [offset, value] : shader) Append(commands, 0x76, {offset, value}); + const auto table = reinterpret_cast(PixelConstant.data()); + Append(commands, 0x76, {0x00c, static_cast(table)}); + Append(commands, 0x76, {0x00d, static_cast(table >> 32u)}); + Append(commands, 0x76, {0x00e, std::bit_cast(0.25f)}); + return commands; +} + +} + +namespace { + +std::uint64_t LookupDrains(const std::string& drains) { + const auto at = drains.find(" lookup "); + Require(at != std::string::npos, "the finisher's drain text has no lookup site: " + drains); + return std::strtoull(drains.c_str() + at + 8, nullptr, 10); +} + +void SubmitDraws(std::uint32_t draws) { + auto commands = Setup(); + for (std::uint32_t draw = 0; draw < draws; ++draw) Append(commands, 0x2d, {3, 2}); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); +} + +} + +int main() { + try { + bool libraries = false; + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + libraries = device->GraphicsPipelineLibraries(); + } + if (!libraries && std::getenv("APS5_NO_GPL") == nullptr) return VulkanTestSkipped; + using AgcDriver::DriverDetail::DrawFinisher; + const bool finisher = DrawFinisher::Enabled() && DrawFinisher::Overlap(); + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + Registered(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1); + PixelConstant[0] = 0.25f; + SubmitDraws(8); + static_cast(DrawFinisher::DrainText()); + SubmitDraws(64); + const auto drains = DrawFinisher::DrainText(); + AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(ColorMemory.data()), ColorMemory.size()); + unsigned brightest = 0; + for (const auto value : ColorMemory) brightest = std::max(brightest, static_cast(std::to_integer(value))); + Require(brightest + 2 >= 128 && brightest <= 130, "the repeated draws wrote " + std::to_string(brightest) + ", expected 128"); + if (finisher) Require(LookupDrains(drains) == 0u, "a draw-cache lookup drained the finisher for held draws of its key that hit the cache and insert nothing:" + drains); + AgcDriverShutdown_nid_postfix(); + std::cout << "repeated draw-cache hits " << (finisher ? "looked up beside the finisher" : "drawn without the finisher") << "\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + AgcDriverShutdown_nid_postfix(); + return 1; + } +} From d0c63514234d78426f203d6fb6bc838e713a56f0 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 9 Nov 2026 23:55:13 +0530 Subject: [PATCH 164/269] perf(agc): read a heap walk's tracker generation without the tracker mutex MaterializeHeapStage took the guest write tracker's mutex for TrackerGeneration() on every heap stage of every draw, before its walk memo lookup, and again for the memo hit's NoStampAfter proof. The finisher contends for that mutex with the collects. The walk now reads StableTrackerGeneration(): the generation the tracker publishes when a lock holder releases it (not on a suspension), so every collect that bumped to it has finished its walk. It is never newer than the locked read, and every use of it here asks that the stage's ranges hold no stamp after it, read before their values are; an older value only refuses more. A collect memo hit already answers with this value (2df7e993d3). Tested: agc_driver_heap_walk_capture_failure requires a walk memo hit to take the tracker mutex at most once per non-empty range list (GuestMemory::TrackerAcquisitions under APS5_PROFILE_DRAW); with the locked read it took it once over no ranges. --- .../prx/libSceAgcDriver/Execution/include/GuestMemory.hpp | 2 ++ .../Execution/src/Driver/Draw/HeapStages.cpp | 2 +- .../prx/libSceAgcDriver/Execution/src/GuestMemory.cpp | 8 ++++++++ .../tests/execution/HeapWalkCaptureFailure.cpp | 8 ++++++++ 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp index c027f5547906..b9b6da8b2cff 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp @@ -132,6 +132,8 @@ std::uint64_t CollectWritesUncached(std::uint64_t address, std::size_t bytes); // tracker mutex, so every collect that bumped before it has finished its walk and every later // collect stamps newer. std::uint64_t TrackerGeneration(); +std::uint64_t StableTrackerGeneration(); +std::uint64_t TrackerAcquisitions(); void AdvanceTrackerGenerationForTest(std::uint64_t generation); std::uint64_t NewestStamp(std::uint64_t address, std::size_t bytes); bool NoStampAfter(std::span> ranges, std::uint64_t generation); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 25efa39458fe..4fb978c24f4d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -585,7 +585,7 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade Graphics::HeapCostScope snapshotCost(Graphics::HeapCost::Guards); const auto before = Graphics::Recorder::PendingWriteSnapshot(); snapshotCost.Stop(); - const auto generation = GuestMemory::TrackerGeneration(); + const auto generation = GuestMemory::StableTrackerGeneration(); const bool memoOn = !invocation.Request().context.vertex.has_value(); std::uint64_t memoKey = 0; bool memoKnown = false; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp index a29442264eae..d79b1e86519b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp @@ -2468,6 +2468,14 @@ std::uint64_t TrackerGeneration() { return tracker.generation; } +std::uint64_t StableTrackerGeneration() { + return Tracker().stable.load(std::memory_order_acquire); +} + +std::uint64_t TrackerAcquisitions() { + return trackerAcquisitions.load(std::memory_order_relaxed); +} + void AdvanceTrackerGenerationForTest(std::uint64_t generation) { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp index e9107f4da25a..2dc82d9ae904 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" @@ -100,11 +101,18 @@ void MemoHitSharesWalkedWords(AgcDriver::VulkanDevice& device) { Require(walk.result != nullptr && walk.words != nullptr, "a repeated heap walk over valid buffer descriptors declined its stage"); } Require(walks[2].words == walks[1].words, "a heap walk memo hit returned a copy of the walked words instead of the words its walk stored"); + const auto before = AgcDriver::GuestMemory::TrackerAcquisitions(); + const auto hit = AgcDriver::DriverDetail::MaterializeHeapStage(*invocation, userData, request.shader.codeAddress); + const auto taken = AgcDriver::GuestMemory::TrackerAcquisitions() - before; + Require(hit.words == walks[1].words, "a repeated heap walk missed its memo"); + const std::uint64_t proofs = hit.reads.ranges != nullptr && !hit.reads.ranges->empty() ? 1u : 0u; + Require(taken <= proofs, "a heap walk memo hit took the guest write tracker's mutex " + std::to_string(taken) + " times; only its no-stamp proof over its " + std::to_string(proofs) + " range lists needs it"); } } int main() { + SetTestEnvironment("APS5_PROFILE_DRAW", "1"); try { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; From f07da0c3e8e2715ba8e7a9bf58c8ed65ca90d7ec Mon Sep 17 00:00:00 2001 From: Dean Galvin Date: Tue, 10 Nov 2026 11:08:01 +1300 Subject: [PATCH 165/269] fix(agc): do not share a ring stage's draw key when moved-buffer templates are off TemplateKeyWords() memoized a ring stage's content key on the template without checking MovableBuffers(). With APS5_NO_MOVED_BUFFER_TEMPLATES set, the key includes the per-draw ShaderData words, so later draws reused the first draw's key. Return false in that mode so each stage keeps its own memo. Adds a heap-ring draw-key arm with the variable set: it builds a key per draw (1024 over 512 draws), where the unfixed code built none after the first. The default arm is unchanged. Found in review of this PR; credit to the reviewers. --- core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp | 2 ++ .../tests/cmake/agc_driver_heap_ring_draw_key_tests.cmake | 2 ++ .../libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp | 7 ++++++- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 7f0ba502802f..dc9b562e3bab 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1275,6 +1275,8 @@ std::atomic& drawContentKeysBuilt() { } bool TemplateKeyWords(const CompiledShader& shader) { + // With moved buffers off the key carries the per-draw ShaderData words, so it cannot be shared on the template. + if (!MovableBuffers()) return false; const auto* heap = shader.heap; if (heap == nullptr || heap->base == nullptr || shader.program->heapTemplateId == 0) return false; const auto& bindings = shader.program->bindings; diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_ring_draw_key_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_ring_draw_key_tests.cmake index 5b04523b2510..c72737e907db 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_ring_draw_key_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_ring_draw_key_tests.cmake @@ -1,4 +1,6 @@ if(BUILD_TESTING) agc_add_draw_pipeline_test(agc_driver_heap_ring_draw_key) agc_add_gpu_heap_test(agc_driver_heap_ring_draw_key) + agc_add_env_test(agc_driver_heap_ring_draw_key_gpu_heap_fixed_buffers agc_driver_heap_ring_draw_key_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1 APS5_NO_MOVED_BUFFER_TEMPLATES=1) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp index 4add88aa29bc..7ab8695b1c9e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp @@ -308,7 +308,12 @@ int main() { Require(sets == 0, "walked heap draws allocated " + std::to_string(sets) + " rewritten descriptor sets that a descriptor heap pipeline never binds"); std::printf("walked draws allocated %llu rewritten descriptor sets\n", static_cast(sets)); if (heap && AgcDriver::Graphics::DescriptorHeapEnabled()) - Require(built * 8u < repeated, "repeated heap draws built " + std::to_string(built) + " resource-cache content keys over " + std::to_string(repeated) + " draws instead of reusing their stages' keys"); + { + if (std::getenv("APS5_NO_MOVED_BUFFER_TEMPLATES") == nullptr) + Require(built * 8u < repeated, "repeated heap draws built " + std::to_string(built) + " resource-cache content keys over " + std::to_string(repeated) + " draws instead of reusing their stages' keys"); + else + Require(built * 2u >= repeated, "with moved-buffer templates off, repeated heap draws built only " + std::to_string(built) + " content keys over " + std::to_string(repeated) + " draws, so a ring stage's key was shared across draws that carry different ShaderData words"); + } std::printf("repeated draws built %llu content keys over %zu draws\n", static_cast(built), repeated); AgcDriverShutdown_nid_postfix(); return 0; From f208a0245e6e69065d6cb89b06f1038b8246e47e Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 10 Nov 2026 02:39:26 +0530 Subject: [PATCH 166/269] perf(agc): patch a relocated heap draw's ring words instead of copying its program A draw relocated from a cached donor whose user words moved carried its data and V# patches by copying the whole RecompileResult (every binding's vectors) and, for heap ring stages, the ring template as well, on every relocated draw. GTA V relocates nearly every draw, so the decoder allocated eight objects per draw for these copies and the committer or finisher freed them, which the glibc arena lock serializes across the pipeline threads. A heap ring stage already reads every binding through its per-draw ring words (DrawGuestWords), which come from a recycled pool. A ring variant now keeps the shared program and records its patches (ringDescriptorPatches, ringDataPatches, inherited by later relocations of it); buildRingWords applies them to the ring words after CompleteHeapDataWords, filling each patched binding from the words DrawGuestWords would have returned. The program is still copied when a data patch lands in the program's push constants, or when a flattened SRT V# patch must stay with the program because the template carries no flattened SRT and the stage data words patch the program's copy. There is no vkd3d-proton counterpart: this is the per-draw PS5 descriptor translation step. Heap draw bench, fresh mode (SRT tables never repeat, so every draw relocates), game env (draw pipeline, finisher, 32 pipelined draws), us/draw medians: heap off 9.20-9.48, heap on 10.36-10.60 before, 8.17-8.48 after. Serial: heap off 14.76-14.92, heap on 14.50-14.62. --- .../include/Driver/Dispatch/DispatchCache.hpp | 2 + .../src/Driver/Dispatch/DispatchCache.cpp | 2 +- .../Execution/src/Driver/Draw/Draw.cpp | 24 ++++++++++ .../src/Driver/Draw/DrawRelocate.cpp | 48 ++++++++----------- 4 files changed, 46 insertions(+), 30 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp index 18b54be70f9b..7103ec1eb4d0 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp @@ -75,6 +75,8 @@ struct DispatchVariant { std::uint64_t userDataMask = ~std::uint64_t{0}; std::shared_ptr vertexInfo; std::shared_ptr ringTemplate; + std::vector> ringDescriptorPatches; + std::vector> ringDataPatches; std::shared_ptr memory; std::vector captured; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp index 73eaf8bcc44a..179c1298005d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp @@ -66,7 +66,7 @@ Driver::DispatchCacheFootprint Driver::DispatchCacheSize() { std::uint64_t Driver::variantBytes(const DispatchVariant& variant) { const auto held = [](const auto& values) { return static_cast(values.capacity() * sizeof(values[0])); }; - return sizeof(DispatchVariant) + held(variant.runs) + held(variant.words) + held(variant.shared) + held(variant.dataPositions) + held(variant.dataSlots) + held(variant.runBases) + held(variant.shaderDataPatches) + held(variant.captured) + held(variant.spans) + (variant.registeredViews != nullptr ? held(*variant.registeredViews) : 0u) + (variant.vertexInfo != nullptr ? sizeof(ShaderRecompiler::ShaderVertexStageInfo) : 0) + (variant.memory != nullptr ? variant.memory->Bytes() : 0); + return sizeof(DispatchVariant) + held(variant.runs) + held(variant.words) + held(variant.shared) + held(variant.dataPositions) + held(variant.dataSlots) + held(variant.runBases) + held(variant.shaderDataPatches) + held(variant.ringDescriptorPatches) + held(variant.ringDataPatches) + held(variant.captured) + held(variant.spans) + (variant.registeredViews != nullptr ? held(*variant.registeredViews) : 0u) + (variant.vertexInfo != nullptr ? sizeof(ShaderRecompiler::ShaderVertexStageInfo) : 0) + (variant.memory != nullptr ? variant.memory->Bytes() : 0); } void Driver::accountVariant(const DispatchVariant& variant, bool added) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 9b380505e59e..15853fc7cac9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -972,6 +972,30 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { words->bindings.clear(); } ShaderRecompiler::CompleteHeapDataWords(*variant.compiled, *words); + if (!variant.ringDescriptorPatches.empty() || !variant.ringDataPatches.empty()) { + const auto& program = variant.compiled->bindings; + if (words->bindings.empty()) words->bindings.resize(program.size()); + const auto own = [&](std::size_t index) -> std::vector& { + auto& descriptor = words->bindings[index]; + if (descriptor.empty()) { + const auto& source = Graphics::DrawGuestWords(*variant.compiled, words.get(), program[index]); + descriptor.assign(source.begin(), source.end()); + } + return descriptor; + }; + for (const auto& [binding, word, value] : variant.ringDescriptorPatches) { + if (binding >= program.size() || word >= program[binding].guestDescriptor.size()) continue; + auto& descriptor = own(binding); + if (word < descriptor.size()) descriptor[word] = value; + } + for (const auto& [slot, value] : variant.ringDataPatches) { + for (std::size_t index = 0; index < program.size(); ++index) { + if (program[index].role != ShaderRecompiler::DescriptorRole::ShaderData || slot >= program[index].guestDescriptor.size()) continue; + auto& descriptor = own(index); + if (slot < descriptor.size()) descriptor[slot] = value; + } + } + } if (words->vertexAttributes.empty()) return words; decodeVertexInfo(i); require(vertexInfos[i].has_value(), "a ring vertex hit has no vertex stage info"); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp index dc2198184217..0ac4a30db6b0 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp @@ -336,6 +336,8 @@ void Driver::relocateDrawEntry(const QueueState& queue, std::uint64_t alias, std copy->pushOffset = variant->pushOffset; copy->vertexInfo = variant->vertexInfo; copy->ringTemplate = variant->ringTemplate; + copy->ringDescriptorPatches = variant->ringDescriptorPatches; + copy->ringDataPatches = variant->ringDataPatches; for (const auto& move : moves) { if (move.program != i) continue; const auto delta = AlignedWord(move.to) - AlignedWord(move.from); @@ -363,41 +365,29 @@ void Driver::relocateDrawEntry(const QueueState& queue, std::uint64_t alias, std void Driver::applyShaderDataPatches(DispatchVariant& variant) { if (variant.shaderDataPatches.empty() && variant.descriptorPatches.empty()) return; - const bool templateOnly = variant.ringTemplate != nullptr && variant.shaderDataPatches.empty() && - std::all_of(variant.descriptorPatches.begin(), variant.descriptorPatches.end(), [&](const std::array& patch) { - if (patch[0] >= variant.compiled->bindings.size()) return true; - const auto role = variant.compiled->bindings[patch[0]].role; - return role != ShaderRecompiler::DescriptorRole::FlattenedSrt && role != ShaderRecompiler::DescriptorRole::ShaderData; - }); - if (templateOnly) { - auto ringTemplate = std::make_shared(*variant.ringTemplate); - if (ringTemplate->bindings.empty()) ringTemplate->bindings.resize(variant.compiled->bindings.size()); - for (const auto& [binding, word, value] : variant.descriptorPatches) { - if (binding >= ringTemplate->bindings.size()) continue; - auto& words = ringTemplate->bindings[binding]; - if (words.empty()) words = variant.compiled->bindings[binding].guestDescriptor; - if (word < words.size()) words[word] = value; + const auto& compiled = *variant.compiled; + if (variant.ringTemplate != nullptr) { + const bool templateSrt = !variant.ringTemplate->flattenedSrt.empty(); + bool programWords = false; + for (const auto& patch : variant.descriptorPatches) { + if (!templateSrt && patch[0] < compiled.bindings.size() && compiled.bindings[patch[0]].role == ShaderRecompiler::DescriptorRole::FlattenedSrt) programWords = true; + else variant.ringDescriptorPatches.push_back(patch); + } + for (const auto& patch : variant.shaderDataPatches) { + variant.ringDataPatches.push_back(patch); + if (!compiled.dataAddressPush && static_cast(patch.first) * sizeof(std::uint32_t) + sizeof(std::uint32_t) <= compiled.pushConstants.size()) programWords = true; + } + if (!programWords) { + variant.shaderDataPatches.clear(); + variant.descriptorPatches.clear(); + return; } - variant.ringTemplate = std::move(ringTemplate); - variant.descriptorPatches.clear(); - return; } - auto rebased = std::make_shared(*variant.compiled); + auto rebased = std::make_shared(compiled); for (const auto& [slot, value] : variant.shaderDataPatches) patchForwardedWord(*rebased, slot, value); for (const auto& [binding, word, value] : variant.descriptorPatches) { if (binding < rebased->bindings.size() && word < rebased->bindings[binding].guestDescriptor.size()) rebased->bindings[binding].guestDescriptor[word] = value; } - if (variant.ringTemplate != nullptr && !variant.descriptorPatches.empty()) { - auto ringTemplate = std::make_shared(*variant.ringTemplate); - if (ringTemplate->bindings.empty()) ringTemplate->bindings.resize(variant.compiled->bindings.size()); - for (const auto& [binding, word, value] : variant.descriptorPatches) { - if (binding >= ringTemplate->bindings.size()) continue; - auto& words = ringTemplate->bindings[binding]; - if (words.empty()) words = variant.compiled->bindings[binding].guestDescriptor; - if (word < words.size()) words[word] = value; - } - variant.ringTemplate = std::move(ringTemplate); - } variant.compiled = std::move(rebased); variant.shaderDataPatches.clear(); variant.descriptorPatches.clear(); From 3fdda79a3a6ce33eb9d7d66b9b040fce2fee4c7c Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 10 Nov 2026 02:40:13 +0530 Subject: [PATCH 167/269] test(agc): skip the ring draw key reuse count under APS5_VERIFY_DRAW_ENTRIES The entry verifier turns every draw-cache hit into a full rebuild, so each repeated draw builds its content key by design and the reuse count cannot hold under it. --- .../prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp index 7ab8695b1c9e..419a1c573b50 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp @@ -309,10 +309,10 @@ int main() { std::printf("walked draws allocated %llu rewritten descriptor sets\n", static_cast(sets)); if (heap && AgcDriver::Graphics::DescriptorHeapEnabled()) { - if (std::getenv("APS5_NO_MOVED_BUFFER_TEMPLATES") == nullptr) - Require(built * 8u < repeated, "repeated heap draws built " + std::to_string(built) + " resource-cache content keys over " + std::to_string(repeated) + " draws instead of reusing their stages' keys"); - else + if (std::getenv("APS5_NO_MOVED_BUFFER_TEMPLATES") != nullptr) Require(built * 2u >= repeated, "with moved-buffer templates off, repeated heap draws built only " + std::to_string(built) + " content keys over " + std::to_string(repeated) + " draws, so a ring stage's key was shared across draws that carry different ShaderData words"); + else if (std::getenv("APS5_VERIFY_DRAW_ENTRIES") == nullptr) + Require(built * 8u < repeated, "repeated heap draws built " + std::to_string(built) + " resource-cache content keys over " + std::to_string(repeated) + " draws instead of reusing their stages' keys"); } std::printf("repeated draws built %llu content keys over %zu draws\n", static_cast(built), repeated); AgcDriverShutdown_nid_postfix(); From 36d3735f3c6134b0a750ebb618e406834556d336 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 10 Nov 2026 02:43:47 +0530 Subject: [PATCH 168/269] fix(agc): read a heap stage's flattened SRT guard words from its draw words The poisoned-SRT fault records took the flattened SRT from the program's own binding, while a heap ring stage's SRT words live in its per-draw ring words (template SRT, fresh stage data words and relocation patches). Read them through DrawGuestWords like every other heap binding read. --- core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 8bcc131f6b23..f7b97eb40b1f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -2279,7 +2279,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons if (shader.program->poisonedSrtReads != 0) { const auto& programBindings = shader.program->bindings; const auto flat = std::find_if(programBindings.begin(), programBindings.end(), [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt; }); - if (flat != programBindings.end()) srtGuardFaults.push_back({IrStage(shader.stage), flat->guestDescriptor}); + if (flat != programBindings.end()) srtGuardFaults.push_back({IrStage(shader.stage), DrawGuestWords(shader, *flat)}); } const VkShaderStageFlags flags = VulkanStage(shader.stage); std::uint64_t stageStorageBuffers = 0; From 21d6bfbf1743038af6d9b3f93f72c780ff3178b2 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 10 Nov 2026 03:57:09 +0530 Subject: [PATCH 169/269] perf(agc): inline Require and move its throw out of line Require built its error string in the inline body, so the compiler kept it out of line and every check on the draw paths paid a call. The check is now always inlined and only the cold throw is a call. --- .../libSceAgcDriver/Graphics/include/Context.hpp | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index 527ae75f6e8b..765007cb3c55 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -52,8 +52,16 @@ class PipelineCacheSynchronization { mutable PrimedSharedMutex mutex; }; -inline void Require(bool condition, const std::string& reason) { - if (!condition) throw std::runtime_error("AGC graphics: " + reason); +[[noreturn, gnu::cold, gnu::noinline]] inline void RequireFailed(const std::string& reason) { + throw std::runtime_error("AGC graphics: " + reason); +} + +[[noreturn, gnu::cold, gnu::noinline]] inline void RequireFailed(const char* reason) { + throw std::runtime_error(std::string("AGC graphics: ") + reason); +} + +[[gnu::always_inline]] inline void Require(bool condition, const std::string& reason) { + if (!condition) [[unlikely]] RequireFailed(reason); } inline std::function& DeviceLostHook() { @@ -87,8 +95,8 @@ inline VkShaderModule CreateShaderModule(PFN_vkCreateShaderModule create, VkDevi return module; } -inline void Require(bool condition, const char* reason) { - if (!condition) throw std::runtime_error(std::string("AGC graphics: ") + reason); +[[gnu::always_inline]] inline void Require(bool condition, const char* reason) { + if (!condition) [[unlikely]] RequireFailed(reason); } struct DescriptorRejected : std::runtime_error { From 91decca2d3026809fb33e5833b2c11254f020d90 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 10 Nov 2026 03:57:09 +0530 Subject: [PATCH 170/269] perf(agc): skip comparing a GPU heap stage's shader data when it has the same origin A heap stage's non-user shader data words are fixed by where they came from: a walked capture's words never change after the walk, and a ring stage's words are its ring template's words plus the variant's patches. Each such source now carries a data origin id, and a stage whose words share the origin of its kept data skips the full word compare (vkd3d-proton only re-reads root parameters marked dirty). Patches that reach past the user words clear the origin, and APS5_VERIFY_GPU_HEAP still compares and throws on a mismatch. --- .../Execution/include/Driver/Draw/HeapStages.hpp | 2 ++ .../Execution/src/Driver/Draw/Draw.cpp | 4 ++++ .../Execution/src/Driver/Draw/DrawCapture.cpp | 2 ++ .../Execution/src/Driver/Draw/HeapStages.cpp | 6 ++++++ .../Graphics/include/ShaderResources.hpp | 2 ++ .../Graphics/src/ShaderResources.cpp | 13 +++++++++---- core/shader/recompiler/Recompiler.hpp | 1 + 7 files changed, 26 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index 89fbf66b86b7..c5cee8718688 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -45,6 +45,8 @@ void NoteHeapDirect(); void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const ShaderRecompiler::RecompileResult& expected, const ShaderRecompiler::ResourceCapture* expectedCapture = nullptr); std::uint64_t HeapStagesTaken(); + +std::uint64_t NextHeapDataOrigin(); std::uint64_t HeapRingHitsVerified(); std::uint64_t HeapRingHitsDiffering(); std::shared_ptr PatchedHeapResult(const ShaderRecompiler::RecompileResult& shared, diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 15853fc7cac9..64e772c61a07 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -62,6 +62,7 @@ std::shared_ptr RecycledRingWords() { candidate->userData.clear(); candidate->drawKeyMemo.words.store(nullptr, std::memory_order_relaxed); candidate->memoizeKey = false; + candidate->dataOrigin = 0; return candidate; } auto words = std::make_shared(); @@ -947,6 +948,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { words->flattenedSrt.clear(); for (auto& descriptor : words->bindings) descriptor.clear(); words->base = nullptr; + words->dataOrigin = ringTemplate.dataOrigin; if (!ringTemplate.flattenedSrt.empty()) { words->flattenedSrt = ringTemplate.flattenedSrt; if (&variant == matched[i].get() && stageData[i].compiled != nullptr) { @@ -985,10 +987,12 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { }; for (const auto& [binding, word, value] : variant.ringDescriptorPatches) { if (binding >= program.size() || word >= program[binding].guestDescriptor.size()) continue; + if (program[binding].role == ShaderRecompiler::DescriptorRole::ShaderData && word >= words->userData.size()) words->dataOrigin = 0; auto& descriptor = own(binding); if (word < descriptor.size()) descriptor[word] = value; } for (const auto& [slot, value] : variant.ringDataPatches) { + if (slot >= words->userData.size()) words->dataOrigin = 0; for (std::size_t index = 0; index < program.size(); ++index) { if (program[index].role != ShaderRecompiler::DescriptorRole::ShaderData || slot >= program[index].guestDescriptor.size()) continue; auto& descriptor = own(index); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 22aa983526bb..6d85384f925b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -272,6 +272,7 @@ std::shared_ptr Driver::materializeDraw if (request.target.gpuResolvedImages) { auto words = std::make_shared(); if (auto shared = invocation.MaterializeHeap(*capture, *words)) { + words->dataOrigin = NextHeapDataOrigin(); stageCapture.compiled = std::move(shared); stageCapture.heapWords = std::move(words); stageCapture.direct = true; @@ -369,6 +370,7 @@ void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawP if (ringTemplate->bindings[index] == program[index].guestDescriptor) ringTemplate->bindings[index].clear(); } } + ringTemplate->dataOrigin = NextHeapDataOrigin(); variant->ringTemplate = std::move(ringTemplate); } if (vertexInfos[i]) variant->vertexInfo = std::make_shared(*vertexInfos[i]); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 4fb978c24f4d..d0fb19d05a69 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -620,6 +620,7 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade auto words = std::make_shared(); auto result = invocation.MaterializeHeap(*capture, *words); if (result == nullptr) result = invocation.Materialize(*capture); + words->dataOrigin = NextHeapDataOrigin(); materializeCost.Stop(); const bool complete = !reads.failed && result != nullptr; HeapStageMaterialized materialized; @@ -635,6 +636,11 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade } +std::uint64_t NextHeapDataOrigin() { + static std::atomic next{0}; + return next.fetch_add(1, std::memory_order_relaxed) + 1u; +} + std::uint64_t HeapStagesTaken() { return heapStages().load(); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 3a912ab23a70..bb0d6e5834fc 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -762,6 +762,8 @@ class ShaderResources { }; KeptSpan data, flat, map; std::vector dataInput; + std::uint64_t dataOrigin = 0; + const void* dataProgram = nullptr; std::uint64_t inertProgram = 0; std::vector owned; VkShaderStageFlags laidOutFor = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index f7b97eb40b1f..3496a3967b85 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -5660,6 +5660,7 @@ void ShaderResources::forgetShaderDataWords(const CompiledShader& shader) { auto& stageState = heapStages[HeapStageIndex(shader.stage)]; stageState.data.mark.entry = 0; stageState.dataInput.clear(); + stageState.dataOrigin = 0; } if (const auto allocation = shaderDataAllocation(shader)) { allocations[*allocation].dataWords.clear(); @@ -7964,10 +7965,12 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl const auto userData = shader.heap != nullptr ? std::span(shader.heap->userData) : std::span{}; const auto userFront = static_cast(std::min(userData.size(), words.size())); - const bool sameWords = - binding.role == ShaderRecompiler::DescriptorRole::ShaderData && current && - stageState.dataInput.size() == words.size() + userData.size() && - std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront); + const auto origin = shaderData && shader.heap != nullptr ? shader.heap->dataOrigin : 0u; + const bool sameShape = shaderData && current && stageState.dataInput.size() == words.size() + userData.size(); + const bool sameOrigin = sameShape && origin != 0u && origin == stageState.dataOrigin && stageState.dataProgram == shader.program; + const bool sameWords = sameShape && (sameOrigin || std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)); + if (verifySlots && sameOrigin && !std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)) + throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data differs from the data of the same origin"); const auto userInput = stageState.dataInput.begin() + static_cast(words.size()); const bool sameInput = sameWords && std::equal(userData.begin(), userData.end(), userInput); if (sameInput && !verifySlots) { @@ -8011,6 +8014,8 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl heapOffsets[dataIndex] = heapSpan(spans, heap, stageState.data, patched, pushedUser); stageState.dataInput.assign(words.begin(), words.end()); stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); + stageState.dataOrigin = origin; + stageState.dataProgram = shader.program; } const bool unbound = stageState.key.empty() && !dataBindings && !heapTableMapSet[stageIndex] && stageState.imageSlots.empty() && stageState.samplerSlots.empty(); if (unbound && !addressedBuffers) stageState.inertProgram = programIdentity; diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 40e1680ab820..73c075825ab5 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -532,6 +532,7 @@ struct HeapStageWords { std::vector vertexAttributes; std::vector> bindings; std::shared_ptr base; + std::uint64_t dataOrigin = 0; ResultKeyMemo drawKeyMemo; bool memoizeKey = true; }; From 57066e7c0f8b39eca40a6a9b42427c467ad1d186 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 10 Nov 2026 04:14:29 +0530 Subject: [PATCH 171/269] perf(agc): evict the heap walk memo's least recently used keys The memo swapped its whole key set into a previous generation at the key cap and then drained two arbitrary previous keys per insert, so keys still in use were dropped in bursts and missed together, and the misses refilled the memo toward the next swap. Keys now keep a use order: a hit moves its key to the front, and both the key cap and the byte budget drop the least recently used keys first. --- .../include/Driver/Draw/HeapWalkMemo.hpp | 67 +++++++++---------- .../Execution/src/Driver/Draw/HeapStages.cpp | 16 +---- .../libSceAgcDriver/tests/HeapWalkMemo.cpp | 61 ++++++----------- 3 files changed, 51 insertions(+), 93 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp index c70fb8154ed3..e75e3efcf57b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp @@ -4,6 +4,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include #include +#include #include #include #include @@ -32,8 +33,6 @@ constexpr std::size_t HeapWalkWays = 4; constexpr std::size_t HeapWalkMemoKeys = 16384; -constexpr std::size_t HeapWalkDrain = 2; - constexpr std::size_t HeapWalkSeenKeys = 1u << 16; std::uint64_t HeapWalkEntryBytes(const HeapWalkEntry& entry); @@ -49,8 +48,12 @@ std::uint64_t HeapWalkWordsBytes(const ShaderRecompiler::HeapStageWords& words); std::uint64_t HeapWalkMemoBudget(); struct HeapWalkMemo { - std::unordered_map> current; - std::unordered_map> previous; + struct Slot { + std::vector ways; + std::list::iterator age; + }; + std::unordered_map entries; + std::list order; std::vector seen = std::vector(HeapWalkSeenKeys, 0); std::unordered_map> pins; std::uint64_t heldBytes = 0; @@ -65,25 +68,29 @@ struct HeapWalkMemo { } std::vector* find(std::uint64_t key) { - if (const auto found = current.find(key); found != current.end()) return &found->second; - const auto old = previous.find(key); - if (old == previous.end()) return nullptr; - auto moved = std::move(old->second); - previous.erase(old); - auto& ways = slot(key); - ways = std::move(moved); - return &ways; + const auto found = entries.find(key); + if (found == entries.end()) return nullptr; + order.splice(order.begin(), order, found->second.age); + return &found->second.ways; } void remember(std::uint64_t key, HeapWalkEntry entry) { - auto& ways = slot(key); - if (ways.size() >= HeapWalkWays) { - drop(ways.back()); - ways.pop_back(); + auto [found, inserted] = entries.try_emplace(key); + auto& slot = found->second; + if (inserted) { + order.push_front(key); + slot.age = order.begin(); + } else { + order.splice(order.begin(), order, slot.age); + } + if (slot.ways.size() >= HeapWalkWays) { + drop(slot.ways.back()); + slot.ways.pop_back(); } charge(entry); touch(entry); - ways.insert(ways.begin(), std::move(entry)); + slot.ways.insert(slot.ways.begin(), std::move(entry)); + while (entries.size() > HeapWalkMemoKeys) evictOldest(); if (budget != 0 && heldBytes > budget) trim(); } @@ -92,19 +99,6 @@ struct HeapWalkMemo { } private: - std::vector& slot(std::uint64_t key) { - for (std::size_t drained = 0; drained < HeapWalkDrain && !previous.empty(); ++drained) { - release(previous.begin()->second); - previous.erase(previous.begin()); - } - if (current.size() >= HeapWalkMemoKeys && !current.contains(key)) { - retirePrevious(); - previous = std::move(current); - current.clear(); - } - return current[key]; - } - template void pin(const std::shared_ptr& object, TSize size) { if (object == nullptr) return; @@ -138,13 +132,12 @@ struct HeapWalkMemo { unpin(entry.words.get()); } - void release(const std::vector& ways) { - for (const auto& entry : ways) drop(entry); - } - - void retirePrevious() { - for (const auto& [key, ways] : previous) release(ways); - previous.clear(); + void evictOldest() { + const auto key = order.back(); + const auto found = entries.find(key); + for (const auto& entry : found->second.ways) drop(entry); + entries.erase(found); + order.pop_back(); } void trim(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index d0fb19d05a69..ed0f44cc8b1d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -372,22 +372,8 @@ std::uint64_t HeapWalkMemoBudget() { } void HeapWalkMemo::trim() { - retirePrevious(); - if (heldBytes <= budget) return; - std::vector> stamps; - for (const auto& [key, ways] : current) { - for (const auto& entry : ways) stamps.emplace_back(entry.stored, key); - } - std::sort(stamps.begin(), stamps.end()); const auto target = budget / 4u * 3u; - for (const auto& [stored, key] : stamps) { - if (heldBytes <= target) break; - const auto ways = current.find(key); - const auto entry = std::find_if(ways->second.begin(), ways->second.end(), [&](const HeapWalkEntry& way) { return way.stored == stored; }); - drop(*entry); - ways->second.erase(entry); - if (ways->second.empty()) current.erase(ways); - } + while (heldBytes > target && order.size() > 1u) evictOldest(); } namespace { diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp index 1ff947209baf..cb432a9de44f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp @@ -32,16 +32,15 @@ HeapWalkEntry sizedEntry(std::size_t words, std::shared_ptr pinned; - for (const auto* generation : {&memo.current, &memo.previous}) { - for (const auto& [key, ways] : *generation) { - for (const auto& entry : ways) { - bytes += AgcDriver::DriverDetail::HeapWalkEntryOwnBytes(entry); - if (entry.capture != nullptr && pinned.insert(entry.capture.get()).second) bytes += AgcDriver::DriverDetail::HeapWalkCaptureBytes(*entry.capture); - if (entry.result != nullptr && pinned.insert(entry.result.get()).second) bytes += AgcDriver::DriverDetail::HeapWalkResultBytes(*entry.result); - if (entry.words != nullptr && pinned.insert(entry.words.get()).second) bytes += AgcDriver::DriverDetail::HeapWalkWordsBytes(*entry.words); - } + for (const auto& [key, slot] : memo.entries) { + for (const auto& entry : slot.ways) { + bytes += AgcDriver::DriverDetail::HeapWalkEntryOwnBytes(entry); + if (entry.capture != nullptr && pinned.insert(entry.capture.get()).second) bytes += AgcDriver::DriverDetail::HeapWalkCaptureBytes(*entry.capture); + if (entry.result != nullptr && pinned.insert(entry.result.get()).second) bytes += AgcDriver::DriverDetail::HeapWalkResultBytes(*entry.result); + if (entry.words != nullptr && pinned.insert(entry.words.get()).second) bytes += AgcDriver::DriverDetail::HeapWalkWordsBytes(*entry.words); } } + require(memo.order.size() == memo.entries.size(), "the heap walk memo ages " + std::to_string(memo.order.size()) + " keys for the " + std::to_string(memo.entries.size()) + " it holds"); require(pinned.size() == memo.pins.size(), "the heap walk memo pins " + std::to_string(memo.pins.size()) + " objects for the " + std::to_string(pinned.size()) + " its entries hold"); return bytes; } @@ -71,24 +70,21 @@ void oldestEntriesDroppedTests() { const auto* newest = memo.find(keys); require(newest != nullptr && newest->size() == 1 && newest->front().values->size() == words, "the newest heap walk entry is not findable under the budget"); require(!results.back().expired(), "the newest heap walk entry lost its result"); - std::cout << "the heap walk memo keeps " << memo.current.size() << " of " << keys << " entries within its budget of " << memo.budget << " bytes\n"; + std::cout << "the heap walk memo keeps " << memo.entries.size() << " of " << keys << " entries within its budget of " << memo.budget << " bytes\n"; } -void previousGenerationDroppedFirstTests() { - const auto tinyBytes = HeapWalkEntryBytes(sizedEntry(1)); - constexpr std::size_t largeWords = std::size_t{2} << 20u; - const auto largeBytes = HeapWalkEntryBytes(sizedEntry(largeWords)); +void keyCapDropsLeastRecentTests() { HeapWalkMemo memo; - memo.budget = largeBytes + 64 * tinyBytes; - require((HeapWalkMemoKeys + 1) * tinyBytes < memo.budget, "the generation fixture does not fit its budget"); - for (std::uint64_t key = 1; key <= HeapWalkMemoKeys + 1; ++key) memo.remember(key, sizedEntry(1)); - require(memo.previous.size() == HeapWalkMemoKeys && memo.current.size() == 1, "the heap walk memo did not start a generation at its key cap"); - requireWithinBudget(memo, "after the generation swap"); - memo.remember(HeapWalkMemoKeys + 2, sizedEntry(largeWords)); - requireWithinBudget(memo, "after the large entry"); - require(memo.previous.empty(), "the heap walk memo kept its previous generation over the budget"); - require(memo.find(HeapWalkMemoKeys + 1) != nullptr && memo.find(HeapWalkMemoKeys + 2) != nullptr, "the heap walk memo dropped current entries while its previous generation could go"); - std::cout << "the heap walk memo drops its previous generation before its current entries\n"; + memo.budget = 2 * (HeapWalkMemoKeys + 1) * HeapWalkEntryBytes(sizedEntry(1)); + for (std::uint64_t key = 1; key <= HeapWalkMemoKeys; ++key) memo.remember(key, sizedEntry(1)); + require(memo.find(1) != nullptr, "the heap walk memo dropped an entry below its key cap"); + memo.remember(HeapWalkMemoKeys + 1, sizedEntry(1)); + require(memo.entries.size() == HeapWalkMemoKeys, "the heap walk memo holds " + std::to_string(memo.entries.size()) + " keys, not its cap of " + std::to_string(HeapWalkMemoKeys)); + require(memo.find(1) != nullptr, "the heap walk memo dropped an entry hit just before it reached its key cap"); + require(memo.find(2) == nullptr, "the heap walk memo kept its least recently used key past its key cap"); + for (std::uint64_t key = 3; key <= HeapWalkMemoKeys + 1; ++key) require(memo.find(key) != nullptr, "the heap walk memo dropped key " + std::to_string(key) + ", more recent than the one its cap needed to drop"); + requireWithinBudget(memo, "after the key cap"); + std::cout << "the heap walk memo drops only its least recently used key at its key cap\n"; } void hitEntriesKeptTests() { @@ -107,22 +103,6 @@ void hitEntriesKeptTests() { std::cout << "the heap walk memo keeps its recently hit entries\n"; } -void promotedHitKeptTests() { - const auto tinyBytes = HeapWalkEntryBytes(sizedEntry(1)); - constexpr std::size_t largeWords = std::size_t{2} << 20u; - const auto largeBytes = HeapWalkEntryBytes(sizedEntry(largeWords)); - HeapWalkMemo memo; - memo.budget = largeBytes + 64 * tinyBytes; - for (std::uint64_t key = 1; key <= HeapWalkMemoKeys + 1; ++key) memo.remember(key, sizedEntry(1)); - auto* promoted = memo.find(1); - require(promoted != nullptr && memo.current.contains(1), "a hit did not move the heap walk entry into the current generation"); - memo.touch(promoted->front()); - memo.remember(HeapWalkMemoKeys + 2, sizedEntry(largeWords)); - requireWithinBudget(memo, "after the large entry"); - require(memo.find(1) != nullptr, "the heap walk memo dropped an entry promoted by a hit with its previous generation"); - std::cout << "the heap walk memo keeps an entry a hit promoted from its previous generation\n"; -} - void sharedResultsChargedOnceTests() { constexpr std::size_t resultWords = std::size_t{1} << 16u; auto result = std::make_shared(); @@ -150,9 +130,8 @@ void sharedResultsChargedOnceTests() { int main() { try { oldestEntriesDroppedTests(); - previousGenerationDroppedFirstTests(); + keyCapDropsLeastRecentTests(); hitEntriesKeptTests(); - promotedHitKeptTests(); sharedResultsChargedOnceTests(); std::cout << "heap walk memo budget tests passed\n"; return 0; From f7ca5e4f9f9dc33e4ab0082c123fbd70c23c8657 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 10 Nov 2026 04:18:27 +0530 Subject: [PATCH 172/269] perf(agc): keep a GPU heap stage's slots in one compact per-stage record Each heap stage kept an array of 65 per-kind slot vectors between the fields every draw reads, so a stage refresh touched about 1.5 KiB of mostly empty vectors spread over many cache lines per stage. The stage's image slots are now one list grouped by kind with a short list of kind ranges (the list the generation checks already used), and the fields a draw reads come first in the record, as vkd3d-proton keeps a root signature's per-draw masks together. --- .../Graphics/include/ShaderResources.hpp | 31 ++++++---- .../Graphics/src/ShaderResources.cpp | 59 ++++++++++--------- 2 files changed, 53 insertions(+), 37 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index bb0d6e5834fc..924f7c2a363d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -747,14 +747,26 @@ class ShaderResources { mutable std::array heapOffsets{}; void writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader); struct HeapStageState { + std::uint64_t inertProgram = 0; + std::uint64_t slotSerial = 0; + std::uint64_t dataOrigin = 0; + std::uint64_t pushedUserWords = 0; + const void* dataProgram = nullptr; + VkShaderStageFlags laidOutFor = 0; + std::uint32_t touchedEpoch = 0; + std::uint32_t pushedPlaced = 0; + std::vector owned; std::vector key; - std::array, static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)> slots; + struct KindRange { + std::uint32_t kind = 0; + std::uint32_t first = 0; + std::uint32_t count = 0; + }; std::vector imageSlots; + std::vector kindRanges; std::vector slotGenerations; std::vector samplerSlots; std::vector samplerGenerations; - std::uint64_t slotSerial = 0; - std::uint32_t touchedEpoch = 0; std::vector> dataPatches; struct KeptSpan { std::vector words; @@ -762,13 +774,12 @@ class ShaderResources { }; KeptSpan data, flat, map; std::vector dataInput; - std::uint64_t dataOrigin = 0; - const void* dataProgram = nullptr; - std::uint64_t inertProgram = 0; - std::vector owned; - VkShaderStageFlags laidOutFor = 0; - std::uint64_t pushedUserWords = 0; - std::uint32_t pushedPlaced = 0; + std::span Slots(std::uint32_t kind) const { + for (const auto& range : kindRanges) { + if (range.kind == kind) return std::span(imageSlots).subspan(range.first, range.count); + } + return {}; + } }; std::array heapStages; std::uint64_t heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words, std::uint64_t pushed = 0); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 3496a3967b85..f558b8df26d8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -7766,41 +7766,41 @@ void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, s namespace Abi = ShaderRecompiler::RuntimeAbi; constexpr auto bindingCount = static_cast(Abi::Binding::Count); constexpr auto absent = std::numeric_limits::max(); - for (auto& kindSlots : state.slots) kindSlots.clear(); + struct TakenStorage {}; + auto& taken = HostThreadLocal>, TakenStorage>(); + taken.clear(); state.samplerSlots.clear(); std::size_t cursor = 0; for (const auto bindingIndex : owned) { const auto& binding = bindings[bindingIndex]; const auto kind = binding.layout.binding % bindingCount; if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) { - auto& kindSlots = state.slots[kind]; for (const auto index : binding.imageAllocations) { if (index == absent) { ++cursor; - kindSlots.push_back(heap.AbsentSlot(kind, heapPlaceholderView(kind))); + taken.emplace_back(kind, heap.AbsentSlot(kind, heapPlaceholderView(kind))); continue; } const auto view = reinterpret_cast(key[cursor + 1]); cursor += 3; - kindSlots.push_back(takenSlot(heap.TextureSlot(kind, textures[index].get(), view, textures[index]->Layout()), "the global image heap is full")); + taken.emplace_back(kind, takenSlot(heap.TextureSlot(kind, textures[index].get(), view, textures[index]->Layout()), "the global image heap is full")); } } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { - auto& kindSlots = state.slots[kind]; for (const auto index : binding.imageAllocations) { if (index != absent && storageTextures[index] == nullptr && heapMultisampleStorageView(index) != VK_NULL_HANDLE) { const auto view = reinterpret_cast(key[cursor + 1]); cursor += 3; - kindSlots.push_back(takenSlot(heap.ViewSlot(kind, heapMultisampleStorageOwner(index), view), "the global storage image heap is full")); + taken.emplace_back(kind, takenSlot(heap.ViewSlot(kind, heapMultisampleStorageOwner(index), view), "the global storage image heap is full")); continue; } if (index == absent || storageTextures[index] == nullptr) { ++cursor; - kindSlots.push_back(heap.AbsentSlot(kind, heapPlaceholderView(kind))); + taken.emplace_back(kind, heap.AbsentSlot(kind, heapPlaceholderView(kind))); continue; } const auto view = reinterpret_cast(key[cursor + 1]); cursor += 3; - kindSlots.push_back(takenSlot(heap.StorageSlot(kind, storageTextures[index].get(), view), "the global storage image heap is full")); + taken.emplace_back(kind, takenSlot(heap.StorageSlot(kind, storageTextures[index].get(), view), "the global storage image heap is full")); } } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { for (std::size_t element = 0; element < binding.imageAllocations.size(); ++element) { @@ -7810,17 +7810,20 @@ void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, s } } } + std::stable_sort(taken.begin(), taken.end(), [](const auto& left, const auto& right) { return left.first < right.first; }); + state.imageSlots.clear(); + state.kindRanges.clear(); + for (const auto& [kind, slot] : taken) { + if (state.kindRanges.empty() || state.kindRanges.back().kind != kind) + state.kindRanges.push_back({kind, static_cast(state.imageSlots.size()), 0u}); + state.imageSlots.push_back(slot); + ++state.kindRanges.back().count; + } } void ShaderResources::noteHeapSlotGenerations(const BindlessHeap& heap, HeapStageState& state) { - state.imageSlots.clear(); state.slotGenerations.clear(); - for (const auto& kindSlots : state.slots) { - for (const auto slot : kindSlots) { - state.imageSlots.push_back(slot); - state.slotGenerations.push_back(heap.SlotGeneration(slot)); - } - } + for (const auto slot : state.imageSlots) state.slotGenerations.push_back(heap.SlotGeneration(slot)); state.samplerGenerations.clear(); for (const auto slot : state.samplerSlots) state.samplerGenerations.push_back(heap.SamplerGeneration(slot)); } @@ -7837,21 +7840,22 @@ void ShaderResources::verifyHeapSlots(const BindlessHeap& heap, const HeapStageS for (std::size_t element = 0; element < binding.imageAllocations.size(); ++element) { const auto index = binding.imageAllocations[element]; if (index == std::numeric_limits::max()) continue; - const bool bound = element < state.slots[kind].size(); + const auto kindSlots = state.Slots(kind); + const bool bound = element < kindSlots.size(); if (sampled) { ++checked; - if (!bound || heap.SlotTexture(kind, state.slots[kind][element]) != textures[index].get()) ++wrong; + if (!bound || heap.SlotTexture(kind, kindSlots[element]) != textures[index].get()) ++wrong; continue; } if (storageTextures[index] == nullptr) { const auto view = heapMultisampleStorageView(index); if (view == VK_NULL_HANDLE) continue; ++storageChecked; - if (!bound || !heap.SlotHoldsStorage(kind, state.slots[kind][element], heapMultisampleStorageOwner(index), view)) ++storageWrong; + if (!bound || !heap.SlotHoldsStorage(kind, kindSlots[element], heapMultisampleStorageOwner(index), view)) ++storageWrong; continue; } ++storageChecked; - if (!bound || !heap.SlotHoldsStorage(kind, state.slots[kind][element], storageTextures[index].get(), heapStorageView(index, binding.layout.binding))) ++storageWrong; + if (!bound || !heap.SlotHoldsStorage(kind, kindSlots[element], storageTextures[index].get(), heapStorageView(index, binding.layout.binding))) ++storageWrong; } } if ((checked.load() + storageChecked.load()) % 100000u < 8u) { @@ -7880,23 +7884,23 @@ void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const Hea constexpr auto bindingCount = static_cast(Abi::Binding::Count); constexpr auto metadataWords = sizeof(Abi::ResourceMetadata) / sizeof(std::uint32_t); const auto& program = *shader.program; - const auto& slots = stageState.slots; const auto& samplerSlots = stageState.samplerSlots; for (std::uint32_t image = 0; image < program.runtimeImageCount; ++image) { const auto offset = program.imageMetadataDword + image * metadataWords; const auto kind = patched[offset + offsetof(Abi::ResourceMetadata, binding) / 4u] % bindingCount; const bool storageKind = kind >= Abi::FirstStorageImageBinding && kind < static_cast(Abi::Binding::Samplers); - if (storageKind && (!Abi::GpuHeapStorageKind(kind) || slots[kind].empty())) continue; + const auto kindSlots = stageState.Slots(kind); + if (storageKind && (!Abi::GpuHeapStorageKind(kind) || kindSlots.empty())) continue; auto& first = patched[offset + offsetof(Abi::ResourceMetadata, firstElement) / 4u]; if (kind < Abi::FirstImageBinding) continue; - if (!(kind < slots.size() && first < slots[kind].size())) { + if (!(kind < bindingCount && first < kindSlots.size())) { ThrowHeapSlotMismatch( "AGC graphics: GPU-mode image metadata names an element the stage does not bind (stage %u, image %u of %u, kind %u, first %u, slots of the kind %zu, flags 0x%x, element count %u, bindings %zu, stage state reused %d)", static_cast(shader.stage), image, program.runtimeImageCount, kind, first, - kind < slots.size() ? slots[kind].size() : std::size_t{0}, patched[offset + offsetof(Abi::ResourceMetadata, flags) / 4u], + kindSlots.size(), patched[offset + offsetof(Abi::ResourceMetadata, flags) / 4u], patched[offset + offsetof(Abi::ResourceMetadata, elementCount) / 4u], bindings.size(), current ? 1 : 0); } - first = slots[kind][first]; + first = kindSlots[first]; } for (const auto& word : program.heapSlotWords) { Require(word.dword < patched.size(), "a GPU-mode slot word lies outside the shader data"); @@ -7908,13 +7912,14 @@ void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const Hea patched[word.dword] = samplerSlots[word.element]; continue; } - if (!(word.kind < slots.size() && word.element < slots[word.kind].size())) { + const auto wordSlots = stageState.Slots(word.kind); + if (!(word.kind < bindingCount && word.element < wordSlots.size())) { ThrowHeapSlotMismatch( "AGC graphics: a GPU-mode slot word names an image the stage does not bind (stage %u, kind %u, element %u, slots of the kind %zu, bindings %zu)", static_cast(shader.stage), word.kind, word.element, - word.kind < slots.size() ? slots[word.kind].size() : std::size_t{0}, bindings.size()); + wordSlots.size(), bindings.size()); } - patched[word.dword] = slots[word.kind][word.element]; + patched[word.dword] = wordSlots[word.element]; } const bool slotWords = !program.registrationModule; Require(slotWords || program.samplerSlotDword + samplerSlots.size() <= patched.size(), "GPU-mode sampler slots exceed the shader data"); From dfdaa94a7c45518f1e7510dfdfb3d5b038b28efb Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 10 Nov 2026 06:01:04 +0530 Subject: [PATCH 173/269] perf(agc): count why a moved buffer refuses an address-based template An address-based template hit whose read-only buffer moved and could not be rebound counted only as "moved GuestBuffers element", which does not say which check refused it. MovedReadOnlyBuffers now reports its refusal, and the draw profile prints the reasons, including the in-place checks: range not imported, alignment changed, or shared with a classic binding. Such a hit also counted a resource-cache miss twice, once when refused and again when its rebuild counted it. --- .../Graphics/include/ShaderResources.hpp | 4 +- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 16 +++++++- .../Graphics/src/ShaderResources.cpp | 40 ++++++++++++------- 3 files changed, 41 insertions(+), 19 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 924f7c2a363d..aec431f0a18f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -270,9 +270,9 @@ class ShaderResources { void CompleteDrawUse(const DrawUse& use) const; void BindDrawUse(VkCommandBuffer commands, VkPipelineLayout layout, const DrawUse* use) const; std::shared_ptr PrepareDrawBindings(Recorder& recorder, std::span moved = {}, bool movedOnly = false, const BdaResources* faultRecord = nullptr) const; - std::optional> MovedReadOnlyBuffers(std::span shaders, Recorder& recorder, const ColorTarget* target, bool* patchedData = nullptr) const; static std::uint64_t BytesUpToTarget(std::uint64_t address, std::uint64_t bytes, std::uint64_t stride, const ColorTarget* target); - enum class MoveRefusal : std::size_t { None, Shape, NotGuest, Written, Limit, Inaccessible, Overlap, Bindings, Count }; + enum class MoveRefusal : std::size_t { None, Shape, NotGuest, Written, Limit, Inaccessible, Overlap, Bindings, NotImported, Alignment, SharedBinding, Count }; + std::optional> MovedReadOnlyBuffers(std::span shaders, Recorder& recorder, const ColorTarget* target, bool* patchedData = nullptr, MoveRefusal* refusal = nullptr) const; struct MoveProof { MoveRefusal refusal = MoveRefusal::None; std::size_t buffers = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index dc9b562e3bab..1450a1fe6ca1 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -908,6 +908,11 @@ std::array, static_cast(AddressDrawReuse return counts; } +std::array, static_cast(ShaderResources::MoveRefusal::Count)>& addressMoveRefusals() { + static std::array, static_cast(ShaderResources::MoveRefusal::Count)> counts{}; + return counts; +} + void countAddressDrawReuse(AddressDrawReuse outcome) { addressDrawReuses()[static_cast(outcome)].fetch_add(1, std::memory_order_relaxed); } @@ -1052,6 +1057,12 @@ void reportDraw(const std::array& us, const ShaderResources: } AgcDriver::ProfilePrint_nid_no_patch("%s\n", reuse); profile.addressSeen = address; + std::string refusals = "[rescache] address-based moved-buffer refusals (cumulative):"; + for (std::size_t why = 1; why < addressMoveRefusals().size(); ++why) { + const auto count = addressMoveRefusals()[why].load(std::memory_order_relaxed); + if (count != 0) refusals += std::string(" ") + ShaderResources::MoveRefusalName(static_cast(why)) + " " + std::to_string(count); + } + AgcDriver::ProfilePrint_nid_no_patch("%s\n", refusals.c_str()); } profile.totalsUs.fill(0); profile.maxUs.fill(0); @@ -2251,7 +2262,8 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat auto* recorder = Recorder::Active(); std::optional> moved; bool patched = false; - if (valid && recorder != nullptr) moved = cached->MovedReadOnlyBuffers(shaders, *recorder, &state.color, &patched); + auto refusal = ShaderResources::MoveRefusal::None; + if (valid && recorder != nullptr) moved = cached->MovedReadOnlyBuffers(shaders, *recorder, &state.color, &patched, &refusal); if (moved.has_value()) { if (trimKey) CheckBufferAliases(shaders, state.color, draw.indexAddress, indexBytes); if (counted && verifyAddressDrawReuse()) verifyServedSpace(context, state, draw, shaders, snapshots, indexBytes, *cached); @@ -2266,7 +2278,7 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat } else if (valid || inUse) { if (valid && cached->SpaceReuse()) static_cast(cached->ReleaseSpace()); if (valid && counted) reuse = patched ? AddressDrawReuse::PatchedData : AddressDrawReuse::MovedBuffer; - countCache(&DrawProfile::cacheMisses); + if (valid && counted) addressMoveRefusals()[static_cast(refusal)].fetch_add(1, std::memory_order_relaxed); } else { if (cached->SpaceReuse()) static_cast(cached->ReleaseSpace()); SharedResourceCache().Remove(resolved.contentKey); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index f558b8df26d8..87cbb3360727 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -6831,28 +6831,32 @@ ShaderResources::DrawBindings::~DrawBindings() { release(fragmentLayout, fragmentAllocation); } -std::optional> ShaderResources::MovedReadOnlyBuffers(std::span shaders, Recorder& recorder, const ColorTarget* target, bool* patchedData) const { +std::optional> ShaderResources::MovedReadOnlyBuffers(std::span shaders, Recorder& recorder, const ColorTarget* target, bool* patchedData, MoveRefusal* refusal) const { + const auto refuse = [&](MoveRefusal why) { + if (refusal != nullptr) *refusal = why; + return std::optional>{}; + }; std::vector moved; std::size_t movedBytes = 0; if ((_set == VK_NULL_HANDLE && fragment.set == VK_NULL_HANDLE && !heapStage) || (usesBda && !spaceReuse)) return moved; for (const auto& shader : shaders) { - if (shader.program == nullptr) return std::nullopt; + if (shader.program == nullptr) return refuse(MoveRefusal::Shape); const bool heapShader = HeapShader(shader); for (const auto& binding : shader.program->bindings) { if (heapShader && (DataRole(binding.role) || binding.role == ShaderRecompiler::DescriptorRole::GuestImages || binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers)) continue; if (DataRole(binding.role)) { const auto kept = std::find_if(bindings.begin(), bindings.end(), [&](const Binding& item) { return item.layout.binding == binding.binding; }); - if (kept == bindings.end() || kept->allocations.size() != 1) return std::nullopt; + if (kept == bindings.end() || kept->allocations.size() != 1) return refuse(MoveRefusal::Shape); const auto index = kept->allocations.front(); const auto& item = allocations[index]; const auto& guestWords = DrawGuestWords(shader, binding); - if (item.guest || item.buffer == nullptr || item.size != guestWords.size() * sizeof(std::uint32_t)) return std::nullopt; + if (item.guest || item.buffer == nullptr || item.size != guestWords.size() * sizeof(std::uint32_t)) return refuse(MoveRefusal::Shape); const bool patched = std::any_of(dataPatches.begin(), dataPatches.end(), [&](const DataPatch& patch) { return patch.allocation == index; }); const bool same = !item.dataWords.empty() ? item.dataWords == guestWords : !patched && std::memcmp(item.buffer->Bytes().data(), guestWords.data(), item.size) == 0; if (same) continue; if (item.dataWords.empty() && patched) { if (patchedData != nullptr) *patchedData = true; - return std::nullopt; + return refuse(MoveRefusal::Bindings); } if (moved.empty()) moved.reserve(allocations.size()); moved.push_back({index, 0, item.size, guestWords}); @@ -6861,7 +6865,7 @@ std::optional> ShaderResources::MovedR if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; const auto& guestWords = DrawGuestWords(shader, binding); const auto kept = std::find_if(bindings.begin(), bindings.end(), [&](const Binding& item) { return item.layout.binding == binding.binding; }); - if (kept == bindings.end() || kept->allocations.size() != binding.count || guestWords.size() != static_cast(binding.count) * 4u) return std::nullopt; + if (kept == bindings.end() || kept->allocations.size() != binding.count || guestWords.size() != static_cast(binding.count) * 4u) return refuse(MoveRefusal::Shape); for (std::uint32_t element = 0; element < binding.count; ++element) { const auto* words = guestWords.data() + static_cast(element) * 4u; const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; @@ -6873,23 +6877,24 @@ std::optional> ShaderResources::MovedR const bool empty = size == 0 || address == 0; if (!item.guest) { if (empty) continue; - return std::nullopt; + return refuse(MoveRefusal::NotGuest); } if (item.address == address && item.size == size) continue; - if (written || empty || item.written || size > context.limits.maxStorageBufferRange) return std::nullopt; + if (written || empty || item.written) return refuse(MoveRefusal::Written); + if (size > context.limits.maxStorageBufferRange) return refuse(MoveRefusal::Limit); const auto begin = address - item.adjustment; const auto bytes = static_cast(GuestBufferMemory::ViewBytes(size, item.adjustment)); const bool behind = recorder.PendingWriteOverlaps(begin, bytes); const bool inPlace = (usesBda && heapStage) || (behind && heapShader && addressedBuffers); - if (behind && !inPlace) return std::nullopt; - if (!inPlace && bytes > maxDrawSnapshotBytes - movedBytes) return std::nullopt; - if (!GuestMemory::Accessible(reinterpret_cast(begin), bytes)) return std::nullopt; - if (guestMemory.WritesOverlap(begin, bytes) || PendingStorageOverlaps(begin, bytes, nullptr) || AnyShadowedOverlaps(begin, bytes)) return std::nullopt; + if (behind && !inPlace) return refuse(MoveRefusal::Overlap); + if (!inPlace && bytes > maxDrawSnapshotBytes - movedBytes) return refuse(MoveRefusal::Limit); + if (!GuestMemory::Accessible(reinterpret_cast(begin), bytes)) return refuse(MoveRefusal::Inaccessible); + if (guestMemory.WritesOverlap(begin, bytes) || PendingStorageOverlaps(begin, bytes, nullptr) || AnyShadowedOverlaps(begin, bytes)) return refuse(MoveRefusal::Overlap); if (behind) { const auto overlaps = [&](const std::shared_ptr& writer) { return writer != nullptr && writer->WritesOverlap(begin, bytes); }; - if (context.copiedWriters != nullptr && std::any_of(context.copiedWriters->begin(), context.copiedWriters->end(), overlaps)) return std::nullopt; + if (context.copiedWriters != nullptr && std::any_of(context.copiedWriters->begin(), context.copiedWriters->end(), overlaps)) return refuse(MoveRefusal::Overlap); const auto drawWriters = DrawCopiedWriters(); - if (std::any_of(drawWriters->begin(), drawWriters->end(), overlaps)) return std::nullopt; + if (std::any_of(drawWriters->begin(), drawWriters->end(), overlaps)) return refuse(MoveRefusal::Overlap); } VkDeviceAddressRangeEXT view{}; if (inPlace) { @@ -6904,7 +6909,9 @@ std::optional> ShaderResources::MovedR found = guestMemory.TryDescriptor(address, static_cast(size), adjustment, nullptr, &handle).has_value() && handle != 0; } const bool classic = std::any_of(bindings.begin(), bindings.end(), [&](const Binding& other) { return !(other.heap && other.addressed) && std::find(other.allocations.begin(), other.allocations.end(), index) != other.allocations.end(); }); - if (!found || adjustment != item.adjustment || classic) return std::nullopt; + if (!found) return refuse(MoveRefusal::NotImported); + if (adjustment != item.adjustment) return refuse(MoveRefusal::Alignment); + if (classic) return refuse(MoveRefusal::SharedBinding); } if (moved.empty()) moved.reserve(allocations.size()); moved.push_back({index, address, static_cast(size), {}, inPlace, view}); @@ -6925,6 +6932,9 @@ const char* ShaderResources::MoveRefusalName(MoveRefusal refusal) { case MoveRefusal::Inaccessible: return "unmapped"; case MoveRefusal::Overlap: return "pending write"; case MoveRefusal::Bindings: return "no bindings made"; + case MoveRefusal::NotImported: return "not imported"; + case MoveRefusal::Alignment: return "alignment changed"; + case MoveRefusal::SharedBinding: return "shared with a classic binding"; case MoveRefusal::Count: break; } return "?"; From 0d4e6c662ea397c1a0d43e2dad1411cb8e8387b7 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 10 Nov 2026 06:01:12 +0530 Subject: [PATCH 174/269] perf(agc): key heap address-based templates on their buffers' view alignment Heap mode keys a template without its read-only buffers' addresses and moves a buffer in place when it moves. An address-based heap template reads its moved buffers in place, which needs the buffer's alignment adjustment inside its view to be the template's. When a buffer moved to another offset modulo the view alignment the move was refused and the draw rebuilt its template. GTA V did this about 640 times per 10 s, all refused for a changed alignment, where heap off keys these templates per buffer address and hits. The draw key of such a draw now carries each read-only buffer's offset modulo the device's guest buffer view alignment, outside the template's memoized key words. Each alignment class gets its own template, and moves within a class are read in place as before. The in-place alignment check stays. The space reuse test now expects a draw at a new alignment to build once and draws moving between two alignments to reuse their templates. Its pending-fill case no longer relied on the previous step's alignment: a heap draw reads the moved buffer in place behind the fill. --- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 22 +++++++++++++ .../tests/execution/AddressDrawSpaceReuse.cpp | 31 +++++++++++++++---- 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 1450a1fe6ca1..69a7a1fb3e88 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1299,6 +1299,25 @@ bool TemplateKeyWords(const CompiledShader& shader) { return true; } +bool ReadsAddressTable(const CompiledShader& shader) { + return std::ranges::any_of(shader.program->bindings, [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable; }); +} + +void AppendMovedBufferAlignments(const CompiledShader& shader, std::uint64_t alignment, ResourceCache::Key& key) { + for (const auto& binding : shader.program->bindings) { + if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; + const auto& words = DrawGuestWords(shader, binding); + if (words.size() != static_cast(binding.count) * 4u) continue; + for (std::uint32_t element = 0; element < binding.count; ++element) { + const auto* descriptor = words.data() + static_cast(element) * 4u; + const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; + const bool empty = descriptor[2] == 0 || (descriptor[0] == 0 && (descriptor[1] & 0xffffu) == 0); + if (written || empty) continue; + key.push_back(static_cast(descriptor[0] & (alignment - 1u))); + } + } +} + ResourceCache::Key DrawResourceKey(const Context& context, std::span shaders, const ColorTarget& target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::uint64_t indexBytes, bool ranges) { ResourceCache::Key key; key.reserve(256); @@ -1309,6 +1328,8 @@ ResourceCache::Key DrawResourceKey(const Context& context, std::span(context.device)); key.push_back(static_cast(shaders.size())); + const bool inPlaceMoves = MovableBuffers() && AnyHeapShader(shaders) && std::ranges::any_of(shaders, ReadsAddressTable); + const auto alignment = inPlaceMoves ? static_cast(GuestBufferViewAlignment(context.limits)) : 0u; for (const auto& shader : shaders) { const auto sizeAt = key.size(); key.push_back(0u); @@ -1334,6 +1355,7 @@ ResourceCache::Key DrawResourceKey(const Context& context, std::span(key.size() - sizeAt - 1u); } key.push_back(colorAttachments); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp index 0ec36bed065e..73a392a94aab 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp @@ -66,6 +66,7 @@ constexpr std::size_t IndirectCodeOffset = 512; constexpr std::size_t PointerSlots = 1024; constexpr std::size_t MovedVerticesOffset = 32768; constexpr std::size_t ShiftedVerticesOffset = MovedVerticesOffset + 4100; +constexpr std::size_t ShiftedAgainVerticesOffset = ShiftedVerticesOffset + 4096; constexpr std::size_t RingSlotBytes = 256; constexpr std::size_t RingSlots = 8; constexpr std::uint32_t PinWaitMs = 4000; @@ -332,6 +333,7 @@ struct Scene { std::memcpy(vertices.Data(), Triangle.data(), sizeof(Triangle)); std::memcpy(vertices.Data() + MovedVerticesOffset, Triangle.data(), sizeof(Triangle)); std::memcpy(vertices.Data() + ShiftedVerticesOffset, Triangle.data(), sizeof(Triangle)); + std::memcpy(vertices.Data() + ShiftedAgainVerticesOffset, Triangle.data(), sizeof(Triangle)); vertices.Register(false); std::memcpy(code.Data() + VertexCodeOffset, VertexCode.data(), sizeof(VertexCode)); std::memcpy(code.Data() + PixelCodeOffset, PixelCode.data(), sizeof(PixelCode)); @@ -775,19 +777,31 @@ void RingRefusals(Scene& scene) { Require(outcomes[AddressDrawReuse::Reused] == 1 && outcomes.Total() == 1, "address draw space reuse: a draw whose read-only vertex buffer moved inside the space counted " + outcomes.Text() + ", expected one reuse with the buffer bound anew"); } if (HeapStages) { + { + const Outcomes outcomes; + scene.Fetch(ShiftedVerticesOffset); + const auto copies = AgcDriver::Graphics::DrawInputCopies(); + const auto color = scene.DrawnColor(); + Require(color == 170, "address draw space reuse: the draw after its vertex buffer moved off its view's alignment read " + std::to_string(color) + " instead of 170"); + Require(outcomes[AddressDrawReuse::Built] == 1 && outcomes.Total() == 1, "address draw space reuse: a heap-stage draw whose vertex buffer moved off its view's alignment counted " + outcomes.Text() + ", expected one build for the new alignment"); + Require(AgcDriver::Graphics::DrawInputCopies() == copies, "address draw space reuse: heap stages read a copy of a vertex buffer that moved off its view's alignment"); + } const Outcomes outcomes; - scene.Fetch(ShiftedVerticesOffset); const auto copies = AgcDriver::Graphics::DrawInputCopies(); - const auto color = scene.DrawnColor(); - Require(color == 170, "address draw space reuse: the draw after its vertex buffer moved off its view's alignment read " + std::to_string(color) + " instead of 170"); - Require(outcomes[AddressDrawReuse::MovedBuffer] == 1 && outcomes.Total() == 1, "address draw space reuse: a heap-stage draw whose vertex buffer moved off its view's alignment counted " + outcomes.Text() + ", expected one refusal for a moved GuestBuffers element"); - Require(AgcDriver::Graphics::DrawInputCopies() == copies, "address draw space reuse: heap stages read a copy of a vertex buffer that moved off its view's alignment"); + for (const auto offset : {ShiftedAgainVerticesOffset, MovedVerticesOffset, ShiftedVerticesOffset}) { + scene.Fetch(offset); + const auto color = scene.DrawnColor(); + Require(color == 170, "address draw space reuse: a draw whose vertex buffer moved between two view alignments read " + std::to_string(color) + " instead of 170"); + } + Require(outcomes[AddressDrawReuse::Reused] == 3 && outcomes.Total() == 3, "address draw space reuse: heap-stage draws whose vertex buffer moved between two view alignments counted " + outcomes.Text() + ", expected each alignment's build reused with the buffer read in place"); + Require(AgcDriver::Graphics::DrawInputCopies() == copies, "address draw space reuse: heap stages read a copy of a vertex buffer that moved between two view alignments"); } { std::memcpy(scene.spare.Data(), Triangle.data(), sizeof(Triangle)); constexpr std::size_t Filled = 64; const std::array pattern{}; const Outcomes outcomes; + const auto behindBefore = AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites(); scene.Fetch(scene.spare, 0); { std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); @@ -797,7 +811,12 @@ void RingRefusals(Scene& scene) { } const auto color = scene.Color(); Require(color == 170, "address draw space reuse: the draw whose moved vertex buffer a pending fill overlaps read " + std::to_string(color) + " instead of 170"); - Require(outcomes[AddressDrawReuse::MovedBuffer] == 1 && outcomes.Total() == 1, "address draw space reuse: a draw whose moved read-only vertex buffer a pending GPU write overlaps counted " + outcomes.Text() + ", expected one refusal for a moved GuestBuffers element"); + if (HeapStages) { + Require(outcomes[AddressDrawReuse::Reused] == 1 && outcomes.Total() == 1, "address draw space reuse: a heap-stage draw whose moved read-only vertex buffer a pending GPU write overlaps counted " + outcomes.Text() + ", expected one reuse reading the buffer in place"); + Require(AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites() > behindBefore, "address draw space reuse: a heap-stage draw whose moved vertex buffer a pending GPU write overlaps was not read in place behind the write"); + } else { + Require(outcomes[AddressDrawReuse::MovedBuffer] == 1 && outcomes.Total() == 1, "address draw space reuse: a draw whose moved read-only vertex buffer a pending GPU write overlaps counted " + outcomes.Text() + ", expected one refusal for a moved GuestBuffers element"); + } } scene.Fetch(0); scene.cachedVertex = false; From 4c2a7419709bac88fd74c776154662ece5bfafd2 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 10 Nov 2026 07:31:30 +0530 Subject: [PATCH 175/269] perf(agc): read heap stages' user data from a per-draw block A heap stage's user-data words now live in their own small block with its own root address, the way the PS5 delivers user SGPRs and vkd3d-proton gives per-draw constants a root CBV, instead of sharing the stage's shader-data block. A draw that changes only user words keeps the data block and writes just the user block. - Recompiler: new Binding::UserData and RootItem::UserData. User-word reads go to the user block (a uniform buffer from its pushed address when it fits, raw address otherwise); dynamically indexed reads pick the block by index. - Push layout: the user root is optional. It is placed after the mandatory roots and buffer pointers and before pushed data; a stage with no room reads its user words from the data block at the same dwords (its position defaults to NoPushPosition and the shader selects the ShaderData root), and the driver does not split it. - Push budget: the FlattenedSrt root (unread since the ring path was removed), SrtDwords (the visible SRT size is static: reads plus guard flags) and PagetableDwords (the BDA table header holds the count; a null-table check replaces the length check) are removed, so a stage needs no more push dwords than before. - The pushed-user-data keep and APS5_NO_PUSHED_USER_DATA_KEEP are removed; the pushed-word mask now applies to the user block. - Root item specialization IDs move to 8448 (between the mip counts and store quantization) with range checks. Runtime ABI 17, so stale disk caches and pipeline journals are rejected. GTA V heap on, same spot: 350-353 presents per 10 s (p50 28.1-28.4 ms) vs 348-351 before (p50 28.4-28.5 ms); upload pool writes 98 MiB per 10 s vs 138 MiB; 223 user-word-only rewrites per 10 s took the unsplit fallback. --- .../Graphics/include/BindlessHeap.hpp | 1 + .../Graphics/include/ShaderResources.hpp | 13 ++- .../Graphics/src/BindlessHeap.cpp | 26 ++++- .../Graphics/src/ShaderResources.cpp | 105 +++++++++++++----- .../Graphics/src/ShaderValidation.cpp | 5 +- .../tests/PushDataPlacements.cpp | 37 +++++- .../tests/ShaderDeviceProfile.cpp | 2 +- ...river_draw_recipe_moved_buffer_tests.cmake | 2 - .../tests/execution/DrawRecipeMovedBuffer.cpp | 5 +- .../src/DescriptorBindingBuilder.cpp | 3 +- .../recompiler/PipelineSpecialization.hpp | 7 +- core/shader/recompiler/PushDataLayout.hpp | 18 ++- core/shader/recompiler/RuntimeAbi.hpp | 11 +- .../SpirvBackend/SpirvEmitterState.hpp | 1 + .../SpirvMemory/SpirvBufferAccess.hpp | 1 + .../SpirvBackend/src/SpirvBdaLookup.cpp | 47 +++++--- .../src/SpirvMemory/SpirvBufferAccess.cpp | 34 +++++- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 12 +- docs/dev/ENVIRONMENT.md | 1 - 19 files changed, 253 insertions(+), 78 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index ed92dca8e172..ca2d62a61b50 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -288,6 +288,7 @@ void NoteImageTableBuild(); std::uint64_t ImageTableBuilds(); void NoteDataAddressPush(); void NotePushedUserDataKeep(); +void NoteUserWordsRewrite(std::size_t blockWords, std::size_t userWords); std::uint64_t PushedUserDataKeeps(); void NoteEmptyResourceSet(); std::uint64_t EmptyResourceSets(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index aec431f0a18f..634c791e48ac 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -243,7 +243,7 @@ class ShaderResources { DescriptorCache::SetAllocation allocation; std::vector snapshots; bool addressOffsets = false; - std::array heapOffsets{}; + std::array heapOffsets{}; std::vector addressOverrides; std::vector> movedReads; ~DrawBindings(); @@ -744,7 +744,7 @@ class ShaderResources { }; bool splitSets = false; bool heapStage = false; - mutable std::array heapOffsets{}; + mutable std::array heapOffsets{}; void writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader); struct HeapStageState { std::uint64_t inertProgram = 0; @@ -755,6 +755,8 @@ class ShaderResources { VkShaderStageFlags laidOutFor = 0; std::uint32_t touchedEpoch = 0; std::uint32_t pushedPlaced = 0; + std::uint32_t userWords = 0; + bool splitUser = false; std::vector owned; std::vector key; struct KindRange { @@ -772,7 +774,7 @@ class ShaderResources { std::vector words; BindlessHeap::SpanMark mark; }; - KeptSpan data, flat, map; + KeptSpan data, flat, map, user; std::vector dataInput; std::span Slots(std::uint32_t kind) const { for (const auto& range : kindRanges) { @@ -796,7 +798,9 @@ class ShaderResources { void takeHeapSlots(BindlessHeap& heap, HeapStageState& state, std::span owned, std::span key); static void noteHeapSlotGenerations(const BindlessHeap& heap, HeapStageState& state); void verifyHeapSlots(const BindlessHeap& heap, const HeapStageState& state, VkShaderStageFlags stageBit) const; - void patchHeapSlotWords(const CompiledShader& shader, const HeapStageState& stageState, std::vector& patched, bool current) const; + void patchHeapSlotWords(const CompiledShader& shader, const HeapStageState& stageState, std::vector& patched, bool current, bool leading = false) const; + std::pair writeSplitHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, + std::span words, std::span userData, bool sameWalk, bool current); static constexpr std::int64_t HeapRingDataFirst = -2; static constexpr std::int64_t HeapRingData(std::size_t stage) { return HeapRingDataFirst - static_cast(stage); } static constexpr bool IsHeapRingData(std::int64_t allocation) { return allocation <= HeapRingDataFirst && allocation > HeapRingDataFirst - static_cast(ShaderRecompiler::RuntimeAbi::StageCount); } @@ -824,7 +828,6 @@ class ShaderResources { VkDeviceAddress emptyAddress = 0; VkDeviceAddress resolvedGds = 0; std::size_t gdsAllocation = std::numeric_limits::max(); - std::array heapSrtDwords{}; std::array heapTableMaps{}; std::array heapTableMapSet{}; void writeHeapTableMap(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, std::size_t stageIndex); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 17125e56559a..95d168537238 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -80,6 +80,9 @@ std::atomic descriptorHeapDevice{false}; std::atomic imageTableBuilds{0}; std::atomic dataAddressPushes{0}; std::atomic pushedUserDataKeeps{0}; +std::atomic userWordsRewrites{0}; +std::atomic userWordsRewriteBlockWords{0}; +std::atomic userWordsRewriteUserWords{0}; std::atomic embeddedSamplerMappings{0}; std::atomic slotPressureSubmits{0}; std::atomic heapSlotEvictions{0}; @@ -112,6 +115,12 @@ void NotePushedUserDataKeep() { pushedUserDataKeeps.fetch_add(1, std::memory_order_relaxed); } +void NoteUserWordsRewrite(std::size_t blockWords, std::size_t userWords) { + userWordsRewrites.fetch_add(1, std::memory_order_relaxed); + userWordsRewriteBlockWords.fetch_add(blockWords, std::memory_order_relaxed); + userWordsRewriteUserWords.fetch_add(userWords, std::memory_order_relaxed); +} + std::uint64_t PushedUserDataKeeps() { return pushedUserDataKeeps.load(std::memory_order_relaxed); } @@ -1005,7 +1014,9 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& use.scratchPoolMemory = true; continue; } - if (set == Abi::GpuDataSet && binding % bindingCount == static_cast(Abi::Binding::ShaderData) && binding / bindingCount < Abi::StageCount) { + const auto dataKind = binding % bindingCount; + const bool dataBlock = dataKind == static_cast(Abi::Binding::ShaderData) || dataKind == static_cast(Abi::Binding::UserData); + if (set == Abi::GpuDataSet && dataBlock && binding / bindingCount < Abi::StageCount) { use.dataUniforms.push_back(binding); continue; } @@ -1085,7 +1096,9 @@ VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, co mapping.bindingCount = 1; mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT; mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; - mapping.sourceData.pushAddressOffset = rootItemOffset(placement, Abi::RootItem::ShaderData); + const bool user = binding % static_cast(Abi::Binding::Count) == static_cast(Abi::Binding::UserData); + const bool userPlaced = user && placement != nullptr && placement->Item(Abi::RootItem::UserData) != Abi::NoPushPosition; + mapping.sourceData.pushAddressOffset = rootItemOffset(placement, userPlaced ? Abi::RootItem::UserData : Abi::RootItem::ShaderData); return mapping; } @@ -1376,14 +1389,19 @@ void reportHeapStatistics() { const auto pushedKeepsTotal = PushedUserDataKeeps(); const auto pushedKeeps = windowDelta(pushedKeepsTotal, lastPushedKeeps); lastPushedKeeps = pushedKeepsTotal; + static std::array lastUserRewrites{}; + const std::array userRewriteTotals{userWordsRewrites.load(std::memory_order_relaxed), userWordsRewriteBlockWords.load(std::memory_order_relaxed), userWordsRewriteUserWords.load(std::memory_order_relaxed)}; + std::array userRewrites{}; + for (std::size_t i = 0; i < userRewrites.size(); ++i) userRewrites[i] = windowDelta(userRewriteTotals[i], lastUserRewrites[i]); + lastUserRewrites = userRewriteTotals; const auto templates = ShaderRecompiler::HeapTemplateCounts(); std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; excluded:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept (%llu for pushed user data only) / %llu expired; data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; image descriptors %llu encoded / %llu copied; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept (%llu for pushed user data only) / %llu expired, %llu written for user words only (%llu block words, %llu user words); data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; image descriptors %llu encoded / %llu copied; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), excluded.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(pushedKeeps), printed(spansExpired), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.spanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(pushedKeeps), printed(spansExpired), printed(userRewrites[0]), printed(userRewrites[1]), printed(userRewrites[2]), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.spanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 87cbb3360727..628fb555ea25 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -5659,6 +5659,7 @@ void ShaderResources::forgetShaderDataWords(const CompiledShader& shader) { if (HeapShader(shader)) { auto& stageState = heapStages[HeapStageIndex(shader.stage)]; stageState.data.mark.entry = 0; + stageState.user.mark.entry = 0; stageState.dataInput.clear(); stageState.dataOrigin = 0; } @@ -7239,8 +7240,8 @@ void ShaderResources::BindDrawUse(VkCommandBuffer commands, VkPipelineLayout lay namespace { std::size_t DataOffsetIndex(std::size_t stage, ShaderRecompiler::RuntimeAbi::Binding binding) { - Require(binding == ShaderRecompiler::RuntimeAbi::Binding::ShaderData || binding == ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt, "only shader data and the flattened SRT have ring offsets"); - return stage * 2u + (binding == ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt ? 1u : 0u); + Require(binding == ShaderRecompiler::RuntimeAbi::Binding::ShaderData || binding == ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt || binding == ShaderRecompiler::RuntimeAbi::Binding::UserData, "only shader data and the flattened SRT have ring offsets"); + return stage * 3u + (binding == ShaderRecompiler::RuntimeAbi::Binding::FlattenedSrt ? 1u : binding == ShaderRecompiler::RuntimeAbi::Binding::UserData ? 2u : 0u); } } @@ -7401,7 +7402,6 @@ void ShaderResources::PatchDataAddresses(std::spanheapOffsets : heapOffsets; VkDeviceAddress table = 0; VkDeviceAddress fault = 0; - std::uint32_t tableDwords = 0; const bool sameStages = rootRoles.count == shaders.size() && std::equal(shaders.begin(), shaders.end(), rootRoles.programs.begin(), [](const CompiledShader& shader, const ShaderRecompiler::RecompileResult* program) { return shader.program == program; }); if (!sameStages) { const auto binds = [&](ShaderRecompiler::DescriptorRole role) { @@ -7422,10 +7422,7 @@ void ShaderResources::PatchDataAddresses(std::spanTableAddress(); - tableDwords = static_cast(bda->Table().range / sizeof(std::uint32_t)); - } + if (tableBound) table = bda->TableAddress(); if (faultBound) fault = bda->FaultAddress(); } Require(placements.size() == shaders.size(), "the push layout does not describe the draw's stages"); @@ -7458,14 +7455,12 @@ void ShaderResources::PatchDataAddresses(std::spandataAddressPush) continue; const auto stage = HeapStageIndex(shader.stage); putAddress(Abi::RootItem::ShaderData, offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); - put(Abi::RootItem::FlattenedSrt, 0u, static_cast(offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)])); + putAddress(Abi::RootItem::UserData, offsets[DataOffsetIndex(stage, Abi::Binding::UserData)]); putAddress(Abi::RootItem::SrtAddress, offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)]); - put(Abi::RootItem::SrtDwords, 0u, heapSrtDwords[stage]); putAddress(Abi::RootItem::TableMap, heapTableMapSet[stage] ? heapTableMaps[stage] : offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); writePushedData(bytes, shader, placement.pushed); if (shader.program->pushedBufferCount != 0u) writePushedBuffers(bytes, stage, placement, addressed ? &rewritten->addressOverrides : nullptr, offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); @@ -7538,8 +7533,10 @@ void ShaderResources::writePushedData(std::span shaders) { - static const bool keepPushedUserData = std::getenv("APS5_NO_PUSHED_USER_DATA_KEEP") == nullptr; - const bool addressed = keepPushedUserData && std::ranges::any_of(shaders, [](const CompiledShader& shader) { return HeapShader(shader) && shader.program->dataAddressPush; }); + namespace Abi = ShaderRecompiler::RuntimeAbi; + const auto splits = [](const CompiledShader& shader) { return (shader.program->pushItems & Abi::RootItemBit(Abi::RootItem::UserData)) != 0u; }; + const bool addressed = std::ranges::any_of(shaders, [&](const CompiledShader& shader) { return HeapShader(shader) && shader.program->dataAddressPush; }); const auto placements = addressed ? PushDataPlacements(shaders) : std::vector{}; for (std::size_t shaderIndex = 0; shaderIndex < shaders.size(); ++shaderIndex) { const auto& shader = shaders[shaderIndex]; @@ -7700,8 +7698,10 @@ void ShaderResources::layOutHeapStages(std::span shaders) state.laidOutFor = stageBit; state.pushedUserWords = 0; state.pushedPlaced = 0; + state.splitUser = false; if (placements.empty() || !shader.program->dataAddressPush) continue; const auto& program = *shader.program; + state.splitUser = splits(shader) && placements[shaderIndex].Item(Abi::RootItem::UserData) != Abi::NoPushPosition; const auto placed = std::min(placements[shaderIndex].pushed.count, program.pushedData.size()); const auto userWords = std::max(program.heapUserWords.size(), program.shaderDataUserWords.size()); for (std::size_t item = 0; item < placed; ++item) { @@ -7889,13 +7889,14 @@ namespace { } void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const HeapStageState& stageState, - std::vector& patched, bool current) const { + std::vector& patched, bool current, bool leading) const { namespace Abi = ShaderRecompiler::RuntimeAbi; constexpr auto bindingCount = static_cast(Abi::Binding::Count); constexpr auto metadataWords = sizeof(Abi::ResourceMetadata) / sizeof(std::uint32_t); const auto& program = *shader.program; const auto& samplerSlots = stageState.samplerSlots; - for (std::uint32_t image = 0; image < program.runtimeImageCount; ++image) { + Require(!leading || program.runtimeImageCount == 0u || program.imageMetadataDword >= patched.size(), "GPU-mode image metadata lies among a stage's user words"); + for (std::uint32_t image = 0; !leading && image < program.runtimeImageCount; ++image) { const auto offset = program.imageMetadataDword + image * metadataWords; const auto kind = patched[offset + offsetof(Abi::ResourceMetadata, binding) / 4u] % bindingCount; const bool storageKind = kind >= Abi::FirstStorageImageBinding && kind < static_cast(Abi::Binding::Samplers); @@ -7913,6 +7914,7 @@ void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const Hea first = kindSlots[first]; } for (const auto& word : program.heapSlotWords) { + if (leading && word.dword >= patched.size()) continue; Require(word.dword < patched.size(), "a GPU-mode slot word lies outside the shader data"); if (word.kind == static_cast(Abi::Binding::Samplers)) { if (word.element >= samplerSlots.size()) { @@ -7932,10 +7934,59 @@ void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const Hea patched[word.dword] = wordSlots[word.element]; } const bool slotWords = !program.registrationModule; + if (leading) { + Require(slotWords || program.samplerSlotDword >= patched.size(), "GPU-mode sampler slots lie among a stage's user words"); + return; + } Require(slotWords || program.samplerSlotDword + samplerSlots.size() <= patched.size(), "GPU-mode sampler slots exceed the shader data"); if (!slotWords) std::copy(samplerSlots.begin(), samplerSlots.end(), patched.begin() + program.samplerSlotDword); } +std::pair ShaderResources::writeSplitHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, + std::span words, std::span userData, bool sameWalk, bool current) { + static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + const auto& program = *shader.program; + const auto userWords = std::min(std::max(program.heapUserWords.size(), program.shaderDataUserWords.size()), words.size()); + stageState.userWords = static_cast(userWords); + const auto applyUserData = [&](std::vector& target) { + std::copy_n(userData.begin(), std::min(userData.size(), target.size()), target.begin()); + for (const auto& [byte, adjustment] : stageState.dataPatches) { + if (byte < target.size() * sizeof(std::uint32_t)) reinterpret_cast(target.data())[byte] = static_cast(adjustment); + } + }; + struct PatchedStorage {}; + auto& patched = HostThreadLocal, PatchedStorage>(); + const bool dataKept = sameWalk && !verifySlots && heap.Held(stageState.data.mark); + auto dataAddress = stageState.data.mark.address; + if (!dataKept) { + ValidateRuntimeResources(shader, words); + patched.assign(words.begin(), words.end()); + for (const auto& [byte, adjustment] : stageState.dataPatches) { + Require(byte < patched.size() * sizeof(std::uint32_t), "a GPU-mode guest buffer offset lies outside the shader data"); + } + applyUserData(patched); + patchHeapSlotWords(shader, stageState, patched, current); + if (verifySlots && sameWalk && stageState.data.words.size() == patched.size() && + !std::equal(patched.begin() + static_cast(userWords), patched.end(), stageState.data.words.begin() + static_cast(userWords))) + throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its walked words and slots did not"); + dataAddress = heapSpan(spans, heap, stageState.data, patched); + stageState.dataInput.assign(words.begin(), words.end()); + stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); + stageState.dataOrigin = shader.heap != nullptr ? shader.heap->dataOrigin : 0u; + stageState.dataProgram = shader.program; + } + struct UserStorage {}; + auto& user = HostThreadLocal, UserStorage>(); + user.assign(words.begin(), words.begin() + static_cast(userWords)); + applyUserData(user); + patchHeapSlotWords(shader, stageState, user, current, true); + if (verifySlots && !std::equal(user.begin(), user.end(), patched.begin())) + throw std::runtime_error("AGC graphics: a GPU-mode stage's user-data block differs from the user words of its full shader data"); + const auto counted = std::min(userWords, 64u); + const auto pushedUser = stageState.pushedUserWords & (counted == 64u ? ~std::uint64_t{0} : (std::uint64_t{1} << counted) - 1u); + return {dataAddress, heapSpan(spans, heap, stageState.user, user, pushedUser)}; +} + void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader) { namespace Abi = ShaderRecompiler::RuntimeAbi; HeapCostScope slotsCost(HeapCost::Slots); @@ -7970,6 +8021,9 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl const std::size_t flatIndex = DataOffsetIndex(stageIndex, Abi::Binding::FlattenedSrt); const auto& program = *shader.program; if (program.dataAddressPush) writeHeapTableMap(spans, heap, shader, stageIndex); + const std::size_t userIndex = DataOffsetIndex(stageIndex, Abi::Binding::UserData); + const bool splitUser = stageState.splitUser; + stageState.userWords = 0; bool dataBindings = false; for (const auto& binding : program.bindings) { const bool shaderData = binding.role == ShaderRecompiler::DescriptorRole::ShaderData; @@ -7988,6 +8042,12 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data differs from the data of the same origin"); const auto userInput = stageState.dataInput.begin() + static_cast(words.size()); const bool sameInput = sameWords && std::equal(userData.begin(), userData.end(), userInput); + if (shaderData && splitUser) { + const auto [dataAddress, userAddress] = writeSplitHeapStage(spans, heap, shader, stageState, words, userData, sameWords, current); + heapOffsets[dataIndex] = dataAddress; + heapOffsets[userIndex] = userAddress; + continue; + } if (sameInput && !verifySlots) { if (heap.Held(stageState.data.mark)) { heapOffsets[dataIndex] = stageState.data.mark.address; @@ -7995,20 +8055,8 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl } stageState.data.mark.entry = 0; } - if (sameWords && !sameInput && !verifySlots && stageState.pushedUserWords != 0u && userData.size() <= 64u && stageState.data.words.size() >= userData.size()) { - bool pushedOnly = std::ranges::none_of(stageState.dataPatches, [&](const auto& patch) { return patch.first < userData.size() * sizeof(std::uint32_t); }); - for (std::size_t index = 0; pushedOnly && index < userData.size(); ++index) pushedOnly = userData[index] == userInput[static_cast(index)] || ((stageState.pushedUserWords >> index) & 1u) != 0u; - if (pushedOnly && heap.Held(stageState.data.mark)) { - std::copy(userData.begin(), userData.end(), stageState.data.words.begin()); - std::copy(userData.begin(), userData.end(), userInput); - heapOffsets[dataIndex] = stageState.data.mark.address; - NotePushedUserDataKeep(); - continue; - } - } if (!shaderData) { heapOffsets[flatIndex] = heapSpan(spans, heap, stageState.flat, words); - heapSrtDwords[stageIndex] = static_cast(words.size()); continue; } ValidateRuntimeResources(shader, words); @@ -8026,6 +8074,7 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its inputs and slots did not"); const auto userWords = std::min(userData.size(), 64u); const auto pushedUser = stageState.pushedUserWords & (userWords == 64u ? ~std::uint64_t{0} : (std::uint64_t{1} << userWords) - 1u); + if (sameWords) NoteUserWordsRewrite(patched.size(), userData.size()); heapOffsets[dataIndex] = heapSpan(spans, heap, stageState.data, patched, pushedUser); stageState.dataInput.assign(words.begin(), words.end()); stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index d904c3a937c5..868c1b31b944 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -648,9 +648,10 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi } else if (variable.storage == spv::StorageClassUniform) { namespace Abi = ShaderRecompiler::RuntimeAbi; constexpr auto bindingCount = static_cast(Abi::Binding::Count); + const auto kind = decoration.binding ? *decoration.binding % bindingCount : bindingCount; Require(shader.dataAddressPush && decoration.set && decoration.binding && *decoration.set == Abi::GpuDataSet && - *decoration.binding % bindingCount == static_cast(Abi::Binding::ShaderData), - "a uniform buffer is only the GPU heap's shader data"); + (kind == static_cast(Abi::Binding::ShaderData) || kind == static_cast(Abi::Binding::UserData)), + "a uniform buffer is only the GPU heap's shader data or user data"); } else { Require(variable.storage == spv::StorageClassStorageBuffer && decoration.set && decoration.binding, "unsupported or unbound shader resource"); const auto key = std::make_pair(*decoration.set, *decoration.binding); diff --git a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp index e5804fb28a0c..f6d258e446da 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp @@ -1,6 +1,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include "PushDataLayout.hpp" #include "RuntimeAbi.hpp" +#include "IntermediateRepresentation/IrMetadata/ShaderInfo.hpp" #include #include #include @@ -68,8 +69,9 @@ void disjoint(const std::vector& stages, const std::vector(item) == Item::UserData; + require(wanted == (position != Abi::NoPushPosition) || (optional && wanted), std::string("a stage's root items and its placement disagree: ") + what); + if (position == Abi::NoPushPosition) continue; const auto kind = static_cast(item); if (Abi::RootAddressItem(kind)) require(position % 2u == 0u, std::string("a root address is not 8-byte aligned: ") + what); claim(position, Abi::RootAddressItem(kind) ? 2u : 1u, static_cast(kind) < static_cast(Abi::RootItem::ShaderData)); @@ -100,7 +102,7 @@ void disjoint(const std::vector& stages, const std::vector stages{{ShaderStage::Vertex, vertexItems, 6}, {ShaderStage::Fragment, pixelItems, 30}}; @@ -110,11 +112,32 @@ int main() { require(place({stages[1]})[0] == placements[1], "a pixel stage that fits is placed as it is alone, so its fragment library is shared"); require(placements[0].Item(Item::PagetableAddress) != placements[1].Item(Item::PagetableAddress), "the pre-rasterization and fragment parts hold their own globals"); } + { + const auto user = Abi::RootItemBit(Item::UserData); + const std::vector stages{{ShaderStage::Vertex, vertexItems | user, 6, 4}, {ShaderStage::Fragment, pixelItems | user, 30, 4}}; + const auto placements = place(stages); + disjoint(stages, placements, 0, "vertex and pixel stages with user-data roots"); + require(placements[0].Item(Item::UserData) != Abi::NoPushPosition && placements[1].Item(Item::UserData) != Abi::NoPushPosition, "stages with room place their user-data roots"); + const std::vector without{{ShaderStage::Vertex, vertexItems, 6, 4}, {ShaderStage::Fragment, pixelItems, 30, 4}}; + const auto plain = place(without); + for (std::size_t index = 0; index < plain.size(); ++index) { + for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { + if (static_cast(item) != Item::UserData) require(plain[index].items[item] == placements[index].items[item], "a user-data root moves another root item"); + } + require(plain[index].bufferRoots == placements[index].bufferRoots, "a user-data root moves a pushed buffer"); + } + const auto pushedTotal = [](const std::vector& stages) { + std::size_t total = 0; + for (const auto& stage : stages) total += stage.pushed.count; + return total; + }; + require(pushedTotal(placements) + 2u * placements.size() >= pushedTotal(plain), "a user-data root takes more than its own dwords from pushed data"); + } { const std::vector stages{{ShaderStage::Vertex, vertexItems, 40}, {ShaderStage::Fragment, pixelItems, 40}}; const auto placements = place(stages); disjoint(stages, placements, 0, "stages that want too much"); - require(placements[0].pushed.count == 27 && placements[1].pushed.count == 26, "stages that want too much share the room evenly"); + require(placements[0].pushed.count == 26 && placements[1].pushed.count == 26, "stages that want too much share the room evenly"); } { const std::vector stages{{ShaderStage::Local, vertexItems, 4}, {ShaderStage::TessellationControl, bits({Item::PagetableAddress, Item::ShaderData}), 3}, {ShaderStage::TessellationEvaluation, vertexItems, 10}, {ShaderStage::Fragment, pixelItems, 48}}; @@ -193,6 +216,12 @@ int main() { require(Ids::IsPushPlacement(id), "a buffer root specialization id is not a push placement"); } for (std::uint32_t id = Ids::StoreQuantizeBase; id < Ids::DescriptorIndexBase; ++id) require(!Ids::IsPushPlacement(id), "a store quantization specialization id counts as a push placement"); + for (std::uint32_t id = Ids::HeapCountBase; id < Ids::MipCountBase + ShaderRecompiler::ShaderInfo::MaxImages; ++id) require(!Ids::IsPushPlacement(id), "a heap or mip count specialization id counts as a push placement"); + for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { + const auto id = Ids::RootItemPositionBase + item; + require(id >= Ids::MipCountBase + ShaderRecompiler::ShaderInfo::MaxImages && id < Ids::StoreQuantizeBase, "a root item specialization id lies inside another constant's range"); + require(Ids::IsPushPlacement(id), "a root item specialization id is not a push placement"); + } } { const auto all = (1u << Abi::RootItemCount) - 1u; diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp index ca7b65b6fbb5..bf7363e86031 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderDeviceProfile.cpp @@ -199,7 +199,7 @@ void CheckAbi() { Require(bindings.insert(BindingNumber(static_cast(stage), static_cast(binding))).second, "runtime ABI bindings overlap"); } } - Require(BindingNumber(Stage::Main, Binding::ShaderData) == 62u && BindingNumber(Stage::Fragment, Binding::ShaderData) == 127u, "runtime ABI binding numbers changed"); + Require(BindingNumber(Stage::Main, Binding::ShaderData) == 62u && BindingNumber(Stage::Fragment, Binding::ShaderData) == 128u, "runtime ABI binding numbers changed"); Require(BindingNumber(Stage::Main, Binding::ImageTable) == ShaderRecompiler::RuntimeAbi::ImageTableBinding && BindingNumber(Stage::TessellationEvaluation, Binding::ImageTable) == ShaderRecompiler::RuntimeAbi::ImageTableBinding && !bindings.contains(ShaderRecompiler::RuntimeAbi::ImageTableBinding), "the shared image table binding overlaps a stage binding"); for (std::uint32_t stage = 0u; stage < ShaderRecompiler::RuntimeAbi::StageCount; ++stage) { for (std::uint32_t binding = 0u; binding < static_cast(Binding::Count); ++binding) { diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake index 63716809287f..96a1ed2653d0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_recipe_moved_buffer_tests.cmake @@ -2,8 +2,6 @@ if(BUILD_TESTING) agc_add_gpu_heap_test(agc_driver_draw_recipe_moved_buffer) agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_overflow agc_driver_draw_recipe_moved_buffer_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_PUSHED_BUFFER_RECORDS=0) - agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_no_pushed_keep agc_driver_draw_recipe_moved_buffer_tests - ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_NO_PUSHED_USER_DATA_KEEP=1) agc_add_env_test(agc_driver_draw_recipe_moved_buffer_gpu_heap_unverified agc_driver_draw_recipe_moved_buffer_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp index 673300598a77..a5e062f12321 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp @@ -370,8 +370,9 @@ int main() { const auto keepsBefore = AgcDriver::Graphics::PushedUserDataKeeps(); for (int round = 0; round < 2; ++round) Require(Submit(slices) == SecondAlphaByte, "the draw of the moved buffer did not read it"); const auto keeps = AgcDriver::Graphics::PushedUserDataKeeps() - keepsBefore; - if (!AgcDriver::Graphics::DescriptorHeapEnabled() || std::getenv("APS5_NO_PUSHED_USER_DATA_KEEP") != nullptr) Require(keeps == 0u, "draws kept a shader-data block for pushed user data " + std::to_string(keeps) + " times with the keep off"); - else Require(keeps >= 2u, "heap draws whose only change was the moved buffer's pushed user words kept their shader-data block " + std::to_string(keeps) + " times, expected at least 2"); + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) Require(keeps == 0u, "draws without the GPU heap kept a pushed user-data block " + std::to_string(keeps) + " times"); + else Require(keeps >= 2u, "heap draws whose only change was the moved buffer's pushed user words kept their user-data block " + std::to_string(keeps) + " times, expected at least 2"); + const auto hitsBefore = AgcDriver::VulkanDevice::DrawRecipeHits(); const auto pathsBefore = AgcDriver::Graphics::HeapBufferPaths(); Require(Submit(slices) == SecondAlphaByte, "the repeated draw of the moved buffer did not read it"); diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index 4eaea8d85a36..47824ad434dc 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -20,7 +20,8 @@ namespace ShaderRecompiler { static_assert(PipelineSpecialization::ImageBase + ShaderInfo::MaxImages * PipelineSpecialization::ImageWords <= PipelineSpecialization::VertexBase); -static_assert(PipelineSpecialization::MipCountBase + ShaderInfo::MaxImages <= PipelineSpecialization::StoreQuantizeBase); +static_assert(PipelineSpecialization::MipCountBase + ShaderInfo::MaxImages <= PipelineSpecialization::RootItemPositionBase); +static_assert(PipelineSpecialization::RootItemPositionBase + PipelineSpecialization::RootItemPositions <= PipelineSpecialization::StoreQuantizeBase); static_assert(PipelineSpecialization::StoreQuantizeBase + ShaderInfo::MaxImages * PipelineSpecialization::StoreQuantizeWords <= PipelineSpecialization::DescriptorIndexBase); static_assert(PipelineSpecialization::CompareBase + ShaderInfo::MaxImages * PipelineSpecialization::CompareWords <= PipelineSpecialization::FoldOffsetBase); static_assert(PipelineSpecialization::FoldOffsetBase + ShaderInfo::MaxSamplers <= PipelineSpecialization::UnnormalizedBaseLevelBase); diff --git a/core/shader/recompiler/PipelineSpecialization.hpp b/core/shader/recompiler/PipelineSpecialization.hpp index 4298b44130b6..67dac7c81aa0 100644 --- a/core/shader/recompiler/PipelineSpecialization.hpp +++ b/core/shader/recompiler/PipelineSpecialization.hpp @@ -42,7 +42,8 @@ inline constexpr std::uint32_t WorkgroupOffsetBase = 8241u; inline constexpr std::uint32_t WorkgroupOffsetWords = 3u; inline constexpr std::uint32_t PushedDataBase = 8244u; inline constexpr std::uint32_t PushedDataCount = 8245u; -inline constexpr std::uint32_t RootItemPositionBase = 8246u; +inline constexpr std::uint32_t RootItemPositionBase = 8448u; +inline constexpr std::uint32_t RootItemPositions = 16u; inline constexpr std::uint32_t HeapCountBase = 8256u; inline constexpr std::uint32_t MipCountBase = 8320u; inline constexpr std::uint32_t StoreQuantizeBase = 12288u; @@ -65,8 +66,10 @@ inline constexpr std::uint32_t DescriptorIndex(std::uint32_t binding, std::uint3 return DescriptorIndexBase + binding * DescriptorIndexStride + element; } +static_assert(MipCountBase < RootItemPositionBase && RootItemPositionBase + RootItemPositions <= StoreQuantizeBase); + inline constexpr bool IsPushPlacement(std::uint32_t id) { - return id == PushedDataBase || id == PushedDataCount || (id >= BufferRootPosition && id <= BufferOverflowPosition) || (id >= RootItemPositionBase && id < HeapCountBase); + return id == PushedDataBase || id == PushedDataCount || (id >= BufferRootPosition && id <= BufferOverflowPosition) || (id >= RootItemPositionBase && id < RootItemPositionBase + RootItemPositions); } inline constexpr bool IsWorkgroupOffset(std::uint32_t id) { diff --git a/core/shader/recompiler/PushDataLayout.hpp b/core/shader/recompiler/PushDataLayout.hpp index 3c7f0914811d..4d0658a8d283 100644 --- a/core/shader/recompiler/PushDataLayout.hpp +++ b/core/shader/recompiler/PushDataLayout.hpp @@ -106,6 +106,7 @@ inline std::vector PlacePushData(std::span } }; constexpr auto globalItems = Abi::RootItemBit(Abi::RootItem::ShaderData) - 1u; + constexpr auto optionalItems = Abi::RootItemBit(Abi::RootItem::UserData); constexpr std::array parts{PushPart::Fragment, PushPart::Compute, PushPart::PreRasterization}; std::vector overflows(stages.size(), Abi::NoPushPosition); for (const auto part : parts) { @@ -122,7 +123,7 @@ inline std::vector PlacePushData(std::span for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { if ((stages[index].items & globalItems & (1u << item)) != 0u) placements[index].items[item] = shared[item]; } - placeRoot(stages[index].items & ~globalItems, top, placements[index].items); + placeRoot(stages[index].items & ~globalItems & ~optionalItems, top, placements[index].items); placements[index].pushedBuffers = stages[index].pushedBuffers; } } @@ -151,6 +152,16 @@ inline std::vector PlacePushData(std::span } used &= ~reserved; } + for (const auto part : parts) { + const bool top = part != PushPart::PreRasterization; + const auto reserved = part == PushPart::Fragment ? PushFeatureDwords(true, true, true) & ~used : 0u; + used |= reserved; + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part != part || (stages[index].items & Abi::RootItemBit(Abi::RootItem::UserData)) == 0u) continue; + placements[index].items[static_cast(Abi::RootItem::UserData)] = tryTake(2u, true, top); + } + used &= ~reserved; + } std::vector> runs; for (std::uint32_t dword = 0; dword < total;) { @@ -229,6 +240,8 @@ inline std::vector PlacePushData(std::span return placements; } +static_assert(RuntimeAbi::RootItemCount <= PipelineSpecialization::RootItemPositions); + inline StagePushPlacement StandalonePushPlacement(ShaderStage stage, std::uint32_t pushItems, std::size_t pushedWanted, std::uint32_t pushedBuffers = 0u) { const PushStage pushStage{PushPartOf(stage), pushItems & RootItemMask, static_cast(pushedWanted), pushedBuffers}; return PlacePushData(std::span(&pushStage, 1), StagePushFeatures(stage, pushItems)).front(); @@ -236,7 +249,8 @@ inline StagePushPlacement StandalonePushPlacement(ShaderStage stage, std::uint32 inline void AppendPushSpecialization(std::vector& constants, const StagePushPlacement& placement) { for (std::uint32_t item = 0; item < RuntimeAbi::RootItemCount; ++item) { - if (placement.items[item] != RuntimeAbi::NoPushPosition) constants.push_back({PipelineSpecialization::RootItemPositionBase + item, placement.items[item]}); + const bool optional = item == static_cast(RuntimeAbi::RootItem::UserData); + if (optional || placement.items[item] != RuntimeAbi::NoPushPosition) constants.push_back({PipelineSpecialization::RootItemPositionBase + item, placement.items[item]}); } for (std::uint32_t buffer = 0; buffer < std::min(placement.pushedBuffers, RuntimeAbi::PushedBufferLimit); ++buffer) constants.push_back({PipelineSpecialization::BufferRootPosition + buffer, placement.bufferRoots[buffer]}); if (placement.pushedBuffers != 0u) constants.push_back({PipelineSpecialization::BufferOverflowPosition, placement.bufferOverflow}); diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index 0622c8a0e0f2..634a2c4d2cc9 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -9,7 +9,7 @@ namespace ShaderRecompiler::RuntimeAbi { -inline constexpr std::uint32_t Version = 16u; +inline constexpr std::uint32_t Version = 17u; inline constexpr std::uint32_t DescriptorSet = 0u; inline constexpr std::uint32_t FragmentDescriptorSet = 1u; inline constexpr std::uint32_t StageCount = 4u; @@ -63,7 +63,8 @@ enum class Binding : std::uint32_t { ShaderData = 62u, SamplerTable = 63u, ImageTableMap = 64u, - Count = 65u, + UserData = 65u, + Count = 66u, ImageTable = 256u, ImageStorageTable = 257u }; @@ -97,12 +98,12 @@ inline constexpr std::uint32_t NoEmbeddedSampler = ~0u; inline constexpr std::uint32_t GdsBytes = 0x10000u; inline constexpr std::uint32_t PushDataDwords = 64u; inline constexpr std::uint32_t PushedDataWantedLimit = 48u; -enum class RootItem : std::uint32_t { PagetableAddress, FaultAddress, GdsAddress, PagetableDwords, StencilReference, ShaderData, TableMap, SrtAddress, FlattenedSrt, SrtDwords, Count }; +enum class RootItem : std::uint32_t { PagetableAddress, FaultAddress, GdsAddress, StencilReference, ShaderData, TableMap, SrtAddress, UserData, Count }; inline constexpr std::uint32_t RootItemCount = static_cast(RootItem::Count); inline constexpr std::uint32_t RootItemBit(RootItem item) { return 1u << static_cast(item); } inline constexpr bool RootAddressItem(RootItem item) { return item == RootItem::PagetableAddress || item == RootItem::FaultAddress || item == RootItem::GdsAddress || item == RootItem::ShaderData || item == RootItem::TableMap || - item == RootItem::SrtAddress; + item == RootItem::SrtAddress || item == RootItem::UserData; } inline constexpr std::uint32_t DepthRemapPushBit = 1u << 16u; inline constexpr std::uint32_t NoPushPosition = 0xffffffffu; @@ -193,7 +194,7 @@ inline bool UintStorageImageBinding(std::uint32_t number) { } static_assert(FirstImageBinding + ImageBindingCount == static_cast(Binding::Samplers)); -static_assert(static_cast(Binding::ImageTable) > static_cast(Binding::Count) && ImageStorageTableBinding == 260u && ImageTableBinding == 261u); +static_assert(static_cast(Binding::ImageTable) > static_cast(Binding::Count) && ImageStorageTableBinding == 264u && ImageTableBinding == 265u); } diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index 2d7250854b4d..7472f75ce4d9 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -244,6 +244,7 @@ struct SpirvEmitterState { std::uint32_t pushConstantVariable = 0; std::uint32_t shaderDataStorageVariable = 0; std::uint32_t shaderDataUniformVariable = 0; + std::uint32_t userDataUniformVariable = 0; std::uint32_t pushItems = 0; std::unordered_map heapSlotVariables; std::uint32_t flattenedSrtVariable = 0; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp index eda4baeedfb5..1ad0c6c25689 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp @@ -21,6 +21,7 @@ std::uint32_t EmitRootAddress(SpirvEmitterState& state, RuntimeAbi::RootItem ite std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index); bool HasFlattenedSrt(const SpirvEmitterState& state); +bool SplitUserData(const SpirvEmitterState& state); void EmitMemoryOffsets(SpirvEmitterState& state); std::uint32_t LoadTableMap(SpirvEmitterState& state, std::uint32_t index); std::uint32_t LoadHeapSlotWord(SpirvEmitterState& state, std::uint32_t dword); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp index c1ae3df21d13..433d72e39796 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp @@ -65,21 +65,42 @@ std::uint32_t DefineBdaLookup(SpirvEmitterState& state, const char* name, bool r } leaveIf(binary(spv::OpINotEqual, boolean, reason, constant(0u)), reason); }; - auto length = state.BdaAddressed() ? EmitRootItemDword(state, RuntimeAbi::RootItem::PagetableDwords, 0u) : state.module.AllocateId(); - if (!state.BdaAddressed()) state.module.AddFunction(spv::OpArrayLength, u32, length, state.bdaPagetableVariable, 0u); - fail(binary(spv::OpULessThan, boolean, length, constant(4)), BdaAbi::FaultReason::InvalidTable); + std::uint32_t length = 0; + if (state.BdaAddressed()) { + const auto table = EmitRootAddress(state, RuntimeAbi::RootItem::PagetableAddress); + fail(binary(spv::OpIEqual, boolean, table, BdaConstant(state, 0u)), BdaAbi::FaultReason::InvalidTable); + } else { + length = state.module.AllocateId(); + state.module.AddFunction(spv::OpArrayLength, u32, length, state.bdaPagetableVariable, 0u); + fail(binary(spv::OpULessThan, boolean, length, constant(4)), BdaAbi::FaultReason::InvalidTable); + } const auto count = BdaLoadWord(state, constant(1)); - const auto available = binary(spv::OpISub, u32, length, constant(4)); const auto end = binary(spv::OpIAdd, u64, address, Unary(state, spv::OpUConvert, u64, bytes)); - failFirst({ - {binary(spv::OpINotEqual, boolean, BdaLoadWord(state, constant(0)), constant(BdaAbi::Version)), BdaAbi::FaultReason::InvalidTable}, - {binary(spv::OpINotEqual, boolean, BdaLoadWord(state, constant(2)), constant(sizeof(BdaAbi::Range))), BdaAbi::FaultReason::InvalidTable}, - {binary(spv::OpINotEqual, boolean, BdaLoadWord(state, constant(3)), constant(0)), BdaAbi::FaultReason::InvalidTable}, - {binary(spv::OpINotEqual, boolean, binary(spv::OpBitwiseAnd, u32, available, constant(7)), constant(0)), BdaAbi::FaultReason::InvalidTable}, - {binary(spv::OpINotEqual, boolean, count, binary(spv::OpShiftRightLogical, u32, available, constant(3))), BdaAbi::FaultReason::InvalidTable}, - {binary(spv::OpIEqual, boolean, bytes, constant(0)), BdaAbi::FaultReason::Overflow}, - {binary(spv::OpULessThanEqual, boolean, end, address), BdaAbi::FaultReason::Overflow}, - }); + const auto version = binary(spv::OpINotEqual, boolean, BdaLoadWord(state, constant(0)), constant(BdaAbi::Version)); + const auto entryBytes = binary(spv::OpINotEqual, boolean, BdaLoadWord(state, constant(2)), constant(sizeof(BdaAbi::Range))); + const auto reserved = binary(spv::OpINotEqual, boolean, BdaLoadWord(state, constant(3)), constant(0)); + const auto empty = binary(spv::OpIEqual, boolean, bytes, constant(0)); + const auto wrapped = binary(spv::OpULessThanEqual, boolean, end, address); + if (state.BdaAddressed()) { + failFirst({ + {version, BdaAbi::FaultReason::InvalidTable}, + {entryBytes, BdaAbi::FaultReason::InvalidTable}, + {reserved, BdaAbi::FaultReason::InvalidTable}, + {empty, BdaAbi::FaultReason::Overflow}, + {wrapped, BdaAbi::FaultReason::Overflow}, + }); + } else { + const auto available = binary(spv::OpISub, u32, length, constant(4)); + failFirst({ + {version, BdaAbi::FaultReason::InvalidTable}, + {entryBytes, BdaAbi::FaultReason::InvalidTable}, + {reserved, BdaAbi::FaultReason::InvalidTable}, + {binary(spv::OpINotEqual, boolean, binary(spv::OpBitwiseAnd, u32, available, constant(7)), constant(0)), BdaAbi::FaultReason::InvalidTable}, + {binary(spv::OpINotEqual, boolean, count, binary(spv::OpShiftRightLogical, u32, available, constant(3))), BdaAbi::FaultReason::InvalidTable}, + {empty, BdaAbi::FaultReason::Overflow}, + {wrapped, BdaAbi::FaultReason::Overflow}, + }); + } const auto header = state.module.AllocateId(); const auto body = state.module.AllocateId(); const auto continuation = state.module.AllocateId(); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 9915df597c44..32d240f10400 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -80,7 +80,16 @@ std::uint32_t EmitRootItemDword(SpirvEmitterState& state, RuntimeAbi::RootItem i if (!state.program.Metadata().bindings.UsesDataAddress()) FailEmit("the root is read only by stages that take their data through it"); state.pushItems |= RuntimeAbi::RootItemBit(item); const auto u32 = TypeU32(state); - const auto position = state.module.SpecializationConstant(u32, PipelineSpecialization::RootItemPositionBase + static_cast(item), 0u); + std::uint32_t position = 0; + if (item == RuntimeAbi::RootItem::UserData) { + state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::ShaderData); + const auto user = state.module.SpecializationConstant(u32, PipelineSpecialization::RootItemPositionBase + static_cast(item), RuntimeAbi::NoPushPosition); + const auto data = state.module.SpecializationConstant(u32, PipelineSpecialization::RootItemPositionBase + static_cast(RuntimeAbi::RootItem::ShaderData), 0u); + const auto placed = Binary(state, spv::OpINotEqual, TypeBool(state), user, ConstantU32(state, RuntimeAbi::NoPushPosition)); + position = Select(state, u32, placed, user, data); + } else { + position = state.module.SpecializationConstant(u32, PipelineSpecialization::RootItemPositionBase + static_cast(item), 0u); + } const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), word == 0u ? position : Binary(state, spv::OpIAdd, u32, position, ConstantU32(state, word))); const auto value = state.module.AllocateId(); @@ -160,13 +169,14 @@ std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::Roo namespace { std::uint32_t dataAddressLoad(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index) { - if (item == RuntimeAbi::RootItem::ShaderData && state.shaderDataUniformVariable != 0u) { + const auto uniform = item == RuntimeAbi::RootItem::ShaderData ? state.shaderDataUniformVariable : item == RuntimeAbi::RootItem::UserData ? state.userDataUniformVariable : 0u; + if (uniform != 0u) { const auto u32 = TypeU32(state); const auto vector = Binary(state, spv::OpShiftRightLogical, u32, index, ConstantU32(state, 2u)); const auto component = Binary(state, spv::OpBitwiseAnd, u32, index, ConstantU32(state, 3u)); const auto u32x4 = TypeU32Vector(state, 4); const auto element = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassUniform, u32x4), element, state.shaderDataUniformVariable, ConstantU32(state, 0u), vector); + state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassUniform, u32x4), element, uniform, ConstantU32(state, 0u), vector); const auto words = state.module.AllocateId(); state.module.AddFunction(spv::OpLoad, u32x4, words, element); const auto value = state.module.AllocateId(); @@ -183,7 +193,19 @@ bool HasFlattenedSrt(const SpirvEmitterState& state) { return state.flattenedSrtVariable != 0 || state.flattenedSrtAddressed; } +bool SplitUserData(const SpirvEmitterState& state) { + const auto& layout = state.program.Metadata().bindings; + return layout.UsesDataAddress() && !layout.userDataRegisters.empty(); +} + std::uint32_t EmitShaderDataWordLoad(SpirvEmitterState& state, std::uint32_t index) { + if (SplitUserData(state)) { + const auto u32 = TypeU32(state); + const auto userWords = static_cast(state.program.Metadata().bindings.userDataRegisters.size()); + const auto user = Binary(state, spv::OpULessThan, TypeBool(state), index, ConstantU32(state, userWords)); + const auto userValue = dataAddressLoad(state, RuntimeAbi::RootItem::UserData, Select(state, u32, user, index, ConstantU32(state, 0u))); + return Select(state, u32, user, userValue, dataAddressLoad(state, RuntimeAbi::RootItem::ShaderData, index)); + } if (state.program.Metadata().bindings.UsesDataAddress()) return dataAddressLoad(state, RuntimeAbi::RootItem::ShaderData, index); if (state.shaderDataStorageVariable == 0) FailEmit("shader data is neither in push constants nor in a storage buffer"); const auto pointer = state.module.AllocateId(); @@ -196,7 +218,8 @@ std::uint32_t EmitShaderDataWordLoad(SpirvEmitterState& state, std::uint32_t ind std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index) { if (state.flattenedSrtAddressed) { const auto u32 = TypeU32(state); - const auto dwords = EmitRootItemDword(state, RuntimeAbi::RootItem::SrtDwords, 0u); + const auto& resources = state.program.Resources(); + const auto dwords = ConstantU32(state, resources.srtGuardOffset + static_cast(resources.guardedSrtSlots.size())); const auto inBounds = Binary(state, spv::OpULessThan, TypeBool(state), index, dwords); const auto last = Select(state, u32, Binary(state, spv::OpIEqual, TypeBool(state), dwords, ConstantU32(state, 0u)), ConstantU32(state, 0u), Binary(state, spv::OpISub, u32, dwords, ConstantU32(state, 1u))); const auto clamped = Select(state, u32, inBounds, index, last); @@ -215,7 +238,8 @@ std::uint32_t EmitShaderDataDwordLoad(SpirvEmitterState& state, std::uint32_t dw const IrBindingLayout& layout = state.program.Metadata().bindings; if (layout.UsesDataAddress()) { const auto pushed = std::ranges::find(layout.pushedData, dwordIndex); - const auto ring = dataAddressLoad(state, RuntimeAbi::RootItem::ShaderData, ConstantU32(state, dwordIndex)); + const bool user = SplitUserData(state) && dwordIndex < layout.userDataRegisters.size(); + const auto ring = dataAddressLoad(state, user ? RuntimeAbi::RootItem::UserData : RuntimeAbi::RootItem::ShaderData, ConstantU32(state, dwordIndex)); if (pushed == layout.pushedData.end()) return ring; return EmitPushedDataSelect(state, static_cast(pushed - layout.pushedData.begin()), ring); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index c10d0b3c610b..26204fbe315a 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -7,6 +7,7 @@ #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" #include "SpirvBackend/SpirvMemory/SpirvDescriptors.hpp" #include "SpirvBackend/SpirvMemory/SpirvInputOutput.hpp" +#include "SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp" #include #include #include @@ -604,7 +605,6 @@ void DefineDescriptors(SpirvEmitterState& state) { break; } state.storageBufferVariable = Define(ArrayType(StorageBufferBlockType(state)), "buffers"); - if (layout.UsesDataAddress()) state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::FlattenedSrt); if (state.requirements.coherentBufferAlias) state.storageBufferCoherentVariable = Define(ArrayType(StorageBufferBlockType(state)), "buffers_coherent"); if (state.requirements.bufferU64View) state.storageBufferU64Variable = Define(ArrayType(StorageBufferU64BlockType(state)), "buffers_u64"); if (state.storageBufferU64Variable != 0u || state.storageBufferCoherentVariable != 0u) { @@ -644,6 +644,16 @@ void DefineDescriptors(SpirvEmitterState& state) { state.shaderDataUniformVariable = Define(block, "shader_data", spv::StorageClassUniform); state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::ShaderData); } + if (layout.UsesDataAddress() && SplitUserData(state) && layout.userDataRegisters.size() <= state.heapDataUniformDwords) { + const auto vectors = static_cast((layout.userDataRegisters.size() + 3u) / 4u); + const auto array = state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 16u}}}, TypeU32Vector(state, 4), ConstantU32(state, vectors)); + const auto block = state.module.DecoratedType(spv::OpTypeStruct, {{spv::OpDecorate, {spv::DecorationBlock}}, {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}}, array); + state.userDataUniformVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniform, block), spv::StorageClassUniform); + state.module.AddName(state.userDataUniformVariable, "user_data"); + state.module.AddAnnotation(spv::OpDecorate, state.userDataUniformVariable, spv::DecorationDescriptorSet, RuntimeAbi::GpuDataSet); + state.module.AddAnnotation(spv::OpDecorate, state.userDataUniformVariable, spv::DecorationBinding, NativeBinding(stage, DescriptorBindingKind::UserData)); + state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::UserData) | RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::ShaderData); + } break; case DescriptorBindingKind::FlattenedSrt: if (layout.UsesDataAddress()) state.flattenedSrtAddressed = true; diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index a9b9b9e415e2..394397ffcde3 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -364,7 +364,6 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_PRESENT_EPOCH` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | keeps the presenter at collect epoch 0 instead of adopting the newest epoch a worker started | | `APS5_NO_PRESYNC` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | disables the stage-A pre-sync of pending writes | | `APS5_NO_PROC_TABLE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | resolves the device's Vulkan entry points per call instead of filling the function table once | -| `APS5_NO_PUSHED_USER_DATA_KEEP` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | writes a new heap shader-data block when only user-data words the pipeline pushes changed, instead of keeping the stage's block and pushing the new words | | `APS5_NO_QUEUED_DRAW_READ_ORDER` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp` | | stops queued draws and DMA copies from holding back write-backs over the guest memory they read at commit | | `APS5_NO_QUEUED_LABELS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/DeferredLabels.cpp` | | disables the queued-label table | | `APS5_NO_READS_OVERLAP_WALK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | builds the list of in-place reads for each read-overlap test instead of walking the regions to the first overlap | From 3f20fdd36f097423b824e3fe1b578468d3d5ffbf Mon Sep 17 00:00:00 2001 From: Dean Galvin Date: Tue, 10 Nov 2026 19:28:36 +1300 Subject: [PATCH 176/269] fix(recompiler): validate uniform constant buffers under uniformBufferStandardLayout The device enables uniformBufferStandardLayout whenever pushed constant buffers are read as uniform buffers (tightly packed u32 arrays), so the validator has to accept that layout too. --- core/shader/recompiler/SpirvBackend/src/SpirvOptimizer.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvOptimizer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvOptimizer.cpp index 2b089a3e8f41..521f54e8424e 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvOptimizer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvOptimizer.cpp @@ -175,6 +175,7 @@ std::vector ValidateAndOptimizeSpirvInline(std::span Date: Tue, 10 Nov 2026 21:34:49 +0530 Subject: [PATCH 177/269] test(agc): run the heap walk memo on two threads under eviction pressure Two threads each materialize 1024 distinct heap stages three times under a 1 MiB walk memo (APS5_HEAP_WALK_MEMO_MB=1) and hand every stage to the other thread, which reads its result, words and capture and keeps the last 48 before dropping them. Each thread's memo evicts entries whose captures and words the other thread still holds, the way the draw finisher's memo evicts stages the committer still reads. HeapWalkMemoEvictions() counts evictions so the test proves the pressure happened (3400 evictions per run here). Run under ASan with the draw pipeline (APS5_GPU_HEAP=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINE_DISPATCH=1 APS5_PIPELINED_DRAWS=32), 30 runs, it reports nothing, so it does not reproduce the MGS4 abort in HeapWalkMemo::evictOldest; it guards the cross-thread eviction path. --- .../include/Driver/Draw/HeapWalkMemo.hpp | 5 + .../Execution/src/Driver/Draw/HeapStages.cpp | 17 ++ ..._driver_heap_walk_memo_threads_tests.cmake | 3 + .../tests/execution/HeapWalkMemoThreads.cpp | 150 ++++++++++++++++++ 4 files changed, 175 insertions(+) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_memo_threads_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkMemoThreads.cpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp index e75e3efcf57b..bca6e1a10e8b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp @@ -47,6 +47,10 @@ std::uint64_t HeapWalkWordsBytes(const ShaderRecompiler::HeapStageWords& words); std::uint64_t HeapWalkMemoBudget(); +void NoteHeapWalkMemoEviction(); + +std::uint64_t HeapWalkMemoEvictions(); + struct HeapWalkMemo { struct Slot { std::vector ways; @@ -138,6 +142,7 @@ struct HeapWalkMemo { for (const auto& entry : found->second.ways) drop(entry); entries.erase(found); order.pop_back(); + NoteHeapWalkMemoEviction(); } void trim(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index ed0f44cc8b1d..cca9ab323b81 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -362,6 +362,23 @@ std::uint64_t HeapWalkEntryBytes(const HeapWalkEntry& entry) { return bytes; } +namespace { + +std::atomic& heapWalkMemoEvictions() { + static std::atomic evictions{0}; + return evictions; +} + +} + +void NoteHeapWalkMemoEviction() { + heapWalkMemoEvictions().fetch_add(1, std::memory_order_relaxed); +} + +std::uint64_t HeapWalkMemoEvictions() { + return heapWalkMemoEvictions().load(std::memory_order_relaxed); +} + std::uint64_t HeapWalkMemoBudget() { static const std::uint64_t budget = [] { const char* value = std::getenv("APS5_HEAP_WALK_MEMO_MB"); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_memo_threads_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_memo_threads_tests.cmake new file mode 100644 index 000000000000..e0004937af92 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_memo_threads_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_heap_walk_memo_threads) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkMemoThreads.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkMemoThreads.cpp new file mode 100644 index 000000000000..fb93df3bd497 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkMemoThreads.cpp @@ -0,0 +1,150 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Lanes = 32; +constexpr std::uint32_t Format32UInt = 20; +constexpr std::size_t Variants = 1024; +constexpr std::size_t Rounds = 3; +constexpr std::size_t Held = 48; +alignas(256) std::array Input{}; +alignas(256) std::array Output{}; +alignas(256) constexpr std::array Code{0x34020082u, 0xe0001000u, 0x80000201u, 0xe0301000u, 0x80000301u, 0xbf8c0000u, + 0xe0101000u, 0x80000201u, 0xe0701000u, 0x80000301u, + 0xe0701000u, 0x80010201u, 0xe0701080u, 0x80010301u, 0xbf800000u, 0xbf810000u}; + +std::array Descriptor(const void* data, std::uint32_t bytes) { + const auto address = reinterpret_cast(data); + const auto word3 = (((0x01016facu & ~(0x7fu << 12u)) | (Format32UInt << 12u) | (3u << 28u)) & ~(3u << 30u)); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu), bytes, word3}; +} + +struct Variant { + std::vector userData; + ShaderRecompiler::RecompileRequest request; + std::optional invocation; +}; + +std::vector> Prepare(AgcDriver::VulkanDevice& device) { + static const std::array memory{{{reinterpret_cast(Code.data()), std::as_bytes(std::span(Code))}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Lanes, 1, 1}, 0u, {false, false, false}, false, 1}; + std::vector> variants; + for (std::size_t index = 0; index < Variants; ++index) { + auto variant = std::make_unique(); + const auto inputBytes = static_cast(sizeof(Input) - 4u * (index % 64u)); + const auto outputBytes = static_cast(sizeof(Output) - 4u * (index / 64u)); + const auto input = Descriptor(Input.data(), inputBytes); + const auto output = Descriptor(Output.data(), outputBytes); + variant->userData.insert(variant->userData.end(), input.begin(), input.end()); + variant->userData.insert(variant->userData.end(), output.begin(), output.end()); + variant->request = ShaderRecompiler::RecompileRequest{ + {ShaderStage::Compute, reinterpret_cast(Code.data()), Code, 0, {}}, + {Lanes, 0, variant->userData, compute, std::nullopt, std::nullopt, memory}, + device.Target(), + {0, 0, 0, 128}}; + const auto handle = ShaderRecompiler::PrepareShader(variant->request); + variant->invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(variant->request, handle); + Require(variant->invocation.has_value(), "the prepared shader refused its own request"); + variants.push_back(std::move(variant)); + } + return variants; +} + +struct Inbox { + std::mutex mutex; + std::deque stages; +}; + +std::size_t Touch(const AgcDriver::DriverDetail::HeapStageMaterialized& stage) { + std::size_t sum = stage.result->spirv.size() + stage.words->userData.size() + stage.words->bindings.size(); + if (stage.reads.capture != nullptr) sum += stage.reads.capture->userDataUse.reads.size(); + if (stage.reads.values != nullptr) sum += stage.reads.values->size(); + return sum; +} + +void Work(const std::vector>& variants, std::size_t first, Inbox& own, Inbox& peer, std::atomic& failed, std::string& error) { + try { + std::deque held; + std::size_t touched = 0; + for (std::size_t round = 0; round < Rounds; ++round) { + for (std::size_t step = 0; step < variants.size(); ++step) { + const auto& variant = *variants[(first + step * 7u) % variants.size()]; + auto stage = AgcDriver::DriverDetail::MaterializeHeapStage(*variant.invocation, variant.userData, variant.request.shader.codeAddress); + Require(stage.result != nullptr && stage.words != nullptr, "a heap walk over valid buffer descriptors declined its stage"); + { + std::lock_guard lock(peer.mutex); + peer.stages.push_back(std::move(stage)); + } + std::deque received; + { + std::lock_guard lock(own.mutex); + received.swap(own.stages); + } + for (auto& item : received) { + touched += Touch(item); + held.push_back(std::move(item)); + } + while (held.size() > Held) held.pop_front(); + if (failed.load(std::memory_order_relaxed)) return; + } + } + Require(touched != 0, "a heap walk thread received no stage from the other thread"); + } catch (const std::exception& caught) { + error = caught.what(); + failed.store(true, std::memory_order_relaxed); + } +} + +void TwoThreadsShareEvictedWalks(AgcDriver::VulkanDevice& device) { + const auto variants = Prepare(device); + const auto evictionsBefore = AgcDriver::DriverDetail::HeapWalkMemoEvictions(); + Inbox first, second; + std::atomic failed{false}; + std::string firstError, secondError; + std::thread one(Work, std::cref(variants), std::size_t{0}, std::ref(first), std::ref(second), std::ref(failed), std::ref(firstError)); + std::thread two(Work, std::cref(variants), variants.size() / 2u, std::ref(second), std::ref(first), std::ref(failed), std::ref(secondError)); + one.join(); + two.join(); + Require(firstError.empty() && secondError.empty(), "a heap walk thread failed: " + firstError + secondError); + const auto evictions = AgcDriver::DriverDetail::HeapWalkMemoEvictions() - evictionsBefore; + Require(evictions != 0, "two threads walked " + std::to_string(Variants) + " stages " + std::to_string(Rounds) + " times each under a 1 MiB heap walk memo without evicting an entry"); + std::printf("two heap walk threads: %llu memo evictions while the other thread held the stages\n", static_cast(evictions)); +} + +} + +int main() { + SetTestEnvironment("APS5_HEAP_WALK_MEMO_MB", "1"); + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + TwoThreadsShareEvictedWalks(*device); + std::puts("heap walk memo thread tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} From 8888d4dd175e5679f3c508177f032e4abd26fe8e Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 12 Nov 2026 04:17:23 +0530 Subject: [PATCH 178/269] test(agc): give main's color write mask and copy input lifetime tests a timeline recorder Both tests came in with the main merge and create their own recorder without a timeline semaphore, which the GPU heap requires, so they failed with APS5_GPU_HEAP set. They now create it with one, as the other tests that make their own recorder do. --- .../libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp | 2 +- .../prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp index 4fa2a4a0b060..81f088cb91c1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp @@ -236,7 +236,7 @@ void RecordedMasks(AgcDriver::VulkanDevice& device, const Shaders& compiled, VkC const auto context = device.graphicsContext(); const auto shaders = Stages(device, compiled); const std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); - Recorder recorder(context); + Recorder recorder(context, true); recorder.Activate(); const MaskTrace trace(context); const auto continued = [] { return DrawPassTotals()[0].passesContinued; }; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp index 7425d8269b13..5d29d6473a31 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp @@ -94,7 +94,7 @@ void Scenario(Graphics::Context context, bool fail) { bool caught = false; bool earlyReuse = false; { - Graphics::Recorder recorder(context); + Graphics::Recorder recorder(context, true); recorder.Activate(); try { Graphics::GuestBufferMemory memory(context); From 681015d9dc4cd318a6f68abd5a25d78c99fb96ef Mon Sep 17 00:00:00 2001 From: raghav314 Date: Wed, 11 Nov 2026 05:04:34 +0530 Subject: [PATCH 179/269] perf(agc): skip the heap walk memo for shaders whose lookups do not hit A shader whose walk keys never repeat (ring pointers that come back only after the ring wraps) paid the memo key hash, lookup, insert, pinning and eviction on every walk for no hits. The memo now counts each shader's lookups and hits over 64 lookups; with no hits at all it skips that shader's lookups, inserts and evictions for the next 1024 walks. Skipped walks still note their key in the memo's second-sight table, and once one in eight of 64 skipped walks repeats a key the shader uses the memo again, so a shader whose keys repeat only after a long gap is not shut out. Skipping a cache never changes a walk's result. --- .../include/Driver/Draw/HeapWalkMemo.hpp | 50 +++++++++++++++++++ .../Execution/src/Driver/Draw/HeapStages.cpp | 10 ++-- .../libSceAgcDriver/tests/HeapWalkMemo.cpp | 30 +++++++++++ 3 files changed, 87 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp index bca6e1a10e8b..fd5f4586118f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp @@ -35,6 +35,21 @@ constexpr std::size_t HeapWalkMemoKeys = 16384; constexpr std::size_t HeapWalkSeenKeys = 1u << 16; +constexpr std::size_t HeapWalkVariantSlots = 4096; + +constexpr std::uint32_t HeapWalkProbeLookups = 64; + +constexpr std::uint32_t HeapWalkSkippedWalks = 1024; + +struct HeapWalkVariantUse { + std::uint64_t variant = 0; + std::uint32_t lookups = 0; + std::uint32_t hits = 0; + std::uint32_t skip = 0; + std::uint32_t skipped = 0; + std::uint32_t repeats = 0; +}; + std::uint64_t HeapWalkEntryBytes(const HeapWalkEntry& entry); std::uint64_t HeapWalkEntryOwnBytes(const HeapWalkEntry& entry); @@ -60,10 +75,39 @@ struct HeapWalkMemo { std::list order; std::vector seen = std::vector(HeapWalkSeenKeys, 0); std::unordered_map> pins; + std::vector variants = std::vector(HeapWalkVariantSlots); std::uint64_t heldBytes = 0; std::uint64_t stores = 0; std::uint64_t budget = HeapWalkMemoBudget(); + bool consult(std::uint64_t variant) { + auto& use = variantUse(variant); + if (use.skip == 0) return true; + --use.skip; + return false; + } + + void noteSkipped(std::uint64_t variant, std::uint64_t key) { + const bool repeated = admit(key); + auto& use = variantUse(variant); + ++use.skipped; + if (repeated) ++use.repeats; + if (use.skipped < HeapWalkProbeLookups) return; + if (use.repeats * 8u >= use.skipped) use.skip = 0; + use.skipped = 0; + use.repeats = 0; + } + + void noteLookup(std::uint64_t variant, bool hit) { + auto& use = variantUse(variant); + ++use.lookups; + if (hit) ++use.hits; + if (use.lookups < HeapWalkProbeLookups) return; + if (use.hits == 0u) use.skip = HeapWalkSkippedWalks; + use.lookups = 0; + use.hits = 0; + } + bool admit(std::uint64_t key) { auto& last = seen[(key ^ (key >> 29)) & (HeapWalkSeenKeys - 1u)]; if (last == key) return true; @@ -103,6 +147,12 @@ struct HeapWalkMemo { } private: + HeapWalkVariantUse& variantUse(std::uint64_t variant) { + auto& use = variants[(variant ^ (variant >> 31u)) & (HeapWalkVariantSlots - 1u)]; + if (use.variant != variant) use = {variant}; + return use; + } + template void pin(const std::shared_ptr& object, TSize size) { if (object == nullptr) return; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index cca9ab323b81..f414c077747f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -589,16 +589,20 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade const auto before = Graphics::Recorder::PendingWriteSnapshot(); snapshotCost.Stop(); const auto generation = GuestMemory::StableTrackerGeneration(); - const bool memoOn = !invocation.Request().context.vertex.has_value(); + const auto variant = invocation.VariantId(); + const bool memoAllowed = !invocation.Request().context.vertex.has_value(); + const bool memoOn = memoAllowed && heapWalkMemo().consult(variant); std::uint64_t memoKey = 0; bool memoKnown = false; + if (memoAllowed && !memoOn) heapWalkMemo().noteSkipped(variant, walkMemoKey(invocation, userData, shaderBase)); Graphics::HeapCostScope memoCost(Graphics::HeapCost::WalkMemo); if (memoOn) { memoKey = walkMemoKey(invocation, userData, shaderBase); HeapStageMaterialized adopted; - if (adoptWalk(memoKey, invocation, userData, shaderBase, before.get(), generation, adopted, memoKnown)) - return adopted; + const bool hit = adoptWalk(memoKey, invocation, userData, shaderBase, before.get(), generation, adopted, memoKnown); + heapWalkMemo().noteLookup(variant, hit); + if (hit) return adopted; } memoCost.Stop(); diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp index cb432a9de44f..f7394f9ae603 100644 --- a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp @@ -125,6 +125,35 @@ void sharedResultsChargedOnceTests() { std::cout << "the heap walk memo charges a result its entries share once\n"; } +void unrepeatedVariantsSkipTests() { + using AgcDriver::DriverDetail::HeapWalkProbeLookups; + using AgcDriver::DriverDetail::HeapWalkSkippedWalks; + HeapWalkMemo memo; + constexpr std::uint64_t missing = 7; + constexpr std::uint64_t hitting = 9; + for (std::uint32_t lookup = 0; lookup < HeapWalkProbeLookups; ++lookup) { + require(memo.consult(missing), "the heap walk memo skipped a shader before its first probe window ended"); + memo.noteLookup(missing, false); + require(memo.consult(hitting), "the heap walk memo skipped a shader whose lookups hit"); + memo.noteLookup(hitting, lookup == 17u); + } + for (std::uint32_t walk = 0; walk < HeapWalkSkippedWalks; ++walk) { + require(!memo.consult(missing), "the heap walk memo kept looking up a shader none of whose " + std::to_string(HeapWalkProbeLookups) + " lookups hit (walk " + std::to_string(walk) + ")"); + require(memo.consult(hitting), "the heap walk memo skipped a shader one of whose lookups hit: a walk costs far more than a lookup"); + } + require(memo.consult(missing), "the heap walk memo never probed a skipped shader again"); + for (std::uint32_t lookup = 0; lookup < HeapWalkProbeLookups; ++lookup) memo.noteLookup(missing, true); + for (std::uint32_t walk = 0; walk < 4u * HeapWalkSkippedWalks; ++walk) require(memo.consult(missing), "the heap walk memo skipped a shader whose new lookups all hit"); + constexpr std::uint64_t returning = 11; + for (std::uint32_t lookup = 0; lookup < HeapWalkProbeLookups; ++lookup) memo.noteLookup(returning, false); + require(!memo.consult(returning), "the heap walk memo kept looking up a shader none of whose lookups hit"); + for (std::uint64_t key = 0; key < HeapWalkProbeLookups; ++key) memo.noteSkipped(returning, 0x1000u + key); + require(!memo.consult(returning), "the heap walk memo resumed a skipped shader whose walks never repeated a key"); + for (std::uint64_t key = 0; key < HeapWalkProbeLookups; ++key) memo.noteSkipped(returning, 0x1000u + key); + require(memo.consult(returning), "the heap walk memo kept skipping a shader whose skipped walks repeated their keys"); + std::cout << "the heap walk memo skips shaders whose lookups do not hit and resumes when their keys repeat\n"; +} + } int main() { @@ -133,6 +162,7 @@ int main() { keyCapDropsLeastRecentTests(); hitEntriesKeptTests(); sharedResultsChargedOnceTests(); + unrepeatedVariantsSkipTests(); std::cout << "heap walk memo budget tests passed\n"; return 0; } catch (const std::exception& error) { From d5ed08b6ca661f834fa9c5c0e2da1258cd0a3616 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Wed, 11 Nov 2026 05:09:57 +0530 Subject: [PATCH 180/269] perf(agc): recycle a heap walk's stage words, values and ranges Every heap walk allocated its stage words, a copy of its read values and a copy of its read ranges, and the committer or the memo freed them on another thread, so the finisher paid malloc, the arena lock and cross-thread frees per stage. The walking thread now keeps a pool of each and takes back an object once it is the sole owner (the way the ring words were already pooled, now shared as RecycledShared). A full pool replaces long-held objects with new ones so memoized records do not pin it, and a taken object drops any buffer over 16 KiB so the pool does not hold every record at its largest size. --- .../include/Driver/Draw/HeapStages.hpp | 2 + .../include/Driver/Draw/RecycledShared.hpp | 62 ++++++++++ .../Execution/src/Driver/Draw/Draw.cpp | 30 ++--- .../Execution/src/Driver/Draw/HeapStages.cpp | 61 +++++++++- .../libSceAgcDriver/tests/RecycledShared.cpp | 106 ++++++++++++++++++ .../agc_driver_recycled_shared_tests.cmake | 24 ++++ 6 files changed, 261 insertions(+), 24 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/RecycledShared.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recycled_shared_tests.cmake diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index c5cee8718688..bc53800b7bd9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -39,6 +39,8 @@ struct HeapStageMaterialized { HeapStageReads reads; }; +void ResetHeapStageWords(ShaderRecompiler::HeapStageWords& words); + HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase); void NoteHeapDirect(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp new file mode 100644 index 000000000000..25f97a12a458 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp @@ -0,0 +1,62 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_RECYCLEDSHARED_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_RECYCLEDSHARED_HPP + +#include +#include +#include +#include +#include + +namespace AgcDriver::DriverDetail { + +template +class RecycledShared { +public: + RecycledShared(std::size_t capacity, std::size_t probes) : capacity(capacity), probes(probes) {} + + template + std::shared_ptr Take(TReset&& reset) { + for (std::size_t probe = 0; probe < probes && probe < pool.size(); ++probe) { + auto& candidate = pool[cursor]; + advance(); + if (candidate.use_count() != 1) continue; + std::atomic_thread_fence(std::memory_order_acquire); + reset(*candidate); + ++reused; + return candidate; + } + auto made = std::make_shared(); + ++fresh; + if (pool.size() < capacity) { + pool.push_back(made); + } else { + pool[cursor] = made; + advance(); + } + return made; + } + + std::uint64_t Reused() const { + return reused; + } + + std::uint64_t Fresh() const { + return fresh; + } + +private: + void advance() { + cursor = cursor + 1 >= pool.size() ? 0 : cursor + 1; + } + + std::vector> pool; + std::size_t cursor = 0; + std::size_t capacity; + std::size_t probes; + std::uint64_t reused = 0; + std::uint64_t fresh = 0; +}; + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 64e772c61a07..2bbda54a234c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -8,6 +8,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawProgramTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DrawWriteRanges.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp" #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -42,32 +43,19 @@ namespace AgcDriver::DriverDetail { namespace { -struct RecycledRingWordsPool { - std::vector> words; - std::size_t cursor = 0; -}; - struct RecycledRingWordsStorage {}; std::shared_ptr RecycledRingWords() { constexpr std::size_t PoolSize = 1024, Probes = 16; - auto& state = HostThreadLocal(); - auto& pool = state.words; - auto& cursor = state.cursor; - for (std::size_t probe = 0; probe < Probes && probe < pool.size(); ++probe) { - auto& candidate = pool[cursor]; - cursor = cursor + 1 == pool.size() ? 0 : cursor + 1; - if (candidate.use_count() != 1) continue; - std::atomic_thread_fence(std::memory_order_acquire); - candidate->userData.clear(); - candidate->drawKeyMemo.words.store(nullptr, std::memory_order_relaxed); - candidate->memoizeKey = false; - candidate->dataOrigin = 0; - return candidate; - } - auto words = std::make_shared(); + struct Pool : RecycledShared { + Pool() : RecycledShared(PoolSize, Probes) {} + }; + auto words = HostThreadLocal().Take([](ShaderRecompiler::HeapStageWords& candidate) { + candidate.userData.clear(); + candidate.drawKeyMemo.words.store(nullptr, std::memory_order_relaxed); + candidate.dataOrigin = 0; + }); words->memoizeKey = false; - if (pool.size() < PoolSize) pool.push_back(words); return words; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index f414c077747f..fa0a6ad4d4bc 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -577,6 +578,60 @@ captureWalk(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::s } +namespace { + +constexpr std::size_t RecycledKeptBytes = 16u << 10u; + +template +void clearRecycled(TVector& vector) { + if (vector.capacity() * sizeof(typename TVector::value_type) > RecycledKeptBytes) TVector().swap(vector); + else vector.clear(); +} + +} + +void ResetHeapStageWords(ShaderRecompiler::HeapStageWords& words) { + clearRecycled(words.userData); + clearRecycled(words.flattenedSrt); + clearRecycled(words.vertexAttributes); + clearRecycled(words.bindings); + words.base.reset(); + words.dataOrigin = 0; + words.drawKeyMemo.words.store(nullptr, std::memory_order_relaxed); + words.memoizeKey = true; +} + +namespace { + +constexpr std::size_t RecycledStageRecords = 1024, RecycledStageProbes = 8; + +template +struct RecycledStagePool : RecycledShared { + RecycledStagePool() : RecycledShared(RecycledStageRecords, RecycledStageProbes) {} +}; + +struct RecycledWordsStorage {}; +struct RecycledValuesStorage {}; +struct RecycledRangesStorage {}; + +std::shared_ptr recycledStageWords() { + return HostThreadLocal, RecycledWordsStorage>().Take(ResetHeapStageWords); +} + +std::shared_ptr> recycledValues(const std::vector& values) { + auto copy = HostThreadLocal>, RecycledValuesStorage>().Take(clearRecycled>); + copy->assign(values.begin(), values.end()); + return copy; +} + +std::shared_ptr recycledRanges(const AddressRanges& ranges) { + auto copy = HostThreadLocal, RecycledRangesStorage>().Take(clearRecycled); + copy->assign(ranges.begin(), ranges.end()); + return copy; +} + +} + HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase) { struct ReadsStorage {}; @@ -624,15 +679,15 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade guardRanges(ranges); guardCost.Stop(); Graphics::HeapCostScope materializeCost(Graphics::HeapCost::Materialize); - auto words = std::make_shared(); + auto words = recycledStageWords(); auto result = invocation.MaterializeHeap(*capture, *words); if (result == nullptr) result = invocation.Materialize(*capture); words->dataOrigin = NextHeapDataOrigin(); materializeCost.Stop(); const bool complete = !reads.failed && result != nullptr; HeapStageMaterialized materialized; - auto shared = complete ? std::make_shared>(values) : nullptr; - auto sharedRanges = complete ? std::make_shared(ranges) : nullptr; + auto shared = complete ? recycledValues(values) : nullptr; + auto sharedRanges = complete ? recycledRanges(ranges) : nullptr; if (complete) materialized.reads = {sharedRanges, shared, capture->userDataUse, capture, true}; Graphics::HeapCostScope insertCost(Graphics::HeapCost::MemoInsert); if (memoOn && complete && (memoKnown || heapWalkMemo().admit(memoKey))) diff --git a/core/libs/prx/libSceAgcDriver/tests/RecycledShared.cpp b/core/libs/prx/libSceAgcDriver/tests/RecycledShared.cpp new file mode 100644 index 000000000000..0cc0e1f760ad --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/RecycledShared.cpp @@ -0,0 +1,106 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::DriverDetail::RecycledShared; + +void require(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +void heldObjectsNotReusedTests() { + RecycledShared> pool(4, 4); + std::vector>> held; + for (std::uint32_t index = 0; index < 4; ++index) { + held.push_back(pool.Take([](std::vector& values) { values.clear(); })); + held.back()->assign(16, index); + } + auto next = pool.Take([](std::vector& values) { values.clear(); }); + for (std::size_t index = 0; index < held.size(); ++index) { + require(next.get() != held[index].get(), "the recycled pool handed out object " + std::to_string(index) + " while a draw still held it"); + require(*held[index] == std::vector(16, static_cast(index)), "the recycled pool changed object " + std::to_string(index) + " while a draw still held it"); + } + require(pool.Reused() == 0, "the recycled pool reused an object although every pooled object was held"); + std::cout << "the recycled pool never reuses an object another owner holds\n"; +} + +void releasedObjectsReusedTests() { + RecycledShared> pool(8, 8); + std::size_t resets = 0; + const void* first = nullptr; + for (std::uint32_t round = 0; round < 64; ++round) { + auto values = pool.Take([&](std::vector& reused) { + ++resets; + reused.clear(); + }); + require(values->empty(), "a recycled object kept the contents of its previous use in round " + std::to_string(round)); + values->assign(256, round); + if (first == nullptr) first = values.get(); + } + require(pool.Fresh() == 1 && pool.Reused() == 63 && resets == 63, "a pool whose objects were released after each use made " + std::to_string(pool.Fresh()) + " objects and reused " + std::to_string(pool.Reused()) + ", not 1 and 63"); + std::cout << "the recycled pool reuses released objects and resets them\n"; +} + +void fullPoolCyclesTests() { + RecycledShared> pool(2, 2); + std::vector>> heldLong; + for (int index = 0; index < 2; ++index) heldLong.push_back(pool.Take([](std::vector&) {})); + for (int index = 0; index < 6; ++index) static_cast(pool.Take([](std::vector&) {})); + require(pool.Reused() == 5, "a pool full of objects held long ago reused " + std::to_string(pool.Reused()) + " of the 6 short-lived takes after it filled, not 5"); + std::cout << "a full recycled pool replaces long-held objects with newer ones\n"; +} + +void stageWordsResetTests() { + ShaderRecompiler::HeapStageWords words; + words.userData = {1, 2, 3}; + words.flattenedSrt = {4, 5}; + words.vertexAttributes.resize(2); + words.bindings = {{6}, {7, 8}}; + words.base = std::make_shared(); + words.dataOrigin = 9; + words.drawKeyMemo.words.store(std::make_shared>(1, 10u), std::memory_order_relaxed); + words.memoizeKey = false; + AgcDriver::DriverDetail::ResetHeapStageWords(words); + const ShaderRecompiler::HeapStageWords fresh; + require(words.userData.empty() && words.flattenedSrt.empty() && words.vertexAttributes.empty() && words.bindings.empty(), "a recycled heap stage record kept its previous draw's words"); + require(words.base == nullptr, "a recycled heap stage record kept its previous draw's ring template"); + require(words.dataOrigin == fresh.dataOrigin, "a recycled heap stage record kept its previous data origin"); + require(words.drawKeyMemo.words.load(std::memory_order_relaxed) == nullptr, "a recycled heap stage record kept its previous draw key"); + require(words.memoizeKey == fresh.memoizeKey, "a recycled heap stage record kept its previous key memo switch"); + words.userData.assign(64u << 10u, 1u); + words.flattenedSrt.assign(16, 2u); + words.vertexAttributes.resize(64u << 10u); + words.bindings.resize(4096); + const auto smallCapacity = words.flattenedSrt.capacity(); + AgcDriver::DriverDetail::ResetHeapStageWords(words); + require(words.userData.capacity() == 0u, "a recycled heap stage record kept a 256 KiB buffer in the pool"); + require(words.vertexAttributes.capacity() == 0u, "a recycled heap stage record kept a large vertex attribute buffer in the pool"); + require(words.bindings.capacity() == 0u, "a recycled heap stage record kept a large binding list in the pool"); + require(words.flattenedSrt.capacity() == smallCapacity, "a recycled heap stage record dropped a small buffer it should reuse"); + std::cout << "a recycled heap stage record is reset to a new record's state\n"; +} + +} + +int main() { + try { + heldObjectsNotReusedTests(); + releasedObjectsReusedTests(); + fullPoolCyclesTests(); + stageWordsResetTests(); + std::cout << "recycled stage record tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "recycled stage record tests failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recycled_shared_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recycled_shared_tests.cmake new file mode 100644 index 000000000000..eb4799c28ea6 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recycled_shared_tests.cmake @@ -0,0 +1,24 @@ +add_test_executable(agc_driver_recycled_shared_tests EXCLUDE_FROM_ALL + tests/RecycledShared.cpp +) + +target_include_directories(agc_driver_recycled_shared_tests PRIVATE + ${LIBS_INCLUDE_DIR} + $ + ${CMAKE_SOURCE_DIR}/core/shader/recompiler + ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} + ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR} +) + +target_link_libraries(agc_driver_recycled_shared_tests PRIVATE + libSceAgcDriver + SDL2-static + libc +) + +set_target_properties(agc_driver_recycled_shared_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_driver_recycled_shared_tests) + +if(BUILD_TESTING) + agc_add_default_test(agc_driver_recycled_shared_tests) +endif() From 23eeaf7de178b8cdd3fa69ded56cc6dfcfa142da Mon Sep 17 00:00:00 2001 From: raghav314 Date: Wed, 11 Nov 2026 05:19:24 +0530 Subject: [PATCH 181/269] perf(agc): encode a stage's constant pushed buffer records once and count heap pushes without locked adds A stage whose pushed buffer ranges are constant re-encoded every record (clamped size, alignment check with a 64-bit modulo, stand-in address) on every draw. The records are now encoded with the cached ranges, and a draw copies them and fills in only the records that stand in for the stage's data address (vkd3d keeps root descriptor addresses from resource creation instead of rebuilding them per draw). The per-draw heap diagnostic counters (data address pushes, pushed stages, pushed user data keeps, user word rewrites, empty resource sets) are bumped by the recording thread right after its write-combined heap span stores; a locked add there waits for those stores to drain, so they now use a relaxed load and store. Two threads recording at once can lose a count; the counters are diagnostics and feed no decision. --- .../Graphics/include/ShaderResources.hpp | 2 + .../Graphics/src/BindlessHeap.cpp | 22 ++++-- .../Graphics/src/ShaderResources.cpp | 76 ++++++++++++++----- 3 files changed, 74 insertions(+), 26 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 634c791e48ac..28052c96e008 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -399,6 +399,8 @@ class ShaderResources { bool built = false; bool constant = false; std::vector ranges; + std::vector records; + std::vector emptyRecords; }; mutable std::array pushedRanges; struct RootRoles { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 95d168537238..829a58e8b1c7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -103,8 +104,17 @@ std::uint64_t ImageTableBuilds() { return imageTableBuilds.load(std::memory_order_relaxed); } +namespace { + +template +void countOnRecordingThread(std::atomic& counter, std::type_identity_t amount) { + counter.store(counter.load(std::memory_order_relaxed) + amount, std::memory_order_relaxed); +} + +} + void NoteDataAddressPush() { - dataAddressPushes.fetch_add(1, std::memory_order_relaxed); + countOnRecordingThread(dataAddressPushes, 1); } std::uint64_t DataAddressPushes() { @@ -112,13 +122,13 @@ std::uint64_t DataAddressPushes() { } void NotePushedUserDataKeep() { - pushedUserDataKeeps.fetch_add(1, std::memory_order_relaxed); + countOnRecordingThread(pushedUserDataKeeps, 1); } void NoteUserWordsRewrite(std::size_t blockWords, std::size_t userWords) { - userWordsRewrites.fetch_add(1, std::memory_order_relaxed); - userWordsRewriteBlockWords.fetch_add(blockWords, std::memory_order_relaxed); - userWordsRewriteUserWords.fetch_add(userWords, std::memory_order_relaxed); + countOnRecordingThread(userWordsRewrites, 1); + countOnRecordingThread(userWordsRewriteBlockWords, blockWords); + countOnRecordingThread(userWordsRewriteUserWords, userWords); } std::uint64_t PushedUserDataKeeps() { @@ -138,7 +148,7 @@ std::uint64_t HeapSlotEvictions() { } void NoteEmptyResourceSet() { - emptyResourceSets.fetch_add(1, std::memory_order_relaxed); + countOnRecordingThread(emptyResourceSets, 1); } std::uint64_t EmptyResourceSets() { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index f286c795772e..cb3e20735176 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -7576,15 +7576,43 @@ void ShaderResources::PatchDataAddresses(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const { namespace Abi = ShaderRecompiler::RuntimeAbi; static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; - const std::vector* kept = nullptr; + const auto uniformAlignment = UniformConstantBuffersEnabled() ? context.limits.minUniformBufferOffsetAlignment : VkDeviceSize{1}; + const auto clampedSize = [](const VkDeviceAddressRangeEXT& range) { + return static_cast(std::min(range.size, 0xffffffffu)); + }; + const auto record = [&](VkDeviceAddress address, std::uint32_t size) { + Require(address % uniformAlignment == 0, "a pushed buffer address is off the uniform buffer offset alignment"); + return std::array{static_cast(address), static_cast(address >> 32u), size, 0u}; + }; + const auto encode = [&](const VkDeviceAddressRangeEXT& range) { + const auto size = clampedSize(range); + const auto address = size != 0u && range.address != 0u ? range.address : empty; + return record(address, address == empty ? 0u : size); + }; + const PushedRanges* kept = nullptr; if (overrides == nullptr && !verify) { auto& cached = pushedRanges[stage]; if (!cached.built) { - cached.constant = constantBufferRanges(static_cast(stage)); - cached.built = cached.constant || !resolvedAddresses.empty(); - if (cached.constant) bufferRanges(static_cast(stage), nullptr, cached.ranges); + const bool constant = constantBufferRanges(static_cast(stage)); + if (constant) { + bufferRanges(static_cast(stage), nullptr, cached.ranges); + cached.records.assign(cached.ranges.size() * Abi::OverflowRecordWords, 0u); + cached.emptyRecords.clear(); + for (std::size_t index = 0; index < cached.ranges.size(); ++index) { + const auto& range = cached.ranges[index]; + const auto size = clampedSize(range); + if (size == 0u || range.address == 0u) { + cached.emptyRecords.push_back(static_cast(index)); + continue; + } + const auto words = record(range.address, size); + std::copy(words.begin(), words.end(), cached.records.begin() + static_cast(index * Abi::OverflowRecordWords)); + } + } + cached.constant = constant; + cached.built = constant || !resolvedAddresses.empty(); } - if (cached.constant) kept = &cached.ranges; + if (cached.constant) kept = &cached; } struct RangeStorage {}; auto& scratch = HostThreadLocal, RangeStorage>(); @@ -7592,17 +7620,29 @@ void ShaderResources::writePushedBuffers(std::span(stage), overrides, scratch); } - const auto& ranges = kept != nullptr ? *kept : scratch; + const auto& ranges = kept != nullptr ? kept->ranges : scratch; Require(ranges.size() == placement.pushedBuffers, "a stage's buffer addresses do not match its push layout's buffer count"); - heapPushedStages.fetch_add(1, std::memory_order_relaxed); + heapPushedStages.store(heapPushedStages.load(std::memory_order_relaxed) + 1u, std::memory_order_relaxed); Require(empty != 0u, "a stage with pushed buffers has no shader data to stand in for an empty buffer"); - const auto uniformAlignment = UniformConstantBuffersEnabled() ? context.limits.minUniformBufferOffsetAlignment : VkDeviceSize{1}; - const auto record = [&](std::size_t index) { - const auto size = static_cast(std::min(ranges[index].size, 0xffffffffu)); - const auto address = size != 0u && ranges[index].address != 0u ? ranges[index].address : empty; - Require(address % uniformAlignment == 0, "a pushed buffer address is off the uniform buffer offset alignment"); - return std::array{static_cast(address), static_cast(address >> 32u), address == empty ? 0u : size, 0u}; - }; + struct RecordStorage {}; + auto& records = HostThreadLocal, RecordStorage>(); + if (kept != nullptr) { + records.assign(kept->records.begin(), kept->records.end()); + if (!kept->emptyRecords.empty()) { + const auto stand = encode({0u, 0u}); + for (const auto index : kept->emptyRecords) + std::copy(stand.begin(), stand.end(), records.begin() + static_cast(index * Abi::OverflowRecordWords)); + } + for (std::size_t index = 0; index < ranges.size(); ++index) { + if (ranges[index].address == empty) records[index * Abi::OverflowRecordWords + 2u] = 0u; + } + } else { + records.resize(ranges.size() * Abi::OverflowRecordWords); + for (std::size_t index = 0; index < ranges.size(); ++index) { + const auto words = encode(ranges[index]); + std::copy(words.begin(), words.end(), records.begin() + static_cast(index * Abi::OverflowRecordWords)); + } + } const auto put = [&](std::uint32_t position, std::span words) { Require(position != Abi::NoPushPosition && (position + words.size()) * sizeof(std::uint32_t) <= bytes.size(), "a stage's pushed buffer words lie outside the push data"); std::memcpy(bytes.data() + position * sizeof(std::uint32_t), words.data(), words.size_bytes()); @@ -7614,16 +7654,12 @@ void ShaderResources::writePushedBuffers(std::span(records).subspan(index * Abi::OverflowRecordWords, Abi::PushedBufferWords)); } if (!overflowed) return; heapOverflowStages.fetch_add(1, std::memory_order_relaxed); const auto span = BindlessHeap::For(context).Allocate(ranges.size() * Abi::OverflowRecordWords); - for (std::size_t index = 0; index < ranges.size(); ++index) { - const auto words = record(index); - std::copy(words.begin(), words.end(), span.words.begin() + static_cast(index * Abi::OverflowRecordWords)); - } + std::copy(records.begin(), records.end(), span.words.begin()); const std::array address{static_cast(span.address), static_cast(span.address >> 32u)}; put(placement.bufferOverflow, address); } From af655a4ccbe93a18ac58e1f47870894be7e2b80a Mon Sep 17 00:00:00 2001 From: raghav314 Date: Wed, 11 Nov 2026 05:19:24 +0530 Subject: [PATCH 182/269] perf(recompiler): look up a heap template through a per-thread front table Every materialized heap stage locked its shader's template map to find its template and then took the global template LRU lock to touch it. A per-thread direct-mapped table now answers repeat lookups without either lock. When the LRU erases templates, each thread drops its whole table on its next lookup, so the table keeps no evicted template alive past that. A template is touched in the LRU at most once per 256 lookups on that thread (an aging touch, as the resource cache does). --- core/shader/recompiler/Recompiler.cpp | 59 ++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 5 deletions(-) diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index b459a15c7615..c6aa8e4fb136 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -508,6 +508,41 @@ HeapTemplateLru::Name HeapTemplateName(const SourceEntry& source, std::uint64_t return {source.id, key, entry.result->heapTemplateId}; } +std::atomic& HeapTemplateErasures() { + static std::atomic erasures{0}; + return erasures; +} + +constexpr std::size_t HeapTemplateFrontEntries = 1024; +constexpr std::uint64_t HeapTemplateTouchInterval = 256; + +struct HeapTemplateFront { + struct Entry { + std::uint64_t source = 0; + std::uint64_t key = 0; + std::uint64_t touched = 0; + std::shared_ptr found; + }; + std::array entries{}; + std::uint64_t lookups = 0; + std::uint64_t erasures = 0; + + void Follow(std::uint64_t current) { + if (current == erasures) return; + for (auto& entry : entries) entry.found.reset(); + erasures = current; + } + + Entry& At(std::uint64_t source, std::uint64_t key) { + return entries[((key ^ (source * 0x9e3779b97f4a7c15ull)) >> 17u) & (HeapTemplateFrontEntries - 1u)]; + } +}; + +HeapTemplateFront& HeapTemplateFrontTable() { + struct FrontStorage {}; + return HostThreadLocal(); +} + void KeepHeapTemplate(const std::shared_ptr& source, std::uint64_t key, const HeapTemplate& entry) { auto& store = HeapTemplates(); std::vector evicted; @@ -526,6 +561,7 @@ void KeepHeapTemplate(const std::shared_ptr& source, std::uint64_t ++erased; } if (erased == 0) return; + HeapTemplateErasures().fetch_add(1, std::memory_order_release); std::lock_guard lock(store.mutex); store.evicted += erased; } @@ -2508,15 +2544,27 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap if (perDrawBindings) HeapBindingWords(request, *variant, merged, *shared, words); CompleteHeapDataWords(*shared->result, words); }; + auto& front = HeapTemplateFrontTable(); + front.Follow(HeapTemplateErasures().load(std::memory_order_acquire)); + auto& entry = front.At(source.id, key); + ++front.lookups; std::shared_ptr hit; - { - std::lock_guard lock(source.mutex); - const auto found = source.heapTemplates.find(key); - if (found != source.heapTemplates.end()) hit = found->second; + if (entry.found != nullptr && entry.source == source.id && entry.key == key) { + hit = entry.found; + } else { + { + std::lock_guard lock(source.mutex); + const auto found = source.heapTemplates.find(key); + if (found != source.heapTemplates.end()) hit = found->second; + } + if (hit != nullptr) entry = {source.id, key, 0, hit}; } if (hit != nullptr) { complete(hit); - TouchHeapTemplate({source.id, key, hit->result->heapTemplateId}); + if (front.lookups - entry.touched >= HeapTemplateTouchInterval || entry.touched == 0) { + entry.touched = front.lookups; + TouchHeapTemplate({source.id, key, hit->result->heapTemplateId}); + } return hit->result; } UsedBindingPlan usedPlan; @@ -2536,6 +2584,7 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap } if (inserted) KeepHeapTemplate(source.shared_from_this(), key, *shared); else TouchHeapTemplate(HeapTemplateName(source, key, *shared)); + entry = {source.id, key, front.lookups, shared}; complete(shared); return shared->result; } From ec18bbba5aa4135470769b3f5113b4a62ba4505f Mon Sep 17 00:00:00 2001 From: raghav314 Date: Wed, 11 Nov 2026 07:04:34 +0530 Subject: [PATCH 183/269] perf(agc): build a heap walk's read ranges as it reads instead of sorting every word Each walked word's address was pushed to a list that the walk then sorted and merged into read ranges. SRT reads are mostly consecutive, so the walk now extends the current run as it reads and only sorts the few runs when they are out of order; the merged ranges are the same. --- .../include/Driver/Draw/HeapStages.hpp | 4 ++ .../Execution/src/Driver/Draw/HeapStages.cpp | 40 +++++++++++------- .../libSceAgcDriver/tests/HeapWalkMemo.cpp | 41 +++++++++++++++++++ 3 files changed, 70 insertions(+), 15 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index bc53800b7bd9..ee16999ecce9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -41,6 +41,10 @@ struct HeapStageMaterialized { void ResetHeapStageWords(ShaderRecompiler::HeapStageWords& words); +void AppendWalkRead(std::vector>& runs, std::uint64_t address); + +void CoalesceWalkReads(std::vector>& runs, std::vector>& ranges); + HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase); void NoteHeapDirect(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index fa0a6ad4d4bc..a88c7fe95f43 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -404,18 +404,38 @@ HeapWalkMemo& heapWalkMemo() { } +void AppendWalkRead(std::vector>& runs, std::uint64_t address) { + if (!runs.empty() && address >= runs.back().first && address <= runs.back().second) { + runs.back().second = std::max(runs.back().second, address + WordBytes); + return; + } + runs.emplace_back(address, address + WordBytes); +} + +void CoalesceWalkReads(std::vector>& runs, std::vector>& ranges) { + if (!std::is_sorted(runs.begin(), runs.end())) std::sort(runs.begin(), runs.end()); + ranges.clear(); + for (const auto& [begin, end] : runs) { + if (!ranges.empty() && begin <= ranges.back().second) { + ranges.back().second = std::max(ranges.back().second, end); + continue; + } + ranges.emplace_back(begin, end); + } +} + namespace { using AddressRanges = std::vector>; struct WalkReads { - std::vector words; + AddressRanges runs; std::uint64_t page = ~std::uint64_t{0}; AddressRanges accessible; bool failed = false; void Reset() { - words.clear(); + runs.clear(); accessible.clear(); failed = false; page = ~std::uint64_t{0}; @@ -434,7 +454,7 @@ bool readWalkWord(void* context, std::uint64_t address, std::uint32_t* value) { } } std::memcpy(value, reinterpret_cast(address), sizeof(*value)); - reads.words.push_back(address); + AppendWalkRead(reads.runs, address); return true; } @@ -446,17 +466,7 @@ bool walkAccessible(void* context, std::uint64_t address, std::uint64_t bytes) { return accessible; } -void coalesceWords(std::vector& words, AddressRanges& ranges) { - std::sort(words.begin(), words.end()); - ranges.clear(); - for (const auto address : words) { - if (!ranges.empty() && address <= ranges.back().second) { - ranges.back().second = std::max(ranges.back().second, address + WordBytes); - continue; - } - ranges.emplace_back(address, address + WordBytes); - } -} + void copyRangeValues(const AddressRanges& ranges, std::vector& values) { values.clear(); @@ -668,7 +678,7 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade } catch (const std::exception&) { return {}; } - coalesceWords(reads.words, ranges); + CoalesceWalkReads(reads.runs, ranges); auto& values = HostThreadLocal, ValuesStorage>(); if (!reads.failed) copyRangeValues(ranges, values); const bool settled = rangesSettled(ranges, before.get(), generation); diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp index f7394f9ae603..d9f1b6956127 100644 --- a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp" +#include #include #include #include @@ -154,6 +155,45 @@ void unrepeatedVariantsSkipTests() { std::cout << "the heap walk memo skips shaders whose lookups do not hit and resumes when their keys repeat\n"; } +void walkReadRunsTests() { + std::uint64_t state = 0x9e3779b97f4a7c15ull; + const auto next = [&] { + state ^= state << 13u; + state ^= state >> 7u; + state ^= state << 17u; + return state; + }; + for (int round = 0; round < 512; ++round) { + std::vector words; + const auto count = 1u + next() % 96u; + std::uint64_t cursor = 0x10000u + (next() % 64u) * 4u; + for (std::uint32_t index = 0; index < count; ++index) { + const auto pick = next() % 8u; + if (pick < 4u) cursor += 4u; + else if (pick == 4u) cursor = 0x10000u + (next() % 512u) * 4u; + else if (pick == 5u) cursor += 2u; + else if (pick == 6u && cursor >= 0x10008u) cursor -= 8u; + words.push_back(cursor); + } + std::vector> runs; + for (const auto word : words) AgcDriver::DriverDetail::AppendWalkRead(runs, word); + std::vector> ranges; + AgcDriver::DriverDetail::CoalesceWalkReads(runs, ranges); + auto sorted = words; + std::sort(sorted.begin(), sorted.end()); + std::vector> expected; + for (const auto word : sorted) { + if (!expected.empty() && word <= expected.back().second) { + expected.back().second = std::max(expected.back().second, word + 4u); + continue; + } + expected.emplace_back(word, word + 4u); + } + require(ranges == expected, "the heap walk's read ranges in round " + std::to_string(round) + " differ from the merged ranges of its " + std::to_string(words.size()) + " word reads"); + } + std::cout << "the heap walk's read runs merge to the same ranges as its sorted word reads\n"; +} + } int main() { @@ -163,6 +203,7 @@ int main() { hitEntriesKeptTests(); sharedResultsChargedOnceTests(); unrepeatedVariantsSkipTests(); + walkReadRunsTests(); std::cout << "heap walk memo budget tests passed\n"; return 0; } catch (const std::exception& error) { From 847fe14434b787e4766c7665cff8defeca03a52f Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 12 Nov 2026 05:30:21 +0530 Subject: [PATCH 184/269] feat(agc): count why recorded dispatches get no recipe A dispatch without a recipe cannot become a committer item, so it drains the finisher and the committer and records on the worker. In GTA V that is about 5,000 of 9,000 dispatches per 10 s (the [dispatch-item] "no recipe" count), in both heap modes. Under APS5_PROFILE_DRAW the [dispatch-item] line now also says which recipe condition each such dispatch failed (not cacheable, binding overlay, no objects, no content key, fault checks, copied writes, unreusable), and for unreusable objects which noteReusable check refused them. --- .../Execution/include/VulkanDevice.hpp | 1 + .../src/Driver/Dispatch/Dispatch.cpp | 2 +- .../Execution/src/VulkanDevice.cpp | 46 ++++++++++++++++++- .../Graphics/include/ShaderResources.hpp | 4 ++ .../Graphics/src/ShaderResources.cpp | 36 +++++++++++++-- 5 files changed, 82 insertions(+), 7 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp index 29061ead3c07..63b719ce750c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp @@ -347,6 +347,7 @@ class VulkanDevice { // Whether dispatch-cache hits use recipes (APS5_NO_DISPATCH_RECIPE unset) and whether every // hit is verified (APS5_VERIFY_RECIPE=1). static bool DispatchRecipes(); + static std::string DispatchRecipeRefusalText(); static bool VerifyRecipes(); // Whether compute templates refresh their data buffers with a hit's words instead of keying // them (APS5_NO_TEMPLATE_DATA_REFRESH unset); the driver's data-only hits require it. diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index d6cdec4d4035..d8ab28b8c338 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -58,7 +58,7 @@ void ReportDispatchItems(bool profile) { std::snprintf(item, sizeof(item), " %s %llu", ItemFallbackNames[i], static_cast(itemFallbacks[i].load(std::memory_order_relaxed))); drained += item; } - std::fprintf(stderr, "[dispatch-item] %llu commit items (%llu recipes rebuilt on the committer); drained instead, cumulative:%s\n", static_cast(itemCommits.load(std::memory_order_relaxed)), static_cast(itemRebuilds.load(std::memory_order_relaxed)), drained.c_str()); + std::fprintf(stderr, "[dispatch-item] %llu commit items (%llu recipes rebuilt on the committer); drained instead, cumulative:%s; recipes refused:%s\n", static_cast(itemCommits.load(std::memory_order_relaxed)), static_cast(itemRebuilds.load(std::memory_order_relaxed)), drained.c_str(), VulkanDevice::DispatchRecipeRefusalText().c_str()); } bool CapturedCurrent(std::span captured, const ShaderSnapshot& code) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 3f8c0966f8cb..ff3a79f6e18a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -6673,6 +6673,47 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec return recordCompletedDispatch(shader, x, y, z, arguments, programAddress, recipeOut, threadGroup, htileClear, completion); } +namespace { + +enum class RecipeRefusal : std::size_t { NotCacheable, Overlay, NoObjects, NoContentKey, NeedsFaultChecks, NeedsCopiedWrites, Unreusable, Count }; +constexpr std::size_t UnreusableReasons = 11; +std::array, static_cast(RecipeRefusal::Count)> recipeRefusals{}; +std::array, UnreusableReasons> unreusableRefusals{}; + +void noteRecipeRefusal(bool cacheable, bool overlay, bool objects, bool contentKey, const Graphics::ShaderResources& resources) { + const auto note = [](RecipeRefusal reason) { recipeRefusals[static_cast(reason)].fetch_add(1, std::memory_order_relaxed); }; + if (!cacheable) return note(RecipeRefusal::NotCacheable); + if (overlay) return note(RecipeRefusal::Overlay); + if (!objects) return note(RecipeRefusal::NoObjects); + if (!contentKey) return note(RecipeRefusal::NoContentKey); + if (!resources.Reusable()) { + note(RecipeRefusal::Unreusable); + unreusableRefusals[std::min(resources.UnreusableReason(), UnreusableReasons - 1)].fetch_add(1, std::memory_order_relaxed); + return; + } + if (resources.NeedsCompletion()) note(resources.HoldsCopiedWrites() ? RecipeRefusal::NeedsCopiedWrites : RecipeRefusal::NeedsFaultChecks); +} + +} + +std::string VulkanDevice::DispatchRecipeRefusalText() { + constexpr std::array(RecipeRefusal::Count)> names{"not cacheable", "binding overlay", "no objects", "no content key", "fault checks", "copied writes", "unreusable"}; + std::string text; + for (std::size_t index = 0; index < names.size(); ++index) { + const auto count = recipeRefusals[index].load(std::memory_order_relaxed); + if (count == 0) continue; + text += " " + std::string(names[index]) + " " + std::to_string(count); + } + std::string unreusable; + for (std::size_t index = 0; index < UnreusableReasons; ++index) { + const auto count = unreusableRefusals[index].load(std::memory_order_relaxed); + if (count == 0) continue; + unreusable += std::string(unreusable.empty() ? "" : ", ") + Graphics::ShaderResources::UnreusableReasonName(static_cast(index)) + " " + std::to_string(count); + } + if (!unreusable.empty()) text += " (unreusable: " + unreusable + ")"; + return text.empty() ? " none" : text; +} + VulkanDevice::IndirectOutcome VulkanDevice::recordCompletedDispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint64_t arguments, std::uint64_t programAddress, std::shared_ptr* recipeOut, const std::array& threadGroup, std::optional> htileClear, DispatchCompletion& completion) { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; const auto& context = completion.context; @@ -6751,7 +6792,10 @@ VulkanDevice::IndirectOutcome VulkanDevice::recordCompletedDispatch(const Shader // object the resource cache serves under this content key (reusable: no lease, no copied // writes, every direct region import- or mirror-served), so a hit's proof is the template's // Revalidate and nothing needs completion work. - if (recipeOut != nullptr && DispatchRecipes() && cacheable && overlay == nullptr && resources->Reusable() && !resources->NeedsCompletion() && objects != nullptr && !contentKey.empty()) { + const bool recipeWanted = recipeOut != nullptr && DispatchRecipes(); + if (recipeWanted && profile && !(cacheable && overlay == nullptr && resources->Reusable() && !resources->NeedsCompletion() && objects != nullptr && !contentKey.empty())) + noteRecipeRefusal(cacheable, overlay != nullptr, objects != nullptr, !contentKey.empty(), *resources); + if (recipeWanted && cacheable && overlay == nullptr && resources->Reusable() && !resources->NeedsCompletion() && objects != nullptr && !contentKey.empty()) { auto recipe = std::make_shared(); recipe->device = state->device; recipe->templateRef = resources; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 28052c96e008..a687a59e9891 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -290,6 +290,7 @@ class ShaderResources { void WriteBackBuffers(); // Whether WriteBackBuffers has anything the CPU must see (copied written buffers, BDA faults). bool NeedsCompletion() const { return (bda != nullptr && faultChecks) || guestMemory.HasCopiedWrites(); } + bool HoldsCopiedWrites() const { return guestMemory.HasCopiedWrites(); } // Whether a written buffer was copied (its results reach guest memory by the CPU write-back). bool HasCopiedWrites() const { return guestMemory.HasCopiedWrites(); } bool HasGpuCopies() const { return guestMemory.HasGpuCopies(); } @@ -357,6 +358,8 @@ class ShaderResources { // ranges are fixed by the build), so a Revalidate's collects on the same worker are memo hits. void PrecollectSurfaces() const; bool Reusable() const { return reusable; } + std::uint8_t UnreusableReason() const { return unreusableReason; } + static const char* UnreusableReasonName(std::uint8_t reason); void KeepStorageImageBytes(Recorder& recorder) const; const std::vector& MultisampleSources() const { return multisampleSources; } static bool NeverReusable(std::span shaders); @@ -881,6 +884,7 @@ class ShaderResources { }; std::vector samplerSources; bool reusable = false; + std::uint8_t unreusableReason = 0; std::vector directRegions; std::vector validatedTextures; std::vector registeredImageViews; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index cb3e20735176..6f18d7f8f5ab 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -3098,21 +3098,39 @@ void ShaderResources::noteReusable() { // Taken whether or not the object turns out reusable: the lookups' records are this build's. captureValidation(); reusable = false; + unreusableReason = 0; spaceReuse = false; importsReconcilable = false; spaceReuse = false; directRegions.clear(); const bool spaceReusable = !htileClear.has_value() && drawBuild && usesBda && bdaReadOnly && !SpaceReuseDisabled() && guestMemory.SpaceOnly() && !guestMemory.HasCopiedWrites() && multisampleSources.empty() && !(bda != nullptr && LoopGuardEnabled()); - if (!spaceReusable && (htileClear.has_value() || guestMemory.HasCopiedWrites() || HoldsLease() || usesBda || !multisampleSources.empty() || (bda != nullptr && LoopGuardEnabled()))) return; - if (std::any_of(textures.begin(), textures.end(), [](const std::shared_ptr& texture) { return texture != nullptr && texture->RefreshedPerUse(); })) return; - if (TemplateDataRefresh() && std::any_of(allocations.begin(), allocations.end(), [](const Allocation& allocation) { return allocation.buffer != nullptr && !allocation.guest && allocation.role != ShaderRecompiler::DescriptorRole::ImageTableMap && allocation.size > MaxRefreshBytes; })) return; + if (!spaceReusable) { + if (htileClear.has_value()) unreusableReason = 1; + else if (guestMemory.HasCopiedWrites()) unreusableReason = 2; + else if (HoldsLease()) unreusableReason = 3; + else if (usesBda) unreusableReason = 4; + else if (!multisampleSources.empty()) unreusableReason = 5; + else if (bda != nullptr && LoopGuardEnabled()) unreusableReason = 6; + if (unreusableReason != 0) return; + } + if (std::any_of(textures.begin(), textures.end(), [](const std::shared_ptr& texture) { return texture != nullptr && texture->RefreshedPerUse(); })) { + unreusableReason = 7; + return; + } + if (TemplateDataRefresh() && std::any_of(allocations.begin(), allocations.end(), [](const Allocation& allocation) { return allocation.buffer != nullptr && !allocation.guest && allocation.role != ShaderRecompiler::DescriptorRole::ImageTableMap && allocation.size > MaxRefreshBytes; })) { + unreusableReason = 8; + return; + } if (spaceReusable) { spaceReuse = true; reusable = true; return; } const auto regions = guestMemory.DirectRegions(); - if (!regions.has_value()) return; + if (!regions.has_value()) { + unreusableReason = 9; + return; + } bool mirrored = false; for (const auto& [begin, end] : *regions) { // No reconcile here: the upload just took these imports, and the set is about to be recorded @@ -3122,7 +3140,10 @@ void ShaderResources::noteReusable() { // bit set, so the two spaces never collide. const bool imported = serial != 0; if (serial == 0) serial = ImageMirrorSerial(context, begin, static_cast(end - begin)); - if (serial == 0) return; + if (serial == 0) { + unreusableReason = 10; + return; + } directRegions.push_back({begin, end, serial}); mirrored = mirrored || !imported; } @@ -3139,6 +3160,11 @@ void ShaderResources::noteReusable() { reusable = true; } +const char* ShaderResources::UnreusableReasonName(std::uint8_t reason) { + constexpr std::array names{"unchecked", "htile clear", "copied writes", "lease", "bda", "multisample source", "loop guard", "texture refreshed per use", "template data refresh", "no direct regions", "region not served"}; + return reason < names.size() ? names[reason] : "unknown"; +} + namespace { std::atomic movedBehindGpuWrites{0}; } From 5204b8a4d41184566c71d6a1c87fe21d8b981848 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 12 Nov 2026 05:30:28 +0530 Subject: [PATCH 185/269] perf(agc): queue pipelined dispatches and sample dumps behind the finisher's draws While the draw finisher held draws, the worker drained it before every queue-0 dispatch and before every sample-count dump (EVENT_WRITE 0x39), so neither could reach the committer ahead of those draws. GTA V drained it about 2,100 times per 10 s for dispatches and 700 for dumps, and each drain waits until the finisher has built every held draw's stages, which takes longer with the GPU heap on. A dispatch that becomes a committer item and a dump that queues now reach the committer through the finisher, as queued labels already do: their enqueue runs as a finisher job, after the draws, and their write ranges are pending writes of the finisher until then. A dispatch that records on the worker, or whose kernel is one of the fills, clears and copies handled on the worker, still drains the finisher first (drain site "dispatch"). --- .../include/Driver/Draw/DrawPipeline.hpp | 2 +- .../Execution/include/Driver/Driver.hpp | 1 + .../src/Driver/Dispatch/Dispatch.cpp | 24 ++- .../src/Driver/Draw/DrawPipeline.cpp | 2 +- .../src/Driver/Packets/PacketExecution.cpp | 4 +- .../src/Driver/Packets/PacketMemory.cpp | 45 +++-- ...driver_finisher_dispatch_order_tests.cmake | 7 + .../tests/execution/FinisherDispatchOrder.cpp | 172 ++++++++++++++++++ 8 files changed, 237 insertions(+), 20 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_dispatch_order_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp index 1d3050d970ba..0a1b310b4a1c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp @@ -140,7 +140,7 @@ class DrawFinisher { LabelLookup PendingLabel(std::uint64_t address, std::size_t bytes, std::uint64_t& value); bool PendingOverlapsAny(std::span ranges); bool PendingKey(std::uint64_t key, std::uint64_t shape); - enum class DrainSite : std::uint32_t { Lookup, Reads, Packet, Kept, Count }; + enum class DrainSite : std::uint32_t { Lookup, Reads, Packet, Kept, Dispatch, Count }; static void NoteDrain(DrainSite site, bool drained); static std::string DrainText(); static void NoteDrainedOpcode(std::uint32_t opcode, bool besideCommits); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp index 21319456671f..16940c312867 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp @@ -350,6 +350,7 @@ class Driver { bool labelPacketQueues(std::span packet, std::uint32_t opcode); bool enqueueLabelPacket(std::span packet, std::uint32_t opcode, std::uint32_t queue, std::optional interrupt); bool enqueueDmaPacket(std::span packet, std::uint32_t opcode, std::uint32_t queue, const QueueState& state); + bool sampleDumpQueues(std::span packet, std::uint32_t opcode, std::uint32_t queue); bool enqueueSampleDumpPacket(std::span packet, std::uint32_t opcode, std::uint32_t queue); bool enqueueConstantRamDump(std::span packet, std::uint32_t opcode, std::uint32_t queue, const QueueState& state); void commitStore(std::uint32_t queue, std::uint64_t address, std::span bytes); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index d8ab28b8c338..3d2135ac16fd 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -138,6 +138,16 @@ void Driver::dispatch(QueueState& queue, std::span packet, } const bool pipelineCandidate = !resolving && !fromAhead && DispatchItemsEnabled() && DrawPipeline::Active() && indirectArguments == 0 && deferredLabels().labels.empty() && !matchesCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesStreamCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesIndexedCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute); const bool partialLastGroup = partialGroups != std::array{}; + if (!resolving && DrawPipeline::Active() && DrawFinisher::Busy() && !DrawFinisher::OnFinisherThread()) { + const auto code = std::span(snapshot.code).subspan(codeOffset); + const bool handled = !pipelineCandidate || Graphics::MatchMultisampledSingleClear(code, userData, compute.numThreads) || matchesFillKernel(code, userData, compute) || + (indirectArguments == 0 && (MatchDwordPatternFill(packet, code, userData, compute) || MatchConstantDwordFill(packet, code, userData, compute) || + MatchClampedGlobalFill(packet, code, userData, compute) || MatchMemoryValueBufferFill(packet, code, userData, compute) || + Graphics::MatchMemoryValueFill(code, userData, compute.numThreads, {packet[1], packet[2], packet[3]}).has_value())) || + Graphics::HtileDepthClearAddress(code, userData, compute.numThreads) != 0 || Graphics::MatchHtileBufferMaskClear(code, userData, compute, packet, indirectArguments).has_value(); + if (handled) DrawFinisher::Get().Drain(); + DrawFinisher::NoteDrain(DrawFinisher::DrainSite::Dispatch, handled); + } std::optional> htileClearCompletion; Graphics::HtileMaskClear htileMask; if (resolving) { @@ -531,7 +541,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, const auto epoch = DrawPipeline::EpochToken().load(std::memory_order_relaxed); const auto queueId = submission.queue; itemCommits.fetch_add(1, std::memory_order_relaxed); - DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Dispatch, [this, localDevice = std::move(localDevice), result = compiledResult, capture, registeredViews, snapshots = std::move(snapshots), liveWords = std::move(liveWords), groups, address, queueId, recipe, keepVariant, dataHit, epoch, htileClearCompletion, htileMask] { + auto commit = [this, localDevice = std::move(localDevice), result = compiledResult, capture, registeredViews, snapshots = std::move(snapshots), liveWords = std::move(liveWords), groups, address, queueId, recipe, keepVariant, dataHit, epoch, htileClearCompletion, htileMask] { DrawPipeline::FollowEpoch(epoch); GuestMemory::SetCurrentPacket(0x15, queueId); const auto& compiledCommit = *result; @@ -580,7 +590,17 @@ void Driver::dispatch(QueueState& queue, std::span packet, std::snprintf(where, sizeof(where), "compute shader 0x%llx: ", static_cast(address)); throw std::runtime_error(where + std::string(error.what())); } - }, std::move(itemWrites)); + }; + if (DrawFinisher::Overlap() && DrawFinisher::Busy() && !DrawFinisher::OnFinisherThread()) { + DrawFinisher::Pending held; + held.unknown = false; + held.writes = itemWrites; + DrawFinisher::Get().Enqueue([commit = std::move(commit), writes = std::move(itemWrites)]() mutable { + DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Dispatch, std::move(commit), std::move(writes)); + }, std::move(held)); + } else { + DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Dispatch, std::move(commit), std::move(itemWrites)); + } ReportDispatchItems(profile); return; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp index 79795ba47f85..707c828fd50d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp @@ -149,7 +149,7 @@ void DrawFinisher::NoteDrainedOpcode(std::uint32_t opcode, bool besideCommits) { } std::string DrawFinisher::DrainText() { - constexpr std::array(DrainSite::Count)> names{"lookup", "reads", "packet", "kept draw"}; + constexpr std::array(DrainSite::Count)> names{"lookup", "reads", "packet", "kept draw", "dispatch"}; std::string text = "; worker drains of the finisher (drained/skipped):"; for (std::size_t i = 0; i < names.size(); ++i) { char item[64]; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp index 09bfb00dadb5..d81b0500895a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp @@ -294,7 +294,9 @@ void Driver::execute(const Submission& submission) { if (submission.queue == 0 && DrawFinisher::Busy() && !keepsDrawFinisher(header, opcode)) { const bool queuesLabel = pipelined && !predicated && header != FlipPacketHeader && header != RenderingWaitPacketHeader && !submission.flips.contains(cursor) && labelPacketQueues(packet, opcode); const bool heldLabelWait = pipelined && !predicated && orderedWaits && (opcode == 0x3c || opcode == 0x93) && header != RenderingWaitPacketHeader && waitTakesPendingLabel(packet); - const bool beside = DrawFinisher::Overlap() && opcode != 0x15 && (queuesLabel || heldLabelWait || keepsDrawPipeline(packet, header, opcode)); + const bool queuesSampleDump = pipelined && !predicated && header != FlipPacketHeader && header != RenderingWaitPacketHeader && !submission.flips.contains(cursor) && sampleDumpQueues(packet, opcode, submission.queue); + const bool queuesDispatch = opcode == 0x15 && pipelined && pipelineDispatch() && !predicated; + const bool beside = DrawFinisher::Overlap() && (opcode != 0x15 || queuesDispatch) && (queuesLabel || heldLabelWait || queuesSampleDump || queuesDispatch || keepsDrawPipeline(packet, header, opcode)); if (!beside) DrawFinisher::Get().Drain(); if (DrawFinisher::Overlap()) { DrawFinisher::NoteDrain(DrawFinisher::DrainSite::Packet, !beside); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp index 8423c0c33671..ad7a1dc85f66 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp @@ -338,25 +338,40 @@ void Driver::dumpSampleCounters(std::uint64_t address) { } } -bool Driver::enqueueSampleDumpPacket(std::span packet, std::uint32_t opcode, std::uint32_t queue) { +bool Driver::sampleDumpQueues(std::span packet, std::uint32_t opcode, std::uint32_t queue) { static const bool ordered = std::getenv("APS5_PIPELINE_DRAIN_SAMPLE_DUMPS") == nullptr; if (!ordered || opcode != 0x46 || queue != 0 || packet.size() < 4 || !Pm4::SampleDump(packet) || !DrawPipeline::Active() || !deferredLabels().labels.empty()) return false; const auto address = Pm4::SampleDumpAddress(packet); - if (address == 0 || !GuestMemory::Accessible(reinterpret_cast(address), Pm4::SampleDumpBytes, true)) return false; - DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::SampleDump, [this, queue, address] { - GuestMemory::SetCurrentPacket(0x46, queue); - bool wrote = false; - { - GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Label); - std::lock_guard gpuLock(GuestMemory::GpuMutex()); - if (const auto localDevice = device.Load()) { - recordDeferredLabels(localDevice.get(), queue); - wrote = localDevice->DumpSamplesOnGpu(address); - if (!wrote) localDevice->WaitIdle(); + return address != 0 && GuestMemory::Accessible(reinterpret_cast(address), Pm4::SampleDumpBytes, true); +} + +bool Driver::enqueueSampleDumpPacket(std::span packet, std::uint32_t opcode, std::uint32_t queue) { + if (!sampleDumpQueues(packet, opcode, queue)) return false; + const auto address = Pm4::SampleDumpAddress(packet); + auto enqueue = [this, queue, address] { + DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::SampleDump, [this, queue, address] { + GuestMemory::SetCurrentPacket(0x46, queue); + bool wrote = false; + { + GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Label); + std::lock_guard gpuLock(GuestMemory::GpuMutex()); + if (const auto localDevice = device.Load()) { + recordDeferredLabels(localDevice.get(), queue); + wrote = localDevice->DumpSamplesOnGpu(address); + if (!wrote) localDevice->WaitIdle(); + } } - } - if (!wrote) dumpSampleCounters(address); - }, {{address, address + Pm4::SampleDumpBytes}}); + if (!wrote) dumpSampleCounters(address); + }, {{address, address + Pm4::SampleDumpBytes}}); + }; + if (DrawFinisher::Overlap() && DrawFinisher::Busy() && !DrawFinisher::OnFinisherThread()) { + DrawFinisher::Pending held; + held.unknown = false; + held.writes = {{address, address + Pm4::SampleDumpBytes}}; + DrawFinisher::Get().Enqueue(std::move(enqueue), std::move(held)); + } else { + enqueue(); + } ++sampleDumpsQueued; Graphics::Recorder::CountRecordedWork(); return true; diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_dispatch_order_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_dispatch_order_tests.cmake new file mode 100644 index 000000000000..ab71ab726682 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_finisher_dispatch_order_tests.cmake @@ -0,0 +1,7 @@ +if(BUILD_TESTING) + agc_add_draw_pipeline_test(agc_driver_finisher_dispatch_order) +endif() + +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_finisher_dispatch_order) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp new file mode 100644 index 000000000000..755ba1c1535f --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp @@ -0,0 +1,172 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "HeapSampleKernel.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, +}; +alignas(256) constexpr std::array PixelCode{0xf4000100u, 0xfa000000u, 0xbf8cc07fu, 0x7e000204u, 0x06000002u, 0x7e020280u, 0xf800180fu, 0x00010100u, 0xbf810000u, 0xbf810000u}; +alignas(256) std::array PixelConstant{}; +alignas(256) std::array ColorMemory{}; +constexpr std::uint32_t Rounds = 8; +alignas(256) std::array TextureMemory{}; +alignas(4096) std::array, Rounds> Outputs{}; +alignas(256) std::array SampleMemory{}; + +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(Header& header, const std::uint32_t* code, std::size_t bytes, std::uint8_t type) { + header.shader.file_header = 0x34333231u; + header.shader.version = 0x18u; + header.shader.header_size = sizeof(Header); + header.shader.shader_size = static_cast(bytes); + header.shader.code = code; + header.shader.type = type; + header.shader.user_data = &header.userData; + AgcDriverRegisterShader_nid_postfix(&header.shader); +} + +void Append(std::vector& commands, std::uint32_t opcode, std::initializer_list payload) { + commands.push_back(0xc0000000u | (static_cast(payload.size() - 1) << 16u) | (opcode << 8u)); + commands.insert(commands.end(), payload); +} + +std::vector Setup() { + const auto color = reinterpret_cast(ColorMemory.data()); + const auto vertex = reinterpret_cast(VertexCode.data()); + const auto pixel = reinterpret_cast(PixelCode.data()); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, {0x207, 0}, {0x200, 0}, {0x203, 0x800}, + {0x2dc, 0xaa00}, {0x2f8, 0}, {0x292, 2}, {0x293, 0}, + {0x80, 0}, {0x8d, 0}, {0x83, 0xffff}, {0x8c, 0xa}, + {0x2f9, 0x2d}, {0x313, 0x6000}, {0x30e, 0xffffffff}, {0x30f, 0xffffffff}, + {0x206, 0x43f}, {0x204, 0x80000}, {0x205, 0x240}, + {0x8e, 0xf}, {0x8f, 0xf}, {0x202, 0xcc0010}, + {0x1c4, 0}, {0x1c5, 9}, {0x1c3, 4}, {0x31c, 0x28028}, + {0x31b, 0}, {0x31d, 0}, {0x3b0, (63u << 14u) | 3u}, + {0x3b8, 0x9000000}, {0x1e0, 0}, + {0xc, 0}, {0xd, 0x40040}, + {0x81, 0x80000000}, {0x82, 0x40040}, + {0x90, 0x80000000}, {0x91, 0x40040}, + {0x94, 0x80000000}, {0x95, 0x40040}, + {0x318, static_cast(color >> 8u)}, {0x390, static_cast(color >> 40u)}, + {0x10f, std::bit_cast(32.0f)}, {0x110, std::bit_cast(32.0f)}, + {0x111, std::bit_cast(-2.0f)}, {0x112, std::bit_cast(2.0f)}, + {0x113, std::bit_cast(1.0f)}, {0x114, 0}, + {0xb4, 0}, {0xb5, std::bit_cast(1.0f)}, + {0x2fe, 0}, {0x302, 0}, {0x306, 0}, {0x30a, 0}, + }; + const std::vector> shader{ + {0xc8, static_cast(vertex >> 8u)}, {0xc9, static_cast(vertex >> 40u)}, {0x8b, 0}, {0x8c, 0}, + {0x008, static_cast(pixel >> 8u)}, {0x009, static_cast(pixel >> 40u)}, {0x00b, 3u << 1u}, + }; + std::vector commands; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + for (const auto& [offset, value] : shader) Append(commands, 0x76, {offset, value}); + const auto table = reinterpret_cast(PixelConstant.data()); + Append(commands, 0x76, {0x00c, static_cast(table)}); + Append(commands, 0x76, {0x00d, static_cast(table >> 32u)}); + Append(commands, 0x76, {0x00e, std::bit_cast(0.25f)}); + return commands; +} + +void SetShaderRegister(std::vector& commands, std::uint32_t offset, std::uint32_t value) { + Append(commands, 0x76, {offset, value}); +} + +void Sample(std::vector& commands, float* output) { + const auto address = static_cast(reinterpret_cast(SampleCode.data())); + SetShaderRegister(commands, 0x20c, static_cast(address >> 8u)); + SetShaderRegister(commands, 0x20d, static_cast(address >> 40u) & 0xffu); + for (const std::uint32_t offset : {0x207u, 0x208u, 0x209u}) SetShaderRegister(commands, offset, 1); + SetShaderRegister(commands, 0x212, 0); + SetShaderRegister(commands, 0x213, 16u << 1u); + std::uint32_t offset = 0x240; + for (const auto value : SampleUserData(TextureMemory.data(), output)) SetShaderRegister(commands, offset++, value); + Append(commands, 0x15, {1, 1, 1, 0x8041u}); +} + +void DumpSamples(std::vector& commands, std::uint32_t round) { + const auto address = reinterpret_cast(SampleMemory.data() + 32u * round); + Append(commands, 0x46, {AgcDriver::Pm4::SampleDumpEvent | (1u << 8u), static_cast(address), static_cast(address >> 32u)}); +} + +} + +int main() { + try { + bool libraries = false; + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + libraries = device->GraphicsPipelineLibraries(); + } + if (!libraries && std::getenv("APS5_NO_GPL") == nullptr) return VulkanTestSkipped; + using AgcDriver::DriverDetail::DrawFinisher; + const bool finisher = DrawFinisher::Enabled() && DrawFinisher::Overlap(); + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + Registered(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1); + PixelConstant[0] = 0.25f; + FillTexels(TextureMemory, SampleTexel); + for (auto& output : Outputs) output.fill(-1.0f); + std::string drains; + for (std::uint32_t pass = 0; pass < 2; ++pass) { + static_cast(DrawFinisher::DrainText()); + auto commands = Setup(); + for (std::uint32_t round = 0; round < Rounds; ++round) { + Append(commands, 0x2d, {3, 2}); + Sample(commands, Outputs[round].data()); + Append(commands, 0x2d, {3, 2}); + DumpSamples(commands, round); + } + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); + drains = DrawFinisher::DrainText(); + } + AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(Outputs.data()), sizeof(Outputs)); + AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(ColorMemory.data()), ColorMemory.size()); + for (std::uint32_t round = 0; round < Rounds; ++round) RequireSampled(Outputs[round].data(), SampleTexel, "the dispatch after finisher draws in round " + std::to_string(round)); + unsigned brightest = 0; + for (const auto value : ColorMemory) brightest = std::max(brightest, static_cast(std::to_integer(value))); + Require(brightest + 2 >= 128 && brightest <= 130, "the draws around the dispatches wrote " + std::to_string(brightest) + ", expected 128"); + if (finisher) Require(drains.find(" 0x15 x") == std::string::npos, "a pipelined dispatch after a draw handed to the finisher drained the finisher:" + drains); + if (finisher) Require(drains.find(" 0x46 x") == std::string::npos, "a sample dump after a draw handed to the finisher drained the finisher:" + drains); + AgcDriverShutdown_nid_postfix(); + std::cout << "dispatches and sample dumps after finisher draws " << (finisher ? "queued through the finisher" : "run in order") << "\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + AgcDriverShutdown_nid_postfix(); + return 1; + } +} From a934a5ea2e50691362f498e5d2d91d393c405f82 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Thu, 12 Nov 2026 05:30:35 +0530 Subject: [PATCH 186/269] perf(recompiler): fill a heap stage's per-draw binding words without a full populate When a heap stage's images or samplers differed from its template's, HeapBindingWords ran a full DescriptorBindingBuilder::Populate for every draw: it copied each planned binding (shapes, flags, counts and all), built its words and resolved image tables, only to keep each binding's guest words. PopulateGuestWords fills just those words through the same per-role code Populate now uses, and the image tables are resolved only for a plan that has table bindings, which a stage with per-draw bindings never does. On the game-shaped bench (fresh, 512 programs, 2048 textures) the finisher's heap binding work drops from 0.34 to 0.18 us per draw. APS5_VERIFY_GPU_HEAP compares every stage's words with a full populate. --- .../Optimization/DescriptorBindingBuilder.hpp | 1 + .../src/DescriptorBindingBuilder.cpp | 169 ++++++++++-------- core/shader/recompiler/Recompiler.cpp | 23 ++- 3 files changed, 112 insertions(+), 81 deletions(-) diff --git a/core/shader/recompiler/Optimization/include/Optimization/DescriptorBindingBuilder.hpp b/core/shader/recompiler/Optimization/include/Optimization/DescriptorBindingBuilder.hpp index 58b871b38c3a..8cc8eccd9e76 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/DescriptorBindingBuilder.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/DescriptorBindingBuilder.hpp @@ -56,6 +56,7 @@ class DescriptorBindingBuilder { DescriptorBindingPlan Prepare(const IrBindingLayout& layout, const ShaderInfo& info, IrShaderStage stage, const ResourceSnapshot& snapshot, std::span exportMappings = {}, bool registrationModules = false, bool fragmentDescriptorSet = false, std::span substitutes = {}, bool shaderImageMinLod = false) const; DescriptorBindingPlan Select(const DescriptorBindingPlan& plan, std::span bindings) const; void Populate(BindingAllocationResult& allocation, const CompiledBindingLayout& compiled, const DescriptorBindingPlan& plan, std::uint32_t userDataBase, const ResourceSnapshot& snapshot, const std::array& partialThreads, const ResolvedImageTables* tables = nullptr) const; + void PopulateGuestWords(std::vector>& words, const CompiledBindingLayout& compiled, const DescriptorBindingPlan& plan, std::uint32_t userDataBase, const ResourceSnapshot& snapshot, const std::array& partialThreads, const ResolvedImageTables* tables = nullptr) const; void Populate(BindingAllocationResult& allocation, const IrProgram& program, const ResourceSnapshot& snapshot, const std::array& partialThreads, std::span exportMappings = {}) const; void Populate(BindingAllocationResult& allocation, const ShaderInfo& info, IrShaderStage stage, std::uint32_t userDataBase, const ResourceSnapshot& snapshot, const std::array& partialThreads, std::span exportMappings = {}) const; }; diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index 47824ad434dc..e6482752f2ee 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -161,24 +161,6 @@ DescriptorImageShape ImageShapeForResource(const ImageResource& image) { fail("DescriptorBindingBuilder::Populate image resource dimension has no descriptor image shape"); } -std::vector GuestBuffersDescriptor(const std::vector& resources, const ResourceSnapshot& snapshot) { - std::vector result; - result.reserve(resources.size() * 4u); - for (const std::uint32_t r : resources) { - if (r >= snapshot.buffers.size()) { - fail("DescriptorBindingBuilder::Populate guest buffer index is out of range"); - } - const DescriptorValue& value = snapshot.buffers[r]; - if (value.dwordCount != 4u) { - fail("DescriptorBindingBuilder::Populate guest buffer descriptor has an invalid width"); - } - for (std::uint32_t dword = 0; dword < 4u; dword++) { - result.push_back(value.dwords[dword]); - } - } - return result; -} - std::vector GuestSamplersDescriptor(const std::vector& resources, const ResourceSnapshot& snapshot) { std::vector result; result.reserve(resources.size() * 4u); @@ -748,6 +730,80 @@ DescriptorBindingPlan DescriptorBindingBuilder::Select(const DescriptorBindingPl return selected; } +namespace { + +void guestBindingWords(const PreparedDescriptorBinding& entry, std::vector& words, const ResourceSnapshot& snapshot, const ResolvedImageTables* tables) { + switch (entry.descriptor.role) { + case DescriptorRole::GuestBuffers: + words.clear(); + words.reserve(entry.resources.size() * 4u); + for (const std::uint32_t resource : entry.resources) { + if (resource >= snapshot.buffers.size()) fail("DescriptorBindingBuilder::Populate guest buffer index is out of range"); + const DescriptorValue& value = snapshot.buffers[resource]; + if (value.dwordCount != 4u) fail("DescriptorBindingBuilder::Populate guest buffer descriptor has an invalid width"); + words.insert(words.end(), value.dwords.begin(), value.dwords.begin() + 4); + } + break; + case DescriptorRole::GuestImages: + words.reserve(words.size() + entry.resources.size() * 8u); + for (std::size_t element = 0; element < entry.resources.size(); ++element) { + const auto& descriptor = snapshot.images.at(entry.resources[element]); + if (descriptor.dwordCount != 8u) fail("invalid runtime image descriptor width"); + if (!entry.inactive.empty() && entry.inactive[element]) { + words.insert(words.end(), 8u, 0u); + continue; + } + const auto offset = words.size(); + words.insert(words.end(), descriptor.dwords.begin(), descriptor.dwords.begin() + 8); + if (entry.identityImageSwizzle[element]) words[offset + 3u] = (words[offset + 3u] & ~0xfffu) | ShaderImageIdentitySwizzle; + } + break; + case DescriptorRole::GuestSamplers: + words = GuestSamplersDescriptor(entry.resources, snapshot); + for (const auto element : entry.samplerFilterElements) { + auto& filter = words.at(element * 4u + 2u); + filter = PointFilteredSamplerWord(words.at(element * 4u), filter); + } + break; + case DescriptorRole::ImageTable: + case DescriptorRole::ImageStorageTable: + if (tables == nullptr) fail("DescriptorBindingBuilder::Populate image table elements were not resolved"); + words.reserve(words.size() + tables->elements.size() * 8u); + for (const auto& element : tables->elements) words.insert(words.end(), element.words.begin(), element.words.end()); + break; + case DescriptorRole::SamplerTable: + if (tables == nullptr) fail("DescriptorBindingBuilder::Populate sampler table elements were not resolved"); + words.reserve(words.size() + tables->samplers.size() * 4u); + for (const auto& element : tables->samplers) { + const auto first = words.size(); + words.insert(words.end(), element.words.begin(), element.words.end()); + if (element.point) words[first + 2u] = PointFilteredSamplerWord(words[first], words[first + 2u]); + } + break; + case DescriptorRole::ImageTableMap: + if (tables == nullptr || tables->map.empty()) fail("DescriptorBindingBuilder::Populate image table map was not resolved"); + words = tables->map; + break; + case DescriptorRole::FlattenedSrt: + if (snapshot.flattenedSrt.empty()) fail("DescriptorBindingBuilder::Populate flattened SRT snapshot is empty"); + words = snapshot.flattenedSrt; + break; + case DescriptorRole::ShaderData: + case DescriptorRole::Gds: + case DescriptorRole::BdaPagetable: + case DescriptorRole::FaultBuffer: + break; + } + const auto role = entry.descriptor.role; + if (role == DescriptorRole::GuestBuffers || role == DescriptorRole::GuestImages || role == DescriptorRole::GuestSamplers) { + if (entry.descriptor.count == 0u || words.size() % entry.descriptor.count != 0u) { + fail("DescriptorBindingBuilder::Populate guest descriptor size is not a multiple of the binding count"); + } + } +} + +} + void DescriptorBindingBuilder::Populate(BindingAllocationResult& allocation, const CompiledBindingLayout& compiled, const DescriptorBindingPlan& plan, std::uint32_t userDataBase, const ResourceSnapshot& snapshot, const std::array& partialThreads, const ResolvedImageTables* tables) const { const auto& layout = compiled.layout; const bool needsShaderData = layout.UsesPushData() || plan.storageData; @@ -763,39 +819,16 @@ void DescriptorBindingBuilder::Populate(BindingAllocationResult& allocation, con std::size_t readOnlyHere = 0; for (const auto& entry : plan.bindings) { auto physical = entry.descriptor; + if (physical.role == DescriptorRole::ShaderData) physical.guestDescriptor = std::move(shaderData); + else guestBindingWords(entry, physical.guestDescriptor, snapshot, tables); switch (physical.role) { case DescriptorRole::GuestBuffers: - physical.guestDescriptor = GuestBuffersDescriptor(entry.resources, snapshot); writtenHere += entry.writtenBuffers; readOnlyHere += entry.readOnlyBuffers; break; - case DescriptorRole::GuestImages: - physical.guestDescriptor.reserve(entry.resources.size() * 8u); - for (std::size_t element = 0; element < entry.resources.size(); ++element) { - const auto& descriptor = snapshot.images.at(entry.resources[element]); - if (descriptor.dwordCount != 8u) fail("invalid runtime image descriptor width"); - if (!entry.inactive.empty() && entry.inactive[element]) { - physical.guestDescriptor.insert(physical.guestDescriptor.end(), 8u, 0u); - continue; - } - const auto offset = physical.guestDescriptor.size(); - physical.guestDescriptor.insert(physical.guestDescriptor.end(), descriptor.dwords.begin(), descriptor.dwords.begin() + 8); - if (entry.identityImageSwizzle[element]) physical.guestDescriptor[offset + 3u] = (physical.guestDescriptor[offset + 3u] & ~0xfffu) | ShaderImageIdentitySwizzle; - } - break; - case DescriptorRole::GuestSamplers: - physical.guestDescriptor = GuestSamplersDescriptor(entry.resources, snapshot); - for (const auto element : entry.samplerFilterElements) { - auto& filter = physical.guestDescriptor.at(element * 4u + 2u); - filter = PointFilteredSamplerWord(physical.guestDescriptor.at(element * 4u), filter); - } - break; case DescriptorRole::ImageTable: case DescriptorRole::ImageStorageTable: - if (tables == nullptr) fail("DescriptorBindingBuilder::Populate image table elements were not resolved"); - physical.guestDescriptor.reserve(tables->elements.size() * 8u); for (const auto& element : tables->elements) { - physical.guestDescriptor.insert(physical.guestDescriptor.end(), element.words.begin(), element.words.end()); ImageResource shape; shape.dimension = element.dimension; physical.imageShapes.push_back(ImageShapeForResource(shape)); @@ -812,44 +845,14 @@ void DescriptorBindingBuilder::Populate(BindingAllocationResult& allocation, con physical.count = static_cast(tables->elements.size()); break; case DescriptorRole::SamplerTable: - if (tables == nullptr) fail("DescriptorBindingBuilder::Populate sampler table elements were not resolved"); - physical.guestDescriptor.reserve(tables->samplers.size() * 4u); - for (const auto& element : tables->samplers) { - const auto first = physical.guestDescriptor.size(); - physical.guestDescriptor.insert(physical.guestDescriptor.end(), element.words.begin(), element.words.end()); - if (element.point) physical.guestDescriptor[first + 2u] = PointFilteredSamplerWord(physical.guestDescriptor[first], physical.guestDescriptor[first + 2u]); - physical.samplerDepthCompare.push_back(element.compare); - } + for (const auto& element : tables->samplers) physical.samplerDepthCompare.push_back(element.compare); physical.count = static_cast(tables->samplers.size()); break; - case DescriptorRole::ImageTableMap: - if (tables == nullptr || tables->map.empty()) fail("DescriptorBindingBuilder::Populate image table map was not resolved"); - physical.guestDescriptor = tables->map; - break; - case DescriptorRole::FlattenedSrt: - if (snapshot.flattenedSrt.empty()) { - fail("DescriptorBindingBuilder::Populate flattened SRT snapshot is empty"); - } - physical.guestDescriptor = snapshot.flattenedSrt; - break; - case DescriptorRole::ShaderData: - physical.guestDescriptor = std::move(shaderData); + default: break; - case DescriptorRole::Gds: - case DescriptorRole::BdaPagetable: - case DescriptorRole::FaultBuffer: - break; - } - - if (physical.role == DescriptorRole::GuestBuffers || physical.role == DescriptorRole::GuestImages || physical.role == DescriptorRole::GuestSamplers) { - if (physical.count == 0u || physical.guestDescriptor.size() % physical.count != 0u) { - fail("DescriptorBindingBuilder::Populate guest descriptor size is not a multiple of the binding count"); - } } - bindings.push_back(std::move(physical)); } - if (bufferWrittenTraceEnabled()) { // Cumulative counts include every Populate of the process (the replay tool populates // each program twice), so the per-call counts are the ones to sum per program. @@ -865,4 +868,20 @@ void DescriptorBindingBuilder::Populate(BindingAllocationResult& allocation, con } } +void DescriptorBindingBuilder::PopulateGuestWords(std::vector>& words, const CompiledBindingLayout& compiled, const DescriptorBindingPlan& plan, std::uint32_t userDataBase, const ResourceSnapshot& snapshot, const std::array& partialThreads, const ResolvedImageTables* tables) const { + const auto& layout = compiled.layout; + words.resize(plan.bindings.size()); + for (std::size_t index = 0; index < plan.bindings.size(); ++index) { + const auto& entry = plan.bindings[index]; + if (entry.descriptor.role != DescriptorRole::ShaderData) { + words[index].assign(entry.descriptor.guestDescriptor.begin(), entry.descriptor.guestDescriptor.end()); + guestBindingWords(entry, words[index], snapshot, tables); + } else if (layout.UsesPushData() || plan.storageData) { + words[index] = ShaderDataDwordsFor(layout, userDataBase, snapshot, partialThreads, plan.imageMetadata, plan.runtimeState); + } else { + words[index].clear(); + } + } +} + } diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index c6aa8e4fb136..8c75a50c33c4 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -2494,12 +2495,22 @@ void HeapBindingWords(const RecompileRequest& request, const CompiledVariant& va if (AllEmpty(words.bindings)) words.bindings.clear(); return; } - const auto tables = ResourceMaterializer::ResolveImageTables(variant.info.info, snapshot, variant.artifact.variantId); - BindingAllocationResult bindings; - DescriptorBindingBuilder{}.Populate(bindings, variant.bindings, *shared.plan.plan, variant.info.userDataBase, snapshot, partialThreads(request), &tables); - if (bindings.bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw bindings differ from its template"); - words.bindings.reserve(count); - for (auto& binding : bindings.bindings) words.bindings.push_back(std::move(binding.guestDescriptor)); + const bool tableRoles = std::ranges::any_of(shared.plan.plan->bindings, [](const PreparedDescriptorBinding& entry) { + const auto role = entry.descriptor.role; + return role == DescriptorRole::ImageTable || role == DescriptorRole::ImageStorageTable || role == DescriptorRole::SamplerTable || role == DescriptorRole::ImageTableMap; + }); + const auto tables = tableRoles ? std::optional(ResourceMaterializer::ResolveImageTables(variant.info.info, snapshot, variant.artifact.variantId)) : std::nullopt; + DescriptorBindingBuilder{}.PopulateGuestWords(words.bindings, variant.bindings, *shared.plan.plan, variant.info.userDataBase, snapshot, partialThreads(request), tables ? &*tables : nullptr); + if (words.bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw bindings differ from its template"); + static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + if (verify) { + const auto resolved = ResourceMaterializer::ResolveImageTables(variant.info.info, snapshot, variant.artifact.variantId); + BindingAllocationResult bindings; + DescriptorBindingBuilder{}.Populate(bindings, variant.bindings, *shared.plan.plan, variant.info.userDataBase, snapshot, partialThreads(request), &resolved); + for (std::size_t index = 0; index < count; ++index) { + if (bindings.bindings[index].guestDescriptor != words.bindings[index]) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw binding " + std::to_string(index) + " words differ from a full populate"); + } + } if (variant.artifact.registrationModule && request.shader.stage != ShaderStage::Fragment && layout.runtimeStateDwords != 0u) { const auto first = layout.RuntimeStateDword() + RuntimeAbi::StateVertexSelectors; for (std::size_t index = 0; index < words.bindings.size(); ++index) { From db48d574b4229c6291929f04a1288e2d93723a30 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 02:12:02 +0530 Subject: [PATCH 187/269] fix(recompiler): keep a specialized module's words once a result needed them again Since 0e1767b24b the specialized module caches hold only a weak reference to a module's words, so a module no result uses releases them, and the next result built from the same key runs the whole specialization pass again. In GTA V with the GPU heap on, the same dozen fragment modules (55k-120k words each) were released and rebuilt over and over on the stage capture path, 6 ms per rebuild on the finisher while the decoder waited, which showed as frame spikes: about 30 frames per 40 s over the median by 4 ms or more, against about 10 with the heap off. A module whose words had to be built again now keeps them; a module used once still releases them as before. In GTA V the rebuilt modules hold about 4 MiB, slow stage builds at the test spot drop from 23 per 30 s to 2 per 44 s, and the heap-on spikes match heap off (11 against 11 per 40 s). --- .../libSceAgcDriver/tests/ShaderMemory.cpp | 30 +++++++++++++++++++ core/shader/recompiler/Recompiler.cpp | 3 ++ 2 files changed, 33 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 2114cc39bd82..3c0c622c9529 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -444,6 +444,35 @@ void verifySpecializedModuleRelease() { require(shared.spirv.data() == again.spirv.data(), "specialized module release: a second result of a live module copied its words"); } +void verifyRebuiltModuleKeepsWords() { + using namespace ShaderRecompiler; + const std::array color{0x3f800000u}; + const std::vector code{0xbf800003u, 0x7e000200u, 0xf800180fu, 0u, 0xbf810000u}; + auto pixel = FrontendRequest(code, color); + pixel.shader.stage = ShaderStage::Fragment; + pixel.context.compute.reset(); + pixel.context.pixel = ShaderPixelStageInfo{}; + pixel.context.pixel->wave32 = true; + pixel.context.pixel->targetOutputMode[0] = 9u; + pixel.context.pixel->dualSourceBlend = true; + pixel.context.waveSize = 32u; + pixel.useCache = true; + { + const auto built = Recompile(pixel); + require(built.specializationId != 0u, "rebuilt module: the pixel fixture was not specialized"); + } + SharedSpirv::Weak rebuilt; + const std::uint32_t* words = nullptr; + { + const auto again = Recompile(pixel); + rebuilt = again.spirv.Weaken(); + words = again.spirv.data(); + } + require(!rebuilt.Expired(), "rebuilt module: a module needed again after its release dropped its words a second time"); + const auto third = Recompile(pixel); + require(third.spirv.data() == words, "rebuilt module: a kept module was specialized again"); +} + void verifyLayerSpecializationRelease() { using namespace ShaderRecompiler; const std::array code{ @@ -12149,6 +12178,7 @@ int main(int argc, char** argv) { verifyImageTableKeys(); verifyImageTables(); verifySpecializedModuleRelease(); + verifyRebuiltModuleKeepsWords(); verifyLayerSpecializationRelease(); verifyImageTableRegistration(); verifyScalarAddressRule(); diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 8c75a50c33c4..aeb9bafe82e2 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -967,6 +967,7 @@ struct SpecializedModule { SpirvContentHash hash; mutable std::mutex mutex; mutable SharedSpirv::Weak spirv; + mutable SharedSpirv kept; }; struct SpecializedSpirv { @@ -1120,6 +1121,7 @@ SharedSpirv specializedWords(const SpecializedModule& module, const CompiledShad auto spirv = InternSpirv(specializeWords(artifact, classes, constants, target)); if (spirv.ContentHash() != module.hash) throw std::runtime_error("ShaderRecompiler: a specialized module built again from its key differs from its first build"); module.spirv = spirv.Weaken(); + module.kept = spirv; return spirv; } @@ -1152,6 +1154,7 @@ struct RegistrationModuleEntry { SharedSpirv lockedWords(const SpecializedModule& module) { std::lock_guard lock(module.mutex); + if (!module.kept.empty()) return module.kept; return module.spirv.Lock(); } From 7035a25dfbb66783ccd2a91e7ab11df1da0b8d57 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 02:12:18 +0530 Subject: [PATCH 188/269] perf(agc): keep heap stage tables across draws and drop heap caches that do not pay Heap stages now work like vkd3d's descriptor tables instead of rebuilding their shader data every draw: - Image slots are taken once per stage result instead of walked every draw. A stage's finished shader data (walked words, user front, data patches, slot indices), its flattened SRT and its image table map live in persistent tables owned by the stage result, retired after the serial of the last batch that used them; a rebuilt table is written fresh. - Fully pushed user words write no block; overflow user words are written into the ring every draw, with no compare and no keep. The push image is cached with a version per stage, and the vertex and fragment sides share one copy of the push globals (fragment globals first, so a pixel stage keeps its standalone layout). - The image table map is cached per stage and checked with slot generations. APS5_HEAP_NO_CACHE=all|heap|,... bypasses the heap and shared draw caches by name, and every heap verify check (slot contents, stage against a full capture, pushed ranges, ring hits) now throws at the draw instead of counting. Benched off one by one on the game-shaped walk bench, the walk memo, the stage skip, the BDA root-role memo and the pushed-range cache cost as much as they saved, so they are deleted; without the walk memo GTA V's heap-on frame rate rose about 2%. The template front table stays (APS5_HEAP_NO_CACHE=template-front). In GTA V the heap-on gap to heap off falls from about 4% to about 2.8%; the finisher's extra stage-build time drops from 0.47 to 0.14 ms per frame. --- .../include/Driver/Draw/HeapWalkMemo.hpp | 203 ----------- .../Execution/src/Driver/Draw/Draw.cpp | 1 - .../Execution/src/Driver/Draw/DrawCache.cpp | 9 +- .../Execution/src/Driver/Draw/HeapStages.cpp | 236 +----------- .../Execution/src/VulkanDevice.cpp | 3 +- .../Graphics/include/BindlessHeap.hpp | 34 +- .../Graphics/include/ShaderResources.hpp | 44 ++- .../Graphics/src/BindlessHeap.cpp | 128 +++++-- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 11 +- .../Graphics/src/ShaderResources.cpp | 338 +++++++++++------- .../tests/BindlessHeapSlots.cpp | 38 ++ .../libSceAgcDriver/tests/HeapWalkMemo.cpp | 213 ----------- .../libSceAgcDriver/tests/HeapWalkReads.cpp | 67 ++++ .../tests/PushDataPlacements.cpp | 7 +- ...driver_draw_pushed_user_values_tests.cmake | 5 + .../agc_driver_heap_draw_sample_tests.cmake | 2 + .../agc_driver_heap_walk_memo_tests.cmake | 24 -- ..._driver_heap_walk_memo_threads_tests.cmake | 3 - .../agc_driver_heap_walk_reads_tests.cmake | 24 ++ .../agc_driver_heap_walk_threads_tests.cmake | 3 + .../tests/execution/DrawPushedUserValues.cpp | 223 ++++++++++++ .../tests/execution/HeapDrawSample.cpp | 7 +- .../tests/execution/HeapTableStageReuse.cpp | 29 ++ .../execution/HeapWalkCaptureFailure.cpp | 18 +- ...alkMemoThreads.cpp => HeapWalkThreads.cpp} | 13 +- core/shader/recompiler/CMakeLists.txt | 6 + core/shader/recompiler/HeapCacheSwitch.hpp | 79 ++++ core/shader/recompiler/PushDataLayout.hpp | 25 +- core/shader/recompiler/Recompiler.cpp | 12 +- core/shader/recompiler/ShaderDiskCache.cpp | 1 + 30 files changed, 909 insertions(+), 897 deletions(-) delete mode 100644 core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp delete mode 100644 core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/HeapWalkReads.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_pushed_user_values_tests.cmake delete mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_memo_tests.cmake delete mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_memo_threads_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_reads_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_threads_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/DrawPushedUserValues.cpp rename core/libs/prx/libSceAgcDriver/tests/execution/{HeapWalkMemoThreads.cpp => HeapWalkThreads.cpp} (88%) create mode 100644 core/shader/recompiler/HeapCacheSwitch.hpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp deleted file mode 100644 index fd5f4586118f..000000000000 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp +++ /dev/null @@ -1,203 +0,0 @@ -#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_HEAPWALKMEMO_HPP -#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_HEAPWALKMEMO_HPP - -#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" -#include -#include -#include -#include -#include -#include -#include - -namespace AgcDriver::DriverDetail { - -struct HeapWalkEntry { - std::uint64_t variant = 0; - std::uint64_t shaderBase = 0; - std::uint32_t pushOffset = 0; - std::vector userData; - std::vector merges; - std::shared_ptr>> ranges; - std::shared_ptr> values; - std::vector> accessible; - ShaderRecompiler::SrtUserDataUse userDataUse; - std::shared_ptr capture; - std::shared_ptr result; - std::shared_ptr words; - std::uint64_t bytes = 0; - std::uint64_t stored = 0; -}; - -constexpr std::size_t HeapWalkWays = 4; - -constexpr std::size_t HeapWalkMemoKeys = 16384; - -constexpr std::size_t HeapWalkSeenKeys = 1u << 16; - -constexpr std::size_t HeapWalkVariantSlots = 4096; - -constexpr std::uint32_t HeapWalkProbeLookups = 64; - -constexpr std::uint32_t HeapWalkSkippedWalks = 1024; - -struct HeapWalkVariantUse { - std::uint64_t variant = 0; - std::uint32_t lookups = 0; - std::uint32_t hits = 0; - std::uint32_t skip = 0; - std::uint32_t skipped = 0; - std::uint32_t repeats = 0; -}; - -std::uint64_t HeapWalkEntryBytes(const HeapWalkEntry& entry); - -std::uint64_t HeapWalkEntryOwnBytes(const HeapWalkEntry& entry); - -std::uint64_t HeapWalkCaptureBytes(const ShaderRecompiler::ResourceCapture& capture); - -std::uint64_t HeapWalkResultBytes(const ShaderRecompiler::RecompileResult& result); - -std::uint64_t HeapWalkWordsBytes(const ShaderRecompiler::HeapStageWords& words); - -std::uint64_t HeapWalkMemoBudget(); - -void NoteHeapWalkMemoEviction(); - -std::uint64_t HeapWalkMemoEvictions(); - -struct HeapWalkMemo { - struct Slot { - std::vector ways; - std::list::iterator age; - }; - std::unordered_map entries; - std::list order; - std::vector seen = std::vector(HeapWalkSeenKeys, 0); - std::unordered_map> pins; - std::vector variants = std::vector(HeapWalkVariantSlots); - std::uint64_t heldBytes = 0; - std::uint64_t stores = 0; - std::uint64_t budget = HeapWalkMemoBudget(); - - bool consult(std::uint64_t variant) { - auto& use = variantUse(variant); - if (use.skip == 0) return true; - --use.skip; - return false; - } - - void noteSkipped(std::uint64_t variant, std::uint64_t key) { - const bool repeated = admit(key); - auto& use = variantUse(variant); - ++use.skipped; - if (repeated) ++use.repeats; - if (use.skipped < HeapWalkProbeLookups) return; - if (use.repeats * 8u >= use.skipped) use.skip = 0; - use.skipped = 0; - use.repeats = 0; - } - - void noteLookup(std::uint64_t variant, bool hit) { - auto& use = variantUse(variant); - ++use.lookups; - if (hit) ++use.hits; - if (use.lookups < HeapWalkProbeLookups) return; - if (use.hits == 0u) use.skip = HeapWalkSkippedWalks; - use.lookups = 0; - use.hits = 0; - } - - bool admit(std::uint64_t key) { - auto& last = seen[(key ^ (key >> 29)) & (HeapWalkSeenKeys - 1u)]; - if (last == key) return true; - last = key; - return false; - } - - std::vector* find(std::uint64_t key) { - const auto found = entries.find(key); - if (found == entries.end()) return nullptr; - order.splice(order.begin(), order, found->second.age); - return &found->second.ways; - } - - void remember(std::uint64_t key, HeapWalkEntry entry) { - auto [found, inserted] = entries.try_emplace(key); - auto& slot = found->second; - if (inserted) { - order.push_front(key); - slot.age = order.begin(); - } else { - order.splice(order.begin(), order, slot.age); - } - if (slot.ways.size() >= HeapWalkWays) { - drop(slot.ways.back()); - slot.ways.pop_back(); - } - charge(entry); - touch(entry); - slot.ways.insert(slot.ways.begin(), std::move(entry)); - while (entries.size() > HeapWalkMemoKeys) evictOldest(); - if (budget != 0 && heldBytes > budget) trim(); - } - - void touch(HeapWalkEntry& entry) { - entry.stored = ++stores; - } - -private: - HeapWalkVariantUse& variantUse(std::uint64_t variant) { - auto& use = variants[(variant ^ (variant >> 31u)) & (HeapWalkVariantSlots - 1u)]; - if (use.variant != variant) use = {variant}; - return use; - } - - template - void pin(const std::shared_ptr& object, TSize size) { - if (object == nullptr) return; - auto& held = pins[object.get()]; - if (held.first++ == 0) { - held.second = size(*object); - heldBytes += held.second; - } - } - - void unpin(const void* object) { - if (object == nullptr) return; - const auto held = pins.find(object); - if (--held->second.first != 0) return; - heldBytes -= held->second.second; - pins.erase(held); - } - - void charge(HeapWalkEntry& entry) { - entry.bytes = HeapWalkEntryOwnBytes(entry); - heldBytes += entry.bytes; - pin(entry.capture, HeapWalkCaptureBytes); - pin(entry.result, HeapWalkResultBytes); - pin(entry.words, HeapWalkWordsBytes); - } - - void drop(const HeapWalkEntry& entry) { - heldBytes -= entry.bytes; - unpin(entry.capture.get()); - unpin(entry.result.get()); - unpin(entry.words.get()); - } - - void evictOldest() { - const auto key = order.back(); - const auto found = entries.find(key); - for (const auto& entry : found->second.ways) drop(entry); - entries.erase(found); - order.pop_back(); - NoteHeapWalkMemoEviction(); - } - - void trim(); -}; - -} - -#endif diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 2bbda54a234c..bbbed0ca6360 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -1070,7 +1070,6 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { pushCursorBytes = Graphics::StagePushOffset(pushCursorBytes, program.binary.stage, localDevice->GraphicsPipelineLibraries()); pushOffsets[i] = pushCursorBytes; if (drawHit) { - programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); ringWords(i); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp index 1d903b4a961a..64b5f2c3e04e 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "HeapCacheSwitch.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp" #include #include @@ -22,17 +23,17 @@ bool DrawRecipeRecord::Expired() const { } bool Driver::drawEntries() { - static const bool entries = std::getenv("APS5_NO_DRAW_SRT_ENTRIES") == nullptr && !stampValidate(); + static const bool entries = std::getenv("APS5_NO_DRAW_SRT_ENTRIES") == nullptr && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::DrawSrtEntries) && !stampValidate(); return entries; } bool Driver::drawDataHits() { - static const bool hits = std::getenv("APS5_NO_DRAW_DATA_HITS") == nullptr; + static const bool hits = std::getenv("APS5_NO_DRAW_DATA_HITS") == nullptr && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::DrawDataHits); return hits; } bool Driver::drawStageDataHits() { - static const bool hits = std::getenv("APS5_NO_DRAW_STAGE_DATA_HITS") == nullptr && !stampValidate(); + static const bool hits = std::getenv("APS5_NO_DRAW_STAGE_DATA_HITS") == nullptr && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::DrawStageDataHits) && !stampValidate(); return hits; } @@ -47,7 +48,7 @@ bool Driver::verifyDrawEntries() { } bool Driver::registerKeyEnabled() { - static const bool registerKey = std::getenv("APS5_NO_DRAW_KEY") == nullptr; + static const bool registerKey = std::getenv("APS5_NO_DRAW_KEY") == nullptr && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::DrawKey); return registerKey; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index a88c7fe95f43..8eee214e950b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -1,5 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" -#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp" +#include "HeapCacheSwitch.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -31,7 +32,6 @@ namespace { constexpr std::size_t ThreadCacheLimit = 65536u; constexpr std::uint64_t WalkPageBytes = 0x1000u; constexpr std::uint64_t WordBytes = sizeof(std::uint32_t); -constexpr std::uint64_t DefaultWalkMemoMiB = 256u; std::atomic& heapStages() { static std::atomic count{0}; @@ -286,124 +286,6 @@ bool SampleHeapStageVerify() { return calls++ % every == 0; } -namespace { - -template -std::uint64_t vectorBytes(const std::vector& values) { - return static_cast(values.capacity()) * sizeof(TValue); -} - -std::uint64_t vectorBytes(const std::vector& values) { - return static_cast(values.capacity() + 7u) / 8u; -} - -// ElementFlags keeps up to 64 flags inline; larger sets spill every flag into a std::vector. -std::uint64_t vectorBytes(const ShaderRecompiler::ElementFlags& flags) { - return flags.size() > 64u ? (static_cast(flags.size()) + 7u) / 8u : 0u; -} - -template -std::uint64_t sharedBytes(const ShaderRecompiler::SharedValues& values) { - return static_cast(values.size()) * sizeof(TValue); -} - -std::uint64_t descriptorBindingBytes(const ShaderRecompiler::DescriptorBinding& binding) { - return vectorBytes(binding.guestDescriptor) + vectorBytes(binding.samplerDepthCompare) + vectorBytes(binding.imageWritten) + - vectorBytes(binding.imageDepthCompare) + vectorBytes(binding.imageAtomic) + vectorBytes(binding.imageAtomic64) + - vectorBytes(binding.imageShapes) + vectorBytes(binding.bufferAtomic) + vectorBytes(binding.bufferWritten) + - vectorBytes(binding.samplerUnnormalized) + vectorBytes(binding.samplerIntegerBorder) + vectorBytes(binding.samplerCoordinatesIgnored) + - vectorBytes(binding.samplerEmbedded) + vectorBytes(binding.samplerEmbeddedWords) + - vectorBytes(binding.imageUnnormalized) + vectorBytes(binding.imageUnnormalizedBaseLevel) + vectorBytes(binding.imageSamplers) + - vectorBytes(binding.bufferRead) + vectorBytes(binding.bufferExtent); -} - -} - -std::uint64_t HeapWalkResultBytes(const ShaderRecompiler::RecompileResult& result) { - auto bytes = sizeof(ShaderRecompiler::RecompileResult) + vectorBytes(result.vertexInputPatches) + vectorBytes(result.runtimeImageResources) + - vectorBytes(result.vertexInputs) + vectorBytes(result.parameterExports) + vectorBytes(result.fragmentParameters) + - vectorBytes(result.stencilReferences) + vectorBytes(result.specialization) + vectorBytes(result.heapSlotWords) + - vectorBytes(result.bindings) + vectorBytes(result.pushConstants) + vectorBytes(result.vertexAttributes) + - vectorBytes(result.imageTablePoison) + vectorBytes(result.imageTableRanges) + vectorBytes(result.imageTableReadRanges) + - vectorBytes(result.heapUserWords) + vectorBytes(result.shaderDataUserWords); - if (result.meshBarycentrics.has_value()) bytes += vectorBytes(result.meshBarycentrics->parameters); - for (const auto& binding : result.bindings) bytes += descriptorBindingBytes(binding); - for (const auto& ranges : result.imageTableReadRanges) bytes += vectorBytes(ranges); - return bytes; -} - -std::uint64_t HeapWalkCaptureBytes(const ShaderRecompiler::ResourceCapture& capture) { - const auto& snapshot = capture.snapshot; - auto bytes = sizeof(ShaderRecompiler::ResourceCapture) + vectorBytes(snapshot.buffers) + vectorBytes(snapshot.images) + - vectorBytes(snapshot.samplers) + vectorBytes(snapshot.flattenedSrt) + vectorBytes(snapshot.userData) + - vectorBytes(snapshot.srtPoison) + vectorBytes(snapshot.tables.tables) + vectorBytes(snapshot.tables.ranges) + - vectorBytes(capture.readTrace.leaves) + vectorBytes(capture.readTrace.otherReads) + vectorBytes(capture.userDataUse.reads); - for (const auto& column : snapshot.tables.tables) - bytes += sharedBytes(column.codes) + sharedBytes(column.words) + sharedBytes(column.readRanges); - return bytes; -} - -std::uint64_t HeapWalkWordsBytes(const ShaderRecompiler::HeapStageWords& words) { - auto bytes = sizeof(ShaderRecompiler::HeapStageWords) + vectorBytes(words.userData) + vectorBytes(words.flattenedSrt) + - vectorBytes(words.vertexAttributes) + vectorBytes(words.bindings); - for (const auto& binding : words.bindings) bytes += vectorBytes(binding); - return bytes; -} - -std::uint64_t HeapWalkEntryOwnBytes(const HeapWalkEntry& entry) { - return sizeof(HeapWalkEntry) + vectorBytes(entry.userData) + (entry.ranges != nullptr ? vectorBytes(*entry.ranges) : 0u) + (entry.values != nullptr ? vectorBytes(*entry.values) : 0u) + - vectorBytes(entry.accessible) + vectorBytes(entry.userDataUse.reads) + vectorBytes(entry.merges); -} - -std::uint64_t HeapWalkEntryBytes(const HeapWalkEntry& entry) { - auto bytes = HeapWalkEntryOwnBytes(entry); - if (entry.capture != nullptr) bytes += HeapWalkCaptureBytes(*entry.capture); - if (entry.result != nullptr) bytes += HeapWalkResultBytes(*entry.result); - if (entry.words != nullptr) bytes += HeapWalkWordsBytes(*entry.words); - return bytes; -} - -namespace { - -std::atomic& heapWalkMemoEvictions() { - static std::atomic evictions{0}; - return evictions; -} - -} - -void NoteHeapWalkMemoEviction() { - heapWalkMemoEvictions().fetch_add(1, std::memory_order_relaxed); -} - -std::uint64_t HeapWalkMemoEvictions() { - return heapWalkMemoEvictions().load(std::memory_order_relaxed); -} - -std::uint64_t HeapWalkMemoBudget() { - static const std::uint64_t budget = [] { - const char* value = std::getenv("APS5_HEAP_WALK_MEMO_MB"); - const std::uint64_t megabytes = value == nullptr || *value == '\0' ? DefaultWalkMemoMiB : std::strtoull(value, nullptr, 10); - return megabytes << 20u; - }(); - return budget; -} - -void HeapWalkMemo::trim() { - const auto target = budget / 4u * 3u; - while (heldBytes > target && order.size() > 1u) evictOldest(); -} - -namespace { - -HeapWalkMemo& heapWalkMemo() { - struct WalkMemoStorage {}; - auto& memo = HostThreadLocal(); - return memo; -} - -} - void AppendWalkRead(std::vector>& runs, std::uint64_t address) { if (!runs.empty() && address >= runs.back().first && address <= runs.back().second) { runs.back().second = std::max(runs.back().second, address + WordBytes); @@ -431,12 +313,10 @@ using AddressRanges = std::vector>; struct WalkReads { AddressRanges runs; std::uint64_t page = ~std::uint64_t{0}; - AddressRanges accessible; bool failed = false; void Reset() { runs.clear(); - accessible.clear(); failed = false; page = ~std::uint64_t{0}; } @@ -461,8 +341,7 @@ bool readWalkWord(void* context, std::uint64_t address, std::uint32_t* value) { bool walkAccessible(void* context, std::uint64_t address, std::uint64_t bytes) { auto& reads = *static_cast(context); const bool accessible = GuestMemory::Accessible(reinterpret_cast(address), static_cast(bytes)); - if (accessible) reads.accessible.emplace_back(address, bytes); - else reads.failed = true; + if (!accessible) reads.failed = true; return accessible; } @@ -487,93 +366,6 @@ void guardRanges(const AddressRanges& ranges) { for (const auto& [begin, end] : ranges) GuestMemory::GuardRead(begin, static_cast(end - begin)); } -std::span targetMerges(const ShaderRecompiler::PreparedShaderInvocation& invocation) { - const auto& pixel = invocation.Request().context.pixel; - return pixel ? std::span(pixel->targetMerges) : std::span{}; -} - -std::uint64_t walkMemoKey(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, - std::uint64_t shaderBase) { - auto key = (invocation.VariantId() * 0x9e3779b97f4a7c15ull ^ shaderBase) + invocation.Request().layout.pushConstantOffsetBytes; - for (const auto word : userData) key = (key ^ word) * 0x100000001b3ull; - for (const auto& merge : targetMerges(invocation)) - for (const auto word : merge.descriptor) key = (key ^ word) * 0x100000001b3ull; - return key; -} - -bool sameWalkInputs(const HeapWalkEntry& entry, const ShaderRecompiler::PreparedShaderInvocation& invocation, - std::span userData, std::uint64_t shaderBase) { - const bool sameStage = entry.variant == invocation.VariantId() && entry.shaderBase == shaderBase && - entry.pushOffset == invocation.Request().layout.pushConstantOffsetBytes; - if (!sameStage || !std::equal(entry.userData.begin(), entry.userData.end(), userData.begin(), userData.end())) return false; - if (!std::ranges::equal(entry.merges, targetMerges(invocation))) return false; - std::size_t cursor = 0; - for (const auto& [begin, end] : *entry.ranges) { - const auto count = static_cast((end - begin) / WordBytes); - if (GuestMemory::CompareMapped(begin, std::as_bytes(std::span(entry.values->data() + cursor, count))) != GuestMemory::Compare::Equal) - return false; - cursor += count; - } - for (const auto& [address, bytes] : entry.accessible) { - if (!GuestMemory::Accessible(reinterpret_cast(address), static_cast(bytes))) return false; - } - return true; -} - -void noteMemoBytes(const HeapWalkMemo& memo, std::uint64_t heldBefore) { - Graphics::NoteHeapWalkMemoBytes(static_cast(memo.heldBytes) - static_cast(heldBefore)); -} - -void rememberWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderInvocation& invocation, - std::span userData, std::uint64_t shaderBase, const std::shared_ptr& ranges, - const std::shared_ptr>& values, const AddressRanges& accessible, - const std::shared_ptr& capture, - const std::shared_ptr& result, std::shared_ptr words) { - HeapWalkEntry entry; - entry.variant = invocation.VariantId(); - entry.pushOffset = invocation.Request().layout.pushConstantOffsetBytes; - entry.shaderBase = shaderBase; - entry.userData.assign(userData.begin(), userData.end()); - const auto merges = targetMerges(invocation); - entry.merges.assign(merges.begin(), merges.end()); - entry.ranges = ranges; - entry.values = values; - entry.accessible = accessible; - entry.userDataUse = capture->userDataUse; - entry.capture = capture; - entry.result = result; - entry.words = std::move(words); - auto& memo = heapWalkMemo(); - const auto heldBefore = memo.heldBytes; - memo.remember(memoKey, std::move(entry)); - noteMemoBytes(memo, heldBefore); -} - -bool adoptWalk(std::uint64_t memoKey, const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, - std::uint64_t shaderBase, const Graphics::Recorder::WriteRanges* before, std::uint64_t generation, - HeapStageMaterialized& adopted, bool& memoKnown) { - auto& memo = heapWalkMemo(); - const auto heldBefore = memo.heldBytes; - auto* found = memo.find(memoKey); - noteMemoBytes(memo, heldBefore); - memoKnown = found != nullptr; - for (std::size_t way = 0; found != nullptr && way < found->size(); ++way) { - auto& entry = (*found)[way]; - if (!sameWalkInputs(entry, invocation, userData, shaderBase)) continue; - if (!rangesSettled(*entry.ranges, before, generation)) break; - memo.touch(entry); - guardRanges(*entry.ranges); - adopted.words = entry.words; - adopted.reads = {entry.ranges, entry.values, entry.userDataUse, entry.capture, true}; - adopted.result = entry.result; - if (way != 0) - std::rotate(found->begin(), found->begin() + static_cast(way), - found->begin() + static_cast(way) + 1); - return true; - } - return false; -} - std::shared_ptr captureWalk(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase, WalkReads& reads) { @@ -655,21 +447,6 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade snapshotCost.Stop(); const auto generation = GuestMemory::StableTrackerGeneration(); const auto variant = invocation.VariantId(); - const bool memoAllowed = !invocation.Request().context.vertex.has_value(); - const bool memoOn = memoAllowed && heapWalkMemo().consult(variant); - std::uint64_t memoKey = 0; - bool memoKnown = false; - if (memoAllowed && !memoOn) heapWalkMemo().noteSkipped(variant, walkMemoKey(invocation, userData, shaderBase)); - - Graphics::HeapCostScope memoCost(Graphics::HeapCost::WalkMemo); - if (memoOn) { - memoKey = walkMemoKey(invocation, userData, shaderBase); - HeapStageMaterialized adopted; - const bool hit = adoptWalk(memoKey, invocation, userData, shaderBase, before.get(), generation, adopted, memoKnown); - heapWalkMemo().noteLookup(variant, hit); - if (hit) return adopted; - } - memoCost.Stop(); Graphics::HeapCostScope walkCost(Graphics::HeapCost::Walk); std::shared_ptr capture; @@ -699,9 +476,6 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade auto shared = complete ? recycledValues(values) : nullptr; auto sharedRanges = complete ? recycledRanges(ranges) : nullptr; if (complete) materialized.reads = {sharedRanges, shared, capture->userDataUse, capture, true}; - Graphics::HeapCostScope insertCost(Graphics::HeapCost::MemoInsert); - if (memoOn && complete && (memoKnown || heapWalkMemo().admit(memoKey))) - rememberWalk(memoKey, invocation, userData, shaderBase, sharedRanges, shared, reads.accessible, capture, result, words); materialized.result = std::move(result); materialized.words = std::move(words); return materialized; @@ -785,6 +559,7 @@ void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const if (const auto* what = resultDifference(direct, expected, index)) { counts.differ.fetch_add(1, std::memory_order_relaxed); reportHeapMismatch("heap stage vs full capture", what, expected, index); + throw std::runtime_error(std::string("APS5_VERIFY_GPU_HEAP: a heap stage differs from its full capture in its ") + what); } } @@ -797,6 +572,7 @@ void VerifyHeapAccessor(const Graphics::CompiledShader& stage) { if (Graphics::DrawGuestWords(stage, stage.program->bindings[index]) == patched->bindings[index].guestDescriptor) continue; counts.accessorDiffer.fetch_add(1, std::memory_order_relaxed); reportHeapMismatch("accessor vs patched result", "binding words", *patched, index); + throw std::runtime_error("APS5_VERIFY_GPU_HEAP: a heap stage's binding words differ from its patched result"); } const auto& attributes = Graphics::DrawVertexAttributes(stage); bool sameAttributes = attributes.size() == patched->vertexAttributes.size(); @@ -806,6 +582,7 @@ void VerifyHeapAccessor(const Graphics::CompiledShader& stage) { if (!sameAttributes) { counts.accessorDiffer.fetch_add(1, std::memory_order_relaxed); reportHeapMismatch("accessor vs patched result", "vertex attributes", *patched, 0); + throw std::runtime_error("APS5_VERIFY_GPU_HEAP: a heap stage's vertex attributes differ from its patched result"); } } @@ -820,6 +597,7 @@ void VerifyRingWords(const ShaderRecompiler::RecompileResult& kept, const Shader if (const auto* what = resultDifference(*reused, *expected, index)) { counts.ringDiffer.fetch_add(1, std::memory_order_relaxed); reportHeapMismatch("ring hit vs fresh build", what, *expected, index); + throw std::runtime_error(std::string("a ring hit's rebuilt words differ from a fresh build in its ") + what); } } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index ff3a79f6e18a..0e832f0a8af8 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" +#include "HeapCacheSwitch.hpp" #include "prx/libSceAgcDriver/Execution/include/FrameDumpIo.hpp" #include "prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" @@ -5103,7 +5104,7 @@ namespace { // which needs the texture caches: without them every lookup makes a fresh object, so a hit could // never validate and would only upload everything twice. bool ResourceCacheEnabled() { - static const bool noResourceCache = std::getenv("APS5_NO_RESOURCE_CACHE") != nullptr; + static const bool noResourceCache = std::getenv("APS5_NO_RESOURCE_CACHE") != nullptr || ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::ResourceCache); static const bool noTextureCache = std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr; return !noResourceCache && !noTextureCache; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index ca2d62a61b50..916035808adc 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -56,6 +56,7 @@ class BindlessHeap { void WritePixelLdsBuffer(VkDeviceAddress address, VkDeviceSize bytes); void WriteMeshWindowBuffer(VkDeviceAddress address, VkDeviceSize bytes); std::pair DataLocation(VkDeviceAddress address) const; + std::span DataWords(VkDeviceAddress address, std::size_t words) const; std::uint32_t EmbeddedSamplerCount() const; std::optional TextureSlot(std::uint32_t kind, Texture* texture, VkImageView view, VkImageLayout layout); @@ -106,6 +107,17 @@ class BindlessHeap { bool acquired; }; std::optional KeepOrAllocate(const SpanScope& held, std::size_t words, SpanMark& mark, bool same); + struct TableMark { + std::uint32_t block = 0; + std::uint32_t offset = 0; + std::uint32_t sizeClass = 0; + VkDeviceAddress address = 0; + }; + std::optional AllocateTable(const SpanScope& held, std::size_t words, TableMark& mark); + void RetireTable(const SpanScope& held, TableMark& mark); + void NoteTableKept(const SpanScope& held); + static constexpr std::size_t TableBlockBytes = 1u << 20u; + static constexpr std::uint32_t TableClasses = 16u; static constexpr std::uint32_t SamplerKind = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Samplers); void Submitted(Recorder& recorder, std::uint64_t serial); @@ -152,6 +164,25 @@ class BindlessHeap { bool open = false; }; std::vector poolBlocks; + struct TableBlock { + std::unique_ptr buffer; + std::byte* data = nullptr; + VkDeviceAddress address = 0; + std::size_t bytes = 0; + std::size_t cursor = 0; + }; + std::vector tableBlocks; + std::array>, TableClasses> tableFree; + struct RetiredTable { + TableMark mark; + Recorder* recorder = nullptr; + std::uint64_t serial = 0; + bool submitted = false; + }; + std::deque retiredTables; + std::size_t tableShared = 0; + std::size_t makeTableBlockLocked(std::size_t bytes); + void reclaimTablesLocked(); std::size_t poolCurrent = ~std::size_t{0}; std::uint32_t poolAlignment = 256; std::size_t poolBatchBytes = 0; @@ -314,20 +345,17 @@ enum class HeapCost : std::uint8_t { StagePrepare, HeapStageCall, StageFinish, - WalkMemo, Walk, Materialize, TemplateFind, TemplateBuild, Slots, StageData, - MemoInsert, Guards, Count }; bool HeapCostTimed(); -void NoteHeapWalkMemoBytes(std::int64_t delta); void NoteHeapCost(HeapCost cost, std::uint64_t nanoseconds); class HeapCostScope { public: diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index a687a59e9891..955c0cc5f7f4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -397,22 +397,22 @@ class ShaderResources { void PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const; void writePushedData(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const; void writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const; - bool constantBufferRanges(std::uint32_t dataStage) const; - struct PushedRanges { - bool built = false; - bool constant = false; - std::vector ranges; - std::vector records; - std::vector emptyRecords; - }; - mutable std::array pushedRanges; - struct RootRoles { + void writeDataRoots(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten, bool cached) const; + struct PushImage { + std::array bytes{}; + std::uint64_t mask = 0; + std::vector placements; std::array programs{}; - std::size_t count = std::numeric_limits::max(); - bool table = false; - bool fault = false; + std::size_t count = 0; + struct Stage { + std::uint64_t version = ~std::uint64_t{0}; + std::array addresses{}; + bool live = true; + }; + std::array stages{}; + bool valid = false; }; - mutable RootRoles rootRoles; + mutable PushImage pushImage; // Whether RefreshData would record anything for `shader` (the per-word compare; verification). bool DataWordsDiffer(const CompiledShader& shader) const; std::size_t BindingCount() const { return bindings.size(); } @@ -752,7 +752,6 @@ class ShaderResources { mutable std::array heapOffsets{}; void writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader); struct HeapStageState { - std::uint64_t inertProgram = 0; std::uint64_t slotSerial = 0; std::uint64_t dataOrigin = 0; std::uint64_t pushedUserWords = 0; @@ -762,6 +761,14 @@ class ShaderResources { std::uint32_t pushedPlaced = 0; std::uint32_t userWords = 0; bool splitUser = false; + bool keyTaken = false; + std::uint64_t pushVersion = 0; + bool mapBuilt = false; + std::uint32_t mapTouched = 0; + std::vector mapSlots; + std::vector mapGenerations; + std::vector mapSamplers; + std::vector mapSamplerGenerations; std::vector owned; std::vector key; struct KindRange { @@ -777,7 +784,7 @@ class ShaderResources { std::vector> dataPatches; struct KeptSpan { std::vector words; - BindlessHeap::SpanMark mark; + BindlessHeap::TableMark table; }; KeptSpan data, flat, map, user; std::vector dataInput; @@ -789,7 +796,10 @@ class ShaderResources { } }; std::array heapStages; - std::uint64_t heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words, std::uint64_t pushed = 0); + std::uint64_t heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words); + std::uint64_t heapTable(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words); + bool keptTable(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept); + void retireHeapTables() noexcept; bool ownsHeapBinding(const Binding& binding, VkShaderStageFlags stageBit) const; VkImageView heapPlaceholderView(std::uint32_t kind) const; VkImageView heapSampledView(std::size_t index) const; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 829a58e8b1c7..96ed66c60140 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -35,26 +35,6 @@ namespace AgcDriver::Graphics { -namespace { - -std::atomic& walkMemoHeld() { - static std::atomic held{0}; - return held; -} - -std::atomic& walkMemoPeak() { - static std::atomic peak{0}; - return peak; -} - -} - -void NoteHeapWalkMemoBytes(std::int64_t delta) { - if (delta == 0) return; - const auto now = walkMemoHeld().fetch_add(delta, std::memory_order_relaxed) + delta; - auto peak = walkMemoPeak().load(std::memory_order_relaxed); - while (now > peak && !walkMemoPeak().compare_exchange_weak(peak, now, std::memory_order_relaxed)) {} -} namespace { @@ -798,6 +778,86 @@ std::optional BindlessHeap::KeepOrAllocate(const SpanSco return allocateLocked(words, mark); } +std::size_t BindlessHeap::makeTableBlockLocked(std::size_t bytes) { + constexpr VkBufferUsageFlags usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + constexpr VkMemoryPropertyFlags deviceVisible = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + std::unique_ptr buffer; + try { + buffer = std::make_unique(context, bytes, usage, deviceVisible); + } catch (const std::exception&) { + } + if (buffer == nullptr) buffer = std::make_unique(context, bytes, usage); + const auto vacant = std::find_if(tableBlocks.begin(), tableBlocks.end(), [](const TableBlock& block) { return block.buffer == nullptr; }); + auto& block = vacant != tableBlocks.end() ? *vacant : tableBlocks.emplace_back(); + block.data = buffer->Bytes().data(); + block.address = buffer->DeviceAddress(); + block.buffer = std::move(buffer); + block.bytes = bytes; + block.cursor = 0; + return static_cast(&block - tableBlocks.data()); +} + +std::optional BindlessHeap::AllocateTable(const SpanScope& held, std::size_t words, TableMark& mark) { + Require(&held.heap == this, "a heap table was allocated under another heap's lock"); + const auto bytes = std::max(words, 1u) * sizeof(std::uint32_t); + std::uint32_t sizeClass = 0; + while (sizeClass < TableClasses && (static_cast(poolAlignment) << sizeClass) < bytes) ++sizeClass; + const bool dedicated = sizeClass == TableClasses || (static_cast(poolAlignment) << sizeClass) > TableBlockBytes; + std::pair place{}; + std::size_t placedBytes = 0; + if (dedicated) { + placedBytes = static_cast(alignUp(bytes, poolAlignment)); + place = {static_cast(makeTableBlockLocked(placedBytes) + 1u), 0u}; + sizeClass = TableClasses; + } else { + placedBytes = static_cast(poolAlignment) << sizeClass; + auto& free = tableFree[sizeClass]; + if (!free.empty()) { + place = free.back(); + free.pop_back(); + } else { + if (tableShared == 0u || tableBlocks[tableShared - 1u].cursor + placedBytes > tableBlocks[tableShared - 1u].bytes) tableShared = makeTableBlockLocked(TableBlockBytes) + 1u; + auto& block = tableBlocks[tableShared - 1u]; + place = {static_cast(tableShared), static_cast(block.cursor)}; + block.cursor += placedBytes; + } + } + const auto& block = tableBlocks[place.first - 1u]; + mark = {place.first, place.second, sizeClass, block.address + place.second}; + ++counts.spansWritten; + counts.poolBytes += placedBytes; + return DataSpan{place.second, std::span(reinterpret_cast(block.data + place.second), words), mark.address}; +} + +void BindlessHeap::RetireTable(const SpanScope& held, TableMark& mark) { + Require(&held.heap == this, "a heap table was retired under another heap's lock"); + if (mark.address == 0u) return; + retiredTables.push_back({mark, nullptr, 0u, false}); + mark = {}; +} + +void BindlessHeap::NoteTableKept(const SpanScope& held) { + Require(&held.heap == this, "a heap table was kept under another heap's lock"); + ++counts.spansKept; +} + +void BindlessHeap::reclaimTablesLocked() { + while (!retiredTables.empty()) { + const auto& front = retiredTables.front(); + if (!front.submitted || (front.serial != 0u && !front.recorder->WaitSerialFor(front.serial, 0u))) return; + if (front.mark.sizeClass == TableClasses) { + auto& block = tableBlocks[front.mark.block - 1u]; + block.buffer.reset(); + block.data = nullptr; + block.address = 0; + block.bytes = 0; + } else { + tableFree[front.mark.sizeClass].emplace_back(front.mark.block, front.mark.offset); + } + retiredTables.pop_front(); + } +} + BindlessHeap::DataSpan BindlessHeap::allocateLocked(std::size_t words, SpanMark& mark) { const auto bytes = alignUp(std::max(words, 1u) * sizeof(std::uint32_t), SpanAlignment); if (poolCurrent >= poolBlocks.size() || alignUp(poolBlocks[poolCurrent].cursor, poolAlignment) + bytes > poolBlocks[poolCurrent].bytes) poolCurrent = takePoolBlockLocked(bytes); @@ -895,11 +955,26 @@ bool BindlessHeap::TakeSlotPressure() { return true; } +std::span BindlessHeap::DataWords(VkDeviceAddress address, std::size_t words) const { + SpanScope scope(*this); + const auto bytes = words * sizeof(std::uint32_t); + for (const auto& block : poolBlocks) { + if (block.buffer != nullptr && address >= block.address && address + bytes <= block.address + block.bytes) return {reinterpret_cast(block.data + (address - block.address)), words}; + } + for (const auto& block : tableBlocks) { + if (block.buffer != nullptr && address >= block.address && address + bytes <= block.address + block.bytes) return {reinterpret_cast(block.data + (address - block.address)), words}; + } + throw std::runtime_error("AGC bindless heap: the words read lie outside every data block"); +} + std::pair BindlessHeap::DataLocation(VkDeviceAddress address) const { SpanScope scope(*this); for (const auto& block : poolBlocks) { if (block.buffer != nullptr && address >= block.address && address < block.address + block.bytes) return {block.buffer->Handle(), address - block.address}; } + for (const auto& block : tableBlocks) { + if (block.buffer != nullptr && address >= block.address && address < block.address + block.bytes) return {block.buffer->Handle(), address - block.address}; + } throw std::runtime_error("AGC bindless heap: shader data lies outside every data pool block"); } @@ -1315,8 +1390,7 @@ unsigned long long printed(std::uint64_t value) { std::array, static_cast(HeapCost::Count)> heapCostNs{}; std::array, static_cast(HeapCost::Count)> heapCostCalls{}; constexpr std::array(HeapCost::Count)> HeapCostNames{ - "stage prepare", "heap stage call", "stage finish", "walk memo", "walk", "materialize", "template find", - "template build", "slots", "stage data", "memo insert", "guards"}; + "stage prepare", "heap stage call", "stage finish", "walk", "materialize", "template find", "template build", "slots", "stage data", "guards"}; void reportHeapStatistics() { if (!pipelineStats()) return; @@ -1342,9 +1416,7 @@ void reportHeapStatistics() { costs += cost; } if (HeapCostTimed()) { - const auto held = static_cast(std::max(walkMemoHeld().load(std::memory_order_relaxed), 0)) / 1048576.0; - const auto peak = static_cast(walkMemoPeak().load(std::memory_order_relaxed)) / 1048576.0; - std::fprintf(stderr, "[gpu-heap] cost (10 s):%s; walk memos hold %.1f MiB on all threads (peak %.1f MiB)\n", costs.c_str(), held, peak); + std::fprintf(stderr, "[gpu-heap] cost (10 s):%s\n", costs.c_str()); } const auto heapDraws = takeCount(heapRecords[heapRecordIndex(false, true)]); const auto plainDraws = takeCount(heapRecords[heapRecordIndex(false, false)]); @@ -1622,6 +1694,12 @@ void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { block.serial = serial; block.open = index == poolCurrent; } + for (auto entry = retiredTables.rbegin(); entry != retiredTables.rend() && !entry->submitted; ++entry) { + entry->recorder = &recorder; + entry->serial = serial; + entry->submitted = true; + } + reclaimTablesLocked(); trimPoolLocked(); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index c8465de41773..19b899446ea1 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "HeapCacheSwitch.hpp" #include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" @@ -1119,7 +1120,7 @@ void countCache(std::uint64_t DrawProfile::*counter) { // every draw. bool ValidationKey(const Context& context, std::span shaders, const State& state, std::vector& key) { using Stage = ShaderRecompiler::ShaderStage; - static const bool disabled = std::getenv("APS5_NO_VALIDATE_CACHE") != nullptr; + static const bool disabled = std::getenv("APS5_NO_VALIDATE_CACHE") != nullptr || ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::ValidateCache); const auto add = [&](auto value) { key.push_back(static_cast(value)); }; bool keyed = !disabled; if (keyed) { @@ -1283,7 +1284,7 @@ std::uint32_t CachedFragmentOutputs(const Context& context, std::spanPipelineVariantId() != 0; }); @@ -3277,7 +3278,7 @@ void keepHeldSpace(PreparedDraw& prepared) { } bool ShapeMemoEnabled() { - static const bool enabled = std::getenv("APS5_NO_SHAPE_MEMO") == nullptr; + static const bool enabled = std::getenv("APS5_NO_SHAPE_MEMO") == nullptr && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::ShapeMemo); return enabled; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 6f18d7f8f5ab..c0e0b34c3cf7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" +#include "HeapCacheSwitch.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" @@ -5788,8 +5789,12 @@ VkBuffer ShaderResources::shaderDataBuffer(const CompiledShader& shader) const { void ShaderResources::forgetShaderDataWords(const CompiledShader& shader) { if (HeapShader(shader)) { auto& stageState = heapStages[HeapStageIndex(shader.stage)]; - stageState.data.mark.entry = 0; - stageState.user.mark.entry = 0; + ++stageState.pushVersion; + if (stageState.data.table.address != 0u) { + auto& heap = BindlessHeap::For(context); + BindlessHeap::SpanScope spans(heap); + heap.RetireTable(spans, stageState.data.table); + } stageState.dataInput.clear(); stageState.dataOrigin = 0; } @@ -6887,6 +6892,7 @@ std::vector ShaderResources::PresyncSurfaces() const { } ShaderResources::~ShaderResources() { + retireHeapTables(); release(); } @@ -7510,47 +7516,24 @@ void ShaderResources::bufferRanges(std::uint32_t dataStage, const std::vector= addressedElements.size()) return true; - return std::all_of(addressedElements[dataStage].begin(), addressedElements[dataStage].end(), [&](std::size_t index) { - const auto& allocation = allocations[index]; - const bool owned = !allocation.guest && allocation.buffer != nullptr && allocation.role != ShaderRecompiler::DescriptorRole::GuestBuffers && allocation.role != ShaderRecompiler::DescriptorRole::BdaPagetable && allocation.role != ShaderRecompiler::DescriptorRole::FaultBuffer; - return owned || (index < resolvedAddresses.size() && resolvedAddresses[index].address != 0); - }); -} - std::pair ShaderResources::shaderDataLocation(const CompiledShader& shader, const DrawBindings* rewritten) const { if (!heapStage || !HeapShader(shader)) return {shaderDataBuffer(shader), 0}; const auto& offsets = rewritten != nullptr && rewritten->addressOffsets ? rewritten->heapOffsets : heapOffsets; return BindlessHeap::For(context).DataLocation(offsets[DataOffsetIndex(HeapStageIndex(shader.stage), ShaderRecompiler::RuntimeAbi::Binding::ShaderData)]); } -void ShaderResources::PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const { +void ShaderResources::writeDataRoots(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten, bool cached) const { namespace Abi = ShaderRecompiler::RuntimeAbi; if (!heapStage) return; const bool addressed = rewritten != nullptr && rewritten->addressOffsets; const auto& offsets = addressed ? rewritten->heapOffsets : heapOffsets; VkDeviceAddress table = 0; VkDeviceAddress fault = 0; - const bool sameStages = rootRoles.count == shaders.size() && std::equal(shaders.begin(), shaders.end(), rootRoles.programs.begin(), [](const CompiledShader& shader, const ShaderRecompiler::RecompileResult* program) { return shader.program == program; }); - if (!sameStages) { - const auto binds = [&](ShaderRecompiler::DescriptorRole role) { - return std::any_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [&](const auto& binding) { return binding.role == role; }); }); - }; - rootRoles.table = binds(ShaderRecompiler::DescriptorRole::BdaPagetable); - rootRoles.fault = binds(ShaderRecompiler::DescriptorRole::FaultBuffer); - rootRoles.count = shaders.size() <= rootRoles.programs.size() ? shaders.size() : std::numeric_limits::max(); - for (std::size_t index = 0; index < shaders.size() && index < rootRoles.programs.size(); ++index) rootRoles.programs[index] = shaders[index].program; - } - static const bool verifyRoles = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; - if (verifyRoles && sameStages) { - const auto binds = [&](ShaderRecompiler::DescriptorRole role) { - return std::any_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [&](const auto& binding) { return binding.role == role; }); }); - }; - if (binds(ShaderRecompiler::DescriptorRole::BdaPagetable) != rootRoles.table || binds(ShaderRecompiler::DescriptorRole::FaultBuffer) != rootRoles.fault) throw std::runtime_error("AGC graphics: the BDA roots kept for a GPU heap draw's stages differ from their bindings"); - } - const bool tableBound = rootRoles.table; - const bool faultBound = rootRoles.fault; + const auto binds = [&](ShaderRecompiler::DescriptorRole role) { + return std::any_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [&](const auto& binding) { return binding.role == role; }); }); + }; + const bool tableBound = binds(ShaderRecompiler::DescriptorRole::BdaPagetable); + const bool faultBound = binds(ShaderRecompiler::DescriptorRole::FaultBuffer); if (bda != nullptr && (tableBound || faultBound)) { if (tableBound) table = bda->TableAddress(); if (faultBound) fault = bda->FaultAddress(); @@ -7569,6 +7552,41 @@ void ShaderResources::PatchDataAddresses(std::spandataAddressPush; + for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { + const auto kind = static_cast(item); + const bool global = kind == Abi::RootItem::PagetableAddress || kind == Abi::RootItem::FaultAddress || kind == Abi::RootItem::GdsAddress; + if (global || rootedStage) own(placement.items[item], Abi::RootAddressItem(kind) ? 2u : 1u); + } + if (!rootedStage) continue; + own(placement.pushed.count != 0u ? placement.pushed.base : Abi::NoPushPosition, placement.pushed.count); + for (std::uint32_t buffer = 0; buffer < std::min(placement.pushedBuffers, Abi::PushedBufferLimit); ++buffer) own(placement.bufferRoots[buffer], Abi::PushedBufferWords); + own(placement.bufferOverflow, 2u); + } + } + if (!image.valid) cached = false; + } + const auto target = cached ? std::span(image.bytes) : bytes; bool rooted = false; for (std::size_t index = 0; index < shaders.size(); ++index) { const auto& shader = shaders[index]; @@ -7576,8 +7594,8 @@ void ShaderResources::PatchDataAddresses(std::span(address)); @@ -7587,21 +7605,65 @@ void ShaderResources::PatchDataAddresses(std::spandataAddressPush) continue; - const auto stage = HeapStageIndex(shader.stage); - putAddress(Abi::RootItem::ShaderData, offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); - putAddress(Abi::RootItem::UserData, offsets[DataOffsetIndex(stage, Abi::Binding::UserData)]); - putAddress(Abi::RootItem::SrtAddress, offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)]); - putAddress(Abi::RootItem::TableMap, heapTableMapSet[stage] ? heapTableMaps[stage] : offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); - writePushedData(bytes, shader, placement.pushed); - if (shader.program->pushedBufferCount != 0u) writePushedBuffers(bytes, stage, placement, addressed ? &rewritten->addressOverrides : nullptr, offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]); rooted = true; + const auto stage = HeapStageIndex(shader.stage); + const auto data = offsets[DataOffsetIndex(stage, Abi::Binding::ShaderData)]; + const std::array addresses{data, offsets[DataOffsetIndex(stage, Abi::Binding::UserData)], offsets[DataOffsetIndex(stage, Abi::Binding::FlattenedSrt)], heapTableMapSet[stage] ? heapTableMaps[stage] : data}; + if (cached) { + auto& kept = image.stages[index]; + if (!kept.live && kept.version == heapStages[stage].pushVersion && kept.addresses == addresses) continue; + kept.version = heapStages[stage].pushVersion; + kept.addresses = addresses; + kept.live = false; + } + putAddress(Abi::RootItem::ShaderData, addresses[0]); + putAddress(Abi::RootItem::UserData, addresses[1]); + putAddress(Abi::RootItem::SrtAddress, addresses[2]); + putAddress(Abi::RootItem::TableMap, addresses[3]); + writePushedData(target, shader, placement.pushed); + const bool live = shader.program->pushedBufferCount != 0u; + if (live) writePushedBuffers(target, stage, placement, addressed ? &rewritten->addressOverrides : nullptr, data); + if (cached) image.stages[index].live = live; + } + if (cached) { + for (auto mask = image.mask; mask != 0u; mask &= mask - 1u) { + const auto dword = static_cast(std::countr_zero(mask)); + std::memcpy(bytes.data() + dword * sizeof(std::uint32_t), image.bytes.data() + dword * sizeof(std::uint32_t), sizeof(std::uint32_t)); + } } if (rooted) NoteDataAddressPush(); } +void ShaderResources::PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const { + if (!heapStage) return; + static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + const bool addressed = rewritten != nullptr && rewritten->addressOffsets; + if (addressed) { + pushImage.valid = false; + writeDataRoots(bytes, shaders, placements, rewritten, false); + return; + } + if (!verify) { + writeDataRoots(bytes, shaders, placements, rewritten, !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::PushImage)); + return; + } + std::array reference; + std::copy(bytes.begin(), bytes.end(), reference.begin()); + writeDataRoots(reference, shaders, placements, rewritten, false); + writeDataRoots(bytes, shaders, placements, rewritten, true); + std::uint64_t fresh = 0; + for (const auto& placement : placements) { + if (placement.bufferOverflow != ShaderRecompiler::RuntimeAbi::NoPushPosition) fresh |= std::uint64_t{3} << placement.bufferOverflow; + } + for (std::size_t dword = 0; dword < ShaderRecompiler::RuntimeAbi::PushDataDwords; ++dword) { + if ((fresh >> dword & 1u) != 0u) continue; + if (std::memcmp(reference.data() + dword * sizeof(std::uint32_t), bytes.data() + dword * sizeof(std::uint32_t), sizeof(std::uint32_t)) != 0) + throw std::runtime_error("AGC graphics: a GPU heap draw's cached push data differs from the push data written in full"); + } +} + void ShaderResources::writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const { namespace Abi = ShaderRecompiler::RuntimeAbi; - static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; const auto uniformAlignment = UniformConstantBuffersEnabled() ? context.limits.minUniformBufferOffsetAlignment : VkDeviceSize{1}; const auto clampedSize = [](const VkDeviceAddressRangeEXT& range) { return static_cast(std::min(range.size, 0xffffffffu)); @@ -7615,59 +7677,19 @@ void ShaderResources::writePushedBuffers(std::span(stage)); - if (constant) { - bufferRanges(static_cast(stage), nullptr, cached.ranges); - cached.records.assign(cached.ranges.size() * Abi::OverflowRecordWords, 0u); - cached.emptyRecords.clear(); - for (std::size_t index = 0; index < cached.ranges.size(); ++index) { - const auto& range = cached.ranges[index]; - const auto size = clampedSize(range); - if (size == 0u || range.address == 0u) { - cached.emptyRecords.push_back(static_cast(index)); - continue; - } - const auto words = record(range.address, size); - std::copy(words.begin(), words.end(), cached.records.begin() + static_cast(index * Abi::OverflowRecordWords)); - } - } - cached.constant = constant; - cached.built = constant || !resolvedAddresses.empty(); - } - if (cached.constant) kept = &cached; - } struct RangeStorage {}; - auto& scratch = HostThreadLocal, RangeStorage>(); - if (kept == nullptr) { - scratch.clear(); - bufferRanges(static_cast(stage), overrides, scratch); - } - const auto& ranges = kept != nullptr ? kept->ranges : scratch; + auto& ranges = HostThreadLocal, RangeStorage>(); + ranges.clear(); + bufferRanges(static_cast(stage), overrides, ranges); Require(ranges.size() == placement.pushedBuffers, "a stage's buffer addresses do not match its push layout's buffer count"); heapPushedStages.store(heapPushedStages.load(std::memory_order_relaxed) + 1u, std::memory_order_relaxed); Require(empty != 0u, "a stage with pushed buffers has no shader data to stand in for an empty buffer"); struct RecordStorage {}; auto& records = HostThreadLocal, RecordStorage>(); - if (kept != nullptr) { - records.assign(kept->records.begin(), kept->records.end()); - if (!kept->emptyRecords.empty()) { - const auto stand = encode({0u, 0u}); - for (const auto index : kept->emptyRecords) - std::copy(stand.begin(), stand.end(), records.begin() + static_cast(index * Abi::OverflowRecordWords)); - } - for (std::size_t index = 0; index < ranges.size(); ++index) { - if (ranges[index].address == empty) records[index * Abi::OverflowRecordWords + 2u] = 0u; - } - } else { - records.resize(ranges.size() * Abi::OverflowRecordWords); - for (std::size_t index = 0; index < ranges.size(); ++index) { - const auto words = encode(ranges[index]); - std::copy(words.begin(), words.end(), records.begin() + static_cast(index * Abi::OverflowRecordWords)); - } + records.resize(ranges.size() * Abi::OverflowRecordWords); + for (std::size_t index = 0; index < ranges.size(); ++index) { + const auto words = encode(ranges[index]); + std::copy(words.begin(), words.end(), records.begin() + static_cast(index * Abi::OverflowRecordWords)); } const auto put = [&](std::uint32_t position, std::span words) { Require(position != Abi::NoPushPosition && (position + words.size()) * sizeof(std::uint32_t) <= bytes.size(), "a stage's pushed buffer words lie outside the push data"); @@ -7718,6 +7740,23 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi const auto table = std::find_if(tableStages.begin(), tableStages.end(), [&](const TableStage& candidate) { return candidate.stage == shader.stage && candidate.heap; }); if (table == tableStages.end() || table->mapAllocation == noElement) return; + static const bool verifyMap = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + auto& stageState = heapStages[stageIndex]; + const bool mapCurrent = !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::TableMap) && stageState.mapBuilt && stageState.map.table.address != 0u && + heap.GenerationsCurrent(stageState.mapSlots, stageState.mapGenerations, stageState.mapSamplers, stageState.mapSamplerGenerations); + if (mapCurrent && !verifyMap) { + stageState.mapTouched = heap.TouchSlots(stageState.mapSlots, stageState.mapSamplers, stageState.mapTouched); + heap.NoteTableKept(spans); + heapTableMaps[stageIndex] = stageState.map.table.address; + heapTableMapSet[stageIndex] = true; + return; + } + stageState.mapSlots.clear(); + stageState.mapSamplers.clear(); + const auto image = [&](std::uint32_t slot) { + stageState.mapSlots.push_back(slot); + return slot; + }; const ShaderRecompiler::DescriptorBinding* images = nullptr; for (const auto& binding : shader.program->bindings) { if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable) @@ -7729,8 +7768,8 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi const auto elements = images != nullptr ? static_cast(images->count) : std::size_t{0}; const auto base = static_cast(map.size()); map[TableAbi::HeaderElementBase] = base; - const auto sampledAbsent = heap.AbsentSlot(Abi::FirstImageBinding, heapPlaceholderView(Abi::FirstImageBinding)); - const auto storageAbsent = heap.AbsentSlot(Abi::FirstStorageImageBinding, heapPlaceholderView(Abi::FirstStorageImageBinding)); + const auto sampledAbsent = image(heap.AbsentSlot(Abi::FirstImageBinding, heapPlaceholderView(Abi::FirstImageBinding))); + const auto storageAbsent = image(heap.AbsentSlot(Abi::FirstStorageImageBinding, heapPlaceholderView(Abi::FirstStorageImageBinding))); for (std::size_t element = 0; element < elements; ++element) { const auto index = element < table->elementTextures.size() ? table->elementTextures[element] : noElement; if (index == noElement) { @@ -7738,7 +7777,7 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi continue; } const auto view = textureFirstLayer[index] ? textures[index]->FirstLayerView() : textures[index]->View(); - map.push_back(takenSlot(heap.TextureSlot(Abi::FirstImageBinding, textures[index].get(), view, textures[index]->Layout()), "the global image heap is full")); + map.push_back(image(takenSlot(heap.TextureSlot(Abi::FirstImageBinding, textures[index].get(), view, textures[index]->Layout()), "the global image heap is full"))); } const auto appendStorageSlots = [&](std::uint32_t kind, std::uint32_t absent, const char* full, const auto& wanted, const auto& viewOf) { for (std::size_t element = 0; element < elements; ++element) { @@ -7747,13 +7786,17 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi map.push_back(absent); continue; } - map.push_back(takenSlot(heap.StorageSlot(kind, storageTextures[index].get(), viewOf(*storageTextures[index], index)), full)); + map.push_back(image(takenSlot(heap.StorageSlot(kind, storageTextures[index].get(), viewOf(*storageTextures[index], index)), full))); } }; appendStorageSlots( Abi::FirstStorageImageBinding, storageAbsent, "the global storage image heap is full", [](std::size_t) { return true; }, [&](StorageTexture& image, std::size_t index) { return image.StorageView(storageMips[index], storageFirstLayer[index]); }); - const auto samplerSlotOf = [&](std::size_t index) { return takenSlot(heap.SamplerSlot(samplers[index]), "the global sampler heap is full"); }; + const auto samplerSlotOf = [&](std::size_t index) { + const auto slot = takenSlot(heap.SamplerSlot(samplers[index]), "the global sampler heap is full"); + stageState.mapSamplers.push_back(slot); + return slot; + }; const auto firstSampler = std::find_if(table->tableSamplers.begin(), table->tableSamplers.end(), [&](const auto index) { return index != noElement; }); const std::uint32_t fallbackSampler = firstSampler != table->tableSamplers.end() ? samplerSlotOf(*firstSampler) : 0u; for (const auto index : table->tableSamplers) map.push_back(index == noElement ? fallbackSampler : samplerSlotOf(index)); @@ -7776,7 +7819,7 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi for (const bool wide : {false, true}) { const auto kind = wide ? Abi::FirstAtomic64ImageBinding : Abi::FirstAtomicImageBinding; appendStorageSlots( - kind, heap.AbsentSlot(kind, heapPlaceholderView(kind)), "the global atomic image heap is full", + kind, image(heap.AbsentSlot(kind, heapPlaceholderView(kind))), "the global atomic image heap is full", [&](std::size_t element) { return atomicElement(element, wide); }, [&](StorageTexture& image, std::size_t index) { return wide ? image.Atomic64View(storageMips[index], storageFirstLayer[index]) @@ -7791,35 +7834,56 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi map.resize(extraBase + 2u * elements, fallbackSampler); const auto kind = Abi::FirstUintStorageImageBinding; appendStorageSlots( - kind, heap.AbsentSlot(kind, heapPlaceholderView(kind)), "the global storage image heap is full", [](std::size_t) { return true; }, + kind, image(heap.AbsentSlot(kind, heapPlaceholderView(kind))), "the global storage image heap is full", [](std::size_t) { return true; }, [&](StorageTexture& image, std::size_t index) { return image.UintStorageViewOrDefault(storageMips[index], storageFirstLayer[index]); }); } if (map.size() == base) map.push_back(sampledAbsent); - heapTableMaps[stageIndex] = heapSpan(spans, heap, heapStages[stageIndex].map, map); + if (mapCurrent && !std::ranges::equal(stageState.map.words, map)) throw std::runtime_error("AGC graphics: a GPU heap stage's image table map changed although its slots did not"); + heapTableMaps[stageIndex] = heapSpan(spans, heap, stageState.map, map); heapTableMapSet[stageIndex] = true; + stageState.mapGenerations.clear(); + for (const auto slot : stageState.mapSlots) stageState.mapGenerations.push_back(heap.SlotGeneration(slot)); + stageState.mapSamplerGenerations.clear(); + for (const auto slot : stageState.mapSamplers) stageState.mapSamplerGenerations.push_back(heap.SamplerGeneration(slot)); + stageState.mapBuilt = true; } -std::uint64_t ShaderResources::heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words, std::uint64_t pushed) { - const bool same = std::ranges::equal(kept.words, words); - bool pushedOnly = false; - if (!same && pushed != 0u && kept.words.size() == words.size()) { - const auto prefix = std::min(words.size(), 64u); - pushedOnly = std::equal(words.begin() + static_cast(prefix), words.end(), kept.words.begin() + static_cast(prefix)); - for (std::size_t index = 0; pushedOnly && index < prefix; ++index) pushedOnly = kept.words[index] == words[index] || ((pushed >> index) & 1u) != 0u; - } - const auto span = heap.KeepOrAllocate(spans, words.size(), kept.mark, same || pushedOnly); - if (!span) { - if (pushedOnly) { - std::copy(words.begin(), words.end(), kept.words.begin()); - NotePushedUserDataKeep(); - } - return kept.mark.address; +std::uint64_t ShaderResources::heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words) { + if (kept.table.address != 0u && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::StageData) && std::ranges::equal(kept.words, words)) { + heap.NoteTableKept(spans); + return kept.table.address; } + return heapTable(spans, heap, kept, words); +} + +std::uint64_t ShaderResources::heapTable(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words) { + heap.RetireTable(spans, kept.table); + const auto span = heap.AllocateTable(spans, words.size(), kept.table); BindlessHeap::Write(*span, words); kept.words.assign(words.begin(), words.end()); return span->address; } +bool ShaderResources::keptTable(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept) { + if (kept.table.address == 0u) return false; + heap.NoteTableKept(spans); + return true; +} + +void ShaderResources::retireHeapTables() noexcept { + try { + auto* heap = BindlessHeap::Existing(context); + if (heap == nullptr) return; + BindlessHeap::SpanScope spans(*heap); + for (auto& stage : heapStages) { + heap->RetireTable(spans, stage.data.table); + heap->RetireTable(spans, stage.flat.table); + heap->RetireTable(spans, stage.map.table); + } + } catch (...) { + } +} + bool ShaderResources::ownsHeapBinding(const Binding& binding, VkShaderStageFlags stageBit) const { return binding.heap && (binding.layout.stageFlags & stageBit) != 0u; } @@ -7862,6 +7926,9 @@ void ShaderResources::layOutHeapStages(std::span shaders) if (ownsHeapBinding(bindings[index], stageBit)) state.owned.push_back(static_cast(index)); } state.laidOutFor = stageBit; + state.keyTaken = false; + state.mapBuilt = false; + ++state.pushVersion; state.pushedUserWords = 0; state.pushedPlaced = 0; state.splitUser = false; @@ -8007,6 +8074,7 @@ void ShaderResources::noteHeapSlotGenerations(const BindlessHeap& heap, HeapStag void ShaderResources::verifyHeapSlots(const BindlessHeap& heap, const HeapStageState& state, VkShaderStageFlags stageBit) const { constexpr auto bindingCount = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count); static std::atomic checked{0}, wrong{0}, storageChecked{0}, storageWrong{0}; + const auto wrongBefore = wrong.load() + storageWrong.load(); for (const auto& binding : bindings) { if (!ownsHeapBinding(binding, stageBit)) continue; const bool sampled = binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; @@ -8039,6 +8107,7 @@ void ShaderResources::verifyHeapSlots(const BindlessHeap& heap, const HeapStageS static_cast(checked.load()), static_cast(wrong.load()), static_cast(storageChecked.load()), static_cast(storageWrong.load())); } + if (wrong.load() + storageWrong.load() != wrongBefore) throw std::runtime_error("AGC graphics: a GPU heap stage's slots hold another image, view or texture than its bindings"); } namespace { @@ -8122,8 +8191,8 @@ std::pair ShaderResources::writeSplitHeapStage(con }; struct PatchedStorage {}; auto& patched = HostThreadLocal, PatchedStorage>(); - const bool dataKept = sameWalk && !verifySlots && heap.Held(stageState.data.mark); - auto dataAddress = stageState.data.mark.address; + const bool dataKept = sameWalk && !verifySlots && keptTable(spans, heap, stageState.data); + auto dataAddress = stageState.data.table.address; if (!dataKept) { ValidateRuntimeResources(shader, words); patched.assign(words.begin(), words.end()); @@ -8135,7 +8204,8 @@ std::pair ShaderResources::writeSplitHeapStage(con if (verifySlots && sameWalk && stageState.data.words.size() == patched.size() && !std::equal(patched.begin() + static_cast(userWords), patched.end(), stageState.data.words.begin() + static_cast(userWords))) throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its walked words and slots did not"); - dataAddress = heapSpan(spans, heap, stageState.data, patched); + dataAddress = heapTable(spans, heap, stageState.data, patched); + ++stageState.pushVersion; stageState.dataInput.assign(words.begin(), words.end()); stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); stageState.dataOrigin = shader.heap != nullptr ? shader.heap->dataOrigin : 0u; @@ -8149,8 +8219,19 @@ std::pair ShaderResources::writeSplitHeapStage(con if (verifySlots && !std::equal(user.begin(), user.end(), patched.begin())) throw std::runtime_error("AGC graphics: a GPU-mode stage's user-data block differs from the user words of its full shader data"); const auto counted = std::min(userWords, 64u); - const auto pushedUser = stageState.pushedUserWords & (counted == 64u ? ~std::uint64_t{0} : (std::uint64_t{1} << counted) - 1u); - return {dataAddress, heapSpan(spans, heap, stageState.user, user, pushedUser)}; + const auto userMask = counted == 64u ? ~std::uint64_t{0} : (std::uint64_t{1} << counted) - 1u; + const auto pushedUser = stageState.pushedUserWords & userMask; + const bool userChanged = !std::ranges::equal(stageState.user.words, user); + if (userChanged) ++stageState.pushVersion; + if (userWords <= 64u && pushedUser == userMask) { + if (stageState.user.words.size() == user.size() && userChanged) NotePushedUserDataKeep(); + if (userChanged) stageState.user.words.assign(user.begin(), user.end()); + return {dataAddress, dataAddress}; + } + if (userChanged) stageState.user.words.assign(user.begin(), user.end()); + const auto span = heap.Allocate(user.size()); + BindlessHeap::Write(span, user); + return {dataAddress, span.address}; } void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader) { @@ -8160,12 +8241,12 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl const auto stageIndex = HeapStageIndex(shader.stage); auto& stageState = heapStages[stageIndex]; static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; - const auto programIdentity = shader.program->heapTemplateId; - if (programIdentity != 0 && stageState.inertProgram == programIdentity && !verifySlots) return; - stageState.inertProgram = 0; Require(stageState.laidOutFor == stageBit, "a GPU heap stage was refreshed for a stage its resources were not laid out for"); const auto& owned = stageState.owned; - bool current = heapSlotKeySame(owned, stageState.key); + const bool keyed = stageState.keyTaken; + static const bool slotsBypassed = ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::Slots); + bool current = !slotsBypassed && (keyed && !verifySlots ? true : heapSlotKeySame(owned, stageState.key)); + if (keyed && verifySlots && !slotsBypassed && !current) throw std::runtime_error("AGC graphics: a GPU heap stage's textures, views or samplers changed after its resources were built"); const auto slotSerial = heap.SlotSerial(); const bool unmoved = current && EpochProofs() && stageState.slotSerial == slotSerial; if (!unmoved && current) @@ -8175,6 +8256,7 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl appendHeapSlotKey(owned, stageState.key); takeHeapSlots(heap, stageState, owned, stageState.key); noteHeapSlotGenerations(heap, stageState); + stageState.keyTaken = true; } else { stageState.touchedEpoch = heap.TouchSlots(stageState.imageSlots, stageState.samplerSlots, stageState.touchedEpoch); } @@ -8189,6 +8271,7 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl if (program.dataAddressPush) writeHeapTableMap(spans, heap, shader, stageIndex); const std::size_t userIndex = DataOffsetIndex(stageIndex, Abi::Binding::UserData); const bool splitUser = stageState.splitUser; + const auto previousUserWords = stageState.userWords; stageState.userWords = 0; bool dataBindings = false; for (const auto& binding : program.bindings) { @@ -8201,7 +8284,7 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl shader.heap != nullptr ? std::span(shader.heap->userData) : std::span{}; const auto userFront = static_cast(std::min(userData.size(), words.size())); const auto origin = shaderData && shader.heap != nullptr ? shader.heap->dataOrigin : 0u; - const bool sameShape = shaderData && current && stageState.dataInput.size() == words.size() + userData.size(); + const bool sameShape = shaderData && current && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::StageData) && stageState.dataInput.size() == words.size() + userData.size(); const bool sameOrigin = sameShape && origin != 0u && origin == stageState.dataOrigin && stageState.dataProgram == shader.program; const bool sameWords = sameShape && (sameOrigin || std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)); if (verifySlots && sameOrigin && !std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)) @@ -8215,11 +8298,10 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl continue; } if (sameInput && !verifySlots) { - if (heap.Held(stageState.data.mark)) { - heapOffsets[dataIndex] = stageState.data.mark.address; + if (keptTable(spans, heap, stageState.data)) { + heapOffsets[dataIndex] = stageState.data.table.address; continue; } - stageState.data.mark.entry = 0; } if (!shaderData) { heapOffsets[flatIndex] = heapSpan(spans, heap, stageState.flat, words); @@ -8238,17 +8320,15 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl patchHeapSlotWords(shader, stageState, patched, current); if (verifySlots && sameInput && !std::ranges::equal(stageState.data.words, patched)) throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its inputs and slots did not"); - const auto userWords = std::min(userData.size(), 64u); - const auto pushedUser = stageState.pushedUserWords & (userWords == 64u ? ~std::uint64_t{0} : (std::uint64_t{1} << userWords) - 1u); if (sameWords) NoteUserWordsRewrite(patched.size(), userData.size()); - heapOffsets[dataIndex] = heapSpan(spans, heap, stageState.data, patched, pushedUser); + heapOffsets[dataIndex] = heapTable(spans, heap, stageState.data, patched); + ++stageState.pushVersion; stageState.dataInput.assign(words.begin(), words.end()); stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); stageState.dataOrigin = origin; stageState.dataProgram = shader.program; } - const bool unbound = stageState.key.empty() && !dataBindings && !heapTableMapSet[stageIndex] && stageState.imageSlots.empty() && stageState.samplerSlots.empty(); - if (unbound && !addressedBuffers) stageState.inertProgram = programIdentity; + if (stageState.userWords != previousUserWords) ++stageState.pushVersion; } namespace { diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 342b978fd40d..786658b57234 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -281,6 +281,44 @@ bool dataPool(const Context& context) { require(counts.poolBlocksFreed != 0u && counts.poolBlockBytes <= AgcDriver::Graphics::BindlessHeap::PoolIdleBytes + AgcDriver::Graphics::BindlessHeap::PoolBlockBytes, "idle blocks beyond the pool's budget are freed"); } + { + BindlessHeap heap(context); + const BindlessHeap::SpanScope spans(heap); + BindlessHeap::TableMark table; + const std::vector words(40u, 0x5au); + const auto first = heap.AllocateTable(spans, words.size(), table); + require(first.has_value() && table.address == first->address && first->words.size() == words.size(), "a stage table is allocated"); + BindlessHeap::Write(*first, words); + const auto firstAddress = table.address; + heap.RetireTable(spans, table); + require(table.address == 0u, "a retired table leaves its owner"); + BindlessHeap::TableMark unsubmitted; + const auto second = heap.AllocateTable(spans, words.size(), unsubmitted); + require(second.has_value() && second->address != firstAddress, "a table retired in the open batch is not reused before the batch is submitted"); + heap.Submitted(recorder, recorder.Submissions() + (1ull << 40u)); + BindlessHeap::TableMark busy; + const auto third = heap.AllocateTable(spans, words.size(), busy); + require(third.has_value() && third->address != firstAddress, "a table a batch in flight still reads is not reused"); + heap.RetireTable(spans, unsubmitted); + heap.Submitted(recorder, 0u); + BindlessHeap::TableMark reused; + const auto fourth = heap.AllocateTable(spans, words.size(), reused); + require(fourth.has_value() && fourth->address != firstAddress, "a table waits for the batch that last read it, not a later one"); + BindlessHeap::TableMark large; + const auto big = heap.AllocateTable(spans, AgcDriver::Graphics::BindlessHeap::TableBlockBytes, large); + require(big.has_value() && big->words.size() == AgcDriver::Graphics::BindlessHeap::TableBlockBytes && heap.DataLocation(large.address).first != VK_NULL_HANDLE, "a table larger than a shared block gets a block of its own"); + } + { + BindlessHeap heap(context); + const BindlessHeap::SpanScope spans(heap); + BindlessHeap::TableMark table; + static_cast(heap.AllocateTable(spans, 40u, table)); + const auto address = table.address; + heap.RetireTable(spans, table); + heap.Submitted(recorder, 0u); + BindlessHeap::TableMark next; + require(heap.AllocateTable(spans, 40u, next).has_value() && next.address == address, "a table whose batch completed is reused"); + } return true; } diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp deleted file mode 100644 index d9f1b6956127..000000000000 --- a/core/libs/prx/libSceAgcDriver/tests/HeapWalkMemo.cpp +++ /dev/null @@ -1,213 +0,0 @@ -#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -using AgcDriver::DriverDetail::HeapWalkEntry; -using AgcDriver::DriverDetail::HeapWalkEntryBytes; -using AgcDriver::DriverDetail::HeapWalkMemo; -using AgcDriver::DriverDetail::HeapWalkMemoKeys; - -void require(bool condition, const std::string& message) { - if (!condition) throw std::runtime_error(message); -} - -HeapWalkEntry sizedEntry(std::size_t words, std::shared_ptr result = nullptr) { - HeapWalkEntry entry; - std::vector values(words); - values.shrink_to_fit(); - entry.values = std::make_shared>(std::move(values)); - entry.result = std::move(result); - return entry; -} - -std::uint64_t heldBytes(const HeapWalkMemo& memo) { - std::uint64_t bytes = 0; - std::unordered_set pinned; - for (const auto& [key, slot] : memo.entries) { - for (const auto& entry : slot.ways) { - bytes += AgcDriver::DriverDetail::HeapWalkEntryOwnBytes(entry); - if (entry.capture != nullptr && pinned.insert(entry.capture.get()).second) bytes += AgcDriver::DriverDetail::HeapWalkCaptureBytes(*entry.capture); - if (entry.result != nullptr && pinned.insert(entry.result.get()).second) bytes += AgcDriver::DriverDetail::HeapWalkResultBytes(*entry.result); - if (entry.words != nullptr && pinned.insert(entry.words.get()).second) bytes += AgcDriver::DriverDetail::HeapWalkWordsBytes(*entry.words); - } - } - require(memo.order.size() == memo.entries.size(), "the heap walk memo ages " + std::to_string(memo.order.size()) + " keys for the " + std::to_string(memo.entries.size()) + " it holds"); - require(pinned.size() == memo.pins.size(), "the heap walk memo pins " + std::to_string(memo.pins.size()) + " objects for the " + std::to_string(pinned.size()) + " its entries hold"); - return bytes; -} - -void requireWithinBudget(const HeapWalkMemo& memo, const std::string& where) { - const auto held = heldBytes(memo); - require(held == memo.heldBytes, where + ": the heap walk memo charged " + std::to_string(memo.heldBytes) + " bytes for the " + std::to_string(held) + " it holds"); - require(held <= memo.budget, where + ": the heap walk memo holds " + std::to_string(held) + " bytes, over its budget of " + std::to_string(memo.budget)); -} - -void oldestEntriesDroppedTests() { - constexpr std::size_t words = 4096; - require(HeapWalkEntryBytes(sizedEntry(words)) == sizeof(HeapWalkEntry) + words * sizeof(std::uint32_t), "a heap walk entry is not charged its struct and the capacity of its vectors"); - const auto entryBytes = HeapWalkEntryBytes(sizedEntry(words, std::make_shared())); - HeapWalkMemo memo; - memo.budget = 16 * entryBytes; - constexpr std::uint64_t keys = 64; - std::vector> results; - for (std::uint64_t key = 1; key <= keys; ++key) { - auto result = std::make_shared(); - results.push_back(result); - memo.remember(key, sizedEntry(words, std::move(result))); - requireWithinBudget(memo, "after key " + std::to_string(key)); - } - require(memo.find(1) == nullptr && memo.find(keys / 2) == nullptr, "the oldest heap walk entries stayed past the budget"); - require(results.front().expired() && results[keys / 2 - 1].expired(), "a heap walk entry the budget dropped still holds its result"); - const auto* newest = memo.find(keys); - require(newest != nullptr && newest->size() == 1 && newest->front().values->size() == words, "the newest heap walk entry is not findable under the budget"); - require(!results.back().expired(), "the newest heap walk entry lost its result"); - std::cout << "the heap walk memo keeps " << memo.entries.size() << " of " << keys << " entries within its budget of " << memo.budget << " bytes\n"; -} - -void keyCapDropsLeastRecentTests() { - HeapWalkMemo memo; - memo.budget = 2 * (HeapWalkMemoKeys + 1) * HeapWalkEntryBytes(sizedEntry(1)); - for (std::uint64_t key = 1; key <= HeapWalkMemoKeys; ++key) memo.remember(key, sizedEntry(1)); - require(memo.find(1) != nullptr, "the heap walk memo dropped an entry below its key cap"); - memo.remember(HeapWalkMemoKeys + 1, sizedEntry(1)); - require(memo.entries.size() == HeapWalkMemoKeys, "the heap walk memo holds " + std::to_string(memo.entries.size()) + " keys, not its cap of " + std::to_string(HeapWalkMemoKeys)); - require(memo.find(1) != nullptr, "the heap walk memo dropped an entry hit just before it reached its key cap"); - require(memo.find(2) == nullptr, "the heap walk memo kept its least recently used key past its key cap"); - for (std::uint64_t key = 3; key <= HeapWalkMemoKeys + 1; ++key) require(memo.find(key) != nullptr, "the heap walk memo dropped key " + std::to_string(key) + ", more recent than the one its cap needed to drop"); - requireWithinBudget(memo, "after the key cap"); - std::cout << "the heap walk memo drops only its least recently used key at its key cap\n"; -} - -void hitEntriesKeptTests() { - constexpr std::size_t words = 4096; - const auto entryBytes = HeapWalkEntryBytes(sizedEntry(words)); - HeapWalkMemo memo; - memo.budget = 4 * entryBytes; - for (std::uint64_t key = 1; key <= 4; ++key) memo.remember(key, sizedEntry(words)); - auto* hit = memo.find(1); - require(hit != nullptr && hit->size() == 1, "the first heap walk entry is not findable under the budget"); - memo.touch(hit->front()); - memo.remember(5, sizedEntry(words)); - requireWithinBudget(memo, "after the trim"); - require(memo.find(1) != nullptr, "the heap walk memo dropped an entry that was hit after the entries it kept"); - require(memo.find(2) == nullptr, "the heap walk memo kept its least recently used entry past the budget"); - std::cout << "the heap walk memo keeps its recently hit entries\n"; -} - -void sharedResultsChargedOnceTests() { - constexpr std::size_t resultWords = std::size_t{1} << 16u; - auto result = std::make_shared(); - result->heapUserWords.resize(resultWords); - result->heapUserWords.shrink_to_fit(); - const std::shared_ptr shared = std::move(result); - const auto ownBytes = AgcDriver::DriverDetail::HeapWalkEntryOwnBytes(sizedEntry(1)); - const auto sharedBytes = AgcDriver::DriverDetail::HeapWalkResultBytes(*shared); - HeapWalkMemo memo; - memo.budget = 2 * HeapWalkEntryBytes(sizedEntry(1, shared)); - constexpr std::uint64_t keys = 16; - for (std::uint64_t key = 1; key <= keys; ++key) memo.remember(key, sizedEntry(1, shared)); - require(memo.heldBytes == keys * ownBytes + sharedBytes, "the heap walk memo charged " + std::to_string(memo.heldBytes) + " bytes for " + std::to_string(keys) + " entries that share one result, not " + std::to_string(keys * ownBytes + sharedBytes)); - for (std::uint64_t key = 1; key <= keys; ++key) require(memo.find(key) != nullptr, "the heap walk memo dropped an entry whose shared result it already charged"); - for (std::uint64_t key = keys + 1; key <= keys + 64; ++key) { - memo.remember(key, sizedEntry(1, std::make_shared())); - require(memo.heldBytes <= memo.budget, "after key " + std::to_string(key) + ": the heap walk memo holds " + std::to_string(memo.heldBytes) + " bytes, over its budget of " + std::to_string(memo.budget)); - } - requireWithinBudget(memo, "after the shared result's entries aged out"); - std::cout << "the heap walk memo charges a result its entries share once\n"; -} - -void unrepeatedVariantsSkipTests() { - using AgcDriver::DriverDetail::HeapWalkProbeLookups; - using AgcDriver::DriverDetail::HeapWalkSkippedWalks; - HeapWalkMemo memo; - constexpr std::uint64_t missing = 7; - constexpr std::uint64_t hitting = 9; - for (std::uint32_t lookup = 0; lookup < HeapWalkProbeLookups; ++lookup) { - require(memo.consult(missing), "the heap walk memo skipped a shader before its first probe window ended"); - memo.noteLookup(missing, false); - require(memo.consult(hitting), "the heap walk memo skipped a shader whose lookups hit"); - memo.noteLookup(hitting, lookup == 17u); - } - for (std::uint32_t walk = 0; walk < HeapWalkSkippedWalks; ++walk) { - require(!memo.consult(missing), "the heap walk memo kept looking up a shader none of whose " + std::to_string(HeapWalkProbeLookups) + " lookups hit (walk " + std::to_string(walk) + ")"); - require(memo.consult(hitting), "the heap walk memo skipped a shader one of whose lookups hit: a walk costs far more than a lookup"); - } - require(memo.consult(missing), "the heap walk memo never probed a skipped shader again"); - for (std::uint32_t lookup = 0; lookup < HeapWalkProbeLookups; ++lookup) memo.noteLookup(missing, true); - for (std::uint32_t walk = 0; walk < 4u * HeapWalkSkippedWalks; ++walk) require(memo.consult(missing), "the heap walk memo skipped a shader whose new lookups all hit"); - constexpr std::uint64_t returning = 11; - for (std::uint32_t lookup = 0; lookup < HeapWalkProbeLookups; ++lookup) memo.noteLookup(returning, false); - require(!memo.consult(returning), "the heap walk memo kept looking up a shader none of whose lookups hit"); - for (std::uint64_t key = 0; key < HeapWalkProbeLookups; ++key) memo.noteSkipped(returning, 0x1000u + key); - require(!memo.consult(returning), "the heap walk memo resumed a skipped shader whose walks never repeated a key"); - for (std::uint64_t key = 0; key < HeapWalkProbeLookups; ++key) memo.noteSkipped(returning, 0x1000u + key); - require(memo.consult(returning), "the heap walk memo kept skipping a shader whose skipped walks repeated their keys"); - std::cout << "the heap walk memo skips shaders whose lookups do not hit and resumes when their keys repeat\n"; -} - -void walkReadRunsTests() { - std::uint64_t state = 0x9e3779b97f4a7c15ull; - const auto next = [&] { - state ^= state << 13u; - state ^= state >> 7u; - state ^= state << 17u; - return state; - }; - for (int round = 0; round < 512; ++round) { - std::vector words; - const auto count = 1u + next() % 96u; - std::uint64_t cursor = 0x10000u + (next() % 64u) * 4u; - for (std::uint32_t index = 0; index < count; ++index) { - const auto pick = next() % 8u; - if (pick < 4u) cursor += 4u; - else if (pick == 4u) cursor = 0x10000u + (next() % 512u) * 4u; - else if (pick == 5u) cursor += 2u; - else if (pick == 6u && cursor >= 0x10008u) cursor -= 8u; - words.push_back(cursor); - } - std::vector> runs; - for (const auto word : words) AgcDriver::DriverDetail::AppendWalkRead(runs, word); - std::vector> ranges; - AgcDriver::DriverDetail::CoalesceWalkReads(runs, ranges); - auto sorted = words; - std::sort(sorted.begin(), sorted.end()); - std::vector> expected; - for (const auto word : sorted) { - if (!expected.empty() && word <= expected.back().second) { - expected.back().second = std::max(expected.back().second, word + 4u); - continue; - } - expected.emplace_back(word, word + 4u); - } - require(ranges == expected, "the heap walk's read ranges in round " + std::to_string(round) + " differ from the merged ranges of its " + std::to_string(words.size()) + " word reads"); - } - std::cout << "the heap walk's read runs merge to the same ranges as its sorted word reads\n"; -} - -} - -int main() { - try { - oldestEntriesDroppedTests(); - keyCapDropsLeastRecentTests(); - hitEntriesKeptTests(); - sharedResultsChargedOnceTests(); - unrepeatedVariantsSkipTests(); - walkReadRunsTests(); - std::cout << "heap walk memo budget tests passed\n"; - return 0; - } catch (const std::exception& error) { - std::cerr << "heap walk memo budget tests failed: " << error.what() << '\n'; - return 1; - } -} diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapWalkReads.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapWalkReads.cpp new file mode 100644 index 000000000000..26b41fba9f6d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/HeapWalkReads.cpp @@ -0,0 +1,67 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void require(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +void walkReadRunsTests() { + std::uint64_t state = 0x9e3779b97f4a7c15ull; + const auto next = [&] { + state ^= state << 13u; + state ^= state >> 7u; + state ^= state << 17u; + return state; + }; + for (int round = 0; round < 512; ++round) { + std::vector words; + const auto count = 1u + next() % 96u; + std::uint64_t cursor = 0x10000u + (next() % 64u) * 4u; + for (std::uint32_t index = 0; index < count; ++index) { + const auto pick = next() % 8u; + if (pick < 4u) cursor += 4u; + else if (pick == 4u) cursor = 0x10000u + (next() % 512u) * 4u; + else if (pick == 5u) cursor += 2u; + else if (pick == 6u && cursor >= 0x10008u) cursor -= 8u; + words.push_back(cursor); + } + std::vector> runs; + for (const auto word : words) AgcDriver::DriverDetail::AppendWalkRead(runs, word); + std::vector> ranges; + AgcDriver::DriverDetail::CoalesceWalkReads(runs, ranges); + auto sorted = words; + std::sort(sorted.begin(), sorted.end()); + std::vector> expected; + for (const auto word : sorted) { + if (!expected.empty() && word <= expected.back().second) { + expected.back().second = std::max(expected.back().second, word + 4u); + continue; + } + expected.emplace_back(word, word + 4u); + } + require(ranges == expected, "the heap walk's read ranges in round " + std::to_string(round) + " differ from the merged ranges of its " + std::to_string(words.size()) + " word reads"); + } + std::cout << "the heap walk's read runs merge to the same ranges as its sorted word reads\n"; +} + +} + +int main() { + try { + walkReadRunsTests(); + std::cout << "heap walk read tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "heap walk read tests failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp index f6d258e446da..979dcf2ac810 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp @@ -110,7 +110,10 @@ int main() { disjoint(stages, placements, 0, "vertex and pixel"); require(placements[0].pushed.count == 6 && placements[1].pushed.count == 30, "stages that fit push everything they want"); require(place({stages[1]})[0] == placements[1], "a pixel stage that fits is placed as it is alone, so its fragment library is shared"); - require(placements[0].Item(Item::PagetableAddress) != placements[1].Item(Item::PagetableAddress), "the pre-rasterization and fragment parts hold their own globals"); + require(placements[0].Item(Item::PagetableAddress) == placements[1].Item(Item::PagetableAddress), "the pre-rasterization and fragment parts share their globals"); + const std::vector fault{{ShaderStage::Vertex, vertexItems | bits({Item::FaultAddress, Item::GdsAddress}), 6}, {ShaderStage::Fragment, pixelItems, 30}}; + disjoint(fault, place(fault), 0, "globals only the pre-rasterization part reads"); + require(place(fault)[1] == place({fault[1]})[0], "globals only the pre-rasterization part reads do not move the fragment part's roots"); } { const auto user = Abi::RootItemBit(Item::UserData); @@ -137,7 +140,7 @@ int main() { const std::vector stages{{ShaderStage::Vertex, vertexItems, 40}, {ShaderStage::Fragment, pixelItems, 40}}; const auto placements = place(stages); disjoint(stages, placements, 0, "stages that want too much"); - require(placements[0].pushed.count == 26 && placements[1].pushed.count == 26, "stages that want too much share the room evenly"); + require(placements[0].pushed.count == 27 && placements[1].pushed.count == 27, "stages that want too much share the room evenly"); } { const std::vector stages{{ShaderStage::Local, vertexItems, 4}, {ShaderStage::TessellationControl, bits({Item::PagetableAddress, Item::ShaderData}), 3}, {ShaderStage::TessellationEvaluation, vertexItems, 10}, {ShaderStage::Fragment, pixelItems, 48}}; diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_pushed_user_values_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_pushed_user_values_tests.cmake new file mode 100644 index 000000000000..195b460d7279 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_draw_pushed_user_values_tests.cmake @@ -0,0 +1,5 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_draw_pushed_user_values) + agc_add_env_test(agc_driver_draw_pushed_user_values_gpu_heap_unverified agc_driver_draw_pushed_user_values_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake index 2c43f3600527..4512d8eee6ab 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake @@ -5,6 +5,8 @@ if(BUILD_TESTING AND TARGET agc_driver_heap_draw_sample_tests) ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5) agc_add_env_test(agc_driver_heap_draw_sample_full_heap_pipelined agc_driver_heap_draw_sample_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) + agc_add_env_test(agc_driver_heap_draw_sample_full_heap_unverified agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_HEAP_SLOT_CAP=5) agc_add_env_test(agc_driver_heap_draw_sample_heap_excluded agc_driver_heap_draw_sample_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_GPU_HEAP_EXCLUDE=sampled) agc_add_env_test(agc_driver_heap_draw_sample_no_timeline agc_driver_heap_draw_sample_tests diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_memo_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_memo_tests.cmake deleted file mode 100644 index 56ccd917a0c6..000000000000 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_memo_tests.cmake +++ /dev/null @@ -1,24 +0,0 @@ -add_test_executable(agc_driver_heap_walk_memo_tests EXCLUDE_FROM_ALL - tests/HeapWalkMemo.cpp -) - -target_include_directories(agc_driver_heap_walk_memo_tests PRIVATE - ${LIBS_INCLUDE_DIR} - $ - ${CMAKE_SOURCE_DIR}/core/shader/recompiler - ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} - ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR} -) - -target_link_libraries(agc_driver_heap_walk_memo_tests PRIVATE - libSceAgcDriver - SDL2-static - libc -) - -set_target_properties(agc_driver_heap_walk_memo_tests PROPERTIES CXX_EXTENSIONS OFF) -configure_windows_unwind(agc_driver_heap_walk_memo_tests) - -if(BUILD_TESTING) - agc_add_default_test(agc_driver_heap_walk_memo_tests) -endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_memo_threads_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_memo_threads_tests.cmake deleted file mode 100644 index e0004937af92..000000000000 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_memo_threads_tests.cmake +++ /dev/null @@ -1,3 +0,0 @@ -if(BUILD_TESTING) - agc_add_gpu_heap_test(agc_driver_heap_walk_memo_threads) -endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_reads_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_reads_tests.cmake new file mode 100644 index 000000000000..49e761c6ca0b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_reads_tests.cmake @@ -0,0 +1,24 @@ +add_test_executable(agc_driver_heap_walk_reads_tests EXCLUDE_FROM_ALL + tests/HeapWalkReads.cpp +) + +target_include_directories(agc_driver_heap_walk_reads_tests PRIVATE + ${LIBS_INCLUDE_DIR} + $ + ${CMAKE_SOURCE_DIR}/core/shader/recompiler + ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} + ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR} +) + +target_link_libraries(agc_driver_heap_walk_reads_tests PRIVATE + libSceAgcDriver + SDL2-static + libc +) + +set_target_properties(agc_driver_heap_walk_reads_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_driver_heap_walk_reads_tests) + +if(BUILD_TESTING) + agc_add_default_test(agc_driver_heap_walk_reads_tests) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_threads_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_threads_tests.cmake new file mode 100644 index 000000000000..e2e2f0ceb11c --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_threads_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_heap_walk_threads) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawPushedUserValues.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawPushedUserValues.cpp new file mode 100644 index 000000000000..49e0f8c8090f --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawPushedUserValues.cpp @@ -0,0 +1,223 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; + +constexpr std::byte Kept{0x40}; + +alignas(256) constexpr std::array VertexCode{ + 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, + 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, +}; +alignas(256) constexpr std::array UserPixelCode{0x7e00020cu, 0x7e02020du, 0x7e04020eu, 0x7e06020fu, + 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; + +alignas(256) std::array ColorMemory{}; + +std::span MergedTarget(std::size_t index) { + constexpr std::size_t Bytes = 65536; + static std::array data{}; + if (data.at(index) == nullptr) data[index] = [] { + std::byte* block = nullptr; +#ifdef _WIN32 + block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Bytes, Bytes)); + GuestArena::GuestArenaCommit_nid_postfix(block, Bytes, PAGE_READWRITE, Bytes); +#else + void* raw = mmap(nullptr, 2u * Bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(raw != MAP_FAILED, "cannot map the merged color target"); + const auto begin = reinterpret_cast(raw); + block = reinterpret_cast((begin + Bytes - 1u) & ~static_cast(Bytes - 1u)); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Bytes); +#endif + GuestAllocations::Mutation mutation; + mutation.Add(block, Bytes, true, true, true); + return block; + }(); + return {data[index], ColorMemory.size()}; +} +struct Header { + Shader shader{}; + ShaderUserData userData{}; +}; + +alignas(8) Header VertexHeader{}; +alignas(8) Header PixelHeader{}; + +void Registered(Header& header, const std::uint32_t* code, std::size_t bytes, std::uint8_t type) { + header.shader.file_header = 0x34333231u; + header.shader.version = 0x18u; + header.shader.header_size = sizeof(Header); + header.shader.shader_size = static_cast(bytes); + header.shader.code = code; + header.shader.type = type; + header.shader.user_data = &header.userData; + AgcDriverRegisterShader_nid_postfix(&header.shader); +} + +void Append(std::vector& commands, std::uint32_t opcode, std::initializer_list payload) { + commands.push_back(0xc0000000u | (static_cast(payload.size() - 1) << 16u) | (opcode << 8u)); + commands.insert(commands.end(), payload); +} + +std::vector Frame(std::span alphas) { + const auto color = reinterpret_cast(MergedTarget(0).data()); + const std::vector> context{ + {0x2d5, 0x2000}, + {0x1b6, 0}, + {0x207, 0}, + {0x200, 0}, + {0x203, 0x800}, + {0x2dc, 0xaa00}, + {0x2f8, 0}, + {0x293, 0}, + {0x80, 0}, + {0x8d, 0}, + {0x83, 0xffff}, + {0x8c, 0xa}, + {0x2f9, 0x2d}, + {0x313, 0x6000}, + {0x30e, 0xffffffff}, + {0x30f, 0xffffffff}, + {0x206, 0x43f}, + {0x204, 0x80000}, + {0x205, 0x240}, + {0x8e, 0xf}, + {0x8f, 0xf}, + {0x202, 0xcc0010}, + {0x1c4, 0}, + {0x1c5, 9}, + {0x1c3, 4}, + {0x31c, 0x28028}, + {0x31b, 0}, + {0x31d, 0}, + {0x3b0, (63u << 14u) | 3u}, + {0x3b8, 0x9000000}, + {0x1e0, 0}, + {0xc, 0}, + {0xd, 0x40040}, + {0x81, 0x80000000}, + {0x82, 0x40040}, + {0x90, 0x80000000}, + {0x91, 0x40040}, + {0x94, 0x80000000}, + {0x95, 0x40040}, + {0x10f, std::bit_cast(32.0f)}, + {0x110, std::bit_cast(32.0f)}, + {0x111, std::bit_cast(-2.0f)}, + {0x112, std::bit_cast(2.0f)}, + {0x113, std::bit_cast(1.0f)}, + {0x114, 0}, + {0xb4, 0}, + {0xb5, std::bit_cast(1.0f)}, + {0x2fe, 0}, + {0x302, 0}, + {0x306, 0}, + {0x30a, 0}, + {0x318, static_cast(color >> 8u)}, + {0x390, static_cast(color >> 40u)}, + {0x292, 2}, + }; + + std::vector commands; + Append(commands, 0x79, {0x242, 4}); + for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value}); + const auto vertex = reinterpret_cast(VertexCode.data()); + Append(commands, 0x76, {0xc8, static_cast(vertex >> 8u)}); + Append(commands, 0x76, {0xc9, static_cast(vertex >> 40u)}); + Append(commands, 0x76, {0x8b, 1u << 1u}); + Append(commands, 0x76, {0x8c, 0}); + const auto pixel = reinterpret_cast(UserPixelCode.data()); + for (const auto alpha : alphas) { + const std::array words{std::bit_cast(0.25f), std::bit_cast(0.5f), std::bit_cast(0.75f), std::bit_cast(alpha)}; + Append(commands, 0x76, {0x008, static_cast(pixel >> 8u)}); + Append(commands, 0x76, {0x009, static_cast(pixel >> 40u)}); + Append(commands, 0x76, {0x00b, 16u << 1u}); + for (std::uint32_t index = 0; index < 12u; ++index) Append(commands, 0x76, {0x00cu + index, 0u}); + for (std::uint32_t index = 0; index < 4u; ++index) Append(commands, 0x76, {0x018u + index, words[index]}); + Append(commands, 0x2d, {3, 2}); + } + return commands; +} + +unsigned Submit(std::span alphas) { + std::ranges::fill(MergedTarget(0), Kept); + auto commands = Frame(alphas); + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); + AgcDriverWaitIdle_nid_postfix(); + const auto color = MergedTarget(0); + for (std::size_t offset = 0; offset < color.size(); offset += 4) { + if (std::all_of(color.begin() + static_cast(offset), color.begin() + static_cast(offset + 4), [](std::byte value) { return value == Kept; })) continue; + return static_cast(color[offset + 3]); + } + throw std::runtime_error("the draws covered no pixel"); +} + +unsigned Byte(float value) { + return static_cast(value * 255.0f + 0.5f); +} + +} + +int main() { + try { + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); + Registered(PixelHeader, UserPixelCode.data(), sizeof(UserPixelCode), 1); + const auto keepsBefore = AgcDriver::Graphics::PushedUserDataKeeps(); + const std::vector> frames{{0.2f, 0.6f}, {0.6f, 0.2f}, {0.2f, 0.2f}, {0.8f}, {0.8f, 0.4f, 0.8f}, {0.4f}, {0.4f}}; + for (const auto& frame : frames) { + const auto drawn = Submit(frame); + Require(drawn == Byte(frame.back()), "a draw whose only change was a user word read from push data drew alpha " + std::to_string(drawn) + ", expected " + std::to_string(Byte(frame.back()))); + } + if (AgcDriver::Graphics::DescriptorHeapEnabled()) + Require(AgcDriver::Graphics::PushedUserDataKeeps() > keepsBefore, "heap draws whose user words all fit push data did not take the pushed user-data path"); + std::puts("draws whose only change was a pushed user word read the new word"); + AgcDriverShutdown_nid_postfix(); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index af50fd9632ee..6a8044d9c3df 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -377,7 +377,7 @@ std::span PixelProgram(Mode mode, bool buffer, bool vertexS return PixelCode; } -void DrawSamplesTheTexture(bool heap, Mode mode) { +void DrawSamplesTheTexture(bool heap, Mode mode, bool repeated = false) { const bool buffer = mode == Mode::Buffer || mode == Mode::Bda || mode == Mode::MovedBuffer; const auto colorMemory = mode == Mode::MergedBlend ? MergedTarget(0) : mode == Mode::MergedBlendOther ? MergedTarget(1) : std::span(ColorMemory); std::ranges::fill(colorMemory, Kept); @@ -425,7 +425,7 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { ++drawn; } Require(drawn != 0, "the draw covered no pixel"); - if (mode == Mode::Table || mode == Mode::VertexTable) + if ((mode == Mode::Table || mode == Mode::VertexTable) && !repeated) Require(AgcDriver::Graphics::ImageTableBuilds() > tablesBefore, std::string("the table draw's ") + (mode == Mode::Table ? "fragment" : "vertex") + " stage bound no image table"); if (mode == Mode::Gds) Require(*gdsCounter != 0u, "the GDS append did not count the drawn lanes"); @@ -435,7 +435,7 @@ void DrawSamplesTheTexture(bool heap, Mode mode) { std::to_string(StorageMemory[channel]) + ", expected the sampled " + std::to_string(Texel[channel]) + (heap ? " through the heap" : "")); } - if (!heap) return; + if (!heap || repeated) return; if (mode == Mode::Vertex || mode == Mode::VertexTable) Require(AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore, "the heap did not take the sampling vertex stage with descriptor memory"); @@ -542,6 +542,7 @@ int main() { for (const auto mode : {Mode::Texture, Mode::Buffer, Mode::Storage, Mode::Gds, Mode::Vertex, Mode::Bda, Mode::Table, Mode::VertexTable, Mode::MovedBuffer, Mode::MovedTexture, Mode::PixelLds, Mode::ConstantSampler, Mode::BorderSampler, Mode::WrapSampler, Mode::MergedBlend, Mode::MergedBlendOther, Mode::Texture}) DrawSamplesTheTexture(heap, mode); + for (const auto mode : {Mode::Table, Mode::VertexTable}) DrawSamplesTheTexture(heap, mode, true); const bool capped = heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr; if (heap && !capped) UnpreparedPairTakesTheHeap(); if (heap) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp index 4756ae1f406b..50093c6858fc 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp @@ -8,6 +8,7 @@ #include "prx/libc/include/GuestWriteWatch.hpp" #include "Recompiler.hpp" #include "RuntimeAbi.hpp" +#include "ImageTableAbi.hpp" #include "VulkanTestDevice.hpp" #ifdef _WIN32 #ifndef NOMINMAX @@ -205,6 +206,33 @@ void RefreshAfterOriginalDestroyed(const AgcDriver::VulkanDevice& device, const std::printf("the heap table map refreshed for %s\n", what); } +void RefreshAfterSlotReleased(const AgcDriver::VulkanDevice& device, const GuestBlock& block) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + namespace TableAbi = ShaderRecompiler::ImageTableAbi; + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); + const auto program = Compile(device, block); + RequireHeapTable(program); + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + const CompiledShader shader{ShaderStage::Compute, &program, 0}; + auto resources = std::make_shared(context, shader); + Require(resources->HeapStage(), "heap table slot release: the set was not built on the heap"); + auto& heap = AgcDriver::Graphics::BindlessHeap::For(context); + const auto sampledSlot = [&](std::uint64_t root) -> std::pair { + const auto header = heap.DataWords(root, TableAbi::HeaderElementBase + 1u); + const auto base = header[TableAbi::HeaderElementBase]; + const auto slot = heap.DataWords(root, base + 1u)[base]; + return {slot, heap.SlotTexture(Abi::FirstImageBinding, slot)}; + }; + const auto [slot, texture] = sampledSlot(TableMapRoot(*resources, shader)); + Require(texture != nullptr, "heap table slot release: the table's first element holds no texture"); + heap.ReleaseSlots(texture); + Require(heap.SlotTexture(Abi::FirstImageBinding, slot) == nullptr, "heap table slot release: releasing the texture's slots left its slot held"); + resources->RefreshHeapStage(std::span(&shader, 1)); + const auto [refreshedSlot, refreshedTexture] = sampledSlot(TableMapRoot(*resources, shader)); + Require(refreshedTexture == texture, "heap table slot release: after the texture's slot was released the stage's table map still names slot " + std::to_string(refreshedSlot) + ", which no longer holds the texture"); + std::puts("the heap table map was rebuilt after its texture's slot was released"); +} + } int main() { @@ -218,6 +246,7 @@ int main() { Prepare(block, surfaces); RefreshAfterOriginalDestroyed(*device, block, false); RefreshAfterOriginalDestroyed(*device, block, true); + RefreshAfterSlotReleased(*device, block); std::puts("heap table stage reuse tests passed"); return 0; } catch (const std::exception& error) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp index 2dc82d9ae904..6b57bee3ceec 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp @@ -88,25 +88,17 @@ void ValidTypeYieldsStage(AgcDriver::VulkanDevice& device) { Require(materialized.result != nullptr, "a heap walk over valid buffer descriptors declined its stage"); } -void MemoHitSharesWalkedWords(AgcDriver::VulkanDevice& device) { +void RepeatedWalksYieldStages(AgcDriver::VulkanDevice& device) { auto userData = UserData(0u); userData[6] -= 16u; const auto request = Request(device, userData); const auto handle = ShaderRecompiler::PrepareShader(request); const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, handle); Require(invocation.has_value(), "the prepared shader refused its own request"); - std::array walks; - for (auto& walk : walks) { - walk = AgcDriver::DriverDetail::MaterializeHeapStage(*invocation, userData, request.shader.codeAddress); - Require(walk.result != nullptr && walk.words != nullptr, "a repeated heap walk over valid buffer descriptors declined its stage"); + for (int walk = 0; walk < 3; ++walk) { + const auto materialized = AgcDriver::DriverDetail::MaterializeHeapStage(*invocation, userData, request.shader.codeAddress); + Require(materialized.result != nullptr && materialized.words != nullptr, "a repeated heap walk over valid buffer descriptors declined its stage"); } - Require(walks[2].words == walks[1].words, "a heap walk memo hit returned a copy of the walked words instead of the words its walk stored"); - const auto before = AgcDriver::GuestMemory::TrackerAcquisitions(); - const auto hit = AgcDriver::DriverDetail::MaterializeHeapStage(*invocation, userData, request.shader.codeAddress); - const auto taken = AgcDriver::GuestMemory::TrackerAcquisitions() - before; - Require(hit.words == walks[1].words, "a repeated heap walk missed its memo"); - const std::uint64_t proofs = hit.reads.ranges != nullptr && !hit.reads.ranges->empty() ? 1u : 0u; - Require(taken <= proofs, "a heap walk memo hit took the guest write tracker's mutex " + std::to_string(taken) + " times; only its no-stamp proof over its " + std::to_string(proofs) + " range lists needs it"); } } @@ -118,7 +110,7 @@ int main() { if (!device) return VulkanTestSkipped; UnsupportedTypeDeclines(*device); ValidTypeYieldsStage(*device); - MemoHitSharesWalkedWords(*device); + RepeatedWalksYieldStages(*device); std::puts("heap walk capture failure tests passed"); return 0; } catch (const std::exception& error) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkMemoThreads.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp similarity index 88% rename from core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkMemoThreads.cpp rename to core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp index fb93df3bd497..672cb27fb42c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkMemoThreads.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp @@ -1,5 +1,4 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" -#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapWalkMemo.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "Recompiler.hpp" @@ -117,9 +116,8 @@ void Work(const std::vector>& variants, std::size_t fir } } -void TwoThreadsShareEvictedWalks(AgcDriver::VulkanDevice& device) { +void TwoThreadsShareWalks(AgcDriver::VulkanDevice& device) { const auto variants = Prepare(device); - const auto evictionsBefore = AgcDriver::DriverDetail::HeapWalkMemoEvictions(); Inbox first, second; std::atomic failed{false}; std::string firstError, secondError; @@ -128,20 +126,17 @@ void TwoThreadsShareEvictedWalks(AgcDriver::VulkanDevice& device) { one.join(); two.join(); Require(firstError.empty() && secondError.empty(), "a heap walk thread failed: " + firstError + secondError); - const auto evictions = AgcDriver::DriverDetail::HeapWalkMemoEvictions() - evictionsBefore; - Require(evictions != 0, "two threads walked " + std::to_string(Variants) + " stages " + std::to_string(Rounds) + " times each under a 1 MiB heap walk memo without evicting an entry"); - std::printf("two heap walk threads: %llu memo evictions while the other thread held the stages\n", static_cast(evictions)); + std::puts("two heap walk threads exchanged their stages"); } } int main() { - SetTestEnvironment("APS5_HEAP_WALK_MEMO_MB", "1"); try { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; - TwoThreadsShareEvictedWalks(*device); - std::puts("heap walk memo thread tests passed"); + TwoThreadsShareWalks(*device); + std::puts("heap walk thread tests passed"); return 0; } catch (const std::exception& error) { std::cerr << error.what() << '\n'; diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index e91c175cd68b..1deb1d7eaae5 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -244,6 +244,12 @@ function(add_shader_recompiler target runtimeTarget) string(APPEND shaderCacheExtra " system-deps=${ANYPS5_SYSTEM_DEPS_STAMP}") endif() set(shaderCacheReviewedNames + HeapCache + HeapCacheBypassed + HeapCacheBypassMask + HeapCacheNames + HeapOnlyCacheCount + ParseHeapCacheBypass BdaAbi::RangesOrdered RuntimeAbi::GpuHeapStorageKind RuntimeAbi::StageGroup diff --git a/core/shader/recompiler/HeapCacheSwitch.hpp b/core/shader/recompiler/HeapCacheSwitch.hpp new file mode 100644 index 000000000000..314b5fc35ab2 --- /dev/null +++ b/core/shader/recompiler/HeapCacheSwitch.hpp @@ -0,0 +1,79 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace ShaderRecompiler { + +enum class HeapCache : std::uint32_t { + TemplateFront, + Templates, + Slots, + StageData, + TableMap, + PushImage, + DrawKey, + DrawDataHits, + DrawStageDataHits, + DrawSrtEntries, + DrawRecipe, + DrawResourceCache, + ResourceCache, + ValidateCache, + ShapeMemo, + MovedBufferTemplates, + ResultMemo, + Count, +}; + +inline constexpr std::uint32_t HeapOnlyCacheCount = static_cast(HeapCache::DrawKey); + +inline constexpr std::array(HeapCache::Count)> HeapCacheNames{ + "template-front", "templates", "slots", "stage-data", "table-map", "push-image", "draw-key", "draw-data-hits", "draw-stage-data-hits", "draw-srt-entries", + "draw-recipe", "draw-resource-cache", "resource-cache", "validate-cache", "shape-memo", "moved-buffer-templates", "result-memo", +}; + +[[nodiscard]] inline std::uint64_t ParseHeapCacheBypass(std::string_view text) { + std::uint64_t mask = 0; + constexpr auto count = static_cast(HeapCache::Count); + while (!text.empty()) { + const auto comma = text.find(','); + const auto name = text.substr(0, comma); + text = comma == std::string_view::npos ? std::string_view{} : text.substr(comma + 1); + if (name.empty()) continue; + if (name == "all" || name == "1") { + mask |= (std::uint64_t{1} << count) - 1u; + continue; + } + if (name == "heap") { + mask |= (std::uint64_t{1} << HeapOnlyCacheCount) - 1u; + continue; + } + bool known = false; + for (std::uint32_t index = 0; index < count; ++index) { + if (HeapCacheNames[index] != name) continue; + mask |= std::uint64_t{1} << index; + known = true; + } + if (!known) throw std::runtime_error("APS5_HEAP_NO_CACHE names an unknown cache: " + std::string(name)); + } + return mask; +} + +[[nodiscard]] inline std::uint64_t HeapCacheBypassMask() { + static const std::uint64_t mask = [] { + const char* text = std::getenv("APS5_HEAP_NO_CACHE"); + return text == nullptr ? std::uint64_t{0} : ParseHeapCacheBypass(text); + }(); + return mask; +} + +[[nodiscard]] inline bool HeapCacheBypassed(HeapCache cache) { + return (HeapCacheBypassMask() >> static_cast(cache) & 1u) != 0u; +} + +} diff --git a/core/shader/recompiler/PushDataLayout.hpp b/core/shader/recompiler/PushDataLayout.hpp index 4d0658a8d283..c083160b2bed 100644 --- a/core/shader/recompiler/PushDataLayout.hpp +++ b/core/shader/recompiler/PushDataLayout.hpp @@ -109,20 +109,25 @@ inline std::vector PlacePushData(std::span constexpr auto optionalItems = Abi::RootItemBit(Abi::RootItem::UserData); constexpr std::array parts{PushPart::Fragment, PushPart::Compute, PushPart::PreRasterization}; std::vector overflows(stages.size(), Abi::NoPushPosition); + std::uint32_t globals = 0; + std::uint32_t fragmentGlobals = 0; + for (const auto& stage : stages) { + globals |= stage.items & globalItems; + if (stage.part == PushPart::Fragment) fragmentGlobals |= stage.items & globalItems; + } + std::array shared{}; + shared.fill(Abi::NoPushPosition); + placeRoot(fragmentGlobals, false, shared); + placeRoot(globals & ~fragmentGlobals, false, shared); + for (std::size_t index = 0; index < stages.size(); ++index) { + for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { + if ((stages[index].items & globalItems & (1u << item)) != 0u) placements[index].items[item] = shared[item]; + } + } for (const auto part : parts) { const bool top = part != PushPart::PreRasterization; - std::uint32_t globals = 0; - for (const auto& stage : stages) { - if (stage.part == part) globals |= stage.items & globalItems; - } - std::array shared{}; - shared.fill(Abi::NoPushPosition); - placeRoot(globals, top, shared); for (std::size_t index = 0; index < stages.size(); ++index) { if (stages[index].part != part) continue; - for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { - if ((stages[index].items & globalItems & (1u << item)) != 0u) placements[index].items[item] = shared[item]; - } placeRoot(stages[index].items & ~globalItems & ~optionalItems, top, placements[index].items); placements[index].pushedBuffers = stages[index].pushedBuffers; } diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index aeb9bafe82e2..727784da83e9 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -1,4 +1,5 @@ #include "prx/libc/include/HostThreadLocal.hpp" +#include "HeapCacheSwitch.hpp" #include "Recompiler.hpp" #include "PushDataLayout.hpp" #include "HeapTemplateBudget.hpp" @@ -1783,7 +1784,7 @@ RecompileResult RecompileImpl(const RecompileRequest& request) { // APS5_NO_RESULT_MEMO=1: every Recompile(request, capture) materializes its own result as before. bool ResultMemo() { - static const bool resultMemo = std::getenv("APS5_NO_RESULT_MEMO") == nullptr; + static const bool resultMemo = std::getenv("APS5_NO_RESULT_MEMO") == nullptr && !HeapCacheBypassed(HeapCache::ResultMemo); return resultMemo; } @@ -2563,9 +2564,10 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap auto& entry = front.At(source.id, key); ++front.lookups; std::shared_ptr hit; - if (entry.found != nullptr && entry.source == source.id && entry.key == key) { + const bool templates = !HeapCacheBypassed(HeapCache::Templates); + if (templates && !HeapCacheBypassed(HeapCache::TemplateFront) && entry.found != nullptr && entry.source == source.id && entry.key == key) { hit = entry.found; - } else { + } else if (templates) { { std::lock_guard lock(source.mutex); const auto found = source.heapTemplates.find(key); @@ -2589,6 +2591,10 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap auto created = std::make_shared(HeapTemplate{std::move(built), std::move(usedPlan), perDrawBindings ? merged.buffers : std::vector{}, perDrawBindings ? merged.images : std::vector{}, perDrawBindings ? merged.samplers : std::vector{}}); created->bytes = HeapTemplateBytes(*created); std::shared_ptr shared = std::move(created); + if (!templates) { + complete(shared); + return shared->result; + } bool inserted = false; { std::lock_guard lock(source.mutex); diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index 442402304626..2fc1341c5bc6 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -1473,6 +1473,7 @@ constexpr std::string_view NeutralSwitches[] = { "APS5_NO_PERF_LAYOUT_PAIR", "APS5_NO_BUFFER_SUBSTITUTES", "APS5_NO_RESULT_MEMO", + "APS5_HEAP_NO_CACHE", "APS5_NO_TABLE_RESOLUTION_REUSE", "APS5_NO_TABLE_SNAPSHOT_REUSE", "APS5_RESULT_MEMO_MB", From b5b0bff0390e2b437e2ee30d12ca3499dc9b5af2 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 02:28:08 +0530 Subject: [PATCH 189/269] fix(agc): rebuild a heap stage's image table map after a rebuild that failed A table map rebuild cleared the stage's slot lists and refilled them while it took slots, but left the map marked built until it finished. When taking a slot threw (a full heap), the next draw could reuse the old map against a partly refilled slot list, and the generation check compared only the sampler slots that were refilled. The rebuild now marks the map unbuilt before it clears the lists, and the generation check requires both lists to match their generations in length. --- core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp | 4 ++-- .../libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 96ed66c60140..52f2d3fc8000 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -648,13 +648,13 @@ std::uint32_t BindlessHeap::SamplerGeneration(std::uint32_t slot) const { bool BindlessHeap::GenerationsCurrent(std::span slots, std::span slotGenerations, std::span samplerSlots, std::span samplerGenerations) const { - if (slots.size() != slotGenerations.size()) return false; + if (slots.size() != slotGenerations.size() || samplerSlots.size() != samplerGenerations.size()) return false; for (std::size_t i = 0; i < slots.size(); ++i) { if (imagePool.Generation(slots[i]) != slotGenerations[i]) return false; } for (std::size_t i = 0; i < samplerSlots.size(); ++i) { if (samplerSlots[i] == Abi::NoEmbeddedSampler) continue; - if (i >= samplerGenerations.size() || samplerPool.Generation(samplerSlots[i]) != samplerGenerations[i]) return false; + if (samplerPool.Generation(samplerSlots[i]) != samplerGenerations[i]) return false; } return true; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 3c37603ef146..1f6261da8d56 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -7766,6 +7766,7 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi heapTableMapSet[stageIndex] = true; return; } + stageState.mapBuilt = false; stageState.mapSlots.clear(); stageState.mapSamplers.clear(); const auto image = [&](std::uint32_t slot) { From c02c8e4e85ff0e933c79517166a53080172c7864 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 02:28:44 +0530 Subject: [PATCH 190/269] docs(agc): list APS5_HEAP_NO_CACHE and drop the deleted walk memo budget --- docs/dev/ENVIRONMENT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 86cc60ac7045..f3ca01196018 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -40,6 +40,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_EXACT_RCP` | presence | `core/shader/recompiler/SpirvBackend/src/SpirvAlu/SpirvAluEmitterReciprocal.cpp` | | emits `v_rcp_f32` and `v_rcp_iflag_f32` as the RDNA hardware reciprocal (bit-exact for normal inputs and results) instead of the driver's division; adds about 13k SPIR-V words to each shader that uses them | | `APS5_FAST_F32` | presence | `core/shader/recompiler/Translation/src/DispatchInstructions.cpp` | | set to anything but 0, compiles f32 arithmetic with the host's float rules instead of RDNA's: no emulated denormal flush and no RDNA NaN payloads, which differ only for denormals and NaN results; the shader disk cache keeps the two modes apart | | `APS5_GATHER_CONST` | integer | `core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp` | | integer every non-depth gather returns in all four texels instead of the sampled value | +| `APS5_HEAP_NO_CACHE` | string | `core/shader/recompiler/HeapCacheSwitch.hpp` | | bypasses caches by name for debugging and verification: `all`, `heap` (the GPU heap caches) or a comma-separated list of names such as `templates`, `template-front`, `slots`, `stage-data`, `table-map`, `push-image`, `result-memo`, `draw-key`, `draw-recipe`; output-neutral, so it is kept out of the shader cache key | | `APS5_IMAGE_TABLE_KEY_SCAN` | integer | `core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp` | 256 | number of image-table entries the key scan examines | | `APS5_IMAGE_TABLE_STRICT` | string | `core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp` | | sets image-table materialization to its strict form; 0 leaves it off | | `APS5_NO_ATOMIC_BARRIER` | presence | `core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvFormatConvert.cpp` | | drops the device-scope acquire/release memory barrier emitted after atomics | @@ -210,7 +211,6 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_HEADLESS_PIPELINE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | loads the pipeline cache file on a device without a window too; `agc_frame_replay` sets it by default and clears it with `--cold-pipelines`, including inherited values | | `APS5_HEAP_MIRROR_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 24576 | budget in MiB for the heap mirrors held for registered allocations | | `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first | -| `APS5_HEAP_WALK_MEMO_MB` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | 256 | MiB each thread's GPU heap walk memo may hold across both its generations before the previous generation and then the oldest walks are dropped (0 keeps them until the 16,384-key cap rotates them out) | | `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a nearly full heap submits the open batch at the next draw or dispatch and evicts the slots that batch no longer uses | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | From 1a7d1b770bac487d9770a72bad8980ae4008e594 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 06:19:38 +0530 Subject: [PATCH 191/269] test(agc): recompile the float rounding test's store for the device's wave64 compute target again The main merge took #17613's rewrite of this test, which moved the store's shader request into Recompile(target, ...), and dropped the branch's device.ComputeTarget(64) at the old request. Pass it at the new call; the CPU-only Target() of the codegen checks is unchanged. --- .../libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp index e94e7543b795..8418351001d4 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageStoreFloatRounding.cpp @@ -313,7 +313,7 @@ void Store(AgcDriver::VulkanDevice& device, std::uint8_t* texels, const Format& } } } - const auto result = Recompile(device.Target(), format, d16, mixed, texels); + const auto result = Recompile(device.ComputeTarget(64), format, d16, mixed, texels); device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); AgcDriver::Graphics::StorageTexture::FlushPending(reinterpret_cast(texels), TexelBytes, nullptr, "test"); From 1bedba27136d09a79178c39379bb79f0961ac833 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 06:20:41 +0530 Subject: [PATCH 192/269] perf(agc): copy heap push data in runs and keep only a draw's own buffer address overrides writeDrawSets allocated a vector the size of every allocation of the resource object on each addressed heap draw and walked every addressed binding to see whether anything in it was overridden. A draw now records only its snapshot and in-place ranges, as (allocation, range) pairs, and checks them against a per-allocation flag taken once in layOutHeapStages; draws without an override keep nothing. writePushedData checked, branched and copied each pushed dword on its own. layOutHeapStages now turns a stage's pushed-data list into runs of consecutive dwords from one source (user words or shader data), for both the split and the whole user-word layout, and writePushedData copies a run with one memcpy. A placement or user-word split the runs were not made for takes the per-dword copy. writePushedBuffers encodes each pushed buffer record straight into the push data instead of collecting ranges and records in scratch vectors first; the overflow span is filled from the same encoding. --- .../Graphics/include/ShaderResources.hpp | 17 +- .../Graphics/src/ShaderResources.cpp | 149 +++++++++++------- 2 files changed, 107 insertions(+), 59 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index ce7dac7b6d61..72a63d803d4e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -255,7 +255,8 @@ class ShaderResources { std::vector snapshots; bool addressOffsets = false; std::array heapOffsets{}; - std::vector addressOverrides; + std::vector> addressOverrides; + const VkDeviceAddressRangeEXT* AddressOverride(std::size_t allocation) const; std::vector> movedReads; ~DrawBindings(); }; @@ -407,7 +408,7 @@ class ShaderResources { } void PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const; void writePushedData(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const; - void writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const; + void writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const DrawBindings* overrides, VkDeviceAddress empty) const; void writeDataRoots(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten, bool cached) const; struct PushImage { std::array bytes{}; @@ -799,6 +800,15 @@ class ShaderResources { }; KeptSpan data, flat, map, user; std::vector dataInput; + struct PushRun { + std::uint32_t index = 0; + std::uint32_t dword = 0; + std::uint32_t count = 0; + bool user = false; + }; + std::uint32_t pushRunUserWords = 0; + std::vector splitPushRuns; + std::vector wholePushRuns; std::span Slots(std::uint32_t kind) const { for (const auto& range : kindRanges) { if (range.kind == kind) return std::span(imageSlots).subspan(range.first, range.count); @@ -851,13 +861,14 @@ class ShaderResources { bool addressedBuffers = false; std::vector resolvedAddresses; std::array, ShaderRecompiler::RuntimeAbi::StageCount> addressedElements; + std::vector addressedAllocations; VkDeviceAddress emptyAddress = 0; VkDeviceAddress resolvedGds = 0; std::size_t gdsAllocation = std::numeric_limits::max(); std::array heapTableMaps{}; std::array heapTableMapSet{}; void writeHeapTableMap(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, std::size_t stageIndex); - void bufferRanges(std::uint32_t dataStage, const std::vector* overrides, std::vector& ranges) const; + VkDeviceAddressRangeEXT bufferRange(std::uint32_t index, const DrawBindings* overrides) const; VkDeviceAddressRangeEXT bufferAddress(const Allocation& allocation) const; void resolveBufferAddresses(); struct FaultDescriptor { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 1f6261da8d56..02beb1d1e562 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -7268,25 +7268,36 @@ std::shared_ptr ShaderResources::PrepareDrawBindi void ShaderResources::writeDrawSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord, std::span> inPlace) const { if (!heapStage) writeRewrittenSets(result, selected, faultRecord); if (addressedBuffers) { - std::vector overrides(allocations.size(), VkDeviceAddressRangeEXT{0, 0}); - bool overridden = false; + auto& overrides = result.addressOverrides; + overrides.clear(); + overrides.reserve(selected.size() + inPlace.size()); for (std::size_t index = 0; index < selected.size(); ++index) { const auto& snapshot = result.snapshots[index]; - overrides[selected[index]] = {snapshot.buffer->DeviceAddress() + snapshot.offset, snapshot.bytes}; + overrides.push_back({selected[index], {snapshot.buffer->DeviceAddress() + snapshot.offset, snapshot.bytes}}); } - for (const auto& [index, range] : inPlace) overrides[index] = range; - for (const auto& binding : bindings) { - if (!binding.addressed) continue; - for (const auto allocation : binding.allocations) overridden = overridden || overrides[allocation].address != 0; + for (const auto& [index, range] : inPlace) overrides.push_back({index, range}); + bool overridden = false; + for (const auto& [index, range] : overrides) { + if (index >= addressedAllocations.size() || !addressedAllocations[index]) continue; + const auto* last = result.AddressOverride(index); + overridden = overridden || last->address != 0; } if (overridden) { result.heapOffsets = heapOffsets; result.addressOffsets = true; - result.addressOverrides = std::move(overrides); + } else { + overrides.clear(); } } } +const VkDeviceAddressRangeEXT* ShaderResources::DrawBindings::AddressOverride(std::size_t allocation) const { + for (auto entry = addressOverrides.rbegin(); entry != addressOverrides.rend(); ++entry) { + if (entry->first == allocation) return &entry->second; + } + return nullptr; +} + void ShaderResources::writeRewrittenSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord) const { Require(context.descriptorCache != nullptr, "draw snapshots require a descriptor cache"); std::array described{}; @@ -7499,36 +7510,34 @@ void ShaderResources::resolveBufferAddresses() { } } -void ShaderResources::bufferRanges(std::uint32_t dataStage, const std::vector* overrides, std::vector& ranges) const { +VkDeviceAddressRangeEXT ShaderResources::bufferRange(std::uint32_t index, const DrawBindings* overrides) const { static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; - if (dataStage >= addressedElements.size()) return; - for (const auto index : addressedElements[dataStage]) { - const auto& allocation = allocations[index]; - const bool overridden = overrides != nullptr && (*overrides)[index].address != 0; - const bool owned = !overridden && !allocation.guest && allocation.buffer != nullptr && allocation.role != ShaderRecompiler::DescriptorRole::GuestBuffers && allocation.role != ShaderRecompiler::DescriptorRole::BdaPagetable && allocation.role != ShaderRecompiler::DescriptorRole::FaultBuffer; - const bool resolved = !overridden && index < resolvedAddresses.size() && resolvedAddresses[index].address != 0; - VkDeviceAddress address = 0; - VkDeviceSize range = 0; - if (owned) { - address = allocation.buffer->DeviceAddress(); - range = allocation.size; - } else if (resolved) { - address = resolvedAddresses[index].address; - range = resolvedAddresses[index].size; - if (verify) { - const auto fresh = bufferAddress(allocation); - if (fresh.address != address || fresh.size != range) throw std::runtime_error("AGC graphics: a GPU heap buffer address resolved when the draw's resources were built changed"); - } - } else if (overridden) { - address = (*overrides)[index].address; - range = (*overrides)[index].size; - } else { + const auto& allocation = allocations[index]; + const auto* override = overrides != nullptr ? overrides->AddressOverride(index) : nullptr; + const bool overridden = override != nullptr && override->address != 0; + const bool owned = !overridden && !allocation.guest && allocation.buffer != nullptr && allocation.role != ShaderRecompiler::DescriptorRole::GuestBuffers && allocation.role != ShaderRecompiler::DescriptorRole::BdaPagetable && allocation.role != ShaderRecompiler::DescriptorRole::FaultBuffer; + const bool resolved = !overridden && index < resolvedAddresses.size() && resolvedAddresses[index].address != 0; + VkDeviceAddress address = 0; + VkDeviceSize range = 0; + if (owned) { + address = allocation.buffer->DeviceAddress(); + range = allocation.size; + } else if (resolved) { + address = resolvedAddresses[index].address; + range = resolvedAddresses[index].size; + if (verify) { const auto fresh = bufferAddress(allocation); - address = fresh.address; - range = fresh.size; + if (fresh.address != address || fresh.size != range) throw std::runtime_error("AGC graphics: a GPU heap buffer address resolved when the draw's resources were built changed"); } - ranges.push_back({address, std::min(range, context.limits.maxStorageBufferRange)}); + } else if (overridden) { + address = override->address; + range = override->size; + } else { + const auto fresh = bufferAddress(allocation); + address = fresh.address; + range = fresh.size; } + return {address, std::min(range, context.limits.maxStorageBufferRange)}; } std::pair ShaderResources::shaderDataLocation(const CompiledShader& shader, const DrawBindings* rewritten) const { @@ -7559,9 +7568,9 @@ void ShaderResources::writeDataRoots(std::span::max()) return *gds; - const auto* overrides = rewritten != nullptr && rewritten->addressOffsets ? &rewritten->addressOverrides : nullptr; - const bool overridden = overrides != nullptr && (*overrides)[gdsAllocation].address != 0; - gds = overridden ? (*overrides)[gdsAllocation].address : resolvedGds; + const auto* override = rewritten != nullptr && rewritten->addressOffsets ? rewritten->AddressOverride(gdsAllocation) : nullptr; + const bool overridden = override != nullptr && override->address != 0; + gds = overridden ? override->address : resolvedGds; Require(*gds != 0, "the GDS buffer has no device address"); static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; if (verify && !overridden && bufferAddress(allocations[gdsAllocation]).address != *gds) throw std::runtime_error("AGC graphics: the GDS address resolved when the draw's resources were built changed"); @@ -7637,7 +7646,7 @@ void ShaderResources::writeDataRoots(std::spanpushedBufferCount != 0u; - if (live) writePushedBuffers(target, stage, placement, addressed ? &rewritten->addressOverrides : nullptr, data); + if (live) writePushedBuffers(target, stage, placement, addressed ? rewritten : nullptr, data); if (cached) image.stages[index].live = live; } if (cached) { @@ -7677,7 +7686,7 @@ void ShaderResources::PatchDataAddresses(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const std::vector* overrides, VkDeviceAddress empty) const { +void ShaderResources::writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const DrawBindings* overrides, VkDeviceAddress empty) const { namespace Abi = ShaderRecompiler::RuntimeAbi; const auto uniformAlignment = UniformConstantBuffersEnabled() ? context.limits.minUniformBufferOffsetAlignment : VkDeviceSize{1}; const auto clampedSize = [](const VkDeviceAddressRangeEXT& range) { @@ -7692,37 +7701,32 @@ void ShaderResources::writePushedBuffers(std::span, RangeStorage>(); - ranges.clear(); - bufferRanges(static_cast(stage), overrides, ranges); - Require(ranges.size() == placement.pushedBuffers, "a stage's buffer addresses do not match its push layout's buffer count"); + static const std::vector none; + const auto& elements = stage < addressedElements.size() ? addressedElements[stage] : none; + Require(elements.size() == placement.pushedBuffers, "a stage's buffer addresses do not match its push layout's buffer count"); heapPushedStages.store(heapPushedStages.load(std::memory_order_relaxed) + 1u, std::memory_order_relaxed); Require(empty != 0u, "a stage with pushed buffers has no shader data to stand in for an empty buffer"); - struct RecordStorage {}; - auto& records = HostThreadLocal, RecordStorage>(); - records.resize(ranges.size() * Abi::OverflowRecordWords); - for (std::size_t index = 0; index < ranges.size(); ++index) { - const auto words = encode(ranges[index]); - std::copy(words.begin(), words.end(), records.begin() + static_cast(index * Abi::OverflowRecordWords)); - } const auto put = [&](std::uint32_t position, std::span words) { Require(position != Abi::NoPushPosition && (position + words.size()) * sizeof(std::uint32_t) <= bytes.size(), "a stage's pushed buffer words lie outside the push data"); std::memcpy(bytes.data() + position * sizeof(std::uint32_t), words.data(), words.size_bytes()); }; bool overflowed = false; - for (std::size_t index = 0; index < ranges.size(); ++index) { + for (std::size_t index = 0; index < elements.size(); ++index) { const auto root = index < Abi::PushedBufferLimit ? placement.bufferRoots[index] : Abi::NoPushPosition; if (root == Abi::NoPushPosition) { overflowed = true; continue; } - put(root, std::span(records).subspan(index * Abi::OverflowRecordWords, Abi::PushedBufferWords)); + const auto words = encode(bufferRange(elements[index], overrides)); + put(root, std::span(words).first(Abi::PushedBufferWords)); } if (!overflowed) return; heapOverflowStages.fetch_add(1, std::memory_order_relaxed); - const auto span = BindlessHeap::For(context).Allocate(ranges.size() * Abi::OverflowRecordWords); - std::copy(records.begin(), records.end(), span.words.begin()); + const auto span = BindlessHeap::For(context).Allocate(elements.size() * Abi::OverflowRecordWords); + for (std::size_t index = 0; index < elements.size(); ++index) { + const auto words = encode(bufferRange(elements[index], overrides)); + std::copy(words.begin(), words.end(), span.words.begin() + static_cast(index * Abi::OverflowRecordWords)); + } const std::array address{static_cast(span.address), static_cast(span.address >> 32u)}; put(placement.bufferOverflow, address); } @@ -7734,6 +7738,15 @@ void ShaderResources::writePushedData(std::span= stageState.pushedPlaced, "a stage's shader data was kept for user data its pipeline does not push"); Require(placement.count <= program.pushedData.size() && (placement.base + placement.count) * sizeof(std::uint32_t) <= bytes.size(), "a stage's pushed shader data does not fit"); + if (placement.count == stageState.pushedPlaced && (stageState.userWords == 0u || stageState.userWords == stageState.pushRunUserWords)) { + const auto& runs = stageState.userWords == 0u ? stageState.wholePushRuns : stageState.splitPushRuns; + for (const auto& run : runs) { + const auto& source = run.user ? stageState.user.words : words; + Require(run.dword + run.count <= source.size(), "a pushed shader-data dword lies outside the stage's shader data"); + std::memcpy(bytes.data() + (placement.base + run.index) * sizeof(std::uint32_t), source.data() + run.dword, run.count * sizeof(std::uint32_t)); + } + return; + } for (std::uint32_t index = 0; index < placement.count; ++index) { const auto dword = program.pushedData[index]; const bool user = dword < stageState.userWords; @@ -7948,6 +7961,9 @@ void ShaderResources::layOutHeapStages(std::span shaders) state.pushedUserWords = 0; state.pushedPlaced = 0; state.splitUser = false; + state.pushRunUserWords = 0; + state.splitPushRuns.clear(); + state.wholePushRuns.clear(); if (placements.empty() || !shader.program->dataAddressPush) continue; const auto& program = *shader.program; state.splitUser = splits(shader) && placements[shaderIndex].Item(Abi::RootItem::UserData) != Abi::NoPushPosition; @@ -7958,12 +7974,33 @@ void ShaderResources::layOutHeapStages(std::span shaders) if (dword < userWords && dword < 64u) state.pushedUserWords |= std::uint64_t{1} << dword; } state.pushedPlaced = static_cast(placed); + state.pushRunUserWords = static_cast(userWords); + const auto runsOf = [&](std::vector& runs, std::size_t split) { + for (std::size_t item = 0; item < placed; ++item) { + const auto dword = program.pushedData[item]; + const bool user = dword < split; + if (!runs.empty()) { + auto& run = runs.back(); + if (run.user == user && run.index + run.count == item && run.dword + run.count == dword) { + ++run.count; + continue; + } + } + runs.push_back({static_cast(item), dword, 1u, user}); + } + }; + runsOf(state.splitPushRuns, userWords); + runsOf(state.wholePushRuns, 0u); } for (auto& elements : addressedElements) elements.clear(); + addressedAllocations.assign(allocations.size(), 0); for (const auto& binding : bindings) { if (!binding.addressed) continue; Require(binding.dataStage < addressedElements.size(), "an addressed buffer binding names no data stage"); - for (const auto index : binding.allocations) addressedElements[binding.dataStage].push_back(static_cast(index)); + for (const auto index : binding.allocations) { + addressedElements[binding.dataStage].push_back(static_cast(index)); + addressedAllocations[index] = 1; + } } } From 0433c017515128a3e832d329be13de2d5ff3d738 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 06:39:21 +0530 Subject: [PATCH 193/269] perf(agc): look up a heap draw's buffer address overrides by binary search The draw's override list is sorted by allocation and deduplicated once (the in-place range wins over the snapshot, as before), so each pushed buffer record finds its override with a binary search instead of a scan of the whole list, and the overridden check is one pass. --- .../Graphics/src/ShaderResources.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 02beb1d1e562..09bdee892bb8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -7276,12 +7276,13 @@ void ShaderResources::writeDrawSets(DrawBindings& result, std::spanDeviceAddress() + snapshot.offset, snapshot.bytes}}); } for (const auto& [index, range] : inPlace) overrides.push_back({index, range}); - bool overridden = false; - for (const auto& [index, range] : overrides) { - if (index >= addressedAllocations.size() || !addressedAllocations[index]) continue; - const auto* last = result.AddressOverride(index); - overridden = overridden || last->address != 0; + for (std::size_t next = 1; next < overrides.size(); ++next) { + for (auto at = next; at > 0 && overrides[at - 1].first > overrides[at].first; --at) std::swap(overrides[at - 1], overrides[at]); } + const auto last = std::unique(overrides.rbegin(), overrides.rend(), [](const auto& a, const auto& b) { return a.first == b.first; }); + overrides.erase(overrides.begin(), last.base()); + bool overridden = false; + for (const auto& [index, range] : overrides) overridden = overridden || (index < addressedAllocations.size() && addressedAllocations[index] && range.address != 0); if (overridden) { result.heapOffsets = heapOffsets; result.addressOffsets = true; @@ -7292,10 +7293,8 @@ void ShaderResources::writeDrawSets(DrawBindings& result, std::spanfirst == allocation) return &entry->second; - } - return nullptr; + const auto entry = std::lower_bound(addressOverrides.begin(), addressOverrides.end(), allocation, [](const auto& item, std::size_t index) { return item.first < index; }); + return entry != addressOverrides.end() && entry->first == allocation ? &entry->second : nullptr; } void ShaderResources::writeRewrittenSets(DrawBindings& result, std::span selected, const BdaResources* faultRecord) const { From 93a0e7c4a9b9abcfd4ed670a3e92da4d6ab37fbd Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 06:58:18 +0530 Subject: [PATCH 194/269] perf(agc): keep a depth surface's plane sizes instead of recomputing them per overlap check DepthSurface::Overlaps and the other plane-range checks called DepthSliceBytes for the depth and the stencil plane on every call, over every surface. The target is const, so the sizes are taken once at construction. --- .../libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp index 0eeb0b438054..7b316f302c69 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp @@ -1694,6 +1694,8 @@ class DepthSurface { const Context context; const DepthTarget target; const VkFormat hostFormat; + const std::uint64_t depthPlaneBytes = DepthSliceBytes(target.extent, target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT ? 2u : 4u); + const std::uint64_t stencilPlaneBytes = DepthSliceBytes(target.extent, 1u); VkImage image = VK_NULL_HANDLE; VkImageView view = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; @@ -2022,12 +2024,11 @@ class DepthSurface { } std::uint64_t depthBytes() const { - const bool d16 = target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT; - return DepthSliceBytes(target.extent, d16 ? 2u : 4u); + return depthPlaneBytes; } std::uint64_t stencilBytes() const { - return DepthSliceBytes(target.extent, 1u); + return stencilPlaneBytes; } PlaneStorage mirrorPlane; PlaneStorage stencilMirror; From c9a4ea4d87f4c83805378f8d1b3d88d4473baa70 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 06:58:18 +0530 Subject: [PATCH 195/269] perf(agc): find the pending storage images that overlap a range through a sorted index The pending storage list kept merged ranges that only said whether anything might overlap; on a hit, FlushPending's nothing-to-store check, otherPendingOverlaps, PendingStorageOverlaps, AnyPendingOverlaps, AnyPendingUnitsOverlap and ScanPending walked every pending image. GTA V runs about 600k such checks per 10 s on the draw committer, most of them for a range that an image being refreshed overlaps itself. PendingRangeIndex keeps the pending images sorted by base address with the running maximum of their ends; a query does one binary search and walks back only while an earlier image can still reach the range, the way Ryujinx's range lists answer overlap queries. The list rebuilds it with its merged ranges whenever it changes. ScanPending's first match in list order is kept through each entry's list position. Scans that store or erase images while they iterate keep the list order and are unchanged. Tested: agc_pending_range_index compares the index with a full scan on 2000 random lists of up to 40 ranges, 200 queries each, plus edge cases. The default and heap AGC suites pass; with the index answering "none" 69 storage, depth and copy tests fail. --- .../Graphics/include/PendingRangeIndex.hpp | 84 +++++++++++++++++ .../libSceAgcDriver/Graphics/src/Texture.cpp | 58 +++++++----- .../tests/PendingRangeIndex.cpp | 93 +++++++++++++++++++ .../cmake/agc_pending_range_index_tests.cmake | 10 ++ 4 files changed, 220 insertions(+), 25 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_pending_range_index_tests.cmake diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp new file mode 100644 index 000000000000..f78de44ba04b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp @@ -0,0 +1,84 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +template +class PendingRangeIndex { +public: + struct Entry { + std::uint64_t begin = 0; + std::uint64_t end = 0; + Item item{}; + std::size_t position = 0; + }; + + void Clear() { + entries.clear(); + reach.clear(); + } + + void Add(std::uint64_t begin, std::uint64_t end, Item item, std::size_t position) { + entries.push_back({begin, end, item, position}); + } + + void Seal() { + std::sort(entries.begin(), entries.end(), [](const Entry& a, const Entry& b) { return a.begin != b.begin ? a.begin < b.begin : a.position < b.position; }); + reach.resize(entries.size()); + std::uint64_t furthest = 0; + for (std::size_t index = 0; index < entries.size(); ++index) { + furthest = std::max(furthest, entries[index].end); + reach[index] = furthest; + } + } + + template + bool AnyOverlapping(std::uint64_t address, std::size_t bytes, Visit&& visit) const { + if (bytes == 0 || entries.empty()) return false; + const auto end = bytes > std::numeric_limits::max() - address ? std::numeric_limits::max() : address + bytes; + auto index = static_cast(std::lower_bound(entries.begin(), entries.end(), end, [](const Entry& entry, std::uint64_t value) { return entry.begin < value; }) - entries.begin()); + while (index != 0) { + --index; + if (reach[index] <= address) break; + const auto& entry = entries[index]; + if (entry.end > address && entry.begin < end && visit(entry.item)) return true; + } + return false; + } + + template + void ForEachOverlapping(std::uint64_t address, std::size_t bytes, Visit&& visit) const { + static_cast(AnyOverlapping(address, bytes, [&](const Item& item) { + visit(item); + return false; + })); + } + + template + const Entry* FirstByPosition(std::uint64_t address, std::size_t bytes, Match&& match) const { + const Entry* first = nullptr; + if (bytes == 0 || entries.empty()) return nullptr; + const auto end = bytes > std::numeric_limits::max() - address ? std::numeric_limits::max() : address + bytes; + auto index = static_cast(std::lower_bound(entries.begin(), entries.end(), end, [](const Entry& entry, std::uint64_t value) { return entry.begin < value; }) - entries.begin()); + while (index != 0) { + --index; + if (reach[index] <= address) break; + const auto& entry = entries[index]; + if (entry.end > address && entry.begin < end && match(entry.item) && (first == nullptr || entry.position < first->position)) first = &entry; + } + return first; + } + + std::size_t Size() const { return entries.size(); } + +private: + std::vector entries; + std::vector reach; +}; + +} diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index 96d9210278cc..6958c81fc8b5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" +#include "prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp" #include "prx/libSceAgcDriver/Execution/include/AsyncLog.hpp" #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" @@ -1835,6 +1836,17 @@ class PendingList { if (indexed != version) rebuild(); return !textures.empty() && Overlaps(ranges, address, bytes); } + template + bool AnyOverlapping(std::uint64_t address, std::size_t bytes, Visit&& visit) { + if (indexed != version) rebuild(); + return index.AnyOverlapping(address, bytes, visit); + } + template + StorageTexture* FirstOverlapping(std::uint64_t address, std::size_t bytes, Match&& match) { + if (indexed != version) rebuild(); + const auto* entry = index.FirstByPosition(address, bytes, match); + return entry != nullptr ? entry->item : nullptr; + } bool SurelyClear(std::uint64_t address, std::size_t bytes) const { const auto current = published.load(std::memory_order_acquire); return current != nullptr && current->version == changes.load(std::memory_order_acquire) && !Overlaps(current->ranges, address, bytes); @@ -1860,7 +1872,15 @@ class PendingList { void rebuild() { ranges.clear(); - for (const auto* texture : textures) ranges.emplace_back(texture->Descriptor().baseAddress, texture->Descriptor().baseAddress + texture->GuestBytes()); + index.Clear(); + for (std::size_t position = 0; position < textures.size(); ++position) { + auto* texture = textures[position]; + const auto begin = texture->Descriptor().baseAddress; + const auto end = begin + texture->GuestBytes(); + ranges.emplace_back(begin, end); + index.Add(begin, end, texture, position); + } + index.Seal(); std::sort(ranges.begin(), ranges.end()); std::size_t merged = 0; for (const auto& range : ranges) { @@ -1873,6 +1893,7 @@ class PendingList { } std::vector textures; Ranges ranges; + PendingRangeIndex index; std::uint64_t version = 0; std::uint64_t indexed = ~std::uint64_t{0}; std::atomic changes{0}; @@ -2857,7 +2878,7 @@ bool StorageTexture::otherPendingOverlaps() const { auto& pending = Pending(); std::lock_guard lock(pending.mutex); const auto other = [&](const StorageTexture* texture) { return texture != this && texture->overlaps(descriptor.baseAddress, static_cast(guestBytes)); }; - return std::any_of(pending.textures.begin(), pending.textures.end(), other) || std::any_of(pending.flushing.begin(), pending.flushing.end(), other); + return pending.textures.AnyOverlapping(descriptor.baseAddress, static_cast(guestBytes), [&](const StorageTexture* texture) { return texture != this; }) || std::any_of(pending.flushing.begin(), pending.flushing.end(), other); } bool StorageTexture::refreshProved() { @@ -4959,7 +4980,7 @@ bool StorageTexture::FlushPending(std::uint64_t address, std::size_t bytes, cons if (!pending.textures.SurelyClear(address, bytes)) { std::lock_guard lock(pending.mutex); const auto* exempt = Refreshing::Get(); - if (pending.textures.MayOverlap(address, bytes) && std::any_of(pending.textures.begin(), pending.textures.end(), [&](const StorageTexture* texture) { return texture != except && texture != exempt && texture->overlaps(address, bytes) && texture->pendingUnitInside(address, bytes); })) return false; + if (pending.textures.AnyOverlapping(address, bytes, [&](const StorageTexture* texture) { return texture != except && texture != exempt && texture->pendingUnitInside(address, bytes); })) return false; if (pending.flushingCount.load(std::memory_order_acquire) != 0) return false; } return scope == PublishScope::None || !AnyShadowedOverlaps(address, bytes); @@ -5662,14 +5683,7 @@ std::shared_ptr StorageTexture::FindPendingSlice(std::uint64_t a bool PendingStorageOverlaps(std::uint64_t address, std::size_t bytes, const StorageTexture* except) { auto& pending = Pending(); std::lock_guard lock(pending.mutex); - if (!pending.textures.MayOverlap(address, bytes)) return false; - for (const auto* texture : pending.textures) { - // A free function (declared in ShaderResources.hpp): the overlap is computed from the public - // surface description rather than the private helper. - const auto begin = texture->Descriptor().baseAddress; - if (texture != except && address < begin + texture->GuestBytes() && begin < address + bytes) return true; - } - return false; + return pending.textures.AnyOverlapping(address, bytes, [&](const StorageTexture* texture) { return texture != except; }); } std::uint64_t StorageTexture::StampKeepingNewerResults(std::uint64_t address, std::size_t bytes, std::uint64_t recorded, const std::function& stamp) { @@ -5777,10 +5791,8 @@ bool StorageTexture::AnyPendingOverlaps(std::span range.first && pending.textures.MayOverlap(range.first, static_cast(range.second - range.first)); })) { - for (const auto* texture : pending.textures) { - if (overlapsAny(texture)) return true; - } + for (const auto& [begin, end] : ranges) { + if (end > begin && pending.textures.AnyOverlapping(begin, static_cast(end - begin), [](const StorageTexture*) { return true; })) return true; } for (const auto* texture : pending.flushing) { if (overlapsAny(texture)) return true; @@ -5797,14 +5809,14 @@ bool StorageTexture::AnyPendingUnitsOverlap(std::spanoverlaps(begin, bytes)) return true; } - if (!pending.textures.MayOverlap(begin, bytes)) continue; - for (const auto* texture : pending.textures) { - if (!texture->overlaps(begin, bytes)) continue; + const auto unitPending = [&](const StorageTexture* texture) { for (std::uint32_t layer = 0; layer < texture->trackedLayers; ++layer) { const auto unit = texture->layerBegin(layer); if (texture->layerPending[layer] && unit < end && begin < unit + texture->layerBytes(layer)) return true; } - } + return false; + }; + if (pending.textures.AnyOverlapping(begin, bytes, unitPending)) return true; } return false; } @@ -6016,12 +6028,8 @@ bool StorageTexture::ScanPending(std::span queries) { query.found = nullptr; if (query.end <= query.begin) continue; const auto bytes = static_cast(query.end - query.begin); - if (pending.textures.MayOverlap(query.begin, bytes)) { - for (const auto* texture : pending.textures) { - if (query.found == nullptr && texture->descriptor.baseAddress == query.begin && texture->guestBytes >= bytes) query.found = texture; - if (texture != query.except && texture->overlaps(query.begin, bytes)) query.overlaps = true; - } - } + query.found = pending.textures.FirstOverlapping(query.begin, bytes, [&](const StorageTexture* texture) { return texture->descriptor.baseAddress == query.begin && texture->guestBytes >= bytes; }); + query.overlaps = pending.textures.AnyOverlapping(query.begin, bytes, [&](const StorageTexture* texture) { return texture != query.except; }); for (const auto* texture : pending.flushing) { if (texture != query.except && texture->overlaps(query.begin, bytes)) query.overlaps = true; } diff --git a/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp b/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp new file mode 100644 index 000000000000..b82b169eeab6 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp @@ -0,0 +1,93 @@ +#include "prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp" +#include +#include +#include +#include +#include + +namespace { + +struct Range { + std::uint64_t begin; + std::uint64_t end; +}; + +bool Overlaps(const Range& range, std::uint64_t address, std::size_t bytes) { + return bytes != 0 && address < range.end && range.begin < address + bytes; +} + +void Require(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +void RandomAgainstScan() { + std::mt19937_64 random(0x5eed); + for (int round = 0; round < 2000; ++round) { + const auto count = static_cast(random() % 40); + std::vector ranges; + AgcDriver::Graphics::PendingRangeIndex index; + for (std::size_t item = 0; item < count; ++item) { + const auto begin = (random() % 4096) * 64; + const auto bytes = 1 + random() % (random() % 4 == 0 ? 65536 : 4096); + ranges.push_back({begin, begin + bytes}); + index.Add(begin, begin + bytes, item, item); + } + index.Seal(); + for (int query = 0; query < 200; ++query) { + const auto address = (random() % 4200) * 64 + random() % 64; + const auto bytes = static_cast(random() % 8 == 0 ? 0 : random() % 20000); + const auto except = static_cast(random() % (count + 1)); + bool scanned = false; + std::size_t firstScanned = count; + std::vector scannedSet(count, false); + for (std::size_t item = 0; item < count; ++item) { + if (!Overlaps(ranges[item], address, bytes)) continue; + scannedSet[item] = true; + if (item == except) continue; + scanned = true; + if (firstScanned == count) firstScanned = item; + } + const bool indexed = index.AnyOverlapping(address, bytes, [&](std::size_t item) { return item != except; }); + Require(indexed == scanned, "the index and the scan disagree on whether a range overlaps"); + std::vector visited(count, false); + index.ForEachOverlapping(address, bytes, [&](std::size_t item) { + Require(!visited[item], "the index visited an item twice"); + visited[item] = true; + }); + Require(visited == scannedSet, "the index visited a different set of overlapping items than the scan"); + const auto* first = index.FirstByPosition(address, bytes, [&](std::size_t item) { return item != except; }); + Require((first == nullptr) == (firstScanned == count), "the index and the scan disagree on the first overlapping item"); + Require(first == nullptr || first->item == firstScanned, "the index named a later item than the first overlapping one"); + } + } +} + +void Edges() { + AgcDriver::Graphics::PendingRangeIndex index; + index.Add(100, 200, 1, 0); + index.Add(0, 1000, 2, 1); + index.Add(300, 301, 3, 2); + index.Seal(); + const auto any = [&](std::uint64_t address, std::size_t bytes, int skip) { return index.AnyOverlapping(address, bytes, [&](int item) { return item != skip; }); }; + Require(any(500, 1, 0), "a long earlier range covering the query was missed"); + Require(!any(500, 1, 2), "an excluded item was reported"); + Require(any(200, 101, 2), "a one-byte range at the end of the query was missed"); + Require(!any(200, 100, 2), "a range touching the query's end was reported as overlapping"); + Require(!any(1000, 10, -1), "a range ending at the query's start was reported as overlapping"); + Require(!any(150, 0, -1), "an empty query overlapped"); + Require(any(~std::uint64_t{0} - 5, 100, -1) == false, "a query past the address space overlapped"); +} + +} + +int main() { + try { + Edges(); + RandomAgainstScan(); + std::cout << "pending range index tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "pending range index test failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pending_range_index_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pending_range_index_tests.cmake new file mode 100644 index 000000000000..5e073f4d18f5 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pending_range_index_tests.cmake @@ -0,0 +1,10 @@ +if(BUILD_TESTING) + add_test_executable(agc_pending_range_index_tests + tests/PendingRangeIndex.cpp + ) + target_include_directories(agc_pending_range_index_tests PRIVATE ${LIBS_INCLUDE_DIR}) + set_target_properties(agc_pending_range_index_tests PROPERTIES CXX_EXTENSIONS OFF) + configure_windows_unwind(agc_pending_range_index_tests) + add_test(NAME agc_pending_range_index COMMAND agc_pending_range_index_tests) + set_tests_properties(agc_pending_range_index PROPERTIES TIMEOUT 30) +endif() From 6d6465d81270391052e104d7073bec7d0b040b97 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 06:58:18 +0530 Subject: [PATCH 196/269] perf(agc): set a storage image's pending-since generation in one fill when no layer is kept for the CPU markLayersPending looked up keptAtUnwatch once per layer to skip layers kept for the CPU; GTA V marks about 600k times per 10 s, about 30 layers each for array images. With nothing kept the whole range takes the tracker generation in one fill. --- core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index 6958c81fc8b5..cd3e3dd10173 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -4568,8 +4568,12 @@ void StorageTexture::markLayersPending(std::uint32_t first, std::uint32_t count) layerPending.SetRange(first, count, true); } const auto pendingSince = GuestMemory::TrackerGeneration(); - for (std::uint32_t layer = first; layer < first + count; ++layer) { - if (!keptForCpu(layer)) layerPendingSince[layer] = pendingSince; + if (keptAtUnwatch.empty()) { + std::fill(layerPendingSince.begin() + first, layerPendingSince.begin() + first + count, pendingSince); + } else { + for (std::uint32_t layer = first; layer < first + count; ++layer) { + if (!keptForCpu(layer)) layerPendingSince[layer] = pendingSince; + } } // Results of this image now cover the alias's results borrowed into these units: this image // stores them, the alias no longer has to (its results, unchanged since the borrow, are in From bbffef5822ef139f6104ca9920fc8d278028825c Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 07:20:23 +0530 Subject: [PATCH 197/269] perf(agc): let a storage refresh keep its proof when another pending image only overlaps its bounds takeRefreshProof and refreshProved refused the proof whenever another pending storage image overlapped this one's bytes, even when that image's pending layers were elsewhere. GTA V with the heap on refused 104k of 118k refreshes per 10 s this way and took the slow full refresh instead. Another pending image now blocks the proof only when its pending layers touch this image's bytes; images with DCC metadata still always block, because their store writes the whole range. Since a proof no longer covers every overlapping pending image, an image that gains new pending layers bumps the pending serial, so proofs re-check before they are used. Tested: depth_plane_proof_under_other_pending proves a refresh under an array pending on another layer, and refuses it after the array gains a pending layer over the image. It fails with either half reverted. The default and heap AGC suites pass. --- .../libSceAgcDriver/Graphics/src/Texture.cpp | 8 +-- ...iver_depth_plane_partial_store_tests.cmake | 7 +++ .../execution/DepthPlanePartialStore.cpp | 50 +++++++++++++++++++ 3 files changed, 62 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index cd3e3dd10173..fb0c5b042a32 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -2878,7 +2878,8 @@ bool StorageTexture::otherPendingOverlaps() const { auto& pending = Pending(); std::lock_guard lock(pending.mutex); const auto other = [&](const StorageTexture* texture) { return texture != this && texture->overlaps(descriptor.baseAddress, static_cast(guestBytes)); }; - return pending.textures.AnyOverlapping(descriptor.baseAddress, static_cast(guestBytes), [&](const StorageTexture* texture) { return texture != this; }) || std::any_of(pending.flushing.begin(), pending.flushing.end(), other); + const auto pendingHere = [&](const StorageTexture* texture) { return texture != this && (texture->descriptor.dccAddress != 0 || texture->pendingUnitInside(descriptor.baseAddress, static_cast(guestBytes))); }; + return pending.textures.AnyOverlapping(descriptor.baseAddress, static_cast(guestBytes), pendingHere) || std::any_of(pending.flushing.begin(), pending.flushing.end(), other); } bool StorageTexture::refreshProved() { @@ -4523,7 +4524,8 @@ void StorageTexture::markLayersPending(std::uint32_t first, std::uint32_t count) } std::optional publication; if (!layerPending.Any()) publication.emplace(descriptor.baseAddress, guestBytes); - if (!layerPending.AllIn(first, count)) { + const bool newUnits = !layerPending.AllIn(first, count); + if (newUnits) { std::vector unsaved; bool anyUnsaved = false; const bool trims = CommitTrims(); @@ -4615,7 +4617,7 @@ void StorageTexture::markLayersPending(std::uint32_t first, std::uint32_t count) if (const auto format = ResolveTextureFormat(descriptor.format); format == VK_FORMAT_R8_UINT || format == VK_FORMAT_R8_UNORM) eightBitWrites().fetch_add(1, std::memory_order_release); const bool wasLent = std::exchange(lent, false); if (dirty) { - if (wasLent) BumpPendingSerial(); + if (wasLent || newUnits) BumpPendingSerial(); return; } dirty = true; diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_partial_store_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_partial_store_tests.cmake index cf198b5fdd33..5f6306d47b77 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_partial_store_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_partial_store_tests.cmake @@ -1,4 +1,11 @@ if(BUILD_TESTING) + add_test(NAME agc_driver_depth_plane_proof_under_other_pending COMMAND agc_driver_depth_plane_partial_store_tests --proof-under-other-pending) + set_tests_properties(agc_driver_depth_plane_proof_under_other_pending PROPERTIES + ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + if(WIN32) + set_tests_properties(agc_driver_depth_plane_proof_under_other_pending PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test(NAME agc_driver_depth_plane_cpu_write_after_page_unwatch COMMAND agc_driver_depth_plane_partial_store_tests --cpu-write-after-page-unwatch) set_tests_properties(agc_driver_depth_plane_cpu_write_after_page_unwatch PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlanePartialStore.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlanePartialStore.cpp index 515947e791c0..f11e1ac07c4f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlanePartialStore.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlanePartialStore.cpp @@ -250,6 +250,56 @@ int main(int argc, char** argv) { return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--proof-under-other-pending") { + auto* arrayBlocks = static_cast(AllocateBlocks(3u * PlaneBytes, true)); + if (!AgcDriver::GuestMemory::WriteWatched() || !AgcDriver::GuestMemory::Watched(reinterpret_cast(arrayBlocks), 3u * PlaneBytes)) return VulkanTestSkipped; + AgcDriver::Graphics::GuestTextureResource array{}; + array.baseAddress = reinterpret_cast(arrayBlocks); + array.width = PlaneWidth; + array.height = PlaneHeight; + array.depthOrLastArray = 2; + array.mipCount = 1; + array.tileMode = AgcDriver::Graphics::TextureTileMode::kR64KBX; + array.dimension = AgcDriver::Graphics::TextureDimension::k2DArray; + array.format = 22; + array.dstSelX = 4; + array.dstSelY = 5; + array.dstSelZ = 6; + array.dstSelW = 7; + auto last = array; + last.baseAddress = array.baseAddress + 2u * PlaneBytes; + last.depthOrLastArray = 0; + last.dimension = AgcDriver::Graphics::TextureDimension::k2D; + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(*device); + const auto lookup = [&](const AgcDriver::Graphics::GuestTextureResource& resource, std::uint32_t count) { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + return AgcDriver::Graphics::CachedStorageLayers(context, resource, 0, count); + }; + for (std::size_t layer = 0; layer < 3u; ++layer) Fill(reinterpret_cast(arrayBlocks + layer * PlaneBytes), 1.0f); + const auto whole = lookup(array, 3); + const auto single = lookup(last, 1); + Require(whole != nullptr && single != nullptr && whole != single, "the array and the image over its last layer did not get two cached images"); + device->WaitIdle(); + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + whole->MarkSliceDirty(0, 1); + } + static_cast(lookup(last, 1)); + auto proved = AgcDriver::Graphics::StorageTexture::RefreshesProved(); + Require(lookup(last, 1) == single, "a lookup of the image over the last layer replaced its cached image"); + Require(AgcDriver::Graphics::StorageTexture::RefreshesProved() != proved, "an array pending only on its first layer kept the image over its last layer from proving its refresh"); + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + whole->MarkSliceDirty(2, 1); + } + proved = AgcDriver::Graphics::StorageTexture::RefreshesProved(); + static_cast(lookup(last, 1)); + Require(AgcDriver::Graphics::StorageTexture::RefreshesProved() == proved, "an image kept its refresh proof after the array under it gained a pending write over its bytes"); + device->WaitIdle(); + std::puts("depth plane partial store tests passed (refresh proof under another pending image)"); + return 0; + } + Fill(plane, 1.0f); Require(draw(depth, writeHalf) == PlaneTexels, "the draw writing depth 0.5 did not cover the plane"); Require(AgcDriver::Graphics::DepthPlanesStale(), "the draw writing depth left the plane unregistered"); From 56033b9a9d0c03c06181d20a4bf507b22518aca2 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 07:30:02 +0530 Subject: [PATCH 198/269] perf(agc): keep the pending range index sorted as images join and leave the list The pending storage list rebuilt its range index from scratch on every change: a sort of the index plus a second sort of the merged ranges. GTA V changes the list often enough that the rebuild cost 0.26 ms per frame on the draw committer. The index now takes a binary insert when an image joins and an erase when it leaves, recomputing the running end only from that point on. List order for ScanPending's first match comes from a counter that only grows, so erases need no renumbering. The merged ranges for SurelyClear are read off the already-sorted index instead of sorted again. Tested: agc_pending_range_index also runs 20000 random inserts and erases against a full scan (fails if an insert skips recomputing the running end). The default and heap AGC suites pass. --- .../Graphics/include/PendingRangeIndex.hpp | 32 +++++++++++++ .../libSceAgcDriver/Graphics/src/Texture.cpp | 37 +++++++-------- .../tests/PendingRangeIndex.cpp | 47 +++++++++++++++++++ 3 files changed, 97 insertions(+), 19 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp index f78de44ba04b..b0c2e1056cca 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include namespace AgcDriver::Graphics { @@ -37,6 +38,29 @@ class PendingRangeIndex { } } + void Insert(std::uint64_t begin, std::uint64_t end, Item item, std::size_t position) { + const auto at = std::upper_bound(entries.begin(), entries.end(), std::pair{begin, position}, [](const std::pair& key, const Entry& entry) { return key.first != entry.begin ? key.first < entry.begin : key.second < entry.position; }); + const auto index = static_cast(at - entries.begin()); + entries.insert(at, {begin, end, item, position}); + reach.insert(reach.begin() + static_cast(index), 0); + recompute(index); + } + + bool Erase(std::uint64_t begin, const Item& item) { + auto at = std::lower_bound(entries.begin(), entries.end(), begin, [](const Entry& entry, std::uint64_t value) { return entry.begin < value; }); + for (; at != entries.end() && at->begin == begin; ++at) { + if (!(at->item == item)) continue; + const auto index = static_cast(at - entries.begin()); + entries.erase(at); + reach.erase(reach.begin() + static_cast(index)); + recompute(index); + return true; + } + return false; + } + + const std::vector& Entries() const { return entries; } + template bool AnyOverlapping(std::uint64_t address, std::size_t bytes, Visit&& visit) const { if (bytes == 0 || entries.empty()) return false; @@ -77,6 +101,14 @@ class PendingRangeIndex { std::size_t Size() const { return entries.size(); } private: + void recompute(std::size_t from) { + std::uint64_t furthest = from == 0 ? 0 : reach[from - 1]; + for (std::size_t index = from; index < entries.size(); ++index) { + furthest = std::max(furthest, entries[index].end); + reach[index] = furthest; + } + } + std::vector entries; std::vector reach; }; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index fb0c5b042a32..546e577359a9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -31,6 +31,7 @@ #include "RdnaDecoder/include/RdnaDecoder/RdnaDescriptorFormat.hpp" #include "IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/BufferFormat.hpp" #include +#include #include #include #include @@ -1822,15 +1823,21 @@ class PendingList { iterator end() { return textures.end(); } void push_back(StorageTexture* texture) { textures.push_back(texture); + const auto begin = texture->Descriptor().baseAddress; + index.Insert(begin, begin + texture->GuestBytes(), texture, nextOrder++); changed(); } iterator erase(iterator it) { + unindex(*it); const auto next = textures.erase(it); changed(); return next; } void remove(const StorageTexture* texture) { - if (std::erase(textures, texture) != 0) changed(); + if (std::find(textures.begin(), textures.end(), texture) == textures.end()) return; + unindex(const_cast(texture)); + std::erase(textures, texture); + changed(); } bool MayOverlap(std::uint64_t address, std::size_t bytes) { if (indexed != version) rebuild(); @@ -1838,12 +1845,10 @@ class PendingList { } template bool AnyOverlapping(std::uint64_t address, std::size_t bytes, Visit&& visit) { - if (indexed != version) rebuild(); return index.AnyOverlapping(address, bytes, visit); } template StorageTexture* FirstOverlapping(std::uint64_t address, std::size_t bytes, Match&& match) { - if (indexed != version) rebuild(); const auto* entry = index.FirstByPosition(address, bytes, match); return entry != nullptr ? entry->item : nullptr; } @@ -1870,30 +1875,24 @@ class PendingList { changes.store(version, std::memory_order_release); } + void unindex(StorageTexture* texture) { + const bool found = index.Erase(texture->Descriptor().baseAddress, texture); + assert(found); + static_cast(found); + } void rebuild() { ranges.clear(); - index.Clear(); - for (std::size_t position = 0; position < textures.size(); ++position) { - auto* texture = textures[position]; - const auto begin = texture->Descriptor().baseAddress; - const auto end = begin + texture->GuestBytes(); - ranges.emplace_back(begin, end); - index.Add(begin, end, texture, position); - } - index.Seal(); - std::sort(ranges.begin(), ranges.end()); - std::size_t merged = 0; - for (const auto& range : ranges) { - if (merged != 0 && range.first <= ranges[merged - 1].second) ranges[merged - 1].second = std::max(ranges[merged - 1].second, range.second); - else ranges[merged++] = range; - } - ranges.resize(merged); + for (const auto& entry : index.Entries()) { + if (!ranges.empty() && entry.begin <= ranges.back().second) ranges.back().second = std::max(ranges.back().second, entry.end); + else ranges.emplace_back(entry.begin, entry.end); + } indexed = version; published.store(std::make_shared(Snapshot{version, ranges}), std::memory_order_release); } std::vector textures; Ranges ranges; PendingRangeIndex index; + std::size_t nextOrder = 0; std::uint64_t version = 0; std::uint64_t indexed = ~std::uint64_t{0}; std::atomic changes{0}; diff --git a/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp b/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp index b82b169eeab6..45b424fa6011 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp" +#include #include #include #include @@ -62,6 +63,51 @@ void RandomAgainstScan() { } } +void InsertEraseAgainstScan() { + std::mt19937_64 random(0xfeed); + struct Live { + std::uint64_t begin; + std::uint64_t end; + int item; + }; + AgcDriver::Graphics::PendingRangeIndex index; + std::vector list; + int nextItem = 0; + std::size_t order = 0; + for (int step = 0; step < 20000; ++step) { + if (list.empty() || random() % 3 != 0) { + const auto begin = (random() % 256) * 4096; + const auto end = begin + 1 + random() % (random() % 5 == 0 ? 262144 : 16384); + list.push_back({begin, end, nextItem}); + index.Insert(begin, end, nextItem++, order++); + } else { + const auto at = static_cast(random() % list.size()); + Require(index.Erase(list[at].begin, list[at].item), "the index lost an entry it was given"); + list.erase(list.begin() + static_cast(at)); + } + Require(index.Size() == list.size(), "the index holds a different number of entries than the list"); + Require(!index.Erase(1u << 30, -1), "the index erased an entry it was never given"); + for (int query = 0; query < 8; ++query) { + const auto address = (random() % 300) * 4096 + random() % 4096; + const auto bytes = static_cast(random() % 70000); + int firstScanned = -1; + std::size_t overlapping = 0; + for (const auto& live : list) { + if (!Overlaps({live.begin, live.end}, address, bytes)) continue; + ++overlapping; + if (firstScanned < 0 && live.item % 2 == 0) firstScanned = live.item; + } + std::size_t visited = 0; + index.ForEachOverlapping(address, bytes, [&](int) { ++visited; }); + Require(visited == overlapping, "after inserts and erases the index visited a different number of overlapping entries than the scan"); + const auto* first = index.FirstByPosition(address, bytes, [](int item) { return item % 2 == 0; }); + Require((first == nullptr ? -1 : first->item) == firstScanned, "after inserts and erases the index named a different first match than the list order"); + } + const auto& entries = index.Entries(); + for (std::size_t at = 1; at < entries.size(); ++at) Require(entries[at - 1].begin <= entries[at].begin, "the index entries are out of base order"); + } +} + void Edges() { AgcDriver::Graphics::PendingRangeIndex index; index.Add(100, 200, 1, 0); @@ -84,6 +130,7 @@ int main() { try { Edges(); RandomAgainstScan(); + InsertEraseAgainstScan(); std::cout << "pending range index tests passed\n"; return 0; } catch (const std::exception& error) { From bdd18b93059a72c0e9c0880ea26343fc5b5ea608 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 07:30:02 +0530 Subject: [PATCH 199/269] perf(agc): answer a pending-image overlap check without the lock when nothing pending is near StorageTexture::AnyPendingOverlaps took the pending list's mutex on every call; GTA V calls it about 980k times per 10 s, 770k of them from Recorder::ReadsSettled, and most reads touch no pending image. It now first asks the published merged ranges (SurelyClear) without the lock, the way FlushPending's nothing-to-store check already does, re-reading the flushing count after, and only falls back to the locked query when that cannot say no. The locked path publishes the ranges, so later checks can take the fast path. Tested: the default and heap AGC suites pass. --- .../prx/libSceAgcDriver/Graphics/src/Texture.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index 546e577359a9..8282f31129b6 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -1852,6 +1852,9 @@ class PendingList { const auto* entry = index.FirstByPosition(address, bytes, match); return entry != nullptr ? entry->item : nullptr; } + void Publish() { + if (indexed != version) rebuild(); + } bool SurelyClear(std::uint64_t address, std::size_t bytes) const { const auto current = published.load(std::memory_order_acquire); return current != nullptr && current->version == changes.load(std::memory_order_acquire) && !Overlaps(current->ranges, address, bytes); @@ -5789,7 +5792,16 @@ std::uint64_t StorageTexture::StampKeepingNewerResults(std::uint64_t address, st bool StorageTexture::AnyPendingOverlaps(std::span> ranges) { if (ranges.empty()) return false; auto& pending = Pending(); + const auto surelyClear = [&] { + if (pending.flushingCount.load(std::memory_order_acquire) != 0) return false; + for (const auto& [begin, end] : ranges) { + if (end > begin && !pending.textures.SurelyClear(begin, static_cast(end - begin))) return false; + } + return pending.flushingCount.load(std::memory_order_acquire) == 0; + }; + if (surelyClear()) return false; std::lock_guard lock(pending.mutex); + pending.textures.Publish(); const auto overlapsAny = [&](const StorageTexture* texture) { for (const auto& [begin, end] : ranges) { if (end > begin && texture->overlaps(begin, static_cast(end - begin))) return true; From bf28d721f025659c9c718a326d6bfedbf57f8603 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 07:30:02 +0530 Subject: [PATCH 200/269] perf(agc): walk only the pending images a label readback can store StoreReadbackBeforeLabel ran twice over the whole pending list on every label (about 80k times per 10 s in GTA V) to find the linear and small images it stores and the occasionally written ones up to 1 MiB. The list now keeps those candidates, in list order, as images join and leave, and the label walks only them; the rules for which ones it stores are unchanged. Tested: the default and heap AGC suites pass. --- .../prx/libSceAgcDriver/Graphics/src/Texture.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index 8282f31129b6..ab8cbfa1bb64 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -1823,6 +1823,7 @@ class PendingList { iterator end() { return textures.end(); } void push_back(StorageTexture* texture) { textures.push_back(texture); + if (LabelCandidate(texture)) labelCandidates.push_back(texture); const auto begin = texture->Descriptor().baseAddress; index.Insert(begin, begin + texture->GuestBytes(), texture, nextOrder++); changed(); @@ -1852,6 +1853,10 @@ class PendingList { const auto* entry = index.FirstByPosition(address, bytes, match); return entry != nullptr ? entry->item : nullptr; } + static bool LabelCandidate(const StorageTexture* texture) { + return texture->Descriptor().tileMode == TextureTileMode::kLinear || texture->GuestBytes() <= StorageTexture::OccasionalStoreBytes; + } + const std::vector& LabelCandidates() const { return labelCandidates; } void Publish() { if (indexed != version) rebuild(); } @@ -1879,6 +1884,7 @@ class PendingList { } void unindex(StorageTexture* texture) { + if (LabelCandidate(texture)) std::erase(labelCandidates, texture); const bool found = index.Erase(texture->Descriptor().baseAddress, texture); assert(found); static_cast(found); @@ -1893,6 +1899,7 @@ class PendingList { published.store(std::make_shared(Snapshot{version, ranges}), std::memory_order_release); } std::vector textures; + std::vector labelCandidates; Ranges ranges; PendingRangeIndex index; std::size_t nextOrder = 0; @@ -5563,7 +5570,8 @@ void StorageTexture::StoreReadbackBeforeLabel(const char* reason, VkDevice devic return std::any_of(pending.textures.begin(), pending.textures.end(), sharesStored) || std::any_of(pending.flushing.begin(), pending.flushing.end(), shares); }; #endif - for (const auto* texture : pending.textures) { + const auto& candidates = pending.textures.LabelCandidates(); + for (const auto* texture : candidates) { if (texture->descriptor.tileMode != TextureTileMode::kLinear && texture->guestBytes > SmallStoreBytes) continue; #if defined(__APPLE__) if (trap && !sharesPage(texture) && (texture->readTrapped.load(std::memory_order_acquire) || !DirectMemoryAliased_nid_postfix(static_cast(texture->descriptor.baseAddress), static_cast(texture->guestBytes))) && GuestWriteWatch::GuestWriteWatchTrapReads_nid_postfix(static_cast(texture->descriptor.baseAddress), static_cast(texture->guestBytes))) { @@ -5573,7 +5581,7 @@ void StorageTexture::StoreReadbackBeforeLabel(const char* reason, VkDevice devic #endif ranges.emplace_back(texture->descriptor.baseAddress, static_cast(texture->guestBytes)); } - for (auto* texture : pending.textures) { + for (auto* texture : candidates) { if (texture->descriptor.tileMode == TextureTileMode::kLinear || texture->guestBytes <= SmallStoreBytes || texture->guestBytes > OccasionalStoreBytes) continue; if (device != VK_NULL_HANDLE && texture->context.device != device) continue; if (!texture->writtenOccasionally.exchange(false, std::memory_order_relaxed)) continue; From b92b489ce08543034d6e8118b8cfb73d135ad49b Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 08:48:43 +0530 Subject: [PATCH 201/269] perf(agc): reuse a heap stage's user block when its inputs did not change, and keep a draw's bound roots with its push image writeSplitHeapStage rebuilt a stage's user block on every draw: a copy of the leading words, the user data and data patches, and the slot words, then compared it with the last one. With the stage's slots current, the same program, and the same leading words and user data, the block is the one built last time, so it is reused without the copy and patching. APS5_VERIFY_GPU_HEAP=1 still builds it in full and throws when the two differ. writeDataRoots scanned every stage's bindings twice per draw to learn whether the page table and the fault buffer are bound. That depends only on the draw's programs, so it is kept with the push image, which already records the programs it was built for. GTA V with the heap on: writeSplitHeapStage and patchHeapSlotWords cost 0.16 ms per frame on the draw committer, and the bindings scans were the visible lines of writeDataRoots' 0.06 ms. Tested: the default and heap AGC suites pass; the heap-mode verify run shows no difference between the reused and the rebuilt user block. --- .../Graphics/include/ShaderResources.hpp | 4 ++ .../Graphics/src/ShaderResources.cpp | 45 ++++++++++++------- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 72a63d803d4e..f257c79ac9c9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -423,6 +423,8 @@ class ShaderResources { }; std::array stages{}; bool valid = false; + bool tableBound = false; + bool faultBound = false; }; mutable PushImage pushImage; // Whether RefreshData would record anything for `shader` (the per-word compare; verification). @@ -800,6 +802,8 @@ class ShaderResources { }; KeptSpan data, flat, map, user; std::vector dataInput; + std::vector userInput; + const void* userProgram = nullptr; struct PushRun { std::uint32_t index = 0; std::uint32_t dword = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 09bdee892bb8..478bc8f19ff7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -7550,17 +7550,9 @@ void ShaderResources::writeDataRoots(std::spanaddressOffsets; const auto& offsets = addressed ? rewritten->heapOffsets : heapOffsets; - VkDeviceAddress table = 0; - VkDeviceAddress fault = 0; const auto binds = [&](ShaderRecompiler::DescriptorRole role) { return std::any_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [&](const auto& binding) { return binding.role == role; }); }); }; - const bool tableBound = binds(ShaderRecompiler::DescriptorRole::BdaPagetable); - const bool faultBound = binds(ShaderRecompiler::DescriptorRole::FaultBuffer); - if (bda != nullptr && (tableBound || faultBound)) { - if (tableBound) table = bda->TableAddress(); - if (faultBound) fault = bda->FaultAddress(); - } Require(placements.size() == shaders.size(), "the push layout does not describe the draw's stages"); std::optional gds; const auto gdsAddress = [&] { @@ -7589,6 +7581,8 @@ void ShaderResources::writeDataRoots(std::spanTableAddress(); + if (faultBound) fault = bda->FaultAddress(); + } const auto target = cached ? std::span(image.bytes) : bytes; bool rooted = false; for (std::size_t index = 0; index < shaders.size(); ++index) { @@ -8263,17 +8265,30 @@ std::pair ShaderResources::writeSplitHeapStage(con stageState.dataOrigin = shader.heap != nullptr ? shader.heap->dataOrigin : 0u; stageState.dataProgram = shader.program; } + const auto userFront = words.first(userWords); + auto& input = stageState.userInput; + const bool sameUserInput = current && stageState.userProgram == shader.program && stageState.user.words.size() == userWords && + input.size() == userWords + userData.size() && std::equal(userFront.begin(), userFront.end(), input.begin()) && + std::equal(userData.begin(), userData.end(), input.begin() + static_cast(userWords)); struct UserStorage {}; - auto& user = HostThreadLocal, UserStorage>(); - user.assign(words.begin(), words.begin() + static_cast(userWords)); - applyUserData(user); - patchHeapSlotWords(shader, stageState, user, current, true); - if (verifySlots && !std::equal(user.begin(), user.end(), patched.begin())) - throw std::runtime_error("AGC graphics: a GPU-mode stage's user-data block differs from the user words of its full shader data"); + auto& built = HostThreadLocal, UserStorage>(); + if (!sameUserInput || verifySlots) { + built.assign(userFront.begin(), userFront.end()); + applyUserData(built); + patchHeapSlotWords(shader, stageState, built, current, true); + if (verifySlots && !std::equal(built.begin(), built.end(), patched.begin())) + throw std::runtime_error("AGC graphics: a GPU-mode stage's user-data block differs from the user words of its full shader data"); + if (verifySlots && sameUserInput && !std::ranges::equal(built, stageState.user.words)) + throw std::runtime_error("AGC graphics: a GPU-mode stage's user-data block changed although its words, user data and slots did not"); + input.assign(userFront.begin(), userFront.end()); + input.insert(input.end(), userData.begin(), userData.end()); + stageState.userProgram = shader.program; + } + const auto& user = sameUserInput ? stageState.user.words : built; const auto counted = std::min(userWords, 64u); const auto userMask = counted == 64u ? ~std::uint64_t{0} : (std::uint64_t{1} << counted) - 1u; const auto pushedUser = stageState.pushedUserWords & userMask; - const bool userChanged = !std::ranges::equal(stageState.user.words, user); + const bool userChanged = !sameUserInput && !std::ranges::equal(stageState.user.words, user); if (userChanged) ++stageState.pushVersion; if (userWords <= 64u && pushedUser == userMask) { if (stageState.user.words.size() == user.size() && userChanged) NotePushedUserDataKeep(); From bcd73c1fb7da44b928718406412a77cfeba78961 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 09:46:31 +0530 Subject: [PATCH 202/269] fix(agc): draw the FSR upscaler through the descriptor heap in heap mode The upscaler bound its source with raw vkCmdBindDescriptorSets and vkCmdPushConstants. In a heap command buffer that leaves descriptor-heap mode without telling the heap-bind tracker, so the next presentation pass skipped rebinding the heaps and drew with none bound (VUID-vkCmdDraw-None-11308, and a crash on lavapipe in agc_driver_present_upscale). In heap mode each upscaler target now also builds a heap pipeline that maps the source sampler onto a heap slot taken through ViewSlot, with the parameters and slot index in push data, as the presentation pass does. ViewSlot takes the image layout, since the upscaler samples its surfaces in SHADER_READ_ONLY_OPTIMAL. When no slot is free the draw falls back to the descriptor set, bound through the driver's CmdBindDescriptorSets and CmdPushConstants wrappers so the tracker stays correct. A surface's slots are released before its view is destroyed. --- .../include/PresentationUpscaler.hpp | 13 +++- .../Execution/src/PresentationUpscaler.cpp | 76 ++++++++++++++----- .../Graphics/include/BindlessHeap.hpp | 2 +- .../Graphics/src/BindlessHeap.cpp | 4 +- 4 files changed, 71 insertions(+), 24 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp index 8b3445b6845b..c5e0ee80c6d5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp @@ -3,6 +3,7 @@ #define VK_NO_PROTOTYPES #include +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include #include @@ -34,6 +35,7 @@ class PresentationUpscaler { struct Target { VkRenderPass renderPass = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + VkPipeline heapPipeline = VK_NULL_HANDLE; }; struct Surface { VkImage image = VK_NULL_HANDLE; @@ -42,7 +44,8 @@ class PresentationUpscaler { VkFormat format = VK_FORMAT_UNDEFINED; VkExtent2D extent{}; }; - struct Slot { + struct Slot : Graphics::HeapSlotOwner { + using Graphics::HeapSlotOwner::ReleaseHeapSlots; Surface stage; Surface upscaled; VkDescriptorSet easuSet = VK_NULL_HANDLE; @@ -51,16 +54,18 @@ class PresentationUpscaler { }; const Target& target(VkFormat format, VkImageLayout finalLayout, Filter filter); - void ensureSurface(Surface& surface, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage); - void releaseSurface(Surface& surface) noexcept; + void ensureSurface(Slot& slot, Surface& surface, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage); + void releaseSurface(Slot& slot, Surface& surface) noexcept; VkImageView createView(VkImage image, VkFormat format, VkImageUsageFlags usage) const; VkFramebuffer transientFramebuffer(Slot& slot, VkRenderPass renderPass, VkImage image, VkFormat format, VkExtent2D extent, VkImageLayout finalLayout); void bindSource(VkDescriptorSet set, VkImageView view) const; - void draw(VkCommandBuffer commands, const Target& target, VkFramebuffer framebuffer, VkExtent2D extent, VkDescriptorSet set, const void* parameters, std::uint32_t size) const; + void draw(VkCommandBuffer commands, Slot& slot, const Target& target, VkFramebuffer framebuffer, VkExtent2D extent, VkDescriptorSet set, VkImageView source, const void* parameters, std::uint32_t size) const; void release() noexcept; Graphics::Context context; float sharpness; + bool heap = false; + VkSamplerCreateInfo samplerInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; VkSampler sampler = VK_NULL_HANDLE; VkDescriptorSetLayout descriptorLayout = VK_NULL_HANDLE; VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp index bd958e5d2f72..5b871305e494 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp @@ -1,12 +1,15 @@ #include "prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp" #include "prx/libSceAgcDriver/Execution/include/AspectFit.hpp" #include "prx/libSceAgcDriver/Execution/include/PresentationPass.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/FsrEasuFrag_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/FsrRcasFrag_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/PresentationPassVert_spv.h" #include #include +#include +#include namespace AgcDriver { namespace { @@ -29,13 +32,20 @@ struct RcasParameters { constexpr std::uint32_t ParameterBytes = sizeof(RcasParameters); static_assert(sizeof(EasuParameters) <= ParameterBytes); +struct HeapPush { + std::uint8_t parameters[ParameterBytes]; + std::uint32_t slot; +}; + +static_assert(offsetof(HeapPush, slot) == 20 && sizeof(HeapPush) == 24); + } PresentationUpscaler::PresentationUpscaler(const Graphics::Context& context, std::size_t slotCount, float sharpness) : context(context), sharpness(sharpness), slots(slotCount) { Graphics::Require(slotCount != 0, "presentation upscaler needs at least one slot"); Graphics::Require(std::isfinite(sharpness) && sharpness >= 0.0f && sharpness <= 2.0f, "FSR sharpness must be from 0.0 to 2.0 stops"); try { - VkSamplerCreateInfo samplerInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; + heap = Graphics::DescriptorHeapEnabled() && Graphics::BindlessHeap::For(context).DescriptorHeapMode(); samplerInfo.magFilter = VK_FILTER_NEAREST; samplerInfo.minFilter = VK_FILTER_NEAREST; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; @@ -89,10 +99,11 @@ PresentationUpscaler::~PresentationUpscaler() { void PresentationUpscaler::release() noexcept { for (std::size_t i = 0; i < slots.size(); ++i) { Release(i); - releaseSurface(slots[i].stage); - releaseSurface(slots[i].upscaled); + releaseSurface(slots[i], slots[i].stage); + releaseSurface(slots[i], slots[i].upscaled); } for (const auto& [key, entry] : targets) { + if (entry.heapPipeline) context.Function("vkDestroyPipeline")(context.device, entry.heapPipeline, nullptr); if (entry.pipeline) context.Function("vkDestroyPipeline")(context.device, entry.pipeline, nullptr); if (entry.renderPass) context.Function("vkDestroyRenderPass")(context.device, entry.renderPass, nullptr); } @@ -131,16 +142,17 @@ void PresentationUpscaler::Release(std::size_t index) noexcept { slots[index].transient.clear(); } -void PresentationUpscaler::releaseSurface(Surface& surface) noexcept { +void PresentationUpscaler::releaseSurface(Slot& slot, Surface& surface) noexcept { + if (surface.sampled && heap) slot.ReleaseHeapSlots(context); if (surface.sampled) context.Function("vkDestroyImageView")(context.device, surface.sampled, nullptr); if (surface.image) context.Function("vkDestroyImage")(context.device, surface.image, nullptr); if (surface.memory) context.Function("vkFreeMemory")(context.device, surface.memory, nullptr); surface = Surface{}; } -void PresentationUpscaler::ensureSurface(Surface& surface, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage) { +void PresentationUpscaler::ensureSurface(Slot& slot, Surface& surface, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage) { if (surface.image != VK_NULL_HANDLE && surface.format == format && surface.extent.width == extent.width && surface.extent.height == extent.height) return; - releaseSurface(surface); + releaseSurface(slot, surface); VkFormatProperties properties{}; context.formatProperties(context.physical, format, &properties); VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT; @@ -170,7 +182,7 @@ void PresentationUpscaler::ensureSurface(Surface& surface, VkFormat format, VkEx surface.format = format; surface.extent = extent; } catch (...) { - releaseSurface(surface); + releaseSurface(slot, surface); throw; } } @@ -194,7 +206,7 @@ VkImage PresentationUpscaler::Stage(std::size_t index, VkFormat format, VkExtent Graphics::Require(index < slots.size(), "presentation upscaler slot is out of range"); Graphics::Require(extent.width != 0 && extent.height != 0, "presentation upscaler stage extent must be non-zero"); auto& slot = slots[index]; - ensureSurface(slot.stage, format, extent, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); + ensureSurface(slot, slot.stage, format, extent, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); return slot.stage.image; } @@ -303,7 +315,28 @@ const PresentationUpscaler::Target& PresentationUpscaler::target(VkFormat format pipelineInfo.renderPass = created.renderPass; const auto lock = context.LockPipelineCacheForUse(); Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.pipeline), "vkCreateGraphicsPipelines presentation upscaler"); + if (heap) { + const auto& bindless = Graphics::BindlessHeap::For(context); + VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; + mapping.firstBinding = 0; + mapping.bindingCount = 1; + mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_COMBINED_SAMPLED_IMAGE_BIT_EXT; + mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; + mapping.sourceData.pushIndex.pushOffset = offsetof(HeapPush, slot); + mapping.sourceData.pushIndex.heapIndexStride = static_cast(bindless.ImageHeapStride()); + mapping.sourceData.pushIndex.heapArrayStride = static_cast(bindless.ImageHeapStride()); + mapping.sourceData.pushIndex.pEmbeddedSampler = &samplerInfo; + VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; + mappingInfo.mappingCount = 1; + mappingInfo.pMappings = &mapping; + stages[1].pNext = &mappingInfo; + auto heapFlags = Graphics::DescriptorHeapFlags(); + pipelineInfo.pNext = &heapFlags; + pipelineInfo.layout = VK_NULL_HANDLE; + Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.heapPipeline), "vkCreateGraphicsPipelines presentation upscaler heap"); + } } catch (...) { + if (created.pipeline) context.Function("vkDestroyPipeline")(context.device, created.pipeline, nullptr); if (created.renderPass) context.Function("vkDestroyRenderPass")(context.device, created.renderPass, nullptr); throw; } @@ -338,19 +371,30 @@ void PresentationUpscaler::bindSource(VkDescriptorSet set, VkImageView view) con context.Function("vkUpdateDescriptorSets")(context.device, 1, &write, 0, nullptr); } -void PresentationUpscaler::draw(VkCommandBuffer commands, const Target& entry, VkFramebuffer framebuffer, VkExtent2D extent, VkDescriptorSet set, const void* parameters, std::uint32_t size) const { +void PresentationUpscaler::draw(VkCommandBuffer commands, Slot& slot, const Target& entry, VkFramebuffer framebuffer, VkExtent2D extent, VkDescriptorSet set, VkImageView source, const void* parameters, std::uint32_t size) const { + Graphics::Require(size <= ParameterBytes, "presentation upscaler parameters exceed the push range"); VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; begin.renderPass = entry.renderPass; begin.framebuffer = framebuffer; begin.renderArea = {{0, 0}, extent}; context.Function("vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE); - context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, entry.pipeline); + const auto heapSlot = entry.heapPipeline != VK_NULL_HANDLE ? Graphics::BindlessHeap::For(context).ViewSlot(Graphics::HeapPassSampledKind, &slot, source, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) : std::nullopt; + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, heapSlot ? entry.heapPipeline : entry.pipeline); const VkViewport viewport{0.0f, 0.0f, static_cast(extent.width), static_cast(extent.height), 0.0f, 1.0f}; const VkRect2D scissor{{0, 0}, extent}; context.Function("vkCmdSetViewport")(commands, 0, 1, &viewport); context.Function("vkCmdSetScissor")(commands, 0, 1, &scissor); - context.Function("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, 0, nullptr); - context.Function("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, size, parameters); + if (heapSlot) { + Graphics::BindlessHeap::For(context).BindDescriptorHeaps(commands); + HeapPush pushed{}; + std::memcpy(pushed.parameters, parameters, size); + pushed.slot = *heapSlot; + Graphics::CmdPushData(context, commands, sizeof(pushed), &pushed); + } else { + bindSource(set, source); + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, Graphics::SetBindSite::Presentation); + Graphics::CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, size, parameters); + } context.Function("vkCmdDraw")(commands, 3, 1, 0, 0); context.Function("vkCmdEndRenderPass")(commands); } @@ -361,9 +405,8 @@ void PresentationUpscaler::RecordUpscale(VkCommandBuffer commands, std::size_t i auto& slot = slots[index]; const auto& entry = target(slot.stage.format, finalLayout, Filter::Easu); const auto framebuffer = transientFramebuffer(slot, entry.renderPass, destination, slot.stage.format, extent, finalLayout); - bindSource(slot.easuSet, slot.stage.sampled); const EasuParameters parameters{static_cast(slot.stage.extent.width), static_cast(slot.stage.extent.height), static_cast(extent.width), static_cast(extent.height)}; - draw(commands, entry, framebuffer, extent, slot.easuSet, ¶meters, sizeof(parameters)); + draw(commands, slot, entry, framebuffer, extent, slot.easuSet, slot.stage.sampled, ¶meters, sizeof(parameters)); } void PresentationUpscaler::RecordPresent(VkCommandBuffer commands, std::size_t index, std::uint32_t width, std::uint32_t height, VkImage destination, VkExtent2D extent, VkImageLayout finalLayout) { @@ -376,15 +419,14 @@ void PresentationUpscaler::RecordPresent(VkCommandBuffer commands, std::size_t i VkImageView sharpened = slot.stage.sampled; if (Upscales(width, height, extent)) { const VkExtent2D upscaled{rect.width, rect.height}; - ensureSurface(slot.upscaled, slot.stage.format, upscaled, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); + ensureSurface(slot, slot.upscaled, slot.stage.format, upscaled, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); RecordUpscale(commands, index, slot.upscaled.image, upscaled, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); sharpened = slot.upscaled.sampled; } const auto& entry = target(slot.stage.format, finalLayout, Filter::Rcas); const auto framebuffer = transientFramebuffer(slot, entry.renderPass, destination, slot.stage.format, extent, finalLayout); - bindSource(slot.rcasSet, sharpened); const RcasParameters parameters{rect.x, rect.y, static_cast(rect.width), static_cast(rect.height), sharpness}; - draw(commands, entry, framebuffer, extent, slot.rcasSet, ¶meters, sizeof(parameters)); + draw(commands, slot, entry, framebuffer, extent, slot.rcasSet, sharpened, ¶meters, sizeof(parameters)); } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 916035808adc..acda6a05c5d0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -61,7 +61,7 @@ class BindlessHeap { std::optional TextureSlot(std::uint32_t kind, Texture* texture, VkImageView view, VkImageLayout layout); std::optional StorageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view); - std::optional ViewSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view); + std::optional ViewSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view, VkImageLayout layout = VK_IMAGE_LAYOUT_GENERAL); void ReleaseSlots(const HeapSlotOwner* owner); std::uint32_t SlotGeneration(std::uint32_t slot) const; const Texture* SlotTexture(std::uint32_t kind, std::uint32_t slot) const; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 52f2d3fc8000..3b36adbdc23a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -378,9 +378,9 @@ std::optional BindlessHeap::StorageSlot(std::uint32_t kind, const return imageSlot(kind, owner, view, VK_IMAGE_LAYOUT_GENERAL, nullptr); } -std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view) { +std::optional BindlessHeap::ViewSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view, VkImageLayout layout) { Require(isImageKind(kind) && owner != nullptr && view != VK_NULL_HANDLE, "bindless heap: invalid view slot request"); - return imageSlot(kind, owner, view, VK_IMAGE_LAYOUT_GENERAL, nullptr); + return imageSlot(kind, owner, view, layout, nullptr); } std::optional BindlessHeap::imageSlot(std::uint32_t kind, const HeapSlotOwner* owner, VkImageView view, VkImageLayout layout, Texture* texture) { From fd6cf2c100c5b7ee10ffbebab09a94d26f5456a5 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 09:46:31 +0530 Subject: [PATCH 203/269] fix(agc): write shader request dumps for heap draw stages A heap draw stage was built straight from its template, which skips the capture that writes APS5_DUMP_GRAPHICS_SHADERS / APS5_DUMP_SHADERS request dumps, so in heap mode those dumps were never written (agc_driver_graphics_dump_graphics and _filtered failed). While a dump or trace capture is requested, the stage takes the capture path, as it does with the heap off. --- .../Execution/src/Driver/Draw/DrawCapture.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 6d85384f925b..5e4181a8eaed 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -211,7 +211,9 @@ std::shared_ptr Driver::materializeDraw stageCapture.capture.reset(); stageCapture.forgetSerial = GuestMemory::ForgetSerial(); stageCapture.pushOffset = pushOffset; - if (request.target.gpuResolvedImages) { + static const bool dumpGraphics = std::getenv("APS5_DUMP_GRAPHICS_SHADERS") != nullptr; + const bool captured = dumpGraphics || traceCapSync() || (context.profile && (context.dumpTarget != 0 || context.dumpSlot1 != 0)); + if (request.target.gpuResolvedImages && !captured) { if (materializeHeapDirect(context, i, invocation, request, timing)) return stageCapture.compiled; } const auto capture = [&] { @@ -235,7 +237,6 @@ std::shared_ptr Driver::materializeDraw if (j < i && context.recompiled[j] && context.stageCaptures[j].direct) context.memory.insert(context.memory.end(), context.stageCaptures[j].regions.begin(), context.stageCaptures[j].regions.end()); } request.context.memory = context.memory; - static const bool dumpGraphics = std::getenv("APS5_DUMP_GRAPHICS_SHADERS") != nullptr; if (dumpGraphics) static_cast(dumpRequest(program.binary.codeAddress, request)); if (traceCapSync()) traceCapture("draw-capture", program.binary.codeAddress, context.submission.queue, context.memory, Graphics::Recorder::ThreadWaitedMs() - waitedBefore); if (context.profile) { From b635a721bea93bb68e94d212dacb4f4b6529a94c Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 09:46:31 +0530 Subject: [PATCH 204/269] test(agc): check relocated ring-hit verification only when draw entries are verified The driver compares a relocated ring hit with a fresh capture only under APS5_VERIFY_DRAW_ENTRIES (a verified hit is re-captured). The test required such a comparison whenever APS5_VERIFY_GPU_HEAP was set, so the plain variant failed when the suite ran it with APS5_VERIFY_GPU_HEAP alone. The _gpu_heap variant sets both and still checks it. --- .../tests/execution/DrawRelocateUserValues.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRelocateUserValues.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRelocateUserValues.cpp index e89a689ee1a6..7a1f605e6e03 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRelocateUserValues.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRelocateUserValues.cpp @@ -309,7 +309,8 @@ void MovedRecordCountsReachEveryDescriptor(bool sharedCount) { Require(taught.hits > start.hits, mode + ": draws whose descriptors moved to equal contents never reused the cached draw (" + std::to_string(taught.lookups - start.lookups) + " lookups)"); if (std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr) { Require(AgcDriver::DriverDetail::HeapStagesTaken() > heapStart, mode + ": the draws never reached the GPU heap"); - Require(AgcDriver::DriverDetail::HeapRingHitsVerified() > ringStart, mode + ": no relocated ring hit was compared with a fresh capture"); + if (std::getenv("APS5_VERIFY_DRAW_ENTRIES") != nullptr) + Require(AgcDriver::DriverDetail::HeapRingHitsVerified() > ringStart, mode + ": no relocated ring hit was compared with a fresh capture"); Require(AgcDriver::DriverDetail::HeapRingHitsDiffering() == 0, mode + ": a relocated ring hit's rebuilt words differ from a fresh capture"); } const auto pixel = DrawWithUserData(pixelCode, userData(5, 8u)); @@ -347,7 +348,8 @@ void ForwardedBaseWordsFollowRelocatedDraws() { const auto after = Driver::Get().DrawCacheCounters(); Require(after.hits > start.hits, "draws that moved only their first V# never reused the cached draw, so the forwarded base word was never rebuilt for a hit"); if (std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr) { - Require(AgcDriver::DriverDetail::HeapRingHitsVerified() > ringStart, "no relocated ring hit of the forwarded-base draws was compared with a fresh capture"); + if (std::getenv("APS5_VERIFY_DRAW_ENTRIES") != nullptr) + Require(AgcDriver::DriverDetail::HeapRingHitsVerified() > ringStart, "no relocated ring hit of the forwarded-base draws was compared with a fresh capture"); Require(AgcDriver::DriverDetail::HeapRingHitsDiffering() == 0, "a relocated ring hit of the forwarded-base draws differs from a fresh capture"); } } From 7a3eecfaa7e3110a377f665cd33c335c972076dc Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 09:55:01 +0530 Subject: [PATCH 205/269] perf(agc): publish the pending ranges when an overlap check takes the lock FlushPending's nothing-to-store check now looks up overlaps through the pending range index under the lock, and no longer goes through MayOverlap, which republished the merged ranges as a side effect. Until another caller published them, every later lock-free SurelyClear check missed and fell back to the lock. Publish them under the lock, as AnyPendingOverlaps does. PendingList::remove also erases through the iterator its lookup found instead of scanning the list a second time. --- core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index ab8cbfa1bb64..d58e4b9cd4fd 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -1835,9 +1835,10 @@ class PendingList { return next; } void remove(const StorageTexture* texture) { - if (std::find(textures.begin(), textures.end(), texture) == textures.end()) return; + const auto found = std::find(textures.begin(), textures.end(), texture); + if (found == textures.end()) return; unindex(const_cast(texture)); - std::erase(textures, texture); + textures.erase(found); changed(); } bool MayOverlap(std::uint64_t address, std::size_t bytes) { @@ -4994,6 +4995,7 @@ bool StorageTexture::FlushPending(std::uint64_t address, std::size_t bytes, cons if (pending.flushingCount.load(std::memory_order_acquire) != 0) return false; if (!pending.textures.SurelyClear(address, bytes)) { std::lock_guard lock(pending.mutex); + pending.textures.Publish(); const auto* exempt = Refreshing::Get(); if (pending.textures.AnyOverlapping(address, bytes, [&](const StorageTexture* texture) { return texture != except && texture != exempt && texture->pendingUnitInside(address, bytes); })) return false; if (pending.flushingCount.load(std::memory_order_acquire) != 0) return false; From 28ff546b61faa6535967b46c5966ec3a90a40d46 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 20:14:35 +0530 Subject: [PATCH 206/269] test(agc): link the pending range index test against libc The MinGW Windows build links a test's C++ runtime through libc, so the standalone agc_pending_range_index_tests failed to link there with an undefined __gxx_personality_v0. Link libc and put its directory on the test's PATH, as the other standalone AGC tests do. --- .../tests/cmake/agc_pending_range_index_tests.cmake | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pending_range_index_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pending_range_index_tests.cmake index 5e073f4d18f5..b2770b22610b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pending_range_index_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pending_range_index_tests.cmake @@ -3,8 +3,13 @@ if(BUILD_TESTING) tests/PendingRangeIndex.cpp ) target_include_directories(agc_pending_range_index_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(agc_pending_range_index_tests PRIVATE libc) set_target_properties(agc_pending_range_index_tests PROPERTIES CXX_EXTENSIONS OFF) configure_windows_unwind(agc_pending_range_index_tests) add_test(NAME agc_pending_range_index COMMAND agc_pending_range_index_tests) set_tests_properties(agc_pending_range_index PROPERTIES TIMEOUT 30) + if(WIN32) + set_tests_properties(agc_pending_range_index PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() endif() From 8f863c78e89ed6f913ba6488b656d3318ea3aa26 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Fri, 13 Nov 2026 22:43:08 +0530 Subject: [PATCH 207/269] perf(agc): push only the changed range of a heap draw's push data vkd3d-proton (d3d12_command_list_update_root_constants) pushes only the root parameters that changed, never the whole block. Heap draws now keep the last pushed block per command buffer (PushDataShadow) and push only the changed range. The kept block is dropped whenever push data may have changed or become undefined: every vkCmdPushDataEXT goes through CmdPushData, and command buffer begin, push constants and descriptor set binds (the points that forget the bound heap) bump the push-data mark. The range is compared and pushed in whole 8-byte units, as vkd3d pushes a root address whole. NVIDIA 620.70 keeps reading the previous buffer when a push updates only the low dword of an address that a uniform buffer is mapped from (VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT); agc_driver_draw_recipe_moved_buffer caught that with 4-byte units. --- .../Execution/src/PresentationPass.cpp | 3 +- .../Execution/src/VulkanDevice.cpp | 6 +- .../Graphics/include/BindlessHeap.hpp | 4 +- .../Graphics/include/PushDataShadow.hpp | 52 +++++++++++ .../Graphics/src/BindlessHeap.cpp | 28 +++++- .../libSceAgcDriver/Graphics/src/Pipeline.cpp | 10 ++- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 3 +- .../Graphics/src/TextureDetiler.cpp | 6 +- .../libSceAgcDriver/tests/PushDataShadow.cpp | 88 +++++++++++++++++++ .../cmake/agc_push_data_shadow_tests.cmake | 8 ++ .../tests/execution/HeapDrawSample.cpp | 3 + 11 files changed, 194 insertions(+), 17 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/Graphics/include/PushDataShadow.hpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/PushDataShadow.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_push_data_shadow_tests.cmake diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp index 666930ec2539..bc2c7b54d503 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp @@ -412,8 +412,7 @@ void PresentationPass::draw(VkCommandBuffer commands, Slot& slot, const Target& Graphics::BindlessHeap::For(context).BindDescriptorHeaps(commands); HeapPush pushed{{}, 0u, pqNits->DeviceAddress(), *heapSlot, 0u}; std::copy(std::begin(parameters), std::end(parameters), pushed.parameters); - const VkPushDataInfoEXT data{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {&pushed, sizeof(pushed)}}; - context.Function("vkCmdPushDataEXT")(commands, &data); + Graphics::CmdPushData(context, commands, sizeof(pushed), &pushed); } else { Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &slot.set, Graphics::SetBindSite::Presentation); Graphics::CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), parameters); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 17cac470ce8b..b3ab9221cb2d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -6142,8 +6142,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { recorder.Keep(std::move(pool)); } if (record.objects->descriptorHeap && record.pushStages == 0 && (workgroupAddress != 0 || record.shader->program->scratchPoolSlotDwords != 0)) { - const VkPushDataInfoEXT push{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, Graphics::ComputePushConstantBytes, {stageAddresses.data(), stageAddresses.size()}}; - context.Function("vkCmdPushDataEXT")(commands, &push); + Graphics::CmdPushData(context, commands, static_cast(stageAddresses.size()), stageAddresses.data(), Graphics::ComputePushConstantBytes); } if (record.pushStages != 0) { std::array patchedBytes; @@ -6155,8 +6154,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { } if (record.objects->descriptorHeap) { std::memcpy(patchedBytes.data() + Graphics::ComputePushConstantBytes, stageAddresses.data(), stageAddresses.size()); - const VkPushDataInfoEXT push{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {patchedBytes.data(), patchedBytes.size()}}; - context.Function("vkCmdPushDataEXT")(commands, &push); + Graphics::CmdPushData(context, commands, static_cast(patchedBytes.size()), patchedBytes.data()); } else { Graphics::CmdPushConstants(context, commands, record.objects->layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, Graphics::ComputePushConstantBytes, pushed); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index acda6a05c5d0..c266826954e9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -401,7 +401,9 @@ VkDescriptorSetAndBindingMappingEXT HeapPushIndexMapping(const BindlessHeap& hea std::uint32_t pushOffset); VkPipeline CreateHeapComputePipeline(const Context& context, VkComputePipelineCreateInfo info, std::span mappings); VkPipeline CreateHeapGraphicsPipeline(const Context& context, VkGraphicsPipelineCreateInfo info, std::span mappings); -void CmdPushData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values); +void CmdPushData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values, std::uint32_t offset = 0); +std::uint64_t NotePushDataWritten() noexcept; +std::uint64_t PushDataMark() noexcept; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PushDataShadow.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PushDataShadow.hpp new file mode 100644 index 000000000000..51232994333b --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PushDataShadow.hpp @@ -0,0 +1,52 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_PUSHDATASHADOW_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_PUSHDATASHADOW_HPP + +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +template +class PushDataShadow { +public: + static constexpr std::size_t Unit = sizeof(VkDeviceAddress); + static_assert(Bytes % Unit == 0); + + std::pair Changed(VkCommandBuffer target, std::uint64_t currentMark, std::span next) { + if (target != commands || currentMark != mark) { + commands = target; + std::memcpy(bytes.data(), next.data(), Bytes); + return {0, Bytes}; + } + std::size_t first = Bytes; + std::size_t end = 0; + for (std::size_t offset = 0; offset < Bytes; offset += Unit) { + if (std::memcmp(next.data() + offset, bytes.data() + offset, Unit) == 0) continue; + first = std::min(first, offset); + end = offset + Unit; + } + if (first >= end) return {0, 0}; + std::memcpy(bytes.data() + first, next.data() + first, end - first); + return {first, end}; + } + + void Pushed(std::uint64_t newMark) { mark = newMark; } + +private: + VkCommandBuffer commands = VK_NULL_HANDLE; + std::uint64_t mark = 0; + std::array bytes{}; +}; + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 3b36adbdc23a..a5d2ee6288fc 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -1488,6 +1488,7 @@ void reportHeapStatistics() { void forgetHeapBinding(VkCommandBuffer commands) { if (!DescriptorHeapEnabled()) return; + static_cast(NotePushDataWritten()); std::lock_guard lock(boundHeapsMutex); if (boundHeaps.erase(commands) != 0) boundHeapsEpoch.fetch_add(1, std::memory_order_release); } @@ -1633,9 +1634,32 @@ VkPipeline CreateHeapGraphicsPipeline(const Context& context, VkGraphicsPipeline return pipeline; } -void CmdPushData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values) { - const VkPushDataInfoEXT data{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {values, bytes}}; +namespace { + +std::atomic& pushDataMark() { + static std::atomic mark{0}; + return mark; +} + +} + +std::uint64_t NotePushDataWritten() noexcept { + static std::atomic threads{0}; + thread_local const std::uint64_t base = (threads.fetch_add(1, std::memory_order_relaxed) + 1u) << 40u; + thread_local std::uint64_t sequence = 0; + const auto mark = base | (++sequence & ((std::uint64_t{1} << 40u) - 1u)); + pushDataMark().store(mark, std::memory_order_relaxed); + return mark; +} + +std::uint64_t PushDataMark() noexcept { + return pushDataMark().load(std::memory_order_relaxed); +} + +void CmdPushData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values, std::uint32_t offset) { + const VkPushDataInfoEXT data{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, offset, {values, bytes}}; context.Function("vkCmdPushDataEXT")(commands, &data); + static_cast(NotePushDataWritten()); } void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index 076cc6f5513a..6055b341d4e9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -5,6 +5,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp" +#include "prx/libSceAgcDriver/Graphics/include/PushDataShadow.hpp" #include "prx/libSceAgcDriver/Graphics/include/PipelineJournal.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libSceAgcDriver/Graphics/include/PatchVertexLayer.hpp" @@ -18,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -1087,8 +1089,12 @@ void Pipeline::ContinueBackFaces(VkCommandBuffer commands, const State& state, c void Pipeline::PushConstants(VkCommandBuffer commands, VkShaderStageFlags stages, std::span bytes) const { if (stages == 0) return; if (descriptorHeap) { - const VkPushDataInfoEXT push{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {bytes.data(), bytes.size()}}; - context.Function("vkCmdPushDataEXT")(commands, &push); + thread_local PushDataShadow shadow; + const auto [first, end] = shadow.Changed(commands, PushDataMark(), bytes); + if (first >= end) return; + const VkPushDataInfoEXT info{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, static_cast(first), {bytes.data() + first, end - first}}; + context.Function("vkCmdPushDataEXT")(commands, &info); + shadow.Pushed(NotePushDataWritten()); return; } if (dynamicRendering) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index f7c13c0cba20..b6d91ccd65bd 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -3083,8 +3083,7 @@ void Recorder::pushOnlyParameters(VkCommandBuffer commands, VkPipeline heapPipel CmdPushConstants(context, commands, layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, bytes, values); return; } - const VkPushDataInfoEXT data{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {values, bytes}}; - context.Function("vkCmdPushDataEXT")(commands, &data); + CmdPushData(context, commands, bytes, values); } bool Recorder::RecordChangedCopy(VkCommandBuffer commands, VkDeviceAddress result, VkDeviceAddress snapshot, VkDeviceAddress target, std::uint32_t dwords, VkDeviceAddress counter) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index ccb4b28ab0e9..2b33278a9991 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -606,8 +606,7 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask BindlessHeap::For(context).BindDescriptorHeaps(commands); context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskHeapPipeline); const HeapCmaskPush pushed{push, 0u, cmaskAddress + descriptorOffset, errorsAddress, *slot, 0u}; - const VkPushDataInfoEXT data{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {&pushed, sizeof(pushed)}}; - context.Function("vkCmdPushDataEXT")(commands, &data); + CmdPushData(context, commands, sizeof(pushed), &pushed); } else { context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipeline); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipelineLayout, 0, 1, &set, SetBindSite::Detiler); @@ -662,8 +661,7 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til bindless.BindDescriptorHeaps(commands); context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, heapPipeline); const HeapImagePush pushed{push, tiledAddress + descriptorOffset, *slot, 0u}; - const VkPushDataInfoEXT data{VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT, nullptr, 0, {&pushed, sizeof(pushed)}}; - context.Function("vkCmdPushDataEXT")(commands, &data); + CmdPushData(context, commands, sizeof(pushed), &pushed); } else { const auto target = pipeline(MipTileMode(tileMode, layout), elementBytes, retile, false, true); const auto set = allocateSet(true); diff --git a/core/libs/prx/libSceAgcDriver/tests/PushDataShadow.cpp b/core/libs/prx/libSceAgcDriver/tests/PushDataShadow.cpp new file mode 100644 index 000000000000..d3ee3b3f3aa3 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/PushDataShadow.cpp @@ -0,0 +1,88 @@ +#include "prx/libSceAgcDriver/Graphics/include/PushDataShadow.hpp" +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::PushDataShadow; +constexpr std::size_t Bytes = 256; +using Block = std::array; +int failures = 0; + +void Expect(bool condition, const std::string& what) { + if (condition) return; + std::fprintf(stderr, "FAILED: %s\n", what.c_str()); + ++failures; +} + +void SetWord(Block& block, std::size_t word, std::uint32_t value) { + std::memcpy(block.data() + word * 4, &value, sizeof(value)); +} + +VkCommandBuffer Commands(std::uintptr_t value) { + return reinterpret_cast(value); +} + +void testRanges() { + PushDataShadow shadow; + Block block{}; + for (std::size_t word = 0; word < Bytes / 4; ++word) SetWord(block, word, 0x1000u + static_cast(word)); + auto range = shadow.Changed(Commands(1), 7, block); + Expect(range.first == 0 && range.second == Bytes, "the first push of a command buffer covers the whole block"); + shadow.Pushed(8); + range = shadow.Changed(Commands(1), 8, block); + Expect(range.first == range.second, "an unchanged block pushes nothing"); + SetWord(block, 56, 0xbeefu); + range = shadow.Changed(Commands(1), 8, block); + Expect(range.first == 224 && range.second == 232, "a change to the low dword of an address pushes the whole address"); + shadow.Pushed(9); + SetWord(block, 5, 0x1u); + SetWord(block, 41, 0x2u); + range = shadow.Changed(Commands(1), 9, block); + Expect(range.first == 16 && range.second == 168, "two changes push one range from the first to the last changed address"); + shadow.Pushed(10); + range = shadow.Changed(Commands(1), 11, block); + Expect(range.first == 0 && range.second == Bytes, "a push by anything else since the last one pushes the whole block"); + shadow.Pushed(12); + range = shadow.Changed(Commands(2), 12, block); + Expect(range.first == 0 && range.second == Bytes, "another command buffer gets the whole block"); +} + +void testKeptBytes() { + PushDataShadow shadow; + Block block{}; + shadow.Changed(Commands(3), 1, block); + shadow.Pushed(2); + std::uint64_t mark = 2; + std::uint64_t seed = 0x9e3779b97f4a7c15ull; + Block gpu = block; + for (int round = 0; round < 4000; ++round) { + seed ^= seed << 13u; + seed ^= seed >> 7u; + seed ^= seed << 17u; + const auto changes = seed % 4u; + for (std::uint64_t change = 0; change < changes; ++change) SetWord(block, (seed >> (8u * change + 4u)) % (Bytes / 4), static_cast(seed >> 32u) + static_cast(change)); + const auto [first, end] = shadow.Changed(Commands(3), mark, block); + Expect(first % 8u == 0u && end % 8u == 0u && first <= end && end <= Bytes, "pushed ranges are whole addresses inside the block"); + std::memcpy(gpu.data() + first, block.data() + first, end - first); + if (first < end) shadow.Pushed(++mark); + if (gpu != block) { + Expect(false, "the pushed ranges rebuild the block in round " + std::to_string(round)); + return; + } + } +} + +} + +int main() { + testRanges(); + testKeptBytes(); + if (failures != 0) return EXIT_FAILURE; + std::puts("push data shadow tests passed"); + return EXIT_SUCCESS; +} diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_push_data_shadow_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_push_data_shadow_tests.cmake new file mode 100644 index 000000000000..9c13d15221d1 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_push_data_shadow_tests.cmake @@ -0,0 +1,8 @@ +add_test_executable(agc_push_data_shadow_tests EXCLUDE_FROM_ALL tests/PushDataShadow.cpp) +target_include_directories(agc_push_data_shadow_tests PRIVATE ${LIBS_INCLUDE_DIR} ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR}) +set_target_properties(agc_push_data_shadow_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_push_data_shadow_tests) + +if(BUILD_TESTING) + agc_add_default_test(agc_push_data_shadow_tests) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index 6a8044d9c3df..aebad33df13d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -548,6 +548,9 @@ int main() { if (heap) { OversizedStageFails(); UnmappableStageFails(); + const auto mark = AgcDriver::Graphics::PushDataMark(); + AgcDriver::Graphics::NoteCommandBufferBegun(VK_NULL_HANDLE); + Require(AgcDriver::Graphics::PushDataMark() != mark, "beginning a command buffer kept the push data recorded before it"); } if (excluded) Require(AgcDriver::Graphics::HeapExcludedCount(AgcDriver::Graphics::HeapExcluded::Draw) != 0u, From 3cd415ad07c56dcfb8992ad2637b1dbdf1d2df1d Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 14 Nov 2026 00:13:14 +0530 Subject: [PATCH 208/269] perf(agc): size a heap template's content key by the words it holds A heap stage with a template id is keyed on that id plus its image and sampler words only (VisitContentKey), but AppendContentKey still sized the key by walking every binding, reading the draw words of buffers, tables and data. Reserve only the heap key's own words. The key is unchanged. --- .../prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index a208eb266afd..bd01c315414d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -3351,6 +3351,15 @@ std::vector ShaderResources::ContentKey(const CompiledShader& sha void ShaderResources::AppendContentKey(const CompiledShader& shader, bool dataWords, bool movableBuffers, std::vector& key) { Require(shader.program != nullptr, "missing compiled shader"); + if (shader.heap != nullptr && shader.program->heapTemplateId != 0) { + std::size_t heapWords = key.size() + 8; + for (const auto& binding : shader.program->bindings) { + if (binding.role == ShaderRecompiler::DescriptorRole::GuestImages || binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers) heapWords += 1 + DrawGuestWords(shader, binding).size(); + } + key.reserve(heapWords); + VisitContentKey(shader, dataWords, movableBuffers, [&](std::uint32_t word) { key.push_back(word); }); + return; + } std::size_t words = key.size() + 5; const auto addWords = [&](std::size_t count) { if (count > key.max_size() - words) throw std::length_error("resource content key exceeds vector limits"); From b02157c92c8edc420c8f547261fd8963bf984015 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 14 Nov 2026 07:29:42 +0530 Subject: [PATCH 209/269] fix(agc): link the push data shadow test as a host test on MinGW --- .../tests/cmake/agc_push_data_shadow_tests.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_push_data_shadow_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_push_data_shadow_tests.cmake index 9c13d15221d1..e8252ab14f8d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_push_data_shadow_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_push_data_shadow_tests.cmake @@ -1,7 +1,7 @@ add_test_executable(agc_push_data_shadow_tests EXCLUDE_FROM_ALL tests/PushDataShadow.cpp) target_include_directories(agc_push_data_shadow_tests PRIVATE ${LIBS_INCLUDE_DIR} ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR}) set_target_properties(agc_push_data_shadow_tests PROPERTIES CXX_EXTENSIONS OFF) -configure_windows_unwind(agc_push_data_shadow_tests) +configure_host_test_executable(agc_push_data_shadow_tests) if(BUILD_TESTING) agc_add_default_test(agc_push_data_shadow_tests) From b0f5a07f4a0b37a9d3766a33cd151f65e2c7be6f Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sat, 14 Nov 2026 09:20:39 +0530 Subject: [PATCH 210/269] fix(agc): key described pipeline identities on embedded samplers --- .../prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp | 8 ++++++++ core/libs/prx/libSceAgcDriver/tests/Graphics.cpp | 3 +++ 2 files changed, 11 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 280dba86b7bb..1413a1eb0a0d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -2887,6 +2887,14 @@ ShaderRecompiler::PipelineIdentity DescribedPipelineIdentity(const ShaderRecompi const bool fixedCapacity = binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable || binding.role == ShaderRecompiler::DescriptorRole::SamplerTable; const std::uint64_t count = fixedCapacity ? 0u : binding.count; mix(binding.descriptorSet | (static_cast(binding.binding) << 16u) | (static_cast(binding.kind) << 40u) | (count << 48u)); + mix(binding.samplerEmbedded.size()); + for (const auto value : binding.samplerEmbedded) mix(value); + mix(binding.samplerEmbeddedWords.size()); + for (const auto value : binding.samplerEmbeddedWords) mix(value); + for (const auto* flags : {&binding.samplerDepthCompare, &binding.samplerUnnormalized, &binding.samplerIntegerBorder, &binding.samplerCoordinatesIgnored}) { + mix(flags->size()); + for (std::size_t element = 0; element < flags->size(); ++element) mix((*flags)[element] ? 1u : 0u); + } } if (identity.Empty()) identity.low = 1; return identity; diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index 8c0447982405..1a416eb21102 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -13835,6 +13835,9 @@ void pipelineJournalTests(bool longPath = false, bool extended = false) { return result; }; for (std::size_t flag = 0; flag < 4u; ++flag) Require(!(flagged(flag).Identity() == flagged(4u).Identity()), "an embedded sampler flag did not enter the identity"); + Require(DescribedPipelineIdentity(embedded(0u, 5u)) == embedded(0u, 5u).Identity(), "the described identity of a result with an embedded sampler differs from its identity"); + Require(!(DescribedPipelineIdentity(embedded(0u, 5u)) == DescribedPipelineIdentity(embedded(0u, 6u))), "the embedded sampler words did not enter the described identity"); + for (std::size_t flag = 0; flag < 4u; ++flag) Require(!(DescribedPipelineIdentity(flagged(flag)) == DescribedPipelineIdentity(flagged(4u))), "an embedded sampler flag did not enter the described identity"); Require(DescribedPipelineIdentity(ShaderRecompiler::RecompileResult{}).Empty(), "a result without a module has a described identity"); const auto withTable = [&](Role role, std::uint32_t elements, std::uint32_t buffers) { auto result = module(1); From 11aa97886c1b5bc32fe5e3f5d12201c77ea29dc8 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 00:53:01 +0530 Subject: [PATCH 211/269] test(agc): keep prepared shader results alive while comparing their modules The heap-mode loops compared each result's SPIR-V address with the first result's after that result was freed, so they passed only when malloc reused its block; any change in RecompileResult's size or glibc tunables (glibc.malloc.mmap_threshold=0) failed them on the unchanged tree. --- .../prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp index 235fecbce199..eb7ec7b0d6af 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp @@ -91,6 +91,7 @@ void RunUnregistered(AgcDriver::VulkanDevice& device, ShaderRecompiler::Recompil const auto handle = snapshot.prepared->entries.front().handle; const auto& artifact = ShaderRecompiler::GetPreparedArtifact(*handle); const std::uint32_t* module = artifact.gpuResolvedImages ? nullptr : artifact.spirv.data(); + std::vector> keptResults; for (const bool useCache : {false, true}) { request.useCache = useCache; Require(AgcDriver::DriverDetail::SourceHandleFor(snapshot, 0, request) == handle, "unregistered compute source was prepared again"); @@ -100,6 +101,7 @@ void RunUnregistered(AgcDriver::VulkanDevice& device, ShaderRecompiler::Recompil const auto capture = repeated.Capture(runtime); const auto result = repeated.Materialize(*capture); if (module == nullptr) module = result->spirv.data(); + keptResults.push_back(result); Require(snapshot.prepared->entries.size() == 1 && result->variantId == artifact.variantId && result->spirv.data() == module, "unregistered compute invocation replaced its cached artifact"); device.Dispatch(*result, 1, 1, 1); } @@ -144,6 +146,7 @@ void Run(AgcDriver::VulkanDevice& device) { ExpectFailure([&] { static_cast(AgcDriver::DriverDetail::SourceHandleFor(snapshot, 1, request)); }, "outside the snapshot"); const auto& artifact = ShaderRecompiler::GetPreparedArtifact(*handle); const std::uint32_t* module = artifact.gpuResolvedImages ? nullptr : artifact.spirv.data(); + std::vector> keptResults; for (std::uint32_t value = 0; value < 8; ++value) { users.fill(value); request.useCache = value % 2 == 0; @@ -153,6 +156,7 @@ void Run(AgcDriver::VulkanDevice& device) { const auto capture = ShaderRecompiler::CaptureResources(request, runtime, *ready); const auto result = ShaderRecompiler::MaterializeShader(request, *capture, *ready); if (module == nullptr) module = result->spirv.data(); + keptResults.push_back(result); Require(result->variantId == artifact.variantId && result->spirv.data() == module, "invocation replaced the prepared artifact"); device.Dispatch(*result, 1, 1, 1); } From 3f2a9e5381a4b393b619243f0596177a8be4e46b Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 00:53:01 +0530 Subject: [PATCH 212/269] perf(shader): compute a result's pipeline identity once instead of per draw Identity() hashed the module and every binding on each call, and the draw path calls it per stage for every kept shape choice and pipeline key. Shared results are sealed when published and keep their identity; copies start unhashed. APS5_VERIFY_IDENTITY recomputes it on every lookup and fails on a difference. --- core/shader/recompiler/Recompiler.cpp | 32 ++++++++++------ core/shader/recompiler/Recompiler.hpp | 44 ++++++++++++++++++++++ core/shader/recompiler/ShaderDiskCache.cpp | 2 +- docs/dev/ENVIRONMENT.md | 1 + 4 files changed, 67 insertions(+), 12 deletions(-) diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 06a12a2da194..9f9ac0cc3d25 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -67,6 +67,16 @@ namespace ShaderRecompiler { +static std::shared_ptr Sealed(std::shared_ptr result) { + if (result != nullptr) result->SealIdentity(); + return result; +} + +bool VerifyIdentityMemo() { + static const bool verify = std::getenv("APS5_VERIFY_IDENTITY") != nullptr; + return verify; +} + namespace { ShaderStageKind toShaderStageKind(ShaderStage stage) { @@ -2297,10 +2307,10 @@ std::shared_ptr RecompileImpl(const RecompileRequest& req if (!request.useCache || capture.source == nullptr) { auto program = PrepareResourceProgram(request); const auto variant = CountedCompile([&] { return compileVariant(request, std::move(program)); }); - return std::make_shared(materializeResult(variant, request, capture.snapshot)); + return Sealed(std::make_shared(materializeResult(variant, request, capture.snapshot))); } - if (!ResultMemo()) return std::make_shared(materializeVariant(*capture.source, request, capture.snapshot)); - return materializeMemoized(*capture.source, request, capture.snapshot, memoHit); + if (!ResultMemo()) return Sealed(std::make_shared(materializeVariant(*capture.source, request, capture.snapshot))); + return Sealed(materializeMemoized(*capture.source, request, capture.snapshot, memoHit)); } template @@ -2595,7 +2605,7 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap entry.touched = front.lookups; TouchHeapTemplate({source.id, key, hit->result->heapTemplateId}); } - return hit->result; + return Sealed(hit->result); } UsedBindingPlan usedPlan; auto built = std::make_shared(materializeResult(*variant, request, snapshot, false, &usedPlan, nullptr, &substitutes)); @@ -2607,7 +2617,7 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap std::shared_ptr shared = std::move(created); if (!templates) { complete(shared); - return shared->result; + return Sealed(shared->result); } bool inserted = false; { @@ -2620,15 +2630,15 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap else TouchHeapTemplate(HeapTemplateName(source, key, *shared)); entry = {source.id, key, front.lookups, shared}; complete(shared); - return shared->result; + return Sealed(shared->result); } std::shared_ptr PreparedShaderInvocation::Materialize(const ResourceCapture& capture) const { if (capture.source != handle->source) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); - if (request.useCache && ResultMemo()) return materializePreparedMemoized(*handle->source, handle->artifact, request, capture.snapshot, true, nullptr); + if (request.useCache && ResultMemo()) return Sealed(materializePreparedMemoized(*handle->source, handle->artifact, request, capture.snapshot, true, nullptr)); auto result = std::make_shared(materializeResult(*handle->artifact, request, capture.snapshot)); result->cacheHit = true; - return result; + return Sealed(std::move(result)); } const std::shared_ptr& PreparedShaderInvocation::Plan() const { @@ -2683,16 +2693,16 @@ std::shared_ptr RegistrationResult(const RecompileRequest snapshot.samplers.assign(info.samplers.size(), {{}, 4u}); snapshot.userData.assign(RuntimeAbi::UserDataCapacity, 0u); snapshot.flattenedSrt.assign(1u, 0u); - return std::make_shared(materializeResult(*handle.artifact, request, snapshot, true)); + return Sealed(std::make_shared(materializeResult(*handle.artifact, request, snapshot, true))); } std::shared_ptr MaterializeShader(const RecompileRequest& request, const ResourceCapture& capture, const SourceHandle& handle) { if (!MatchesPreparedShader(request, handle)) throw std::runtime_error("ShaderRecompiler: prepared artifact does not match the static ABI"); if (capture.source != handle.source) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); - if (request.useCache && ResultMemo()) return materializePreparedMemoized(*handle.source, handle.artifact, request, capture.snapshot, true, nullptr); + if (request.useCache && ResultMemo()) return Sealed(materializePreparedMemoized(*handle.source, handle.artifact, request, capture.snapshot, true, nullptr)); auto result = std::make_shared(materializeResult(*handle.artifact, request, capture.snapshot)); result->cacheHit = true; - return result; + return Sealed(std::move(result)); } std::shared_ptr CaptureResources(const RecompileRequest& request, const SrtRuntime& runtime, const SourceHandle& handle) { diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 182d4ec39a1b..eab842cbad78 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -526,6 +526,27 @@ struct ResultKeyMemo { } }; +struct IdentityMemo { + mutable std::atomic taken{false}; + mutable std::atomic sealed{false}; + mutable std::atomic low{0}; + mutable std::atomic high{0}; + mutable std::atomic moduleLow{0}; + mutable std::atomic moduleHigh{0}; + IdentityMemo() = default; + IdentityMemo(const IdentityMemo&) {} + IdentityMemo& operator=(const IdentityMemo&) { + Reset(); + return *this; + } + void Reset() const { + taken.store(false, std::memory_order_relaxed); + sealed.store(false, std::memory_order_relaxed); + } +}; + +[[nodiscard]] bool VerifyIdentityMemo(); + struct HeapStageWords { std::vector userData; std::vector flattenedSrt; @@ -1020,7 +1041,30 @@ struct RecompileResult : CompiledShaderArtifact, ShaderInvocation { std::uint32_t workgroupMemoryDwords = 0; std::vector shaderDataUserWords; [[nodiscard]] std::uint64_t PipelineVariantId() const { return specializationId != 0 ? specializationId : variantId; } + IdentityMemo identityMemo; [[nodiscard]] PipelineIdentity Identity() const { + if (!identityMemo.sealed.load(std::memory_order_acquire)) return ComputeIdentity(); + const auto module = spirv.ContentHash(); + if (identityMemo.taken.load(std::memory_order_acquire) && identityMemo.moduleLow.load(std::memory_order_relaxed) == module.low && + identityMemo.moduleHigh.load(std::memory_order_relaxed) == module.high) { + const PipelineIdentity kept{identityMemo.low.load(std::memory_order_relaxed), identityMemo.high.load(std::memory_order_relaxed)}; + if (VerifyIdentityMemo() && !(kept == ComputeIdentity())) throw std::runtime_error("a shader's kept pipeline identity differs from its hash: a hashed field changed after the identity was taken"); + return kept; + } + const auto identity = ComputeIdentity(); + if (identity.Empty()) return identity; + identityMemo.taken.store(false, std::memory_order_relaxed); + identityMemo.low.store(identity.low, std::memory_order_relaxed); + identityMemo.high.store(identity.high, std::memory_order_relaxed); + identityMemo.moduleLow.store(module.low, std::memory_order_relaxed); + identityMemo.moduleHigh.store(module.high, std::memory_order_relaxed); + identityMemo.taken.store(true, std::memory_order_release); + return identity; + } + void SealIdentity() const { + if (!identityMemo.sealed.load(std::memory_order_relaxed)) identityMemo.sealed.store(true, std::memory_order_release); + } + [[nodiscard]] PipelineIdentity ComputeIdentity() const { const auto hash = spirv.ContentHash(); if (hash == SpirvContentHash{}) return {}; PipelineIdentity identity{hash.low, hash.high}; diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index f8fbf3b156d4..887682d80567 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -90,7 +90,7 @@ namespace ShaderRecompiler::ShaderDiskCache { static_assert(sizeof(CompiledShaderArtifact) == 336, "CompiledShaderArtifact changed: update the artifact encoder"); static_assert(sizeof(ShaderInvocation) == 240, "ShaderInvocation changed: update the invocation encoder"); #if defined(__cpp_lib_atomic_shared_ptr) -static_assert(sizeof(RecompileResult) == 656, "RecompileResult changed: update EncodeResult and DecodeResult"); +static_assert(sizeof(RecompileResult) == 696, "RecompileResult changed: update EncodeResult and DecodeResult"); #endif static_assert(sizeof(DescriptorBinding) == 912, "DescriptorBinding changed: update the binding encoder"); static_assert(sizeof(VertexAttribute) == 32, "VertexAttribute changed: update the attribute encoder"); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index aadf333aebaa..667ec0f84818 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -73,6 +73,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_TRACE_BDA` | presence | `core/shader/recompiler/Optimization/src/ResourceTracker.cpp` | | prints the first few accesses that make a program take the address-based path | | `APS5_TRACE_BUFFER_WRITTEN` | presence | `core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp` | | prints how many guest buffer elements a program may store to and how many it only loads | | `APS5_TRACE_IMAGE_TABLE` | presence | `core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp` | | traces image-table resolution | +| `APS5_VERIFY_IDENTITY` | presence | `core/shader/recompiler/Recompiler.cpp` | | recomputes a shader result's pipeline identity on every lookup of its kept identity and fails if they differ | | `APS5_VERIFY_MASKED_RESULT_MEMO` | presence | `core/shader/recompiler/Recompiler.cpp` | | also materializes every patched result memo hit, prints the first twenty whose patched result differs and counts them in the result memo report of `APS5_PROFILE_DRAW` | | `APS5_VERIFY_SRT_COMPACT` | presence | `core/shader/recompiler/Optimization/src/SrtWalker/SrtDescriptorEvaluation.cpp` | | walks every SRT descriptor a second time through the IR evaluator and throws when the two walks differ | | `APS5_VERIFY_SRT_TAPE` | presence | `core/shader/recompiler/Optimization/src/SrtWalker/SrtTape.cpp` | | walks a plan's runtime sources a second time through the evaluator, adopts its answers where the two differ and prints the first twenty differences | From 96828beaa66447db4e6ae28d025abc810043d2a8 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 01:44:07 +0530 Subject: [PATCH 213/269] perf(agc): skip a dispatch variant's pending image check while the pending serial is unchanged A variant that passed the storage-image overlap test at pending serial S passes it again until the pending set changes; the serial bumps on every change. APS5_VERIFY_PENDING_SERIAL_SKIP runs the test anyway and fails on disagreement. --- .../include/Driver/Dispatch/DispatchCache.hpp | 1 + .../src/Driver/Dispatch/VariantValidation.cpp | 17 ++++++++++++++++- .../Execution/src/Driver/Draw/DrawRelocate.cpp | 1 + 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp index 7103ec1eb4d0..4fd3fb3a91a6 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp @@ -82,6 +82,7 @@ struct DispatchVariant { std::vector captured; std::vector> spans; std::atomic generation{0}; + mutable std::atomic cleanPendingSerial{~0ull}; }; struct DispatchEntry { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp index 9cc9fbf809d6..071d796555b5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp @@ -107,6 +107,13 @@ bool Driver::vouchedValidation() { return enabled; } +namespace { +bool verifyPendingSerialSkip() { + static const bool verify = std::getenv("APS5_VERIFY_PENDING_SERIAL_SKIP") != nullptr; + return verify; +} +} + EntryOutcome Driver::validateVariant(std::uint64_t program, std::uint32_t queue, const DispatchVariant& variant, std::span regions, std::uint64_t& imagesFlushed, std::uint64_t& runsSynced, std::optional& sampling, std::vector>* live) { if (live != nullptr) live->clear(); if (DrawPipeline::Active()) { @@ -144,7 +151,15 @@ EntryOutcome Driver::validateVariant(std::uint64_t program, std::uint32_t queue, auto pendingSerial = Graphics::StorageTexture::PendingSerial(); auto forget = GuestMemory::ForgetSerial(); - if (Graphics::StorageTexture::AnyPendingOverlaps(runs) || Graphics::AnyShadowedOverlaps(runs)) { + const bool wholeRuns = vouched.empty(); + bool pendingOverlaps = false; + if (!wholeRuns || variant.cleanPendingSerial.load(std::memory_order_acquire) != pendingSerial) { + pendingOverlaps = Graphics::StorageTexture::AnyPendingOverlaps(runs); + if (wholeRuns && !pendingOverlaps) variant.cleanPendingSerial.store(pendingSerial, std::memory_order_release); + } else if (verifyPendingSerialSkip()) { + if (Graphics::StorageTexture::AnyPendingOverlaps(runs)) throw std::runtime_error("APS5_VERIFY_PENDING_SERIAL_SKIP: a dispatch variant skipped its pending image check at an unchanged serial while a pending image overlaps its runs"); + } + if (pendingOverlaps || Graphics::AnyShadowedOverlaps(runs)) { vouched.clear(); for (const auto& region : regions) { if (Graphics::StorageTexture::FlushPending(region.guestAddress, region.bytes.size(), nullptr, "dispatch-cache entry")) ++imagesFlushed; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp index 0ac4a30db6b0..ba2b3e8d4327 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp @@ -143,6 +143,7 @@ void Driver::tagUserValueWords(DispatchVariant& variant, const DrawProgram& prog } void Driver::tagVariantRuns(DispatchVariant& variant, std::span regions, const ShaderRecompiler::SrtUserDataUse& use, bool eligible, std::uint32_t hiddenWords, std::span> supplied) { + variant.cleanPendingSerial.store(~0ull, std::memory_order_relaxed); variant.userWordsWalked = use.asBase | use.asValue; std::uint64_t relocatable = eligible && drawRelocationEnabled() ? use.asBase & ~use.asValue : 0; if (hiddenWords != 0) relocatable &= hiddenWords >= 64 ? 0 : ~((std::uint64_t {1} << hiddenWords) - 1); From 1ebbeac779774cb5850be27079a38cf963b6e95e Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 01:44:07 +0530 Subject: [PATCH 214/269] perf(agc): reuse the queue worker's vertex stage decode on heap ring hits The finisher decoded every ring hit's vertex stage again from the same user data the worker decoded in submission order. Mesh draws, whose hidden words the finisher may rewrite, still decode. APS5_VERIFY_DECODE_REUSE decodes anyway and fails on any difference. --- .../Execution/src/Driver/Draw/Draw.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 4f5435e45fe1..740e33880e72 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -43,6 +43,12 @@ namespace AgcDriver::DriverDetail { namespace { +bool verifyDecodeReuse() { + static const bool verify = std::getenv("APS5_VERIFY_DECODE_REUSE") != nullptr; + return verify; +} + + struct RecycledRingWordsStorage {}; std::shared_ptr RecycledRingWords() { @@ -1001,7 +1007,14 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { } } if (words->vertexAttributes.empty()) return words; - decodeVertexInfo(i); + if (!vertexInfos[i] || graphics.stages.mesh) { + decodeVertexInfo(i); + } else if (verifyDecodeReuse()) { + const auto kept = vertexInfos[i]; + decodeVertexInfo(i); + if (!vertexInfos[i] || !sameVertexInfo(*vertexInfos[i], *kept)) + throw std::runtime_error("APS5_VERIFY_DECODE_REUSE: a ring hit's vertex stage info decoded on the finisher differs from the queue worker's"); + } require(vertexInfos[i].has_value(), "a ring vertex hit has no vertex stage info"); const auto& vertex = *vertexInfos[i]; for (auto& attribute : words->vertexAttributes) { From ecdf20ed4abb1c99244ec3943e0d600a1d905042 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 01:44:07 +0530 Subject: [PATCH 215/269] perf(agc): fill a heap stage's walk ranges and values in recycled buffers The walk filled thread-local vectors that were then copied into recycled shared buffers for the draw; fill the recycled buffers directly. --- .../Execution/src/Driver/Draw/DrawCapture.cpp | 4 ++-- .../Execution/src/Driver/Draw/HeapStages.cpp | 24 +++++++------------ 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index e0467f05307b..a345c5f2c847 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -124,9 +124,9 @@ bool Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t cursor += count; } stageCapture.heapReadWords = std::move(owned); - stageCapture.userDataUse = reads.userDataUse; - stageCapture.capture = std::move(reads.capture); stageCapture.userDataMask = UserDataMask(program, context.vertexInfos[i], reads.userDataUse.asValue | reads.userDataUse.asBase, *stageCapture.compiled); + stageCapture.userDataUse = std::move(reads.userDataUse); + stageCapture.capture = std::move(reads.capture); stageCapture.ring = true; context.memory.insert(context.memory.end(), stageCapture.regions.begin(), stageCapture.regions.end()); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 8eee214e950b..2c09da748e8d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -420,16 +420,12 @@ std::shared_ptr recycledStageWords() { return HostThreadLocal, RecycledWordsStorage>().Take(ResetHeapStageWords); } -std::shared_ptr> recycledValues(const std::vector& values) { - auto copy = HostThreadLocal>, RecycledValuesStorage>().Take(clearRecycled>); - copy->assign(values.begin(), values.end()); - return copy; +std::shared_ptr> takeRecycledValues() { + return HostThreadLocal>, RecycledValuesStorage>().Take(clearRecycled>); } -std::shared_ptr recycledRanges(const AddressRanges& ranges) { - auto copy = HostThreadLocal, RecycledRangesStorage>().Take(clearRecycled); - copy->assign(ranges.begin(), ranges.end()); - return copy; +std::shared_ptr takeRecycledRanges() { + return HostThreadLocal, RecycledRangesStorage>().Take(clearRecycled); } } @@ -437,10 +433,9 @@ std::shared_ptr recycledRanges(const AddressRanges& ranges) HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, std::uint64_t shaderBase) { struct ReadsStorage {}; - struct RangesStorage {}; - struct ValuesStorage {}; auto& reads = HostThreadLocal(); - auto& ranges = HostThreadLocal(); + auto sharedRanges = takeRecycledRanges(); + auto& ranges = *sharedRanges; reads.Reset(); Graphics::HeapCostScope snapshotCost(Graphics::HeapCost::Guards); const auto before = Graphics::Recorder::PendingWriteSnapshot(); @@ -456,7 +451,8 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade return {}; } CoalesceWalkReads(reads.runs, ranges); - auto& values = HostThreadLocal, ValuesStorage>(); + auto sharedValues = takeRecycledValues(); + auto& values = *sharedValues; if (!reads.failed) copyRangeValues(ranges, values); const bool settled = rangesSettled(ranges, before.get(), generation); walkCost.Stop(); @@ -473,9 +469,7 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade materializeCost.Stop(); const bool complete = !reads.failed && result != nullptr; HeapStageMaterialized materialized; - auto shared = complete ? recycledValues(values) : nullptr; - auto sharedRanges = complete ? recycledRanges(ranges) : nullptr; - if (complete) materialized.reads = {sharedRanges, shared, capture->userDataUse, capture, true}; + if (complete) materialized.reads = {std::move(sharedRanges), std::move(sharedValues), capture->userDataUse, capture, true}; materialized.result = std::move(result); materialized.words = std::move(words); return materialized; From b43aa4817e0c1f61195917002b501be2e7f68ab5 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 01:54:38 +0530 Subject: [PATCH 216/269] perf(agc): trust a range the heap walk already proved accessible for the rest of the walk The walk asked the page table again for every SRT page change and every buffer range it checked. Remember the last proven spans for the walk, as its page cache already did for one page. --- .../Execution/src/Driver/Draw/HeapStages.cpp | 32 +++++++++++++++---- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 2c09da748e8d..bbb7ad15e4b9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -310,24 +310,42 @@ namespace { using AddressRanges = std::vector>; +constexpr std::size_t WalkVerifiedSpans = 8; + struct WalkReads { AddressRanges runs; - std::uint64_t page = ~std::uint64_t{0}; + std::array, WalkVerifiedSpans> verified{}; + std::size_t verifiedCount = 0; + std::size_t verifiedNext = 0; bool failed = false; void Reset() { runs.clear(); failed = false; - page = ~std::uint64_t{0}; + verifiedCount = 0; + verifiedNext = 0; + } + + bool Verified(std::uint64_t address, std::uint64_t bytes) const { + for (std::size_t i = 0; i < verifiedCount; ++i) { + if (address >= verified[i].first && address <= verified[i].second && bytes <= verified[i].second - address) return true; + } + return false; + } + + void Verify(std::uint64_t address, std::uint64_t bytes) { + verified[verifiedNext] = {address, address + bytes}; + verifiedNext = (verifiedNext + 1) % WalkVerifiedSpans; + verifiedCount = std::min(verifiedCount + 1, WalkVerifiedSpans); } }; bool readWalkWord(void* context, std::uint64_t address, std::uint32_t* value) { auto& reads = *static_cast(context); - const auto page = address & ~(WalkPageBytes - 1u); - const bool crossesPage = (address & (WalkPageBytes - 1u)) > WalkPageBytes - sizeof(*value); - if (page != reads.page || crossesPage) { - if (GuestMemory::Accessible(reinterpret_cast(page), WalkPageBytes)) reads.page = page; + if (!reads.Verified(address, sizeof(*value))) { + const auto page = address & ~(WalkPageBytes - 1u); + const bool crossesPage = (address & (WalkPageBytes - 1u)) > WalkPageBytes - sizeof(*value); + if (!crossesPage && GuestMemory::Accessible(reinterpret_cast(page), WalkPageBytes)) reads.Verify(page, WalkPageBytes); else if (!GuestMemory::Accessible(reinterpret_cast(address), sizeof(*value))) { reads.failed = true; return false; @@ -340,8 +358,10 @@ bool readWalkWord(void* context, std::uint64_t address, std::uint32_t* value) { bool walkAccessible(void* context, std::uint64_t address, std::uint64_t bytes) { auto& reads = *static_cast(context); + if (bytes != 0 && reads.Verified(address, bytes)) return true; const bool accessible = GuestMemory::Accessible(reinterpret_cast(address), static_cast(bytes)); if (!accessible) reads.failed = true; + else if (bytes != 0) reads.Verify(address, bytes); return accessible; } From 50b6bf710db67baf62ebb060092b72ed1936a425 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 04:35:41 +0530 Subject: [PATCH 217/269] perf(agc): look up a written buffer binding's words once per binding visitWrittenBuffers resolved the binding's descriptor words, from the heap stage in heap mode, again for every element of the binding. --- .../Execution/src/Driver/Memory/WrittenBuffers.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp index 41bbeace99ae..a51a8101f41b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp @@ -21,10 +21,11 @@ template void visitWrittenBuffers(const ShaderRecompiler::RecompileResult& compiled, TVisit&& visit, const ShaderRecompiler::HeapStageWords* heap = nullptr) { for (const auto& binding : compiled.bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; - for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto& guestWords = Graphics::DrawGuestWords(compiled, heap, binding); + const auto& guestWords = Graphics::DrawGuestWords(compiled, heap, binding); + const auto elements = std::min(binding.count, guestWords.size() / 4); + for (std::uint32_t element = 0; element < elements; ++element) { const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; - if (!written || guestWords.size() < (static_cast(element) + 1) * 4) continue; + if (!written) continue; const auto words = std::span(guestWords).subspan(static_cast(element) * 4, 4); const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; const auto base = descriptor.Base48(); From 9dfd5db61e78579f8f5b51a9d17bbd792f23bf2b Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 04:35:41 +0530 Subject: [PATCH 218/269] perf(agc): read a stage's walked user data from its capture instead of copying it Each captured stage copied the capture's user-data use, a vector, on every draw; heap stages copied it once more into their reads. The stage now keeps the capture that owns it. --- .../Execution/include/Driver/Draw/DrawCache.hpp | 4 +++- .../Execution/include/Driver/Draw/HeapStages.hpp | 1 - .../Execution/src/Driver/Draw/Draw.cpp | 4 ++-- .../Execution/src/Driver/Draw/DrawCapture.cpp | 15 +++++++++++---- .../Execution/src/Driver/Draw/HeapStages.cpp | 2 +- 5 files changed, 17 insertions(+), 9 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp index 825ab19300de..5cabc021941a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp @@ -132,13 +132,15 @@ struct StageCapture { std::vector> supplied; std::uint64_t forgetSerial = 0; std::uint32_t pushOffset = 0; - ShaderRecompiler::SrtUserDataUse userDataUse; + std::shared_ptr userDataOwner; std::uint64_t userDataMask = ~std::uint64_t{0}; bool direct = false; bool ring = false; std::shared_ptr heapWords; std::shared_ptr> heapReadWords; + const ShaderRecompiler::SrtUserDataUse& UserDataUse() const; + bool Cacheable() const { return !direct || ring; } }; diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index ee16999ecce9..06bf767be34b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -28,7 +28,6 @@ bool SampleHeapStageVerify(); struct HeapStageReads { std::shared_ptr>> ranges; std::shared_ptr> values; - ShaderRecompiler::SrtUserDataUse userDataUse; std::shared_ptr capture; bool complete = false; }; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 740e33880e72..e131324ae588 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -1370,7 +1370,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { const auto sameInfo = [&](const std::optional& a, const std::optional& b) { return a.has_value() == b.has_value() && (!a || sameVertexInfo(*a, *b)); }; const auto forwardRecordWords = [&](std::size_t programIndex, ShaderRecompiler::RecompileResult& result, const std::optional& previousInfo) { std::uint64_t walked = 0; - if (stageCaptures[programIndex].capture != nullptr) walked = stageCaptures[programIndex].userDataUse.asBase | stageCaptures[programIndex].userDataUse.asValue; + if (stageCaptures[programIndex].capture != nullptr) walked = stageCaptures[programIndex].UserDataUse().asBase | stageCaptures[programIndex].UserDataUse().asValue; else if (matched[programIndex] != nullptr) walked = matched[programIndex]->userWordsWalked; else return false; if ((graphics.stages.mesh && programIndex == 0) || !sameInfo(previousInfo, vertexInfos[programIndex])) return false; @@ -1392,7 +1392,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { const bool sameBindings = forwarded.bindings.size() == fresh.bindings.size() && std::equal(forwarded.bindings.begin(), forwarded.bindings.end(), fresh.bindings.begin(), [](const auto& a, const auto& b) { return a.kind == b.kind && a.role == b.role && a.binding == b.binding && a.count == b.count && a.guestDescriptor == b.guestDescriptor; }); std::uint64_t walked = 0; for (const auto& word : recordWords) { - if (word.program == programIndex && word.index < ShaderRecompiler::SrtUserDataUse::TrackedWords) walked |= (stageCaptures[programIndex].userDataUse.asBase | stageCaptures[programIndex].userDataUse.asValue) >> word.index & 1u; + if (word.program == programIndex && word.index < ShaderRecompiler::SrtUserDataUse::TrackedWords) walked |= (stageCaptures[programIndex].UserDataUse().asBase | stageCaptures[programIndex].UserDataUse().asValue) >> word.index & 1u; } const char* what = forwarded.variantId != fresh.variantId ? "variant" : forwarded.pushConstants != fresh.pushConstants ? "push constants" : !sameBindings ? "bindings" : forwarded.shaderDataUserWords != fresh.shaderDataUserWords ? "forwarded words" : walked != 0 ? "walked user word" : nullptr; ++wordsVerified; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index a345c5f2c847..26aa96e11d25 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -28,6 +28,12 @@ namespace AgcDriver::DriverDetail { +const ShaderRecompiler::SrtUserDataUse& StageCapture::UserDataUse() const { + static const ShaderRecompiler::SrtUserDataUse none; + return userDataOwner != nullptr ? userDataOwner->userDataUse : none; +} + + namespace { void TraceMaterializationFailure(std::uint64_t token, const Submission& submission, std::size_t packetOffset, std::size_t stage, const char* phase, const std::exception_ptr& failure) { @@ -124,8 +130,9 @@ bool Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t cursor += count; } stageCapture.heapReadWords = std::move(owned); - stageCapture.userDataMask = UserDataMask(program, context.vertexInfos[i], reads.userDataUse.asValue | reads.userDataUse.asBase, *stageCapture.compiled); - stageCapture.userDataUse = std::move(reads.userDataUse); + const auto& use = reads.capture->userDataUse; + stageCapture.userDataMask = UserDataMask(program, context.vertexInfos[i], use.asValue | use.asBase, *stageCapture.compiled); + stageCapture.userDataOwner = reads.capture; stageCapture.capture = std::move(reads.capture); stageCapture.ring = true; context.memory.insert(context.memory.end(), stageCapture.regions.begin(), stageCapture.regions.end()); @@ -232,7 +239,7 @@ std::shared_ptr Driver::materializeDraw stageCapture.regions = context.shaderMemory.TakeRecentRegions(); stageCapture.supplied = context.shaderMemory.SuppliedBlocks(); - stageCapture.userDataUse = capture->userDataUse; + stageCapture.userDataOwner = capture; stageCapture.registeredViews = std::make_shared>(capture->snapshot.registeredImages); context.recompiled[i] = true; context.memory = context.shaderMemory.Regions(); @@ -385,7 +392,7 @@ void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawP for (const auto& read : decodeReads[i]) regions.push_back({read.address, read.Bytes()}); std::stable_sort(regions.begin(), regions.end(), [](const ShaderRecompiler::MemoryRegion& a, const ShaderRecompiler::MemoryRegion& b) { return a.guestAddress < b.guestAddress; }); const bool relocatable = decodeReads[i].empty() && (!vertexInfos[i] || vertexInfos[i]->resourcesNum == 0); - tagVariantRuns(*variant, regions, stageCapture.userDataUse, relocatable, programs[i].hiddenUserWords, stageCapture.supplied); + tagVariantRuns(*variant, regions, stageCapture.UserDataUse(), relocatable, programs[i].hiddenUserWords, stageCapture.supplied); if (relocatable && (stageCapture.heapWords == nullptr || variant->ringTemplate != nullptr)) tagUserValueWords(*variant, programs[i], stageCapture.heapWords.get()); if (drawStageDataHits() && stageCapture.capture != nullptr && !stageCapture.capture->readTrace.leaves.empty()) recordStageDataPositions(*variant, *stageCapture.capture, decodeReads[i]); if (traceDrawCache() && entry != nullptr && matched[i] == nullptr && i < entry->stages.size()) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index bbb7ad15e4b9..ce0d99562607 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -489,7 +489,7 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade materializeCost.Stop(); const bool complete = !reads.failed && result != nullptr; HeapStageMaterialized materialized; - if (complete) materialized.reads = {std::move(sharedRanges), std::move(sharedValues), capture->userDataUse, capture, true}; + if (complete) materialized.reads = {std::move(sharedRanges), std::move(sharedValues), capture, true}; materialized.result = std::move(result); materialized.words = std::move(words); return materialized; From a68cf39e3939be8094e090aac62a1d85e73c4fea Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 05:02:33 +0530 Subject: [PATCH 219/269] perf(agc): test queued draw writes against the reads' hull before each read WrittenSince and OverlapsAny compared every read range with every queued write. A write outside the hull of the reads overlaps none of them, so only writes inside it are compared range by range. --- .../src/Driver/Draw/DrawPipeline.cpp | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp index 4845aab077b9..50dbbfd32ed1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp @@ -639,9 +639,15 @@ DrawPipeline::Watch DrawPipeline::WatchWrites() { } bool DrawPipeline::WrittenSince(const Watch& watch, const std::vector& reads) { - const auto overlaps = [&reads](const std::vector& writes) { - return std::any_of(reads.begin(), reads.end(), [&writes](const Range& read) { - return std::any_of(writes.begin(), writes.end(), [&read](const Range& write) { return read.first < write.second && write.first < read.second; }); + Range hull{~std::uint64_t{0}, 0}; + for (const auto& read : reads) { + hull.first = std::min(hull.first, read.first); + hull.second = std::max(hull.second, read.second); + } + const auto overlaps = [&reads, &hull](const std::vector& writes) { + return std::any_of(writes.begin(), writes.end(), [&](const Range& write) { + if (!(hull.first < write.second && write.first < hull.second)) return false; + return std::any_of(reads.begin(), reads.end(), [&write](const Range& read) { return read.first < write.second && write.first < read.second; }); }); }; if (DrawFinisher::Overlap() && DrawFinisher::Get().PendingOverlapsAny(reads)) return true; @@ -659,7 +665,14 @@ bool DrawPipeline::Busy() const { bool DrawPipeline::OverlapsAny(std::span> ranges) { if (DrawFinisher::Overlap() && DrawFinisher::Get().PendingOverlapsAny(ranges)) return true; std::lock_guard lock(mutex); + if (queuedWrites.empty() || ranges.empty()) return false; + std::pair hull{~std::uint64_t{0}, 0}; + for (const auto& [address, end] : ranges) { + hull.first = std::min(hull.first, address); + hull.second = std::max(hull.second, end); + } for (const auto& [range, count] : queuedWrites) { + if (!(hull.first < range.second && range.first < hull.second)) continue; for (const auto& [address, end] : ranges) { if (address < range.second && range.first < end) return true; } From 9cb6530a83b99a128ad736e8e71f931da82843cc Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 05:27:24 +0530 Subject: [PATCH 220/269] perf(shader): define AddSignedAddress inline in its header The SRT tape called it out of line for every address step it evaluates. --- core/shader/recompiler/CMakeLists.txt | 1 - .../SrtWalker/SrtAddressArithmetic.hpp | 20 ++++++++++++++- .../src/SrtWalker/SrtAddressArithmetic.cpp | 25 ------------------- 3 files changed, 19 insertions(+), 27 deletions(-) delete mode 100644 core/shader/recompiler/Optimization/src/SrtWalker/SrtAddressArithmetic.cpp diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index cefa48e13e67..ea0db5f8fc92 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -118,7 +118,6 @@ function(add_shader_recompiler target runtimeTarget) ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/DenormalFlushEliminator.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/VectorWindowStoreEliminator.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/RedundantValueEliminator.cpp - ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/SrtWalker/SrtAddressArithmetic.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/SrtWalker/SrtDescriptorEvaluation.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/SrtWalker/SrtDiagnostics.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/SrtWalker/SrtEvaluator.cpp diff --git a/core/shader/recompiler/Optimization/include/Optimization/SrtWalker/SrtAddressArithmetic.hpp b/core/shader/recompiler/Optimization/include/Optimization/SrtWalker/SrtAddressArithmetic.hpp index ae6e279ac180..69af7761e421 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/SrtWalker/SrtAddressArithmetic.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/SrtWalker/SrtAddressArithmetic.hpp @@ -7,7 +7,25 @@ namespace ShaderRecompiler::Detail { inline constexpr std::uint64_t AddressMask = 0x0000ffffffffffffull; -bool AddSignedAddress(std::uint64_t base, std::int64_t offset, std::uint64_t& result); +inline bool AddSignedAddress(std::uint64_t base, std::int64_t offset, std::uint64_t& result) { + if (base > AddressMask) { + return false; + } + if (offset < 0) { + const auto magnitude = std::uint64_t {0} - static_cast(offset); + if (magnitude > base) { + return false; + } + result = base - magnitude; + return true; + } + const auto magnitude = static_cast(offset); + if (magnitude > AddressMask - base) { + return false; + } + result = base + magnitude; + return true; +} } diff --git a/core/shader/recompiler/Optimization/src/SrtWalker/SrtAddressArithmetic.cpp b/core/shader/recompiler/Optimization/src/SrtWalker/SrtAddressArithmetic.cpp deleted file mode 100644 index 9040192bc658..000000000000 --- a/core/shader/recompiler/Optimization/src/SrtWalker/SrtAddressArithmetic.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "Optimization/SrtWalker/SrtAddressArithmetic.hpp" - -namespace ShaderRecompiler::Detail { - -bool AddSignedAddress(std::uint64_t base, std::int64_t offset, std::uint64_t& result) { - if (base > AddressMask) { - return false; - } - if (offset < 0) { - const auto magnitude = std::uint64_t {0} - static_cast(offset); - if (magnitude > base) { - return false; - } - result = base - magnitude; - return true; - } - const auto magnitude = static_cast(offset); - if (magnitude > AddressMask - base) { - return false; - } - result = base + magnitude; - return true; -} - -} From e31fd4b7b8529413ec647729b7c2e471698b6653 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 05:27:24 +0530 Subject: [PATCH 221/269] perf(agc): read a heap stage's flattened SRT from its words instead of a second copy CompleteHeapDataWords copied the stage's flattened SRT into its per-draw binding on every draw, though the stage already held those words. Draw words for the flattened SRT binding now come from the stage's own copy. --- .../Graphics/include/Shaders.hpp | 1 + .../tests/HeapStageWordsBase.cpp | 3 +++ core/shader/recompiler/Recompiler.cpp | 20 +++++++------------ 3 files changed, 11 insertions(+), 13 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp index 9c5437819427..dc391cdec151 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp @@ -97,6 +97,7 @@ inline const std::vector& DrawGuestWords(const ShaderRecompiler:: if (heap == nullptr) return binding.guestDescriptor; const auto index = static_cast(&binding - program.bindings.data()); if (index < heap->bindings.size() && !heap->bindings[index].empty()) return heap->bindings[index]; + if (binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt && !heap->flattenedSrt.empty()) return heap->flattenedSrt; const auto* base = heap->base.get(); const bool shared = binding.role != ShaderRecompiler::DescriptorRole::ShaderData && binding.role != ShaderRecompiler::DescriptorRole::FlattenedSrt; return shared && base != nullptr && index < base->bindings.size() && !base->bindings[index].empty() ? base->bindings[index] : binding.guestDescriptor; diff --git a/core/libs/prx/libSceAgcDriver/tests/HeapStageWordsBase.cpp b/core/libs/prx/libSceAgcDriver/tests/HeapStageWordsBase.cpp index ebec477bc580..133f0796cf9b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/HeapStageWordsBase.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/HeapStageWordsBase.cpp @@ -37,6 +37,9 @@ void TestTemplateWords() { Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[3]) == b[3].guestDescriptor, "a binding the template does not hold does not read the program's words"); Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[0]) == b[0].guestDescriptor, "shader data fell back to the template"); Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[2]) == b[2].guestDescriptor, "the flattened SRT fell back to the template"); + words.flattenedSrt = {70, 71}; + Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[2]) == words.flattenedSrt, "the flattened SRT does not read the stage's own words"); + words.flattenedSrt.clear(); words.bindings[1] = {60, 61, 62, 63, 64, 65, 66, 67}; Check(AgcDriver::Graphics::DrawGuestWords(program, &words, b[1]) == words.bindings[1], "per-draw words do not override the template's"); words.bindings[1].clear(); diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 9f9ac0cc3d25..faff3be5c133 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -2660,20 +2660,14 @@ void CompleteHeapDataWords(const RecompileResult& shared, HeapStageWords& words) if (!words.bindings.empty() && words.bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw bindings differ in number from its template"); for (std::size_t index = 0; index < count; ++index) { const auto& binding = shared.bindings[index]; - if (binding.role != DescriptorRole::ShaderData && binding.role != DescriptorRole::FlattenedSrt) continue; + if (binding.role != DescriptorRole::ShaderData) continue; if (!words.bindings.empty() && !words.bindings[index].empty()) continue; - if (binding.role == DescriptorRole::FlattenedSrt) { - if (words.flattenedSrt.empty() || words.flattenedSrt == binding.guestDescriptor) continue; - if (words.bindings.empty()) words.bindings.resize(count); - words.bindings[index].assign(words.flattenedSrt.begin(), words.flattenedSrt.end()); - } else { - const auto patched = std::min(words.userData.size(), binding.guestDescriptor.size()); - if (std::equal(words.userData.begin(), words.userData.begin() + static_cast(patched), binding.guestDescriptor.begin())) continue; - if (words.bindings.empty()) words.bindings.resize(count); - auto& descriptor = words.bindings[index]; - descriptor.assign(binding.guestDescriptor.begin(), binding.guestDescriptor.end()); - std::copy_n(words.userData.begin(), patched, descriptor.begin()); - } + const auto patched = std::min(words.userData.size(), binding.guestDescriptor.size()); + if (std::equal(words.userData.begin(), words.userData.begin() + static_cast(patched), binding.guestDescriptor.begin())) continue; + if (words.bindings.empty()) words.bindings.resize(count); + auto& descriptor = words.bindings[index]; + descriptor.assign(binding.guestDescriptor.begin(), binding.guestDescriptor.end()); + std::copy_n(words.userData.begin(), patched, descriptor.begin()); } } From a80c51feea1a91322d84ec9e53fee46da5582b38 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 06:22:35 +0530 Subject: [PATCH 222/269] fix(agc): keep main's moved buffer fields ahead of the heap's in-place view --- .../prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index dbddf1d4094a..b22c838eeb29 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -269,11 +269,11 @@ class ShaderResources { std::uint64_t address; std::size_t size; std::span words; - bool heapInPlace = false; - VkDeviceAddressRangeEXT view{}; VkBuffer inPlace = VK_NULL_HANDLE; VkDeviceSize inPlaceOffset = 0; std::uint32_t adjustment = 0; + bool heapInPlace = false; + VkDeviceAddressRangeEXT view{}; }; struct DrawUse { DrawUse() = default; From 84b925e123eb62d02d5565ea473a75684c6b8e10 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 06:22:35 +0530 Subject: [PATCH 223/269] fix(agc): bind the changed-copy pass through the heap-aware push wrappers --- .../prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp | 2 +- core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index c266826954e9..094da3e38abf 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -327,7 +327,7 @@ std::uint64_t DataAddressPushes(); std::uint64_t EmbeddedSamplerMappings(); std::uint64_t SlotPressureSubmits(); std::uint64_t HeapSlotEvictions(); -enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, DepthTransfer, StagedMerge, FirstSampleCopy, Count }; +enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, DepthTransfer, StagedMerge, FirstSampleCopy, ChangedCopy, Count }; enum class HeapExcluded : std::uint8_t { Draw, Dispatch, Count }; enum class HeapStageReason : std::uint8_t { Heap, diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 09079aae1350..31d4a32165a3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -3399,9 +3399,9 @@ bool Recorder::RecordBoundChangedCopy(VkCommandBuffer commands, BoundWords resul writes[binding].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; writes[binding].pBufferInfo = &infos[binding]; } - cmdPushChangedCopySet(commands, VK_PIPELINE_BIND_POINT_COMPUTE, boundChangedCopyLayout, 0, static_cast(writes.size()), writes.data()); + CmdPushDescriptorSet(cmdPushChangedCopySet, commands, VK_PIPELINE_BIND_POINT_COMPUTE, boundChangedCopyLayout, 0, static_cast(writes.size()), writes.data(), SetBindSite::ChangedCopy); const Parameters parameters{bases[0], bases[1], bases[2], count, alwaysCopy ? 1u : 0u, counter != VK_NULL_HANDLE ? 1u : 0u}; - function(cmdPushConstants, "vkCmdPushConstants")(commands, boundChangedCopyLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(parameters), ¶meters); + CmdPushConstants(context, commands, boundChangedCopyLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(parameters), ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, (count + GroupSize - 1) / GroupSize, 1, 1); done += count; } From 6751c9562d9acb76772457f272590b9bff82183b Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 06:22:35 +0530 Subject: [PATCH 224/269] fix(agc): fall back to the classic CMASK clear when its heap pipeline fails --- core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index 708b187754b5..f144c138f2fa 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -560,7 +560,8 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask heapInfo.stage.pNext = &mappingInfo; heapInfo.layout = VK_NULL_HANDLE; auto pipelineCacheLock = context.LockPipelineCacheForUse(); - created = context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &heapInfo, nullptr, &cmaskHeapPipeline); + if (context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &heapInfo, nullptr, &cmaskHeapPipeline) != VK_SUCCESS) + cmaskHeapPipeline = VK_NULL_HANDLE; } context.Function("vkDestroyShaderModule")(context.device, cmaskModule, nullptr); Check(created, "vkCreateComputePipelines CMASK clear"); From 067ae73fd8665ac4596654cecbe9a1c5163703d4 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 06:22:35 +0530 Subject: [PATCH 225/269] test(agc): sample the mirrored embedded sampler and reject a bench without timed rounds --- .../prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp | 3 ++- .../libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp index 0f13c5957b36..30e57e72e2a0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp @@ -327,6 +327,7 @@ int main(int argc, char** argv) { const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; const std::size_t draws = argc > 1 ? std::strtoull(argv[1], nullptr, 10) : 4000u; const std::size_t rounds = argc > 2 ? std::strtoull(argv[2], nullptr, 10) : 12u; + Require(draws > 0 && rounds >= 3, "the bench needs at least one draw and three rounds, the first two of which warm up"); { GuestAllocations::Mutation mutation; mutation.Add(BufferMemory.data(), sizeof(BufferMemory), true, true, true); @@ -354,7 +355,7 @@ int main(int argc, char** argv) { const bool tookHeap = AgcDriver::DriverDetail::HeapStagesTaken() > takenBefore; Require(tookHeap == heap, heap ? "the bench draws did not take the GPU heap" : "the bench draws took the GPU heap with it off"); const auto hits = AgcDriver::VulkanDevice::DrawRecipeHits() - hitsBefore; - if (rounds > 2 && AgcDriver::Graphics::DrawRecipes() && std::getenv("APS5_VERIFY_DRAW_ENTRIES") == nullptr) + if (AgcDriver::Graphics::DrawRecipes() && std::getenv("APS5_VERIFY_DRAW_ENTRIES") == nullptr) Require(hits >= (rounds - 2) * draws, "the bench's repeated draws replayed " + std::to_string(hits) + " recipes, fewer than the " + std::to_string((rounds - 2) * draws) + " draws of its repeated rounds"); std::printf("bench %s: %zu draws x %zu rounds: min %.3f us/draw, median %.3f us/draw, heap stages taken %s\n", heap ? "heap" : "per-draw", draws, perDraw.size(), perDraw.front(), perDraw[perDraw.size() / 2], tookHeap ? "yes" : "no"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp index 8226351a9072..a34d57c40d5c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp @@ -37,7 +37,7 @@ alignas(256) constexpr std::array UserSamplerCode{0x7e0002f3u, constexpr std::array White{0xffu, 0xffu, 0xffu, 0xffu}; alignas(256) std::array TextureMemory{}; -alignas(4096) std::array, 3> Outputs{}; +alignas(4096) std::array, 4> Outputs{}; ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, float* output, std::span code, bool userSampler) { auto userData = SampleUserData(TextureMemory.data(), output); @@ -90,7 +90,7 @@ int main() { const auto constant = Compile(*device, Outputs[0].data(), ConstantSamplerCode, false); const auto user = Compile(*device, Outputs[1].data(), UserSamplerCode, true); const auto wrap = Compile(*device, Outputs[2].data(), WrapSamplerCode, false); - const auto mirror = Compile(*device, Outputs[2].data(), MirrorSamplerCode, false); + const auto mirror = Compile(*device, Outputs[3].data(), MirrorSamplerCode, false); Require(constant.gpuResolvedImages == heap, "the constant-sampler stage is not in the expected mode"); Require((EmbeddedElements(constant) != 0u) == embedding, embedding ? "a constant sampler was not embedded" : "a sampler was embedded outside heap mode"); Require(DecoratesEmbeddedSet(constant) == embedding, "the stage's SPIR-V does not match its embedded samplers"); @@ -105,10 +105,12 @@ int main() { device->Dispatch(constant, 1u, 1u, 1u, {}, reinterpret_cast(ConstantSamplerCode.data())); device->Dispatch(user, 1u, 1u, 1u, {}, reinterpret_cast(UserSamplerCode.data())); device->Dispatch(wrap, 1u, 1u, 1u, {}, reinterpret_cast(WrapSamplerCode.data())); + device->Dispatch(mirror, 1u, 1u, 1u, {}, reinterpret_cast(MirrorSamplerCode.data())); device->WaitIdle(); RequireSampled(Outputs[0].data(), White, "the constant sampler's opaque white border", heap); RequireSampled(Outputs[1].data(), White, "the user-data sampler's opaque white border", heap); RequireSampled(Outputs[2].data(), SampleTexel, "the wrapping constant sampler's texel", heap); + RequireSampled(Outputs[3].data(), SampleTexel, "the mirroring constant sampler's texel", heap); if (embedding) { const bool capped = std::getenv("APS5_EMBEDDED_SAMPLER_CAP") != nullptr; const auto* heapObject = AgcDriver::Graphics::BindlessHeap::Existing(device->graphicsContext()); From 46e1efc5e6ef9af05bcd7e67e0193f36bb1cd9bb Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 06:50:43 +0530 Subject: [PATCH 226/269] refactor(agc): trim the GPU heap's dead APIs, duplicate counters and timing scopes --- .../Execution/src/Driver/Draw/DrawCapture.cpp | 5 - .../Execution/src/Driver/Draw/HeapStages.cpp | 11 +- .../Execution/src/VulkanDevice.cpp | 2 +- .../Graphics/include/BindlessHeap.hpp | 86 ++-- .../Graphics/include/Shaders.hpp | 4 +- .../Graphics/include/TextureDetiler.hpp | 4 +- .../Graphics/src/BindlessHeap.cpp | 373 ++++++------------ .../Graphics/src/DepthSurface.cpp | 33 +- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 4 - .../libSceAgcDriver/Graphics/src/Pipeline.cpp | 16 +- .../Graphics/src/ShaderResources.cpp | 3 - .../Graphics/src/TextureDetiler.cpp | 140 +++---- .../tests/BindlessHeapSlots.cpp | 42 +- .../tests/execution/HeapComputeSample.cpp | 4 +- .../tests/execution/HeapDrawSample.cpp | 7 +- .../tests/execution/HeapTableStageReuse.cpp | 3 +- docs/dev/ENVIRONMENT.md | 2 +- 17 files changed, 250 insertions(+), 489 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 26aa96e11d25..fc19ab7e8b4b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -99,14 +99,11 @@ bool Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t const auto& program = context.programs[i]; auto& stageCapture = context.stageCaptures[i]; HeapStageMaterialized materialized; - Graphics::HeapCostScope callCost(Graphics::HeapCost::HeapStageCall); try { materialized = MaterializeHeapStage(invocation, program.userData, program.binary.codeAddress); } catch (const std::exception& error) { throw stageFailure(program, request, error, request.context.memory); } - callCost.Stop(); - Graphics::HeapCostScope finishCost(Graphics::HeapCost::StageFinish); if (materialized.result == nullptr) return false; RequireHeapStageMappable(*materialized.result); NoteHeapDirect(); @@ -192,7 +189,6 @@ std::shared_ptr Driver::materializeDraw using Stage = ShaderRecompiler::ShaderStage; context.phaseTiming.Phase(DrawRowVectors); const auto& program = context.programs[i]; - Graphics::HeapCostScope prepareCost(Graphics::HeapCost::StagePrepare); auto request = drawStageRequest(context, i, pushOffset, drawParameters); const auto waitedBefore = traceCapSync() || context.profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0; @@ -214,7 +210,6 @@ std::shared_ptr Driver::materializeDraw throw std::runtime_error(std::string("AGC graphics: a GPU heap stage cannot take the heap: ") + ineligible); } Graphics::NoteHeapStageReason(stageReason); - prepareCost.Stop(); timing.Mark("prepared_invocation"); auto& stageCapture = context.stageCaptures[i]; stageCapture.direct = false; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index ce0d99562607..893c0ae59634 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -211,8 +211,7 @@ std::string heapClassesFailure(const ShaderRecompiler::RecompileResult& result) std::string heapStageFailure(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { if (auto failure = heapClassesFailure(result); !failure.empty()) return failure; std::pair refused{}; - if (!Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), workgroupAddress, result.dataAddressPush, - result.functionLdsBuffer, result.meshWindowBuffer, result.scratchPoolSlotDwords != 0u, &refused)) + if (!Graphics::DescriptorHeapMappable(std::span(result.spirv.data(), result.spirv.size()), {.workgroupAddress = workgroupAddress, .gdsAddress = result.dataAddressPush, .pixelLds = result.functionLdsBuffer, .meshWindow = result.meshWindowBuffer, .scratchPool = result.scratchPoolSlotDwords != 0u}, &refused)) return "AGC graphics: a GPU heap stage uses descriptor set " + std::to_string(refused.first) + " binding " + std::to_string(refused.second) + ", which the heap cannot map"; return {}; @@ -457,13 +456,10 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade auto sharedRanges = takeRecycledRanges(); auto& ranges = *sharedRanges; reads.Reset(); - Graphics::HeapCostScope snapshotCost(Graphics::HeapCost::Guards); const auto before = Graphics::Recorder::PendingWriteSnapshot(); - snapshotCost.Stop(); const auto generation = GuestMemory::StableTrackerGeneration(); const auto variant = invocation.VariantId(); - Graphics::HeapCostScope walkCost(Graphics::HeapCost::Walk); std::shared_ptr capture; try { capture = captureWalk(invocation, userData, shaderBase, reads); @@ -475,18 +471,13 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade auto& values = *sharedValues; if (!reads.failed) copyRangeValues(ranges, values); const bool settled = rangesSettled(ranges, before.get(), generation); - walkCost.Stop(); if (!settled) return {}; - Graphics::HeapCostScope guardCost(Graphics::HeapCost::Guards); guardRanges(ranges); - guardCost.Stop(); - Graphics::HeapCostScope materializeCost(Graphics::HeapCost::Materialize); auto words = recycledStageWords(); auto result = invocation.MaterializeHeap(*capture, *words); if (result == nullptr) result = invocation.Materialize(*capture); words->dataOrigin = NextHeapDataOrigin(); - materializeCost.Stop(); const bool complete = !reads.failed && result != nullptr; HeapStageMaterialized materialized; if (complete) materialized.reads = {std::move(sharedRanges), std::move(sharedValues), capture, true}; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 50368389591f..70cfa4926ecc 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -6363,7 +6363,7 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons const bool heapDevice = gpuMode && context.descriptorHeap && Graphics::DescriptorHeapEnabled(); const auto workgroupAddressOffset = workgroupAddress ? Graphics::ComputePushConstantBytes : ~0u; const std::span spirv(shader.spirv.data(), shader.spirv.size()); - objects->descriptorHeap = heapDevice && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(spirv, heapMappings, workgroupAddressOffset, shader.dataAddressPush, false, false, false, scratchPool, &objects->pushPlacements.front(), &shader.bindings); + objects->descriptorHeap = heapDevice && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(spirv, heapMappings, {.workgroupAddress = workgroupAddress, .gdsAddress = shader.dataAddressPush, .scratchPool = scratchPool}, &objects->pushPlacements.front(), &shader.bindings, workgroupAddressOffset); require(!gpuMode || objects->descriptorHeap, "a GPU-mode compute stage does not map onto VK_EXT_descriptor_heap"); const auto createPipelines = state->DeviceFunction("vkCreateComputePipelines"); if (objects->descriptorHeap) CreateComputeHeapPipeline(state->device, createPipelines, context.pipelineCache, objects->module, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, heapMappings, &objects->pipeline, context.pipelineCacheSynchronization); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 094da3e38abf..41a459b3f274 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -5,7 +5,6 @@ #include "RuntimeAbi.hpp" #include #include -#include #include #include #include @@ -26,6 +25,15 @@ struct DescriptorBinding; namespace AgcDriver::Graphics { +struct HeapBindingRoots { + bool workgroupAddress = false; + bool gdsAddress = false; + bool faultAddress = false; + bool pixelLds = false; + bool meshWindow = false; + bool scratchPool = false; +}; + class Buffer; class Recorder; class HeapSlotOwner; @@ -48,11 +56,9 @@ class BindlessHeap { bool DescriptorHeapMode() const { return resourceHeap != nullptr; } VkDeviceSize ImageHeapStride() const { return imageHeapStride; } void BindDescriptorHeaps(VkCommandBuffer commands) const; - bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, - std::uint32_t workgroupAddressOffset = ~0u, bool rootGds = false, bool rootFault = false, - bool pixelLds = false, bool meshWindow = false, bool scratchPool = false, + bool DescriptorHeapMappings(std::span spirv, std::vector& mappings, const HeapBindingRoots& roots, const ShaderRecompiler::StagePushPlacement* placement = nullptr, - const std::vector* bindings = nullptr) const; + const std::vector* bindings = nullptr, std::uint32_t workgroupAddressOffset = 0u); void WritePixelLdsBuffer(VkDeviceAddress address, VkDeviceSize bytes); void WriteMeshWindowBuffer(VkDeviceAddress address, VkDeviceSize bytes); std::pair DataLocation(VkDeviceAddress address) const; @@ -84,16 +90,7 @@ class BindlessHeap { VkDeviceAddress address = 0; }; DataSpan Allocate(std::size_t words); - struct SpanMark { - std::uint32_t offset = 0; - std::uint32_t words = 0; - std::uint64_t entry = 0; - std::uint32_t block = 0; - VkDeviceAddress address = 0; - }; - DataSpan Allocate(std::size_t words, SpanMark& mark); static void Write(const DataSpan& span, std::span words); - bool Held(const SpanMark& mark); class SpanScope { public: explicit SpanScope(const BindlessHeap& heap); @@ -106,7 +103,6 @@ class BindlessHeap { const BindlessHeap& heap; bool acquired; }; - std::optional KeepOrAllocate(const SpanScope& held, std::size_t words, SpanMark& mark, bool same); struct TableMark { std::uint32_t block = 0; std::uint32_t offset = 0; @@ -125,13 +121,15 @@ class BindlessHeap { struct Counts { std::uint64_t encodes = 0, encodedCopies = 0; - std::uint64_t slotsFreed = 0, slotsReused = 0, slotsEvicted = 0, evictionWaits = 0; + std::uint64_t slotsFreed = 0, slotsEvicted = 0, evictionWaits = 0; std::uint64_t spanPeakBytes = 0, imageSlotsHeld = 0; - std::uint64_t spansWritten = 0, spansKept = 0, spansExpired = 0; + std::uint64_t spansWritten = 0, spansKept = 0; std::uint64_t slotPressureSubmits = 0, samplersEvicted = 0; std::uint64_t poolBytes = 0, poolBatchPeakBytes = 0, poolBlocksMade = 0, poolBlocksRecycled = 0, poolBlocksFreed = 0, poolBlocksHeld = 0, poolBlockBytes = 0; + Counts& operator+=(const Counts& other); }; Counts Statistics() const; + static Counts TotalStatistics(); static constexpr std::size_t PoolBlockBytes = 2u << 20u; static constexpr std::size_t PoolIdleBytes = 32u << 20u; @@ -158,7 +156,6 @@ class BindlessHeap { VkDeviceAddress address = 0; std::size_t bytes = 0; std::size_t cursor = 0; - std::uint64_t generation = 0; Recorder* recorder = nullptr; std::uint64_t serial = 0; bool open = false; @@ -187,8 +184,7 @@ class BindlessHeap { std::uint32_t poolAlignment = 256; std::size_t poolBatchBytes = 0; std::size_t takePoolBlockLocked(std::size_t bytes); - bool heldLocked(const SpanMark& mark); - DataSpan allocateLocked(std::size_t words, SpanMark& mark); + DataSpan allocateLocked(std::size_t words); bool poolBlockDoneLocked(PoolBlock& block); void trimPoolLocked(); mutable std::mutex mutex; @@ -201,9 +197,9 @@ class BindlessHeap { std::uint32_t slot = ~0u; }; mutable std::mutex embeddedMutex; - mutable std::map, EmbeddedSampler> embeddedSamplers; - mutable std::uint32_t embeddedSamplerCount = 0; - std::optional embeddedSamplerMapping(const ShaderRecompiler::DescriptorBinding& binding, std::size_t element) const; + std::map, EmbeddedSampler> embeddedSamplers; + std::uint32_t embeddedSamplerCount = 0; + std::optional embeddedSamplerMapping(const ShaderRecompiler::DescriptorBinding& binding, std::size_t element); std::atomic slotSerial{1}; struct ImageSlotKey { std::uint32_t kind; @@ -233,7 +229,7 @@ class BindlessHeap { std::unique_ptr[]> generations; void Configure(std::uint32_t first, std::uint32_t slots); void Retire(std::uint32_t slot); - std::optional Take(bool& reused); + std::optional Take(); void Free(std::uint32_t slot); std::size_t Unused() const; std::uint32_t Generation(std::uint32_t slot) const; @@ -311,8 +307,7 @@ void SetDescriptorHeapDevice(bool available); bool DescriptorHeapEnabled(); bool ChooseUniformConstantBuffers(bool standardLayout, const VkPhysicalDeviceLimits& limits); bool UniformConstantBuffersEnabled(); -bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds = false, bool meshWindow = false, bool scratchPool = false, - std::pair* refused = nullptr); +bool DescriptorHeapMappable(std::span spirv, const HeapBindingRoots& roots, std::pair* refused = nullptr); void NoteHeapComputeStage(); std::uint64_t HeapComputeStages(); void NoteImageTableBuild(); @@ -325,8 +320,6 @@ void NoteEmptyResourceSet(); std::uint64_t EmptyResourceSets(); std::uint64_t DataAddressPushes(); std::uint64_t EmbeddedSamplerMappings(); -std::uint64_t SlotPressureSubmits(); -std::uint64_t HeapSlotEvictions(); enum class SetBindSite : std::uint8_t { Draw, Dispatch, Detiler, ColorTransfer, Presentation, DepthTransfer, StagedMerge, FirstSampleCopy, ChangedCopy, Count }; enum class HeapExcluded : std::uint8_t { Draw, Dispatch, Count }; enum class HeapStageReason : std::uint8_t { @@ -341,40 +334,6 @@ void NoteHeapExcluded(HeapExcluded reason); std::uint64_t HeapExcludedCount(HeapExcluded reason); std::uint64_t HeapStageReasons(HeapStageReason reason); void NoteCpuBufferCopy(std::uint64_t bytes); -enum class HeapCost : std::uint8_t { - StagePrepare, - HeapStageCall, - StageFinish, - Walk, - Materialize, - TemplateFind, - TemplateBuild, - Slots, - StageData, - Guards, - Count -}; -bool HeapCostTimed(); - -void NoteHeapCost(HeapCost cost, std::uint64_t nanoseconds); -class HeapCostScope { -public: - explicit HeapCostScope(HeapCost cost) : - cost(cost), start(HeapCostTimed() ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}) {} - ~HeapCostScope() { Stop(); } - HeapCostScope(const HeapCostScope&) = delete; - HeapCostScope& operator=(const HeapCostScope&) = delete; - void Stop() { - if (start == std::chrono::steady_clock::time_point{}) return; - NoteHeapCost(cost, static_cast( - std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count())); - start = {}; - } - -private: - HeapCost cost; - std::chrono::steady_clock::time_point start; -}; void NoteCommandBufferBegun(VkCommandBuffer commands); void CmdPushConstants(const Context& context, VkCommandBuffer commands, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, std::uint32_t size, const void* values); @@ -385,6 +344,7 @@ void CmdPushDescriptorSet(PFN_vkCmdPushDescriptorSetKHR push, VkCommandBuffer co std::uint64_t DescriptorHeapBinds(); inline constexpr std::uint32_t HeapPassSampledKind = ShaderRecompiler::RuntimeAbi::FirstImageBinding; inline constexpr std::uint32_t HeapPassStorageKind = ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding; +inline constexpr VkSpirvResourceTypeFlagsEXT HeapPassStorageBuffers = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT; inline constexpr VkSpirvResourceTypeFlagsEXT HeapPassStorageImages = VK_SPIRV_RESOURCE_TYPE_READ_ONLY_IMAGE_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; class HeapPassSlots : public HeapSlotOwner { public: @@ -396,7 +356,7 @@ class HeapPassSlots : public HeapSlotOwner { Context context; }; bool HeapPassesActive(const Context& context); -VkDescriptorSetAndBindingMappingEXT HeapPushAddressMapping(std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset); +VkDescriptorSetAndBindingMappingEXT HeapPushAddressMapping(std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset, VkSpirvResourceTypeFlagsEXT resources = HeapPassStorageBuffers); VkDescriptorSetAndBindingMappingEXT HeapPushIndexMapping(const BindlessHeap& heap, std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, std::uint32_t pushOffset); VkPipeline CreateHeapComputePipeline(const Context& context, VkComputePipelineCreateInfo info, std::span mappings); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp index dc391cdec151..7073ef67efc9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp @@ -19,10 +19,8 @@ inline constexpr std::uint32_t PipelinePushSlotBytes = 128; inline constexpr std::uint32_t ComputePushConstantBytes = 128; inline constexpr std::uint32_t HeapLayoutKeyTag = 0x48454150u; -inline constexpr std::uint32_t DataSetKeyTag = 0x44415441u; inline constexpr std::uint32_t MainSetBit = 1u; -inline constexpr std::uint32_t HeapSetBit = 2u; -inline constexpr std::uint32_t DataSetBit = 4u; +inline constexpr std::uint32_t FragmentSetBit = 2u; inline std::uint32_t PushBlockBytes(bool libraries) { return libraries ? PipelinePushConstantBytes : PipelinePushSlotBytes; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp index ab23c7cd82e7..39e3feea6eab 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp @@ -38,6 +38,8 @@ class HeapSlotOwner; std::uint32_t pipeBankXor = 0; }; + enum class DetileVariant : std::uint8_t { Classic, Addressed, Heap }; + class TextureDetiler { public: explicit TextureDetiler(const Context& context); @@ -63,7 +65,7 @@ class HeapSlotOwner; private: VkPipeline multisampleReadbackPipeline(std::uint32_t elementBytes, bool depth, bool heap); VkPipeline multisampleUploadPipeline(std::uint32_t elementBytes, bool heap); - VkPipeline pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image = false, bool addressed = false, bool heap = false); + VkPipeline pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image = false, DetileVariant variant = DetileVariant::Classic); VkDeviceAddress bufferAddress(VkBuffer buffer) const; void release() noexcept; struct DescriptorRing { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index a5d2ee6288fc..6f58db7dbb04 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -65,8 +65,6 @@ std::atomic userWordsRewrites{0}; std::atomic userWordsRewriteBlockWords{0}; std::atomic userWordsRewriteUserWords{0}; std::atomic embeddedSamplerMappings{0}; -std::atomic slotPressureSubmits{0}; -std::atomic heapSlotEvictions{0}; std::atomic emptyResourceSets{0}; } @@ -119,14 +117,6 @@ std::uint64_t EmbeddedSamplerMappings() { return embeddedSamplerMappings.load(std::memory_order_relaxed); } -std::uint64_t SlotPressureSubmits() { - return slotPressureSubmits.load(std::memory_order_relaxed); -} - -std::uint64_t HeapSlotEvictions() { - return heapSlotEvictions.load(std::memory_order_relaxed); -} - void NoteEmptyResourceSet() { countOnRecordingThread(emptyResourceSets, 1); } @@ -250,6 +240,17 @@ std::uint32_t configuredSlotCap(std::uint32_t slots) { std::atomic deviceImageSlots{Abi::GpuImageHeapSlots}; +constexpr VkBufferUsageFlags DataBlockUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + +std::unique_ptr makeHeapBuffer(const Context& context, std::size_t bytes, VkBufferUsageFlags usage) { + constexpr VkMemoryPropertyFlags deviceVisible = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + try { + return std::make_unique(context, bytes, usage, deviceVisible); + } catch (const std::exception&) { + } + return std::make_unique(context, bytes, usage); +} + } BindlessHeap::BindlessHeap(const Context& context) : context(context) { @@ -263,17 +264,9 @@ BindlessHeap::BindlessHeap(const Context& context) : context(context) { meshWindowHeapOffset = sizes.meshWindowOffset; samplerHeapUsed = sizes.samplerUsed; Require(Fits(heapProperties), "the GPU heap's slots exceed the device's descriptor heap sizes"); - constexpr VkMemoryPropertyFlags deviceVisible = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - const auto makeBuffer = [&](std::size_t bytes, VkBufferUsageFlags usage) { - try { - return std::make_unique(context, bytes, usage, deviceVisible); - } catch (const std::exception&) { - } - return std::make_unique(context, bytes, usage); - }; constexpr VkBufferUsageFlags heapUsage = VK_BUFFER_USAGE_DESCRIPTOR_HEAP_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - resourceHeap = makeBuffer(static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange), heapUsage); - samplerHeap = makeBuffer(static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage); + resourceHeap = makeHeapBuffer(context, static_cast(resourceHeapUsed + heapProperties.minResourceHeapReservedRange), heapUsage); + samplerHeap = makeHeapBuffer(context, static_cast(samplerHeapUsed + heapProperties.minSamplerHeapReservedRangeWithEmbedded), heapUsage); std::fill(resourceHeap->Bytes().begin(), resourceHeap->Bytes().end(), std::byte{0}); std::fill(samplerHeap->Bytes().begin(), samplerHeap->Bytes().end(), std::byte{0}); writeResourceDescriptors = context.Function("vkWriteResourceDescriptorsEXT"); @@ -328,20 +321,22 @@ CachedHeap& ThreadCachedHeap() { return cached; } +BindlessHeap* cachedHeap(VkDevice device) { + const auto& cached = ThreadCachedHeap(); + return cached.device == device && cached.epoch == heapsEpoch.load(std::memory_order_acquire) ? cached.heap : nullptr; +} + } BindlessHeap& BindlessHeap::For(const Context& context) { - auto& cached = ThreadCachedHeap(); - if (cached.heap != nullptr && cached.device == context.device && cached.epoch == heapsEpoch.load(std::memory_order_acquire)) { - return *cached.heap; - } + if (auto* cached = cachedHeap(context.device)) return *cached; std::lock_guard lock(heapsMutex()); auto& heap = heaps()[context.device]; if (heap == nullptr) { heap = std::make_unique(context); heapsEpoch.fetch_add(1, std::memory_order_acq_rel); } - cached = {context.device, heap.get(), heapsEpoch.load(std::memory_order_acquire)}; + ThreadCachedHeap() = {context.device, heap.get(), heapsEpoch.load(std::memory_order_acquire)}; return *heap; } @@ -358,12 +353,11 @@ void BindlessHeap::Release(VkDevice device) { } BindlessHeap* BindlessHeap::Existing(const Context& context) { - auto& cached = ThreadCachedHeap(); - if (cached.heap != nullptr && cached.device == context.device && cached.epoch == heapsEpoch.load(std::memory_order_acquire)) return cached.heap; + if (auto* cached = cachedHeap(context.device)) return cached; std::lock_guard lock(heapsMutex()); const auto found = heaps().find(context.device); if (found == heaps().end()) return nullptr; - cached = {context.device, found->second.get(), heapsEpoch.load(std::memory_order_acquire)}; + ThreadCachedHeap() = {context.device, found->second.get(), heapsEpoch.load(std::memory_order_acquire)}; return found->second.get(); } @@ -390,11 +384,9 @@ std::optional BindlessHeap::imageSlot(std::uint32_t kind, const H touchLocked(found->second); return found->second; } - bool reused = false; - auto slot = imagePool.Take(reused); - if (!slot && reclaimLocked(true)) slot = imagePool.Take(reused); + auto slot = imagePool.Take(); + if (!slot && reclaimLocked(true)) slot = imagePool.Take(); if (!slot) return std::nullopt; - if (reused) ++counts.slotsReused; writeImageSlot(kind, *slot, view, layout); claimSlotLocked(key, *slot).texture = texture; touchLocked(*slot); @@ -446,12 +438,10 @@ const BindlessHeap::SlotOwner* BindlessHeap::ownerLocked(std::uint32_t slot) con return slot < owners.size() ? &owners[slot] : nullptr; } -std::optional BindlessHeap::SlotPool::Take(bool& reused) { - reused = false; +std::optional BindlessHeap::SlotPool::Take() { if (!free.empty()) { const auto slot = free.back(); free.pop_back(); - reused = true; return slot; } if (next >= limit) return std::nullopt; @@ -564,7 +554,6 @@ void BindlessHeap::evictLocked(std::uint32_t idleSubmissions) { imagePool.Retire(slot); retiring.push_back({slot, 0u}); ++counts.slotsEvicted; - heapSlotEvictions.fetch_add(1, std::memory_order_relaxed); } slotSerial.fetch_add(1, std::memory_order_release); } @@ -591,7 +580,6 @@ void BindlessHeap::evictSamplersLocked(std::uint32_t idleSubmissions) { retiring.push_back({slot, 0u, true}); ++retiringSamplers; ++counts.samplersEvicted; - heapSlotEvictions.fetch_add(1, std::memory_order_relaxed); } slotSerial.fetch_add(1, std::memory_order_release); } @@ -696,11 +684,9 @@ std::optional BindlessHeap::samplerSlot(const std::shared_ptrsecond] = true; return found->second; } - bool reused = false; - auto slot = samplerPool.Take(reused); - if (!slot && reclaimLocked(true)) slot = samplerPool.Take(reused); + auto slot = samplerPool.Take(); + if (!slot && reclaimLocked(true)) slot = samplerPool.Take(); if (!slot) return std::nullopt; - if (reused) ++counts.slotsReused; writeSamplerSlot(*slot, sampler->Handle()); const HeapSlotOwner* owner = sampler.get(); samplerSlots.emplace(owner, *slot); @@ -717,8 +703,8 @@ std::optional BindlessHeap::samplerSlot(const std::shared_ptr= poolBlocks.size() || poolBlocks[index].generation != mark.entry) { - ++counts.spansExpired; - return false; - } - poolBlocks[index].open = true; - ++counts.spansKept; - return true; - } - return false; -} - void BindlessHeap::Write(const DataSpan& span, std::span words) { Require(words.size() <= span.words.size(), "the words written to a GPU heap span exceed it"); #if defined(__SSE2__) || defined(_M_X64) @@ -767,26 +732,8 @@ void BindlessHeap::Write(const DataSpan& span, std::span wo #endif } -BindlessHeap::DataSpan BindlessHeap::Allocate(std::size_t words, SpanMark& mark) { - SpanScope scope(*this); - return allocateLocked(words, mark); -} - -std::optional BindlessHeap::KeepOrAllocate(const SpanScope& held, std::size_t words, SpanMark& mark, bool same) { - Require(&held.heap == this, "a heap span was kept or allocated under another heap's lock"); - if (same && heldLocked(mark)) return std::nullopt; - return allocateLocked(words, mark); -} - std::size_t BindlessHeap::makeTableBlockLocked(std::size_t bytes) { - constexpr VkBufferUsageFlags usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - constexpr VkMemoryPropertyFlags deviceVisible = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - std::unique_ptr buffer; - try { - buffer = std::make_unique(context, bytes, usage, deviceVisible); - } catch (const std::exception&) { - } - if (buffer == nullptr) buffer = std::make_unique(context, bytes, usage); + auto buffer = makeHeapBuffer(context, bytes, DataBlockUsage); const auto vacant = std::find_if(tableBlocks.begin(), tableBlocks.end(), [](const TableBlock& block) { return block.buffer == nullptr; }); auto& block = vacant != tableBlocks.end() ? *vacant : tableBlocks.emplace_back(); block.data = buffer->Bytes().data(); @@ -858,7 +805,7 @@ void BindlessHeap::reclaimTablesLocked() { } } -BindlessHeap::DataSpan BindlessHeap::allocateLocked(std::size_t words, SpanMark& mark) { +BindlessHeap::DataSpan BindlessHeap::allocateLocked(std::size_t words) { const auto bytes = alignUp(std::max(words, 1u) * sizeof(std::uint32_t), SpanAlignment); if (poolCurrent >= poolBlocks.size() || alignUp(poolBlocks[poolCurrent].cursor, poolAlignment) + bytes > poolBlocks[poolCurrent].bytes) poolCurrent = takePoolBlockLocked(bytes); auto& block = poolBlocks[poolCurrent]; @@ -869,8 +816,7 @@ BindlessHeap::DataSpan BindlessHeap::allocateLocked(std::size_t words, SpanMark& counts.poolBytes += bytes; counts.spanPeakBytes = std::max(counts.spanPeakBytes, bytes); poolBatchBytes += bytes; - mark = {static_cast(offset), static_cast(words), block.generation, static_cast(poolCurrent + 1u), block.address + offset}; - return {static_cast(offset), std::span(reinterpret_cast(block.data + offset), words), mark.address}; + return {static_cast(offset), std::span(reinterpret_cast(block.data + offset), words), block.address + offset}; } bool BindlessHeap::poolBlockDoneLocked(PoolBlock& block) { @@ -897,19 +843,11 @@ std::size_t BindlessHeap::takePoolBlockLocked(std::size_t bytes) { if (best < poolBlocks.size()) { auto& block = poolBlocks[best]; block.cursor = 0; - ++block.generation; ++counts.poolBlocksRecycled; return best; } const auto size = need == PoolBlockBytes ? PoolBlockBytes : static_cast(alignUp(need, PoolBlockBytes)); - constexpr VkBufferUsageFlags usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - constexpr VkMemoryPropertyFlags deviceVisible = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - std::unique_ptr buffer; - try { - buffer = std::make_unique(context, size, usage, deviceVisible); - } catch (const std::exception&) { - } - if (buffer == nullptr) buffer = std::make_unique(context, size, usage); + auto buffer = makeHeapBuffer(context, size, DataBlockUsage); if (vacant == poolBlocks.size()) poolBlocks.emplace_back(); auto& block = poolBlocks[vacant]; block.data = buffer->Bytes().data(); @@ -917,7 +855,6 @@ std::size_t BindlessHeap::takePoolBlockLocked(std::size_t bytes) { block.buffer = std::move(buffer); block.bytes = size; block.cursor = 0; - ++block.generation; block.recorder = nullptr; block.serial = 0u; block.open = false; @@ -939,7 +876,6 @@ void BindlessHeap::trimPoolLocked() { block.data = nullptr; block.address = 0; block.bytes = 0; - ++block.generation; ++counts.poolBlocksFreed; } } @@ -951,31 +887,44 @@ bool BindlessHeap::TakeSlotPressure() { if (imagePool.Unused() + imageRetiring() < 2u * static_cast(imageMargin())) evictLocked(0u); if (samplerPool.Unused() + retiringSamplers < 2u * SamplerSlotMargin) evictSamplersLocked(0u); ++counts.slotPressureSubmits; - slotPressureSubmits.fetch_add(1, std::memory_order_relaxed); return true; } +namespace { + +struct DataBlockHit { + Buffer* buffer = nullptr; + std::byte* data = nullptr; + VkDeviceAddress address = 0; +}; + +template +std::optional findIn(const std::vector& blocks, VkDeviceAddress address, std::size_t bytes) { + for (const auto& block : blocks) { + if (block.buffer != nullptr && address >= block.address && address + bytes <= block.address + block.bytes) return DataBlockHit{block.buffer.get(), block.data, block.address}; + } + return std::nullopt; +} + +template +DataBlockHit findBlock(const PoolBlocks& pool, const TableBlocks& tables, VkDeviceAddress address, std::size_t bytes, const char* outside) { + if (const auto hit = findIn(pool, address, bytes)) return *hit; + if (const auto hit = findIn(tables, address, bytes)) return *hit; + throw std::runtime_error(outside); +} + +} + std::span BindlessHeap::DataWords(VkDeviceAddress address, std::size_t words) const { SpanScope scope(*this); - const auto bytes = words * sizeof(std::uint32_t); - for (const auto& block : poolBlocks) { - if (block.buffer != nullptr && address >= block.address && address + bytes <= block.address + block.bytes) return {reinterpret_cast(block.data + (address - block.address)), words}; - } - for (const auto& block : tableBlocks) { - if (block.buffer != nullptr && address >= block.address && address + bytes <= block.address + block.bytes) return {reinterpret_cast(block.data + (address - block.address)), words}; - } - throw std::runtime_error("AGC bindless heap: the words read lie outside every data block"); + const auto block = findBlock(poolBlocks, tableBlocks, address, words * sizeof(std::uint32_t), "AGC bindless heap: the words read lie outside every data block"); + return {reinterpret_cast(block.data + (address - block.address)), words}; } std::pair BindlessHeap::DataLocation(VkDeviceAddress address) const { SpanScope scope(*this); - for (const auto& block : poolBlocks) { - if (block.buffer != nullptr && address >= block.address && address < block.address + block.bytes) return {block.buffer->Handle(), address - block.address}; - } - for (const auto& block : tableBlocks) { - if (block.buffer != nullptr && address >= block.address && address < block.address + block.bytes) return {block.buffer->Handle(), address - block.address}; - } - throw std::runtime_error("AGC bindless heap: shader data lies outside every data pool block"); + const auto block = findBlock(poolBlocks, tableBlocks, address, 1u, "AGC bindless heap: shader data lies outside every data pool block"); + return {block.buffer->Handle(), address - block.address}; } void BindlessHeap::writeSamplerSlot(std::uint32_t slot, VkSampler sampler) { @@ -1011,7 +960,6 @@ void BindlessHeap::writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImag resource.data.pImage = &imageInfo; encodeScratch.resize(stride); const VkHostAddressRangeEXT range{encodeScratch.data(), stride}; - if (writeResourceDescriptors == nullptr) writeResourceDescriptors = context.Function("vkWriteResourceDescriptorsEXT"); Check(writeResourceDescriptors(context.device, 1, &resource, &range), "vkWriteResourceDescriptorsEXT"); std::memcpy(target, encodeScratch.data(), stride); KeepEncodedImageView(view, record->generation, key, encodeScratch); @@ -1022,15 +970,6 @@ namespace { const std::uint32_t GeneratedFaultBinding = Abi::BindingNumber(Abi::Stage::TessellationControl, Abi::Binding::FaultBuffer); -struct HeapBindingRoots { - bool workgroupAddress = false; - bool gdsAddress = false; - bool faultAddress = false; - bool pixelLds = false; - bool meshWindow = false; - bool scratchPool = false; -}; - using SetAndBinding = std::pair; struct HeapBindingUse { @@ -1125,27 +1064,21 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& (!roots.pixelLds || use.pixelLdsMemory) && (!roots.meshWindow || use.meshWindowMemory) && (!roots.scratchPool || use.scratchPoolMemory); } -VkDescriptorSetAndBindingMappingEXT heapMapping(std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, - VkDeviceSize heapOffset, VkDeviceSize stride) { +VkDescriptorSetAndBindingMappingEXT baseMapping(std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, VkDescriptorMappingSourceEXT source) { VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; mapping.descriptorSet = set; mapping.firstBinding = binding; mapping.bindingCount = 1; mapping.resourceMask = resources; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT; - mapping.sourceData.constantOffset.heapOffset = static_cast(heapOffset); - mapping.sourceData.constantOffset.heapArrayStride = static_cast(stride); + mapping.source = source; return mapping; } -VkDescriptorSetAndBindingMappingEXT pushAddressMapping(std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = set; - mapping.firstBinding = binding; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; - mapping.sourceData.pushAddressOffset = pushOffset; +VkDescriptorSetAndBindingMappingEXT heapMapping(std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, + VkDeviceSize heapOffset, VkDeviceSize stride) { + auto mapping = baseMapping(set, binding, resources, VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT); + mapping.sourceData.constantOffset.heapOffset = static_cast(heapOffset); + mapping.sourceData.constantOffset.heapArrayStride = static_cast(stride); return mapping; } @@ -1156,14 +1089,10 @@ std::uint32_t rootItemOffset(const ShaderRecompiler::StagePushPlacement* placeme VkDescriptorSetAndBindingMappingEXT pushedBufferMapping(std::uint32_t binding, const ShaderRecompiler::StagePushPlacement* placement) { Require(placement != nullptr && binding < placement->pushedBuffers, "a heap mapping reads a pushed buffer its pipeline's push layout does not count"); - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = Abi::PushedBufferSet; - mapping.firstBinding = binding; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT; + auto mapping = baseMapping(Abi::PushedBufferSet, binding, VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT, + VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT); const auto root = binding < Abi::PushedBufferLimit ? placement->bufferRoots[binding] : Abi::NoPushPosition; if (root != Abi::NoPushPosition) { - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; mapping.sourceData.pushAddressOffset = root * static_cast(sizeof(std::uint32_t)); return mapping; } @@ -1175,24 +1104,16 @@ VkDescriptorSetAndBindingMappingEXT pushedBufferMapping(std::uint32_t binding, c } VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, const ShaderRecompiler::StagePushPlacement* placement) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = Abi::GpuDataSet; - mapping.firstBinding = binding; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; const bool user = binding % static_cast(Abi::Binding::Count) == static_cast(Abi::Binding::UserData); const bool userPlaced = user && placement != nullptr && placement->Item(Abi::RootItem::UserData) != Abi::NoPushPosition; - mapping.sourceData.pushAddressOffset = rootItemOffset(placement, userPlaced ? Abi::RootItem::UserData : Abi::RootItem::ShaderData); - return mapping; + return HeapPushAddressMapping(Abi::GpuDataSet, binding, rootItemOffset(placement, userPlaced ? Abi::RootItem::UserData : Abi::RootItem::ShaderData), VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT); } } -bool DescriptorHeapMappable(std::span spirv, bool workgroupAddress, bool gdsAddress, bool pixelLds, bool meshWindow, bool scratchPool, - std::pair* refused) { +bool DescriptorHeapMappable(std::span spirv, const HeapBindingRoots& roots, std::pair* refused) { HeapBindingUse use; - const bool mappable = heapBindings(spirv, {.workgroupAddress = workgroupAddress, .gdsAddress = gdsAddress, .pixelLds = pixelLds, .meshWindow = meshWindow, .scratchPool = scratchPool}, use); + const bool mappable = heapBindings(spirv, roots, use); if (!mappable && refused != nullptr) *refused = use.refused; if (!mappable && pipelineStats()) { static std::mutex causesMutex; @@ -1203,7 +1124,7 @@ bool DescriptorHeapMappable(std::span spirv, bool workgroup std::fprintf( stderr, "[gpu-heap] unmappable stage: descriptor set %d binding %d (workgroup address %d, gds address %d); %llu stage variants with this cause\n", - static_cast(use.refused.first), static_cast(use.refused.second), workgroupAddress ? 1 : 0, gdsAddress ? 1 : 0, + static_cast(use.refused.first), static_cast(use.refused.second), roots.workgroupAddress ? 1 : 0, roots.gdsAddress ? 1 : 0, static_cast(count)); } } @@ -1230,7 +1151,7 @@ std::uint32_t BindlessHeap::EmbeddedSamplerCount() const { return embeddedSamplerCount; } -std::optional BindlessHeap::embeddedSamplerMapping(const ShaderRecompiler::DescriptorBinding& binding, std::size_t element) const { +std::optional BindlessHeap::embeddedSamplerMapping(const ShaderRecompiler::DescriptorBinding& binding, std::size_t element) { if (binding.samplerEmbeddedWords.size() < (element + 1u) * 4u || element >= binding.samplerDepthCompare.size()) return std::nullopt; std::array words{}; std::copy_n(binding.samplerEmbeddedWords.begin() + static_cast(element * 4u), 4u, words.begin()); @@ -1239,12 +1160,7 @@ std::optional BindlessHeap::embeddedSampler const bool unnormalized = element < binding.samplerUnnormalized.size() && binding.samplerUnnormalized[element]; const bool integerBorder = element < binding.samplerIntegerBorder.size() && binding.samplerIntegerBorder[element]; const std::array key{words[0], words[1], words[2], words[3], (compare ? 1u : 0u) | (unnormalized ? 2u : 0u) | (integerBorder ? 4u : 0u)}; - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = Abi::EmbeddedSamplerSet; - mapping.firstBinding = binding.samplerEmbedded[element]; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT; + auto mapping = baseMapping(Abi::EmbeddedSamplerSet, binding.samplerEmbedded[element], VK_SPIRV_RESOURCE_TYPE_SAMPLER_BIT_EXT, VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT); std::lock_guard lock(embeddedMutex); auto found = embeddedSamplers.find(key); if (found == embeddedSamplers.end()) { @@ -1264,7 +1180,7 @@ std::optional BindlessHeap::embeddedSampler return mapping; } if (entry.slot == ~0u) { - const auto slot = const_cast(this)->PinnedSamplerSlot(entry.heapSampler); + const auto slot = PinnedSamplerSlot(entry.heapSampler); Require(slot.has_value(), "the global sampler heap is full"); entry.slot = *slot; } @@ -1272,16 +1188,12 @@ std::optional BindlessHeap::embeddedSampler return mapping; } -bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::vector& mappings, - std::uint32_t workgroupAddressOffset, bool rootGds, bool rootFault, bool pixelLds, bool meshWindow, - bool scratchPool, const ShaderRecompiler::StagePushPlacement* placement, - const std::vector* bindings) const { +bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::vector& mappings, const HeapBindingRoots& roots, + const ShaderRecompiler::StagePushPlacement* placement, const std::vector* bindings, + std::uint32_t workgroupAddressOffset) { mappings.clear(); if (resourceHeap == nullptr) return false; HeapBindingUse use; - const HeapBindingRoots roots{ - .workgroupAddress = workgroupAddressOffset != ~0u, .gdsAddress = rootGds, .faultAddress = rootFault, .pixelLds = pixelLds, .meshWindow = meshWindow, - .scratchPool = scratchPool}; if (!heapBindings(spirv, roots, use)) return false; constexpr auto bindingCount = static_cast(Abi::Binding::Count); constexpr VkSpirvResourceTypeFlagsEXT imageResources = VK_SPIRV_RESOURCE_TYPE_SAMPLED_IMAGE_BIT_EXT | @@ -1313,13 +1225,13 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, std::ranges::sort(use.pushedBuffers); for (const auto binding : use.pushedBuffers) mappings.push_back(pushedBufferMapping(binding, placement)); if (use.workgroupMemory) - mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset)); + mappings.push_back(HeapPushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset, VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT)); if (use.scratchPoolMemory) - mappings.push_back(pushAddressMapping(ShaderRecompiler::GpuScratchPoolDescriptorSet, 0, ShaderRecompiler::GpuScratchPoolAddressPushByte)); + mappings.push_back(HeapPushAddressMapping(ShaderRecompiler::GpuScratchPoolDescriptorSet, 0, ShaderRecompiler::GpuScratchPoolAddressPushByte, VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT)); if (use.gdsBinding != ~0u) - mappings.push_back(pushAddressMapping(Abi::GpuGdsSet, use.gdsBinding, rootItemOffset(placement, Abi::RootItem::GdsAddress))); + mappings.push_back(HeapPushAddressMapping(Abi::GpuGdsSet, use.gdsBinding, rootItemOffset(placement, Abi::RootItem::GdsAddress), VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT)); if (use.faultMemory) - mappings.push_back(pushAddressMapping(Abi::DescriptorSet, GeneratedFaultBinding, rootItemOffset(placement, Abi::RootItem::FaultAddress))); + mappings.push_back(HeapPushAddressMapping(Abi::DescriptorSet, GeneratedFaultBinding, rootItemOffset(placement, Abi::RootItem::FaultAddress), VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT)); if (use.pixelLdsMemory) mappings.push_back(heapMapping(ShaderRecompiler::PixelFunctionLdsDescriptorSet, 0, VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT, pixelLdsHeapOffset, 0)); @@ -1337,7 +1249,7 @@ void BindlessHeap::writeBufferDescriptor(VkDeviceSize offset, VkDeviceAddress ad resource.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; resource.data.pAddressRange = &buffer; const VkHostAddressRangeEXT range{resourceHeap->Bytes().data() + offset, static_cast(properties.bufferDescriptorSize)}; - Check(context.Function("vkWriteResourceDescriptorsEXT")(context.device, 1, &resource, &range), + Check(writeResourceDescriptors(context.device, 1, &resource, &range), (std::string("vkWriteResourceDescriptorsEXT ") + what).c_str()); } @@ -1355,7 +1267,6 @@ std::mutex boundHeapsMutex; std::unordered_set boundHeaps; std::atomic boundHeapsEpoch{0}; std::atomic heapBinds{0}; -std::atomic heapBindWindow{0}; std::atomic commandBuffersBegun{0}; std::atomic cpuBufferCopies{0}; std::atomic cpuBufferCopyBytes{0}; @@ -1387,11 +1298,6 @@ unsigned long long printed(std::uint64_t value) { return static_cast(value); } -std::array, static_cast(HeapCost::Count)> heapCostNs{}; -std::array, static_cast(HeapCost::Count)> heapCostCalls{}; -constexpr std::array(HeapCost::Count)> HeapCostNames{ - "stage prepare", "heap stage call", "stage finish", "walk", "materialize", "template find", "template build", "slots", "stage data", "guards"}; - void reportHeapStatistics() { if (!pipelineStats()) return; static std::atomic calls{0}; @@ -1406,56 +1312,18 @@ void reportHeapStatistics() { const auto binds = takeNamedCounts(setBinds, SetBindSiteNames); const auto excluded = takeNamedCounts(heapExcludedCounts, HeapExcludedNames); const auto stageReasons = takeNamedCounts(heapStageReasons, HeapStageReasonNames); - std::string costs; - for (std::size_t i = 0; i < heapCostNs.size(); ++i) { - const auto calls = takeCount(heapCostCalls[i]); - const auto ns = static_cast(takeCount(heapCostNs[i])); - const auto averageUs = calls != 0 ? ns / static_cast(calls) / 1000.0 : 0.0; - char cost[96]; - std::snprintf(cost, sizeof(cost), " %s %llu x %.2f us = %.0f ms", HeapCostNames[i], printed(calls), averageUs, ns / 1e6); - costs += cost; - } - if (HeapCostTimed()) { - std::fprintf(stderr, "[gpu-heap] cost (10 s):%s\n", costs.c_str()); - } const auto heapDraws = takeCount(heapRecords[heapRecordIndex(false, true)]); const auto plainDraws = takeCount(heapRecords[heapRecordIndex(false, false)]); const auto heapDispatches = takeCount(heapRecords[heapRecordIndex(true, true)]); const auto plainDispatches = takeCount(heapRecords[heapRecordIndex(true, false)]); - const auto heapBindsSeen = takeCount(heapBindWindow); const auto commandBuffers = takeCount(commandBuffersBegun); const auto copies = takeCount(cpuBufferCopies); const auto copiedMiB = takeCount(cpuBufferCopyBytes) >> 20u; static BindlessHeap::Counts lastTotals; - BindlessHeap::Counts totals; - { - std::lock_guard heapsLock(heapsMutex()); - for (const auto& entry : heaps()) { - const auto counts = entry.second->Statistics(); - totals.spansWritten += counts.spansWritten; - totals.spansKept += counts.spansKept; - totals.spansExpired += counts.spansExpired; - totals.encodes += counts.encodes; - totals.encodedCopies += counts.encodedCopies; - totals.slotsEvicted += counts.slotsEvicted; - totals.evictionWaits += counts.evictionWaits; - totals.imageSlotsHeld += counts.imageSlotsHeld; - totals.spanPeakBytes = std::max(totals.spanPeakBytes, counts.spanPeakBytes); - totals.poolBytes += counts.poolBytes; - totals.slotPressureSubmits += counts.slotPressureSubmits; - totals.samplersEvicted += counts.samplersEvicted; - totals.poolBlocksMade += counts.poolBlocksMade; - totals.poolBlocksRecycled += counts.poolBlocksRecycled; - totals.poolBlocksFreed += counts.poolBlocksFreed; - totals.poolBlocksHeld += counts.poolBlocksHeld; - totals.poolBlockBytes += counts.poolBlockBytes; - totals.poolBatchPeakBytes = std::max(totals.poolBatchPeakBytes, counts.poolBatchPeakBytes); - } - } + const auto totals = BindlessHeap::TotalStatistics(); const auto windowDelta = [](std::uint64_t now, std::uint64_t before) { return now >= before ? now - before : now; }; const auto spansWritten = windowDelta(totals.spansWritten, lastTotals.spansWritten); const auto spansKept = windowDelta(totals.spansKept, lastTotals.spansKept); - const auto spansExpired = windowDelta(totals.spansExpired, lastTotals.spansExpired); const auto imageEncodes = windowDelta(totals.encodes, lastTotals.encodes); const auto imageCopies = windowDelta(totals.encodedCopies, lastTotals.encodedCopies); const auto slotsEvicted = windowDelta(totals.slotsEvicted, lastTotals.slotsEvicted); @@ -1467,6 +1335,10 @@ void reportHeapStatistics() { const auto poolRecycled = windowDelta(totals.poolBlocksRecycled, lastTotals.poolBlocksRecycled); const auto poolFreed = windowDelta(totals.poolBlocksFreed, lastTotals.poolBlocksFreed); lastTotals = totals; + static std::uint64_t lastBinds = 0; + const auto bindsTotal = heapBinds.load(std::memory_order_relaxed); + const auto heapBindsSeen = windowDelta(bindsTotal, lastBinds); + lastBinds = bindsTotal; static std::uint64_t lastPushedKeeps = 0; const auto pushedKeepsTotal = PushedUserDataKeeps(); const auto pushedKeeps = windowDelta(pushedKeepsTotal, lastPushedKeeps); @@ -1480,10 +1352,10 @@ void reportHeapStatistics() { std::fprintf(stderr, "[gpu-heap] (10 s): draws %llu heap / %llu plain, dispatches %llu heap / %llu plain; " "heap binds %llu over %llu command buffers; set binds:%s; excluded:%s; draw stages:%s; " - "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept (%llu for pushed user data only) / %llu expired, %llu written for user words only (%llu block words, %llu user words); data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; image descriptors %llu encoded / %llu copied; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", + "CPU buffer copies %llu (%llu MiB); spans %llu written / %llu kept (%llu for pushed user data only), %llu written for user words only (%llu block words, %llu user words); data pool %llu MiB written, %llu blocks (%llu MiB), %llu made / %llu recycled / %llu freed, since start at most %llu KiB per batch and %llu KiB per span; image descriptors %llu encoded / %llu copied; image slots %llu of %u held, %llu evicted (%llu waits); samplers evicted %llu; slot pressure submits %llu; templates %llu (%llu MiB, %llu evicted)\n", printed(heapDraws), printed(plainDraws), printed(heapDispatches), printed(plainDispatches), printed(heapBindsSeen), printed(commandBuffers), binds.c_str(), excluded.c_str(), stageReasons.c_str(), printed(copies), printed(copiedMiB), - printed(spansWritten), printed(spansKept), printed(pushedKeeps), printed(spansExpired), printed(userRewrites[0]), printed(userRewrites[1]), printed(userRewrites[2]), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.spanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); + printed(spansWritten), printed(spansKept), printed(pushedKeeps), printed(userRewrites[0]), printed(userRewrites[1]), printed(userRewrites[2]), printed(poolMiB), printed(totals.poolBlocksHeld), printed(totals.poolBlockBytes >> 20u), printed(poolMade), printed(poolRecycled), printed(poolFreed), printed(totals.poolBatchPeakBytes >> 10u), printed(totals.spanPeakBytes >> 10u), printed(imageEncodes), printed(imageCopies), printed(totals.imageSlotsHeld), BindlessHeap::ImageSlotCapacity(), printed(slotsEvicted), printed(evictionWaits), printed(samplersEvicted), printed(slotPressureSubmits), printed(templates.entries), printed(templates.bytes >> 20u), printed(templates.evicted)); } void forgetHeapBinding(VkCommandBuffer commands) { @@ -1505,19 +1377,6 @@ void NoteHeapStageReason(HeapStageReason reason) { heapStageReasons[static_cast(reason)].fetch_add(1, std::memory_order_relaxed); } -bool HeapCostTimed() { - static const bool timed = [] { - const char* stats = std::getenv("APS5_PIPELINE_STATS"); - return stats != nullptr && std::string_view(stats) == "2"; - }(); - return timed; -} - -void NoteHeapCost(HeapCost cost, std::uint64_t nanoseconds) { - heapCostNs[static_cast(cost)].fetch_add(nanoseconds, std::memory_order_relaxed); - heapCostCalls[static_cast(cost)].fetch_add(1, std::memory_order_relaxed); -} - void NoteCpuBufferCopy(std::uint64_t bytes) { cpuBufferCopies.fetch_add(1, std::memory_order_relaxed); cpuBufferCopyBytes.fetch_add(bytes, std::memory_order_relaxed); @@ -1569,25 +1428,15 @@ bool HeapPassesActive(const Context& context) { return DescriptorHeapEnabled() && context.descriptorHeap && BindlessHeap::For(context).DescriptorHeapMode(); } -VkDescriptorSetAndBindingMappingEXT HeapPushAddressMapping(std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = set; - mapping.firstBinding = binding; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; +VkDescriptorSetAndBindingMappingEXT HeapPushAddressMapping(std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset, VkSpirvResourceTypeFlagsEXT resources) { + auto mapping = baseMapping(set, binding, resources, VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT); mapping.sourceData.pushAddressOffset = pushOffset; return mapping; } VkDescriptorSetAndBindingMappingEXT HeapPushIndexMapping(const BindlessHeap& heap, std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, std::uint32_t pushOffset) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = set; - mapping.firstBinding = binding; - mapping.bindingCount = 1; - mapping.resourceMask = resources; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; + auto mapping = baseMapping(set, binding, resources, VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT); mapping.sourceData.pushIndex.pushOffset = pushOffset; mapping.sourceData.pushIndex.heapIndexStride = static_cast(heap.ImageHeapStride()); mapping.sourceData.pushIndex.heapArrayStride = static_cast(heap.ImageHeapStride()); @@ -1679,7 +1528,6 @@ void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { if (!inserted) return; } heapBinds.fetch_add(1, std::memory_order_relaxed); - heapBindWindow.fetch_add(1, std::memory_order_relaxed); VkBindHeapInfoEXT info{VK_STRUCTURE_TYPE_BIND_HEAP_INFO_EXT}; info.heapRange = {resourceHeap->DeviceAddress(), resourceHeapUsed + context.descriptorHeapProperties.minResourceHeapReservedRange}; info.reservedRangeOffset = resourceHeapUsed; @@ -1727,6 +1575,35 @@ void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { trimPoolLocked(); } +BindlessHeap::Counts& BindlessHeap::Counts::operator+=(const Counts& other) { + encodes += other.encodes; + encodedCopies += other.encodedCopies; + slotsFreed += other.slotsFreed; + slotsEvicted += other.slotsEvicted; + evictionWaits += other.evictionWaits; + imageSlotsHeld += other.imageSlotsHeld; + spansWritten += other.spansWritten; + spansKept += other.spansKept; + slotPressureSubmits += other.slotPressureSubmits; + samplersEvicted += other.samplersEvicted; + poolBytes += other.poolBytes; + poolBlocksMade += other.poolBlocksMade; + poolBlocksRecycled += other.poolBlocksRecycled; + poolBlocksFreed += other.poolBlocksFreed; + poolBlocksHeld += other.poolBlocksHeld; + poolBlockBytes += other.poolBlockBytes; + spanPeakBytes = std::max(spanPeakBytes, other.spanPeakBytes); + poolBatchPeakBytes = std::max(poolBatchPeakBytes, other.poolBatchPeakBytes); + return *this; +} + +BindlessHeap::Counts BindlessHeap::TotalStatistics() { + Counts totals; + std::lock_guard lock(heapsMutex()); + for (const auto& entry : heaps()) totals += entry.second->Statistics(); + return totals; +} + BindlessHeap::Counts BindlessHeap::Statistics() const { SpanScope scope(*this); std::lock_guard lock(mutex); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp index e45758d163ab..a755fdd47576 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp @@ -1167,8 +1167,8 @@ class DepthSurface { bool Overlaps(std::uint64_t address, std::uint64_t bytes) const { const auto end = address + bytes; - if (address < target.address + depthBytes() && target.address < end) return true; - return target.stencilAddress != 0 && address < target.stencilAddress + stencilBytes() && target.stencilAddress < end; + if (address < target.address + depthPlaneBytes && target.address < end) return true; + return target.stencilAddress != 0 && address < target.stencilAddress + stencilPlaneBytes && target.stencilAddress < end; } bool PlaneCoveredBy(bool stencilPlane, std::span> written, std::span extents) const { @@ -1189,9 +1189,9 @@ class DepthSurface { } return false; }; - if (stencilPlane) return target.stencilAddress != 0 && ((target.samples == 1u && reaches(target.stencilAddress, 1u)) || covers(target.stencilAddress, target.stencilAddress + stencilBytes())); + if (stencilPlane) return target.stencilAddress != 0 && ((target.samples == 1u && reaches(target.stencilAddress, 1u)) || covers(target.stencilAddress, target.stencilAddress + stencilPlaneBytes)); const bool d16 = target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT; - return (target.samples == 1u && reaches(target.address, d16 ? 2u : 4u)) || covers(target.address, target.address + depthBytes()); + return (target.samples == 1u && reaches(target.address, d16 ? 2u : 4u)) || covers(target.address, target.address + depthPlaneBytes); } bool CoveredBy(std::span> written, std::span extents) const { @@ -1200,26 +1200,26 @@ class DepthSurface { bool StencilWrittenInMemory() const { if (target.stencilAddress == 0) return false; - GuestMemory::CollectWrites(target.stencilAddress, static_cast(stencilBytes())); - return GuestMemory::WrittenSince(target.stencilAddress, static_cast(stencilBytes()), stencilMemory); + GuestMemory::CollectWrites(target.stencilAddress, static_cast(stencilPlaneBytes)); + return GuestMemory::WrittenSince(target.stencilAddress, static_cast(stencilPlaneBytes), stencilMemory); } void NoteMemory() { - depthMemory = GuestMemory::CollectWrites(target.address, static_cast(depthBytes())); - stencilMemory = target.stencilAddress != 0 ? GuestMemory::CollectWrites(target.stencilAddress, static_cast(stencilBytes())) : 0; + depthMemory = GuestMemory::CollectWrites(target.address, static_cast(depthPlaneBytes)); + stencilMemory = target.stencilAddress != 0 ? GuestMemory::CollectWrites(target.stencilAddress, static_cast(stencilPlaneBytes)) : 0; } bool OverwrittenOnGpu() const { - std::array, 2> ranges{{{target.address, target.address + depthBytes()}, {target.stencilAddress, target.stencilAddress + stencilBytes()}}}; + std::array, 2> ranges{{{target.address, target.address + depthPlaneBytes}, {target.stencilAddress, target.stencilAddress + stencilPlaneBytes}}}; return StorageTexture::AnyPendingOverlaps(std::span(ranges).first(target.stencilAddress != 0 ? 2u : 1u)); } bool OverwrittenInMemory() const { - GuestMemory::CollectWrites(target.address, static_cast(depthBytes())); - if (GuestMemory::WrittenSince(target.address, static_cast(depthBytes()), depthMemory)) return true; + GuestMemory::CollectWrites(target.address, static_cast(depthPlaneBytes)); + if (GuestMemory::WrittenSince(target.address, static_cast(depthPlaneBytes), depthMemory)) return true; if (target.stencilAddress == 0) return false; - GuestMemory::CollectWrites(target.stencilAddress, static_cast(stencilBytes())); - return GuestMemory::WrittenSince(target.stencilAddress, static_cast(stencilBytes()), stencilMemory); + GuestMemory::CollectWrites(target.stencilAddress, static_cast(stencilPlaneBytes)); + return GuestMemory::WrittenSince(target.stencilAddress, static_cast(stencilPlaneBytes), stencilMemory); } VkImageAspectFlags pendingClear = 0; @@ -2057,13 +2057,6 @@ class DepthSurface { stencilCopy = {}; } - std::uint64_t depthBytes() const { - return depthPlaneBytes; - } - - std::uint64_t stencilBytes() const { - return stencilPlaneBytes; - } PlaneStorage mirrorPlane; PlaneStorage stencilMirror; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index d8814e53230a..d501fc8d771c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -2301,7 +2301,6 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat // the alias checks instead. Debug aid: APS5_NO_DRAW_KEY_TRIM=1 keys them as before. static const bool trimKey = std::getenv("APS5_NO_DRAW_KEY_TRIM") == nullptr; const bool candidate = recordable && plan.candidate; - HeapCostScope findCost(HeapCost::TemplateFind); resolved.cacheable = recordable && plan.keyed; const auto address = candidate && !ShaderResources::SpaceReuseDisabled() ? addressStages(shaders) : AddressStages::None; std::optional reuse; @@ -2372,12 +2371,9 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat } else { countCache(&DrawProfile::uncacheable); } - findCost.Stop(); timer.phase(PhaseLookup); if (resolved.resources == nullptr) { - HeapCostScope buildCost(HeapCost::TemplateBuild); resolved.resources = std::make_shared(context, shaders, state.color, static_cast(state.colors.size()), draw.indexAddress, static_cast(indexBytes), snapshots, recordable && drawStagingEnabled()); - buildCost.Stop(); resolved.built = &resolved.resources->Timing(); outcome.addressBased = resolved.resources->HoldsLease(); outcome.kind = outcome.addressBased ? KindBda : KindBuild; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index dab45ae13021..78d85607ba97 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -23,7 +23,6 @@ #include #include #include -#include #include #include #include @@ -410,7 +409,7 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& if (resources.split) { auto& sets = shader.stage == Stage::Fragment ? keys.fragmentSets : keys.preRasterizationSets; if (HeapShader(shader)) { - sets |= HeapSetBit; + sets |= FragmentSetBit; for (const auto& binding : shader.program->bindings) { if (binding.descriptorSet == 0u) sets |= MainSetBit; } @@ -423,13 +422,13 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& } } if (resources.split && AnyHeapShader(shaders)) { - keys.preRasterizationSets |= HeapSetBit; - keys.fragmentSets |= HeapSetBit; + keys.preRasterizationSets |= FragmentSetBit; + keys.fragmentSets |= FragmentSetBit; } if (resources.split) { const auto unused = 3u & ~(keys.preRasterizationSets | keys.fragmentSets); keys.preRasterizationSets |= unused & MainSetBit; - keys.fragmentSets |= unused & HeapSetBit; + keys.fragmentSets |= unused & FragmentSetBit; } for (const auto& binding : input.bindings) { appendKey(keys.vertexInput, binding.binding); @@ -511,11 +510,10 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State& appendKey(key, resources.mainKey.size()); for (const auto word : resources.mainKey) appendKey(key, word); } - if ((sets & HeapSetBit) != 0u) { + if ((sets & FragmentSetBit) != 0u) { appendKey(key, resources.fragmentKey.size()); for (const auto word : resources.fragmentKey) appendKey(key, word); } - if ((sets & DataSetBit) != 0u) appendKey(key, DataSetKeyTag); }; splitKey(keys.layout, 3u); splitKey(keys.preRasterizationLayout, keys.preRasterizationSets); @@ -586,7 +584,9 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput const bool rooted = RootedPushData(shaders); descriptorHeap = std::all_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { const auto index = static_cast(&shader - shaders.data()); - return heap.DescriptorHeapMappings(std::span(shader.program->spirv.data(), shader.program->spirv.size()), heapMappings[index], ~0u, shader.program->dataAddressPush, PushesGeneratedFaultAddress(shader, rooted), shader.program->functionLdsBuffer, shader.program->meshWindowBuffer, false, &pushPlacements[index], &shader.program->bindings); + return heap.DescriptorHeapMappings(std::span(shader.program->spirv.data(), shader.program->spirv.size()), heapMappings[index], + {.gdsAddress = shader.program->dataAddressPush, .faultAddress = PushesGeneratedFaultAddress(shader, rooted), .pixelLds = shader.program->functionLdsBuffer, .meshWindow = shader.program->meshWindowBuffer}, + &pushPlacements[index], &shader.program->bindings); }); } Require(descriptorHeap || !AnyHeapShader(shaders), "a pipeline with GPU-mode stages does not map onto VK_EXT_descriptor_heap"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 4558c730e6c6..00ad9b9e93d2 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -8584,7 +8584,6 @@ std::pair ShaderResources::writeSplitHeapStage(con void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader) { namespace Abi = ShaderRecompiler::RuntimeAbi; - HeapCostScope slotsCost(HeapCost::Slots); const VkShaderStageFlags stageBit = VulkanStage(shader.stage); const auto stageIndex = HeapStageIndex(shader.stage); auto& stageState = heapStages[stageIndex]; @@ -8610,9 +8609,7 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl } stageState.slotSerial = slotSerial; if (verifySlots) verifyHeapSlots(heap, stageState, stageBit); - slotsCost.Stop(); - HeapCostScope dataCost(HeapCost::StageData); const std::size_t dataIndex = DataOffsetIndex(stageIndex, Abi::Binding::ShaderData); const std::size_t flatIndex = DataOffsetIndex(stageIndex, Abi::Binding::FlattenedSrt); const auto& program = *shader.program; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index f144c138f2fa..0b3c601ad64c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -78,29 +78,7 @@ struct HeapCmaskPush { static_assert(offsetof(HeapCmaskPush, cmask) == 32 && offsetof(HeapCmaskPush, errors) == 40 && offsetof(HeapCmaskPush, slot) == 48); -VkDescriptorSetAndBindingMappingEXT PushAddressMapping(std::uint32_t binding, std::uint32_t offset) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = 0; - mapping.firstBinding = binding; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; - mapping.sourceData.pushAddressOffset = offset; - return mapping; -} - -VkDescriptorSetAndBindingMappingEXT PushIndexMapping(const BindlessHeap& heap, std::uint32_t binding, std::uint32_t offset) { - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.descriptorSet = 0; - mapping.firstBinding = binding; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; - mapping.sourceData.pushIndex.pushOffset = offset; - mapping.sourceData.pushIndex.heapIndexStride = static_cast(heap.ImageHeapStride()); - mapping.sourceData.pushIndex.heapArrayStride = static_cast(heap.ImageHeapStride()); - return mapping; -} +constexpr VkSpirvResourceTypeFlagsEXT DetileImageResource = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_IMAGE_BIT_EXT; constexpr std::uint32_t DetileHeapKind = ShaderRecompiler::RuntimeAbi::FirstStorageImageBinding + 27u; @@ -130,8 +108,35 @@ std::uint32_t BlockBytesFor(TextureTileMode tileMode) { throw std::runtime_error("AGC graphics: TextureDetiler encountered an unknown tile mode"); } -std::uint32_t PipelineKey(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, bool addressed, bool heap) { - return (heap ? 1u << 20 : 0u) | (addressed ? 1u << 19 : 0u) | (image ? 1u << 18 : 0u) | (thick ? 1u << 17 : 0u) | (retile ? 1u << 16 : 0u) | (static_cast(tileMode) << 8) | elementBytes; +std::uint32_t PipelineKey(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, DetileVariant variant) { + return (variant == DetileVariant::Heap ? 1u << 20 : 0u) | (variant == DetileVariant::Addressed ? 1u << 19 : 0u) | (image ? 1u << 18 : 0u) | (thick ? 1u << 17 : 0u) | (retile ? 1u << 16 : 0u) | (static_cast(tileMode) << 8) | elementBytes; +} + +void writeBufferPair(const Context& context, VkDescriptorSet set, const VkDescriptorBufferInfo& first, const VkDescriptorBufferInfo& second) { + std::array writes{}; + for (std::uint32_t index = 0; index < writes.size(); ++index) { + writes[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[index].dstSet = set; + writes[index].dstBinding = index; + writes[index].descriptorCount = 1; + writes[index].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + writes[index].pBufferInfo = index == 0 ? &first : &second; + } + context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); +} + +void writeBufferImage(const Context& context, VkDescriptorSet set, const VkDescriptorBufferInfo& buffer, const VkDescriptorImageInfo& image) { + std::array writes{}; + for (std::uint32_t index = 0; index < writes.size(); ++index) { + writes[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[index].dstSet = set; + writes[index].dstBinding = index; + writes[index].descriptorCount = 1; + writes[index].descriptorType = index == 0 ? VK_DESCRIPTOR_TYPE_STORAGE_BUFFER : VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + } + writes[0].pBufferInfo = &buffer; + writes[1].pImageInfo = ℑ + context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); } } @@ -232,9 +237,10 @@ VkDeviceAddress TextureDetiler::bufferAddress(VkBuffer buffer) const { return BufferDeviceAddress(context, buffer); } -VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, bool addressed, bool heap) { +VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elementBytes, bool retile, bool thick, bool image, DetileVariant variant) { Require(std::has_single_bit(elementBytes) && elementBytes <= 16u, "unsupported element size for texture detiling"); - const auto key = PipelineKey(tileMode, elementBytes, retile, thick, image, addressed, heap); + const auto key = PipelineKey(tileMode, elementBytes, retile, thick, image, variant); + const bool heap = variant == DetileVariant::Heap; for (const auto& entry : pipelines) { if (entry.first == key) return entry.second; } @@ -268,7 +274,7 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem std::copy(equation->bits.begin(), equation->bits.end(), values.begin() + 4); } const bool descriptorWords = elementBytes < 4u && (image ? retile && values[2] != 2u : !retile || values[2] != 2u); - addressed = addressed || (heap && !image && descriptorWords); + const bool addressed = variant == DetileVariant::Addressed || (heap && !image && descriptorWords); if (addressed && addressedModule == VK_NULL_HANDLE) { VkShaderModuleCreateInfo moduleInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; moduleInfo.codeSize = sizeof(TEXTURE_DETILE_ADDRESSED_SPV); @@ -302,11 +308,11 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem auto heapFlags = DescriptorHeapFlags(); if (heap) { if (image) { - mappings[0] = PushAddressMapping(0, offsetof(HeapImagePush, tiled)); - mappings[1] = PushIndexMapping(BindlessHeap::For(context), 1, offsetof(HeapImagePush, slot)); + mappings[0] = HeapPushAddressMapping(0, 0, offsetof(HeapImagePush, tiled)); + mappings[1] = HeapPushIndexMapping(BindlessHeap::For(context), 0, 1, DetileImageResource, offsetof(HeapImagePush, slot)); } else if (!addressed) { - mappings[0] = PushAddressMapping(0, offsetof(AddressedPush, input)); - mappings[1] = PushAddressMapping(1, offsetof(AddressedPush, output)); + mappings[0] = HeapPushAddressMapping(0, 0, offsetof(AddressedPush, input)); + mappings[1] = HeapPushAddressMapping(0, 1, offsetof(AddressedPush, output)); } mappingInfo.mappingCount = addressed ? 0u : static_cast(mappings.size()); mappingInfo.pMappings = mappings.data(); @@ -364,33 +370,19 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode Require(sourceRange <= context.limits.maxStorageBufferRange && destinationRange <= context.limits.maxStorageBufferRange, "texture detiling buffer range exceeds device limits"); const auto sourceAddress = bufferAddress(source); const auto destinationAddress = sourceAddress != 0 ? bufferAddress(destination) : 0; - const auto heapPipeline = sourceAddress != 0 && destinationAddress != 0 && HeapPassesActive(context) ? pipeline(MipTileMode(tileMode, layout), elementBytes, retile, thickPipeline, false, false, true) : VK_NULL_HANDLE; - const bool heap = heapPipeline != VK_NULL_HANDLE; - const bool addressed = !heap && sourceAddress != 0 && destinationAddress != 0; - if (heap) { + const bool addressable = sourceAddress != 0 && destinationAddress != 0; + const auto tileModeOfMip = MipTileMode(tileMode, layout); + const auto heapPipeline = addressable && HeapPassesActive(context) ? pipeline(tileModeOfMip, elementBytes, retile, thickPipeline, false, DetileVariant::Heap) : VK_NULL_HANDLE; + const auto variant = heapPipeline != VK_NULL_HANDLE ? DetileVariant::Heap : addressable ? DetileVariant::Addressed : DetileVariant::Classic; + if (variant == DetileVariant::Heap) { BindlessHeap::For(context).BindDescriptorHeaps(commands); context.BindComputePipeline(commands, heapPipeline); - } else if (addressed) { - context.BindComputePipeline(commands, pipeline(MipTileMode(tileMode, layout), elementBytes, retile, thickPipeline, false, true)); + } else if (variant == DetileVariant::Addressed) { + context.BindComputePipeline(commands, pipeline(tileModeOfMip, elementBytes, retile, thickPipeline, false, DetileVariant::Addressed)); } else { const auto set = allocateSet(); - const VkDescriptorBufferInfo sourceInfo{source, sourceDescriptorOffset, sourceRange}; - const VkDescriptorBufferInfo destinationInfo{destination, destinationDescriptorOffset, destinationRange}; - std::array writes{}; - writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[0].dstSet = set; - writes[0].dstBinding = 0; - writes[0].descriptorCount = 1; - writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[0].pBufferInfo = &sourceInfo; - writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[1].dstSet = set; - writes[1].dstBinding = 1; - writes[1].descriptorCount = 1; - writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[1].pBufferInfo = &destinationInfo; - context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); - context.BindComputePipeline(commands, pipeline(MipTileMode(tileMode, layout), elementBytes, retile, thickPipeline)); + writeBufferPair(context, set, {source, sourceDescriptorOffset, sourceRange}, {destination, destinationDescriptorOffset, destinationRange}); + context.BindComputePipeline(commands, pipeline(tileModeOfMip, elementBytes, retile, thickPipeline)); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, SetBindSite::Detiler); } Push push{}; @@ -413,9 +405,9 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode push.rowBegin = window.rowBegin; push.pipeBankXor = window.pipeBankXor ^ layerBankXor(tileMode, elementBytes, layout, slice); push.splitStride = layout.gcnSplitStride; - if (heap || addressed) { + if (variant != DetileVariant::Classic) { const AddressedPush pushed{push, sourceAddress + sourceDescriptorOffset, destinationAddress + destinationDescriptorOffset}; - if (heap) CmdPushData(context, commands, sizeof(pushed), &pushed); + if (variant == DetileVariant::Heap) CmdPushData(context, commands, sizeof(pushed), &pushed); else CmdPushConstants(context, commands, addressedPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pushed), &pushed); } else { CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); @@ -441,7 +433,7 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &createInfo, nullptr, &repackPipeline), "vkCreateComputePipelines repack"); } - const std::array mappings{PushAddressMapping(0, offsetof(AddressedRepackPush, source)), PushAddressMapping(1, offsetof(AddressedRepackPush, destination))}; + const std::array mappings{HeapPushAddressMapping(0, 0, offsetof(AddressedRepackPush, source)), HeapPushAddressMapping(0, 1, offsetof(AddressedRepackPush, destination))}; heapRepackPipeline = CreateHeapComputePipeline(context, createInfo, mappings); } const auto alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); @@ -490,16 +482,7 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s const auto set = allocateSet(); const VkDescriptorBufferInfo sourceInfo{source, sourceDescriptorOffset, sourceRange}; const VkDescriptorBufferInfo destinationInfo{destination, destinationDescriptorOffset, destinationRange}; - std::array writes{}; - for (std::uint32_t index = 0; index < writes.size(); ++index) { - writes[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[index].dstSet = set; - writes[index].dstBinding = index; - writes[index].descriptorCount = 1; - writes[index].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[index].pBufferInfo = index == 0 ? &sourceInfo : &destinationInfo; - } - context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); + writeBufferPair(context, set, sourceInfo, destinationInfo); context.BindComputePipeline(commands, repackPipeline); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, SetBindSite::Detiler); CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(repackPush), repackPush.data()); @@ -550,7 +533,7 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask } if (created == VK_SUCCESS && addressedPipelineLayout != VK_NULL_HANDLE && DescriptorHeapEnabled() && BindlessHeap::For(context).DescriptorHeapMode()) { const auto& bindless = BindlessHeap::For(context); - const std::array mappings{PushAddressMapping(0, offsetof(HeapCmaskPush, cmask)), PushAddressMapping(1, offsetof(HeapCmaskPush, errors)), PushIndexMapping(bindless, 2, offsetof(HeapCmaskPush, slot))}; + const std::array mappings{HeapPushAddressMapping(0, 0, offsetof(HeapCmaskPush, cmask)), HeapPushAddressMapping(0, 1, offsetof(HeapCmaskPush, errors)), HeapPushIndexMapping(bindless, 0, 2, DetileImageResource, offsetof(HeapCmaskPush, slot))}; VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; mappingInfo.mappingCount = static_cast(mappings.size()); mappingInfo.pMappings = mappings.data(); @@ -655,7 +638,7 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til push.splitStride = layout.gcnSplitStride; std::optional slot; const auto tiledAddress = owner != nullptr && DescriptorHeapEnabled() ? bufferAddress(tiled) : 0; - const auto heapPipeline = tiledAddress != 0 ? pipeline(MipTileMode(tileMode, layout), elementBytes, retile, false, true, false, true) : VK_NULL_HANDLE; + const auto heapPipeline = tiledAddress != 0 ? pipeline(MipTileMode(tileMode, layout), elementBytes, retile, false, true, DetileVariant::Heap) : VK_NULL_HANDLE; if (heapPipeline != VK_NULL_HANDLE) slot = BindlessHeap::For(context).ViewSlot(DetileHeapKind, owner, view); if (slot) { auto& bindless = BindlessHeap::For(context); @@ -666,22 +649,7 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til } else { const auto target = pipeline(MipTileMode(tileMode, layout), elementBytes, retile, false, true); const auto set = allocateSet(true); - const VkDescriptorBufferInfo bufferInfo{tiled, descriptorOffset, range}; - const VkDescriptorImageInfo imageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}; - std::array writes{}; - writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[0].dstSet = set; - writes[0].dstBinding = 0; - writes[0].descriptorCount = 1; - writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[0].pBufferInfo = &bufferInfo; - writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[1].dstSet = set; - writes[1].dstBinding = 1; - writes[1].descriptorCount = 1; - writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - writes[1].pImageInfo = &imageInfo; - context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast(writes.size()), writes.data(), 0, nullptr); + writeBufferImage(context, set, {tiled, descriptorOffset, range}, {VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL}); context.BindComputePipeline(commands, target); CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0, 1, &set, SetBindSite::Detiler); CmdPushConstants(context, commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 786658b57234..7dbcdc391675 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -57,7 +57,7 @@ void textureSlots(const Context& context, VkImageView view) { require(heap.SlotGeneration(*slot) != generation, "a freed slot moves its generation"); require(heap.SlotTexture(kind, *slot) == second.get(), "the reused slot names the second texture"); const auto counts = heap.Statistics(); - require(counts.slotsFreed == 1u && counts.slotsReused == 1u, "one slot freed and reused"); + require(counts.slotsFreed == 1u, "one slot freed"); auto shared = fakeTexture(2); const auto otherKind = kind + 1u; @@ -157,7 +157,7 @@ void ownerViewsRelease(const Context& context, VkImageView view) { const auto serial = heap.SlotSerial(); require(heap.StorageSlot(firstKind, &owner, view) == first && heap.ViewSlot(secondKind, &owner, view) == second, "a lookup hit returns the owner's existing slots"); const auto hit = heap.Statistics(); - require(hit.slotsFreed == before.slotsFreed && hit.slotsReused == before.slotsReused && hit.encodes == before.encodes && hit.encodedCopies == before.encodedCopies, + require(hit.slotsFreed == before.slotsFreed && hit.encodes == before.encodes && hit.encodedCopies == before.encodedCopies, "a lookup hit changed the counts"); require(heap.SlotSerial() == serial, "a lookup hit moved the slot serial"); const auto firstGeneration = heap.SlotGeneration(*first), secondGeneration = heap.SlotGeneration(*second); @@ -199,8 +199,7 @@ void writeTails(const Context& context) { for (const std::size_t count : {0u, 1u, 3u, 4u, 5u, 7u, 9u}) { std::vector words(count); for (std::size_t index = 0; index < count; ++index) words[index] = 0x1000u * static_cast(count) + static_cast(index) + 1u; - BindlessHeap::SpanMark mark; - const auto span = heap.Allocate(count + 1u, mark); + const auto span = heap.Allocate(count + 1u); span.words[count] = 0xdeadbeefu; BindlessHeap::Write(span, words); require(std::equal(words.begin(), words.end(), span.words.begin()), "a GPU heap span holds other words than were written"); @@ -210,18 +209,15 @@ void writeTails(const Context& context) { void spanScope(const Context& context) { BindlessHeap heap(context); - BindlessHeap::SpanMark first; std::atomic allocated{false}; std::thread other; bool waited = false; { const BindlessHeap::SpanScope outer(heap); const BindlessHeap::SpanScope inner(heap); - static_cast(heap.Allocate(16u, first)); - require(heap.Held(first) && !heap.KeepOrAllocate(inner, 16u, first, true), "spans are allocated and kept inside nested scopes"); + static_cast(heap.Allocate(16u)); other = std::thread([&] { - BindlessHeap::SpanMark mark; - static_cast(heap.Allocate(16u, mark)); + static_cast(heap.Allocate(16u)); allocated.store(true, std::memory_order_release); }); std::this_thread::sleep_for(std::chrono::milliseconds(50)); @@ -229,7 +225,7 @@ void spanScope(const Context& context) { } other.join(); require(waited, "another thread's span waits while a scope holds the allocator"); - require(allocated.load(std::memory_order_acquire) && heap.Held(first), "the other thread allocates once the scope ends"); + require(allocated.load(std::memory_order_acquire), "the other thread allocates once the scope ends"); require(heap.Statistics().spansWritten == 2u, "both spans are counted"); } @@ -239,38 +235,26 @@ bool dataPool(const Context& context) { constexpr std::size_t blockWords = AgcDriver::Graphics::BindlessHeap::PoolBlockBytes / sizeof(std::uint32_t); { BindlessHeap heap(context); - std::vector marks(5); - for (auto& mark : marks) static_cast(heap.Allocate(blockWords / 2u, mark)); + for (int index = 0; index < 5; ++index) static_cast(heap.Allocate(blockWords / 2u)); require(heap.Statistics().poolBlocksMade == 3u, "one batch's shader data grows into new blocks instead of waiting"); - for (const auto& mark : marks) require(heap.Held(mark), "every span of the batch is held"); - BindlessHeap::SpanMark big; - const auto span = heap.Allocate(blockWords * 3u / 2u, big); + const auto span = heap.Allocate(blockWords * 3u / 2u); require(span.words.size() == blockWords * 3u / 2u && heap.Statistics().poolBlocksMade == 4u, "a span larger than a block gets a block of its own"); const auto [buffer, offset] = heap.DataLocation(span.address + 64u); require(buffer != VK_NULL_HANDLE && offset == span.offset + 64u, "a pooled address maps back to its buffer and offset"); heap.Submitted(recorder, recorder.Submissions() + (1ull << 40u)); const auto made = heap.Statistics().poolBlocksMade; - BindlessHeap::SpanMark fill; - for (int index = 0; index < 4; ++index) static_cast(heap.Allocate(blockWords / 2u + 1u, fill)); + for (int index = 0; index < 4; ++index) static_cast(heap.Allocate(blockWords / 2u + 1u)); const auto busy = heap.Statistics(); require(busy.poolBlocksRecycled == 0u && busy.poolBlocksMade > made, "blocks a batch in flight still reads are not reused"); } { BindlessHeap heap(context); - BindlessHeap::SpanMark kept; - BindlessHeap::SpanMark first; - static_cast(heap.Allocate(blockWords - 64u, kept)); - static_cast(heap.Allocate(blockWords - 64u, first)); - static_cast(heap.Allocate(blockWords - 64u)); + for (int index = 0; index < 3; ++index) static_cast(heap.Allocate(blockWords - 64u)); heap.Submitted(recorder, 0u); - require(heap.Held(kept), "a span a later draw reuses stays held"); const auto made = heap.Statistics().poolBlocksMade; - BindlessHeap::SpanMark fill; - static_cast(heap.Allocate(blockWords - 64u, fill)); + static_cast(heap.Allocate(blockWords - 64u)); const auto counts = heap.Statistics(); require(counts.poolBlocksRecycled == 1u && counts.poolBlocksMade == made, "a completed block is reused instead of making a new one"); - require(heap.Held(kept), "the block a kept span reopened is not reused"); - require(!heap.Held(first), "a span in a reused block has expired"); } { BindlessHeap heap(context); @@ -495,12 +479,12 @@ bool slotPressureSubmits(const Context& context, VkImageView view) { submit(); require(heap.Statistics().slotsEvicted == 0u && BindlessHeap::NearlyFull(), "a submission in the middle of a draw evicts no slot the draw took in the batch it submitted"); - const auto submitsBefore = SlotPressureSubmits(); + const auto submitsBefore = heap.Statistics().slotPressureSubmits; const auto generation = heap.SlotGeneration(slots[0]); { std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); static_cast(recorder.Commands()); - require(heap.TakeSlotPressure() && SlotPressureSubmits() == submitsBefore + 1u, "a nearly full heap asks the next draw to submit its batch"); + require(heap.TakeSlotPressure() && heap.Statistics().slotPressureSubmits == submitsBefore + 1u, "a nearly full heap asks the next draw to submit its batch"); recorder.Submit(); } require(heap.Statistics().slotsEvicted == slots.size(), "the pressure submission evicts every slot, since no draw is being prepared at draw entry"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp index 36545a22c68d..088317663100 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp @@ -92,13 +92,13 @@ void DriverSample(bool heap) { void FullHeapSample() { Outputs[0].fill(-1.0f); const auto stagesBefore = AgcDriver::Graphics::HeapComputeStages(); - const auto submitsBefore = AgcDriver::Graphics::SlotPressureSubmits(); + const auto submitsBefore = AgcDriver::Graphics::BindlessHeap::TotalStatistics().slotPressureSubmits; std::vector words; for (std::size_t index = 0; index < FullHeapTextures; ++index) Sample(words, ManyTextures[index].data(), Outputs[0].data() + 4u * index); Submit(words); for (std::size_t index = 0; index < FullHeapTextures; ++index) RequireSampled(Outputs[0].data() + 4u * index, SampleTexel, "texture " + std::to_string(index) + " of a heap with too few image slots", true); - Require(AgcDriver::Graphics::SlotPressureSubmits() > submitsBefore, "the capped heap never submitted a batch early to free image slots"); + Require(AgcDriver::Graphics::BindlessHeap::TotalStatistics().slotPressureSubmits > submitsBefore, "the capped heap never submitted a batch early to free image slots"); Require(AgcDriver::Graphics::HeapComputeStages() - stagesBefore == FullHeapTextures, "a compute stage left the heap while it ran short of image slots"); } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index aebad33df13d..397a213dfcf5 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -555,9 +555,10 @@ int main() { if (excluded) Require(AgcDriver::Graphics::HeapExcludedCount(AgcDriver::Graphics::HeapExcluded::Draw) != 0u, "no draw took the per-draw path for its excluded heap class"); - if (capped) - Require(AgcDriver::Graphics::HeapSlotEvictions() != 0u, - "the capped heap evicted no image slot"); + if (capped) { + const auto totals = AgcDriver::Graphics::BindlessHeap::TotalStatistics(); + Require(totals.slotsEvicted + totals.samplersEvicted != 0u, "the capped heap evicted no image slot"); + } AgcDriverShutdown_nid_postfix(); if (heap && !capped) Require(AgcDriver::Graphics::EmptyResourceSets() != 0, "no heap draw bound without a per-draw resource set"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp index 50093c6858fc..a12492ed5dfb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp @@ -174,8 +174,7 @@ void RefreshAfterOriginalDestroyed(const AgcDriver::VulkanDevice& device, const RequireHeapTable(*slot); const auto* original = &*slot; std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); - AgcDriver::Graphics::BindlessHeap::SpanMark lead; - static_cast(AgcDriver::Graphics::BindlessHeap::For(context).Allocate(64, lead)); + static_cast(AgcDriver::Graphics::BindlessHeap::For(context).Allocate(64)); const CompiledShader built{ShaderStage::Compute, original, 0}; auto resources = std::make_shared(context, built); Require(resources->HeapStage(), "heap table stage reuse: the set was not built on the heap"); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 844f04556d08..6babd3896bd4 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -460,7 +460,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_PIPELINE_JOURNAL_ENTRIES` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp` | 4096 | number of graphics pipelines a replay builds at most, the last recorded; a log line names how many of each kind were left out | | `APS5_PIPELINE_JOURNAL_MAX_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp` | 1024 | size cap in MiB on the pipeline journal; the file is rewritten down to three quarters of the cap when it is reached, keeping the newest pipelines and the modules they name and leaving room for later records | | `APS5_PIPELINE_JOURNAL_THREADS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp` | | threads that replay the journal's pipelines, 0 disables the replay; unset uses half the hardware threads, at least one | -| `APS5_PIPELINE_STATS` | string | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | captures and prints driver statistics for each new pipeline, requiring `VK_KHR_pipeline_executable_properties`; `1` enables, and `2` also times the GPU heap's per-stage phases in the 10 s `[gpu-heap] cost` line; graphics reports include `[pipeline-source]` Vulkan stage bit, module variant, specialized pipeline variant and stable pipeline identity; disables graphics pipeline libraries, so these counters do not describe the normal GPL/LTO shaders | +| `APS5_PIPELINE_STATS` | string | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | captures and prints driver statistics for each new pipeline, requiring `VK_KHR_pipeline_executable_properties`; `1` enables; graphics reports include `[pipeline-source]` Vulkan stage bit, module variant, specialized pipeline variant and stable pipeline identity; disables graphics pipeline libraries, so these counters do not describe the normal GPL/LTO shaders | | `APS5_PIPELINE_STORE_ENTRIES` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp` | adaptive | fixes the LRU bound on the entries of the pipeline store, which otherwise starts at 1024 and doubles up to 4096 for a journal replay that does not fit and while evicted pipelines keep coming back; an entry is evicted only once no recorded draw holds it | | `APS5_PM4_RING` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Queues/SubmissionRing.cpp` | 16 | number of submissions the PM4 ring keeps for dumps, from 0 to 4096; 0 disables the ring | | `APS5_POISON_VERTEX_PREFIX` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | fills the bytes of a copied vertex range below its lowest fetched vertex with 0x7f instead of leaving them unset, so a draw that reads them shows in its frames | From 17e902f5a368fc2084572a59235031b57cba5867 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 07:14:54 +0530 Subject: [PATCH 227/269] refactor(agc): split the heap stage writers and share the heap element walk --- .../Execution/src/Driver/Draw/HeapStages.cpp | 7 +- .../Execution/src/VulkanDevice.cpp | 8 +- .../Graphics/include/PendingRangeIndex.hpp | 29 - .../Graphics/include/ShaderResources.hpp | 64 +- .../Graphics/include/Shaders.hpp | 27 + .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 139 ++-- .../Graphics/src/ShaderResources.cpp | 758 +++++++++--------- .../Graphics/src/ShaderValidation.cpp | 2 +- .../tests/PendingRangeIndex.cpp | 22 +- core/shader/recompiler/CMakeLists.txt | 2 + core/shader/recompiler/HeapCacheSwitch.hpp | 15 + core/shader/recompiler/Recompiler.cpp | 3 +- docs/dev/ENVIRONMENT.md | 2 +- 13 files changed, 569 insertions(+), 509 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 893c0ae59634..9a3c4bf3cd13 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -274,12 +274,7 @@ bool HeapClassesExcluded() { } bool SampleHeapStageVerify() { - static const std::uint64_t every = [] { - const char* text = std::getenv("APS5_VERIFY_GPU_HEAP"); - if (text == nullptr) return std::uint64_t{0}; - const auto value = std::strtoull(text, nullptr, 10); - return value == 0 ? std::uint64_t{1} : static_cast(value); - }(); + const auto every = ShaderRecompiler::HeapVerifyEvery(); if (every == 0) return false; thread_local std::uint64_t calls = 0; return calls++ % every == 0; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 70cfa4926ecc..42329a10c9a1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -6696,7 +6696,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec namespace { enum class RecipeRefusal : std::size_t { NotCacheable, Overlay, NoObjects, NoContentKey, NeedsFaultChecks, NeedsCopiedWrites, Unreusable, Count }; -constexpr std::size_t UnreusableReasons = 11; +constexpr std::size_t UnreusableReasons = static_cast(Graphics::ShaderResources::Unreusable::Count); std::array, static_cast(RecipeRefusal::Count)> recipeRefusals{}; std::array, UnreusableReasons> unreusableRefusals{}; @@ -6708,10 +6708,10 @@ void noteRecipeRefusal(bool cacheable, bool overlay, bool objects, bool contentK if (!contentKey) return note(RecipeRefusal::NoContentKey); if (!resources.Reusable()) { note(RecipeRefusal::Unreusable); - unreusableRefusals[std::min(resources.UnreusableReason(), UnreusableReasons - 1)].fetch_add(1, std::memory_order_relaxed); + unreusableRefusals[std::min(static_cast(resources.UnreusableReason()), UnreusableReasons - 1)].fetch_add(1, std::memory_order_relaxed); return; } - if (resources.NeedsCompletion()) note(resources.HoldsCopiedWrites() ? RecipeRefusal::NeedsCopiedWrites : RecipeRefusal::NeedsFaultChecks); + if (resources.NeedsCompletion()) note(resources.HasCopiedWrites() ? RecipeRefusal::NeedsCopiedWrites : RecipeRefusal::NeedsFaultChecks); } } @@ -6728,7 +6728,7 @@ std::string VulkanDevice::DispatchRecipeRefusalText() { for (std::size_t index = 0; index < UnreusableReasons; ++index) { const auto count = unreusableRefusals[index].load(std::memory_order_relaxed); if (count == 0) continue; - unreusable += std::string(unreusable.empty() ? "" : ", ") + Graphics::ShaderResources::UnreusableReasonName(static_cast(index)) + " " + std::to_string(count); + unreusable += std::string(unreusable.empty() ? "" : ", ") + Graphics::ShaderResources::UnreusableReasonName(static_cast(index)) + " " + std::to_string(count); } if (!unreusable.empty()) text += " (unreusable: " + unreusable + ")"; return text.empty() ? " none" : text; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp index b0c2e1056cca..09f124c97ec0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PendingRangeIndex.hpp @@ -19,25 +19,6 @@ class PendingRangeIndex { std::size_t position = 0; }; - void Clear() { - entries.clear(); - reach.clear(); - } - - void Add(std::uint64_t begin, std::uint64_t end, Item item, std::size_t position) { - entries.push_back({begin, end, item, position}); - } - - void Seal() { - std::sort(entries.begin(), entries.end(), [](const Entry& a, const Entry& b) { return a.begin != b.begin ? a.begin < b.begin : a.position < b.position; }); - reach.resize(entries.size()); - std::uint64_t furthest = 0; - for (std::size_t index = 0; index < entries.size(); ++index) { - furthest = std::max(furthest, entries[index].end); - reach[index] = furthest; - } - } - void Insert(std::uint64_t begin, std::uint64_t end, Item item, std::size_t position) { const auto at = std::upper_bound(entries.begin(), entries.end(), std::pair{begin, position}, [](const std::pair& key, const Entry& entry) { return key.first != entry.begin ? key.first < entry.begin : key.second < entry.position; }); const auto index = static_cast(at - entries.begin()); @@ -75,14 +56,6 @@ class PendingRangeIndex { return false; } - template - void ForEachOverlapping(std::uint64_t address, std::size_t bytes, Visit&& visit) const { - static_cast(AnyOverlapping(address, bytes, [&](const Item& item) { - visit(item); - return false; - })); - } - template const Entry* FirstByPosition(std::uint64_t address, std::size_t bytes, Match&& match) const { const Entry* first = nullptr; @@ -98,8 +71,6 @@ class PendingRangeIndex { return first; } - std::size_t Size() const { return entries.size(); } - private: void recompute(std::size_t from) { std::uint64_t furthest = from == 0 ? 0 : reach[from - 1]; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index b22c838eeb29..8d7e241671b7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -308,7 +308,6 @@ class ShaderResources { void WriteBackBuffers(); // Whether WriteBackBuffers has anything the CPU must see (copied written buffers, BDA faults). bool NeedsCompletion() const { return (bda != nullptr && faultChecks) || guestMemory.HasCopiedWrites(); } - bool HoldsCopiedWrites() const { return guestMemory.HasCopiedWrites(); } // Whether a written buffer was copied (its results reach guest memory by the CPU write-back). bool HasCopiedWrites() const { return guestMemory.HasCopiedWrites(); } bool HasGpuCopies() const { return guestMemory.HasGpuCopies(); } @@ -376,8 +375,9 @@ class ShaderResources { // ranges are fixed by the build), so a Revalidate's collects on the same worker are memo hits. void PrecollectSurfaces() const; bool Reusable() const { return reusable; } - std::uint8_t UnreusableReason() const { return unreusableReason; } - static const char* UnreusableReasonName(std::uint8_t reason); + enum class Unreusable : std::uint8_t { Unchecked, HtileClear, CopiedWrites, Lease, Bda, MultisampleSource, LoopGuard, TextureRefreshedPerUse, TemplateDataRefresh, NoDirectRegions, RegionNotServed, Count }; + Unreusable UnreusableReason() const { return unreusableReason; } + static const char* UnreusableReasonName(Unreusable reason); void KeepStorageImageBytes(Recorder& recorder) const; const std::vector& MultisampleSources() const { return multisampleSources; } static bool NeverReusable(std::span shaders); @@ -415,6 +415,8 @@ class ShaderResources { void PatchDataAddresses(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const; void writePushedData(std::span bytes, const CompiledShader& shader, ShaderRecompiler::RuntimeAbi::PushedPlacement placement) const; void writePushedBuffers(std::span bytes, std::size_t stage, const ShaderRecompiler::StagePushPlacement& placement, const DrawBindings* overrides, VkDeviceAddress empty) const; + bool pushImageMatches(std::span shaders, std::span placements) const; + void resetPushImage(std::span shaders, std::span placements) const; void writeDataRoots(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten, bool cached) const; struct PushImage { std::array bytes{}; @@ -429,8 +431,6 @@ class ShaderResources { }; std::array stages{}; bool valid = false; - bool tableBound = false; - bool faultBound = false; }; mutable PushImage pushImage; bool PatchMovedPushConstants(std::span bytes, std::span moved) const { @@ -787,9 +787,29 @@ class ShaderResources { }; bool splitSets = false; bool heapStage = false; + bool dataTableBound = false; + bool dataFaultBound = false; mutable std::array heapOffsets{}; void writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader); struct HeapStageState { + struct SlotSet { + std::vector slots; + std::vector generations; + void CaptureImageGenerations(const BindlessHeap& heap) { + generations.clear(); + for (const auto slot : slots) generations.push_back(heap.SlotGeneration(slot)); + } + void CaptureSamplerGenerations(const BindlessHeap& heap) { + generations.clear(); + for (const auto slot : slots) generations.push_back(heap.SamplerGeneration(slot)); + } + static bool Current(const BindlessHeap& heap, const SlotSet& images, const SlotSet& samplers) { + return heap.GenerationsCurrent(images.slots, images.generations, samplers.slots, samplers.generations); + } + static std::uint32_t Touch(const BindlessHeap& heap, const SlotSet& images, const SlotSet& samplers, std::uint32_t touched) { + return heap.TouchSlots(images.slots, samplers.slots, touched); + } + }; std::uint64_t slotSerial = 0; std::uint64_t dataOrigin = 0; std::uint64_t pushedUserWords = 0; @@ -803,10 +823,8 @@ class ShaderResources { std::uint64_t pushVersion = 0; bool mapBuilt = false; std::uint32_t mapTouched = 0; - std::vector mapSlots; - std::vector mapGenerations; - std::vector mapSamplers; - std::vector mapSamplerGenerations; + SlotSet mapImages; + SlotSet mapSamplers; std::vector owned; std::vector key; struct KindRange { @@ -814,11 +832,9 @@ class ShaderResources { std::uint32_t first = 0; std::uint32_t count = 0; }; - std::vector imageSlots; + SlotSet images; std::vector kindRanges; - std::vector slotGenerations; - std::vector samplerSlots; - std::vector samplerGenerations; + SlotSet samplers; std::vector> dataPatches; struct KeptSpan { std::vector words; @@ -839,7 +855,7 @@ class ShaderResources { std::vector wholePushRuns; std::span Slots(std::uint32_t kind) const { for (const auto& range : kindRanges) { - if (range.kind == kind) return std::span(imageSlots).subspan(range.first, range.count); + if (range.kind == kind) return std::span(images.slots).subspan(range.first, range.count); } return {}; } @@ -855,13 +871,28 @@ class ShaderResources { VkImageView heapStorageView(std::size_t index, std::uint32_t binding) const; VkImageView heapMultisampleStorageView(std::size_t index) const; const HeapSlotOwner* heapMultisampleStorageOwner(std::size_t index) const; + static void layOutStagePush(HeapStageState& state, const CompiledShader& shader, const ShaderRecompiler::StagePushPlacement& placement); + void collectAddressedElements(); void layOutHeapStages(std::span shaders); + enum class HeapElementClass { Absent, SampledImage, StorageImage, MultisampleStorage, Sampler }; + static constexpr std::size_t heapElementKeyWords(HeapElementClass kind) { return kind == HeapElementClass::SampledImage || kind == HeapElementClass::StorageImage || kind == HeapElementClass::MultisampleStorage ? 3u : 1u; } + struct HeapElement { + HeapElementClass kind; + std::size_t index; + std::size_t element; + }; + HeapElementClass classifyHeapElement(const Binding& binding, std::size_t element) const; + template bool forEachHeapElement(const Binding& binding, Visit&& visit) const; template void visitHeapSlotKey(std::span owned, Emit&& emit) const; void appendHeapSlotKey(std::span owned, std::vector& key) const; bool heapSlotKeySame(std::span owned, std::span key) const; void takeHeapSlots(BindlessHeap& heap, HeapStageState& state, std::span owned, std::span key); - static void noteHeapSlotGenerations(const BindlessHeap& heap, HeapStageState& state); void verifyHeapSlots(const BindlessHeap& heap, const HeapStageState& state, VkShaderStageFlags stageBit) const; + std::uint64_t commitStageData(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, std::span patched, std::span words, std::span userData); + std::uint64_t writeSplitUserData(BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, std::span words, std::span userData, std::size_t userWords, const std::vector& patched, bool current, std::uint64_t dataAddress); + bool refreshHeapStageSlots(BindlessHeap& heap, HeapStageState& stageState, VkShaderStageFlags stageBit); + void writeHeapDataBinding(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, const ShaderRecompiler::DescriptorBinding& binding, bool current); + void buildPatchedData(std::vector& patched, const CompiledShader& shader, const HeapStageState& stageState, std::span words, std::span userData, bool current) const; void patchHeapSlotWords(const CompiledShader& shader, const HeapStageState& stageState, std::vector& patched, bool current, bool leading = false) const; std::pair writeSplitHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, std::span words, std::span userData, bool sameWalk, bool current); @@ -896,6 +927,7 @@ class ShaderResources { std::array heapTableMaps{}; std::array heapTableMapSet{}; void writeHeapTableMap(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, std::size_t stageIndex); + void buildHeapTableMap(std::vector& map, BindlessHeap& heap, const CompiledShader& shader, const TableStage& table, HeapStageState& stageState); VkDeviceAddressRangeEXT bufferRange(std::uint32_t index, const DrawBindings* overrides) const; VkDeviceAddressRangeEXT bufferAddress(const Allocation& allocation) const; void resolveBufferAddresses(); @@ -945,7 +977,7 @@ class ShaderResources { }; std::vector samplerSources; bool reusable = false; - std::uint8_t unreusableReason = 0; + Unreusable unreusableReason = Unreusable::Unchecked; std::vector directRegions; std::vector validatedTextures; std::vector registeredImageViews; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp index 7073ef67efc9..6c9e929e90e4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Shaders.hpp @@ -109,6 +109,33 @@ inline const std::vector& DrawVertexAttribute return shader.heap != nullptr && !shader.heap->vertexAttributes.empty() ? shader.heap->vertexAttributes : shader.program->vertexAttributes; } +enum class HeapBindingClass { SharedImage, StorageImage, ShaderData, PerDraw, Unsupported }; + +inline HeapBindingClass ClassifyHeapBinding(const ShaderRecompiler::DescriptorBinding& binding) { + using Role = ShaderRecompiler::DescriptorRole; + switch (binding.role) { + case Role::GuestImages: + if (binding.kind != ShaderRecompiler::DescriptorKind::StorageImage) return HeapBindingClass::SharedImage; + return binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet ? HeapBindingClass::StorageImage : HeapBindingClass::PerDraw; + case Role::GuestSamplers: + return HeapBindingClass::SharedImage; + case Role::BdaPagetable: + case Role::FaultBuffer: + case Role::Gds: + case Role::GuestBuffers: + return HeapBindingClass::PerDraw; + case Role::ShaderData: + case Role::FlattenedSrt: + return HeapBindingClass::ShaderData; + default: + return HeapBindingClass::Unsupported; + } +} + +inline bool BindsRole(std::span shaders, ShaderRecompiler::DescriptorRole role) { + return std::ranges::any_of(shaders, [&](const CompiledShader& shader) { return shader.program != nullptr && std::ranges::any_of(shader.program->bindings, [&](const auto& binding) { return binding.role == role; }); }); +} + inline std::uint32_t KeyedPushOffset(const CompiledShader& shader) { return shader.program->pushConstants.empty() ? 0u : shader.pushConstantOffset; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index d501fc8d771c..f056c744d85c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -209,6 +209,26 @@ PixelFunctionLdsLayouts PixelFunctionLdsSetLayouts(const Context& context) { return {pool.empty, pool.bufferLayout}; } +bool PoolAddressed(const Context& context) { + return context.descriptorHeap && context.bufferDeviceAddress; +} + +VkBufferUsageFlags PoolBufferUsage(bool addressed) { + return VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | (addressed ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u); +} + +constexpr VkMemoryAllocateFlagsInfo PoolAddressFlags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, nullptr, VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, 0}; + +template +void WriteHeapPool(const Context& context, Pool& pool, const char* missingAddress, void (Heap::*write)(std::uint64_t, std::uint64_t)) { + if (!context.descriptorHeap || !DescriptorHeapEnabled()) return; + auto& heap = BindlessHeap::For(context); + if (pool.heapWritten == &heap) return; + Require(pool.address != 0, missingAddress); + (heap.*write)(pool.address, pool.bytes); + pool.heapWritten = &heap; +} + void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, std::uint32_t subgroupSize) { const auto operations = VK_SUBGROUP_FEATURE_BASIC_BIT | VK_SUBGROUP_FEATURE_BALLOT_BIT; Require((context.subgroup.supportedStages & VK_SHADER_STAGE_FRAGMENT_BIT) != 0 && (context.subgroup.supportedOperations & operations) == operations, "pixel function LDS needs fragment subgroup elect, ballot and broadcast"); @@ -225,15 +245,14 @@ void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, s const auto bytes = 16ull + stride * pool.slots; VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bufferInfo.size = bytes; - const bool addressed = context.descriptorHeap && context.bufferDeviceAddress; - bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | (addressed ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u); + const bool addressed = PoolAddressed(context); + bufferInfo.usage = PoolBufferUsage(addressed); bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; Check(context.Function("vkCreateBuffer")(context.device, &bufferInfo, nullptr, &pool.buffer), "vkCreateBuffer pixel function LDS"); VkMemoryRequirements requirements{}; context.Function("vkGetBufferMemoryRequirements")(context.device, pool.buffer, &requirements); VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - const VkMemoryAllocateFlagsInfo addressFlags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, nullptr, VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, 0}; - if (addressed) allocation.pNext = &addressFlags; + if (addressed) allocation.pNext = &PoolAddressFlags; allocation.allocationSize = requirements.size; constexpr auto hostCoherent = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; constexpr auto deviceLocalHost = hostCoherent | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; @@ -295,14 +314,7 @@ void PreparePixelFunctionLds(const Context& context, VkCommandBuffer commands, s pool.announced = true; } Require(pool.subgroupSize == subgroupSize, "pixel function LDS subgroup size does not match the pool"); - if (context.descriptorHeap && DescriptorHeapEnabled()) { - auto& heap = BindlessHeap::For(context); - if (pool.heapWritten != &heap) { - Require(pool.address != 0, "the pixel function LDS pool has no device address for the GPU heap"); - heap.WritePixelLdsBuffer(pool.address, pool.bytes); - pool.heapWritten = &heap; - } - } + WriteHeapPool(context, pool, "the pixel function LDS pool has no device address for the GPU heap", &BindlessHeap::WritePixelLdsBuffer); const VkMemoryBarrier beforeFill{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT}; context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &beforeFill, 0, nullptr, 0, nullptr); context.Resolved(&DeviceFunctions::cmdFillBuffer, "vkCmdFillBuffer")(commands, pool.buffer, 0, 4, 0u); @@ -329,12 +341,7 @@ VkDescriptorSetLayout MeshWindowSetLayout(const Context& context) { } void WriteMeshWindowHeap(const Context& context, MeshWindowPool& pool) { - if (!context.descriptorHeap || !DescriptorHeapEnabled()) return; - auto& heap = BindlessHeap::For(context); - if (pool.heapWritten == &heap) return; - Require(pool.address != 0, "the mesh window pool has no device address for the GPU heap"); - heap.WriteMeshWindowBuffer(pool.address, pool.bytes); - pool.heapWritten = &heap; + WriteHeapPool(context, pool, "the mesh window pool has no device address for the GPU heap", &BindlessHeap::WriteMeshWindowBuffer); } void PrepareMeshWindow(const Context& context) { @@ -350,15 +357,14 @@ void PrepareMeshWindow(const Context& context) { Require(bytes <= context.limits.maxStorageBufferRange, "mesh window pool does not fit in the device storage buffer range"); VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bufferInfo.size = bytes; - const bool addressed = context.descriptorHeap && context.bufferDeviceAddress; - bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | (addressed ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u); + const bool addressed = PoolAddressed(context); + bufferInfo.usage = PoolBufferUsage(addressed); bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; Check(context.Function("vkCreateBuffer")(context.device, &bufferInfo, nullptr, &pool.buffer), "vkCreateBuffer mesh window"); VkMemoryRequirements requirements{}; context.Function("vkGetBufferMemoryRequirements")(context.device, pool.buffer, &requirements); VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - const VkMemoryAllocateFlagsInfo addressFlags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, nullptr, VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, 0}; - if (addressed) allocation.pNext = &addressFlags; + if (addressed) allocation.pNext = &PoolAddressFlags; allocation.allocationSize = requirements.size; allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); Check(MemoryAccounting::Allocate(context, allocation, "mesh window", &pool.memory), "vkAllocateMemory mesh window"); @@ -1316,8 +1322,7 @@ std::atomic& drawContentKeysBuilt() { return built; } -bool TemplateKeyWords(const CompiledShader& shader) { - // With moved buffers off the key carries the per-draw ShaderData words, so it cannot be shared on the template. +bool KeysOnTemplate(const CompiledShader& shader) { if (!MovableBuffers()) return false; const auto* heap = shader.heap; if (heap == nullptr || heap->base == nullptr || shader.program->heapTemplateId == 0) return false; @@ -1330,6 +1335,26 @@ bool TemplateKeyWords(const CompiledShader& shader) { return true; } +struct DrawKeyMemoChoice { + decltype(ShaderRecompiler::ResultKeyMemo::words)& memo; + bool memoize; +}; + +DrawKeyMemoChoice ChooseDrawKeyMemo(const CompiledShader& shader) { + const ShaderRecompiler::HeapStageWords* owner = shader.heap; + if (owner == nullptr) return {shader.program->drawKeyMemo.words, true}; + if (!owner->memoizeKey && KeysOnTemplate(shader)) owner = owner->base.get(); + return {owner->drawKeyMemo.words, owner->memoizeKey}; +} + +std::array DrawKeyOwnerWords(const CompiledShader& shader) { + const auto ownerId = shader.program->heapTemplateId != 0 ? shader.program->heapTemplateId : static_cast(reinterpret_cast(shader.program)); + const auto variant = shader.program->PipelineVariantId(); + return {static_cast(ownerId), static_cast(ownerId >> 32u), + static_cast(shader.stage) | (shader.program->heapTemplateId != 0 ? 0x80000000u : 0u), + static_cast(variant), static_cast(variant >> 32u)}; +} + bool ReadsAddressTable(const CompiledShader& shader) { return std::ranges::any_of(shader.program->bindings, [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable; }); } @@ -1364,24 +1389,21 @@ ResourceCache::Key DrawResourceKey(const Context& context, std::spanmemoizeKey && TemplateKeyWords(shader)) memoOwner = memoOwner->base.get(); - auto& memo = memoOwner != nullptr ? memoOwner->drawKeyMemo.words : shader.program->drawKeyMemo.words; - const auto ownerId = shader.program->heapTemplateId != 0 ? shader.program->heapTemplateId : static_cast(reinterpret_cast(shader.program)); - const auto variant = shader.program->PipelineVariantId(); - const std::array owner{static_cast(ownerId), static_cast(ownerId >> 32u), - static_cast(shader.stage) | (shader.program->heapTemplateId != 0 ? 0x80000000u : 0u), - static_cast(variant), static_cast(variant >> 32u)}; - const std::size_t prefix = shader.heap != nullptr ? owner.size() : 0u; - const bool memoize = memoOwner == nullptr || memoOwner->memoizeKey; + const auto [memo, memoize] = ChooseDrawKeyMemo(shader); + std::array ownerStorage{}; + std::span owner; + if (shader.heap != nullptr) { + ownerStorage = DrawKeyOwnerWords(shader); + owner = ownerStorage; + } const auto words = memoize ? memo.load(std::memory_order_acquire) : nullptr; - if (words != nullptr && words->size() >= prefix && std::equal(owner.begin(), owner.begin() + static_cast(prefix), words->begin())) { - key.insert(key.end(), words->begin() + static_cast(prefix), words->end()); + if (words != nullptr && words->size() >= owner.size() && std::equal(owner.begin(), owner.end(), words->begin())) { + key.insert(key.end(), words->begin() + static_cast(owner.size()), words->end()); } else { drawContentKeysBuilt().fetch_add(1, std::memory_order_relaxed); ShaderResources::AppendContentKey(shader, true, MovableBuffers(), key); if (memoize) { - auto stored = std::make_shared>(owner.begin(), owner.begin() + static_cast(prefix)); + auto stored = std::make_shared>(owner.begin(), owner.end()); stored->insert(stored->end(), key.begin() + static_cast(sizeAt + 1u), key.end()); memo.store(std::move(stored), std::memory_order_release); } @@ -1998,7 +2020,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P const bool restartLeft = draw.indirect.has_value(); auto bounds = DrawIndexRange(kept, draw.indexSize, restartLeft); constexpr std::uint32_t ZeroFetchSlack = 0x10000u; - if (const auto zeroFrom = bounds && !DrawVertexAttributes(shaders.front()).empty() ? ZeroFetchVertex(DrawVertexAttributes(shaders.front())) : std::nullopt) { + if (const auto& attributes = DrawVertexAttributes(shaders.front()); const auto zeroFrom = bounds && !attributes.empty() ? ZeroFetchVertex(attributes) : std::nullopt) { const auto limit = *zeroFrom > draw.firstVertex ? *zeroFrom - draw.firstVertex : 0u; if (bounds->highest >= limit && bounds->highest - limit >= ZeroFetchSlack) bounds = ClampDrawIndices(kept, draw.indexSize, restartLeft, limit); } @@ -2044,7 +2066,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P return inputs; } constexpr std::uint32_t ZeroFetchSlack = 0x10000u; - if (const auto zeroFrom = state.stages.mesh || DrawVertexAttributes(shaders.front()).empty() ? std::nullopt : ZeroFetchVertex(DrawVertexAttributes(shaders.front()))) { + if (const auto& attributes = DrawVertexAttributes(shaders.front()); const auto zeroFrom = state.stages.mesh || attributes.empty() ? std::nullopt : ZeroFetchVertex(attributes)) { const auto limit = *zeroFrom > draw.firstVertex ? *zeroFrom - draw.firstVertex : 0u; if (*highest >= limit && *highest - limit >= ZeroFetchSlack) { GuestMemory::FlushGpuWrites(draw.indexAddress, static_cast(indexBytes)); @@ -2959,6 +2981,20 @@ bool WriteOnlyPasses() { return enabled; } +void bindDrawResources(const Context& context, VkCommandBuffer commands, const Pipeline& pipeline, const ShaderResources& resources, const ShaderResources::DrawUse* drawUse, const ShaderResources::DrawBindings* drawBindings, bool guestBuffersChecked) { + if (pipeline.DescriptorHeap()) { + resources.BindDescriptorHeaps(commands, guestBuffersChecked); + NoteEmptyResourceSet(); + } else if (drawBindings != nullptr) { + const auto set = drawBindings->allocation.set; + const auto fragmentSet = drawBindings->fragmentAllocation.set; + if (set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.Layout(), 0, 1, &set, SetBindSite::Draw); + if (fragmentSet != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.Layout(), ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet, SetBindSite::Draw); + } else { + resources.BindDrawUse(commands, pipeline.Layout(), drawUse); + } +} + void recordDraw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, DrawInputs& inputs, RecordedDraw& record, DrawOutcome& outcome, DrawTimer& timer, double& ownWaitedMs, const DrawTraceContext* trace = nullptr) { std::uint32_t subdraw = 0; auto* recorder = record.recorder; @@ -2976,10 +3012,11 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam // A queued DCC key store over memory the draw writes or reads in place (unknown for an // address-based build), or over its GPU-side records, lands before it, as before a dispatch // (VulkanDevice::dispatch); the flush ends an open pass, so it comes before the decision. + const auto movedReadOverlaps = [&](std::uint64_t begin, std::uint64_t end) { return std::any_of(record.moved.begin(), record.moved.end(), [&](const ShaderResources::MovedBuffer& moved) { return moved.words.empty() && moved.address < end && begin < moved.address + moved.size; }); }; const auto touches = [&](std::uint64_t begin, std::uint64_t end) { const auto bytes = static_cast(end - begin); if (resources.WritesOverlap(begin, bytes) || resources.ReadsOverlap(begin, bytes)) return true; - if (std::any_of(record.moved.begin(), record.moved.end(), [&](const ShaderResources::MovedBuffer& moved) { return moved.words.empty() && moved.address < end && begin < moved.address + moved.size; })) return true; + if (movedReadOverlaps(begin, end)) return true; if (!gpuIndirect) return false; return (begin < args->arguments + args->RangeBytes() && args->arguments < end) || (args->countIndirect && begin < args->countAddress + 4 && args->countAddress < end); }; @@ -3019,7 +3056,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam } for (const auto image : record.multisampleImages) passAttachments.emplace_back(image, true); const bool unknownMemory = addressBased || resources.UsesAddressTable() || resources.HasCopiedWrites(); - static_cast(StorageTexture::StoreDrawnLinearTouching("draw access", [&](std::uint64_t begin, std::uint64_t end) { return std::any_of(passReads.begin(), passReads.end(), [&](const auto& read) { return read.first < end && begin < read.second; }) || resources.WritesOverlap(begin, static_cast(end - begin)) || std::any_of(record.moved.begin(), record.moved.end(), [&](const ShaderResources::MovedBuffer& moved) { return moved.words.empty() && moved.address < end && begin < moved.address + moved.size; }); }, unknownMemory)); + static_cast(StorageTexture::StoreDrawnLinearTouching("draw access", [&](std::uint64_t begin, std::uint64_t end) { return std::any_of(passReads.begin(), passReads.end(), [&](const auto& read) { return read.first < end && begin < read.second; }) || resources.WritesOverlap(begin, static_cast(end - begin)) || movedReadOverlaps(begin, end); }, unknownMemory)); const auto drawUse = resources.BeginDrawUse(*recorder); const auto drawBindings = resources.PrepareDrawBindings(*recorder, record.moved, false, drawUse != nullptr ? drawUse->record.get() : nullptr); if (drawBindings != nullptr) passReads.insert(passReads.end(), drawBindings->movedReads.begin(), drawBindings->movedReads.end()); @@ -3134,19 +3171,8 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); const bool heapPipeline = record.pipeline->DescriptorHeap(); NoteHeapRecord(false, heapPipeline); - if (heapPipeline) { - resources.BindDescriptorHeaps(commands, true); - NoteEmptyResourceSet(); - } else if (drawBindings != nullptr) { - Require(!resources.HeapStage(), "a GPU-mode draw needs a VK_EXT_descriptor_heap pipeline"); - const auto set = drawBindings->allocation.set; - const auto fragmentSet = drawBindings->fragmentAllocation.set; - if (set != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), 0, 1, &set, SetBindSite::Draw); - if (fragmentSet != VK_NULL_HANDLE) CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet, SetBindSite::Draw); - } else { - Require(!resources.HeapStage(), "a GPU-mode draw needs a VK_EXT_descriptor_heap pipeline"); - resources.BindDrawUse(commands, record.pipeline->Layout(), drawUse.get()); - } + Require(heapPipeline || !resources.HeapStage(), "a GPU-mode draw needs a VK_EXT_descriptor_heap pipeline"); + bindDrawResources(context, commands, *record.pipeline, resources, drawUse.get(), drawBindings.get(), true); if (!heapPipeline && std::ranges::any_of(shaders, [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->functionLdsBuffer; })) BindPixelFunctionLds(context, commands, record.pipeline->Layout()); if (!heapPipeline && UsesMeshWindow(shaders)) BindMeshWindow(context, commands, record.pipeline->Layout()); APS5_LOG_CHARS_OUT_DEBUG("Resources bound"); @@ -4175,10 +4201,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK"); const bool heapPipeline = pipeline->DescriptorHeap(); const auto drawUse = recorded && !heapPipeline ? resources->BeginDrawUse(*recorder) : nullptr; - if (heapPipeline) { - resources->BindDescriptorHeaps(commands); - NoteEmptyResourceSet(); - } else resources->BindDrawUse(commands, pipeline->Layout(), drawUse.get()); + bindDrawResources(context, commands, *pipeline, *resources, drawUse.get(), nullptr, false); if (pixelLdsSubgroup != 0u && !heapPipeline) BindPixelFunctionLds(context, commands, pipeline->Layout()); if (!heapPipeline && UsesMeshWindow(shaders)) BindMeshWindow(context, commands, pipeline->Layout()); APS5_LOG_CHARS_OUT_DEBUG("Resources bound"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 00ad9b9e93d2..cfd3d74a7514 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -2410,28 +2410,6 @@ void ValidateRuntimeResources(const CompiledShader& shader, std::span shaders, const ColorTarget* target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::size_t indexBytes) { @@ -2487,6 +2465,8 @@ void ShaderResources::buildPrepare(std::span shaders, cons if (heapShader) { Require(DescriptorHeapEnabled(), "a GPU-mode stage needs VK_EXT_descriptor_heap (APS5_GPU_HEAP)"); heapStage = true; + dataTableBound = BindsRole(shaders, ShaderRecompiler::DescriptorRole::BdaPagetable); + dataFaultBound = BindsRole(shaders, ShaderRecompiler::DescriptorRole::FaultBuffer); if (shader.stage == ShaderRecompiler::ShaderStage::Compute) NoteHeapComputeStage(); } for (const auto& binding : shader.program->bindings) { @@ -2505,7 +2485,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons table.firstSampler = firstSampler; continue; } - const bool heapStorage = heapShader && binding.role == ShaderRecompiler::DescriptorRole::GuestImages && binding.kind == ShaderRecompiler::DescriptorKind::StorageImage && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet; + const bool heapStorage = heapShader && ClassifyHeapBinding(binding) == HeapBindingClass::StorageImage; const bool sharedHeapArray = heapShader && (binding.role == ShaderRecompiler::DescriptorRole::GuestSamplers || (binding.role == ShaderRecompiler::DescriptorRole::GuestImages && binding.kind == ShaderRecompiler::DescriptorKind::SampledImage) || heapStorage); Require(std::find(occupied.begin(), occupied.end(), binding.binding) == occupied.end() || sharedHeapArray, "duplicate shader binding"); occupied.push_back(binding.binding); @@ -2870,7 +2850,7 @@ DescribedSetLayouts DescribeSetLayouts(const Context& context, std::spanbufferAddressCount != 0u) || (binding.role == Role::Gds && shader.program->dataAddressPush); - const bool heapStorage = binding.role == Role::GuestImages && binding.kind == ShaderRecompiler::DescriptorKind::StorageImage && binding.descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet; + const bool heapStorage = ClassifyHeapBinding(binding) == HeapBindingClass::StorageImage; if (tableRole || addressRole || heapStorage) continue; } if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable) { @@ -3213,27 +3193,26 @@ void ShaderResources::noteReusable() { // Taken whether or not the object turns out reusable: the lookups' records are this build's. captureValidation(); reusable = false; - unreusableReason = 0; + unreusableReason = Unreusable::Unchecked; spaceReuse = false; importsReconcilable = false; - spaceReuse = false; directRegions.clear(); const bool spaceReusable = !htileClear.has_value() && drawBuild && usesBda && bdaReadOnly && !SpaceReuseDisabled() && guestMemory.SpaceOnly() && !guestMemory.HasCopiedWrites() && multisampleSources.empty() && !(bda != nullptr && LoopGuardEnabled()); if (!spaceReusable) { - if (htileClear.has_value()) unreusableReason = 1; - else if (guestMemory.HasCopiedWrites()) unreusableReason = 2; - else if (HoldsLease()) unreusableReason = 3; - else if (usesBda) unreusableReason = 4; - else if (!multisampleSources.empty()) unreusableReason = 5; - else if (bda != nullptr && LoopGuardEnabled()) unreusableReason = 6; - if (unreusableReason != 0) return; + if (htileClear.has_value()) unreusableReason = Unreusable::HtileClear; + else if (guestMemory.HasCopiedWrites()) unreusableReason = Unreusable::CopiedWrites; + else if (HoldsLease()) unreusableReason = Unreusable::Lease; + else if (usesBda) unreusableReason = Unreusable::Bda; + else if (!multisampleSources.empty()) unreusableReason = Unreusable::MultisampleSource; + else if (bda != nullptr && LoopGuardEnabled()) unreusableReason = Unreusable::LoopGuard; + if (unreusableReason != Unreusable::Unchecked) return; } if (std::any_of(textures.begin(), textures.end(), [](const std::shared_ptr& texture) { return texture != nullptr && texture->RefreshedPerUse(); })) { - unreusableReason = 7; + unreusableReason = Unreusable::TextureRefreshedPerUse; return; } if (TemplateDataRefresh() && std::any_of(allocations.begin(), allocations.end(), [](const Allocation& allocation) { return allocation.buffer != nullptr && !allocation.guest && allocation.role != ShaderRecompiler::DescriptorRole::ImageTableMap && allocation.size > MaxRefreshBytes; })) { - unreusableReason = 8; + unreusableReason = Unreusable::TemplateDataRefresh; return; } if (spaceReusable) { @@ -3243,7 +3222,7 @@ void ShaderResources::noteReusable() { } const auto regions = guestMemory.DirectRegions(); if (!regions.has_value()) { - unreusableReason = 9; + unreusableReason = Unreusable::NoDirectRegions; return; } bool mirrored = false; @@ -3256,7 +3235,7 @@ void ShaderResources::noteReusable() { const bool imported = serial != 0; if (serial == 0) serial = ImageMirrorSerial(context, begin, static_cast(end - begin)); if (serial == 0) { - unreusableReason = 10; + unreusableReason = Unreusable::RegionNotServed; return; } directRegions.push_back({begin, end, serial}); @@ -3275,9 +3254,10 @@ void ShaderResources::noteReusable() { reusable = true; } -const char* ShaderResources::UnreusableReasonName(std::uint8_t reason) { - constexpr std::array names{"unchecked", "htile clear", "copied writes", "lease", "bda", "multisample source", "loop guard", "texture refreshed per use", "template data refresh", "no direct regions", "region not served"}; - return reason < names.size() ? names[reason] : "unknown"; +const char* ShaderResources::UnreusableReasonName(Unreusable reason) { + constexpr std::array(Unreusable::Count)> names{"unchecked", "htile clear", "copied writes", "lease", "bda", "multisample source", "loop guard", "texture refreshed per use", "template data refresh", "no direct regions", "region not served"}; + const auto index = static_cast(reason); + return index < names.size() ? names[index] : "unknown"; } namespace { @@ -3391,10 +3371,11 @@ void VisitContentKey(const CompiledShader& shader, bool dataWords, bool movableB } }; for (const auto& binding : program.bindings) { - for (const auto word : {static_cast(binding.kind), static_cast(binding.role), binding.descriptorSet, binding.binding, binding.count, binding.readOnly ? 1u : 0u, binding.imageShape.has_value() ? static_cast(*binding.imageShape) + 1u : 0u, static_cast(DrawGuestWords(shader, binding).size())}) visit(word); - if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable && DrawGuestWords(shader, binding).size() > CompactTableKeyWords) { + const auto& guestWords = DrawGuestWords(shader, binding); + for (const auto word : {static_cast(binding.kind), static_cast(binding.role), binding.descriptorSet, binding.binding, binding.count, binding.readOnly ? 1u : 0u, binding.imageShape.has_value() ? static_cast(*binding.imageShape) + 1u : 0u, static_cast(guestWords.size())}) visit(word); + if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable && guestWords.size() > CompactTableKeyWords) { TableKeyHash hash; - hash.bytes(DrawGuestWords(shader, binding).data(), DrawGuestWords(shader, binding).size() * sizeof(std::uint32_t)); + hash.bytes(guestWords.data(), guestWords.size() * sizeof(std::uint32_t)); hash.bytes(binding.imageSamplers.data(), binding.imageSamplers.size() * sizeof(binding.imageSamplers[0])); hash.bytes(binding.imageShapes.data(), binding.imageShapes.size() * sizeof(binding.imageShapes[0])); for (const auto* set : {&binding.imageWritten, &binding.samplerDepthCompare, &binding.imageDepthCompare, &binding.imageAtomic, &binding.samplerUnnormalized, &binding.samplerIntegerBorder, &binding.samplerCoordinatesIgnored, &binding.imageUnnormalized, &binding.imageUnnormalizedBaseLevel, &binding.bufferWritten}) hash.bits(*set); @@ -3403,22 +3384,22 @@ void VisitContentKey(const CompiledShader& shader, bool dataWords, bool movableB for (const auto word : {0xc0de7ab1u, static_cast(first), static_cast(first >> 32u), static_cast(second), static_cast(second >> 32u)}) visit(word); continue; } - if (movableBuffers && binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers && DrawGuestWords(shader, binding).size() == static_cast(binding.count) * 4u) { + if (movableBuffers && binding.role == ShaderRecompiler::DescriptorRole::GuestBuffers && guestWords.size() == static_cast(binding.count) * 4u) { for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto* words = DrawGuestWords(shader, binding).data() + static_cast(element) * 4u; + const auto* words = guestWords.data() + static_cast(element) * 4u; const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element]; const bool empty = words[2] == 0 || (words[0] == 0 && (words[1] & 0xffffu) == 0); if (written || empty) { for (std::uint32_t index = 0; index < 4u; ++index) visit(words[index]); } else { for (const auto word : {0u, words[1] & 0xffff0000u, 0u, words[3]}) visit(word); } } - } else if (binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap && DrawGuestWords(shader, binding).size() > CompactTableKeyWords) { + } else if (binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap && guestWords.size() > CompactTableKeyWords) { TableKeyHash hash; - hash.bytes(DrawGuestWords(shader, binding).data(), DrawGuestWords(shader, binding).size() * sizeof(std::uint32_t)); + hash.bytes(guestWords.data(), guestWords.size() * sizeof(std::uint32_t)); const auto first = hash.a(); const auto second = hash.b(); for (const auto word : {0xc0de7ab2u, static_cast(first), static_cast(first >> 32u), static_cast(second), static_cast(second >> 32u)}) visit(word); } else if ((dataWords && !movableBuffers) || !DataRole(binding.role)) { - for (const auto word : DrawGuestWords(shader, binding)) visit(word); + for (const auto word : guestWords) visit(word); } packBits(binding.imageWritten); packBits(binding.samplerDepthCompare); @@ -3466,11 +3447,12 @@ void ShaderResources::AppendContentKey(const CompiledShader& shader, bool dataWo }; for (const auto& binding : shader.program->bindings) { addWords(20); - if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable && DrawGuestWords(shader, binding).size() > CompactTableKeyWords) continue; + const auto& guestWords = DrawGuestWords(shader, binding); + if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable && guestWords.size() > CompactTableKeyWords) continue; addWords(binding.imageSamplers.size() * 2u); addWords(binding.imageShapes.size()); - if (binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap && DrawGuestWords(shader, binding).size() > CompactTableKeyWords) addWords(5); - else if ((dataWords && !movableBuffers) || !DataRole(binding.role)) addWords(DrawGuestWords(shader, binding).size()); + if (binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap && guestWords.size() > CompactTableKeyWords) addWords(5); + else if ((dataWords && !movableBuffers) || !DataRole(binding.role)) addWords(guestWords.size()); for (const auto* bits : {&binding.imageWritten, &binding.samplerDepthCompare, &binding.imageDepthCompare, &binding.imageAtomic, &binding.samplerUnnormalized, &binding.samplerIntegerBorder, &binding.samplerCoordinatesIgnored, &binding.imageUnnormalized, &binding.imageUnnormalizedBaseLevel, &binding.bufferWritten}) addWords(bits->size() / 32u + (bits->size() % 32u != 0 ? 1u : 0u)); } key.reserve(words); @@ -4751,9 +4733,10 @@ bool ShaderResources::revalidateFull(std::span shaders, Pr for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages) continue; if (binding.kind == ShaderRecompiler::DescriptorKind::SampledImage) { - const auto elementWords = binding.count != 0 ? DrawGuestWords(shader, binding).size() / binding.count : 0; + const auto& guestWords = DrawGuestWords(shader, binding); + const auto elementWords = binding.count != 0 ? guestWords.size() / binding.count : 0; for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto raw = std::span(DrawGuestWords(shader, binding)).subspan(static_cast(element) * elementWords, elementWords); + const auto raw = std::span(guestWords).subspan(static_cast(element) * elementWords, elementWords); std::array narrowed{}; const auto words = firstLayerWords(raw, binding.imageShape, narrowed, false); if (IsNullSampledTextureResource(words)) continue; @@ -4765,12 +4748,13 @@ bool ShaderResources::revalidateFull(std::span shaders, Pr ++textureIndex; } } else if (binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) { + const auto& guestWords = DrawGuestWords(shader, binding); for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto words = std::span(DrawGuestWords(shader, binding)).subspan(static_cast(element) * 8u, 8u); + const auto words = std::span(guestWords).subspan(static_cast(element) * 8u, 8u); if (IsNullTextureResource(words)) continue; if (storageIndex >= storageTextures.size()) return false; std::shared_ptr expected; - if (SameAsPreviousStorageElement(DrawGuestWords(shader, binding), element) && StorageDedupeEnabled()) expected = storageTextures[storageIndex - 1]; + if (SameAsPreviousStorageElement(guestWords, element) && StorageDedupeEnabled()) expected = storageTextures[storageIndex - 1]; else expected = cachedStorageTexture(context, words, DecodeTextureResource(words), storageMips[storageIndex], 0, storageWritten[storageIndex]); if (expected != storageTextures[storageIndex]) return false; ++storageIndex; @@ -5878,7 +5862,8 @@ bool ShaderResources::DataWordsDiffer(const CompiledShader& shader) const { const auto held = std::ranges::find_if(bindings, [&](const Binding& candidate) { return candidate.layout.binding == binding.binding; }); if (held == bindings.end() || held->allocations.size() != 1) return true; const auto& allocation = allocations[held->allocations.front()]; - if (allocation.dataWords.size() != DrawGuestWords(shader, binding).size() || !std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), DrawGuestWords(shader, binding).begin())) return true; + const auto& guestWords = DrawGuestWords(shader, binding); + if (allocation.dataWords.size() != guestWords.size() || !std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), guestWords.begin())) return true; } return false; } @@ -5904,13 +5889,14 @@ bool ShaderResources::refreshData(VkCommandBuffer commands, const CompiledShader Require(held != bindings.end(), "template bindings disagree with the shader"); Require(held->allocations.size() == 1, "data binding without its buffer"); auto& allocation = allocations[held->allocations.front()]; - const auto size = DrawGuestWords(shader, binding).size() * sizeof(std::uint32_t); + const auto& guestWords = DrawGuestWords(shader, binding); + const auto size = guestWords.size() * sizeof(std::uint32_t); Require(allocation.buffer != nullptr && !allocation.guest && allocation.size == size && size <= MaxRefreshBytes, "template data buffer cannot take the dispatch's words"); - if (allocation.dataWords.size() == DrawGuestWords(shader, binding).size() && std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), DrawGuestWords(shader, binding).begin())) continue; - if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, DrawGuestWords(shader, binding)); + if (allocation.dataWords.size() == guestWords.size() && std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), guestWords.begin())) continue; + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, guestWords); if (recorder != nullptr && timing == Recorder::NoTiming) timing = recorder->BeginGpuTiming(Recorder::CommandClass::TemplateDataRefresh); - writeDataWords(commands, held->allocations.front(), DrawGuestWords(shader, binding)); - allocation.dataWords.assign(DrawGuestWords(shader, binding).begin(), DrawGuestWords(shader, binding).end()); + writeDataWords(commands, held->allocations.front(), guestWords); + allocation.dataWords.assign(guestWords.begin(), guestWords.end()); refreshedBytes += size; recorded = true; } @@ -7791,7 +7777,7 @@ void ShaderResources::resolveBufferAddresses() { } VkDeviceAddressRangeEXT ShaderResources::bufferRange(std::uint32_t index, const DrawBindings* overrides) const { - static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + const bool verify = ShaderRecompiler::HeapVerifyEnabled(); const auto& allocation = allocations[index]; const auto* override = overrides != nullptr ? overrides->AddressOverride(index) : nullptr; const bool overridden = override != nullptr && override->address != 0; @@ -7826,14 +7812,48 @@ std::pair ShaderResources::shaderDataLocation(const Comp return BindlessHeap::For(context).DataLocation(offsets[DataOffsetIndex(HeapStageIndex(shader.stage), ShaderRecompiler::RuntimeAbi::Binding::ShaderData)]); } +bool ShaderResources::pushImageMatches(std::span shaders, std::span placements) const { + const auto& image = pushImage; + return image.valid && image.count == shaders.size() && shaders.size() <= image.programs.size() && + std::equal(shaders.begin(), shaders.end(), image.programs.begin(), [](const CompiledShader& shader, const ShaderRecompiler::RecompileResult* program) { return shader.program == program; }) && + std::ranges::equal(placements, image.placements); +} + +void ShaderResources::resetPushImage(std::span shaders, std::span placements) const { + namespace Abi = ShaderRecompiler::RuntimeAbi; + auto& image = pushImage; + image.bytes.fill(std::byte{0}); + image.mask = 0; + image.programs.fill(nullptr); + image.stages.fill({}); + image.valid = shaders.size() <= image.programs.size(); + image.count = shaders.size(); + image.placements.assign(placements.begin(), placements.end()); + for (std::size_t index = 0; index < shaders.size() && index < image.programs.size(); ++index) image.programs[index] = shaders[index].program; + const auto own = [&](std::uint32_t position, std::uint32_t width) { + if (position == Abi::NoPushPosition) return; + for (auto dword = position; dword < position + width && dword < Abi::PushDataDwords; ++dword) image.mask |= std::uint64_t{1} << dword; + }; + for (std::size_t index = 0; index < shaders.size(); ++index) { + const auto& placement = placements[index]; + const bool rootedStage = shaders[index].program != nullptr && shaders[index].program->dataAddressPush; + for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { + const auto kind = static_cast(item); + const bool global = kind == Abi::RootItem::PagetableAddress || kind == Abi::RootItem::FaultAddress || kind == Abi::RootItem::GdsAddress; + if (global || rootedStage) own(placement.items[item], Abi::RootAddressItem(kind) ? 2u : 1u); + } + if (!rootedStage) continue; + own(placement.pushed.count != 0u ? placement.pushed.base : Abi::NoPushPosition, placement.pushed.count); + for (std::uint32_t buffer = 0; buffer < std::min(placement.pushedBuffers, Abi::PushedBufferLimit); ++buffer) own(placement.bufferRoots[buffer], Abi::PushedBufferWords); + own(placement.bufferOverflow, 2u); + } +} + void ShaderResources::writeDataRoots(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten, bool cached) const { namespace Abi = ShaderRecompiler::RuntimeAbi; if (!heapStage) return; const bool addressed = rewritten != nullptr && rewritten->addressOffsets; const auto& offsets = addressed ? rewritten->heapOffsets : heapOffsets; - const auto binds = [&](ShaderRecompiler::DescriptorRole role) { - return std::any_of(shaders.begin(), shaders.end(), [&](const CompiledShader& shader) { return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [&](const auto& binding) { return binding.role == role; }); }); - }; Require(placements.size() == shaders.size(), "the push layout does not describe the draw's stages"); std::optional gds; const auto gdsAddress = [&] { @@ -7844,53 +7864,20 @@ void ShaderResources::writeDataRoots(std::spanaddress != 0; gds = overridden ? override->address : resolvedGds; Require(*gds != 0, "the GDS buffer has no device address"); - static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + const bool verify = ShaderRecompiler::HeapVerifyEnabled(); if (verify && !overridden && bufferAddress(allocations[gdsAllocation]).address != *gds) throw std::runtime_error("AGC graphics: the GDS address resolved when the draw's resources were built changed"); return *gds; }; auto& image = pushImage; if (cached) { - const bool same = image.valid && image.count == shaders.size() && shaders.size() <= image.programs.size() && - std::equal(shaders.begin(), shaders.end(), image.programs.begin(), [](const CompiledShader& shader, const ShaderRecompiler::RecompileResult* program) { return shader.program == program; }) && - std::ranges::equal(placements, image.placements); - if (!same) { - image.bytes.fill(std::byte{0}); - image.mask = 0; - image.programs.fill(nullptr); - image.stages.fill({}); - image.valid = shaders.size() <= image.programs.size(); - image.count = shaders.size(); - image.placements.assign(placements.begin(), placements.end()); - for (std::size_t index = 0; index < shaders.size() && index < image.programs.size(); ++index) image.programs[index] = shaders[index].program; - image.tableBound = binds(ShaderRecompiler::DescriptorRole::BdaPagetable); - image.faultBound = binds(ShaderRecompiler::DescriptorRole::FaultBuffer); - const auto own = [&](std::uint32_t position, std::uint32_t width) { - if (position == Abi::NoPushPosition) return; - for (auto dword = position; dword < position + width && dword < Abi::PushDataDwords; ++dword) image.mask |= std::uint64_t{1} << dword; - }; - for (std::size_t index = 0; index < shaders.size(); ++index) { - const auto& placement = placements[index]; - const bool rootedStage = shaders[index].program != nullptr && shaders[index].program->dataAddressPush; - for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { - const auto kind = static_cast(item); - const bool global = kind == Abi::RootItem::PagetableAddress || kind == Abi::RootItem::FaultAddress || kind == Abi::RootItem::GdsAddress; - if (global || rootedStage) own(placement.items[item], Abi::RootAddressItem(kind) ? 2u : 1u); - } - if (!rootedStage) continue; - own(placement.pushed.count != 0u ? placement.pushed.base : Abi::NoPushPosition, placement.pushed.count); - for (std::uint32_t buffer = 0; buffer < std::min(placement.pushedBuffers, Abi::PushedBufferLimit); ++buffer) own(placement.bufferRoots[buffer], Abi::PushedBufferWords); - own(placement.bufferOverflow, 2u); - } - } + if (!pushImageMatches(shaders, placements)) resetPushImage(shaders, placements); if (!image.valid) cached = false; } - const bool tableBound = cached ? image.tableBound : binds(ShaderRecompiler::DescriptorRole::BdaPagetable); - const bool faultBound = cached ? image.faultBound : binds(ShaderRecompiler::DescriptorRole::FaultBuffer); VkDeviceAddress table = 0; VkDeviceAddress fault = 0; - if (bda != nullptr && (tableBound || faultBound)) { - if (tableBound) table = bda->TableAddress(); - if (faultBound) fault = bda->FaultAddress(); + if (bda != nullptr && (dataTableBound || dataFaultBound)) { + if (dataTableBound) table = bda->TableAddress(); + if (dataFaultBound) fault = bda->FaultAddress(); } const auto target = cached ? std::span(image.bytes) : bytes; bool rooted = false; @@ -7942,7 +7929,7 @@ void ShaderResources::writeDataRoots(std::span bytes, std::span shaders, std::span placements, const DrawBindings* rewritten) const { if (!heapStage) return; - static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + const bool verify = ShaderRecompiler::HeapVerifyEnabled(); const bool addressed = rewritten != nullptr && rewritten->addressOffsets; if (addressed) { pushImage.valid = false; @@ -7992,24 +7979,21 @@ void ShaderResources::writePushedBuffers(std::span(words).first(Abi::PushedBufferWords)); + for (std::size_t index = 0; index < elements.size() && !overflowed; ++index) overflowed = rootOf(index) == Abi::NoPushPosition; + BindlessHeap::DataSpan overflow{}; + if (overflowed) { + heapOverflowStages.fetch_add(1, std::memory_order_relaxed); + overflow = BindlessHeap::For(context).Allocate(elements.size() * Abi::OverflowRecordWords); } - if (!overflowed) return; - heapOverflowStages.fetch_add(1, std::memory_order_relaxed); - const auto span = BindlessHeap::For(context).Allocate(elements.size() * Abi::OverflowRecordWords); for (std::size_t index = 0; index < elements.size(); ++index) { const auto words = encode(bufferRange(elements[index], overrides)); - std::copy(words.begin(), words.end(), span.words.begin() + static_cast(index * Abi::OverflowRecordWords)); + if (const auto root = rootOf(index); root != Abi::NoPushPosition) put(root, std::span(words).first(Abi::PushedBufferWords)); + if (overflowed) std::copy(words.begin(), words.end(), overflow.words.begin() + static_cast(index * Abi::OverflowRecordWords)); } - const std::array address{static_cast(span.address), static_cast(span.address >> 32u)}; + if (!overflowed) return; + const std::array address{static_cast(overflow.address), static_cast(overflow.address >> 32u)}; put(placement.bufferOverflow, address); } @@ -8042,30 +8026,12 @@ VkImageView ShaderResources::heapPlaceholderView(std::uint32_t kind) const { return context.nullDescriptors ? VK_NULL_HANDLE : context.placeholderImages->View(kind); } -void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, std::size_t stageIndex) { +void ShaderResources::buildHeapTableMap(std::vector& map, BindlessHeap& heap, const CompiledShader& shader, const TableStage& table, HeapStageState& stageState) { constexpr auto noElement = std::numeric_limits::max(); namespace Abi = ShaderRecompiler::RuntimeAbi; namespace TableAbi = ShaderRecompiler::ImageTableAbi; - heapTableMapSet[stageIndex] = false; - const auto table = std::find_if(tableStages.begin(), tableStages.end(), - [&](const TableStage& candidate) { return candidate.stage == shader.stage && candidate.heap; }); - if (table == tableStages.end() || table->mapAllocation == noElement) return; - static const bool verifyMap = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; - auto& stageState = heapStages[stageIndex]; - const bool mapCurrent = !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::TableMap) && stageState.mapBuilt && stageState.map.table.address != 0u && - heap.GenerationsCurrent(stageState.mapSlots, stageState.mapGenerations, stageState.mapSamplers, stageState.mapSamplerGenerations); - if (mapCurrent && !verifyMap) { - stageState.mapTouched = heap.TouchSlots(stageState.mapSlots, stageState.mapSamplers, stageState.mapTouched); - heap.NoteTableKept(spans); - heapTableMaps[stageIndex] = stageState.map.table.address; - heapTableMapSet[stageIndex] = true; - return; - } - stageState.mapBuilt = false; - stageState.mapSlots.clear(); - stageState.mapSamplers.clear(); const auto image = [&](std::uint32_t slot) { - stageState.mapSlots.push_back(slot); + stageState.mapImages.slots.push_back(slot); return slot; }; const ShaderRecompiler::DescriptorBinding* images = nullptr; @@ -8073,16 +8039,13 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi if (binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable) images = &binding; } - struct MapStorage {}; - auto& map = HostThreadLocal, MapStorage>(); - map.assign(table->map.begin(), table->map.end()); const auto elements = images != nullptr ? static_cast(images->count) : std::size_t{0}; const auto base = static_cast(map.size()); map[TableAbi::HeaderElementBase] = base; const auto sampledAbsent = image(heap.AbsentSlot(Abi::FirstImageBinding, heapPlaceholderView(Abi::FirstImageBinding))); const auto storageAbsent = image(heap.AbsentSlot(Abi::FirstStorageImageBinding, heapPlaceholderView(Abi::FirstStorageImageBinding))); for (std::size_t element = 0; element < elements; ++element) { - const auto index = element < table->elementTextures.size() ? table->elementTextures[element] : noElement; + const auto index = element < table.elementTextures.size() ? table.elementTextures[element] : noElement; if (index == noElement) { map.push_back(sampledAbsent); continue; @@ -8092,7 +8055,7 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi } const auto appendStorageSlots = [&](std::uint32_t kind, std::uint32_t absent, const char* full, const auto& wanted, const auto& viewOf) { for (std::size_t element = 0; element < elements; ++element) { - const auto index = element < table->elementStorage.size() ? table->elementStorage[element] : noElement; + const auto index = element < table.elementStorage.size() ? table.elementStorage[element] : noElement; if (!wanted(element) || index == noElement || storageTextures[index] == nullptr) { map.push_back(absent); continue; @@ -8105,12 +8068,12 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi [&](StorageTexture& image, std::size_t index) { return image.StorageView(storageMips[index], storageFirstLayer[index]); }); const auto samplerSlotOf = [&](std::size_t index) { const auto slot = takenSlot(heap.SamplerSlot(samplers[index]), "the global sampler heap is full"); - stageState.mapSamplers.push_back(slot); + stageState.mapSamplers.slots.push_back(slot); return slot; }; - const auto firstSampler = std::find_if(table->tableSamplers.begin(), table->tableSamplers.end(), [&](const auto index) { return index != noElement; }); - const std::uint32_t fallbackSampler = firstSampler != table->tableSamplers.end() ? samplerSlotOf(*firstSampler) : 0u; - for (const auto index : table->tableSamplers) map.push_back(index == noElement ? fallbackSampler : samplerSlotOf(index)); + const auto firstSampler = std::find_if(table.tableSamplers.begin(), table.tableSamplers.end(), [&](const auto index) { return index != noElement; }); + const std::uint32_t fallbackSampler = firstSampler != table.tableSamplers.end() ? samplerSlotOf(*firstSampler) : 0u; + for (const auto index : table.tableSamplers) map.push_back(index == noElement ? fallbackSampler : samplerSlotOf(index)); const auto atomicElement = [&](std::size_t element, bool wide) { if (images == nullptr) return false; const auto& flags = wide ? images->imageAtomic64 : images->imageAtomic; @@ -8123,7 +8086,7 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi return false; }; const auto samplerSpan = std::max(elements, map[TableAbi::HeaderSamplerCount]); - Require(table->tableSamplers.size() <= samplerSpan, "an image table map has more table samplers than its header counts"); + Require(table.tableSamplers.size() <= samplerSpan, "an image table map has more table samplers than its header counts"); const auto extraBase = base + 2u * elements + samplerSpan; if (anyAtomic(false) || anyAtomic(true)) { map.resize(extraBase, fallbackSampler); @@ -8149,13 +8112,37 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi [&](StorageTexture& image, std::size_t index) { return image.UintStorageViewOrDefault(storageMips[index], storageFirstLayer[index]); }); } if (map.size() == base) map.push_back(sampledAbsent); +} + +void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, std::size_t stageIndex) { + constexpr auto noElement = std::numeric_limits::max(); + heapTableMapSet[stageIndex] = false; + const auto table = std::find_if(tableStages.begin(), tableStages.end(), + [&](const TableStage& candidate) { return candidate.stage == shader.stage && candidate.heap; }); + if (table == tableStages.end() || table->mapAllocation == noElement) return; + const bool verifyMap = ShaderRecompiler::HeapVerifyEnabled(); + auto& stageState = heapStages[stageIndex]; + const bool mapCurrent = !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::TableMap) && stageState.mapBuilt && stageState.map.table.address != 0u && + HeapStageState::SlotSet::Current(heap, stageState.mapImages, stageState.mapSamplers); + if (mapCurrent && !verifyMap) { + stageState.mapTouched = HeapStageState::SlotSet::Touch(heap, stageState.mapImages, stageState.mapSamplers, stageState.mapTouched); + heap.NoteTableKept(spans); + heapTableMaps[stageIndex] = stageState.map.table.address; + heapTableMapSet[stageIndex] = true; + return; + } + stageState.mapBuilt = false; + stageState.mapImages.slots.clear(); + stageState.mapSamplers.slots.clear(); + struct MapStorage {}; + auto& map = HostThreadLocal, MapStorage>(); + map.assign(table->map.begin(), table->map.end()); + buildHeapTableMap(map, heap, shader, *table, stageState); if (mapCurrent && !std::ranges::equal(stageState.map.words, map)) throw std::runtime_error("AGC graphics: a GPU heap stage's image table map changed although its slots did not"); heapTableMaps[stageIndex] = heapSpan(spans, heap, stageState.map, map); heapTableMapSet[stageIndex] = true; - stageState.mapGenerations.clear(); - for (const auto slot : stageState.mapSlots) stageState.mapGenerations.push_back(heap.SlotGeneration(slot)); - stageState.mapSamplerGenerations.clear(); - for (const auto slot : stageState.mapSamplers) stageState.mapSamplerGenerations.push_back(heap.SamplerGeneration(slot)); + stageState.mapImages.CaptureImageGenerations(heap); + stageState.mapSamplers.CaptureSamplerGenerations(heap); stageState.mapBuilt = true; } @@ -8222,9 +8209,50 @@ VkImageView ShaderResources::heapStorageView(std::size_t index, std::uint32_t bi return texture->StorageView(storageMips[index], storageFirstLayer[index], UintStorageBinding(binding)); } -void ShaderResources::layOutHeapStages(std::span shaders) { +void ShaderResources::layOutStagePush(HeapStageState& state, const CompiledShader& shader, const ShaderRecompiler::StagePushPlacement& placement) { namespace Abi = ShaderRecompiler::RuntimeAbi; - const auto splits = [](const CompiledShader& shader) { return (shader.program->pushItems & Abi::RootItemBit(Abi::RootItem::UserData)) != 0u; }; + const auto& program = *shader.program; + state.splitUser = (program.pushItems & Abi::RootItemBit(Abi::RootItem::UserData)) != 0u && placement.Item(Abi::RootItem::UserData) != Abi::NoPushPosition; + const auto placed = std::min(placement.pushed.count, program.pushedData.size()); + const auto userWords = std::max(program.heapUserWords.size(), program.shaderDataUserWords.size()); + for (std::size_t item = 0; item < placed; ++item) { + const auto dword = program.pushedData[item]; + if (dword < userWords && dword < 64u) state.pushedUserWords |= std::uint64_t{1} << dword; + } + state.pushedPlaced = static_cast(placed); + state.pushRunUserWords = static_cast(userWords); + const auto runsOf = [&](std::vector& runs, std::size_t split) { + for (std::size_t item = 0; item < placed; ++item) { + const auto dword = program.pushedData[item]; + const bool user = dword < split; + if (!runs.empty()) { + auto& run = runs.back(); + if (run.user == user && run.index + run.count == item && run.dword + run.count == dword) { + ++run.count; + continue; + } + } + runs.push_back({static_cast(item), dword, 1u, user}); + } + }; + runsOf(state.splitPushRuns, userWords); + runsOf(state.wholePushRuns, 0u); +} + +void ShaderResources::collectAddressedElements() { + for (auto& elements : addressedElements) elements.clear(); + addressedAllocations.assign(allocations.size(), 0); + for (const auto& binding : bindings) { + if (!binding.addressed) continue; + Require(binding.dataStage < addressedElements.size(), "an addressed buffer binding names no data stage"); + for (const auto index : binding.allocations) { + addressedElements[binding.dataStage].push_back(static_cast(index)); + addressedAllocations[index] = 1; + } + } +} + +void ShaderResources::layOutHeapStages(std::span shaders) { const bool addressed = std::ranges::any_of(shaders, [&](const CompiledShader& shader) { return HeapShader(shader) && shader.program->dataAddressPush; }); const auto placements = addressed ? PushDataPlacements(shaders) : std::vector{}; for (std::size_t shaderIndex = 0; shaderIndex < shaders.size(); ++shaderIndex) { @@ -8247,76 +8275,51 @@ void ShaderResources::layOutHeapStages(std::span shaders) state.splitPushRuns.clear(); state.wholePushRuns.clear(); if (placements.empty() || !shader.program->dataAddressPush) continue; - const auto& program = *shader.program; - state.splitUser = splits(shader) && placements[shaderIndex].Item(Abi::RootItem::UserData) != Abi::NoPushPosition; - const auto placed = std::min(placements[shaderIndex].pushed.count, program.pushedData.size()); - const auto userWords = std::max(program.heapUserWords.size(), program.shaderDataUserWords.size()); - for (std::size_t item = 0; item < placed; ++item) { - const auto dword = program.pushedData[item]; - if (dword < userWords && dword < 64u) state.pushedUserWords |= std::uint64_t{1} << dword; - } - state.pushedPlaced = static_cast(placed); - state.pushRunUserWords = static_cast(userWords); - const auto runsOf = [&](std::vector& runs, std::size_t split) { - for (std::size_t item = 0; item < placed; ++item) { - const auto dword = program.pushedData[item]; - const bool user = dword < split; - if (!runs.empty()) { - auto& run = runs.back(); - if (run.user == user && run.index + run.count == item && run.dword + run.count == dword) { - ++run.count; - continue; - } - } - runs.push_back({static_cast(item), dword, 1u, user}); - } - }; - runsOf(state.splitPushRuns, userWords); - runsOf(state.wholePushRuns, 0u); + layOutStagePush(state, shader, placements[shaderIndex]); } - for (auto& elements : addressedElements) elements.clear(); - addressedAllocations.assign(allocations.size(), 0); - for (const auto& binding : bindings) { - if (!binding.addressed) continue; - Require(binding.dataStage < addressedElements.size(), "an addressed buffer binding names no data stage"); - for (const auto index : binding.allocations) { - addressedElements[binding.dataStage].push_back(static_cast(index)); - addressedAllocations[index] = 1; - } + collectAddressedElements(); +} + +ShaderResources::HeapElementClass ShaderResources::classifyHeapElement(const Binding& binding, std::size_t element) const { + if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) return HeapElementClass::Sampler; + const auto index = binding.imageAllocations[element]; + if (index == std::numeric_limits::max()) return HeapElementClass::Absent; + if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) return HeapElementClass::SampledImage; + if (storageTextures[index] != nullptr) return HeapElementClass::StorageImage; + return heapMultisampleStorageView(index) != VK_NULL_HANDLE ? HeapElementClass::MultisampleStorage : HeapElementClass::Absent; +} + +template +bool ShaderResources::forEachHeapElement(const Binding& binding, Visit&& visit) const { + const auto type = binding.layout.descriptorType; + if (type != VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE && type != VK_DESCRIPTOR_TYPE_STORAGE_IMAGE && type != VK_DESCRIPTOR_TYPE_SAMPLER) return true; + for (std::size_t element = 0; element < binding.imageAllocations.size(); ++element) { + if (!visit(HeapElement{classifyHeapElement(binding, element), binding.imageAllocations[element], element})) return false; } + return true; } template void ShaderResources::visitHeapSlotKey(std::span owned, Emit&& emit) const { - constexpr auto absent = std::numeric_limits::max(); const auto put = [&](std::uintptr_t first, std::uintptr_t view, std::uintptr_t layout) { return emit(first) && emit(view) && emit(layout); }; for (const auto bindingIndex : owned) { const auto& binding = bindings[bindingIndex]; - if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) { - for (const auto index : binding.imageAllocations) { - if (index == absent) { - if (!emit(0u)) return; - continue; - } - if (!put(reinterpret_cast(textures[index].get()), reinterpret_cast(heapSampledView(index)), static_cast(textures[index]->Layout()))) return; - } - } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { - for (const auto index : binding.imageAllocations) { - if (index != absent && storageTextures[index] == nullptr && heapMultisampleStorageView(index) != VK_NULL_HANDLE) { - if (!put(reinterpret_cast(heapMultisampleStorageOwner(index)), reinterpret_cast(heapMultisampleStorageView(index)), static_cast(VK_IMAGE_LAYOUT_GENERAL))) return; - continue; - } - if (index == absent || storageTextures[index] == nullptr) { - if (!emit(0u)) return; - continue; - } - if (!put(reinterpret_cast(storageTextures[index].get()), reinterpret_cast(heapStorageView(index, binding.layout.binding)), static_cast(VK_IMAGE_LAYOUT_GENERAL))) return; - } - } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { - for (const auto index : binding.imageAllocations) { - if (!emit(reinterpret_cast(samplers[index].get()))) return; + const bool completed = forEachHeapElement(binding, [&](const HeapElement& item) { + switch (item.kind) { + case HeapElementClass::Absent: + return emit(0u); + case HeapElementClass::SampledImage: + return put(reinterpret_cast(textures[item.index].get()), reinterpret_cast(heapSampledView(item.index)), static_cast(textures[item.index]->Layout())); + case HeapElementClass::StorageImage: + return put(reinterpret_cast(storageTextures[item.index].get()), reinterpret_cast(heapStorageView(item.index, binding.layout.binding)), static_cast(VK_IMAGE_LAYOUT_GENERAL)); + case HeapElementClass::MultisampleStorage: + return put(reinterpret_cast(heapMultisampleStorageOwner(item.index)), reinterpret_cast(heapMultisampleStorageView(item.index)), static_cast(VK_IMAGE_LAYOUT_GENERAL)); + case HeapElementClass::Sampler: + return emit(reinterpret_cast(samplers[item.index].get())); } - } + return true; + }); + if (!completed) return; } } @@ -8343,99 +8346,80 @@ void ShaderResources::takeHeapSlots(BindlessHeap& heap, HeapStageState& state, s std::span key) { namespace Abi = ShaderRecompiler::RuntimeAbi; constexpr auto bindingCount = static_cast(Abi::Binding::Count); - constexpr auto absent = std::numeric_limits::max(); struct TakenStorage {}; auto& taken = HostThreadLocal>, TakenStorage>(); taken.clear(); - state.samplerSlots.clear(); + state.samplers.slots.clear(); std::size_t cursor = 0; for (const auto bindingIndex : owned) { const auto& binding = bindings[bindingIndex]; const auto kind = binding.layout.binding % bindingCount; - if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) { - for (const auto index : binding.imageAllocations) { - if (index == absent) { - ++cursor; - taken.emplace_back(kind, heap.AbsentSlot(kind, heapPlaceholderView(kind))); - continue; - } - const auto view = reinterpret_cast(key[cursor + 1]); - cursor += 3; - taken.emplace_back(kind, takenSlot(heap.TextureSlot(kind, textures[index].get(), view, textures[index]->Layout()), "the global image heap is full")); - } - } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { - for (const auto index : binding.imageAllocations) { - if (index != absent && storageTextures[index] == nullptr && heapMultisampleStorageView(index) != VK_NULL_HANDLE) { - const auto view = reinterpret_cast(key[cursor + 1]); - cursor += 3; - taken.emplace_back(kind, takenSlot(heap.ViewSlot(kind, heapMultisampleStorageOwner(index), view), "the global storage image heap is full")); - continue; - } - if (index == absent || storageTextures[index] == nullptr) { - ++cursor; + forEachHeapElement(binding, [&](const HeapElement& item) { + const auto index = item.index; + const auto keyView = [&] { return reinterpret_cast(key[cursor + 1]); }; + switch (item.kind) { + case HeapElementClass::Absent: taken.emplace_back(kind, heap.AbsentSlot(kind, heapPlaceholderView(kind))); - continue; + break; + case HeapElementClass::SampledImage: + taken.emplace_back(kind, takenSlot(heap.TextureSlot(kind, textures[index].get(), keyView(), textures[index]->Layout()), "the global image heap is full")); + break; + case HeapElementClass::StorageImage: + taken.emplace_back(kind, takenSlot(heap.StorageSlot(kind, storageTextures[index].get(), keyView()), "the global storage image heap is full")); + break; + case HeapElementClass::MultisampleStorage: + taken.emplace_back(kind, takenSlot(heap.ViewSlot(kind, heapMultisampleStorageOwner(index), keyView()), "the global storage image heap is full")); + break; + case HeapElementClass::Sampler: { + const bool embedded = item.element < binding.embeddedSamplers.size() && binding.embeddedSamplers[item.element]; + state.samplers.slots.push_back(embedded ? ShaderRecompiler::RuntimeAbi::NoEmbeddedSampler : takenSlot(heap.SamplerSlot(samplers[index]), "the global sampler heap is full")); + break; } - const auto view = reinterpret_cast(key[cursor + 1]); - cursor += 3; - taken.emplace_back(kind, takenSlot(heap.StorageSlot(kind, storageTextures[index].get(), view), "the global storage image heap is full")); - } - } else if (binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { - for (std::size_t element = 0; element < binding.imageAllocations.size(); ++element) { - ++cursor; - const bool embedded = element < binding.embeddedSamplers.size() && binding.embeddedSamplers[element]; - state.samplerSlots.push_back(embedded ? ShaderRecompiler::RuntimeAbi::NoEmbeddedSampler : takenSlot(heap.SamplerSlot(samplers[binding.imageAllocations[element]]), "the global sampler heap is full")); } - } + cursor += heapElementKeyWords(item.kind); + return true; + }); } std::stable_sort(taken.begin(), taken.end(), [](const auto& left, const auto& right) { return left.first < right.first; }); - state.imageSlots.clear(); + state.images.slots.clear(); state.kindRanges.clear(); for (const auto& [kind, slot] : taken) { if (state.kindRanges.empty() || state.kindRanges.back().kind != kind) - state.kindRanges.push_back({kind, static_cast(state.imageSlots.size()), 0u}); - state.imageSlots.push_back(slot); + state.kindRanges.push_back({kind, static_cast(state.images.slots.size()), 0u}); + state.images.slots.push_back(slot); ++state.kindRanges.back().count; } } -void ShaderResources::noteHeapSlotGenerations(const BindlessHeap& heap, HeapStageState& state) { - state.slotGenerations.clear(); - for (const auto slot : state.imageSlots) state.slotGenerations.push_back(heap.SlotGeneration(slot)); - state.samplerGenerations.clear(); - for (const auto slot : state.samplerSlots) state.samplerGenerations.push_back(heap.SamplerGeneration(slot)); -} - void ShaderResources::verifyHeapSlots(const BindlessHeap& heap, const HeapStageState& state, VkShaderStageFlags stageBit) const { constexpr auto bindingCount = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count); static std::atomic checked{0}, wrong{0}, storageChecked{0}, storageWrong{0}; const auto wrongBefore = wrong.load() + storageWrong.load(); for (const auto& binding : bindings) { if (!ownsHeapBinding(binding, stageBit)) continue; - const bool sampled = binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; - const bool storage = binding.layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - if (!sampled && !storage) continue; const auto kind = binding.layout.binding % bindingCount; - for (std::size_t element = 0; element < binding.imageAllocations.size(); ++element) { - const auto index = binding.imageAllocations[element]; - if (index == std::numeric_limits::max()) continue; - const auto kindSlots = state.Slots(kind); - const bool bound = element < kindSlots.size(); - if (sampled) { - ++checked; - if (!bound || heap.SlotTexture(kind, kindSlots[element]) != textures[index].get()) ++wrong; - continue; + const auto kindSlots = state.Slots(kind); + forEachHeapElement(binding, [&](const HeapElement& item) { + const bool bound = item.element < kindSlots.size(); + switch (item.kind) { + case HeapElementClass::Absent: + case HeapElementClass::Sampler: + break; + case HeapElementClass::SampledImage: + ++checked; + if (!bound || heap.SlotTexture(kind, kindSlots[item.element]) != textures[item.index].get()) ++wrong; + break; + case HeapElementClass::StorageImage: + ++storageChecked; + if (!bound || !heap.SlotHoldsStorage(kind, kindSlots[item.element], storageTextures[item.index].get(), heapStorageView(item.index, binding.layout.binding))) ++storageWrong; + break; + case HeapElementClass::MultisampleStorage: + ++storageChecked; + if (!bound || !heap.SlotHoldsStorage(kind, kindSlots[item.element], heapMultisampleStorageOwner(item.index), heapMultisampleStorageView(item.index))) ++storageWrong; + break; } - if (storageTextures[index] == nullptr) { - const auto view = heapMultisampleStorageView(index); - if (view == VK_NULL_HANDLE) continue; - ++storageChecked; - if (!bound || !heap.SlotHoldsStorage(kind, kindSlots[element], heapMultisampleStorageOwner(index), view)) ++storageWrong; - continue; - } - ++storageChecked; - if (!bound || !heap.SlotHoldsStorage(kind, kindSlots[element], storageTextures[index].get(), heapStorageView(index, binding.layout.binding))) ++storageWrong; - } + return true; + }); } if ((checked.load() + storageChecked.load()) % 100000u < 8u) { std::fprintf(stderr, "[heap-slots] verify: %llu image slots checked, %llu hold another texture; %llu storage slots checked, %llu hold another image or view\n", @@ -8464,7 +8448,7 @@ void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const Hea constexpr auto bindingCount = static_cast(Abi::Binding::Count); constexpr auto metadataWords = sizeof(Abi::ResourceMetadata) / sizeof(std::uint32_t); const auto& program = *shader.program; - const auto& samplerSlots = stageState.samplerSlots; + const auto& samplerSlots = stageState.samplers.slots; Require(!leading || program.runtimeImageCount == 0u || program.imageMetadataDword >= patched.size(), "GPU-mode image metadata lies among a stage's user words"); for (std::uint32_t image = 0; !leading && image < program.runtimeImageCount; ++image) { const auto offset = program.imageMetadataDword + image * metadataWords; @@ -8512,40 +8496,44 @@ void ShaderResources::patchHeapSlotWords(const CompiledShader& shader, const Hea if (!slotWords) std::copy(samplerSlots.begin(), samplerSlots.end(), patched.begin() + program.samplerSlotDword); } -std::pair ShaderResources::writeSplitHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, - std::span words, std::span userData, bool sameWalk, bool current) { - static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; - const auto& program = *shader.program; - const auto userWords = std::min(std::max(program.heapUserWords.size(), program.shaderDataUserWords.size()), words.size()); - stageState.userWords = static_cast(userWords); - const auto applyUserData = [&](std::vector& target) { - std::copy_n(userData.begin(), std::min(userData.size(), target.size()), target.begin()); - for (const auto& [byte, adjustment] : stageState.dataPatches) { - if (byte < target.size() * sizeof(std::uint32_t)) reinterpret_cast(target.data())[byte] = static_cast(adjustment); - } - }; +namespace { + +std::vector& PatchedShaderData() { struct PatchedStorage {}; - auto& patched = HostThreadLocal, PatchedStorage>(); - const bool dataKept = sameWalk && !verifySlots && keptTable(spans, heap, stageState.data); - auto dataAddress = stageState.data.table.address; - if (!dataKept) { - ValidateRuntimeResources(shader, words); - patched.assign(words.begin(), words.end()); - for (const auto& [byte, adjustment] : stageState.dataPatches) { - Require(byte < patched.size() * sizeof(std::uint32_t), "a GPU-mode guest buffer offset lies outside the shader data"); - } - applyUserData(patched); - patchHeapSlotWords(shader, stageState, patched, current); - if (verifySlots && sameWalk && stageState.data.words.size() == patched.size() && - !std::equal(patched.begin() + static_cast(userWords), patched.end(), stageState.data.words.begin() + static_cast(userWords))) - throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its walked words and slots did not"); - dataAddress = heapTable(spans, heap, stageState.data, patched); - ++stageState.pushVersion; - stageState.dataInput.assign(words.begin(), words.end()); - stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); - stageState.dataOrigin = shader.heap != nullptr ? shader.heap->dataOrigin : 0u; - stageState.dataProgram = shader.program; + return HostThreadLocal, PatchedStorage>(); +} + +void ApplyUserData(std::vector& target, std::span userData, const std::vector>& patches) { + std::copy_n(userData.begin(), std::min(userData.size(), target.size()), target.begin()); + for (const auto& [byte, adjustment] : patches) { + if (byte < target.size() * sizeof(std::uint32_t)) reinterpret_cast(target.data())[byte] = static_cast(adjustment); + } +} + +} + +void ShaderResources::buildPatchedData(std::vector& patched, const CompiledShader& shader, const HeapStageState& stageState, std::span words, std::span userData, bool current) const { + ValidateRuntimeResources(shader, words); + patched.assign(words.begin(), words.end()); + for (const auto& [byte, adjustment] : stageState.dataPatches) { + Require(byte < patched.size() * sizeof(std::uint32_t), "a GPU-mode guest buffer offset lies outside the shader data"); } + ApplyUserData(patched, userData, stageState.dataPatches); + patchHeapSlotWords(shader, stageState, patched, current); +} + +std::uint64_t ShaderResources::commitStageData(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, std::span patched, std::span words, std::span userData) { + const auto address = heapTable(spans, heap, stageState.data, patched); + ++stageState.pushVersion; + stageState.dataInput.assign(words.begin(), words.end()); + stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); + stageState.dataOrigin = shader.heap != nullptr ? shader.heap->dataOrigin : 0u; + stageState.dataProgram = shader.program; + return address; +} + +std::uint64_t ShaderResources::writeSplitUserData(BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, std::span words, std::span userData, std::size_t userWords, const std::vector& patched, bool current, std::uint64_t dataAddress) { + const bool verifySlots = ShaderRecompiler::HeapVerifyEnabled(); const auto userFront = words.first(userWords); auto& input = stageState.userInput; const bool sameUserInput = current && stageState.userProgram == shader.program && stageState.user.words.size() == userWords && @@ -8555,7 +8543,7 @@ std::pair ShaderResources::writeSplitHeapStage(con auto& built = HostThreadLocal, UserStorage>(); if (!sameUserInput || verifySlots) { built.assign(userFront.begin(), userFront.end()); - applyUserData(built); + ApplyUserData(built, userData, stageState.dataPatches); patchHeapSlotWords(shader, stageState, built, current, true); if (verifySlots && !std::equal(built.begin(), built.end(), patched.begin())) throw std::runtime_error("AGC graphics: a GPU-mode stage's user-data block differs from the user words of its full shader data"); @@ -8574,20 +8562,35 @@ std::pair ShaderResources::writeSplitHeapStage(con if (userWords <= 64u && pushedUser == userMask) { if (stageState.user.words.size() == user.size() && userChanged) NotePushedUserDataKeep(); if (userChanged) stageState.user.words.assign(user.begin(), user.end()); - return {dataAddress, dataAddress}; + return dataAddress; } if (userChanged) stageState.user.words.assign(user.begin(), user.end()); const auto span = heap.Allocate(user.size()); BindlessHeap::Write(span, user); - return {dataAddress, span.address}; + return span.address; } -void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader) { - namespace Abi = ShaderRecompiler::RuntimeAbi; - const VkShaderStageFlags stageBit = VulkanStage(shader.stage); - const auto stageIndex = HeapStageIndex(shader.stage); - auto& stageState = heapStages[stageIndex]; - static const bool verifySlots = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; +std::pair ShaderResources::writeSplitHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, HeapStageState& stageState, + std::span words, std::span userData, bool sameWalk, bool current) { + const bool verifySlots = ShaderRecompiler::HeapVerifyEnabled(); + const auto& program = *shader.program; + const auto userWords = std::min(std::max(program.heapUserWords.size(), program.shaderDataUserWords.size()), words.size()); + stageState.userWords = static_cast(userWords); + auto& patched = PatchedShaderData(); + const bool dataKept = sameWalk && !verifySlots && keptTable(spans, heap, stageState.data); + auto dataAddress = stageState.data.table.address; + if (!dataKept) { + buildPatchedData(patched, shader, stageState, words, userData, current); + if (verifySlots && sameWalk && stageState.data.words.size() == patched.size() && + !std::equal(patched.begin() + static_cast(userWords), patched.end(), stageState.data.words.begin() + static_cast(userWords))) + throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its walked words and slots did not"); + dataAddress = commitStageData(spans, heap, shader, stageState, patched, words, userData); + } + return {dataAddress, writeSplitUserData(heap, shader, stageState, words, userData, userWords, patched, current, dataAddress)}; +} + +bool ShaderResources::refreshHeapStageSlots(BindlessHeap& heap, HeapStageState& stageState, VkShaderStageFlags stageBit) { + const bool verifySlots = ShaderRecompiler::HeapVerifyEnabled(); Require(stageState.laidOutFor == stageBit, "a GPU heap stage was refreshed for a stage its resources were not laid out for"); const auto& owned = stageState.owned; const bool keyed = stageState.keyTaken; @@ -8596,82 +8599,73 @@ void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, Bindl if (keyed && verifySlots && !slotsBypassed && !current) throw std::runtime_error("AGC graphics: a GPU heap stage's textures, views or samplers changed after its resources were built"); const auto slotSerial = heap.SlotSerial(); const bool unmoved = current && EpochProofs() && stageState.slotSerial == slotSerial; - if (!unmoved && current) - current = - heap.GenerationsCurrent(stageState.imageSlots, stageState.slotGenerations, stageState.samplerSlots, stageState.samplerGenerations); + if (!unmoved && current) current = HeapStageState::SlotSet::Current(heap, stageState.images, stageState.samplers); if (!current) { appendHeapSlotKey(owned, stageState.key); takeHeapSlots(heap, stageState, owned, stageState.key); - noteHeapSlotGenerations(heap, stageState); + stageState.images.CaptureImageGenerations(heap); + stageState.samplers.CaptureSamplerGenerations(heap); stageState.keyTaken = true; } else { - stageState.touchedEpoch = heap.TouchSlots(stageState.imageSlots, stageState.samplerSlots, stageState.touchedEpoch); + stageState.touchedEpoch = HeapStageState::SlotSet::Touch(heap, stageState.images, stageState.samplers, stageState.touchedEpoch); } stageState.slotSerial = slotSerial; if (verifySlots) verifyHeapSlots(heap, stageState, stageBit); + return current; +} +void ShaderResources::writeHeapDataBinding(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader, const ShaderRecompiler::DescriptorBinding& binding, bool current) { + namespace Abi = ShaderRecompiler::RuntimeAbi; + const auto stageIndex = HeapStageIndex(shader.stage); + auto& stageState = heapStages[stageIndex]; + const bool verifySlots = ShaderRecompiler::HeapVerifyEnabled(); const std::size_t dataIndex = DataOffsetIndex(stageIndex, Abi::Binding::ShaderData); - const std::size_t flatIndex = DataOffsetIndex(stageIndex, Abi::Binding::FlattenedSrt); + const bool shaderData = binding.role == ShaderRecompiler::DescriptorRole::ShaderData; + const bool heapFlattened = !shaderData && shader.heap != nullptr && !shader.heap->flattenedSrt.empty(); + const auto& words = heapFlattened ? shader.heap->flattenedSrt : DrawGuestWords(shader, binding); + const auto userData = + shader.heap != nullptr ? std::span(shader.heap->userData) : std::span{}; + const auto userFront = static_cast(std::min(userData.size(), words.size())); + const auto origin = shaderData && shader.heap != nullptr ? shader.heap->dataOrigin : 0u; + const bool sameShape = shaderData && current && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::StageData) && stageState.dataInput.size() == words.size() + userData.size(); + const bool sameOrigin = sameShape && origin != 0u && origin == stageState.dataOrigin && stageState.dataProgram == shader.program; + const bool sameWords = sameShape && (sameOrigin || std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)); + if (verifySlots && sameOrigin && !std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)) + throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data differs from the data of the same origin"); + const auto userInput = stageState.dataInput.begin() + static_cast(words.size()); + const bool sameInput = sameWords && std::equal(userData.begin(), userData.end(), userInput); + if (shaderData && stageState.splitUser) { + const auto [dataAddress, userAddress] = writeSplitHeapStage(spans, heap, shader, stageState, words, userData, sameWords, current); + heapOffsets[dataIndex] = dataAddress; + heapOffsets[DataOffsetIndex(stageIndex, Abi::Binding::UserData)] = userAddress; + return; + } + if (sameInput && !verifySlots && keptTable(spans, heap, stageState.data)) { + heapOffsets[dataIndex] = stageState.data.table.address; + return; + } + if (!shaderData) { + heapOffsets[DataOffsetIndex(stageIndex, Abi::Binding::FlattenedSrt)] = heapSpan(spans, heap, stageState.flat, words); + return; + } + auto& patched = PatchedShaderData(); + buildPatchedData(patched, shader, stageState, words, userData, current); + if (verifySlots && sameInput && !std::ranges::equal(stageState.data.words, patched)) + throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its inputs and slots did not"); + if (sameWords) NoteUserWordsRewrite(patched.size(), userData.size()); + heapOffsets[dataIndex] = commitStageData(spans, heap, shader, stageState, patched, words, userData); +} + +void ShaderResources::writeHeapStage(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, const CompiledShader& shader) { + const auto stageIndex = HeapStageIndex(shader.stage); + auto& stageState = heapStages[stageIndex]; + const bool current = refreshHeapStageSlots(heap, stageState, VulkanStage(shader.stage)); const auto& program = *shader.program; if (program.dataAddressPush) writeHeapTableMap(spans, heap, shader, stageIndex); - const std::size_t userIndex = DataOffsetIndex(stageIndex, Abi::Binding::UserData); - const bool splitUser = stageState.splitUser; const auto previousUserWords = stageState.userWords; stageState.userWords = 0; - bool dataBindings = false; for (const auto& binding : program.bindings) { - const bool shaderData = binding.role == ShaderRecompiler::DescriptorRole::ShaderData; - if (!shaderData && binding.role != ShaderRecompiler::DescriptorRole::FlattenedSrt) continue; - dataBindings = true; - const bool heapFlattened = !shaderData && shader.heap != nullptr && !shader.heap->flattenedSrt.empty(); - const auto& words = heapFlattened ? shader.heap->flattenedSrt : DrawGuestWords(shader, binding); - const auto userData = - shader.heap != nullptr ? std::span(shader.heap->userData) : std::span{}; - const auto userFront = static_cast(std::min(userData.size(), words.size())); - const auto origin = shaderData && shader.heap != nullptr ? shader.heap->dataOrigin : 0u; - const bool sameShape = shaderData && current && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::StageData) && stageState.dataInput.size() == words.size() + userData.size(); - const bool sameOrigin = sameShape && origin != 0u && origin == stageState.dataOrigin && stageState.dataProgram == shader.program; - const bool sameWords = sameShape && (sameOrigin || std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)); - if (verifySlots && sameOrigin && !std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)) - throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data differs from the data of the same origin"); - const auto userInput = stageState.dataInput.begin() + static_cast(words.size()); - const bool sameInput = sameWords && std::equal(userData.begin(), userData.end(), userInput); - if (shaderData && splitUser) { - const auto [dataAddress, userAddress] = writeSplitHeapStage(spans, heap, shader, stageState, words, userData, sameWords, current); - heapOffsets[dataIndex] = dataAddress; - heapOffsets[userIndex] = userAddress; - continue; - } - if (sameInput && !verifySlots) { - if (keptTable(spans, heap, stageState.data)) { - heapOffsets[dataIndex] = stageState.data.table.address; - continue; - } - } - if (!shaderData) { - heapOffsets[flatIndex] = heapSpan(spans, heap, stageState.flat, words); - continue; - } - ValidateRuntimeResources(shader, words); - struct PatchedStorage {}; - auto& patched = HostThreadLocal, PatchedStorage>(); - patched.assign(words.begin(), words.end()); - if (shader.heap != nullptr) - std::copy_n(shader.heap->userData.begin(), std::min(shader.heap->userData.size(), patched.size()), patched.begin()); - for (const auto& [byte, adjustment] : stageState.dataPatches) { - Require(byte < patched.size() * sizeof(std::uint32_t), "a GPU-mode guest buffer offset lies outside the shader data"); - reinterpret_cast(patched.data())[byte] = static_cast(adjustment); - } - patchHeapSlotWords(shader, stageState, patched, current); - if (verifySlots && sameInput && !std::ranges::equal(stageState.data.words, patched)) - throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data changed although its inputs and slots did not"); - if (sameWords) NoteUserWordsRewrite(patched.size(), userData.size()); - heapOffsets[dataIndex] = heapTable(spans, heap, stageState.data, patched); - ++stageState.pushVersion; - stageState.dataInput.assign(words.begin(), words.end()); - stageState.dataInput.insert(stageState.dataInput.end(), userData.begin(), userData.end()); - stageState.dataOrigin = origin; - stageState.dataProgram = shader.program; + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData || binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt) writeHeapDataBinding(spans, heap, shader, binding, current); } if (stageState.userWords != previousUserWords) ++stageState.pushVersion; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index 2344d4fb3788..b33cab3648af 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -636,7 +636,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi const auto heap = static_cast(binding->binding % static_cast(ShaderRecompiler::RuntimeAbi::Binding::Count)); const auto capacity = ShaderRecompiler::RuntimeAbi::HeapCapacity(heap); const auto count = module.constants.find(type[3]); - const bool heapArray = binding->kind != ShaderRecompiler::DescriptorKind::StorageImage || (ShaderRecompiler::RuntimeAbi::GpuHeapStorageKind(static_cast(heap)) && binding->descriptorSet == ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet); + const bool heapArray = binding->kind != ShaderRecompiler::DescriptorKind::StorageImage || (ShaderRecompiler::RuntimeAbi::GpuHeapStorageKind(static_cast(heap)) && ClassifyHeapBinding(*binding) == HeapBindingClass::StorageImage); if (shader.gpuResolvedImages && heapArray) { const auto slots = binding->kind == ShaderRecompiler::DescriptorKind::Sampler ? ShaderRecompiler::RuntimeAbi::GpuSamplerHeapSlots : ShaderRecompiler::RuntimeAbi::GpuImageHeapSlots; const bool length = binding->kind == ShaderRecompiler::DescriptorKind::Sampler ? count != module.constants.end() && count->second == slots : heapImageSlotsLength(module, type[3]); diff --git a/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp b/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp index 45b424fa6011..f5e9b4b859ed 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PendingRangeIndex.cpp @@ -31,9 +31,8 @@ void RandomAgainstScan() { const auto begin = (random() % 4096) * 64; const auto bytes = 1 + random() % (random() % 4 == 0 ? 65536 : 4096); ranges.push_back({begin, begin + bytes}); - index.Add(begin, begin + bytes, item, item); + index.Insert(begin, begin + bytes, item, item); } - index.Seal(); for (int query = 0; query < 200; ++query) { const auto address = (random() % 4200) * 64 + random() % 64; const auto bytes = static_cast(random() % 8 == 0 ? 0 : random() % 20000); @@ -51,10 +50,11 @@ void RandomAgainstScan() { const bool indexed = index.AnyOverlapping(address, bytes, [&](std::size_t item) { return item != except; }); Require(indexed == scanned, "the index and the scan disagree on whether a range overlaps"); std::vector visited(count, false); - index.ForEachOverlapping(address, bytes, [&](std::size_t item) { + static_cast(index.AnyOverlapping(address, bytes, [&](std::size_t item) { Require(!visited[item], "the index visited an item twice"); visited[item] = true; - }); + return false; + })); Require(visited == scannedSet, "the index visited a different set of overlapping items than the scan"); const auto* first = index.FirstByPosition(address, bytes, [&](std::size_t item) { return item != except; }); Require((first == nullptr) == (firstScanned == count), "the index and the scan disagree on the first overlapping item"); @@ -85,7 +85,7 @@ void InsertEraseAgainstScan() { Require(index.Erase(list[at].begin, list[at].item), "the index lost an entry it was given"); list.erase(list.begin() + static_cast(at)); } - Require(index.Size() == list.size(), "the index holds a different number of entries than the list"); + Require(index.Entries().size() == list.size(), "the index holds a different number of entries than the list"); Require(!index.Erase(1u << 30, -1), "the index erased an entry it was never given"); for (int query = 0; query < 8; ++query) { const auto address = (random() % 300) * 4096 + random() % 4096; @@ -98,7 +98,10 @@ void InsertEraseAgainstScan() { if (firstScanned < 0 && live.item % 2 == 0) firstScanned = live.item; } std::size_t visited = 0; - index.ForEachOverlapping(address, bytes, [&](int) { ++visited; }); + static_cast(index.AnyOverlapping(address, bytes, [&](int) { + ++visited; + return false; + })); Require(visited == overlapping, "after inserts and erases the index visited a different number of overlapping entries than the scan"); const auto* first = index.FirstByPosition(address, bytes, [](int item) { return item % 2 == 0; }); Require((first == nullptr ? -1 : first->item) == firstScanned, "after inserts and erases the index named a different first match than the list order"); @@ -110,10 +113,9 @@ void InsertEraseAgainstScan() { void Edges() { AgcDriver::Graphics::PendingRangeIndex index; - index.Add(100, 200, 1, 0); - index.Add(0, 1000, 2, 1); - index.Add(300, 301, 3, 2); - index.Seal(); + index.Insert(100, 200, 1, 0); + index.Insert(0, 1000, 2, 1); + index.Insert(300, 301, 3, 2); const auto any = [&](std::uint64_t address, std::size_t bytes, int skip) { return index.AnyOverlapping(address, bytes, [&](int item) { return item != skip; }); }; Require(any(500, 1, 0), "a long earlier range covering the query was missed"); Require(!any(500, 1, 2), "an excluded item was reported"); diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index 42d8f2dc07ba..de63441c09ba 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -257,6 +257,8 @@ function(add_shader_recompiler target runtimeTarget) HeapCacheBypassed HeapCacheBypassMask HeapCacheNames + HeapVerifyEnabled + HeapVerifyEvery HeapOnlyCacheCount ParseHeapCacheBypass BdaAbi::RangesOrdered diff --git a/core/shader/recompiler/HeapCacheSwitch.hpp b/core/shader/recompiler/HeapCacheSwitch.hpp index 314b5fc35ab2..d7550c7b5c69 100644 --- a/core/shader/recompiler/HeapCacheSwitch.hpp +++ b/core/shader/recompiler/HeapCacheSwitch.hpp @@ -76,4 +76,19 @@ inline constexpr std::array(HeapCache return (HeapCacheBypassMask() >> static_cast(cache) & 1u) != 0u; } +[[nodiscard]] inline bool HeapVerifyEnabled() { + static const bool enabled = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; + return enabled; +} + +[[nodiscard]] inline std::uint64_t HeapVerifyEvery() { + static const std::uint64_t every = [] { + const char* text = std::getenv("APS5_VERIFY_GPU_HEAP"); + if (text == nullptr) return std::uint64_t{0}; + const auto value = std::strtoull(text, nullptr, 10); + return value == 0 ? std::uint64_t{1} : static_cast(value); + }(); + return every; +} + } diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 44f3be9742f1..0557f7b9aeb8 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -2702,8 +2702,7 @@ void HeapBindingWords(const RecompileRequest& request, const CompiledVariant& va const auto tables = tableRoles ? std::optional(ResourceMaterializer::ResolveImageTables(variant.info.info, snapshot, variant.artifact.variantId)) : std::nullopt; DescriptorBindingBuilder{}.PopulateGuestWords(words.bindings, variant.bindings, *shared.plan.plan, variant.info.userDataBase, snapshot, partialThreads(request), tables ? &*tables : nullptr); if (words.bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw bindings differ from its template"); - static const bool verify = std::getenv("APS5_VERIFY_GPU_HEAP") != nullptr; - if (verify) { + if (HeapVerifyEnabled()) { const auto resolved = ResourceMaterializer::ResolveImageTables(variant.info.info, snapshot, variant.artifact.variantId); BindingAllocationResult bindings; DescriptorBindingBuilder{}.Populate(bindings, variant.bindings, *shared.plan.plan, variant.info.userDataBase, snapshot, partialThreads(request), &resolved); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 6babd3896bd4..32f55a28a0b9 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -581,7 +581,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_VERIFY_DRAW_PUSH_WORD` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | with `APS5_DRAW_CACHE_PUSH_WORD`, also builds every forwarded stage in full and throws when its variant, push constants, bindings or forwarded words differ from the forwarded result | | `APS5_VERIFY_DRAW_RECIPE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | re-decodes a draw recipe instead of using the cache and checks the result | | `APS5_VERIFY_DRAW_SNAPSHOTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | re-reads a reused draw snapshot and counts the ones that differ | -| `APS5_VERIFY_GPU_HEAP` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | | checks heap slots and GPU-read constants, and rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (0 or no number means every stage) | +| `APS5_VERIFY_GPU_HEAP` | integer | `core/shader/recompiler/HeapCacheSwitch.hpp` | | checks heap slots and GPU-read constants, and rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (0 or no number means every stage) | | `APS5_VERIFY_GUARD_SPANS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp` | | checks every guard check that the thread's copy of the guard ranges answered without a lock against the guard list and takes the list's answer; a copy that was current, or a copy refilled after the list changed, that still misses an overlapping guard prints a `[guard-spans] verify` line (the first twenty), and a `[guard-spans]` line every 10 s counts the checks and misses (it also prints with `APS5_PROFILE_DRAW`) | | `APS5_VERIFY_KNOWN_VALUES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferCopy.cpp` | | serves known values through the hook too and counts mismatches | | `APS5_VERIFY_OWNED_DRAW_INPUTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | compares reused owned input bytes and throws if they differ while the proof still holds | From ee25c5c773b3eb0d9a28e68c3490609108330097 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 07:39:25 +0530 Subject: [PATCH 228/269] refactor(agc): share the heap ring, finisher and presentation paths and read each cache switch once --- .../include/Driver/Draw/DrawCache.hpp | 9 +- .../include/Driver/Draw/DrawPipeline.hpp | 1 + .../include/Driver/Draw/HeapStages.hpp | 7 +- .../Execution/include/Driver/Driver.hpp | 2 + .../Execution/include/GuestMemory.hpp | 1 - .../src/Driver/Dispatch/Dispatch.cpp | 43 +++++-- .../Execution/src/Driver/Draw/Draw.cpp | 106 +++------------- .../Execution/src/Driver/Draw/DrawCache.cpp | 29 +++-- .../Execution/src/Driver/Draw/DrawCapture.cpp | 26 ++-- .../src/Driver/Draw/DrawPipeline.cpp | 9 ++ .../Execution/src/Driver/Draw/HeapStages.cpp | 116 +++++++++++++----- .../src/Driver/Packets/PacketExecution.cpp | 7 +- .../src/Driver/Packets/PacketMemory.cpp | 12 +- .../Execution/src/GuestMemory.cpp | 4 - .../Execution/src/PresentationPass.cpp | 30 +---- .../Execution/src/PresentationUpscaler.cpp | 23 +--- .../Execution/src/VulkanDevice.cpp | 21 ++-- .../Graphics/include/BindlessHeap.hpp | 3 + .../Graphics/src/BindlessHeap.cpp | 28 +++++ .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 10 +- .../Graphics/src/ShaderResources.cpp | 10 +- core/shader/recompiler/CMakeLists.txt | 4 +- core/shader/recompiler/HeapCacheSwitch.hpp | 27 +++- .../include/Optimization/ResourceProgram.hpp | 7 ++ core/shader/recompiler/Recompiler.cpp | 13 +- core/shader/recompiler/Recompiler.hpp | 11 ++ core/shader/recompiler/ShaderDiskCache.cpp | 2 +- docs/dev/ENVIRONMENT.md | 24 ++-- 28 files changed, 321 insertions(+), 264 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp index 5cabc021941a..441dbd003310 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp @@ -124,6 +124,8 @@ class DrawKeySightings { enum class DrawVerdict { Drawn, Nothing, Rejected }; +enum class StageOrigin { Captured, HeapUnread, HeapRead }; + struct StageCapture { std::shared_ptr compiled; std::shared_ptr capture; @@ -132,16 +134,15 @@ struct StageCapture { std::vector> supplied; std::uint64_t forgetSerial = 0; std::uint32_t pushOffset = 0; - std::shared_ptr userDataOwner; std::uint64_t userDataMask = ~std::uint64_t{0}; - bool direct = false; - bool ring = false; + StageOrigin origin = StageOrigin::Captured; std::shared_ptr heapWords; std::shared_ptr> heapReadWords; const ShaderRecompiler::SrtUserDataUse& UserDataUse() const; - bool Cacheable() const { return !direct || ring; } + bool Cacheable() const { return origin != StageOrigin::HeapUnread; } + bool Direct() const { return origin != StageOrigin::Captured; } }; struct RelocatableUserWord { diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp index 0a1b310b4a1c..07ae0d1a3340 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp @@ -150,6 +150,7 @@ class DrawFinisher { static bool Busy() { return outstanding.load(std::memory_order_acquire) != 0; } void Enqueue(Job job); void Enqueue(Job job, Pending held); + void EnqueueBeside(Job job, std::vector writes, std::uint64_t labelAddress = 0, std::vector labelBytes = {}); void Drain(); void Settle(); void ReleaseRan(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index 06bf767be34b..56a3543f96e5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -14,11 +14,13 @@ namespace AgcDriver::DriverDetail { +struct DispatchVariant; + bool HeapStageExcluded(ShaderRecompiler::ShaderStage stage); bool HeapPreRasterStage(ShaderRecompiler::ShaderStage stage); const char* HeapStageIneligibility(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan); bool HeapStageEligible(ShaderRecompiler::ShaderStage stage, const ShaderRecompiler::IrResourcePlan* plan); -bool HeapPlanExcluded(const ShaderRecompiler::IrResourcePlan& plan); +bool HeapExcludedFor(const ShaderRecompiler::PreparedShaderInvocation& invocation); bool HeapClassesExcluded(); void RequireHeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress = false); bool HeapStageFits(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress = false); @@ -34,7 +36,7 @@ struct HeapStageReads { struct HeapStageMaterialized { std::shared_ptr result; - std::shared_ptr words; + std::shared_ptr words; HeapStageReads reads; }; @@ -56,6 +58,7 @@ std::uint64_t HeapRingHitsVerified(); std::uint64_t HeapRingHitsDiffering(); std::shared_ptr PatchedHeapResult(const ShaderRecompiler::RecompileResult& shared, const ShaderRecompiler::HeapStageWords& words); +void BuildRingWords(const DispatchVariant& variant, std::span user, const std::vector* refreshedData, ShaderRecompiler::HeapStageWords& words); void VerifyHeapAccessor(const Graphics::CompiledShader& stage); void VerifyRingWords(const ShaderRecompiler::RecompileResult& kept, const ShaderRecompiler::HeapStageWords& ring, const ShaderRecompiler::RecompileResult& fresh, const ShaderRecompiler::HeapStageWords* freshWords); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp index fa261b860629..2827eb987ab8 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp @@ -242,6 +242,8 @@ class Driver { void accountDrawVariant(const DispatchVariant& variant, bool added); void insertDrawEntry(std::uint64_t key, std::vector>& fresh, std::shared_ptr decode, std::uint64_t shape = 0, bool replaceShape = false); bool admitDrawKey(std::uint64_t key, std::uint64_t shape); + DrawKeySightings& drawKeySightingsTable(); + DrawKeySightings& drawShapeSightingsTable(); void eraseDrawEntry(std::uint64_t key, const std::shared_ptr& expected); std::shared_ptr findDrawRecipe(std::uint64_t key, const std::vector>& stages, const std::shared_ptr& donor = nullptr); void attachDrawRecipe(std::uint64_t key, const std::vector>& stages, std::shared_ptr recipe, const std::shared_ptr& donor = nullptr); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp index 45b4d07dc788..e5675b6b7baf 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp @@ -169,7 +169,6 @@ void SetObservationHookForTest(void (*hook)(int point)); // collect stamps newer. std::uint64_t TrackerGeneration(); std::uint64_t StableTrackerGeneration(); -std::uint64_t TrackerAcquisitions(); void AdvanceTrackerGenerationForTest(std::uint64_t generation); std::uint64_t NewestStamp(std::uint64_t address, std::size_t bytes); bool NoStampAfter(std::span> ranges, std::uint64_t generation); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index f91416c438f8..fb523150e0fb 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -29,6 +29,19 @@ namespace AgcDriver::DriverDetail { namespace { +template +class Lazy { +public: + template + const TValue& Get(TCompute&& compute) { + if (!value.has_value()) value.emplace(compute()); + return *value; + } + +private: + std::optional value; +}; + bool DispatchItemsEnabled() { static const bool enabled = [] { const char* text = std::getenv("APS5_PIPELINE_DISPATCH"); @@ -146,13 +159,23 @@ void Driver::dispatch(QueueState& queue, std::span packet, } const bool pipelineCandidate = !resolving && !fromAhead && DispatchItemsEnabled() && DrawPipeline::Active() && indirectArguments == 0 && deferredLabels().labels.empty() && !matchesCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesStreamCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesTableCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesIndexedCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute); const bool partialLastGroup = partialGroups != std::array{}; + Lazy htileClear; + Lazy> memoryValueFill; + Lazy> htileBufferMaskClear; + const auto htileClearAddress = [&] { return htileClear.Get([&] { return Graphics::HtileDepthClearAddress(std::span(snapshot.code).subspan(codeOffset), userData, compute.numThreads); }); }; + const auto matchedMemoryValueFill = [&]() -> const std::optional& { + return memoryValueFill.Get([&] { return Graphics::MatchMemoryValueFill(std::span(snapshot.code).subspan(codeOffset), userData, compute.numThreads, {packet[1], packet[2], packet[3]}); }); + }; + const auto matchedHtileBufferMaskClear = [&]() -> const std::optional& { + return htileBufferMaskClear.Get([&] { return Graphics::MatchHtileBufferMaskClear(std::span(snapshot.code).subspan(codeOffset), userData, compute, packet, indirectArguments); }); + }; if (!resolving && DrawPipeline::Active() && DrawFinisher::Busy() && !DrawFinisher::OnFinisherThread()) { const auto code = std::span(snapshot.code).subspan(codeOffset); const bool handled = !pipelineCandidate || Graphics::MatchMultisampledSingleClear(code, userData, compute.numThreads) || matchesFillKernel(code, userData, compute) || (indirectArguments == 0 && (MatchDwordPatternFill(packet, code, userData, compute) || MatchConstantDwordFill(packet, code, userData, compute) || MatchClampedGlobalFill(packet, code, userData, compute) || MatchMemoryValueBufferFill(packet, code, userData, compute) || - Graphics::MatchMemoryValueFill(code, userData, compute.numThreads, {packet[1], packet[2], packet[3]}).has_value())) || - Graphics::HtileDepthClearAddress(code, userData, compute.numThreads) != 0 || Graphics::MatchHtileBufferMaskClear(code, userData, compute, packet, indirectArguments).has_value(); + matchedMemoryValueFill().has_value())) || + htileClearAddress() != 0 || matchedHtileBufferMaskClear().has_value(); if (handled) DrawFinisher::Get().Drain(); DrawFinisher::NoteDrain(DrawFinisher::DrainSite::Dispatch, handled); } @@ -170,7 +193,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, return; } if (indirectArguments == 0 && (packet[4] & 0x20u) == 0) { - if (const auto fill = Graphics::MatchMemoryValueFill(std::span(snapshot.code).subspan(codeOffset), userData, compute.numThreads, {packet[1], packet[2], packet[3]})) Graphics::NoteMemoryValueFill(*fill); + if (const auto& fill = matchedMemoryValueFill()) Graphics::NoteMemoryValueFill(*fill); } if (!partialLastGroup && fillBuffer(queue, submission.queue, packet, std::span(snapshot.code).subspan(codeOffset), userData, compute, localDevice)) { pendingDispatchPhases().outcome = DispatchOutcome::FillHle; @@ -178,13 +201,13 @@ void Driver::dispatch(QueueState& queue, std::span packet, return; } if (DrawPipeline::Active() && !pipelineCandidate) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, 0x15); - if (const auto htile = Graphics::HtileDepthClearAddress(std::span(snapshot.code).subspan(codeOffset), userData, compute.numThreads); htile != 0) { + if (const auto htile = htileClearAddress(); htile != 0) { const auto threads = (packet[4] & 0x20u) != 0 ? static_cast(packet[1]) : static_cast(packet[1]) * compute.numThreads[0]; const auto nativeBytes = Graphics::HtileDepthClearBytes_nid_no_patch(std::span(snapshot.code).subspan(codeOffset), userData, compute, packet, indirectArguments); const auto bytes = static_cast(threads * 16u); if (Graphics::NoteHtileDepthClear(htile, bytes, nativeBytes)) htileClearCompletion = std::pair{htile, bytes}; if (nativeBytes != 0u) htileMask = {htile, nativeBytes, userData[5], userData[4]}; - } else if (const auto buffered = Graphics::MatchHtileBufferMaskClear(std::span(snapshot.code).subspan(codeOffset), userData, compute, packet, indirectArguments)) { + } else if (const auto& buffered = matchedHtileBufferMaskClear()) { if (Graphics::NoteHtileDepthClear(buffered->address, buffered->bytes, buffered->bytes)) htileClearCompletion = std::pair{buffered->address, buffered->bytes}; htileMask = *buffered; } @@ -215,9 +238,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, if (request.target.gpuResolvedImages && HeapStageExcluded(ShaderRecompiler::ShaderStage::Compute)) request.target.gpuResolvedImages = false; if (request.target.gpuResolvedImages && HeapClassesExcluded()) { const auto invocation = InvocationFor(snapshot, codeOffset, request); - const auto plan = invocation.Plan() == nullptr ? invocation.LoadPlan() : invocation.Plan(); - require(plan != nullptr, "a GPU heap compute stage has no resource plan to apply APS5_GPU_HEAP_EXCLUDE to"); - if (HeapPlanExcluded(*plan)) { + if (HeapExcludedFor(invocation)) { Graphics::NoteHeapExcluded(Graphics::HeapExcluded::Dispatch); request.target.gpuResolvedImages = false; } @@ -651,10 +672,8 @@ void Driver::dispatch(QueueState& queue, std::span packet, } }; if (DrawFinisher::Overlap() && DrawFinisher::Busy() && !DrawFinisher::OnFinisherThread()) { - DrawFinisher::Pending held; - held.unknown = false; - held.writes = itemWrites; - DrawFinisher::Get().Enqueue([commit = std::move(commit), writes = std::move(itemWrites)]() mutable { + auto held = itemWrites; + DrawFinisher::Get().EnqueueBeside([commit = std::move(commit), writes = std::move(itemWrites)]() mutable { DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Dispatch, std::move(commit), std::move(writes)); }, std::move(held)); } else { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index e131324ae588..9355798b7d58 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -715,8 +715,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span packe ++drawRelocationCounters.hits; ++drawRelocationTrials[drawIdentity].hits; if (drawHit && drawKey != 0 && !drawCache.contains(drawKey)) { - if (!drawKeySightings) drawKeySightings.emplace(drawCacheEntries() * DrawKeySightings::Ways); - admitRelocated = drawKeySightings->SeenBefore(drawKey); + admitRelocated = drawKeySightingsTable().SeenBefore(drawKey); if (admitRelocated) ++drawRelocationCounters.admitted; } if (const auto alias = drawAliases.find(drawAlias); alias != drawAliases.end()) { @@ -730,16 +729,15 @@ DrawVerdict Driver::draw(QueueState& queue, std::span packe } if (profile && drawRelocationCounters.lookups >= 100000) reportDrawRelocation(); } - if (!userPatches.empty() && !drawHit) { + const auto patchedDecode = [&] { auto current = std::make_shared(*decode); for (const auto& patch : userPatches) current->programs[patch.program].userData[patch.index] = patch.value; - decode = std::move(current); - } + return current; + }; + if (!userPatches.empty() && !drawHit) decode = patchedDecode(); if (admitRelocated && std::all_of(matched.begin(), matched.end(), [](const std::shared_ptr& variant) { return variant != nullptr; })) { - auto current = std::make_shared(*decode); - for (const auto& patch : userPatches) current->programs[patch.program].userData[patch.index] = patch.value; std::vector> fresh(matched.begin(), matched.end()); - insertDrawEntry(drawKey, fresh, std::move(current), 0, false); + insertDrawEntry(drawKey, fresh, patchedDecode(), 0, false); } tail.patchedStages = std::any_of(stageData.begin(), stageData.end(), [](const StageDataHit& hit) { return hit.compiled != nullptr; }); tail.relocatedDecode = relocatedDecode; @@ -944,68 +942,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { }; const auto buildRingWords = [&](std::size_t i, const DispatchVariant& variant) { auto words = RecycledRingWords(); - const auto& user = programs[i].userData; - for (const auto index : variant.compiled->heapUserWords) { - require(index < user.size(), "a ring vertex template reads a user word the draw does not have"); - words->userData.push_back(user[index]); - } - const auto& ringTemplate = *variant.ringTemplate; - words->vertexAttributes = ringTemplate.vertexAttributes; - words->flattenedSrt.clear(); - for (auto& descriptor : words->bindings) descriptor.clear(); - words->base = nullptr; - words->dataOrigin = ringTemplate.dataOrigin; - if (!ringTemplate.flattenedSrt.empty()) { - words->flattenedSrt = ringTemplate.flattenedSrt; - if (&variant == matched[i].get() && stageData[i].compiled != nullptr) { - for (std::size_t k = 0; k < variant.dataPositions.size(); ++k) { - if (variant.dataSlots[k] < words->flattenedSrt.size()) words->flattenedSrt[variant.dataSlots[k]] = stageData[i].words[variant.dataPositions[k]]; - } - } - } - if (!ringTemplate.bindings.empty()) { - const auto& program = variant.compiled->bindings; - require(ringTemplate.bindings.size() == program.size(), "a ring vertex hit's bindings differ in number from its template"); - words->base = variant.ringTemplate; - words->bindings.resize(program.size()); - for (std::size_t index = 0; index < program.size(); ++index) { - const auto& shared = ringTemplate.bindings[index]; - if (program[index].role != ShaderRecompiler::DescriptorRole::ShaderData || shared.empty()) continue; - auto& descriptor = words->bindings[index]; - descriptor.assign(shared.begin(), shared.end()); - std::copy_n(words->userData.begin(), std::min(words->userData.size(), descriptor.size()), descriptor.begin()); - if (descriptor == program[index].guestDescriptor) descriptor.clear(); - } - } else { - words->bindings.clear(); - } - ShaderRecompiler::CompleteHeapDataWords(*variant.compiled, *words); - if (!variant.ringDescriptorPatches.empty() || !variant.ringDataPatches.empty()) { - const auto& program = variant.compiled->bindings; - if (words->bindings.empty()) words->bindings.resize(program.size()); - const auto own = [&](std::size_t index) -> std::vector& { - auto& descriptor = words->bindings[index]; - if (descriptor.empty()) { - const auto& source = Graphics::DrawGuestWords(*variant.compiled, words.get(), program[index]); - descriptor.assign(source.begin(), source.end()); - } - return descriptor; - }; - for (const auto& [binding, word, value] : variant.ringDescriptorPatches) { - if (binding >= program.size() || word >= program[binding].guestDescriptor.size()) continue; - if (program[binding].role == ShaderRecompiler::DescriptorRole::ShaderData && word >= words->userData.size()) words->dataOrigin = 0; - auto& descriptor = own(binding); - if (word < descriptor.size()) descriptor[word] = value; - } - for (const auto& [slot, value] : variant.ringDataPatches) { - if (slot >= words->userData.size()) words->dataOrigin = 0; - for (std::size_t index = 0; index < program.size(); ++index) { - if (program[index].role != ShaderRecompiler::DescriptorRole::ShaderData || slot >= program[index].guestDescriptor.size()) continue; - auto& descriptor = own(index); - if (slot < descriptor.size()) descriptor[slot] = value; - } - } - } + BuildRingWords(variant, programs[i].userData, &variant == matched[i].get() && stageData[i].compiled != nullptr ? &stageData[i].words : nullptr, *words); if (words->vertexAttributes.empty()) return words; if (!vertexInfos[i] || graphics.stages.mesh) { decodeVertexInfo(i); @@ -1078,24 +1015,29 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { const auto ringWords = [&](std::size_t i) { if (matched[i]->ringTemplate == nullptr) return; stageCaptures[i].heapWords = buildRingWords(i, *matched[i]); - stageCaptures[i].direct = true; - stageCaptures[i].ring = true; + stageCaptures[i].origin = StageOrigin::HeapRead; + }; + const auto adoptMatched = [&](std::size_t i) { + programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); + memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); + ringWords(i); }; std::optional indirectCpu; std::size_t completedSubdraws = 0; std::vector pushOffsets(programs.size(), 0); std::optional meshBarycentrics; std::vector resultIndex(programs.size(), 0); - const bool heapCheck = !drawHit && Graphics::DescriptorHeapEnabled(); const DrawStageContext stageContext{queue, submission, packetOffset, trace.token, programs, graphics, pixel, vertexInfos, memory, linked, localDevice, *shaderMemory, stageCaptures, recompiled, drawHit, matched, matchedRegions, profile, dumpTarget, dumpSlot1, captures, phaseTiming, phaseMs, meshBarycentrics}; const bool heapMode = Graphics::DescriptorHeapEnabled(); + const bool heapCheck = !drawHit && heapMode; const bool heapDraw = heapMode && [&] { + const bool descriptorMemory = localDevice->Target().descriptorMemory; std::uint32_t cursor = pushCursorBytes; for (std::size_t i = 0; i < programs.size(); ++i) { if (roles[i] == Role::GeometryBack) continue; const auto stage = programs[i].binary.stage; require(stage == Stage::Fragment || HeapPreRasterStage(stage), "a draw stage kind the GPU heap does not take"); - require(stage == Stage::Fragment || localDevice->Target().descriptorMemory, "a GPU heap draw on a device target without descriptor memory"); + require(stage == Stage::Fragment || descriptorMemory, "a GPU heap draw on a device target without descriptor memory"); cursor = Graphics::StagePushOffset(cursor, stage, localDevice->GraphicsPipelineLibraries()); if (HeapStageExcluded(stage) || (HeapClassesExcluded() && drawStageExcluded(stageContext, i, cursor, drawParameters))) return false; } @@ -1112,9 +1054,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { pushCursorBytes = Graphics::StagePushOffset(pushCursorBytes, program.binary.stage, localDevice->GraphicsPipelineLibraries()); pushOffsets[i] = pushCursorBytes; if (drawHit) { - programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); - memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); - ringWords(i); + adoptMatched(i); } else { if (reused[i] && !fitsDraw(*matched[i]->compiled)) { reused[i] = false; @@ -1123,17 +1063,13 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { } const auto candidate = reused[i] ? dataCandidates[i].end() : candidateForStage(i); if (reused[i]) { - programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); - memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); - ringWords(i); + adoptMatched(i); } else if (candidate != dataCandidates[i].end() && !verifyDrawDataHits()) { matched[i] = candidate->first; stageCaptures[i].registeredViews = matched[i]->registeredViews; matchedRegions[i] = std::move(candidate->second); reused[i] = true; - programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get(); - memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end()); - ringWords(i); + adoptMatched(i); } else { if (!dataCandidates[i].empty() && !verifyDrawDataHits()) decodeVertexInfo(i); if (program.binary.stage == ShaderRecompiler::ShaderStage::Fragment) { @@ -1144,7 +1080,6 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { } } compiledStages.push_back(materializeDrawStage(stageContext, i, pushCursorBytes, drawParameters, heapDraw)); - if (!rejected.empty()) return DrawVerdict::Rejected; programResults[i] = compiledStages.back().get(); if (verifyHit && matched[i] != nullptr && matched[i]->ringTemplate != nullptr) VerifyRingWords(*matched[i]->compiled, *buildRingWords(i, *matched[i]), *programResults[i], stageCaptures[i].heapWords.get()); if (candidate != dataCandidates[i].end()) verifyDataStage(i, *candidate->first); @@ -1272,7 +1207,6 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { const auto pushBytes = programResults[0]->pushConstants.size(); const auto exports = programResults[0]->parameterExports; compiledStages.push_back(materializeDrawStage(stageContext, 0, pushOffsets[0], drawParameters, heapDraw)); - if (!rejected.empty()) return DrawVerdict::Rejected; require(fitsDraw(*compiledStages.back()), "a rebuilt mesh stage left the GPU heap mode of its draw"); programResults[0] = compiledStages.back().get(); stages[0].program = programResults[0]; @@ -1453,14 +1387,12 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { if (!verifyPushWord) continue; const auto fresh = materializeDrawStage(stageContext, programIndex, pushOffsets[programIndex], drawParameters, heapDraw); for (auto& stage : stages) if (stage.program == &result) stage.registeredImageViews = stageCaptures[programIndex].registeredViews.get(); - if (!rejected.empty()) return DrawVerdict::Rejected; verifyForwardedWords(programIndex, result, *fresh); continue; } if (pushWord) wordsRefused += static_cast(std::count_if(recordWords.begin(), recordWords.end(), [&](const RecordWord& word) { return word.program == programIndex; })); result = *materializeDrawStage(stageContext, programIndex, pushOffsets[programIndex], programs[programIndex].binary.stage == Stage::TessellationControl || programs[programIndex].binary.stage == Stage::TessellationEvaluation ? direct : drawParameters, heapDraw); for (auto& stage : stages) if (stage.program == &result) stage.registeredImageViews = stageCaptures[programIndex].registeredViews.get(); - if (!rejected.empty()) return DrawVerdict::Rejected; require(result.pushConstants.size() == pushBytes, "patched program changed its push constant layout"); require(fitsDraw(result), "a patched program left the GPU heap mode of its draw"); for (auto& stage : stages) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp index cc58f0fe4d3f..9c8e6e5eab23 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp @@ -24,17 +24,17 @@ bool DrawRecipeRecord::Expired() const { } bool Driver::drawEntries() { - static const bool entries = std::getenv("APS5_NO_DRAW_SRT_ENTRIES") == nullptr && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::DrawSrtEntries) && !stampValidate(); + static const bool entries = ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::DrawSrtEntries) && !stampValidate(); return entries; } bool Driver::drawDataHits() { - static const bool hits = std::getenv("APS5_NO_DRAW_DATA_HITS") == nullptr && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::DrawDataHits); + static const bool hits = ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::DrawDataHits); return hits; } bool Driver::drawStageDataHits() { - static const bool hits = std::getenv("APS5_NO_DRAW_STAGE_DATA_HITS") == nullptr && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::DrawStageDataHits) && !stampValidate(); + static const bool hits = ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::DrawStageDataHits) && !stampValidate(); return hits; } @@ -49,7 +49,7 @@ bool Driver::verifyDrawEntries() { } bool Driver::registerKeyEnabled() { - static const bool registerKey = std::getenv("APS5_NO_DRAW_KEY") == nullptr && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::DrawKey); + static const bool registerKey = ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::DrawKey); return registerKey; } @@ -165,16 +165,26 @@ bool Driver::drawEntriesThisDraw() { return backoff.use(drawCacheUseful().load(std::memory_order_relaxed)); } +DrawKeySightings& Driver::drawKeySightingsTable() { + if (!drawKeySightings) drawKeySightings.emplace(drawCacheEntries() * DrawKeySightings::Ways); + return *drawKeySightings; +} + +DrawKeySightings& Driver::drawShapeSightingsTable() { + if (!drawShapeSightings) drawShapeSightings.emplace(drawCacheEntries() * DrawKeySightings::Ways); + return *drawShapeSightings; +} + bool Driver::admitDrawKey(std::uint64_t key, std::uint64_t shape) { std::lock_guard cacheLock(drawCacheMutex); if (drawCache.contains(key)) return true; - if (!drawKeySightings) drawKeySightings.emplace(drawCacheEntries() * DrawKeySightings::Ways); - bool seen = drawKeySightings->SeenBefore(key); + auto& keySightings = drawKeySightingsTable(); + bool seen = keySightings.SeenBefore(key); const auto& pending = drawRelocationPending; if (pending.key == key && pending.identity != 0) { if (pending.alias != 0) { const auto trial = drawRelocationTrials.find(pending.identity); - if (drawKeySightings->SeenBefore(pending.alias ^ 0x9e3779b97f4a7c15ull) && trial != drawRelocationTrials.end()) { + if (keySightings.SeenBefore(pending.alias ^ 0x9e3779b97f4a7c15ull) && trial != drawRelocationTrials.end()) { auto& state = trial->second; if (state.productive || state.hits != 0 || state.admissions < DrawRelocationTrial::ProbationAdmissions) { if (!state.productive && state.hits == 0) ++state.admissions; @@ -182,12 +192,11 @@ bool Driver::admitDrawKey(std::uint64_t key, std::uint64_t shape) { } } } else if (!drawRelocations.contains(pending.identity)) { - if (drawKeySightings->SeenBefore(pending.identity ^ 0xc2b2ae3d27d4eb4full)) seen = true; + if (keySightings.SeenBefore(pending.identity ^ 0xc2b2ae3d27d4eb4full)) seen = true; } } if (seen || shape == 0 || drawShapes.contains(shape)) return seen; - if (!drawShapeSightings) drawShapeSightings.emplace(drawCacheEntries() * DrawKeySightings::Ways); - return drawShapeSightings->SeenBefore(shape); + return drawShapeSightingsTable().SeenBefore(shape); } void Driver::insertDrawEntry(std::uint64_t key, std::vector>& fresh, std::shared_ptr decode, std::uint64_t shape, bool replaceShape) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index fc19ab7e8b4b..4fe21f769e3b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -30,7 +30,7 @@ namespace AgcDriver::DriverDetail { const ShaderRecompiler::SrtUserDataUse& StageCapture::UserDataUse() const { static const ShaderRecompiler::SrtUserDataUse none; - return userDataOwner != nullptr ? userDataOwner->userDataUse : none; + return capture != nullptr ? capture->userDataUse : none; } @@ -108,7 +108,7 @@ bool Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t RequireHeapStageMappable(*materialized.result); NoteHeapDirect(); stageCapture.compiled = std::move(materialized.result); - stageCapture.heapWords = stageCapture.compiled->heapTemplateId != 0 ? std::const_pointer_cast(std::move(materialized.words)) : nullptr; + stageCapture.heapWords = stageCapture.compiled->heapTemplateId != 0 ? std::move(materialized.words) : nullptr; if (SampleHeapStageVerify()) { const auto fullCapture = context.shaderMemory.Capture(invocation); const auto expected = invocation.Materialize(*fullCapture); @@ -116,7 +116,7 @@ bool Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t NoteHeapDirectVerify(stageCapture.heapWords != nullptr ? *PatchedHeapResult(*stageCapture.compiled, *stageCapture.heapWords) : *stageCapture.compiled, *expected, fullCapture.get()); } stageCapture.regions.clear(); - stageCapture.direct = true; + stageCapture.origin = StageOrigin::HeapUnread; auto& reads = materialized.reads; if (reads.complete) { auto owned = std::move(reads.values); @@ -129,9 +129,8 @@ bool Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t stageCapture.heapReadWords = std::move(owned); const auto& use = reads.capture->userDataUse; stageCapture.userDataMask = UserDataMask(program, context.vertexInfos[i], use.asValue | use.asBase, *stageCapture.compiled); - stageCapture.userDataOwner = reads.capture; stageCapture.capture = std::move(reads.capture); - stageCapture.ring = true; + stageCapture.origin = StageOrigin::HeapRead; context.memory.insert(context.memory.end(), stageCapture.regions.begin(), stageCapture.regions.end()); } context.recompiled[i] = true; @@ -179,9 +178,7 @@ bool Driver::drawStageExcluded(const DrawStageContext& context, std::size_t i, s auto request = drawStageRequest(context, i, pushOffset, drawParameters); request.target.gpuResolvedImages = true; const auto invocation = InvocationFor(*program.snapshot, program.codeOffset, request); - const auto plan = invocation.Plan() == nullptr ? invocation.LoadPlan() : invocation.Plan(); - if (plan == nullptr) throw std::runtime_error("AGC graphics: a GPU heap stage has no resource plan to apply APS5_GPU_HEAP_EXCLUDE to"); - return HeapPlanExcluded(*plan); + return HeapExcludedFor(invocation); } std::shared_ptr Driver::materializeDrawStage(const DrawStageContext& context, std::size_t i, std::uint32_t pushOffset, const Pm4::DrawParameters& drawParameters, bool heapDraw) try { @@ -205,15 +202,14 @@ std::shared_ptr Driver::materializeDraw using StageReason = Graphics::HeapStageReason; const StageReason stageReason = heapDraw ? StageReason::Heap : !Graphics::DescriptorHeapEnabled() ? StageReason::Disabled : StageReason::Excluded; if (heapDraw) { - const auto plan = invocation.Plan() == nullptr ? invocation.LoadPlan() : invocation.Plan(); + const auto plan = invocation.PlanOrLoad(); if (const auto* ineligible = HeapStageIneligibility(program.binary.stage, plan.get())) throw std::runtime_error(std::string("AGC graphics: a GPU heap stage cannot take the heap: ") + ineligible); } Graphics::NoteHeapStageReason(stageReason); timing.Mark("prepared_invocation"); auto& stageCapture = context.stageCaptures[i]; - stageCapture.direct = false; - stageCapture.ring = false; + stageCapture.origin = StageOrigin::Captured; stageCapture.heapReadWords.reset(); stageCapture.capture.reset(); stageCapture.forgetSerial = GuestMemory::ForgetSerial(); @@ -234,14 +230,13 @@ std::shared_ptr Driver::materializeDraw stageCapture.regions = context.shaderMemory.TakeRecentRegions(); stageCapture.supplied = context.shaderMemory.SuppliedBlocks(); - stageCapture.userDataOwner = capture; stageCapture.registeredViews = std::make_shared>(capture->snapshot.registeredImages); context.recompiled[i] = true; context.memory = context.shaderMemory.Regions(); for (std::size_t j = 0; j < context.programs.size(); ++j) { if (context.matched[j] != nullptr && !context.recompiled[j] && (context.drawHit || j < i)) context.memory.insert(context.memory.end(), context.matchedRegions[j].begin(), context.matchedRegions[j].end()); - if (j < i && context.recompiled[j] && context.stageCaptures[j].direct) context.memory.insert(context.memory.end(), context.stageCaptures[j].regions.begin(), context.stageCaptures[j].regions.end()); + if (j < i && context.recompiled[j] && context.stageCaptures[j].Direct()) context.memory.insert(context.memory.end(), context.stageCaptures[j].regions.begin(), context.stageCaptures[j].regions.end()); } request.context.memory = context.memory; if (dumpGraphics) static_cast(dumpRequest(program.binary.codeAddress, request)); @@ -283,8 +278,7 @@ std::shared_ptr Driver::materializeDraw words->dataOrigin = NextHeapDataOrigin(); stageCapture.compiled = std::move(shared); stageCapture.heapWords = std::move(words); - stageCapture.direct = true; - stageCapture.ring = true; + stageCapture.origin = StageOrigin::HeapRead; if (SampleHeapStageVerify()) NoteHeapDirectVerify(*PatchedHeapResult(*stageCapture.compiled, *stageCapture.heapWords), *invocation.Materialize(*capture)); } } @@ -365,7 +359,7 @@ void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawP variant->forgetSerial = stageCapture.forgetSerial; variant->pushOffset = stageCapture.pushOffset; variant->userDataMask = stageCapture.userDataMask; - if (stageCapture.ring && stageCapture.heapWords != nullptr) { + if (stageCapture.origin == StageOrigin::HeapRead && stageCapture.heapWords != nullptr) { auto ringTemplate = std::make_shared(); ringTemplate->vertexAttributes = stageCapture.heapWords->vertexAttributes; ringTemplate->flattenedSrt = stageCapture.heapWords->flattenedSrt; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp index 50dbbfd32ed1..5eb4742a4359 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp @@ -182,6 +182,15 @@ void DrawFinisher::Enqueue(Job job) { Enqueue(std::move(job), Pending{}); } +void DrawFinisher::EnqueueBeside(Job job, std::vector writes, std::uint64_t labelAddress, std::vector labelBytes) { + Pending held; + held.unknown = false; + held.writes = std::move(writes); + held.labelAddress = labelAddress; + held.labelBytes = std::move(labelBytes); + Enqueue(std::move(job), std::move(held)); +} + void DrawFinisher::Enqueue(Job job, Pending held) { finisherProducer = true; constexpr std::size_t depth = 16; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 9a3c4bf3cd13..abc57cbd9e18 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -1,6 +1,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "HeapCacheSwitch.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -29,7 +30,6 @@ namespace AgcDriver::DriverDetail { namespace { -constexpr std::size_t ThreadCacheLimit = 65536u; constexpr std::uint64_t WalkPageBytes = 0x1000u; constexpr std::uint64_t WordBytes = sizeof(std::uint32_t); @@ -217,46 +217,34 @@ std::string heapStageFailure(const ShaderRecompiler::RecompileResult& result, bo return {}; } -const std::string& knownHeapStageFailure(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { - struct MappableStorage {}; - struct RecentStorage {}; - struct Recent { - std::uint64_t key = 0; - const std::string* failure = nullptr; - }; - constexpr std::size_t RecentSlots = 64; - auto& known = HostThreadLocal, MappableStorage>(); - auto& recent = HostThreadLocal, RecentStorage>(); - const auto key = result.variantId * 2u + (workgroupAddress ? 1u : 0u); - auto& slot = recent[(key ^ (key >> 17u)) % RecentSlots]; - if (slot.failure != nullptr && slot.key == key) return *slot.failure; - auto found = known.find(key); - if (found == known.end()) { - if (known.size() >= ThreadCacheLimit) { - known.clear(); - recent.fill({}); - } - found = known.emplace(key, heapStageFailure(result, workgroupAddress)).first; - } - slot = {key, &found->second}; - return found->second; +bool knownHeapStageFits(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { + constexpr std::uint64_t Fits = 2, Fails = 1, VerdictBits = 2; + auto& memo = result.heapMappableMemo.verdicts[workgroupAddress ? 1 : 0]; + const auto capacity = Graphics::BindlessHeap::ImageSlotCapacity(); + const auto known = memo.load(std::memory_order_relaxed); + if (known != 0 && known >> VerdictBits == capacity) return (known & 3u) == Fits; + const bool fits = heapStageFailure(result, workgroupAddress).empty(); + memo.store(static_cast(capacity) << VerdictBits | (fits ? Fits : Fails), std::memory_order_relaxed); + return fits; } } void RequireHeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { - if (const auto& failure = knownHeapStageFailure(result, workgroupAddress); !failure.empty()) throw std::runtime_error(failure); + if (!knownHeapStageFits(result, workgroupAddress)) throw std::runtime_error(heapStageFailure(result, workgroupAddress)); } bool HeapStageFits(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { - return knownHeapStageFailure(result, workgroupAddress).empty(); + return knownHeapStageFits(result, workgroupAddress); } bool HeapStageExcluded(ShaderRecompiler::ShaderStage stage) { return (heapExclusions().stages >> static_cast(stage) & 1u) != 0u; } -bool HeapPlanExcluded(const ShaderRecompiler::IrResourcePlan& plan) { +namespace { + +bool heapPlanExcluded(const ShaderRecompiler::IrResourcePlan& plan) { using Class = ShaderRecompiler::ImageResourceClass; const auto& exclusions = heapExclusions(); if (exclusions.tables && std::ranges::any_of(plan.descriptorSources, [](const ShaderRecompiler::DescriptorSource& source) { return source.tableColumn.has_value(); })) @@ -268,6 +256,14 @@ bool HeapPlanExcluded(const ShaderRecompiler::IrResourcePlan& plan) { return std::ranges::any_of(plan.info.runtimeImageModes, [&](const std::vector& modes) { return std::ranges::any_of(modes, excludedImage); }); } +} + +bool HeapExcludedFor(const ShaderRecompiler::PreparedShaderInvocation& invocation) { + const auto plan = invocation.PlanOrLoad(); + if (plan == nullptr) throw std::runtime_error("AGC graphics: a GPU heap stage has no resource plan to apply APS5_GPU_HEAP_EXCLUDE to"); + return heapPlanExcluded(*plan); +} + bool HeapClassesExcluded() { const auto& exclusions = heapExclusions(); return exclusions.tables || exclusions.storage || exclusions.sampled; @@ -506,8 +502,7 @@ std::shared_ptr PatchedHeapResult(const if (binding.role == ShaderRecompiler::DescriptorRole::FlattenedSrt && !words.flattenedSrt.empty()) binding.guestDescriptor = words.flattenedSrt; if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) - std::copy_n(words.userData.begin(), std::min(words.userData.size(), binding.guestDescriptor.size()), - binding.guestDescriptor.begin()); + ShaderRecompiler::OverlayUserWords(binding.guestDescriptor, words.userData); } if (words.base != nullptr && !words.base->bindings.empty()) { if (words.base->bindings.size() != result->bindings.size()) @@ -535,6 +530,69 @@ std::shared_ptr PatchedHeapResult(const return result; } +void BuildRingWords(const DispatchVariant& variant, std::span user, const std::vector* refreshedData, ShaderRecompiler::HeapStageWords& words) { + for (const auto index : variant.compiled->heapUserWords) { + if (index >= user.size()) throw std::runtime_error("a ring vertex template reads a user word the draw does not have"); + words.userData.push_back(user[index]); + } + const auto& ringTemplate = *variant.ringTemplate; + words.vertexAttributes = ringTemplate.vertexAttributes; + words.flattenedSrt.clear(); + for (auto& descriptor : words.bindings) descriptor.clear(); + words.base = nullptr; + words.dataOrigin = ringTemplate.dataOrigin; + if (!ringTemplate.flattenedSrt.empty()) { + words.flattenedSrt = ringTemplate.flattenedSrt; + if (refreshedData != nullptr) { + for (std::size_t k = 0; k < variant.dataPositions.size(); ++k) { + if (variant.dataSlots[k] < words.flattenedSrt.size()) words.flattenedSrt[variant.dataSlots[k]] = (*refreshedData)[variant.dataPositions[k]]; + } + } + } + if (!ringTemplate.bindings.empty()) { + const auto& program = variant.compiled->bindings; + if (ringTemplate.bindings.size() != program.size()) throw std::runtime_error("a ring vertex hit's bindings differ in number from its template"); + words.base = variant.ringTemplate; + words.bindings.resize(program.size()); + for (std::size_t index = 0; index < program.size(); ++index) { + const auto& shared = ringTemplate.bindings[index]; + if (program[index].role != ShaderRecompiler::DescriptorRole::ShaderData || shared.empty()) continue; + auto& descriptor = words.bindings[index]; + descriptor.assign(shared.begin(), shared.end()); + ShaderRecompiler::OverlayUserWords(descriptor, words.userData); + if (descriptor == program[index].guestDescriptor) descriptor.clear(); + } + } else { + words.bindings.clear(); + } + ShaderRecompiler::CompleteHeapDataWords(*variant.compiled, words); + if (variant.ringDescriptorPatches.empty() && variant.ringDataPatches.empty()) return; + const auto& program = variant.compiled->bindings; + if (words.bindings.empty()) words.bindings.resize(program.size()); + const auto own = [&](std::size_t index) -> std::vector& { + auto& descriptor = words.bindings[index]; + if (descriptor.empty()) { + const auto& source = Graphics::DrawGuestWords(*variant.compiled, &words, program[index]); + descriptor.assign(source.begin(), source.end()); + } + return descriptor; + }; + for (const auto& [binding, word, value] : variant.ringDescriptorPatches) { + if (binding >= program.size() || word >= program[binding].guestDescriptor.size()) continue; + if (program[binding].role == ShaderRecompiler::DescriptorRole::ShaderData && word >= words.userData.size()) words.dataOrigin = 0; + auto& descriptor = own(binding); + if (word < descriptor.size()) descriptor[word] = value; + } + for (const auto& [slot, value] : variant.ringDataPatches) { + if (slot >= words.userData.size()) words.dataOrigin = 0; + for (std::size_t index = 0; index < program.size(); ++index) { + if (program[index].role != ShaderRecompiler::DescriptorRole::ShaderData || slot >= program[index].guestDescriptor.size()) continue; + auto& descriptor = own(index); + if (slot < descriptor.size()) descriptor[slot] = value; + } + } +} + void NoteHeapDirect() { heapStages().fetch_add(1, std::memory_order_relaxed); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp index 7687fd7c6434..76c276f4c684 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp @@ -305,11 +305,12 @@ void Driver::execute(Submission& submission) { auto nextCursor = cursor + count; const bool predicated = Pm4::Predicated(header) && queue.predication.operation != 0; if (submission.queue == 0 && DrawFinisher::Busy() && !keepsDrawFinisher(header, opcode)) { - const bool queuesLabel = pipelined && !predicated && header != FlipPacketHeader && header != RenderingWaitPacketHeader && !submission.flips.contains(cursor) && labelPacketQueues(packet, opcode); + const bool queueable = pipelined && !predicated && header != FlipPacketHeader && header != RenderingWaitPacketHeader && !submission.flips.contains(cursor); + const bool queuesLabel = queueable && labelPacketQueues(packet, opcode); const bool heldLabelWait = pipelined && !predicated && orderedWaits && (opcode == 0x3c || opcode == 0x93) && header != RenderingWaitPacketHeader && waitTakesPendingLabel(packet); - const bool queuesSampleDump = pipelined && !predicated && header != FlipPacketHeader && header != RenderingWaitPacketHeader && !submission.flips.contains(cursor) && sampleDumpQueues(packet, opcode, submission.queue); + const bool queuesSampleDump = queueable && sampleDumpQueues(packet, opcode, submission.queue); const bool queuesDispatch = opcode == 0x15 && pipelined && pipelineDispatch() && !predicated; - const bool beside = DrawFinisher::Overlap() && (opcode != 0x15 || queuesDispatch) && (queuesLabel || heldLabelWait || queuesSampleDump || queuesDispatch || keepsDrawPipeline(packet, header, opcode)); + const bool beside = DrawFinisher::Overlap() && (queuesDispatch || (opcode != 0x15 && (queuesLabel || heldLabelWait || queuesSampleDump || keepsDrawPipeline(packet, header, opcode)))); if (!beside) DrawFinisher::Get().Drain(); if (DrawFinisher::Overlap()) { DrawFinisher::NoteDrain(DrawFinisher::DrainSite::Packet, !beside); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp index 7c0b8db734e8..4086c85b2277 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp @@ -367,10 +367,7 @@ bool Driver::enqueueSampleDumpPacket(std::span packet, std: }, {{address, address + Pm4::SampleDumpBytes}}); }; if (DrawFinisher::Overlap() && DrawFinisher::Busy() && !DrawFinisher::OnFinisherThread()) { - DrawFinisher::Pending held; - held.unknown = false; - held.writes = {{address, address + Pm4::SampleDumpBytes}}; - DrawFinisher::Get().Enqueue(std::move(enqueue), std::move(held)); + DrawFinisher::Get().EnqueueBeside(std::move(enqueue), {{address, address + Pm4::SampleDumpBytes}}); } else { enqueue(); } @@ -539,12 +536,7 @@ bool Driver::enqueueLabelPacket(std::span packet, std::uint }, std::move(writes), address, std::move(stored)); }; if (queue == 0 && DrawFinisher::Overlap() && DrawFinisher::Busy()) { - DrawFinisher::Pending held; - held.unknown = false; - held.writes = std::move(writes); - held.labelAddress = address; - held.labelBytes = std::move(labelBytes); - DrawFinisher::Get().Enqueue(std::move(enqueue), std::move(held)); + DrawFinisher::Get().EnqueueBeside(std::move(enqueue), std::move(writes), address, std::move(labelBytes)); return true; } enqueue(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp index e25bd09b601c..a359f0292f1b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp @@ -2822,10 +2822,6 @@ std::uint64_t StableTrackerGeneration() { return Tracker().stable.load(std::memory_order_acquire); } -std::uint64_t TrackerAcquisitions() { - return trackerAcquisitions.load(std::memory_order_relaxed); -} - void AdvanceTrackerGenerationForTest(std::uint64_t generation) { auto& tracker = Tracker(); const auto lock = lockTracker(tracker); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp index b78d13032585..b6a6d80bfadd 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationPass.cpp @@ -276,29 +276,10 @@ const PresentationPass::Target& PresentationPass::target(VkFormat format, VkImag pipelineInfo.renderPass = created.renderPass; Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.pipeline), "vkCreateGraphicsPipelines presentation pass"); if (heap) { - const auto& bindless = Graphics::BindlessHeap::For(context); - std::array mappings{{{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}, {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}}}; - mappings[0].firstBinding = 0; - mappings[0].bindingCount = 1; - mappings[0].resourceMask = VK_SPIRV_RESOURCE_TYPE_COMBINED_SAMPLED_IMAGE_BIT_EXT; - mappings[0].source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; - mappings[0].sourceData.pushIndex.pushOffset = offsetof(HeapPush, slot); - mappings[0].sourceData.pushIndex.heapIndexStride = static_cast(bindless.ImageHeapStride()); - mappings[0].sourceData.pushIndex.heapArrayStride = static_cast(bindless.ImageHeapStride()); - mappings[0].sourceData.pushIndex.pEmbeddedSampler = &samplerInfo; - mappings[1].firstBinding = 1; - mappings[1].bindingCount = 1; - mappings[1].resourceMask = VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT | VK_SPIRV_RESOURCE_TYPE_READ_ONLY_STORAGE_BUFFER_BIT_EXT; - mappings[1].source = VK_DESCRIPTOR_MAPPING_SOURCE_PUSH_ADDRESS_EXT; - mappings[1].sourceData.pushAddressOffset = offsetof(HeapPush, pqNits); - VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; - mappingInfo.mappingCount = static_cast(mappings.size()); - mappingInfo.pMappings = mappings.data(); - stages[1].pNext = &mappingInfo; - auto heapFlags = Graphics::DescriptorHeapFlags(); - pipelineInfo.pNext = &heapFlags; - pipelineInfo.layout = VK_NULL_HANDLE; - Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.heapPipeline), "vkCreateGraphicsPipelines presentation pass heap"); + const std::array mappings{ + Graphics::HeapPushSampledImageMapping(Graphics::BindlessHeap::For(context), 0, 0, offsetof(HeapPush, slot), samplerInfo), + Graphics::HeapPushAddressMapping(0, 1, offsetof(HeapPush, pqNits))}; + created.heapPipeline = Graphics::CreateHeapStagePipeline(context, pipelineInfo, 1, mappings, "vkCreateGraphicsPipelines presentation pass heap"); } } catch (...) { if (created.pipeline) context.Function("vkDestroyPipeline")(context.device, created.pipeline, nullptr); @@ -411,10 +392,9 @@ void PresentationPass::draw(VkCommandBuffer commands, Slot& slot, const Target& state.SetViewport(context, {0.0f, 0.0f, static_cast(extent.width), static_cast(extent.height), 0.0f, 1.0f}); state.SetScissor(context, scissor); if (heapSlot) { - Graphics::BindlessHeap::For(context).BindDescriptorHeaps(commands); HeapPush pushed{{}, 0u, pqNits->DeviceAddress(), *heapSlot, 0u}; std::copy(std::begin(parameters), std::end(parameters), pushed.parameters); - Graphics::CmdPushData(context, commands, sizeof(pushed), &pushed); + Graphics::CmdPushHeapData(context, commands, sizeof(pushed), &pushed); } else { Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &slot.set, Graphics::SetBindSite::Presentation); Graphics::CmdPushConstants(context, commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), parameters); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp index f2fe90ab1161..996374c02445 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp @@ -317,24 +317,8 @@ const PresentationUpscaler::Target& PresentationUpscaler::target(VkFormat format const auto lock = context.LockPipelineCacheForUse(); Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.pipeline), "vkCreateGraphicsPipelines presentation upscaler"); if (heap) { - const auto& bindless = Graphics::BindlessHeap::For(context); - VkDescriptorSetAndBindingMappingEXT mapping{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT}; - mapping.firstBinding = 0; - mapping.bindingCount = 1; - mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_COMBINED_SAMPLED_IMAGE_BIT_EXT; - mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; - mapping.sourceData.pushIndex.pushOffset = offsetof(HeapPush, slot); - mapping.sourceData.pushIndex.heapIndexStride = static_cast(bindless.ImageHeapStride()); - mapping.sourceData.pushIndex.heapArrayStride = static_cast(bindless.ImageHeapStride()); - mapping.sourceData.pushIndex.pEmbeddedSampler = &samplerInfo; - VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; - mappingInfo.mappingCount = 1; - mappingInfo.pMappings = &mapping; - stages[1].pNext = &mappingInfo; - auto heapFlags = Graphics::DescriptorHeapFlags(); - pipelineInfo.pNext = &heapFlags; - pipelineInfo.layout = VK_NULL_HANDLE; - Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.heapPipeline), "vkCreateGraphicsPipelines presentation upscaler heap"); + const auto mapping = Graphics::HeapPushSampledImageMapping(Graphics::BindlessHeap::For(context), 0, 0, offsetof(HeapPush, slot), samplerInfo); + created.heapPipeline = Graphics::CreateHeapStagePipeline(context, pipelineInfo, 1, std::span(&mapping, 1), "vkCreateGraphicsPipelines presentation upscaler heap"); } } catch (...) { if (created.pipeline) context.Function("vkDestroyPipeline")(context.device, created.pipeline, nullptr); @@ -390,11 +374,10 @@ void PresentationUpscaler::draw(VkCommandBuffer commands, Slot& slot, const Targ recording.SetViewport(context, viewport); recording.SetScissor(context, scissor); if (heapSlot) { - Graphics::BindlessHeap::For(context).BindDescriptorHeaps(commands); HeapPush pushed{}; std::memcpy(pushed.parameters, parameters, size); pushed.slot = *heapSlot; - Graphics::CmdPushData(context, commands, sizeof(pushed), &pushed); + Graphics::CmdPushHeapData(context, commands, sizeof(pushed), &pushed); } else { bindSource(set, source); Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, Graphics::SetBindSite::Presentation); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 42329a10c9a1..82d7fdd6014f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -2333,18 +2333,18 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : VkPhysicalDeviceMaintenance5FeaturesKHR heapMaintenance5{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR, &descriptorHeapFeatures}; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &heapMaintenance5}; state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &features); - if (descriptorHeapFeatures.descriptorHeap == VK_TRUE && heapMaintenance5.maintenance5 == VK_TRUE) { + const bool heapSupported = descriptorHeapFeatures.descriptorHeap == VK_TRUE && heapMaintenance5.maintenance5 == VK_TRUE; + if (heapSupported) { VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &state->descriptorHeapProperties}; state->InstanceFunction("vkGetPhysicalDeviceProperties2")(selected, &properties); } - if (descriptorHeapFeatures.descriptorHeap == VK_TRUE && heapMaintenance5.maintenance5 == VK_TRUE && Graphics::BindlessHeap::Fits(state->descriptorHeapProperties)) { + if (heapSupported && Graphics::BindlessHeap::Fits(state->descriptorHeapProperties)) { state->descriptorHeap = true; state->maintenance5 = true; state->heapDataUniformDwords = std::min(HeapDataUniformDwordCap, state->properties.limits.maxUniformBufferRange / 4u); if (hasExtension(VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 layoutFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &standardLayout}; state->InstanceFunction("vkGetPhysicalDeviceFeatures2")(selected, &layoutFeatures); - standardLayout.pNext = nullptr; } state->uniformConstantBuffers = Graphics::ChooseUniformConstantBuffers(standardLayout.uniformBufferStandardLayout == VK_TRUE, state->properties.limits); if (state->uniformConstantBuffers) deviceExtensions.push_back(VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME); @@ -5122,7 +5122,7 @@ namespace { // which needs the texture caches: without them every lookup makes a fresh object, so a hit could // never validate and would only upload everything twice. bool ResourceCacheEnabled() { - static const bool noResourceCache = std::getenv("APS5_NO_RESOURCE_CACHE") != nullptr || ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::ResourceCache); + static const bool noResourceCache = !ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::ResourceCache); static const bool noTextureCache = std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr; return !noResourceCache && !noTextureCache; } @@ -6135,11 +6135,10 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { VkDeviceAddress workgroupAddress = 0; if (const auto dwords = record.shader->program->workgroupMemoryDwords; dwords != 0) { auto memory = state->WorkgroupMemoryFor(context, record.x, record.y, record.z, dwords); - const auto workgroupSet = record.shader->program->gpuResolvedImages ? ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet : ShaderRecompiler::WorkgroupMemoryDescriptorSet; if (record.objects->descriptorHeap) { workgroupAddress = memory->address; } else { - Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, workgroupSet, 1, &memory->set, Graphics::SetBindSite::Dispatch); + Graphics::CmdBindDescriptorSets(context, commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, ShaderRecompiler::WorkgroupMemoryDescriptorSet, 1, &memory->set, Graphics::SetBindSite::Dispatch); } recorder.Keep(std::move(memory)); } @@ -6311,6 +6310,7 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons objects->module = Graphics::CreateShaderModule(state->DeviceFunction("vkCreateShaderModule"), state->device, state->graphicsPipelineLibrary, shader.spirv.data(), shader.spirv.size() * sizeof(std::uint32_t), "vkCreateShaderModule"); objects->resourcesLayout = setLayout; const bool gpuMode = shader.gpuResolvedImages; + const bool heapDevice = gpuMode && context.descriptorHeap && Graphics::DescriptorHeapEnabled(); const bool scratchPool = shader.scratchPoolSlotDwords != 0; const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, Graphics::ComputePushConstantBytes}; if (!gpuMode) { @@ -6327,7 +6327,7 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons objects->pushPlacements = Graphics::PushDataPlacements(std::span(&placed, 1)); Graphics::PipelineSpecialization specialization(shader); specialization.PlacePushData(objects->pushPlacements.front()); - if (gpuMode && context.descriptorHeap && Graphics::DescriptorHeapEnabled()) specialization.PlaceHeapImageSlots(Graphics::BindlessHeap::For(context).ImageSlots()); + if (heapDevice) specialization.PlaceHeapImageSlots(Graphics::BindlessHeap::For(context).ImageSlots()); const auto subgroupSize = computeSubgroupSize(shader); const auto stageFlags = computeStageFlags(shader); if (const auto* directory = ComputePipelineDumpDirectory(); directory != nullptr && *directory != 0 && !state->probingFloatControls && ComputePipelineCapture::OptionalEnabled() && CaptureComputePipeline(shader.spirv.size())) { @@ -6360,7 +6360,6 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons if (profile && shader.spirv.size() > 100000) std::fprintf(stderr, "[dispatch] creating a pipeline for %zu SPIR-V words (program 0x%llx)\n", shader.spirv.size(), static_cast(programAddress)); std::vector heapMappings; const bool workgroupAddress = shader.workgroupMemoryDwords != 0; - const bool heapDevice = gpuMode && context.descriptorHeap && Graphics::DescriptorHeapEnabled(); const auto workgroupAddressOffset = workgroupAddress ? Graphics::ComputePushConstantBytes : ~0u; const std::span spirv(shader.spirv.data(), shader.spirv.size()); objects->descriptorHeap = heapDevice && Graphics::BindlessHeap::For(context).DescriptorHeapMappings(spirv, heapMappings, {.workgroupAddress = workgroupAddress, .gdsAddress = shader.dataAddressPush, .scratchPool = scratchPool}, &objects->pushPlacements.front(), &shader.bindings, workgroupAddressOffset); @@ -6813,9 +6812,9 @@ VulkanDevice::IndirectOutcome VulkanDevice::recordCompletedDispatch(const Shader // writes, every direct region import- or mirror-served), so a hit's proof is the template's // Revalidate and nothing needs completion work. const bool recipeWanted = recipeOut != nullptr && DispatchRecipes(); - if (recipeWanted && profile && !(cacheable && overlay == nullptr && resources->Reusable() && !resources->NeedsCompletion() && objects != nullptr && !contentKey.empty())) - noteRecipeRefusal(cacheable, overlay != nullptr, objects != nullptr, !contentKey.empty(), *resources); - if (recipeWanted && cacheable && overlay == nullptr && resources->Reusable() && !resources->NeedsCompletion() && objects != nullptr && !contentKey.empty()) { + const bool recipeable = recipeWanted && cacheable && overlay == nullptr && resources->Reusable() && !resources->NeedsCompletion() && objects != nullptr && !contentKey.empty(); + if (recipeWanted && profile && !recipeable) noteRecipeRefusal(cacheable, overlay != nullptr, objects != nullptr, !contentKey.empty(), *resources); + if (recipeable) { auto recipe = std::make_shared(); recipe->device = state->device; recipe->templateRef = resources; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 41a459b3f274..310e1578927c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -359,9 +359,12 @@ bool HeapPassesActive(const Context& context); VkDescriptorSetAndBindingMappingEXT HeapPushAddressMapping(std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset, VkSpirvResourceTypeFlagsEXT resources = HeapPassStorageBuffers); VkDescriptorSetAndBindingMappingEXT HeapPushIndexMapping(const BindlessHeap& heap, std::uint32_t set, std::uint32_t binding, VkSpirvResourceTypeFlagsEXT resources, std::uint32_t pushOffset); +VkDescriptorSetAndBindingMappingEXT HeapPushSampledImageMapping(const BindlessHeap& heap, std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset, const VkSamplerCreateInfo& embeddedSampler); +VkPipeline CreateHeapStagePipeline(const Context& context, VkGraphicsPipelineCreateInfo info, std::uint32_t stage, std::span mappings, const char* what); VkPipeline CreateHeapComputePipeline(const Context& context, VkComputePipelineCreateInfo info, std::span mappings); VkPipeline CreateHeapGraphicsPipeline(const Context& context, VkGraphicsPipelineCreateInfo info, std::span mappings); void CmdPushData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values, std::uint32_t offset = 0); +void CmdPushHeapData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values); std::uint64_t NotePushDataWritten() noexcept; std::uint64_t PushDataMark() noexcept; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 6f58db7dbb04..006609cbc96c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -1443,6 +1443,29 @@ VkDescriptorSetAndBindingMappingEXT HeapPushIndexMapping(const BindlessHeap& hea return mapping; } +VkDescriptorSetAndBindingMappingEXT HeapPushSampledImageMapping(const BindlessHeap& heap, std::uint32_t set, std::uint32_t binding, std::uint32_t pushOffset, const VkSamplerCreateInfo& embeddedSampler) { + auto mapping = HeapPushIndexMapping(heap, set, binding, VK_SPIRV_RESOURCE_TYPE_COMBINED_SAMPLED_IMAGE_BIT_EXT, pushOffset); + mapping.sourceData.pushIndex.pEmbeddedSampler = &embeddedSampler; + return mapping; +} + +VkPipeline CreateHeapStagePipeline(const Context& context, VkGraphicsPipelineCreateInfo info, std::uint32_t stage, std::span mappings, const char* what) { + std::vector stages(info.pStages, info.pStages + info.stageCount); + VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; + mappingInfo.pNext = stages[stage].pNext; + mappingInfo.mappingCount = static_cast(mappings.size()); + mappingInfo.pMappings = mappings.data(); + stages[stage].pNext = &mappingInfo; + info.pStages = stages.data(); + auto heapFlags = DescriptorHeapFlags(); + heapFlags.pNext = info.pNext; + info.pNext = &heapFlags; + info.layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline), what); + return pipeline; +} + VkPipeline CreateHeapComputePipeline(const Context& context, VkComputePipelineCreateInfo info, std::span mappings) { if (!HeapPassesActive(context)) return VK_NULL_HANDLE; VkShaderDescriptorSetAndBindingMappingInfoEXT mappingInfo{VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT}; @@ -1511,6 +1534,11 @@ void CmdPushData(const Context& context, VkCommandBuffer commands, std::uint32_t static_cast(NotePushDataWritten()); } +void CmdPushHeapData(const Context& context, VkCommandBuffer commands, std::uint32_t bytes, const void* values) { + BindlessHeap::For(context).BindDescriptorHeaps(commands); + CmdPushData(context, commands, bytes, values); +} + void BindlessHeap::BindDescriptorHeaps(VkCommandBuffer commands) const { if (resourceHeap == nullptr) return; struct LastBound { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index f056c744d85c..9a7f5820f558 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1128,7 +1128,7 @@ void countCache(std::uint64_t DrawProfile::*counter) { // every draw. bool ValidationKey(const Context& context, std::span shaders, const State& state, std::vector& key) { using Stage = ShaderRecompiler::ShaderStage; - static const bool disabled = std::getenv("APS5_NO_VALIDATE_CACHE") != nullptr || ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::ValidateCache); + static const bool disabled = !ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::ValidateCache); const auto add = [&](auto value) { key.push_back(static_cast(value)); }; bool keyed = !disabled; if (keyed) { @@ -1313,7 +1313,7 @@ std::uint32_t CachedFragmentOutputs(const Context& context, std::spanPipelineVariantId() != 0; }); @@ -3390,7 +3390,7 @@ void keepHeldSpace(PreparedDraw& prepared) { } bool ShapeMemoEnabled() { - static const bool enabled = std::getenv("APS5_NO_SHAPE_MEMO") == nullptr && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::ShapeMemo); + static const bool enabled = ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::ShapeMemo); return enabled; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index cfd3d74a7514..865162f9c879 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -7937,7 +7937,7 @@ void ShaderResources::PatchDataAddresses(std::span reference; @@ -8122,7 +8122,7 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi if (table == tableStages.end() || table->mapAllocation == noElement) return; const bool verifyMap = ShaderRecompiler::HeapVerifyEnabled(); auto& stageState = heapStages[stageIndex]; - const bool mapCurrent = !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::TableMap) && stageState.mapBuilt && stageState.map.table.address != 0u && + const bool mapCurrent = ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::TableMap) && stageState.mapBuilt && stageState.map.table.address != 0u && HeapStageState::SlotSet::Current(heap, stageState.mapImages, stageState.mapSamplers); if (mapCurrent && !verifyMap) { stageState.mapTouched = HeapStageState::SlotSet::Touch(heap, stageState.mapImages, stageState.mapSamplers, stageState.mapTouched); @@ -8147,7 +8147,7 @@ void ShaderResources::writeHeapTableMap(const BindlessHeap::SpanScope& spans, Bi } std::uint64_t ShaderResources::heapSpan(const BindlessHeap::SpanScope& spans, BindlessHeap& heap, HeapStageState::KeptSpan& kept, std::span words) { - if (kept.table.address != 0u && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::StageData) && std::ranges::equal(kept.words, words)) { + if (kept.table.address != 0u && ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::StageData) && std::ranges::equal(kept.words, words)) { heap.NoteTableKept(spans); return kept.table.address; } @@ -8594,7 +8594,7 @@ bool ShaderResources::refreshHeapStageSlots(BindlessHeap& heap, HeapStageState& Require(stageState.laidOutFor == stageBit, "a GPU heap stage was refreshed for a stage its resources were not laid out for"); const auto& owned = stageState.owned; const bool keyed = stageState.keyTaken; - static const bool slotsBypassed = ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::Slots); + static const bool slotsBypassed = !ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::Slots); bool current = !slotsBypassed && (keyed && !verifySlots ? true : heapSlotKeySame(owned, stageState.key)); if (keyed && verifySlots && !slotsBypassed && !current) throw std::runtime_error("AGC graphics: a GPU heap stage's textures, views or samplers changed after its resources were built"); const auto slotSerial = heap.SlotSerial(); @@ -8627,7 +8627,7 @@ void ShaderResources::writeHeapDataBinding(const BindlessHeap::SpanScope& spans, shader.heap != nullptr ? std::span(shader.heap->userData) : std::span{}; const auto userFront = static_cast(std::min(userData.size(), words.size())); const auto origin = shaderData && shader.heap != nullptr ? shader.heap->dataOrigin : 0u; - const bool sameShape = shaderData && current && !ShaderRecompiler::HeapCacheBypassed(ShaderRecompiler::HeapCache::StageData) && stageState.dataInput.size() == words.size() + userData.size(); + const bool sameShape = shaderData && current && ShaderRecompiler::HeapCacheEnabled(ShaderRecompiler::HeapCache::StageData) && stageState.dataInput.size() == words.size() + userData.size(); const bool sameOrigin = sameShape && origin != 0u && origin == stageState.dataOrigin && stageState.dataProgram == shader.program; const bool sameWords = sameShape && (sameOrigin || std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)); if (verifySlots && sameOrigin && !std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)) diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index de63441c09ba..412e8c2dc9ae 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -254,7 +254,8 @@ function(add_shader_recompiler target runtimeTarget) endif() set(shaderCacheReviewedNames HeapCache - HeapCacheBypassed + HeapCacheEnabled + HeapCacheLegacyBypassed HeapCacheBypassMask HeapCacheNames HeapVerifyEnabled @@ -271,6 +272,7 @@ function(add_shader_recompiler target runtimeTarget) BuildBarycentricGeometryShader BuildBarycentricTessellationShaders CompleteHeapDataWords + OverlayUserWords HeapTemplateCounts BuildPreparedShaderKey BuildRectListShaders diff --git a/core/shader/recompiler/HeapCacheSwitch.hpp b/core/shader/recompiler/HeapCacheSwitch.hpp index d7550c7b5c69..2f3abeb14bd9 100644 --- a/core/shader/recompiler/HeapCacheSwitch.hpp +++ b/core/shader/recompiler/HeapCacheSwitch.hpp @@ -64,16 +64,37 @@ inline constexpr std::array(HeapCache return mask; } +[[nodiscard]] inline bool HeapCacheLegacyBypassed(HeapCache cache) { + switch (cache) { + case HeapCache::DrawKey: return std::getenv("APS5_NO_DRAW_KEY") != nullptr; + case HeapCache::DrawDataHits: return std::getenv("APS5_NO_DRAW_DATA_HITS") != nullptr; + case HeapCache::DrawStageDataHits: return std::getenv("APS5_NO_DRAW_STAGE_DATA_HITS") != nullptr; + case HeapCache::DrawSrtEntries: return std::getenv("APS5_NO_DRAW_SRT_ENTRIES") != nullptr; + case HeapCache::DrawRecipe: return std::getenv("APS5_NO_DRAW_RECIPE") != nullptr; + case HeapCache::DrawResourceCache: return std::getenv("APS5_NO_DRAW_RESOURCE_CACHE") != nullptr; + case HeapCache::ResourceCache: return std::getenv("APS5_NO_RESOURCE_CACHE") != nullptr; + case HeapCache::ValidateCache: return std::getenv("APS5_NO_VALIDATE_CACHE") != nullptr; + case HeapCache::ShapeMemo: return std::getenv("APS5_NO_SHAPE_MEMO") != nullptr; + case HeapCache::MovedBufferTemplates: return std::getenv("APS5_NO_MOVED_BUFFER_TEMPLATES") != nullptr; + case HeapCache::ResultMemo: return std::getenv("APS5_NO_RESULT_MEMO") != nullptr; + default: return false; + } +} + [[nodiscard]] inline std::uint64_t HeapCacheBypassMask() { static const std::uint64_t mask = [] { const char* text = std::getenv("APS5_HEAP_NO_CACHE"); - return text == nullptr ? std::uint64_t{0} : ParseHeapCacheBypass(text); + std::uint64_t bypassed = text == nullptr ? std::uint64_t{0} : ParseHeapCacheBypass(text); + for (std::uint32_t index = 0; index < static_cast(HeapCache::Count); ++index) { + if (HeapCacheLegacyBypassed(static_cast(index))) bypassed |= std::uint64_t{1} << index; + } + return bypassed; }(); return mask; } -[[nodiscard]] inline bool HeapCacheBypassed(HeapCache cache) { - return (HeapCacheBypassMask() >> static_cast(cache) & 1u) != 0u; +[[nodiscard]] inline bool HeapCacheEnabled(HeapCache cache) { + return (HeapCacheBypassMask() >> static_cast(cache) & 1u) == 0u; } [[nodiscard]] inline bool HeapVerifyEnabled() { diff --git a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp index 13bf947f1f99..0540cd22b027 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp @@ -4,8 +4,11 @@ #include "Recompiler.hpp" #include "IntermediateRepresentation/IrProgram.hpp" #include "Optimization/SrtWalker.hpp" +#include #include #include +#include +#include namespace ShaderRecompiler { @@ -69,6 +72,7 @@ class PreparedShaderInvocation { std::shared_ptr MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words) const; const std::shared_ptr& Plan() const; std::shared_ptr LoadPlan() const; + std::shared_ptr PlanOrLoad() const; std::uint64_t VariantId() const; private: @@ -78,6 +82,9 @@ class PreparedShaderInvocation { }; [[nodiscard]] std::span GetPreparedCode(const SourceHandle& handle); void CompleteHeapDataWords(const RecompileResult& shared, HeapStageWords& words); +inline void OverlayUserWords(std::vector& descriptor, std::span userData) { + std::copy_n(userData.begin(), std::min(userData.size(), descriptor.size()), descriptor.begin()); +} [[nodiscard]] std::shared_ptr PrepareShader(const RecompileRequest& request); [[nodiscard]] std::shared_ptr PrepareShader(const RecompileRequest& request, ShaderPreparationContext* preparation); [[nodiscard]] bool MatchesPreparedShader(const RecompileRequest& request, const SourceHandle& handle); diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 0557f7b9aeb8..1f0008a18b62 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -1971,7 +1971,7 @@ RecompileResult RecompileImpl(const RecompileRequest& request) { // APS5_NO_RESULT_MEMO=1: every Recompile(request, capture) materializes its own result as before. bool ResultMemo() { - static const bool resultMemo = std::getenv("APS5_NO_RESULT_MEMO") == nullptr && !HeapCacheBypassed(HeapCache::ResultMemo); + static const bool resultMemo = HeapCacheEnabled(HeapCache::ResultMemo); return resultMemo; } @@ -2759,8 +2759,8 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap auto& entry = front.At(source.id, key); ++front.lookups; std::shared_ptr hit; - const bool templates = !HeapCacheBypassed(HeapCache::Templates); - if (templates && !HeapCacheBypassed(HeapCache::TemplateFront) && entry.found != nullptr && entry.source == source.id && entry.key == key) { + const bool templates = HeapCacheEnabled(HeapCache::Templates); + if (templates && HeapCacheEnabled(HeapCache::TemplateFront) && entry.found != nullptr && entry.source == source.id && entry.key == key) { hit = entry.found; } else if (templates) { { @@ -2822,6 +2822,11 @@ std::shared_ptr PreparedShaderInvocation::LoadPlan() const return acquirePlan(request, handle->source, false, handle.get()); } +std::shared_ptr PreparedShaderInvocation::PlanOrLoad() const { + const auto& plan = Plan(); + return plan != nullptr ? plan : LoadPlan(); +} + std::uint64_t PreparedShaderInvocation::VariantId() const { return handle != nullptr && handle->artifact != nullptr ? handle->artifact->artifact.variantId : 0u; } @@ -2838,7 +2843,7 @@ void CompleteHeapDataWords(const RecompileResult& shared, HeapStageWords& words) if (words.bindings.empty()) words.bindings.resize(count); auto& descriptor = words.bindings[index]; descriptor.assign(binding.guestDescriptor.begin(), binding.guestDescriptor.end()); - std::copy_n(words.userData.begin(), patched, descriptor.begin()); + OverlayUserWords(descriptor, words.userData); } } diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index fc7084748938..f3afff331080 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -546,6 +546,16 @@ struct IdentityMemo { } }; +struct HeapMappableMemo { + mutable std::atomic verdicts[2]{}; + HeapMappableMemo() = default; + HeapMappableMemo(const HeapMappableMemo&) {} + HeapMappableMemo& operator=(const HeapMappableMemo&) { + for (auto& verdict : verdicts) verdict.store(0, std::memory_order_relaxed); + return *this; + } +}; + [[nodiscard]] bool VerifyIdentityMemo(); struct HeapStageWords { @@ -1043,6 +1053,7 @@ struct RecompileResult : CompiledShaderArtifact, ShaderInvocation { std::vector shaderDataUserWords; [[nodiscard]] std::uint64_t PipelineVariantId() const { return specializationId != 0 ? specializationId : variantId; } IdentityMemo identityMemo; + HeapMappableMemo heapMappableMemo; [[nodiscard]] PipelineIdentity Identity() const { if (!identityMemo.sealed.load(std::memory_order_acquire)) return ComputeIdentity(); const auto module = spirv.ContentHash(); diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index ee060507daad..37461138e540 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -90,7 +90,7 @@ namespace ShaderRecompiler::ShaderDiskCache { static_assert(sizeof(CompiledShaderArtifact) == 336, "CompiledShaderArtifact changed: update the artifact encoder"); static_assert(sizeof(ShaderInvocation) == 240, "ShaderInvocation changed: update the invocation encoder"); #if defined(__cpp_lib_atomic_shared_ptr) -static_assert(sizeof(RecompileResult) == 696, "RecompileResult changed: update EncodeResult and DecodeResult"); +static_assert(sizeof(RecompileResult) == 712, "RecompileResult changed: update EncodeResult and DecodeResult"); #endif static_assert(sizeof(DescriptorBinding) == 912, "DescriptorBinding changed: update the binding encoder"); static_assert(sizeof(VertexAttribute) == 32, "VertexAttribute changed: update the attribute encoder"); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 32f55a28a0b9..ed24961f069d 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -58,7 +58,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_PERF_DOMINATOR_TREE` | presence | `core/shader/recompiler/ControlFlow/src/Structurizer.cpp` | | computes the structurizer's dominator and post-dominator sets with the set fixpoint instead of a dominator tree, walks every selection construct instead of testing its members by dominance, and tests every block against each construct when checking the structured constructs instead of walking the construct | | `APS5_NO_PERF_DOM_INTERSECTION` | presence | `core/shader/recompiler/ControlFlow/src/Structurizer.cpp` | | computes dominator intersections into a fresh vector instead of intersecting in place | | `APS5_NO_PERF_ITERATION_SELECTION` | presence | `core/shader/recompiler/ControlFlow/src/Structurizer.cpp` | | recomputes the post-dominator sets when finding a loop's iteration-selection merge instead of reusing them | -| `APS5_NO_RESULT_MEMO` | presence | `core/shader/recompiler/Recompiler.cpp` | | materializes a fresh result for every recompile instead of reusing the result memo | +| `APS5_NO_RESULT_MEMO` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | materializes a fresh result for every recompile instead of reusing the result memo | | `APS5_NO_SCOPED_VECTOR_WINDOW` | presence | `core/shader/recompiler/Translation/src/InstructionTranslator.cpp` | | keeps a program's vector registers in its relative-addressing window in every block instead of only in the blocks between relative accesses | | `APS5_NO_SRT_TAPE` | presence | `core/shader/recompiler/Optimization/src/SrtWalker/SrtTape.cpp` | | runs the runtime-source walk of a plan in the IR evaluator instead of the compiled tape | | `APS5_NO_TABLE_RESOLUTION_REUSE` | presence | `core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp` | | stops a result memo miss from reusing an unchanged image table's resolution, so the table is resolved again | @@ -294,16 +294,16 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_DISPATCH_MOVE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | leaves a dispatch-cache hit from moving its read-only buffers into the template, so it prepares the dispatch again; also off when APS5_NO_TEMPLATE_DATA_REFRESH is set | | `APS5_NO_DISPATCH_OVERLAP` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records every dispatch of a compute ring with its own leading and trailing barrier, also those the title left unordered after the ring's previous dispatch, as before | | `APS5_NO_DISPATCH_RECIPE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | builds no dispatch recipes, so dispatch-cache hits repeat the recorded work | -| `APS5_NO_DRAW_DATA_HITS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | disables draw-cache hits that differ only in ShaderData words | +| `APS5_NO_DRAW_DATA_HITS` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | disables draw-cache hits that differ only in ShaderData words | | `APS5_NO_DRAW_INPUTS_IN_PLACE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | copies draw vertex and index ranges instead of binding them in place from host imports, on any device; wins over `APS5_DRAW_INPUTS_IN_PLACE` | -| `APS5_NO_DRAW_KEY` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | registers no draw key, so every draw decodes its programs instead of hitting the draw cache | +| `APS5_NO_DRAW_KEY` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | registers no draw key, so every draw decodes its programs instead of hitting the draw cache | | `APS5_NO_DRAW_KEY_TRIM` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | keys the render target and index ranges into the draw resource key instead of repeating the alias checks on a hit | | `APS5_NO_DRAW_PRECHECK` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPrecheck.cpp` | | disables the draw precheck that rejects empty or invalid draws early | -| `APS5_NO_DRAW_RECIPE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | builds no draw recipes, so draw-cache hits repeat the recorded stages | +| `APS5_NO_DRAW_RECIPE` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | builds no draw recipes, so draw-cache hits repeat the recorded stages | | `APS5_NO_DRAW_RELOCATION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp` | | disables draw relocation, which rewrites a draw's moved user words from a learned variant instead of preparing the draw again | -| `APS5_NO_DRAW_RESOURCE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | builds every draw's shader resources instead of reusing a cached identical build | -| `APS5_NO_DRAW_SRT_ENTRIES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | disables the draw cache's SRT entries, so every draw decodes its programs | -| `APS5_NO_DRAW_STAGE_DATA_HITS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | disables draw-cache hits that differ only in a stage's ShaderData words | +| `APS5_NO_DRAW_RESOURCE_CACHE` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | builds every draw's shader resources instead of reusing a cached identical build | +| `APS5_NO_DRAW_SRT_ENTRIES` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | disables the draw cache's SRT entries, so every draw decodes its programs | +| `APS5_NO_DRAW_STAGE_DATA_HITS` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | disables draw-cache hits that differ only in a stage's ShaderData words | | `APS5_NO_DRAW_STAGING` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | binds a recorded draw's written and atomic buffer elements in place in host memory instead of staging them through a device-local buffer | | `APS5_NO_DYNAMIC_COLOR_WRITE_MASK` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp`, `core/libs/prx/libSceAgcDriver/tests/Recorder.cpp` | | keeps color write masks in the graphics pipelines instead of setting them per draw through `VK_EXT_extended_dynamic_state3` | | `APS5_NO_EMPTY_INDIRECT_SKIP` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp` | | builds the stages of an indirect draw whose front program last took the CPU path even when none of its records draws anything, instead of reading its records first and skipping it | @@ -364,7 +364,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_MESH_INLINE_FUNCTIONS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | keeps a mesh program's helper functions `DontInline` on NVIDIA's proprietary driver instead of asking the driver to inline every function | | `APS5_NO_MESH_WINDOW_BUFFER` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | keeps a mesh program's relative-addressing window in function arrays on NVIDIA's proprietary driver instead of moving it to a storage buffer | | `APS5_NO_MOVED_BUFFERS_IN_PLACE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | rebuilds the shader resources of a draw whose read-only buffer moved into a range that recorded GPU work still writes, instead of reading the buffer through its host import on the cached set | -| `APS5_NO_MOVED_BUFFER_TEMPLATES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | keys the full descriptor words of read-only guest buffers instead of allowing a hit when they move | +| `APS5_NO_MOVED_BUFFER_TEMPLATES` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | keys the full descriptor words of read-only guest buffers instead of allowing a hit when they move | | `APS5_NO_OBSERVATION_GUARD` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WriteEvidence.cpp` | | observes every validated range, not only the ranges whose flush hook waited | | `APS5_NO_OPPORTUNISTIC_REAP` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | skips retiring already-finished batches before a submit | | `APS5_NO_ORDERED_WAITS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitStatistics.cpp` | | bumps the collect epoch at every memory wait instead of skipping a wait on an unchanged flag an earlier wait already ordered | @@ -399,13 +399,13 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_RESIDENT_LINEAR` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | drops the residency of linear color targets, so a target whose address has a host import, or whose import a draw would make, is copied in and out again | | `APS5_NO_RESIDENT_PRESENT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | always presents through guest memory instead of the resident image | | `APS5_NO_RESIDENT_TARGETS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | copies every render target in and out again instead of keeping it resident | -| `APS5_NO_RESOURCE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | disables the shared resource cache, so every dispatch builds its resources fresh | +| `APS5_NO_RESOURCE_CACHE` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | disables the shared resource cache, so every dispatch builds its resources fresh | | `APS5_NO_RUN_MEMO` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | walks the lease for a host import's run of ranges on every lookup instead of reusing the bounds found for the same lease snapshot and import window block | | `APS5_NO_SAMPLED_FROM_STORAGE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | keeps every sampled texture a CPU snapshot instead of viewing the surface's storage image | | `APS5_NO_SAMPLER_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | creates a sampler per binding instead of caching them | | `APS5_NO_SEPARATE_QUEUED_LABELS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | lets a queued label enter the recorded table and replace a recorded entry of its dword | | `APS5_NO_SETTLED_INDIRECT_READ` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | keeps an indirect draw whose records no unfinished batch writes on the GPU-side path instead of reading the records on the CPU | -| `APS5_NO_SHAPE_MEMO` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | looks up every draw's resident targets and pipeline anew instead of repeating the ones an earlier draw of the same register shape used | +| `APS5_NO_SHAPE_MEMO` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | looks up every draw's resident targets and pipeline anew instead of repeating the ones an earlier draw of the same register shape used | | `APS5_NO_SHARED_FAULT_SLOTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp` | | gives every BDA resource object its own full-size fault buffer for its whole life instead of a slot from the device's shared fault chunks that an idle cached object gives back (a 32-byte slot when its programs can write only the fault report) | | `APS5_NO_SHARED_GDS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp` | | keeps the GDS in a private guest mapping, which the GPU cannot import, instead of anonymous shared memory on an integrated GPU with host imports; DMA_DATA into the GDS behind GPU writes to it then drains, and DMA_DATA out of it is read on the CPU | | `APS5_NO_SINGLE_PASS_COLLECT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp` | | walks the written pages once without clearing them and, when any were written, a second time clearing them, instead of one cleared pass | @@ -436,7 +436,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_UNLOCKED_DRAIN` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp` | | keeps the GPU mutex held while draining a packet instead of the unlocked drain | | `APS5_NO_UNLOCKED_VALIDATE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchLookup.cpp` | | keeps the dispatch-cache mutex held while validating a cache entry | | `APS5_NO_UNREGISTERED_DROP` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | stores a storage image's pending results even when its memory is no longer registered, instead of dropping them | -| `APS5_NO_VALIDATE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | validates every draw instead of serving the validation memo | +| `APS5_NO_VALIDATE_CACHE` | presence | `core/shader/recompiler/HeapCacheSwitch.hpp` | | validates every draw instead of serving the validation memo | | `APS5_NO_VALIDATE_SKIP` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WriteEvidence.cpp` | | syncs every pending write instead of skipping validation on written-element evidence | | `APS5_NO_VOUCHED_VALIDATION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp` | | validates a cached draw or dispatch through its per-run checks instead of its table block's vouch | | `APS5_NO_WAIT_OVERLAP_SUBMIT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp` | | disables the unlocked wait that submits recorded work while overlapping writes are open | @@ -574,6 +574,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_VERIFY_ADDRESS_DRAW_REUSE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | builds the resources of every served read-only address-based draw hit anew, compares its space reuse, BDA table bytes, sampled textures, storage images and set layouts with the hit's, checks that every snapshot lies in a readable range of the hit's table and equals guest memory, and throws on a difference | | `APS5_VERIFY_BDA_TABLES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | checks a reused BDA page table against the one just built | | `APS5_VERIFY_DATA_HITS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp` | | recomputes a dispatch data hit and aborts on a disagreement | +| `APS5_VERIFY_DECODE_REUSE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp` | | decodes the vertex stage info of every ring hit again on the finisher and throws when it differs from the info the queue worker kept | | `APS5_VERIFY_DRAW_DATA_HITS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | recomputes a draw data hit and aborts on a disagreement | | `APS5_VERIFY_DRAW_ENTRIES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | re-decodes every draw-cache hit through the full path and checks it | | `APS5_VERIFY_DRAW_PIPELINE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | with `APS5_DRAW_PIPELINE` set, runs the full check instead of every 64th reused epoch proof on each thread and prints `[epoch-proofs]` counts | @@ -585,6 +586,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_VERIFY_GUARD_SPANS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp` | | checks every guard check that the thread's copy of the guard ranges answered without a lock against the guard list and takes the list's answer; a copy that was current, or a copy refilled after the list changed, that still misses an overlapping guard prints a `[guard-spans] verify` line (the first twenty), and a `[guard-spans]` line every 10 s counts the checks and misses (it also prints with `APS5_PROFILE_DRAW`) | | `APS5_VERIFY_KNOWN_VALUES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferCopy.cpp` | | serves known values through the hook too and counts mismatches | | `APS5_VERIFY_OWNED_DRAW_INPUTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | compares reused owned input bytes and throws if they differ while the proof still holds | +| `APS5_VERIFY_PENDING_SERIAL_SKIP` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp` | | checks a dispatch variant that skipped its pending image check at an unchanged serial against the pending images and throws when one overlaps its runs | | `APS5_VERIFY_PROOFS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | runs the full walk beside every own-object refresh proof and aborts on a different decision | | `APS5_VERIFY_RECIPE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | makes the ordinary prepare path beside a recipe hit and compares the answers | | `APS5_VERIFY_REGISTER_KEYS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRegisterKey.cpp` | | checks the incremental register fingerprint against the full state | From 1a651aef4681ab0c58b08b273fd168ecafddbd16 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 08:08:09 +0530 Subject: [PATCH 229/269] refactor(shader): split push data placement and pushed buffer definitions and drop dead root address helpers --- core/shader/recompiler/CompiledVariant.hpp | 5 + .../include/Optimization/ResourceProgram.hpp | 1 + .../src/DescriptorBindingBuilder.cpp | 4 +- core/shader/recompiler/PushDataLayout.hpp | 257 +++++++++++------- core/shader/recompiler/Recompiler.cpp | 27 +- core/shader/recompiler/ShaderDiskCache.hpp | 2 +- .../SpirvBackend/SpirvEmitterState.hpp | 13 +- .../SpirvMemory/SpirvBufferAccess.hpp | 1 - .../SpirvBackend/src/SpirvImageEmitter.cpp | 2 +- .../src/SpirvMemory/SpirvBufferAccess.cpp | 80 +++--- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 152 ++++++----- .../SpirvBackend/src/SpirvRuntimeBuffer.cpp | 9 +- 12 files changed, 309 insertions(+), 244 deletions(-) diff --git a/core/shader/recompiler/CompiledVariant.hpp b/core/shader/recompiler/CompiledVariant.hpp index adc493521b7f..5d84bcf29ef9 100644 --- a/core/shader/recompiler/CompiledVariant.hpp +++ b/core/shader/recompiler/CompiledVariant.hpp @@ -22,6 +22,11 @@ class BufferSubstituteTable { return slots; } + void CopySlots(std::vector& out) const { + std::lock_guard lock(mutex); + out.assign(slots.begin(), slots.end()); + } + void Learn(std::size_t slot, const BufferSubstitute& value) { std::lock_guard lock(mutex); if (slot >= slots.size() || slots[slot].known) return; diff --git a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp index 0540cd22b027..fc7e8b3e10fc 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp @@ -60,6 +60,7 @@ struct SourceHandle { std::shared_ptr source; std::shared_ptr artifact; std::vector staticKey; + bool imageTableBindings = false; }; class PreparedShaderInvocation { public: diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index 3e9c0324dd61..f0d08f85d6a8 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -21,7 +21,6 @@ namespace ShaderRecompiler { static_assert(PipelineSpecialization::ImageBase + ShaderInfo::MaxImages * PipelineSpecialization::ImageWords <= PipelineSpecialization::VertexBase); static_assert(PipelineSpecialization::MipCountBase + ShaderInfo::MaxImages <= PipelineSpecialization::RootItemPositionBase); -static_assert(PipelineSpecialization::RootItemPositionBase + PipelineSpecialization::RootItemPositions <= PipelineSpecialization::StoreQuantizeBase); static_assert(PipelineSpecialization::StoreQuantizeBase + ShaderInfo::MaxImages * PipelineSpecialization::StoreQuantizeWords <= PipelineSpecialization::DescriptorIndexBase); static_assert(PipelineSpecialization::CompareBase + ShaderInfo::MaxImages * PipelineSpecialization::CompareWords <= PipelineSpecialization::FoldOffsetBase); static_assert(PipelineSpecialization::FoldOffsetBase + ShaderInfo::MaxSamplers <= PipelineSpecialization::UnnormalizedBaseLevelBase); @@ -769,9 +768,9 @@ DescriptorBindingPlan DescriptorBindingBuilder::Select(const DescriptorBindingPl namespace { void guestBindingWords(const PreparedDescriptorBinding& entry, std::vector& words, const ResourceSnapshot& snapshot, const ResolvedImageTables* tables) { + words.clear(); switch (entry.descriptor.role) { case DescriptorRole::GuestBuffers: - words.clear(); words.reserve(entry.resources.size() * 4u); for (const std::uint32_t resource : entry.resources) { if (resource >= snapshot.buffers.size()) fail("DescriptorBindingBuilder::Populate guest buffer index is out of range"); @@ -917,7 +916,6 @@ void DescriptorBindingBuilder::PopulateGuestWords(std::vector PlacePushData(std::span stages, std::uint64_t occupied, std::uint32_t pushedRecords = RuntimeAbi::PushedBufferLimit) { - namespace Abi = RuntimeAbi; - constexpr std::uint32_t total = Abi::PushDataDwords; - std::vector placements(stages.size()); - for (auto& placement : placements) placement.items.fill(Abi::NoPushPosition); - auto used = occupied; - const auto isFree = [&](std::uint32_t first, std::uint32_t width) { +class PushDataPlacer { +public: + PushDataPlacer(std::span stages, std::uint64_t occupied, std::uint32_t pushedRecords) + : stages(stages), used(occupied), pushedRecords(pushedRecords), placements(stages.size()), overflows(stages.size(), RuntimeAbi::NoPushPosition) { + for (auto& placement : placements) placement.items.fill(RuntimeAbi::NoPushPosition); + } + + std::vector Place() { + PlaceRoots(); + PlaceBufferRoots(); + PlaceUserData(); + ClaimPushedData(); + return std::move(placements); + } + +private: + static constexpr std::uint32_t total = RuntimeAbi::PushDataDwords; + static constexpr std::uint32_t globalItems = RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::ShaderData) - 1u; + static constexpr std::uint32_t optionalItems = RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::UserData); + static constexpr std::array parts{PushPart::Fragment, PushPart::Compute, PushPart::PreRasterization}; + + static bool Top(PushPart part) { return part != PushPart::PreRasterization; } + + bool IsFree(std::uint32_t first, std::uint32_t width) const { for (auto dword = first; dword < first + width; ++dword) { if (dword >= total || (used >> dword & 1ull) != 0u) return false; } return true; - }; - const auto tryTake = [&](std::uint32_t width, bool aligned, bool top) { + } + + std::uint32_t TryTake(std::uint32_t width, bool aligned, bool top) { for (std::uint32_t step = 0; step + width <= total; ++step) { const auto first = top ? total - width - step : step; - if ((aligned && first % 2u != 0u) || !isFree(first, width)) continue; + if ((aligned && first % 2u != 0u) || !IsFree(first, width)) continue; for (auto dword = first; dword < first + width; ++dword) used |= 1ull << dword; return first; } - return Abi::NoPushPosition; - }; - const auto take = [&](std::uint32_t width, bool aligned, bool top) { - const auto first = tryTake(width, aligned, top); - if (first == Abi::NoPushPosition) throw std::runtime_error("the push data has no room for a pipeline's root"); + return RuntimeAbi::NoPushPosition; + } + + std::uint32_t Take(std::uint32_t width, bool aligned, bool top) { + const auto first = TryTake(width, aligned, top); + if (first == RuntimeAbi::NoPushPosition) throw std::runtime_error("the push data has no room for a pipeline's root"); return first; - }; - const auto placeRoot = [&](std::uint32_t items, bool top, std::array& positions) { + } + + void PlaceRootItems(std::uint32_t items, bool top, std::array& positions) { for (const bool addresses : {true, false}) { - for (std::uint32_t index = 0; index < Abi::RootItemCount; ++index) { - const auto item = static_cast(index); - if ((items & Abi::RootItemBit(item)) == 0u || Abi::RootAddressItem(item) != addresses) continue; - positions[index] = take(addresses ? 2u : 1u, addresses, top); + for (std::uint32_t index = 0; index < RuntimeAbi::RootItemCount; ++index) { + const auto item = static_cast(index); + if ((items & RuntimeAbi::RootItemBit(item)) == 0u || RuntimeAbi::RootAddressItem(item) != addresses) continue; + positions[index] = Take(addresses ? 2u : 1u, addresses, top); } } - }; - constexpr auto globalItems = Abi::RootItemBit(Abi::RootItem::ShaderData) - 1u; - constexpr auto optionalItems = Abi::RootItemBit(Abi::RootItem::UserData); - constexpr std::array parts{PushPart::Fragment, PushPart::Compute, PushPart::PreRasterization}; - std::vector overflows(stages.size(), Abi::NoPushPosition); - std::uint32_t globals = 0; - std::uint32_t fragmentGlobals = 0; - for (const auto& stage : stages) { - globals |= stage.items & globalItems; - if (stage.part == PushPart::Fragment) fragmentGlobals |= stage.items & globalItems; - } - std::array shared{}; - shared.fill(Abi::NoPushPosition); - placeRoot(fragmentGlobals, false, shared); - placeRoot(globals & ~fragmentGlobals, false, shared); - for (std::size_t index = 0; index < stages.size(); ++index) { - for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { - if ((stages[index].items & globalItems & (1u << item)) != 0u) placements[index].items[item] = shared[item]; - } } - for (const auto part : parts) { - const bool top = part != PushPart::PreRasterization; + + template + void ForEachStageOfPartReserving(PushPart part, Visit&& visit) { + const auto reserved = part == PushPart::Fragment ? PushFeatureDwords(true, true, true) & ~used : 0u; + used |= reserved; for (std::size_t index = 0; index < stages.size(); ++index) { - if (stages[index].part != part) continue; - placeRoot(stages[index].items & ~globalItems & ~optionalItems, top, placements[index].items); - placements[index].pushedBuffers = stages[index].pushedBuffers; + if (stages[index].part == part) visit(index, Top(part)); } + used &= ~reserved; } - const auto recordsOf = [&](std::size_t index) { return std::min({stages[index].pushedBuffers, pushedRecords, Abi::PushedBufferLimit}); }; - for (const auto part : parts) { + + void PlaceSharedRoots() { + std::uint32_t globals = 0; + std::uint32_t fragmentGlobals = 0; + for (const auto& stage : stages) { + globals |= stage.items & globalItems; + if (stage.part == PushPart::Fragment) fragmentGlobals |= stage.items & globalItems; + } + std::array shared{}; + shared.fill(RuntimeAbi::NoPushPosition); + PlaceRootItems(fragmentGlobals, false, shared); + PlaceRootItems(globals & ~fragmentGlobals, false, shared); for (std::size_t index = 0; index < stages.size(); ++index) { - if (stages[index].part == part && stages[index].pushedBuffers != 0u) overflows[index] = tryTake(2u, true, part != PushPart::PreRasterization); + for (std::uint32_t item = 0; item < RuntimeAbi::RootItemCount; ++item) { + if ((stages[index].items & globalItems & (1u << item)) != 0u) placements[index].items[item] = shared[item]; + } } } - for (const auto part : parts) { - const bool top = part != PushPart::PreRasterization; - const auto reserved = part == PushPart::Fragment ? PushFeatureDwords(true, true, true) & ~used : 0u; - used |= reserved; - for (std::size_t index = 0; index < stages.size(); ++index) { - const auto buffers = stages[index].pushedBuffers; - if (stages[index].part != part || buffers == 0u) continue; - const auto records = recordsOf(index); - bool overflowed = buffers > records; - for (std::uint32_t buffer = 0; buffer < records; ++buffer) { - placements[index].bufferRoots[buffer] = tryTake(Abi::PushedBufferWords, true, top); - overflowed = overflowed || placements[index].bufferRoots[buffer] == Abi::NoPushPosition; + + void PlaceRoots() { + PlaceSharedRoots(); + for (const auto part : parts) { + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part != part) continue; + PlaceRootItems(stages[index].items & ~globalItems & ~optionalItems, Top(part), placements[index].items); + placements[index].pushedBuffers = stages[index].pushedBuffers; } - if (overflowed && overflows[index] == Abi::NoPushPosition) throw std::runtime_error("the push data has no room for a stage's buffer addresses"); - if (overflowed) placements[index].bufferOverflow = overflows[index]; - else if (overflows[index] != Abi::NoPushPosition) used &= ~(3ull << overflows[index]); } - used &= ~reserved; } - for (const auto part : parts) { - const bool top = part != PushPart::PreRasterization; - const auto reserved = part == PushPart::Fragment ? PushFeatureDwords(true, true, true) & ~used : 0u; - used |= reserved; - for (std::size_t index = 0; index < stages.size(); ++index) { - if (stages[index].part != part || (stages[index].items & Abi::RootItemBit(Abi::RootItem::UserData)) == 0u) continue; - placements[index].items[static_cast(Abi::RootItem::UserData)] = tryTake(2u, true, top); + + std::uint32_t RecordsOf(std::size_t index) const { return std::min({stages[index].pushedBuffers, pushedRecords, RuntimeAbi::PushedBufferLimit}); } + + void ReserveOverflowRecords() { + for (const auto part : parts) { + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part == part && stages[index].pushedBuffers != 0u) overflows[index] = TryTake(2u, true, Top(part)); + } } - used &= ~reserved; } - std::vector> runs; - for (std::uint32_t dword = 0; dword < total;) { - if ((used >> dword & 1ull) != 0u) { - ++dword; - continue; + void PlaceStageBufferRoots(std::size_t index, bool top) { + const auto buffers = stages[index].pushedBuffers; + if (buffers == 0u) return; + const auto records = RecordsOf(index); + bool overflowed = buffers > records; + for (std::uint32_t buffer = 0; buffer < records; ++buffer) { + placements[index].bufferRoots[buffer] = TryTake(RuntimeAbi::PushedBufferWords, true, top); + overflowed = overflowed || placements[index].bufferRoots[buffer] == RuntimeAbi::NoPushPosition; } - auto end = dword; - while (end < total && (used >> end & 1ull) == 0u) ++end; - runs.emplace_back(dword, end); - dword = end; + if (overflowed && overflows[index] == RuntimeAbi::NoPushPosition) throw std::runtime_error("the push data has no room for a stage's buffer addresses"); + if (overflowed) placements[index].bufferOverflow = overflows[index]; + else if (overflows[index] != RuntimeAbi::NoPushPosition) used &= ~(3ull << overflows[index]); + } + + void PlaceBufferRoots() { + ReserveOverflowRecords(); + for (const auto part : parts) ForEachStageOfPartReserving(part, [&](std::size_t index, bool top) { PlaceStageBufferRoots(index, top); }); } - std::uint32_t room = 0; - std::uint32_t largest = 0; - for (const auto& [first, end] : runs) { - room += end - first; - largest = std::max(largest, end - first); + + void PlaceUserData() { + for (const auto part : parts) { + ForEachStageOfPartReserving(part, [&](std::size_t index, bool top) { + if ((stages[index].items & RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::UserData)) == 0u) return; + placements[index].items[static_cast(RuntimeAbi::RootItem::UserData)] = TryTake(2u, true, top); + }); + } } - std::vector wanted(stages.size(), 0u); - std::uint32_t sum = 0; - for (std::size_t index = 0; index < stages.size(); ++index) { - wanted[index] = std::min({stages[index].pushedWanted, Abi::PushedDataWantedLimit, largest}); - sum += wanted[index]; + + std::vector> FreeRuns() const { + std::vector> runs; + for (std::uint32_t dword = 0; dword < total;) { + if ((used >> dword & 1ull) != 0u) { + ++dword; + continue; + } + auto end = dword; + while (end < total && (used >> end & 1ull) == 0u) ++end; + runs.emplace_back(dword, end); + dword = end; + } + return runs; } - auto counts = wanted; - if (sum > room) { + + std::vector PushedDataCounts(const std::vector>& runs) const { + std::uint32_t room = 0; + std::uint32_t largest = 0; + for (const auto& [first, end] : runs) { + room += end - first; + largest = std::max(largest, end - first); + } + std::vector wanted(stages.size(), 0u); + std::uint32_t sum = 0; + for (std::size_t index = 0; index < stages.size(); ++index) { + wanted[index] = std::min({stages[index].pushedWanted, RuntimeAbi::PushedDataWantedLimit, largest}); + sum += wanted[index]; + } + auto counts = wanted; + if (sum <= room) return counts; const auto sharedAt = [&](std::uint32_t level) { std::uint32_t shared = 0; for (const auto want : wanted) shared += std::min(want, level); @@ -208,9 +248,10 @@ inline std::vector PlacePushData(std::span --left; } } + return counts; } - const auto claim = [&](std::size_t index, bool top) { - auto count = counts[index]; + + void ClaimRun(std::vector>& runs, std::size_t index, std::uint32_t count, bool top) { if (count == 0u) return; auto chosen = runs.end(); if (top) { @@ -235,14 +276,28 @@ inline std::vector PlacePushData(std::span placements[index].pushed = {chosen->first, count}; chosen->first += count; } - }; - for (std::size_t index = 0; index < stages.size(); ++index) { - if (stages[index].part == PushPart::Fragment) claim(index, true); } - for (std::size_t index = 0; index < stages.size(); ++index) { - if (stages[index].part != PushPart::Fragment) claim(index, false); + + void ClaimPushedData() { + auto runs = FreeRuns(); + const auto counts = PushedDataCounts(runs); + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part == PushPart::Fragment) ClaimRun(runs, index, counts[index], true); + } + for (std::size_t index = 0; index < stages.size(); ++index) { + if (stages[index].part != PushPart::Fragment) ClaimRun(runs, index, counts[index], false); + } } - return placements; + + std::span stages; + std::uint64_t used; + std::uint32_t pushedRecords; + std::vector placements; + std::vector overflows; +}; + +inline std::vector PlacePushData(std::span stages, std::uint64_t occupied, std::uint32_t pushedRecords = RuntimeAbi::PushedBufferLimit) { + return PushDataPlacer(stages, occupied, pushedRecords).Place(); } static_assert(RuntimeAbi::RootItemCount <= PipelineSpecialization::RootItemPositions); diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 1f0008a18b62..f7236d2e7e45 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -474,8 +474,20 @@ struct HeapTemplate { std::vector images; std::vector samplers; std::uint64_t bytes = 0; + bool tableRoles = false; }; +bool HasTableRoles(const UsedBindingPlan& used) { + return used.plan != nullptr && std::ranges::any_of(used.plan->bindings, [](const PreparedDescriptorBinding& entry) { + const auto role = entry.descriptor.role; + return role == DescriptorRole::ImageTable || role == DescriptorRole::ImageStorageTable || role == DescriptorRole::SamplerTable || role == DescriptorRole::ImageTableMap; + }); +} + +bool HasImageTableBindings(const CompiledBindingLayout& bindings) { + return std::ranges::any_of(bindings.layout.descriptors, [](const IrDescriptorBinding& descriptor) { return descriptor.kind == DescriptorBindingKind::ImageTable || descriptor.kind == DescriptorBindingKind::SamplerTable || descriptor.kind == DescriptorBindingKind::ImageTableMap; }); +} + struct SourceEntry : std::enable_shared_from_this { std::mutex mutex; const std::uint64_t id = NextSourceId(); @@ -2573,6 +2585,7 @@ std::shared_ptr PrepareShader(const RecompileRequest& reques bool cacheHit = false; std::lock_guard lock(handle->source->mutex); handle->artifact = findOrCompileVariant(*handle->source, request, cacheHit, preparation); + handle->imageTableBindings = HasImageTableBindings(handle->artifact->bindings); return handle; }); trimResourcePlansOverBudget(); @@ -2695,11 +2708,7 @@ void HeapBindingWords(const RecompileRequest& request, const CompiledVariant& va if (AllEmpty(words.bindings)) words.bindings.clear(); return; } - const bool tableRoles = std::ranges::any_of(shared.plan.plan->bindings, [](const PreparedDescriptorBinding& entry) { - const auto role = entry.descriptor.role; - return role == DescriptorRole::ImageTable || role == DescriptorRole::ImageStorageTable || role == DescriptorRole::SamplerTable || role == DescriptorRole::ImageTableMap; - }); - const auto tables = tableRoles ? std::optional(ResourceMaterializer::ResolveImageTables(variant.info.info, snapshot, variant.artifact.variantId)) : std::nullopt; + const auto tables = shared.tableRoles ? std::optional(ResourceMaterializer::ResolveImageTables(variant.info.info, snapshot, variant.artifact.variantId)) : std::nullopt; DescriptorBindingBuilder{}.PopulateGuestWords(words.bindings, variant.bindings, *shared.plan.plan, variant.info.userDataBase, snapshot, partialThreads(request), tables ? &*tables : nullptr); if (words.bindings.size() != count) throw std::runtime_error("ShaderRecompiler: a heap stage's per-draw bindings differ from its template"); if (HeapVerifyEnabled()) { @@ -2742,10 +2751,11 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap } words.flattenedSrt.assign(snapshot.flattenedSrt.begin(), snapshot.flattenedSrt.end()); words.bindings.clear(); - const bool tables = std::ranges::any_of(layout.descriptors, [](const IrDescriptorBinding& descriptor) { return descriptor.kind == DescriptorBindingKind::ImageTable || descriptor.kind == DescriptorBindingKind::SamplerTable || descriptor.kind == DescriptorBindingKind::ImageTableMap; }); - const bool perDrawBindings = (request.shader.stage == ShaderStage::Fragment || request.shader.stage == ShaderStage::Vertex) && !tables; + const bool perDrawBindings = (request.shader.stage == ShaderStage::Fragment || request.shader.stage == ShaderStage::Vertex) && !handle->imageTableBindings; auto& source = *handle->source; - const auto substitutes = bufferSubstitutesEnabled() && variant->substitutes != nullptr ? variant->substitutes->Slots() : std::vector{}; + static thread_local std::vector substitutes; + substitutes.clear(); + if (bufferSubstitutesEnabled() && variant->substitutes != nullptr) variant->substitutes->CopySlots(substitutes); ResourceSnapshot mergedStorage; const auto& merged = mergeTargetImage(*variant, request, snapshot, false, mergedStorage); const std::uint64_t key = HeapTemplateKey(request, *variant, merged, perDrawBindings, substitutes); @@ -2785,6 +2795,7 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap built->heapTemplateId = NextTemplateId(); auto created = std::make_shared(HeapTemplate{std::move(built), std::move(usedPlan), perDrawBindings ? merged.buffers : std::vector{}, perDrawBindings ? merged.images : std::vector{}, perDrawBindings ? merged.samplers : std::vector{}}); created->bytes = HeapTemplateBytes(*created); + created->tableRoles = HasTableRoles(created->plan); std::shared_ptr shared = std::move(created); if (!templates) { complete(shared); diff --git a/core/shader/recompiler/ShaderDiskCache.hpp b/core/shader/recompiler/ShaderDiskCache.hpp index bd6af52ff2db..0b6a0cbdeed9 100644 --- a/core/shader/recompiler/ShaderDiskCache.hpp +++ b/core/shader/recompiler/ShaderDiskCache.hpp @@ -13,7 +13,7 @@ namespace ShaderRecompiler::ShaderDiskCache { -inline constexpr std::uint32_t FormatVersion = 79; +inline constexpr std::uint32_t FormatVersion = 80; enum class LoadStatus { Loaded, diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index 43739023be7a..4c6ddba8dcc8 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -73,11 +73,17 @@ struct MemoryResourceAccess { std::uint32_t memoryAccess = 0; std::uint32_t misalignment = 0; bool physical = false; - bool clampedPhysical = false; bool softwareBounds = false; bool uniform = false; }; +struct PushedBufferVariables { + std::uint32_t plain = 0; + std::uint32_t coherent = 0; + std::uint32_t u64 = 0; + std::uint32_t uniform = 0; +}; + struct SpirvTableImageVariable { DescriptorBindingKind kind = DescriptorBindingKind::Buffers; std::uint32_t variable = 0; @@ -124,10 +130,7 @@ struct SpirvEmitterState { std::uint32_t heapDataUniformDwords = 0; bool uniformConstantBuffers = false; bool addressedBuffers = false; - std::vector pushedBufferVariables; - std::vector pushedBufferCoherentVariables; - std::vector pushedBufferU64Variables; - std::vector pushedBufferUniformVariables; + std::vector pushedBuffers; std::optional guestBuffersWritten; bool fragmentDescriptorSet = false; bool float16DenormPreserve = false; diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp index 1ad0c6c25689..234a36b7e25d 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvMemory/SpirvBufferAccess.hpp @@ -18,7 +18,6 @@ std::uint32_t EmitBufferRootDword(SpirvEmitterState& state, std::uint32_t buffer std::uint32_t EmitRootAddressWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); std::uint32_t EmitRootAddress(SpirvEmitterState& state, RuntimeAbi::RootItem item); -std::uint32_t EmitStageRingWordPointer(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index); std::uint32_t EmitFlattenedSrtLoad(SpirvEmitterState& state, std::uint32_t index); bool HasFlattenedSrt(const SpirvEmitterState& state); bool SplitUserData(const SpirvEmitterState& state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp index 8558f641ea7d..bd9c2de36939 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp @@ -2069,7 +2069,7 @@ ScalarBufferDword EmitScalarBufferDword(SpirvEmitterState& state, std::uint32_t std::uint32_t LoadTableMap(SpirvEmitterState& state, std::uint32_t index) { if (state.TableMapAddressed()) { const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, EmitStageRingWordPointer(state, RuntimeAbi::RootItem::TableMap, index), spv::MemoryAccessAlignedMask, 4u); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, EmitRootAddressReadOnlyWordPointer(state, RuntimeAbi::RootItem::TableMap, index), spv::MemoryAccessAlignedMask, 4u); return value; } const auto pointer = state.module.AllocateId(); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 32d240f10400..99062e1fce13 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -42,16 +42,28 @@ std::uint32_t EmitAlignedLoadU32(SpirvEmitterState& state, std::uint32_t pointer namespace { +std::uint32_t loadPushDword(SpirvEmitterState& state, std::uint32_t index) { + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), index); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); + return value; +} + +std::uint32_t loadStorageDword(SpirvEmitterState& state, std::uint32_t variable, std::uint32_t index) { + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, variable, ConstantU32(state, 0u), index); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); + return value; +} + std::uint32_t placedPushDword(SpirvEmitterState& state, std::uint32_t specialization, std::uint32_t word) { const auto u32 = TypeU32(state); const auto position = state.module.SpecializationConstant(u32, specialization, RuntimeAbi::NoPushPosition); const auto placed = Binary(state, spv::OpINotEqual, TypeBool(state), position, ConstantU32(state, RuntimeAbi::NoPushPosition)); const auto index = Select(state, u32, placed, Binary(state, spv::OpIAdd, u32, position, ConstantU32(state, word)), ConstantU32(state, 0u)); - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), index); - const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, u32, value, pointer); - return value; + return loadPushDword(state, index); } std::uint32_t overflowDword(SpirvEmitterState& state, std::uint32_t buffer, std::uint32_t word) { @@ -90,11 +102,7 @@ std::uint32_t EmitRootItemDword(SpirvEmitterState& state, RuntimeAbi::RootItem i } else { position = state.module.SpecializationConstant(u32, PipelineSpecialization::RootItemPositionBase + static_cast(item), 0u); } - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), word == 0u ? position : Binary(state, spv::OpIAdd, u32, position, ConstantU32(state, word))); - const auto value = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, u32, value, pointer); - return value; + return loadPushDword(state, word == 0u ? position : Binary(state, spv::OpIAdd, u32, position, ConstantU32(state, word))); } namespace { @@ -107,10 +115,7 @@ std::uint32_t EmitPushedDataSelect(SpirvEmitterState& state, std::uint32_t posit state.module.AddFunction(spv::OpULessThan, TypeBool(state), inside, ConstantU32(state, position), count); const auto index = state.module.AllocateId(); state.module.AddFunction(spv::OpSelect, u32, index, inside, Binary(state, spv::OpIAdd, u32, base, ConstantU32(state, position)), ConstantU32(state, 0u)); - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), index); - const auto pushedValue = state.module.AllocateId(); - state.module.AddFunction(spv::OpLoad, u32, pushedValue, pointer); + const auto pushedValue = loadPushDword(state, index); const auto value = state.module.AllocateId(); state.module.AddFunction(spv::OpSelect, u32, value, inside, pushedValue, ring); return value; @@ -125,12 +130,12 @@ std::uint32_t ComposeAddress64(SpirvEmitterState& state, const std::function(pushed - layout.pushedData.begin()), ring); } - const auto pointer = state.module.AllocateId(); - const auto value = state.module.AllocateId(); if (layout.UsesPushData()) { const auto base = state.module.SpecializationConstant(TypeU32(state), PipelineSpecialization::PushDataOffset, state.stencilReplay ? layout.pushDataStartDword % PushData::DwordCount : layout.pushDataStartDword); const auto index = Binary(state, spv::OpIAdd, TypeU32(state), Binary(state, spv::OpISub, TypeU32(state), base, ConstantU32(state, state.stencilReplay ? 0u : layout.PushSlotDword())), ConstantU32(state, dwordIndex)); - state.module.AddFunction(spv::OpAccessChain, TypePushConstantElementPointer(state), pointer, state.pushConstantVariable, ConstantU32(state, 0), index); - } else if (state.shaderDataStorageVariable != 0) { - state.module.AddFunction(spv::OpAccessChain, TypeStorageBufferElementPointer(state), pointer, state.shaderDataStorageVariable, ConstantU32(state, 0), ConstantU32(state, dwordIndex)); - } else { - FailEmit("shader data is neither in push constants nor in a storage buffer"); + return loadPushDword(state, index); } - state.module.AddFunction(spv::OpLoad, TypeU32(state), value, pointer); - return value; + if (state.shaderDataStorageVariable == 0) FailEmit("shader data is neither in push constants nor in a storage buffer"); + return loadStorageDword(state, state.shaderDataStorageVariable, ConstantU32(state, dwordIndex)); } void EmitMemoryOffsets(SpirvEmitterState& state) { @@ -480,7 +462,7 @@ std::uint32_t LdsStorageDwords(const SpirvEmitterState& state) { bool LoadsSelectable(const SpirvEmitterState& state, const MemoryResourceAccess& access) { if (access.kind == ResourceKind::Scratch) return true; - if (access.physical) return access.clampedPhysical; + if (access.physical) return false; if (access.softwareBounds) return true; if (access.kind == ResourceKind::Lds) return false; return state.robustBufferAccess2; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index 26204fbe315a..d1189853d549 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -498,6 +498,84 @@ void DefineOutputs(SpirvEmitterState& state) { namespace { +std::uint32_t UniformWordsBlockType(SpirvEmitterState& state, std::uint32_t elementType, std::uint32_t stride, std::uint32_t count) { + const auto array = state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, stride}}}, elementType, ConstantU32(state, count)); + return state.module.DecoratedType(spv::OpTypeStruct, {{spv::OpDecorate, {spv::DecorationBlock}}, {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}}, array); +} + +std::vector UniformConstantBufferWords(SpirvEmitterState& state, std::uint32_t count) { + std::vector uniformWords(count, 0u); + if (!state.uniformConstantBuffers) return uniformWords; + std::vector eligible(count, true); + std::vector end(count, 0u); + const auto& memory = state.program.Resources().memoryInfo; + for (const auto& block : state.program.Blocks()) { + for (const IrValue* inst : block->Instructions()) { + const auto op = inst->Opcode(); + if (op != IrOpcode::ReadConstBuffer && BufferAccessOf(op) == BufferAccess::None) continue; + const auto index = inst->Flags().index; + if (index >= memory.size()) continue; + const auto& info = memory[index]; + if (info.gpuDescriptor || info.planningOnly || (info.kind != ResourceKind::Buffer && info.kind != ResourceKind::ScalarBuffer)) continue; + const auto element = ResourceForDescriptor(state, DescriptorBindingKind::Buffers, info.resource); + if (element >= count) continue; + const auto* offset = inst->ArgumentCount() > 1u ? inst->Argument(1u) : nullptr; + if (op != IrOpcode::ReadConstBuffer || info.coherent || offset == nullptr || !offset->HasImmediate()) { + eligible[element] = false; + continue; + } + const auto byte = static_cast(offset->ImmediateU32()) + info.offset; + end[element] = std::max(end[element], static_cast(std::min((byte & ~std::uint64_t{3u}) + 8u, 0xffffffffu))); + } + } + for (std::uint32_t element = 0; element < count; ++element) { + const auto bytes = static_cast(end[element]) + RuntimeAbi::UniformViewAdjustmentLimit; + if (eligible[element] && end[element] != 0u && bytes <= RuntimeAbi::UniformConstantBufferBytes) uniformWords[element] = static_cast((bytes + 3u) / 4u); + } + return uniformWords; +} + +std::uint32_t DefinePushedBufferVariable(SpirvEmitterState& state, std::uint32_t pointee, std::uint32_t storage, std::uint32_t element, const std::string& name) { + const auto variable = state.module.DefineGlobalVariable(TypePointer(state, storage, pointee), storage); + state.module.AddName(variable, name.c_str()); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, RuntimeAbi::PushedBufferSet); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, element); + return variable; +} + +PushedBufferVariables DefinePushedStorageBuffer(SpirvEmitterState& state, std::uint32_t element) { + const auto storage = [&](std::uint32_t type, const char* name) { return DefinePushedBufferVariable(state, type, spv::StorageClassStorageBuffer, element, std::string(name) + "_" + std::to_string(element)); }; + const bool aliased = state.requirements.coherentBufferAlias || state.requirements.bufferU64View; + PushedBufferVariables variables; + variables.plain = storage(StorageBufferBlockType(state), "pushed_buffer"); + variables.coherent = state.requirements.coherentBufferAlias ? storage(StorageBufferBlockType(state), "pushed_buffer_coherent") : 0u; + variables.u64 = state.requirements.bufferU64View ? storage(StorageBufferU64BlockType(state), "pushed_buffer_u64") : 0u; + for (const auto variable : {variables.plain, variables.coherent, variables.u64}) { + if (variable != 0u && aliased) state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationAliased); + } + if (state.requirements.coherentBuffers) { + state.module.AddAnnotation(spv::OpDecorate, variables.coherent != 0u ? variables.coherent : variables.plain, spv::DecorationCoherent); + if (variables.u64 != 0u) state.module.AddAnnotation(spv::OpDecorate, variables.u64, spv::DecorationCoherent); + } + return variables; +} + +void DefinePushedBuffers(SpirvEmitterState& state, const IrBindingLayout& layout) { + state.addressedBuffers = true; + const auto count = layout.bufferAddressDwords / RuntimeAbi::BufferAddressWords; + const auto uniformWords = UniformConstantBufferWords(state, count); + for (std::uint32_t element = 0; element < count; ++element) { + PushedBufferVariables variables; + if (uniformWords[element] != 0u) { + const auto block = UniformWordsBlockType(state, TypeU32(state), 4u, uniformWords[element]); + variables.uniform = DefinePushedBufferVariable(state, block, spv::StorageClassUniform, element, "pushed_constant_buffer_" + std::to_string(element)); + } else { + variables = DefinePushedStorageBuffer(state, element); + } + state.pushedBuffers.push_back(variables); + } +} + std::uint32_t defineHeapArray(SpirvEmitterState& state, std::uint32_t slotCount, std::uint32_t elementType, const char* name, std::uint32_t heapKind) { const auto type = state.module.Type(spv::OpTypeArray, elementType, slotCount); const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniformConstant, type), spv::StorageClassUniformConstant); @@ -537,71 +615,7 @@ void DefineDescriptors(SpirvEmitterState& state) { switch (binding.kind) { case DescriptorBindingKind::Buffers: { if (layout.bufferAddressDwords != 0u) { - state.addressedBuffers = true; - const auto count = layout.bufferAddressDwords / RuntimeAbi::BufferAddressWords; - const auto pushedBuffer = [&](std::uint32_t type, std::uint32_t element, const char* name) { - const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassStorageBuffer, type), spv::StorageClassStorageBuffer); - state.module.AddName(variable, (std::string(name) + "_" + std::to_string(element)).c_str()); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, RuntimeAbi::PushedBufferSet); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, element); - return variable; - }; - const bool aliased = state.requirements.coherentBufferAlias || state.requirements.bufferU64View; - std::vector uniformWords(count, 0u); - if (state.uniformConstantBuffers) { - std::vector eligible(count, true); - std::vector end(count, 0u); - const auto& memory = state.program.Resources().memoryInfo; - for (const auto& block : state.program.Blocks()) { - for (const IrValue* inst : block->Instructions()) { - const auto op = inst->Opcode(); - if (op != IrOpcode::ReadConstBuffer && BufferAccessOf(op) == BufferAccess::None) continue; - const auto index = inst->Flags().index; - if (index >= memory.size()) continue; - const auto& info = memory[index]; - if (info.gpuDescriptor || info.planningOnly || (info.kind != ResourceKind::Buffer && info.kind != ResourceKind::ScalarBuffer)) continue; - const auto element = ResourceForDescriptor(state, DescriptorBindingKind::Buffers, info.resource); - if (element >= count) continue; - const auto* offset = inst->ArgumentCount() > 1u ? inst->Argument(1u) : nullptr; - if (op != IrOpcode::ReadConstBuffer || info.coherent || offset == nullptr || !offset->HasImmediate()) { - eligible[element] = false; - continue; - } - const auto byte = static_cast(offset->ImmediateU32()) + info.offset; - end[element] = std::max(end[element], static_cast(std::min((byte & ~std::uint64_t{3u}) + 8u, 0xffffffffu))); - } - } - for (std::uint32_t element = 0; element < count; ++element) { - const auto bytes = static_cast(end[element]) + RuntimeAbi::UniformViewAdjustmentLimit; - if (eligible[element] && end[element] != 0u && bytes <= RuntimeAbi::UniformConstantBufferBytes) uniformWords[element] = static_cast((bytes + 3u) / 4u); - } - } - for (std::uint32_t element = 0; element < count; ++element) { - if (uniformWords[element] != 0u) { - const auto array = state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 4u}}}, TypeU32(state), ConstantU32(state, uniformWords[element])); - const auto block = state.module.DecoratedType(spv::OpTypeStruct, {{spv::OpDecorate, {spv::DecorationBlock}}, {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}}, array); - const auto variable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniform, block), spv::StorageClassUniform); - state.module.AddName(variable, ("pushed_constant_buffer_" + std::to_string(element)).c_str()); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationDescriptorSet, RuntimeAbi::PushedBufferSet); - state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationBinding, element); - state.pushedBufferUniformVariables.push_back(variable); - state.pushedBufferVariables.push_back(0u); - state.pushedBufferCoherentVariables.push_back(0u); - state.pushedBufferU64Variables.push_back(0u); - continue; - } - state.pushedBufferUniformVariables.push_back(0u); - state.pushedBufferVariables.push_back(pushedBuffer(StorageBufferBlockType(state), element, "pushed_buffer")); - state.pushedBufferCoherentVariables.push_back(state.requirements.coherentBufferAlias ? pushedBuffer(StorageBufferBlockType(state), element, "pushed_buffer_coherent") : 0u); - state.pushedBufferU64Variables.push_back(state.requirements.bufferU64View ? pushedBuffer(StorageBufferU64BlockType(state), element, "pushed_buffer_u64") : 0u); - for (const auto variable : {state.pushedBufferVariables.back(), state.pushedBufferCoherentVariables.back(), state.pushedBufferU64Variables.back()}) { - if (variable != 0u && aliased) state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationAliased); - } - if (state.requirements.coherentBuffers) { - state.module.AddAnnotation(spv::OpDecorate, state.pushedBufferCoherentVariables.back() != 0u ? state.pushedBufferCoherentVariables.back() : state.pushedBufferVariables.back(), spv::DecorationCoherent); - if (state.pushedBufferU64Variables.back() != 0u) state.module.AddAnnotation(spv::OpDecorate, state.pushedBufferU64Variables.back(), spv::DecorationCoherent); - } - } + DefinePushedBuffers(state, layout); break; } state.storageBufferVariable = Define(ArrayType(StorageBufferBlockType(state)), "buffers"); @@ -638,16 +652,12 @@ void DefineDescriptors(SpirvEmitterState& state) { state.shaderDataStorageVariable = Define(StorageBufferBlockType(state), "shader_data"); state.module.AddAnnotation(spv::OpDecorate, state.shaderDataStorageVariable, spv::DecorationNonWritable); } else if (layout.ShaderDataDwords() != 0u && layout.ShaderDataDwords() <= state.heapDataUniformDwords) { - const auto vectors = (layout.ShaderDataDwords() + 3u) / 4u; - const auto array = state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 16u}}}, TypeU32Vector(state, 4), ConstantU32(state, vectors)); - const auto block = state.module.DecoratedType(spv::OpTypeStruct, {{spv::OpDecorate, {spv::DecorationBlock}}, {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}}, array); + const auto block = UniformWordsBlockType(state, TypeU32Vector(state, 4), 16u, (layout.ShaderDataDwords() + 3u) / 4u); state.shaderDataUniformVariable = Define(block, "shader_data", spv::StorageClassUniform); state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::ShaderData); } if (layout.UsesDataAddress() && SplitUserData(state) && layout.userDataRegisters.size() <= state.heapDataUniformDwords) { - const auto vectors = static_cast((layout.userDataRegisters.size() + 3u) / 4u); - const auto array = state.module.DecoratedType(spv::OpTypeArray, {{spv::OpDecorate, {spv::DecorationArrayStride, 16u}}}, TypeU32Vector(state, 4), ConstantU32(state, vectors)); - const auto block = state.module.DecoratedType(spv::OpTypeStruct, {{spv::OpDecorate, {spv::DecorationBlock}}, {spv::OpMemberDecorate, {0, spv::DecorationOffset, 0}}}, array); + const auto block = UniformWordsBlockType(state, TypeU32Vector(state, 4), 16u, static_cast((layout.userDataRegisters.size() + 3u) / 4u)); state.userDataUniformVariable = state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassUniform, block), spv::StorageClassUniform); state.module.AddName(state.userDataUniformVariable, "user_data"); state.module.AddAnnotation(spv::OpDecorate, state.userDataUniformVariable, spv::DecorationDescriptorSet, RuntimeAbi::GpuDataSet); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp index 06e2952586b7..4844967da20a 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvRuntimeBuffer.cpp @@ -233,19 +233,20 @@ MemoryResourceAccess directAccess(SpirvValueEmitContext& context, const IrValue& if (state.addressedBuffers) { const auto element = ResourceForDescriptor(state, DescriptorBindingKind::Buffers, memory.resource); const auto word = [&](std::uint32_t index) { return EmitBufferRootDword(state, element, index); }; - if (element >= state.pushedBufferVariables.size()) context.Fail(instruction, "a pushed buffer has no storage buffer variable"); - if (state.pushedBufferUniformVariables[element] != 0u) { + if (element >= state.pushedBuffers.size()) context.Fail(instruction, "a pushed buffer has no storage buffer variable"); + if (state.pushedBuffers[element].uniform != 0u) { if (instruction.Opcode() != IrOpcode::ReadConstBuffer || wide) context.Fail(instruction, "a pushed constant buffer is read by an access other than a scalar load"); MemoryResourceAccess access; access.kind = memory.kind; - access.objectPointer = state.pushedBufferUniformVariables[element]; + access.objectPointer = state.pushedBuffers[element].uniform; access.softwareBounds = true; access.uniform = true; access.length = Binary(state, spv::OpShiftRightLogical, TypeU32(state), word(2u), ConstantU32(state, 2u)); access.byteOffset = state.memoryByteOffsets.at(element); return access; } - const auto variable = wide ? state.pushedBufferU64Variables[element] : plainLoad || state.pushedBufferCoherentVariables[element] == 0u ? state.pushedBufferVariables[element] : state.pushedBufferCoherentVariables[element]; + const auto& pushed = state.pushedBuffers[element]; + const auto variable = wide ? pushed.u64 : plainLoad || pushed.coherent == 0u ? pushed.plain : pushed.coherent; if (variable == 0u) context.Fail(instruction, "a pushed buffer lacks the view this access needs"); MemoryResourceAccess access; access.kind = memory.kind; From 7b9806d8f4212d716b2380a24110799d9fe3cee6 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 08:28:53 +0530 Subject: [PATCH 230/269] perf(agc): restore the per-thread heap stage fit cache keyed by variant --- .../Execution/src/Driver/Draw/HeapStages.cpp | 38 +++++++++++++------ core/shader/recompiler/Recompiler.hpp | 11 ------ core/shader/recompiler/ShaderDiskCache.cpp | 2 +- 3 files changed, 28 insertions(+), 23 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index abc57cbd9e18..cfea038b9db1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -208,6 +208,8 @@ std::string heapClassesFailure(const ShaderRecompiler::RecompileResult& result) return {}; } +constexpr std::size_t ThreadCacheLimit = 65536u; + std::string heapStageFailure(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { if (auto failure = heapClassesFailure(result); !failure.empty()) return failure; std::pair refused{}; @@ -217,25 +219,39 @@ std::string heapStageFailure(const ShaderRecompiler::RecompileResult& result, bo return {}; } -bool knownHeapStageFits(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { - constexpr std::uint64_t Fits = 2, Fails = 1, VerdictBits = 2; - auto& memo = result.heapMappableMemo.verdicts[workgroupAddress ? 1 : 0]; - const auto capacity = Graphics::BindlessHeap::ImageSlotCapacity(); - const auto known = memo.load(std::memory_order_relaxed); - if (known != 0 && known >> VerdictBits == capacity) return (known & 3u) == Fits; - const bool fits = heapStageFailure(result, workgroupAddress).empty(); - memo.store(static_cast(capacity) << VerdictBits | (fits ? Fits : Fails), std::memory_order_relaxed); - return fits; +const std::string& knownHeapStageFailure(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { + struct MappableStorage {}; + struct RecentStorage {}; + struct Recent { + std::uint64_t key = 0; + const std::string* failure = nullptr; + }; + constexpr std::size_t RecentSlots = 64; + auto& known = HostThreadLocal, MappableStorage>(); + auto& recent = HostThreadLocal, RecentStorage>(); + const auto key = result.variantId * 2u + (workgroupAddress ? 1u : 0u); + auto& slot = recent[(key ^ (key >> 17u)) % RecentSlots]; + if (slot.failure != nullptr && slot.key == key) return *slot.failure; + auto found = known.find(key); + if (found == known.end()) { + if (known.size() >= ThreadCacheLimit) { + known.clear(); + recent.fill({}); + } + found = known.emplace(key, heapStageFailure(result, workgroupAddress)).first; + } + slot = {key, &found->second}; + return found->second; } } void RequireHeapStageMappable(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { - if (!knownHeapStageFits(result, workgroupAddress)) throw std::runtime_error(heapStageFailure(result, workgroupAddress)); + if (const auto& failure = knownHeapStageFailure(result, workgroupAddress); !failure.empty()) throw std::runtime_error(failure); } bool HeapStageFits(const ShaderRecompiler::RecompileResult& result, bool workgroupAddress) { - return knownHeapStageFits(result, workgroupAddress); + return knownHeapStageFailure(result, workgroupAddress).empty(); } bool HeapStageExcluded(ShaderRecompiler::ShaderStage stage) { diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index f3afff331080..fc7084748938 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -546,16 +546,6 @@ struct IdentityMemo { } }; -struct HeapMappableMemo { - mutable std::atomic verdicts[2]{}; - HeapMappableMemo() = default; - HeapMappableMemo(const HeapMappableMemo&) {} - HeapMappableMemo& operator=(const HeapMappableMemo&) { - for (auto& verdict : verdicts) verdict.store(0, std::memory_order_relaxed); - return *this; - } -}; - [[nodiscard]] bool VerifyIdentityMemo(); struct HeapStageWords { @@ -1053,7 +1043,6 @@ struct RecompileResult : CompiledShaderArtifact, ShaderInvocation { std::vector shaderDataUserWords; [[nodiscard]] std::uint64_t PipelineVariantId() const { return specializationId != 0 ? specializationId : variantId; } IdentityMemo identityMemo; - HeapMappableMemo heapMappableMemo; [[nodiscard]] PipelineIdentity Identity() const { if (!identityMemo.sealed.load(std::memory_order_acquire)) return ComputeIdentity(); const auto module = spirv.ContentHash(); diff --git a/core/shader/recompiler/ShaderDiskCache.cpp b/core/shader/recompiler/ShaderDiskCache.cpp index 37461138e540..ee060507daad 100644 --- a/core/shader/recompiler/ShaderDiskCache.cpp +++ b/core/shader/recompiler/ShaderDiskCache.cpp @@ -90,7 +90,7 @@ namespace ShaderRecompiler::ShaderDiskCache { static_assert(sizeof(CompiledShaderArtifact) == 336, "CompiledShaderArtifact changed: update the artifact encoder"); static_assert(sizeof(ShaderInvocation) == 240, "ShaderInvocation changed: update the invocation encoder"); #if defined(__cpp_lib_atomic_shared_ptr) -static_assert(sizeof(RecompileResult) == 712, "RecompileResult changed: update EncodeResult and DecodeResult"); +static_assert(sizeof(RecompileResult) == 696, "RecompileResult changed: update EncodeResult and DecodeResult"); #endif static_assert(sizeof(DescriptorBinding) == 912, "DescriptorBinding changed: update the binding encoder"); static_assert(sizeof(VertexAttribute) == 32, "VertexAttribute changed: update the attribute encoder"); From 4d967da88ba4967eb527bd28a1e770df0a7b67b2 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 12:13:50 +0530 Subject: [PATCH 231/269] fix(agc): name the changed-copy bind site in the GPU heap report --- .../prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 006609cbc96c..f2d379611d5f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -12,6 +12,7 @@ #include "SpirvBackend/SpirvAnalysis.hpp" #include "prx/libc/include/HostThreadLocal.hpp" #include +#include #include #include #include @@ -1280,9 +1281,14 @@ std::size_t heapRecordIndex(bool compute, bool heap) { std::array, static_cast(HeapStageReason::Count)> heapStageReasons{}; constexpr std::array(HeapStageReason::Count)> HeapStageReasonNames{"heap", "disabled", "excluded"}; constexpr std::array(SetBindSite::Count)> SetBindSiteNames{"draw", "dispatch", "detiler", - "color transfer", "presentation", "depth transfer", "staged merge", "first-sample copy"}; + "color transfer", "presentation", "depth transfer", "staged merge", "first-sample copy", "changed copy"}; constexpr std::array(HeapExcluded::Count)> HeapExcludedNames{"draw excluded", "dispatch excluded"}; +constexpr bool AllNamed(std::span names) { + return std::ranges::none_of(names, [](const char* name) { return name == nullptr; }); +} +static_assert(AllNamed(HeapStageReasonNames) && AllNamed(SetBindSiteNames) && AllNamed(HeapExcludedNames), "every counter needs a name"); + std::uint64_t takeCount(std::atomic& counter) { return counter.exchange(0, std::memory_order_relaxed); } From c7ec10aa5e4dc510a940323a705ad39b059c7db8 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 23:21:41 +0530 Subject: [PATCH 232/269] perf(agc): read heap SRT and buffer overflow records through mapped uniform blocks Heap stages read the flattened SRT and the overflow buffer records through uniform blocks mapped at their push-data addresses, as vkd3d-proton maps root descriptors, instead of through raw device pointers. A heap stage keeps up to 16 buffer records in push data (was 4); pixel-stage records stay above the pre-rasterization roots so fragment libraries are still shared. --- .../Graphics/src/BindlessHeap.cpp | 20 ++++++++++++++++-- .../Graphics/src/ShaderResources.cpp | 2 +- .../Graphics/src/ShaderValidation.cpp | 5 +++-- .../tests/PushDataPlacements.cpp | 5 ++++- .../src/DescriptorBindingBuilder.cpp | 3 ++- .../recompiler/PipelineSpecialization.hpp | 2 +- core/shader/recompiler/PushDataLayout.hpp | 8 +++++-- core/shader/recompiler/RuntimeAbi.hpp | 5 +++-- .../SpirvBackend/SpirvEmitterState.hpp | 2 ++ .../src/SpirvMemory/SpirvBufferAccess.cpp | 21 ++++++++++++------- .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 17 +++++++++++++-- docs/dev/ENVIRONMENT.md | 2 +- 12 files changed, 69 insertions(+), 23 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index f2d379611d5f..f3798c38556d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -984,6 +984,7 @@ struct HeapBindingUse { std::vector dataUniforms; std::vector embeddedSamplers; std::vector pushedBuffers; + bool overflowRecords = false; std::pair refused{~0u, ~0u}; }; @@ -1040,7 +1041,8 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& continue; } const auto dataKind = binding % bindingCount; - const bool dataBlock = dataKind == static_cast(Abi::Binding::ShaderData) || dataKind == static_cast(Abi::Binding::UserData); + const bool dataBlock = dataKind == static_cast(Abi::Binding::ShaderData) || dataKind == static_cast(Abi::Binding::UserData) || + dataKind == static_cast(Abi::Binding::FlattenedSrt); if (set == Abi::GpuDataSet && dataBlock && binding / bindingCount < Abi::StageCount) { use.dataUniforms.push_back(binding); continue; @@ -1049,6 +1051,10 @@ bool heapBindings(std::span spirv, const HeapBindingRoots& use.embeddedSamplers.push_back(binding); continue; } + if (set == Abi::PushedBufferSet && binding == Abi::PushedBufferOverflowBinding) { + use.overflowRecords = true; + continue; + } if (set == Abi::PushedBufferSet) { if (std::ranges::find(use.pushedBuffers, binding) == use.pushedBuffers.end()) use.pushedBuffers.push_back(binding); continue; @@ -1105,11 +1111,20 @@ VkDescriptorSetAndBindingMappingEXT pushedBufferMapping(std::uint32_t binding, c } VkDescriptorSetAndBindingMappingEXT dataUniformMapping(std::uint32_t binding, const ShaderRecompiler::StagePushPlacement* placement) { - const bool user = binding % static_cast(Abi::Binding::Count) == static_cast(Abi::Binding::UserData); + const auto kind = binding % static_cast(Abi::Binding::Count); + if (kind == static_cast(Abi::Binding::FlattenedSrt)) + return HeapPushAddressMapping(Abi::GpuDataSet, binding, rootItemOffset(placement, Abi::RootItem::SrtAddress), VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT); + const bool user = kind == static_cast(Abi::Binding::UserData); const bool userPlaced = user && placement != nullptr && placement->Item(Abi::RootItem::UserData) != Abi::NoPushPosition; return HeapPushAddressMapping(Abi::GpuDataSet, binding, rootItemOffset(placement, userPlaced ? Abi::RootItem::UserData : Abi::RootItem::ShaderData), VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT); } +VkDescriptorSetAndBindingMappingEXT overflowRecordsMapping(const ShaderRecompiler::StagePushPlacement* placement) { + Require(placement != nullptr, "a heap mapping reads buffer overflow records without a push layout"); + const auto offset = placement->bufferOverflow != Abi::NoPushPosition ? placement->bufferOverflow * static_cast(sizeof(std::uint32_t)) : rootItemOffset(placement, Abi::RootItem::ShaderData); + return HeapPushAddressMapping(Abi::PushedBufferSet, Abi::PushedBufferOverflowBinding, offset, VK_SPIRV_RESOURCE_TYPE_UNIFORM_BUFFER_BIT_EXT); +} + } bool DescriptorHeapMappable(std::span spirv, const HeapBindingRoots& roots, std::pair* refused) { @@ -1225,6 +1240,7 @@ bool BindlessHeap::DescriptorHeapMappings(std::span spirv, for (const auto binding : use.dataUniforms) mappings.push_back(dataUniformMapping(binding, placement)); std::ranges::sort(use.pushedBuffers); for (const auto binding : use.pushedBuffers) mappings.push_back(pushedBufferMapping(binding, placement)); + if (use.overflowRecords) mappings.push_back(overflowRecordsMapping(placement)); if (use.workgroupMemory) mappings.push_back(HeapPushAddressMapping(ShaderRecompiler::GpuWorkgroupMemoryDescriptorSet, 0, workgroupAddressOffset, VK_SPIRV_RESOURCE_TYPE_READ_WRITE_STORAGE_BUFFER_BIT_EXT)); if (use.scratchPoolMemory) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 457367690738..3bfc2fd82172 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -7971,7 +7971,7 @@ void ShaderResources::writePushedBuffers(std::span(std::min(range.size, 0xffffffffu)); }; const auto record = [&](VkDeviceAddress address, std::uint32_t size) { - Require(address % uniformAlignment == 0, "a pushed buffer address is off the uniform buffer offset alignment"); + Require((address & (uniformAlignment - 1u)) == 0u, "a pushed buffer address is off the uniform buffer offset alignment"); return std::array{static_cast(address), static_cast(address >> 32u), size, 0u}; }; const auto encode = [&](const VkDeviceAddressRangeEXT& range) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index b33cab3648af..c2ec02544701 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -651,8 +651,9 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi constexpr auto bindingCount = static_cast(Abi::Binding::Count); const auto kind = decoration.binding ? *decoration.binding % bindingCount : bindingCount; Require(shader.dataAddressPush && decoration.set && decoration.binding && *decoration.set == Abi::GpuDataSet && - (kind == static_cast(Abi::Binding::ShaderData) || kind == static_cast(Abi::Binding::UserData)), - "a uniform buffer is only the GPU heap's shader data or user data"); + (kind == static_cast(Abi::Binding::ShaderData) || kind == static_cast(Abi::Binding::UserData) || + kind == static_cast(Abi::Binding::FlattenedSrt)), + "a uniform buffer is only the GPU heap's shader data, user data or flattened SRT"); } else { Require(variable.storage == spv::StorageClassStorageBuffer && decoration.set && decoration.binding, "unsupported or unbound shader resource"); const auto key = std::make_pair(*decoration.set, *decoration.binding); diff --git a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp index 979dcf2ac810..521ccef0ed7f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp @@ -1,3 +1,4 @@ +#include #include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include "PushDataLayout.hpp" #include "RuntimeAbi.hpp" @@ -236,7 +237,9 @@ int main() { const std::vector typical{{ShaderStage::Vertex, vertexItems, 6, buffers}, {ShaderStage::Fragment, pixelItems, 20, buffers}}; const auto roomy = place(typical); disjoint(typical, roomy, 0, ("typical stages with " + std::to_string(buffers) + " buffers each").c_str()); - require(!defaultCap || (buffers > Abi::PushedBufferLimit) == (roomy[1].bufferOverflow != Abi::NoPushPosition), "a typical pixel stage overflows only buffers past the push limit"); + const auto kept = static_cast(std::count_if(roomy[1].bufferRoots.begin(), roomy[1].bufferRoots.end(), [](std::uint32_t root) { return root != Abi::NoPushPosition; })); + require(!defaultCap || (buffers > kept) == (roomy[1].bufferOverflow != Abi::NoPushPosition), "a typical pixel stage overflows only the buffers it cannot keep in push data"); + require(!defaultCap || kept >= std::min(buffers, 8u), "a typical pixel stage keeps at least eight buffer records in push data"); const auto alone = place({typical[1]})[0]; require(alone.items == roomy[1].items && alone.bufferRoots == roomy[1].bufferRoots && alone.bufferOverflow == roomy[1].bufferOverflow, "a typical pixel stage with buffers is placed as it is alone, so its fragment library is shared"); const std::vector tessellation{{ShaderStage::Local, all & ~stencil, 4, buffers}, {ShaderStage::TessellationControl, all & ~stencil, 3, buffers}, {ShaderStage::TessellationEvaluation, (all & ~stencil) | Abi::DepthRemapPushBit, 10, buffers}, {ShaderStage::Fragment, all, 48, buffers}}; diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index f0d08f85d6a8..7b76450a3461 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -27,7 +27,8 @@ static_assert(PipelineSpecialization::FoldOffsetBase + ShaderInfo::MaxSamplers < static_assert(PipelineSpecialization::UnnormalizedBaseLevelBase + ShaderInfo::MaxSamplers <= PipelineSpecialization::MirrorUnnormalizedBase); static_assert(PipelineSpecialization::MirrorUnnormalizedBase + ShaderInfo::MaxSamplers <= PipelineSpecialization::MinLodBase); static_assert(PipelineSpecialization::MinLodBase + ShaderInfo::MaxImages <= PipelineSpecialization::SamplerLodBiasBase); -static_assert(PipelineSpecialization::SamplerLodBiasBase + ShaderInfo::MaxSamplers <= PipelineSpecialization::FmaskFormatBase); +static_assert(PipelineSpecialization::SamplerLodBiasBase + ShaderInfo::MaxSamplers <= PipelineSpecialization::BufferRootPosition); +static_assert(PipelineSpecialization::BufferOverflowPosition < PipelineSpecialization::FmaskFormatBase); static_assert(PipelineSpecialization::FmaskFormatBase + ShaderInfo::MaxImages <= PipelineSpecialization::VolumeGatherBase); static_assert(PipelineSpecialization::VolumeGatherBase + ShaderInfo::MaxImages <= PipelineSpecialization::ImageComponentBase); static_assert(PipelineSpecialization::ImageComponentBase + ShaderInfo::MaxImages <= PipelineSpecialization::NormalizedImageBase); diff --git a/core/shader/recompiler/PipelineSpecialization.hpp b/core/shader/recompiler/PipelineSpecialization.hpp index 7e5d38a4931e..cf070afe8413 100644 --- a/core/shader/recompiler/PipelineSpecialization.hpp +++ b/core/shader/recompiler/PipelineSpecialization.hpp @@ -51,7 +51,7 @@ inline constexpr std::uint32_t MipCountBase = 8320u; inline constexpr std::uint32_t StoreQuantizeBase = 12288u; inline constexpr std::uint32_t StoreQuantizeWords = 4u; inline constexpr std::uint32_t BufferRootPosition = 57856u; -inline constexpr std::uint32_t BufferRootCount = 4u; +inline constexpr std::uint32_t BufferRootCount = 16u; inline constexpr std::uint32_t BufferOverflowPosition = BufferRootPosition + BufferRootCount; inline constexpr std::uint32_t DescriptorIndexBase = 16384u; inline constexpr std::uint32_t DescriptorIndexStride = 128u; diff --git a/core/shader/recompiler/PushDataLayout.hpp b/core/shader/recompiler/PushDataLayout.hpp index 89f6fc9f8793..96271938331a 100644 --- a/core/shader/recompiler/PushDataLayout.hpp +++ b/core/shader/recompiler/PushDataLayout.hpp @@ -91,6 +91,8 @@ class PushDataPlacer { static constexpr std::uint32_t optionalItems = RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::UserData); static constexpr std::array parts{PushPart::Fragment, PushPart::Compute, PushPart::PreRasterization}; + static constexpr std::uint32_t fragmentRecordFloor = 2u * RuntimeAbi::RootItemCount; + static bool Top(PushPart part) { return part != PushPart::PreRasterization; } bool IsFree(std::uint32_t first, std::uint32_t width) const { @@ -100,9 +102,10 @@ class PushDataPlacer { return true; } - std::uint32_t TryTake(std::uint32_t width, bool aligned, bool top) { + std::uint32_t TryTake(std::uint32_t width, bool aligned, bool top, std::uint32_t floor = 0u) { for (std::uint32_t step = 0; step + width <= total; ++step) { const auto first = top ? total - width - step : step; + if (first < floor) break; if ((aligned && first % 2u != 0u) || !IsFree(first, width)) continue; for (auto dword = first; dword < first + width; ++dword) used |= 1ull << dword; return first; @@ -179,9 +182,10 @@ class PushDataPlacer { const auto buffers = stages[index].pushedBuffers; if (buffers == 0u) return; const auto records = RecordsOf(index); + const auto floor = stages[index].part == PushPart::Fragment ? fragmentRecordFloor : 0u; bool overflowed = buffers > records; for (std::uint32_t buffer = 0; buffer < records; ++buffer) { - placements[index].bufferRoots[buffer] = TryTake(RuntimeAbi::PushedBufferWords, true, top); + placements[index].bufferRoots[buffer] = TryTake(RuntimeAbi::PushedBufferWords, true, top, floor); overflowed = overflowed || placements[index].bufferRoots[buffer] == RuntimeAbi::NoPushPosition; } if (overflowed && overflows[index] == RuntimeAbi::NoPushPosition) throw std::runtime_error("the push data has no room for a stage's buffer addresses"); diff --git a/core/shader/recompiler/RuntimeAbi.hpp b/core/shader/recompiler/RuntimeAbi.hpp index 634a2c4d2cc9..178978f3bc16 100644 --- a/core/shader/recompiler/RuntimeAbi.hpp +++ b/core/shader/recompiler/RuntimeAbi.hpp @@ -9,7 +9,7 @@ namespace ShaderRecompiler::RuntimeAbi { -inline constexpr std::uint32_t Version = 17u; +inline constexpr std::uint32_t Version = 18u; inline constexpr std::uint32_t DescriptorSet = 0u; inline constexpr std::uint32_t FragmentDescriptorSet = 1u; inline constexpr std::uint32_t StageCount = 4u; @@ -26,8 +26,9 @@ inline constexpr std::uint32_t FirstAtomic64ImageBinding = FirstStorageImageBind inline constexpr std::uint32_t SamplerSlotWords = 2u; inline constexpr std::uint32_t BufferAddressWords = 4u; inline constexpr std::uint32_t PushedBufferWords = 3u; -inline constexpr std::uint32_t PushedBufferLimit = 4u; +inline constexpr std::uint32_t PushedBufferLimit = 16u; inline constexpr std::uint32_t OverflowRecordWords = 4u; +inline constexpr std::uint32_t PushedBufferOverflowBinding = 1023u; inline constexpr bool AtomicImageKind(std::uint32_t kind) { return kind >= FirstAtomicImageBinding && kind < FirstAtomic64ImageBinding; } inline constexpr bool Atomic64ImageKind(std::uint32_t kind) { return kind >= FirstAtomic64ImageBinding && kind < FirstImageBinding + ImageBindingCount; } inline constexpr bool UintStorageImageKind(std::uint32_t kind) { return kind >= FirstUintStorageImageBinding && kind < FirstAtomicImageBinding; } diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index 4c6ddba8dcc8..f52ebe68a918 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -250,6 +250,8 @@ struct SpirvEmitterState { std::uint32_t shaderDataStorageVariable = 0; std::uint32_t shaderDataUniformVariable = 0; std::uint32_t userDataUniformVariable = 0; + std::uint32_t flattenedSrtUniformVariable = 0; + std::uint32_t bufferOverflowUniformVariable = 0; std::uint32_t pushItems = 0; std::unordered_map heapSlotVariables; std::uint32_t flattenedSrtVariable = 0; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp index 99062e1fce13..8c1c9829f655 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvBufferAccess.cpp @@ -67,13 +67,15 @@ std::uint32_t placedPushDword(SpirvEmitterState& state, std::uint32_t specializa } std::uint32_t overflowDword(SpirvEmitterState& state, std::uint32_t buffer, std::uint32_t word) { - const auto address = ComposeAddress64(state, [&] { return placedPushDword(state, PipelineSpecialization::BufferOverflowPosition, 0u); }, [&] { return placedPushDword(state, PipelineSpecialization::BufferOverflowPosition, 1u); }); - const auto words = ReadOnlyStorageBufferType(state, TypeU32(state), 4u); - const auto block = state.module.AllocateId(); - state.module.AddFunction(spv::OpConvertUToPtr, TypePointer(state, spv::StorageClassPhysicalStorageBuffer, words), block, address); - const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, TypePhysicalU32Pointer(state), pointer, block, ConstantU32(state, 0u), ConstantU32(state, buffer * RuntimeAbi::OverflowRecordWords + word)); - return EmitAlignedLoadU32(state, pointer); + if (state.bufferOverflowUniformVariable == 0u) FailEmit("a stage reads buffer overflow records without the records block"); + const auto u32x4 = TypeU32Vector(state, 4); + const auto element = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassUniform, u32x4), element, state.bufferOverflowUniformVariable, ConstantU32(state, 0u), ConstantU32(state, buffer)); + const auto record = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, u32x4, record, element); + const auto value = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), value, record, word); + return value; } } @@ -166,7 +168,10 @@ std::uint32_t EmitRootAddressReadOnlyWordPointer(SpirvEmitterState& state, Runti namespace { std::uint32_t dataAddressLoad(SpirvEmitterState& state, RuntimeAbi::RootItem item, std::uint32_t index) { - const auto uniform = item == RuntimeAbi::RootItem::ShaderData ? state.shaderDataUniformVariable : item == RuntimeAbi::RootItem::UserData ? state.userDataUniformVariable : 0u; + const auto uniform = item == RuntimeAbi::RootItem::ShaderData ? state.shaderDataUniformVariable + : item == RuntimeAbi::RootItem::UserData ? state.userDataUniformVariable + : item == RuntimeAbi::RootItem::SrtAddress ? state.flattenedSrtUniformVariable + : 0u; if (uniform != 0u) { const auto u32 = TypeU32(state); const auto vector = Binary(state, spv::OpShiftRightLogical, u32, index, ConstantU32(state, 2u)); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index d1189853d549..a33e77444d4b 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -574,6 +574,11 @@ void DefinePushedBuffers(SpirvEmitterState& state, const IrBindingLayout& layout } state.pushedBuffers.push_back(variables); } + if (count != 0u) { + const auto block = UniformWordsBlockType(state, TypeU32Vector(state, 4), RuntimeAbi::OverflowRecordWords * 4u, count); + state.bufferOverflowUniformVariable = DefinePushedBufferVariable(state, block, spv::StorageClassUniform, RuntimeAbi::PushedBufferOverflowBinding, "buffer_overflow"); + state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::ShaderData); + } } std::uint32_t defineHeapArray(SpirvEmitterState& state, std::uint32_t slotCount, std::uint32_t elementType, const char* name, std::uint32_t heapKind) { @@ -666,8 +671,16 @@ void DefineDescriptors(SpirvEmitterState& state) { } break; case DescriptorBindingKind::FlattenedSrt: - if (layout.UsesDataAddress()) state.flattenedSrtAddressed = true; - else { + if (layout.UsesDataAddress()) { + state.flattenedSrtAddressed = true; + const auto& resources = state.program.Resources(); + const auto dwords = resources.srtGuardOffset + static_cast(resources.guardedSrtSlots.size()); + if (dwords != 0u && dwords <= state.heapDataUniformDwords) { + const auto block = UniformWordsBlockType(state, TypeU32Vector(state, 4), 16u, (dwords + 3u) / 4u); + state.flattenedSrtUniformVariable = Define(block, "flattened_srt", spv::StorageClassUniform); + state.pushItems |= RuntimeAbi::RootItemBit(RuntimeAbi::RootItem::SrtAddress); + } + } else { state.flattenedSrtVariable = Define(StorageBufferBlockType(state), "flattened_srt"); state.module.AddAnnotation(spv::OpDecorate, state.flattenedSrtVariable, spv::DecorationNonWritable); } diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index ed24961f069d..bc550fa2adc4 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -472,7 +472,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_PROFILE_DRAW` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp` | | prints the per-phase driver and draw timing totals | | `APS5_PROFILE_GPU` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records the GPU time of recorded work by key from batch timestamps | | `APS5_PROFILE_GPU_DRAWS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp`, `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | with APS5_PROFILE_GPU, records the GPU time of each recorded draw by its fragment program's variant id and prints a [drawvariant] line with the code address behind each variant id once (draws that do not use a recipe only; the [gputime] line labels each `draw 0x`, the id [drawvariant] prints, and the ranges share the batch's query cap) | -| `APS5_PUSHED_BUFFER_RECORDS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 4 | test cap on the guest buffer records a heap stage keeps in its push data; the rest go to its per-draw overflow block | +| `APS5_PUSHED_BUFFER_RECORDS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 16 | test cap on the guest buffer records a heap stage keeps in its push data; the rest go to its per-draw overflow block | | `APS5_READONLY_DEPTH_BOUNDS_COMPARE` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp` | 0 | `1` enables a read-only GREATER_OR_EQUAL comparison at viewport depth 1 for eligible single-sample D32S8 draws with native depth bounds; read once per process; unset or `0` keeps the normal path | | `APS5_REAP_EACH_PACKET` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/DeferredLabels.cpp` | | reaps deferred labels after every packet | | `APS5_REGISTRATION_PREPARE_COMMIT_GB` | number | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp` | half of physical RAM | stops preparing newly registered shaders ahead of use when process-private memory reaches this GiB budget; `0` disables registration-time preparation | From c42be1f6e19e69d17aa193bfc6486ed4896f9c24 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 23:32:57 +0530 Subject: [PATCH 233/269] perf(agc): read heap walk table ranges in bulk The heap stage walk gave the SRT walker only a word reader, so image-table key scans and descriptor runs were read one word at a time, with an accessibility query per page. Give it the bulk reader the per-draw capture already has: one accessibility query per range (per page as the fallback), one copy and one recorded read range per page. The same words are read. A per-pixel bindless table of 4096 entries now walks in 26.5 us instead of 192 us per stage, against 30 us for the per-draw capture. --- .../Execution/src/Driver/Draw/HeapStages.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index cfea038b9db1..87f8b5eb5fa4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -10,6 +10,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include "prx/libc/include/HostThreadLocal.hpp" #include +#include #include #include #include @@ -362,6 +363,36 @@ bool readWalkWord(void* context, std::uint64_t address, std::uint32_t* value) { return true; } +bool readWalkWords(void* context, std::uint64_t address, std::uint32_t* values, std::uint64_t count) { + auto& reads = *static_cast(context); + if (address % WordBytes != 0u || count > (std::numeric_limits::max() - address) / WordBytes) { + reads.failed = true; + return false; + } + const auto first = address & ~(WalkPageBytes - 1u); + const auto past = (address + count * WordBytes + WalkPageBytes - 1u) & ~(WalkPageBytes - 1u); + if (count != 0u && past > first && !reads.Verified(address, count * WordBytes) && GuestMemory::Accessible(reinterpret_cast(first), static_cast(past - first))) reads.Verify(first, past - first); + while (count != 0u) { + const auto page = address & ~(WalkPageBytes - 1u); + const auto words = std::min(count, (page + WalkPageBytes - address) / WordBytes); + const auto bytes = words * WordBytes; + if (!reads.Verified(address, bytes)) { + if (GuestMemory::Accessible(reinterpret_cast(page), WalkPageBytes)) reads.Verify(page, WalkPageBytes); + else if (!GuestMemory::Accessible(reinterpret_cast(address), static_cast(bytes))) { + reads.failed = true; + return false; + } + } + std::memcpy(values, reinterpret_cast(address), static_cast(bytes)); + if (!reads.runs.empty() && address >= reads.runs.back().first && address <= reads.runs.back().second) reads.runs.back().second = std::max(reads.runs.back().second, address + bytes); + else reads.runs.emplace_back(address, address + bytes); + address += bytes; + values += words; + count -= words; + } + return true; +} + bool walkAccessible(void* context, std::uint64_t address, std::uint64_t bytes) { auto& reads = *static_cast(context); if (bytes != 0 && reads.Verified(address, bytes)) return true; @@ -400,6 +431,7 @@ captureWalk(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::s runtime.shaderBase = shaderBase; runtime.userContext = &reads; runtime.readMemory = readWalkWord; + runtime.readWords = readWalkWords; runtime.accessible = walkAccessible; return invocation.Capture(runtime); } From f81c5f2f41c28ad09ac6568d409ed7dfe7ddf9af Mon Sep 17 00:00:00 2001 From: raghav314 Date: Sun, 15 Nov 2026 23:42:53 +0530 Subject: [PATCH 234/269] perf(agc): reuse unwritten image tables in the heap stage walk The per-draw capture skips re-reading an image table the guest has not written since its memo was taken (stampWrites, unchangedSince, supplyWords); the heap stage walk had none of these hooks, so it re-read and re-compared every bindless table on every draw. Give the walk the same hooks. The walk records the memo's words as the stage's read values for a reused table, so a later guest write is always seen as a change, and copies live memory only around them. A walk that declines only because its own hooks collected writes walks once more with a fresh write snapshot. A 4096-entry per-pixel table on write-tracked memory now walks in 6.0 us per stage instead of 26 us (192 us before the bulk reader); the per-draw capture takes 3.5 us. agc_driver_heap_table_walk_reuse checks that an unwritten table is reused with the same words and that a rewritten descriptor is re-read and matches a full capture. --- .../Execution/src/Driver/Draw/HeapStages.cpp | 121 ++++++++++++-- ...c_driver_heap_table_walk_reuse_tests.cmake | 7 + .../tests/execution/HeapTableWalkReuse.cpp | 157 ++++++++++++++++++ 3 files changed, 268 insertions(+), 17 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_table_walk_reuse_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 87f8b5eb5fa4..cfb3e58bfa53 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -5,9 +5,11 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" +#include "prx/libc/include/GuestAllocations.hpp" #include "prx/libc/include/HostThreadLocal.hpp" #include #include @@ -321,6 +323,9 @@ constexpr std::size_t WalkVerifiedSpans = 8; struct WalkReads { AddressRanges runs; + const Graphics::Recorder::WriteRanges* before = nullptr; + std::vector> supplied; + bool collected = false; std::array, WalkVerifiedSpans> verified{}; std::size_t verifiedCount = 0; std::size_t verifiedNext = 0; @@ -328,6 +333,8 @@ struct WalkReads { void Reset() { runs.clear(); + supplied.clear(); + collected = false; failed = false; verifiedCount = 0; verifiedNext = 0; @@ -393,6 +400,54 @@ bool readWalkWords(void* context, std::uint64_t address, std::uint32_t* values, return true; } +bool walkPending(const WalkReads& reads, std::uint64_t address, std::uint64_t bytes) { + const std::array range{std::pair{address, address + bytes}}; + const bool queuedWrite = DrawPipeline::Active() && DrawPipeline::Queue0().Busy() && DrawPipeline::Queue0().OverlapsAny(range); + return queuedWrite || !Graphics::Recorder::ReadsSettled(range, reads.before); +} + +ShaderRecompiler::SrtWriteStamp stampWalkWrites(void* context, std::uint64_t address, std::uint64_t bytes) { + auto& reads = *static_cast(context); + if (bytes == 0u || address > std::numeric_limits::max() - bytes) return {}; + reads.collected = true; + GuestMemory::FlushGpuWrites(address, static_cast(bytes)); + const auto layout = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); + const auto generation = GuestMemory::CollectWrites(address, static_cast(bytes)); + if (generation == 0u || walkPending(reads, address, bytes)) return {}; + return {generation, layout}; +} + +bool walkUnchangedSince(void* context, std::uint64_t address, std::uint64_t bytes, const ShaderRecompiler::SrtWriteStamp& stamp) { + auto& reads = *static_cast(context); + if (bytes == 0u || address > std::numeric_limits::max() - bytes || walkPending(reads, address, bytes)) return false; + reads.collected = true; + return ShaderMemory::Vouched(nullptr, address, bytes, stamp); +} + +bool supplyWalkWords(void* context, const std::shared_ptr& words) { + auto& reads = *static_cast(context); + if (words == nullptr || words->runs.empty()) return false; + std::uint64_t total = 0; + for (const auto& [address, count] : words->runs) { + const auto bytes = static_cast(count) * WordBytes; + if (count == 0u || address % WordBytes != 0u || address > std::numeric_limits::max() - bytes) return false; + total += count; + } + if (total != words->words.size()) return false; + for (const auto& [address, count] : words->runs) { + const auto bytes = static_cast(count) * WordBytes; + const auto first = address & ~(WalkPageBytes - 1u); + const auto past = (address + bytes + WalkPageBytes - 1u) & ~(WalkPageBytes - 1u); + if (!reads.Verified(address, bytes)) { + if (!GuestMemory::Accessible(reinterpret_cast(first), static_cast(past - first))) return false; + reads.Verify(first, past - first); + } + } + for (const auto& [address, count] : words->runs) reads.runs.emplace_back(address, address + static_cast(count) * WordBytes); + reads.supplied.push_back(words); + return true; +} + bool walkAccessible(void* context, std::uint64_t address, std::uint64_t bytes) { auto& reads = *static_cast(context); if (bytes != 0 && reads.Verified(address, bytes)) return true; @@ -404,12 +459,40 @@ bool walkAccessible(void* context, std::uint64_t address, std::uint64_t bytes) { -void copyRangeValues(const AddressRanges& ranges, std::vector& values) { +void copyRangeValues(const AddressRanges& ranges, std::span> supplied, std::vector& values) { + struct Reused { + std::uint64_t address; + std::uint64_t past; + const std::uint32_t* words; + }; + std::vector reused; + for (const auto& block : supplied) { + std::size_t at = 0; + for (const auto& [address, count] : block->runs) { + reused.push_back({address, address + static_cast(count) * WordBytes, block->words.data() + at}); + at += count; + } + } + std::sort(reused.begin(), reused.end(), [](const Reused& left, const Reused& right) { return left.address < right.address; }); values.clear(); + auto next = reused.begin(); for (const auto& [begin, end] : ranges) { const auto offset = values.size(); values.resize(offset + static_cast((end - begin) / WordBytes)); - std::memcpy(values.data() + offset, reinterpret_cast(begin), static_cast(end - begin)); + auto* const out = values.data() + offset; + auto cursor = begin; + const auto live = [&](std::uint64_t past) { + if (past > cursor) std::memcpy(out + (cursor - begin) / WordBytes, reinterpret_cast(cursor), static_cast(past - cursor)); + cursor = std::max(cursor, past); + }; + for (; next != reused.end() && next->address < end; ++next) { + if (next->address < begin || next->past > end) throw std::runtime_error("a heap walk's reused table words lie outside its read ranges"); + live(next->address); + const auto first = std::max(next->address, cursor); + if (next->past > first) std::memcpy(out + (first - begin) / WordBytes, next->words + (first - next->address) / WordBytes, static_cast(next->past - first)); + cursor = std::max(cursor, next->past); + } + live(end); } } @@ -432,6 +515,9 @@ captureWalk(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::s runtime.userContext = &reads; runtime.readMemory = readWalkWord; runtime.readWords = readWalkWords; + runtime.stampWrites = stampWalkWrites; + runtime.unchangedSince = walkUnchangedSince; + runtime.supplyWords = supplyWalkWords; runtime.accessible = walkAccessible; return invocation.Capture(runtime); } @@ -494,23 +580,24 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade auto& reads = HostThreadLocal(); auto sharedRanges = takeRecycledRanges(); auto& ranges = *sharedRanges; - reads.Reset(); - const auto before = Graphics::Recorder::PendingWriteSnapshot(); - const auto generation = GuestMemory::StableTrackerGeneration(); - const auto variant = invocation.VariantId(); - - std::shared_ptr capture; - try { - capture = captureWalk(invocation, userData, shaderBase, reads); - } catch (const std::exception&) { - return {}; - } - CoalesceWalkReads(reads.runs, ranges); auto sharedValues = takeRecycledValues(); auto& values = *sharedValues; - if (!reads.failed) copyRangeValues(ranges, values); - const bool settled = rangesSettled(ranges, before.get(), generation); - if (!settled) return {}; + std::shared_ptr capture; + for (std::uint32_t attempt = 0;; ++attempt) { + reads.Reset(); + const auto before = Graphics::Recorder::PendingWriteSnapshot(); + reads.before = before.get(); + const auto generation = GuestMemory::StableTrackerGeneration(); + try { + capture = captureWalk(invocation, userData, shaderBase, reads); + } catch (const std::exception&) { + return {}; + } + CoalesceWalkReads(reads.runs, ranges); + if (!reads.failed) copyRangeValues(ranges, reads.supplied, values); + if (rangesSettled(ranges, before.get(), generation)) break; + if (attempt != 0u || !reads.collected) return {}; + } guardRanges(ranges); auto words = recycledStageWords(); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_table_walk_reuse_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_table_walk_reuse_tests.cmake new file mode 100644 index 000000000000..2fe4e40beebc --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_table_walk_reuse_tests.cmake @@ -0,0 +1,7 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_heap_table_walk_reuse) + if(TARGET agc_driver_heap_table_walk_reuse_tests) + agc_add_env_test(agc_driver_heap_table_walk_reuse_heap agc_driver_heap_table_walk_reuse_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1) + endif() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp new file mode 100644 index 000000000000..bf6a51d398b9 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp @@ -0,0 +1,157 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "Optimization/ResourceMaterializer.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; +using namespace ShaderRecompiler; + +constexpr std::uint32_t Entries = 1024; +constexpr std::size_t BlockBytes = 65536; +constexpr std::array Code{0xbf068002u, 0xbf850013u, 0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x7e200500u, 0x93109010u, + 0xf4200406u, 0x20000004u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0xf09c0f08u, 0x00450000u, 0xe0700000u, 0x80070000u, 0xbf810000u, 0xbf800000u}; +alignas(256) std::array, 3> Textures{}; +alignas(256) std::array Output{}; +alignas(256) std::array Srt{}; + +std::array Buffer(const void* pointer, std::uint32_t stride, std::uint32_t records) { + const auto address = reinterpret_cast(pointer); + return {static_cast(address), static_cast(address >> 32u) | (stride << 16u), records, stride == 0u ? 0x31016facu : 0x01016facu}; +} + +std::array Texture(std::uint32_t texture) { + const auto address = reinterpret_cast(Textures[texture].data()); + return {static_cast(address >> 8u), static_cast(address >> 40u) | ((texture == 1u ? 22u : 20u) << 20u) | (3u << 30u), 7u, 0x90000facu, 0u, 0u, 0u, 0u}; +} + +std::uint8_t* WatchedPages(std::size_t bytes) { +#ifdef _WIN32 + auto* data = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(bytes, BlockBytes)); + Require(data != nullptr, "heap table walk reuse: cannot allocate the table pages"); + GuestArena::GuestArenaCommit_nid_postfix(data, bytes, PAGE_READWRITE, bytes); + return data; +#else + void* mapped = mmap(nullptr, bytes + BlockBytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(mapped != MAP_FAILED, "heap table walk reuse: cannot map the table pages"); + auto* data = reinterpret_cast((reinterpret_cast(mapped) + BlockBytes - 1u) & ~std::uintptr_t{BlockBytes - 1u}); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(data, bytes); + return data; +#endif +} + +std::vector> Descriptors(const RecompileResult& result) { + std::vector> descriptors; + for (const auto& binding : result.bindings) descriptors.push_back(binding.guestDescriptor); + return descriptors; +} + +std::vector> StageDescriptors(const AgcDriver::DriverDetail::HeapStageMaterialized& stage) { + if (stage.words != nullptr && stage.result->heapTemplateId != 0u) return Descriptors(*AgcDriver::DriverDetail::PatchedHeapResult(*stage.result, *stage.words)); + return Descriptors(*stage.result); +} + +std::uint32_t RecordedWord(const AgcDriver::DriverDetail::HeapStageMaterialized& stage, std::uint64_t address) { + std::size_t cursor = 0; + for (const auto& [begin, end] : *stage.reads.ranges) { + if (address >= begin && address < end) return (*stage.reads.values)[cursor + static_cast((address - begin) / sizeof(std::uint32_t))]; + cursor += static_cast((end - begin) / sizeof(std::uint32_t)); + } + throw std::runtime_error("heap table walk reuse: the walk did not record the table word"); +} + +void Run(AgcDriver::VulkanDevice& device) { + constexpr std::size_t TableBytes = BlockBytes; + auto* base = WatchedPages(TableBytes * 2u); + auto* table = reinterpret_cast(base); + auto* material = reinterpret_cast(base + TableBytes); + for (std::uint32_t entry = 0; entry < Entries; ++entry) { + const auto descriptor = Texture(entry % 2u); + std::copy(descriptor.begin(), descriptor.end(), table + entry * 8u); + material[entry * 4u + 1u] = entry; + } + const auto tableBuffer = Buffer(table, 32u, Entries); + const auto materialBuffer = Buffer(material, 16u, Entries); + const auto output = Buffer(Output.data(), 0u, 256u); + std::copy(tableBuffer.begin(), tableBuffer.end(), Srt.begin()); + std::copy(materialBuffer.begin(), materialBuffer.end(), Srt.begin() + 8u); + std::copy(output.begin(), output.end(), Srt.begin() + 12u); + const auto srtAddress = reinterpret_cast(Srt.data()); + const std::vector userData{static_cast(srtAddress), static_cast(srtAddress >> 32u), 1u}; + const std::array regions{MemoryRegion{reinterpret_cast(Code.data()), std::as_bytes(std::span(Code))}}; + const ShaderComputeStageInfo compute{{std::min(32u, device.Target().subgroupSize), 1u, 1u}, 0u, {false, false, false}, false, 1u}; + auto target = device.Target(); + target.gpuResolvedImages = true; + RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(Code.data()), Code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, regions}, target, {0u, 0u, 0u, 128u}}; + const auto handle = PrepareShader(request); + const auto invocation = PreparedShaderInvocation::TryCreate(request, handle); + Require(invocation.has_value(), "heap table walk reuse: the prepared table shader refused its own request"); + const auto walk = [&] { + auto stage = AgcDriver::DriverDetail::MaterializeHeapStage(*invocation, userData, request.shader.codeAddress); + Require(stage.result != nullptr && stage.reads.complete, "heap table walk reuse: the heap walk declined the table stage"); + return stage; + }; + const auto expected = [&] { + AgcDriver::ShaderMemory memory({}); + const auto capture = memory.Capture(*invocation); + const auto result = invocation->Materialize(*capture); + Require(result != nullptr, "heap table walk reuse: the full capture declined the table stage"); + return Descriptors(*result); + }; + const auto changed = reinterpret_cast(table + 5u * 8u); + + const auto first = walk(); + const auto before = ResourceMaterializer::TableReuse(); + const auto second = walk(); + const auto reused = ResourceMaterializer::TableReuse(); + Require(reused.unwritten > before.unwritten, "heap table walk reuse: a walk over an unwritten table did not reuse its column"); + Require(StageDescriptors(first) == expected(), "heap table walk reuse: the first walk differs from a full capture"); + Require(*second.reads.ranges == *first.reads.ranges && *second.reads.values == *first.reads.values, "heap table walk reuse: a reused table recorded other words than the walk that read it"); + Require(StageDescriptors(second) == StageDescriptors(first), "heap table walk reuse: a reused table produced other descriptors"); + + const auto replacement = Texture(2u); + std::copy(replacement.begin(), replacement.end(), table + 5u * 8u); + const auto written = ResourceMaterializer::TableReuse(); + const auto third = walk(); + const auto after = ResourceMaterializer::TableReuse(); + Require(after.columns + after.compared > written.columns + written.compared, "heap table walk reuse: a walk did not re-read a table the guest wrote since"); + Require(RecordedWord(third, changed) == replacement[0], "heap table walk reuse: the walk recorded a stale table word"); + const auto current = expected(); + Require(StageDescriptors(third) == current, "heap table walk reuse: the walk after a table write differs from a full capture"); + Require(current != StageDescriptors(first), "heap table walk reuse: the table write did not change the stage's descriptors"); +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) return VulkanTestSkipped; + Run(*device); + std::cout << "heap table walk reuse tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} From 857fa7ce5a44bffa025a0659bf77a5ff180f0e24 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 00:01:43 +0530 Subject: [PATCH 235/269] fix(agc): hash main's shader snapshot key with the snapshot hash scope Main's background specialization keys its jobs with snapshotHash(..., false, ...), the boolean masked argument the heap branch replaced with SnapshotHashScope. Pass the default scope, which hashes the same unmasked snapshot. --- core/shader/recompiler/Recompiler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index a7b8c10d01a1..f7e1e77aaca8 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -2885,7 +2885,7 @@ PreparedShaderInvocation PreparedShaderInvocation::Rebound(const RecompileReques std::uint64_t PreparedShaderInvocation::SnapshotKey(const ResourceCapture& capture) const { if (capture.source != handle->source) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); const auto substitutes = bufferSubstitutesEnabled() && handle->artifact->substitutes != nullptr ? handle->artifact->substitutes->Slots() : std::vector{}; - std::uint64_t key = snapshotHash(request, capture.snapshot, false, substitutes); + std::uint64_t key = snapshotHash(request, capture.snapshot, {}, substitutes); for (const std::uint64_t value : {static_cast(reinterpret_cast(handle.get())), static_cast(handle->artifact->artifact.variantId), static_cast(request.layout.descriptorSet), static_cast(request.layout.pushConstantSizeBytes)}) { key ^= value; key *= 0x100000001b3ull; From c681e7d626b80035c31a30f06e0c30b3bd0850ff Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 00:01:43 +0530 Subject: [PATCH 236/269] perf(agc): build new heap stage templates off the draw thread with APS5_ASYNC_DRAW_COMPILE Main's APS5_ASYNC_DRAW_COMPILE skips a draw while its per-draw specialization runs on the library prebuild pool, but a heap stage compiled a new heap template on the draw thread, the stall the switch removes. MaterializeHeap now reports a missing template without building it, and MaterializeHeapInBackground builds it on the same pool through the same job registry, cheap-shader shortcut and DrawCompilePending skip as MaterializeInBackground, whose steps it now shares. The heap stage walk and the heap branch of draw stage materialization use it, and the walk passes the pending exception through instead of reporting a stage failure. agc_driver_heap_draw_sample runs under APS5_ASYNC_DRAW_COMPILE with and without the draw pipeline, resubmits a skipped draw and requires a heap draw to have waited for a background template. --- .../include/Driver/Draw/HeapStages.hpp | 2 +- .../include/Driver/Shaders/ShaderRegistry.hpp | 2 + .../Execution/src/Driver/Draw/DrawCapture.cpp | 102 +++++++++++++----- .../Execution/src/Driver/Draw/HeapStages.cpp | 7 +- .../agc_driver_heap_draw_sample_tests.cmake | 4 + ...c_driver_heap_table_walk_reuse_tests.cmake | 2 + .../tests/execution/HeapDrawSample.cpp | 32 ++++-- .../tests/execution/HeapStageSettled.hpp | 19 ++++ .../tests/execution/HeapTableWalkReuse.cpp | 19 +++- .../execution/HeapWalkCaptureFailure.cpp | 7 +- .../tests/execution/HeapWalkThreads.cpp | 3 +- .../include/Optimization/ResourceProgram.hpp | 6 +- core/shader/recompiler/Recompiler.cpp | 7 +- docs/dev/ENVIRONMENT.md | 2 +- 14 files changed, 170 insertions(+), 44 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/HeapStageSettled.hpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp index 56a3543f96e5..2ee225760110 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp @@ -47,7 +47,7 @@ void AppendWalkRead(std::vector>& runs, void CoalesceWalkReads(std::vector>& runs, std::vector>& ranges); HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, - std::uint64_t shaderBase); + ShaderRecompiler::MemoryRegionView memory, std::uint64_t shaderBase); void NoteHeapDirect(); void NoteHeapDirectVerify(const ShaderRecompiler::RecompileResult& direct, const ShaderRecompiler::RecompileResult& expected, const ShaderRecompiler::ResourceCapture* expectedCapture = nullptr); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp index 202ae539721c..0bd076fdd04d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp @@ -367,6 +367,8 @@ struct OwnedRecompileRequest { std::shared_ptr OwnRecompileRequest(const ShaderRecompiler::RecompileRequest& source, ShaderRecompiler::MemoryRegionView memory); ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request, bool deferPreparation = false); std::shared_ptr MaterializeInBackground(const ShaderRecompiler::PreparedShaderInvocation& invocation, const std::shared_ptr& capture, ShaderRecompiler::MemoryRegionView memory, std::uint64_t address); +std::uint64_t HeapTemplatesBuiltInBackground(); +std::shared_ptr MaterializeHeapInBackground(const ShaderRecompiler::PreparedShaderInvocation& invocation, const std::shared_ptr& capture, ShaderRecompiler::HeapStageWords& words, ShaderRecompiler::MemoryRegionView memory, std::uint64_t address); std::shared_ptr CaptureInvocation(ShaderMemory& memory, const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request, ShaderRecompiler::PreparedShaderInvocation& invocation); bool StageLinksUserDataCallees(const ShaderSnapshot& snapshot, std::size_t codeOffset); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 262a6c12ef6c..01686bbe0413 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -122,26 +123,32 @@ PendingMaterializes& pendingMaterializes() { } -std::shared_ptr MaterializeInBackground(const ShaderRecompiler::PreparedShaderInvocation& invocation, const std::shared_ptr& capture, ShaderRecompiler::MemoryRegionView memory, std::uint64_t address) { - if (!AsyncDrawCompile()) return invocation.Materialize(*capture); - bool contended = false; - if (auto memoized = invocation.MaterializeIfMemoized(*capture, &contended)) return memoized; +namespace { + +using MaterializeWork = std::function()>; + +std::atomic heapTemplatesInBackground{0}; + +bool cheapAt(std::uint64_t address, bool contended) { auto& pending = pendingMaterializes(); - bool cheap = false; - { - std::lock_guard lock(pending.mutex); - const auto found = pending.lastMs.find(address); - cheap = !contended && found != pending.lastMs.end() && found->second < PendingMaterializes::CheapMs; - } - if (cheap) { - const auto started = std::chrono::steady_clock::now(); - auto result = invocation.Materialize(*capture); - const auto ms = ElapsedMs(started); - std::lock_guard lock(pending.mutex); - pending.lastMs[address] = ms; - return result; - } - const std::pair key{address, invocation.SnapshotKey(*capture)}; + std::lock_guard lock(pending.mutex); + const auto found = pending.lastMs.find(address); + return !contended && found != pending.lastMs.end() && found->second < PendingMaterializes::CheapMs; +} + +std::shared_ptr timedAt(std::uint64_t address, const MaterializeWork& work) { + const auto started = std::chrono::steady_clock::now(); + auto result = work(); + const auto ms = ElapsedMs(started); + auto& pending = pendingMaterializes(); + std::lock_guard lock(pending.mutex); + pending.lastMs[address] = ms; + return result; +} + +std::shared_ptr finishedInBackground(std::uint64_t address, std::uint64_t snapshotKey, const std::function& makeWork, bool* created = nullptr) { + auto& pending = pendingMaterializes(); + const std::pair key{address, snapshotKey}; std::shared_ptr job; bool started = false; { @@ -159,15 +166,14 @@ std::shared_ptr MaterializeInBackground } job = slot; } + if (created != nullptr) *created = started; if (started) { - const auto owned = OwnRecompileRequest(invocation.Request(), memory); - const auto rebound = std::make_shared(invocation.Rebound(owned->request)); - SubmitLibraryPrebuild([job, owned, rebound, capture, address] { + SubmitLibraryPrebuild([job, work = makeWork(), address] { std::shared_ptr result; std::exception_ptr failure; const auto started = std::chrono::steady_clock::now(); try { - result = rebound->Materialize(*capture); + result = work(); } catch (...) { failure = std::current_exception(); } @@ -197,12 +203,58 @@ std::shared_ptr MaterializeInBackground return job->result; } +template +std::function reboundWork(const ShaderRecompiler::PreparedShaderInvocation& invocation, ShaderRecompiler::MemoryRegionView memory, Run run) { + return [&invocation, memory, run] { + std::shared_ptr owned = OwnRecompileRequest(invocation.Request(), memory); + auto rebound = std::make_shared(invocation.Rebound(owned->request)); + return MaterializeWork([owned, rebound, run] { return run(*rebound); }); + }; +} + +constexpr std::uint64_t HeapTemplateJob = std::uint64_t{1} << 63u; + +} + +std::shared_ptr MaterializeInBackground(const ShaderRecompiler::PreparedShaderInvocation& invocation, const std::shared_ptr& capture, ShaderRecompiler::MemoryRegionView memory, std::uint64_t address) { + if (!AsyncDrawCompile()) return invocation.Materialize(*capture); + bool contended = false; + if (auto memoized = invocation.MaterializeIfMemoized(*capture, &contended)) return memoized; + if (cheapAt(address, contended)) return timedAt(address, [&] { return invocation.Materialize(*capture); }); + return finishedInBackground(address, invocation.SnapshotKey(*capture), reboundWork(invocation, memory, [capture](const ShaderRecompiler::PreparedShaderInvocation& rebound) { return rebound.Materialize(*capture); })); +} + +std::uint64_t HeapTemplatesBuiltInBackground() { + return heapTemplatesInBackground.load(std::memory_order_relaxed); +} + +std::shared_ptr MaterializeHeapInBackground(const ShaderRecompiler::PreparedShaderInvocation& invocation, const std::shared_ptr& capture, ShaderRecompiler::HeapStageWords& words, ShaderRecompiler::MemoryRegionView memory, std::uint64_t address) { + if (!AsyncDrawCompile()) return invocation.MaterializeHeap(*capture, words); + ShaderRecompiler::HeapTemplateMiss miss; + if (auto hit = invocation.MaterializeHeap(*capture, words, &miss); hit != nullptr || !miss.missing) return hit; + const auto job = address | HeapTemplateJob; + if (cheapAt(job, false)) return timedAt(job, [&] { return invocation.MaterializeHeap(*capture, words); }); + bool created = false; + try { + static_cast(finishedInBackground(job, miss.key, reboundWork(invocation, memory, [capture](const ShaderRecompiler::PreparedShaderInvocation& rebound) { + ShaderRecompiler::HeapStageWords built; + return rebound.MaterializeHeap(*capture, built); + }), &created)); + } catch (const DrawCompilePending&) { + if (created) heapTemplatesInBackground.fetch_add(1, std::memory_order_relaxed); + throw; + } + return invocation.MaterializeHeap(*capture, words); +} + bool Driver::materializeHeapDirect(const DrawStageContext& context, std::size_t i, const ShaderRecompiler::PreparedShaderInvocation& invocation, const ShaderRecompiler::RecompileRequest& request, PerformanceTimer& timing) { const auto& program = context.programs[i]; auto& stageCapture = context.stageCaptures[i]; HeapStageMaterialized materialized; try { - materialized = MaterializeHeapStage(invocation, program.userData, program.binary.codeAddress); + materialized = MaterializeHeapStage(invocation, program.userData, request.context.memory, program.binary.codeAddress); + } catch (const DrawCompilePending&) { + throw; } catch (const std::exception& error) { throw stageFailure(program, request, error, request.context.memory); } @@ -378,7 +430,7 @@ std::shared_ptr Driver::materializeDraw stageCapture.heapWords.reset(); if (request.target.gpuResolvedImages) { auto words = std::make_shared(); - if (auto shared = invocation.MaterializeHeap(*capture, *words)) { + if (auto shared = MaterializeHeapInBackground(invocation, capture, *words, request.context.memory, program.binary.codeAddress)) { words->dataOrigin = NextHeapDataOrigin(); stageCapture.compiled = std::move(shared); stageCapture.heapWords = std::move(words); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index cfb3e58bfa53..06c9dd9714f9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -3,6 +3,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp" @@ -575,7 +576,7 @@ std::shared_ptr takeRecycledRanges() { } HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, - std::uint64_t shaderBase) { + ShaderRecompiler::MemoryRegionView memory, std::uint64_t shaderBase) { struct ReadsStorage {}; auto& reads = HostThreadLocal(); auto sharedRanges = takeRecycledRanges(); @@ -601,8 +602,8 @@ HeapStageMaterialized MaterializeHeapStage(const ShaderRecompiler::PreparedShade guardRanges(ranges); auto words = recycledStageWords(); - auto result = invocation.MaterializeHeap(*capture, *words); - if (result == nullptr) result = invocation.Materialize(*capture); + auto result = MaterializeHeapInBackground(invocation, capture, *words, memory, shaderBase); + if (result == nullptr) result = MaterializeInBackground(invocation, capture, memory, shaderBase); words->dataOrigin = NextHeapDataOrigin(); const bool complete = !reads.failed && result != nullptr; HeapStageMaterialized materialized; diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake index 4512d8eee6ab..95898aa8ec11 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_draw_sample_tests.cmake @@ -13,6 +13,10 @@ if(BUILD_TESTING AND TARGET agc_driver_heap_draw_sample_tests) ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_NO_TIMELINE=1) set_tests_properties(agc_driver_heap_draw_sample_no_timeline PROPERTIES PASS_REGULAR_EXPRESSION "APS5_NO_TIMELINE cannot be used with APS5_GPU_HEAP" SKIP_REGULAR_EXPRESSION "skipped, the device lacks VK_EXT_descriptor_heap") + agc_add_env_test(agc_driver_heap_draw_sample_heap_async agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 APS5_ASYNC_DRAW_COMPILE=1) + agc_add_env_test(agc_driver_heap_draw_sample_heap_async_pipelined agc_driver_heap_draw_sample_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_ASYNC_DRAW_COMPILE=1 APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1) agc_add_env_test(agc_driver_heap_draw_sample_nogpl agc_driver_heap_draw_sample_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_NO_GPL=1) agc_add_env_test(agc_driver_heap_draw_sample_nogpl_heap agc_driver_heap_draw_sample_tests diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_table_walk_reuse_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_table_walk_reuse_tests.cmake index 2fe4e40beebc..d282888850bf 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_table_walk_reuse_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_table_walk_reuse_tests.cmake @@ -3,5 +3,7 @@ if(BUILD_TESTING) if(TARGET agc_driver_heap_table_walk_reuse_tests) agc_add_env_test(agc_driver_heap_table_walk_reuse_heap agc_driver_heap_table_walk_reuse_tests ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1) + agc_add_env_test(agc_driver_heap_table_walk_reuse_async agc_driver_heap_table_walk_reuse_tests + ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_ASYNC_DRAW_COMPILE=1) endif() endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index 397a213dfcf5..2300cd71ebe3 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -1,4 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Submit/include/Dcb.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -12,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -24,6 +27,7 @@ #include #include #include +#include #include #include #ifdef _WIN32 @@ -377,6 +381,21 @@ std::span PixelProgram(Mode mode, bool buffer, bool vertexS return PixelCode; } +template +void SubmitUntilDrawn(std::vector& commands, std::span colorMemory, const char* failure, Reset&& reset) { + const bool async = AgcDriver::DriverDetail::AsyncDrawCompile(); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60); + while (true) { + Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; + Require(sceAgcDriverSubmitDcb(&packet) == 0, failure); + AgcDriverWaitIdle_nid_postfix(); + const bool covered = std::any_of(colorMemory.begin(), colorMemory.end(), [](std::byte value) { return value != Kept; }); + if (covered || !async || std::chrono::steady_clock::now() >= deadline) return; + reset(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } +} + void DrawSamplesTheTexture(bool heap, Mode mode, bool repeated = false) { const bool buffer = mode == Mode::Buffer || mode == Mode::Bda || mode == Mode::MovedBuffer; const auto colorMemory = mode == Mode::MergedBlend ? MergedTarget(0) : mode == Mode::MergedBlendOther ? MergedTarget(1) : std::span(ColorMemory); @@ -407,9 +426,10 @@ void DrawSamplesTheTexture(bool heap, Mode mode, bool repeated = false) { auto* gdsCounter = reinterpret_cast(AgcDriver::Pm4::GdsAddress() + 0x10u); if (mode == Mode::Gds) *gdsCounter = 0u; auto commands = Draw(code, mode); - Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; - Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); - AgcDriverWaitIdle_nid_postfix(); + SubmitUntilDrawn(commands, colorMemory, "the draw submission failed", [&] { + StorageMemory.fill(0u); + if (mode == Mode::Gds) *gdsCounter = 0u; + }); std::size_t drawn = 0; for (std::size_t offset = 0; offset < colorMemory.size(); offset += 4) { if (std::all_of(colorMemory.begin() + static_cast(offset), @@ -468,9 +488,7 @@ void UnpreparedPairTakesTheHeap() { const auto excludedBefore = HeapExcludedCount(HeapExcluded::Draw); ColorMemory.fill(Kept); auto commands = Draw(FreshPixelCode.data(), Mode::Vertex, FreshVertexCode.data()); - Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; - Require(sceAgcDriverSubmitDcb(&packet) == 0, "the unprepared pair's draw submission failed"); - AgcDriverWaitIdle_nid_postfix(); + SubmitUntilDrawn(commands, ColorMemory, "the unprepared pair's draw submission failed", [] {}); std::size_t drawn = 0; for (std::size_t offset = 0; offset < ColorMemory.size(); offset += 4) { if (std::all_of(ColorMemory.begin() + static_cast(offset), @@ -545,6 +563,8 @@ int main() { for (const auto mode : {Mode::Table, Mode::VertexTable}) DrawSamplesTheTexture(heap, mode, true); const bool capped = heap && std::getenv("APS5_HEAP_SLOT_CAP") != nullptr; if (heap && !capped) UnpreparedPairTakesTheHeap(); + if (heap && AgcDriver::DriverDetail::AsyncDrawCompile() && ShaderRecompiler::HeapTemplateCounts().entries != 0u) + Require(AgcDriver::DriverDetail::HeapTemplatesBuiltInBackground() != 0u, "no heap draw waited for its template to be built in the background"); if (heap) { OversizedStageFails(); UnmappableStageFails(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapStageSettled.hpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapStageSettled.hpp new file mode 100644 index 000000000000..087c60c1b1b1 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapStageSettled.hpp @@ -0,0 +1,19 @@ +#pragma once + +#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" + +#include +#include + +inline AgcDriver::DriverDetail::HeapStageMaterialized MaterializeHeapStageSettled(const ShaderRecompiler::PreparedShaderInvocation& invocation, std::span userData, + ShaderRecompiler::MemoryRegionView memory, std::uint64_t shaderBase) { + for (;;) { + try { + return AgcDriver::DriverDetail::MaterializeHeapStage(invocation, userData, memory, shaderBase); + } catch (const AgcDriver::DriverDetail::DrawCompilePending&) { + AgcDriver::DriverDetail::AwaitLibraryPrebuilds(); + } + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp index bf6a51d398b9..057548b15c69 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp @@ -1,3 +1,4 @@ +#include "HeapStageSettled.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" @@ -59,6 +60,17 @@ std::uint8_t* WatchedPages(std::size_t bytes) { #endif } +const std::byte* NoAccessPage() { +#ifdef _WIN32 + void* page = VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS); + Require(page != nullptr, "heap table walk reuse: cannot reserve a no-access page"); +#else + void* page = mmap(nullptr, 4096, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(page != MAP_FAILED, "heap table walk reuse: cannot map a no-access page"); +#endif + return static_cast(page); +} + std::vector> Descriptors(const RecompileResult& result) { std::vector> descriptors; for (const auto& binding : result.bindings) descriptors.push_back(binding.guestDescriptor); @@ -101,12 +113,13 @@ void Run(AgcDriver::VulkanDevice& device) { const ShaderComputeStageInfo compute{{std::min(32u, device.Target().subgroupSize), 1u, 1u}, 0u, {false, false, false}, false, 1u}; auto target = device.Target(); target.gpuResolvedImages = true; - RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(Code.data()), Code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, regions}, target, {0u, 0u, 0u, 128u}}; + std::vector prepared(regions.begin(), regions.end()); + RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(Code.data()), Code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, prepared}, target, {0u, 0u, 0u, 128u}}; const auto handle = PrepareShader(request); const auto invocation = PreparedShaderInvocation::TryCreate(request, handle); Require(invocation.has_value(), "heap table walk reuse: the prepared table shader refused its own request"); const auto walk = [&] { - auto stage = AgcDriver::DriverDetail::MaterializeHeapStage(*invocation, userData, request.shader.codeAddress); + auto stage = MaterializeHeapStageSettled(*invocation, userData, regions, request.shader.codeAddress); Require(stage.result != nullptr && stage.reads.complete, "heap table walk reuse: the heap walk declined the table stage"); return stage; }; @@ -119,7 +132,9 @@ void Run(AgcDriver::VulkanDevice& device) { }; const auto changed = reinterpret_cast(table + 5u * 8u); + prepared[0] = MemoryRegion{prepared[0].guestAddress, std::span(NoAccessPage(), prepared[0].bytes.size())}; const auto first = walk(); + prepared[0] = regions[0]; const auto before = ResourceMaterializer::TableReuse(); const auto second = walk(); const auto reused = ResourceMaterializer::TableReuse(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp index 6b57bee3ceec..15bb81f5db6c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkCaptureFailure.cpp @@ -1,3 +1,4 @@ +#include "HeapStageSettled.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" @@ -62,7 +63,7 @@ void UnsupportedTypeDeclines(AgcDriver::VulkanDevice& device) { Require(invocation.has_value(), "the prepared shader refused its own request"); AgcDriver::DriverDetail::HeapStageMaterialized materialized; try { - materialized = AgcDriver::DriverDetail::MaterializeHeapStage(*invocation, userData, request.shader.codeAddress); + materialized = MaterializeHeapStageSettled(*invocation, userData, request.context.memory, request.shader.codeAddress); } catch (const std::exception& error) { Require(false, std::string("a heap walk that read words it cannot capture threw instead of leaving the stage to the synchronized capture: ") + error.what()); } @@ -84,7 +85,7 @@ void ValidTypeYieldsStage(AgcDriver::VulkanDevice& device) { const auto handle = ShaderRecompiler::PrepareShader(request); const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, handle); Require(invocation.has_value(), "the prepared shader refused its own request"); - const auto materialized = AgcDriver::DriverDetail::MaterializeHeapStage(*invocation, userData, request.shader.codeAddress); + const auto materialized = MaterializeHeapStageSettled(*invocation, userData, request.context.memory, request.shader.codeAddress); Require(materialized.result != nullptr, "a heap walk over valid buffer descriptors declined its stage"); } @@ -96,7 +97,7 @@ void RepeatedWalksYieldStages(AgcDriver::VulkanDevice& device) { const auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(request, handle); Require(invocation.has_value(), "the prepared shader refused its own request"); for (int walk = 0; walk < 3; ++walk) { - const auto materialized = AgcDriver::DriverDetail::MaterializeHeapStage(*invocation, userData, request.shader.codeAddress); + const auto materialized = MaterializeHeapStageSettled(*invocation, userData, request.context.memory, request.shader.codeAddress); Require(materialized.result != nullptr && materialized.words != nullptr, "a repeated heap walk over valid buffer descriptors declined its stage"); } } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp index 672cb27fb42c..20873caf175b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp @@ -1,3 +1,4 @@ +#include "HeapStageSettled.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/HeapStages.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" @@ -90,7 +91,7 @@ void Work(const std::vector>& variants, std::size_t fir for (std::size_t round = 0; round < Rounds; ++round) { for (std::size_t step = 0; step < variants.size(); ++step) { const auto& variant = *variants[(first + step * 7u) % variants.size()]; - auto stage = AgcDriver::DriverDetail::MaterializeHeapStage(*variant.invocation, variant.userData, variant.request.shader.codeAddress); + auto stage = MaterializeHeapStageSettled(*variant.invocation, variant.userData, variant.request.context.memory, variant.request.shader.codeAddress); Require(stage.result != nullptr && stage.words != nullptr, "a heap walk over valid buffer descriptors declined its stage"); { std::lock_guard lock(peer.mutex); diff --git a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp index f595d06345ed..84f7963ad872 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp @@ -62,6 +62,10 @@ struct SourceHandle { std::vector staticKey; bool imageTableBindings = false; }; +struct HeapTemplateMiss { + bool missing = false; + std::uint64_t key = 0; +}; class PreparedShaderInvocation { public: static std::optional TryCreate(const RecompileRequest& request, const std::shared_ptr& handle); @@ -70,7 +74,7 @@ class PreparedShaderInvocation { const RecompileRequest& Request() const { return request; } std::shared_ptr Capture(const SrtRuntime& runtime) const; std::shared_ptr Materialize(const ResourceCapture& capture) const; - std::shared_ptr MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words) const; + std::shared_ptr MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words, HeapTemplateMiss* miss = nullptr) const; const std::shared_ptr& Plan() const; std::shared_ptr LoadPlan() const; std::shared_ptr PlanOrLoad() const; diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index f7e1e77aaca8..cb5ac5f2b142 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -2750,7 +2750,7 @@ void HeapBindingWords(const RecompileRequest& request, const CompiledVariant& va } -std::shared_ptr PreparedShaderInvocation::MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words) const { +std::shared_ptr PreparedShaderInvocation::MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words, HeapTemplateMiss* miss) const { if (capture.source != handle->source || capture.plan != handle->source->plan) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); const auto& variant = handle->artifact; if (!variant->artifact.gpuResolvedImages || !variant->artifact.registrationModule || variant->bindings.layout.UsesPushData()) return nullptr; @@ -2802,6 +2802,11 @@ std::shared_ptr PreparedShaderInvocation::MaterializeHeap } return Sealed(hit->result); } + if (miss != nullptr && templates) { + miss->missing = true; + miss->key = key ^ source.id * 0x9e3779b97f4a7c15ull; + return nullptr; + } UsedBindingPlan usedPlan; auto built = std::make_shared(materializeResult(*variant, request, snapshot, false, &usedPlan, nullptr, &substitutes)); built->cacheHit = true; diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index a62de8bbe4c7..19916f017370 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -113,7 +113,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_ADDRESS_COPY_MAX_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 64 | upper bound in MiB on the guest memory one address-based build copies; exceeding it aborts | | `APS5_ALL_BUFFERS_WRITTEN` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | notes every shader buffer element as written, as before bufferWritten existed | | `APS5_ASSERT_GPU_LOCK` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp` | | aborts when a guarded path is reached without holding GuestMemory::GpuMutex, or when the unwatch hook would take it while the thread holds the host imports mutex without it; builds without NDEBUG always check the second | -| `APS5_ASYNC_DRAW_COMPILE` | boolean | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Diagnostics.cpp` | unset | when set to a value other than 0, a draw or dispatch whose shader is not prepared yet, or whose specialization for the captured resources is not ready, is skipped while the work runs on the library prebuild pool, and a later draw or dispatch of the same shader and resources uses the result; unset prepares and specializes every draw and dispatch before it records | +| `APS5_ASYNC_DRAW_COMPILE` | boolean | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Diagnostics.cpp` | unset | when set to a value other than 0, a draw or dispatch whose shader is not prepared yet, or whose specialization for the captured resources is not ready, is skipped while the work runs on the library prebuild pool, and a later draw or dispatch of the same shader and resources uses the result; with `APS5_GPU_HEAP=1` a heap stage whose binding shape has no compiled heap template yet is skipped while the template is built there, and later draws of that shape use it; unset prepares and specializes every draw and dispatch before it records | | `APS5_ATOMIC_STAGE_MAX_KIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 1024 | size cap in KiB on an atomic shader element covered by device-local staging | | `APS5_BACKGROUND_COMPILE_KIB` | integer | `core/libs/prx/libSceAgcDriver/Execution/include/CompileBudget.hpp` | 8192 | KiB of SPIR-V that compute pipelines built ahead of their dispatch (dispatch prebuilds and the pipeline journal's replay) may be compiling at once; a build that does not fit waits, one larger than the limit builds alone, and 0 builds them one at a time. Dispatches that need a pipeline now are not limited | | `APS5_BARRIER_VALIDATE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | counts the barriers a hazard-tracking validator would emit and skip, by class and hazard kind | From d3d885a7bb8d540743dfeebff0e0a0a7c9ddaf5e Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 00:20:26 +0530 Subject: [PATCH 237/269] fix(agc): decline a heap walk over a pending table before flushing it The heap walk's write-stamp hook flushed and collected a table's GPU writes before checking for a pending write, so a table with a queued GPU write now waited on the GPU, where the walk used to decline it. Check pending writes first. Retry a walk only when its read ranges were stamped after its snapshot, not when a write is still pending, and drop the walk's references to reused table words once they are recorded. --- .../Execution/src/Driver/Draw/HeapStages.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 06c9dd9714f9..1a386183e9d4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -409,12 +409,12 @@ bool walkPending(const WalkReads& reads, std::uint64_t address, std::uint64_t by ShaderRecompiler::SrtWriteStamp stampWalkWrites(void* context, std::uint64_t address, std::uint64_t bytes) { auto& reads = *static_cast(context); - if (bytes == 0u || address > std::numeric_limits::max() - bytes) return {}; + if (bytes == 0u || address > std::numeric_limits::max() - bytes || walkPending(reads, address, bytes)) return {}; reads.collected = true; GuestMemory::FlushGpuWrites(address, static_cast(bytes)); const auto layout = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); const auto generation = GuestMemory::CollectWrites(address, static_cast(bytes)); - if (generation == 0u || walkPending(reads, address, bytes)) return {}; + if (generation == 0u) return {}; return {generation, layout}; } @@ -497,10 +497,12 @@ void copyRangeValues(const AddressRanges& ranges, std::span Date: Mon, 16 Nov 2026 01:06:19 +0530 Subject: [PATCH 238/269] test(agc): check main's push budget boundaries on the per-draw graphics stages With APS5_GPU_HEAP=1, PrepareGraphicsStages puts each stage's heap variant in front of the per-draw stages, so PushBudgetBoundaries counted more stages than programs. Prepare through PreparePerDrawStages, as the file's other checks do. --- .../prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp index 97f3250a0f94..667ada19fd42 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp @@ -360,7 +360,7 @@ void PushBudgetBoundaries(AgcDriver::VulkanDevice& device) { auto target = device.Target(); target.fixedPushSlots = fixedSlots; target.registrationModules = false; - auto stages = PrepareGraphicsStages(decoded, target); + auto stages = PreparePerDrawStages(decoded, target); Require(stages.size() == decoded.programs.size(), "push budget preparation lost a graphics stage"); for (std::size_t index = 0u; index < stages.size(); ++index) { Require(stages[index].entry.handle != nullptr, "push budget preparation lost its source handle"); From dfad9e5a9766a0e6e6f99053f7da204af6cbd77a Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 04:20:25 +0530 Subject: [PATCH 239/269] fix(shader): validate a moved prepared request's inputs as a copied one does TryCreate's rvalue overload checked the inputs by building the whole stage input info, while the const& overload calls ValidateRequestInputs. Both reject the same vertex buffer descriptors, but the build costs more and the two paths could drift. Call ValidateRequestInputs in both, and test that each rejects merged vertex buffers whose record counts disagree. --- .../libSceAgcDriver/tests/DepthRangeRemap.cpp | 33 +++++++++++++++++++ core/shader/recompiler/Recompiler.cpp | 2 +- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/DepthRangeRemap.cpp b/core/libs/prx/libSceAgcDriver/tests/DepthRangeRemap.cpp index 257d5b498779..0a2726b8989b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/DepthRangeRemap.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/DepthRangeRemap.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace { @@ -126,6 +127,37 @@ void preparedTransformTests(ShaderRecompiler::ShaderStage stage) { require(!PreparedShaderInvocation::TryCreate(other, handle).has_value(), "a prepared vertex shader matched a request of another depth remap mode"); } +void preparedInputValidationTests() { + using namespace ShaderRecompiler; + auto request = baseRequest(false); + request.useCache = true; + auto& vertex = *request.context.vertex; + vertex.resourcesNum = 2u; + vertex.resources[0].fields = {0x10000u, 16u << 16u, 100u, 0u}; + vertex.resources[1].fields = {0x10004u, 16u << 16u, 100u, 0u}; + vertex.resourcesDst[0] = {0, 4, 0, 0u}; + vertex.resourcesDst[1] = {4, 4, 1, 0u}; + const auto handle = PrepareShader(request); + std::vector key; + BuildPreparedShaderKey(request, key); + require(PreparedShaderInvocation::TryCreate(request, handle, key).has_value(), "the prepared vertex shader did not match its own request"); + auto disagreeing = request; + disagreeing.context.vertex->resources[1].fields[2] = 99u; + const auto rejects = [](const auto& create) { + try { + static_cast(create()); + } catch (const std::exception& error) { + return std::string_view(error.what()).find("disagree on record count") != std::string_view::npos; + } + return false; + }; + require(rejects([&] { return PreparedShaderInvocation::TryCreate(disagreeing, handle, key); }), "a copied request with merged vertex buffers of different record counts was not rejected"); + require(rejects([&] { + auto moved = disagreeing; + return PreparedShaderInvocation::TryCreate(std::move(moved), handle, key); + }), "a moved request with merged vertex buffers of different record counts was not rejected"); +} + void pushedTransformTests(ShaderRecompiler::ShaderStage stage) { using namespace ShaderRecompiler; const auto remapped = Recompile(baseRequest(true, stage)); @@ -180,6 +212,7 @@ int main() { pushedTransformTests(stage); clipDistanceCapacityTests(stage); } + preparedInputValidationTests(); std::cout << "Depth range remap tests passed\n"; return 0; } catch (const std::exception& error) { diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 3ef2285e9e34..a3a7320dc5c9 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -2661,7 +2661,7 @@ std::optional PreparedShaderInvocation::TryCreate(cons std::optional PreparedShaderInvocation::TryCreate(RecompileRequest&& request, const std::shared_ptr& handle, std::span key) { if (handle == nullptr || !MatchesPreparedShader(request, *handle, key)) return std::nullopt; - if (request.shader.stage != ShaderStage::Compute && request.shader.stage != ShaderStage::Fragment) static_cast(RequestInputInfo(request)); + if (request.shader.stage != ShaderStage::Compute && request.shader.stage != ShaderStage::Fragment) ValidateRequestInputs(request); return PreparedShaderInvocation(std::move(request), handle); } From e65cf02c405c1c7e5791d6b68f67479cb774b490 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 04:20:25 +0530 Subject: [PATCH 240/269] fix(agc): create split compute pipelines through the descriptor heap A dispatch over the device's workgroup count limit is split into chunks, each with its own pipeline carrying the chunk's workgroup offset. For a heap-mode compute stage those pipelines were created with the classic pipeline layout, which heap-mode objects never create. Keep the stage's heap mappings and create the split pipelines with them. The oversized dispatch test runs its Y split in heap mode too, and gets a _gpu_heap variant. --- .../libSceAgcDriver/Execution/src/VulkanDevice.cpp | 6 +++++- .../cmake/agc_driver_oversized_dispatch_tests.cmake | 3 +++ .../tests/execution/OversizedDispatch.cpp | 11 ++++++++--- 3 files changed, 16 insertions(+), 4 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_oversized_dispatch_tests.cmake diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index b4c36df6aa7a..267f9487b09d 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -509,6 +509,7 @@ struct ComputePipelineObjects { std::mutex splitMutex; std::map, VkPipeline> splitPipelines; std::vector pushPlacements; + std::vector heapMappings; bool descriptorHeap = false; ~ComputePipelineObjects() { for (const auto& [base, split] : splitPipelines) destroyPipeline(device, split, nullptr); @@ -6400,6 +6401,7 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons const auto createPipelines = state->DeviceFunction("vkCreateComputePipelines"); if (objects->descriptorHeap) CreateComputeHeapPipeline(state->device, createPipelines, context.pipelineCache, objects->module, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, heapMappings, &objects->pipeline, context.pipelineCacheSynchronization); else CreateComputePipeline(state->device, createPipelines, context.pipelineCache, objects->module, objects->layout, pipelineFlags, stageFlags, specialization.Info(), subgroupSize, &objects->pipeline, context.pipelineCacheSynchronization); + if (objects->descriptorHeap) objects->heapMappings = std::move(heapMappings); objects->destroyModule(objects->device, objects->module, nullptr); objects->module = VK_NULL_HANDLE; if (!state->probingFloatControls) { @@ -6424,7 +6426,9 @@ VkPipeline VulkanDevice::splitComputePipeline(const Graphics::Context& context, VkShaderModule module = Graphics::CreateShaderModule(state->DeviceFunction("vkCreateShaderModule"), state->device, state->graphicsPipelineLibrary, shader.spirv.data(), shader.spirv.size() * sizeof(std::uint32_t), "vkCreateShaderModule"); VkPipeline pipeline = VK_NULL_HANDLE; try { - CreateComputePipeline(state->device, state->DeviceFunction("vkCreateComputePipelines"), context.pipelineCache, module, objects.layout, computePipelineFlags(), computeStageFlags(shader), specialization.Info(), computeSubgroupSize(shader), &pipeline, context.pipelineCacheSynchronization); + const auto createPipelines = state->DeviceFunction("vkCreateComputePipelines"); + if (objects.descriptorHeap) CreateComputeHeapPipeline(state->device, createPipelines, context.pipelineCache, module, computePipelineFlags(), computeStageFlags(shader), specialization.Info(), computeSubgroupSize(shader), objects.heapMappings, &pipeline, context.pipelineCacheSynchronization); + else CreateComputePipeline(state->device, createPipelines, context.pipelineCache, module, objects.layout, computePipelineFlags(), computeStageFlags(shader), specialization.Info(), computeSubgroupSize(shader), &pipeline, context.pipelineCacheSynchronization); } catch (...) { objects.destroyModule(objects.device, module, nullptr); throw; diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_oversized_dispatch_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_oversized_dispatch_tests.cmake new file mode 100644 index 000000000000..ffbee6f42891 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_oversized_dispatch_tests.cmake @@ -0,0 +1,3 @@ +if(BUILD_TESTING) + agc_add_gpu_heap_test(agc_driver_oversized_dispatch) +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/OversizedDispatch.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/OversizedDispatch.cpp index b31f2c597f42..cc52c5b01c64 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/OversizedDispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/OversizedDispatch.cpp @@ -1,6 +1,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "Recompiler.hpp" @@ -160,7 +161,7 @@ alignas(256) constexpr std::array GroupYCode{ constexpr std::uint32_t GroupYSplitCap = 1u << 20u; constexpr std::uint32_t GroupYTail = 4097u; -bool CheckGroupYSplitCoverage(AgcDriver::VulkanDevice& device) { +bool CheckGroupYSplitCoverage(AgcDriver::VulkanDevice& device, bool heap) { const auto limit = device.WorkGroupCountLimit()[1]; if (limit >= GroupYSplitCap) { std::printf("oversized dispatch Y split: skipped, the device reports a %u Y workgroup limit\n", limit); @@ -174,11 +175,14 @@ bool CheckGroupYSplitCoverage(AgcDriver::VulkanDevice& device) { const std::span code(GroupYCode); const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0, {false, true, false}, false, 1}; + auto target = device.Target(); + target.gpuResolvedImages = heap; ShaderRecompiler::RecompileRequest request{ {ShaderRecompiler::ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, {64, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), {0, 0, 0, 128}, std::nullopt, false}; + target, {0, 0, 0, 128}, std::nullopt, false}; const auto result = ShaderRecompiler::Recompile(request); + Require(result.gpuResolvedImages == heap, "oversized dispatch Y split: the program did not take the requested binding mode"); device.Dispatch(result, 1, groups, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(guest.Data()), guest.Bytes); @@ -195,7 +199,8 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; CheckLdsSplitThrows(*device); - bool split = CheckGroupYSplitCoverage(*device); + bool split = CheckGroupYSplitCoverage(*device, false); + if (split && AgcDriver::Graphics::DescriptorHeapEnabled()) static_cast(CheckGroupYSplitCoverage(*device, true)); if (device->WorkGroupCountLimit()[0] < Groups) { CheckSplitCoverage(*device); split = true; From fcb1a458d28e946fa7d61c711adfeafd62b378e7 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 04:20:25 +0530 Subject: [PATCH 241/269] test(agc): skip the refresh proof test where it cannot run refreshProofTests returned early without host imports, write watching or a watched host import, and agc_storage_refresh_proofs still reported a pass. Return whether it ran, and exit with the skip code when it did not. --- core/libs/prx/libSceAgcDriver/tests/Recorder.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index bd2319449da8..48ed37921423 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -10507,11 +10507,11 @@ void storageUploadLifetimeTests(const Device& device, Recorder& previous, bool f std::cout << "Storage upload lifetime" << (failView ? " after view failure" : " after caller release") << ": passed\n"; } -void refreshProofTests(const Device& device, Recorder& recorder) { +bool refreshProofTests(const Device& device, Recorder& recorder) { const auto& base = device.GetContext(); if (base.hostImportAlignment == 0) { std::cout << "host imports unavailable: refresh proofs not tested\n"; - return; + return false; } constexpr std::uint32_t side = 256; constexpr std::size_t surfaceBytes = side * side * 4; @@ -10520,7 +10520,7 @@ void refreshProofTests(const Device& device, Recorder& recorder) { void* block = AllocateWatched(bytes, 65536); if (block == nullptr) { std::cout << "no write watching: refresh proofs not tested\n"; - return; + return false; } auto* texels = static_cast(block); auto* keys = texels + surfaceBytes; @@ -10545,7 +10545,7 @@ void refreshProofTests(const Device& device, Recorder& recorder) { } unregister{base, block, address}; if (HostImportFor(base, address, bytes) == nullptr || !AgcDriver::GuestMemory::Watched(address, bytes)) { std::cout << "no watched host import: refresh proofs not tested\n"; - return; + return false; } TextureDetiler detiler(base); auto context = base; @@ -10668,6 +10668,7 @@ void refreshProofTests(const Device& device, Recorder& recorder) { recorder.Sync(); ClearCachedTextures(context.device); } + return true; } bool pendingKeyRefreshTests(const Device& device, Recorder& recorder) { @@ -16943,7 +16944,7 @@ int main(int argc, char** argv) { return 0; } if (argc == 2 && std::string_view(argv[1]) == "--refresh-proofs-only") { - refreshProofTests(device, recorder); + if (!refreshProofTests(device, recorder)) return 77; std::cout << "refresh proof tests passed\n"; return 0; } From 050c541acb1c05dd2977f7fa4b4f823cbeb58396 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 04:20:49 +0530 Subject: [PATCH 242/269] test(agc): define NOMINMAX before windows.h in the heap tests HeapDrawSample, HeapDrawBench, HeapTableWalkReuse and DrawRecipeMovedBuffer include windows.h without NOMINMAX and call std::min, which the min macro breaks on Windows. Guard them as HeapTableStageReuse does. --- .../libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp | 3 +++ .../libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp | 3 +++ .../prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp | 3 +++ .../prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp | 3 +++ 4 files changed, 12 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp index a5e062f12321..0812a551aecb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp @@ -32,6 +32,9 @@ #include #include #ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif #include #else #include diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp index 30e57e72e2a0..41204524f3bd 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp @@ -31,6 +31,9 @@ #include #include #ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif #include #else #include diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index 2300cd71ebe3..cd062155f0e1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -31,6 +31,9 @@ #include #include #ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif #include #else #include diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp index 057548b15c69..a08c791c8001 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableWalkReuse.cpp @@ -17,6 +17,9 @@ #include #include #ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif #include #else #include From d6dbd5c8d983b05a40f41f84117385cd6b068d9e Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 04:20:49 +0530 Subject: [PATCH 243/269] chore(agc): drop three added code comments and a trailing blank line --- .../prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp | 1 - .../tests/cmake/agc_driver_heap_walk_capture_failure_tests.cmake | 1 - .../prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp | 1 - core/shader/recompiler/HeapTemplateBudget.hpp | 1 - 4 files changed, 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp index ce11598f7e29..ecf84eaeabd9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp @@ -16,7 +16,6 @@ class FirstSampleCopy { FirstSampleCopy& operator=(const FirstSampleCopy&) = delete; void Record(Recorder& recorder, Texture& source); - // Through a classic descriptor set, for a view without a texture. void Record(Recorder& recorder, VkImageView source, VkImageLayout layout); VkImage Image() const { return image; } diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_capture_failure_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_capture_failure_tests.cmake index e990f737fb33..dc7bba88a614 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_capture_failure_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_walk_capture_failure_tests.cmake @@ -1,4 +1,3 @@ if(BUILD_TESTING) agc_add_gpu_heap_test(agc_driver_heap_walk_capture_failure) endif() - diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp index 701bc613af49..58a7f366f87c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp @@ -294,7 +294,6 @@ void RelocatedDrawsReuseTheirRecipe(bool libraries) { const auto recipeHits = AgcDriver::VulkanDevice::DrawRecipeHits() - recipesBefore; const auto hits = counters.hits - start.hits; Require(hits == moved.size() - 4, mode + ": draws whose data moved again made " + std::to_string(hits) + " draw-cache hits, expected " + std::to_string(moved.size() - 4)); - // Entry verification (APS5_VERIFY_DRAW_ENTRIES) records every hit afresh to compare it, so no hit is drawn from a recipe. if (std::getenv("APS5_VERIFY_DRAW_ENTRIES") != nullptr) { Require(recipeHits == 0, mode + ": " + std::to_string(recipeHits) + " draws served by a relocated entry were recorded from a recipe while entry verification records every hit afresh"); return; diff --git a/core/shader/recompiler/HeapTemplateBudget.hpp b/core/shader/recompiler/HeapTemplateBudget.hpp index 8ba16fcfbd8b..4aaadc627b3f 100644 --- a/core/shader/recompiler/HeapTemplateBudget.hpp +++ b/core/shader/recompiler/HeapTemplateBudget.hpp @@ -20,7 +20,6 @@ template return (static_cast(values.capacity()) + 7u) / 8u; } -// ElementFlags keeps up to 64 flags inline; larger sets spill every flag into a std::vector. [[nodiscard]] inline std::uint64_t OwnedBytes(const ElementFlags& flags) { return flags.size() > 64u ? (static_cast(flags.size()) + 7u) / 8u : 0u; } From 219aca8845a12cbb6ff8b01bf18c175d63c85149 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 04:20:49 +0530 Subject: [PATCH 244/269] refactor(shader): leave image table bindings out of the dropped binding kinds Kinds come from binding numbers modulo the per-stage binding count, so the image table bindings past the stage groups mapped onto kinds 0 and 1. A slot word is dropped only when no selected binding has its kind, which its own binding then lacks too, so no word was dropped wrongly; exclude the table bindings so the set holds only stage binding kinds. --- .../Optimization/src/DescriptorBindingBuilder.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index 7b76450a3461..2c7adbfc4aaa 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -755,8 +756,13 @@ DescriptorBindingPlan DescriptorBindingBuilder::Select(const DescriptorBindingPl selected.runtimeState = plan.runtimeState; constexpr auto bindingCount = static_cast(RuntimeAbi::Binding::Count); std::set droppedKinds; - for (const auto& binding : plan.bindings) droppedKinds.insert(binding.descriptor.binding % bindingCount); - for (const auto& binding : selected.bindings) droppedKinds.erase(binding.descriptor.binding % bindingCount); + const auto bindingKind = [](std::uint32_t binding) { return binding < RuntimeAbi::ImageStorageTableBinding ? std::optional(binding % bindingCount) : std::nullopt; }; + for (const auto& binding : plan.bindings) { + if (const auto kind = bindingKind(binding.descriptor.binding)) droppedKinds.insert(*kind); + } + for (const auto& binding : selected.bindings) { + if (const auto kind = bindingKind(binding.descriptor.binding)) droppedKinds.erase(*kind); + } selected.heapSlotWords.reserve(plan.heapSlotWords.size()); for (const auto& word : plan.heapSlotWords) { if (!droppedKinds.contains(word.kind)) selected.heapSlotWords.push_back(word); From 7938e1a633f5cafec338adad957fe5dac0949654 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 04:20:49 +0530 Subject: [PATCH 245/269] fix(agc): read APS5_GPU_HEAP=0 as off and reject malformed heap settings APS5_GPU_HEAP turned the heap on whenever it was set, so =0 enabled it, while USAGE.md documents =1. Read it as a boolean like APS5_ASYNC_DRAW_COMPILE, and have the heap tests ask GpuHeapEnabled instead of reading the variable themselves. APS5_HEAP_SLOT_CAP, APS5_PUSHED_BUFFER_RECORDS, APS5_EMBEDDED_SAMPLER_CAP, APS5_HEAP_TEMPLATE_MIB and APS5_VERIFY_GPU_HEAP went through strtoul, so a typo or -1 silently changed the cap. Parse them with from_chars and stop with an error that names the variable, as APS5_DUMP_COMPUTE_MIN_WORDS does. HeapDrawBench skips without a descriptor heap device, as HeapDrawSample does. --- .../Graphics/src/BindlessHeap.cpp | 29 ++++++++++++++----- .../tests/execution/HeapComputeSample.cpp | 2 +- .../tests/execution/HeapDrawBench.cpp | 3 +- .../tests/execution/HeapDrawSample.cpp | 2 +- .../tests/execution/HeapEmbeddedSampler.cpp | 2 +- .../tests/execution/HeapRingDrawKey.cpp | 2 +- .../tests/execution/ScratchPool.cpp | 3 +- core/shader/recompiler/HeapCacheSwitch.hpp | 11 +++++-- core/shader/recompiler/Recompiler.cpp | 8 ++++- docs/dev/ENVIRONMENT.md | 12 ++++---- 10 files changed, 52 insertions(+), 22 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index f3798c38556d..862f7e39455b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -70,8 +71,25 @@ std::atomic emptyResourceSets{0}; } +namespace { + +std::uint32_t HeapEnvironmentNumber(const char* name, std::uint32_t fallback, std::uint32_t maximum) { + const char* text = std::getenv(name); + if (text == nullptr || *text == '\0') return fallback; + std::uint32_t value = 0; + const auto* end = text + std::strlen(text); + const auto parsed = std::from_chars(text, end, value); + if (parsed.ec != std::errc{} || parsed.ptr != end || value > maximum) throw std::runtime_error(std::string(name) + " must be an integer from 0 through " + std::to_string(maximum)); + return value; +} + +} + bool GpuHeapEnabled() { - static const bool enabled = std::getenv("APS5_GPU_HEAP") != nullptr; + static const bool enabled = [] { + const char* value = std::getenv("APS5_GPU_HEAP"); + return value != nullptr && std::string_view(value) != "0"; + }(); return enabled; } @@ -144,8 +162,7 @@ bool DescriptorHeapEnabled() { std::uint32_t PushedBufferRecordCap() { static const std::uint32_t cap = [] { - const char* value = std::getenv("APS5_PUSHED_BUFFER_RECORDS"); - return value != nullptr && *value != '\0' ? static_cast(std::strtoul(value, nullptr, 10)) : ShaderRecompiler::RuntimeAbi::PushedBufferLimit; + return HeapEnvironmentNumber("APS5_PUSHED_BUFFER_RECORDS", ShaderRecompiler::RuntimeAbi::PushedBufferLimit, ShaderRecompiler::RuntimeAbi::PushedBufferLimit); }(); return cap; } @@ -232,8 +249,7 @@ namespace { std::uint32_t configuredSlotCap(std::uint32_t slots) { static const std::uint32_t requested = [] { - const char* value = std::getenv("APS5_HEAP_SLOT_CAP"); - return value != nullptr ? static_cast(std::strtoul(value, nullptr, 10)) : 0u; + return HeapEnvironmentNumber("APS5_HEAP_SLOT_CAP", 0u, ~0u); }(); if (requested == 0u || slots <= BindlessHeap::SamplerKind) return slots; return BindlessHeap::SamplerKind + std::min(requested, slots - BindlessHeap::SamplerKind); @@ -1153,8 +1169,7 @@ constexpr std::uint32_t InternalEmbeddedSamplers = 8u; std::uint32_t embeddedSamplerLimit(const Context& context) { static const auto cap = [] { - const char* value = std::getenv("APS5_EMBEDDED_SAMPLER_CAP"); - return value != nullptr ? static_cast(std::strtoul(value, nullptr, 10)) : ~0u; + return HeapEnvironmentNumber("APS5_EMBEDDED_SAMPLER_CAP", ~0u, ~0u); }(); const auto device = context.descriptorHeapProperties.maxDescriptorHeapEmbeddedSamplers; return std::min(cap, device > InternalEmbeddedSamplers ? device - InternalEmbeddedSamplers : 0u); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp index 088317663100..983e8a6130a1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapComputeSample.cpp @@ -145,7 +145,7 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; } - const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; + const bool heap = AgcDriver::Graphics::GpuHeapEnabled(); if (heap && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; FillTexels(TextureMemory, SampleTexel); FillTexels(OtherTextureMemory, OtherTexel); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp index 41204524f3bd..942771697240 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp @@ -327,7 +327,8 @@ int main(int argc, char** argv) { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; } - const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; + const bool heap = AgcDriver::Graphics::GpuHeapEnabled(); + if (heap && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; const std::size_t draws = argc > 1 ? std::strtoull(argv[1], nullptr, 10) : 4000u; const std::size_t rounds = argc > 2 ? std::strtoull(argv[2], nullptr, 10) : 12u; Require(draws > 0 && rounds >= 3, "the bench needs at least one draw and three rounds, the first two of which warm up"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp index cd062155f0e1..9be65b23d241 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawSample.cpp @@ -552,7 +552,7 @@ int main() { if (!device) return VulkanTestSkipped; } const bool excluded = std::getenv("APS5_GPU_HEAP_EXCLUDE") != nullptr; - const bool heapMode = std::getenv("APS5_GPU_HEAP") != nullptr; + const bool heapMode = AgcDriver::Graphics::GpuHeapEnabled(); const bool heap = heapMode && !excluded; if (heapMode && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp index a34d57c40d5c..201e376efe21 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp @@ -82,7 +82,7 @@ int main() { try { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; - const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; + const bool heap = AgcDriver::Graphics::GpuHeapEnabled(); if (heap && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; const bool embedding = heap; FillTexels(TextureMemory, SampleTexel); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp index 419a1c573b50..a81a54749de9 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapRingDrawKey.cpp @@ -268,7 +268,7 @@ int main() { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; } - const bool heap = std::getenv("APS5_GPU_HEAP") != nullptr; + const bool heap = AgcDriver::Graphics::GpuHeapEnabled(); constexpr std::size_t Draws = 256, Rounds = 8; { GuestAllocations::Mutation mutation; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp index d0d92918f951..75cddfdce106 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" @@ -264,7 +265,7 @@ Facts Inspect(const ShaderRecompiler::RecompileResult& result) { } void RequireHeapPipeline(const AgcDriver::VulkanDevice& device, const ShaderRecompiler::RecompileResult& result, std::uint64_t before, const std::string& name) { - if (std::getenv("APS5_GPU_HEAP") == nullptr) return; + if (!AgcDriver::Graphics::GpuHeapEnabled()) return; Require(result.gpuResolvedImages, name + ": the scratch program is not GPU mode"); Require(device.DescriptorHeapComputePipelines() > before, name + ": the scratch program did not take the descriptor heap"); } diff --git a/core/shader/recompiler/HeapCacheSwitch.hpp b/core/shader/recompiler/HeapCacheSwitch.hpp index 2f3abeb14bd9..ebb191092d75 100644 --- a/core/shader/recompiler/HeapCacheSwitch.hpp +++ b/core/shader/recompiler/HeapCacheSwitch.hpp @@ -1,8 +1,10 @@ #pragma once #include +#include #include #include +#include #include #include #include @@ -106,8 +108,13 @@ inline constexpr std::array(HeapCache static const std::uint64_t every = [] { const char* text = std::getenv("APS5_VERIFY_GPU_HEAP"); if (text == nullptr) return std::uint64_t{0}; - const auto value = std::strtoull(text, nullptr, 10); - return value == 0 ? std::uint64_t{1} : static_cast(value); + std::uint64_t value = 0; + const auto* end = text + std::strlen(text); + if (text != end) { + const auto parsed = std::from_chars(text, end, value); + if (parsed.ec != std::errc{} || parsed.ptr != end) throw std::runtime_error("APS5_VERIFY_GPU_HEAP must be empty or a non-negative integer"); + } + return value == 0 ? std::uint64_t{1} : value; }(); return every; } diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index a3a7320dc5c9..f7b281cc0c0f 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -7,6 +7,7 @@ #include "StencilReplay.hpp" #include #include +#include #include #include #include @@ -520,7 +521,12 @@ namespace { std::uint64_t HeapTemplateBudget() { static const std::uint64_t budget = [] { const char* value = std::getenv("APS5_HEAP_TEMPLATE_MIB"); - const auto mib = value != nullptr ? std::strtoull(value, nullptr, 10) : 256ull; + std::uint64_t mib = 256u; + if (value != nullptr && *value != '\0') { + const auto* end = value + std::strlen(value); + const auto parsed = std::from_chars(value, end, mib); + if (parsed.ec != std::errc{} || parsed.ptr != end || mib > (1u << 20u)) throw std::runtime_error("APS5_HEAP_TEMPLATE_MIB must be an integer from 0 through 1048576"); + } return std::max(mib, 1u) << 20u; }(); return budget; diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 144bba2fc5c0..57064696a652 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -209,7 +209,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_FULL_BARRIERS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records every barrier instead of merging redundant ones | | `APS5_GPU_CHECKPOINTS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | attaches device diagnostic checkpoints through VK_NV_device_diagnostic_checkpoints, or buffer markers through VK_AMD_buffer_marker on a device without it | | `APS5_GPU_COPY_MAX_KIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 1024 | size cap in KiB on a descriptor sub-range copied through the GPU path, larger ones staying on the CPU | -| `APS5_GPU_HEAP` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | | binds the sampled and storage images and samplers of eligible stages through the device's VK_EXT_descriptor_heap heaps; without the extension it does nothing | +| `APS5_GPU_HEAP` | boolean | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | unset | when set to a value other than 0, binds the sampled and storage images and samplers of eligible stages through the device's VK_EXT_descriptor_heap heaps; without the extension it does nothing | | `APS5_GPU_HEAP_EXCLUDE` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp` | | debug aid: comma list of stage classes that take the per-draw path while the GPU heap stays on: stage names (compute, vertex, hull, domain, geometry, pixel, local, mesh), or tables, storage or sampled for stages whose resource plan has image tables, storage images or sampled images; a draw with an excluded stage takes the per-draw path for all its stages, decided before any stage is built | | `APS5_GPU_NO_WRITEBACK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | skips writing GPU results back into guest memory | | `APS5_GPU_WAIT_TIMEOUT_MS` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp` | 1000 | milliseconds a GPU wait may run before a warning is printed | @@ -217,8 +217,8 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_HANDOFF_SPIN_US` | integer | `core/libs/prx/libSceAgcDriver/Execution/include/HandoffSpin.hpp` | | microseconds a thread spins for a handed-off draw's work or for the GPU mutex before blocking, clamped to 0..10000; unset spins 150 us when the process has more than 8 usable processors and not at all otherwise | | `APS5_HEADLESS_PIPELINE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | loads the pipeline cache file on a device without a window too; `agc_frame_replay` sets it by default and clears it with `--cold-pipelines`, including inherited values | | `APS5_HEAP_MIRROR_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 24576 | budget in MiB for the heap mirrors held for registered allocations | -| `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first | -| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a nearly full heap submits the open batch at the next draw or dispatch and evicts the slots that batch no longer uses | +| `APS5_HEAP_TEMPLATE_MIB` | integer | `core/shader/recompiler/Recompiler.cpp` | 256 | budget in MiB for the GPU heap's stage templates kept across all shaders; the least recently used go first; 0 means 1 MiB, and values other than an integer from 0 through 1048576 stop the driver with an error naming the variable | +| `APS5_HEAP_SLOT_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device | number of shared image slots the GPU heap hands out, after the 57 slots reserved for each binding kind's absent descriptor; 0 keeps the default (233415, grown into resource heap space the shader data ring leaves unused, up to 524231); a nearly full heap submits the open batch at the next draw or dispatch and evicts the slots that batch no longer uses; values other than an integer from 0 through 4294967295 stop the driver with an error naming the variable | | `APS5_HOOK_FLUSH_CPU_BLOCKS` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | set to 0 flushes pending images whose every 64 KiB block the CPU wrote, instead of skipping them | | `APS5_HOOK_FULL_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the flush hook's recorded-store wait a full Sync under the GpuMutex | | `APS5_HOOK_LOCKED_WAIT` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | keeps the flush hook's pending-write wait under the GpuMutex | @@ -284,7 +284,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_DCC_PRESYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | leaves the DCC key ranges out of the surfaces a build pre-syncs, so only the surface itself waits for its producer | | `APS5_NO_DEFERRED_DESTRUCTION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | on MoltenVK, destroys buffers and frees device memory as soon as the driver releases them, instead of while the graphics queue is idle (KhronosGroup/MoltenVK#2876) | | `APS5_NO_DCC_WORD_SCAN` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp` | | restores the byte-by-byte DCC key scan instead of the word-at-a-time compare | -| `APS5_EMBEDDED_SAMPLER_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device limit | caps the samplers the GPU heap embeds in pipelines below the device's maxDescriptorHeapEmbeddedSamplers; constant samplers past it read a sampler heap slot at a fixed offset (testing) | +| `APS5_EMBEDDED_SAMPLER_CAP` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | device limit | caps the samplers the GPU heap embeds in pipelines below the device's maxDescriptorHeapEmbeddedSamplers; constant samplers past it read a sampler heap slot at a fixed offset (testing); values other than an integer from 0 through 4294967295 stop the driver with an error naming the variable | | `APS5_NO_DEFERRED_EVICTION` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | destroys displaced resource-cache entries under the mutex instead of deferring them to the open batch | | `APS5_NO_DEFERRED_SETTLES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | settles watched private host imports as they open instead of through the deferred block-settling path (Windows only) | | `APS5_NO_DEPTH_PLANE_REUSE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp` | | rebuilds the shader resources of every draw that samples a copy of several depth planes instead of reusing a cached set and repeating the copy's lookup | @@ -481,7 +481,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_PROFILE_DRAW` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp` | | prints the per-phase driver and draw timing totals | | `APS5_PROFILE_GPU` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records the GPU time of recorded work by key from batch timestamps | | `APS5_PROFILE_GPU_DRAWS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp`, `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | with APS5_PROFILE_GPU, records the GPU time of each recorded draw by its fragment program's variant id and prints a [drawvariant] line with the code address behind each variant id once (draws that do not use a recipe only; the [gputime] line labels each `draw 0x`, the id [drawvariant] prints, and the ranges share the batch's query cap) | -| `APS5_PUSHED_BUFFER_RECORDS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 16 | test cap on the guest buffer records a heap stage keeps in its push data; the rest go to its per-draw overflow block | +| `APS5_PUSHED_BUFFER_RECORDS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp` | 16 | test cap on the guest buffer records a heap stage keeps in its push data; the rest go to its per-draw overflow block; values other than an integer from 0 through 16 stop the driver with an error naming the variable | | `APS5_READONLY_DEPTH_BOUNDS_COMPARE` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp` | 0 | `1` enables a read-only GREATER_OR_EQUAL comparison at viewport depth 1 for eligible single-sample D32S8 draws with native depth bounds; read once per process; unset or `0` keeps the normal path | | `APS5_REAP_EACH_PACKET` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/DeferredLabels.cpp` | | reaps deferred labels after every packet | | `APS5_REGISTRATION_PREPARE_COMMIT_GB` | number | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp` | half of physical RAM | stops preparing newly registered shaders ahead of use when process-private memory reaches this GiB budget; `0` disables registration-time preparation | @@ -591,7 +591,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_VERIFY_DRAW_PUSH_WORD` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | with `APS5_DRAW_CACHE_PUSH_WORD`, also builds every forwarded stage in full and throws when its variant, push constants, bindings or forwarded words differ from the forwarded result | | `APS5_VERIFY_DRAW_RECIPE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCache.cpp` | | re-decodes a draw recipe instead of using the cache and checks the result | | `APS5_VERIFY_DRAW_SNAPSHOTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | re-reads a reused draw snapshot and counts the ones that differ | -| `APS5_VERIFY_GPU_HEAP` | integer | `core/shader/recompiler/HeapCacheSwitch.hpp` | | checks heap slots and GPU-read constants, and rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (0 or no number means every stage) | +| `APS5_VERIFY_GPU_HEAP` | integer | `core/shader/recompiler/HeapCacheSwitch.hpp` | | checks heap slots and GPU-read constants, and rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (0 or no number means every stage); a value that is not a non-negative integer stops the driver with an error naming the variable | | `APS5_VERIFY_GUARD_SPANS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp` | | checks every guard check that the thread's copy of the guard ranges answered without a lock against the guard list and takes the list's answer; a copy that was current, or a copy refilled after the list changed, that still misses an overlapping guard prints a `[guard-spans] verify` line (the first twenty), and a `[guard-spans]` line every 10 s counts the checks and misses (it also prints with `APS5_PROFILE_DRAW`) | | `APS5_VERIFY_KNOWN_VALUES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferCopy.cpp` | | serves known values through the hook too and counts mismatches | | `APS5_VERIFY_OWNED_DRAW_INPUTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | compares reused owned input bytes and throws if they differ while the proof still holds | From 0408022e0cdd1141b21591fdc2c14a7bfe9db1ed Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 05:05:54 +0530 Subject: [PATCH 246/269] fix(agc): scan classic programs' SPIR-V for stores through addresses again The heap branch replaced the SPIR-V scan with the emitter's bdaStores flag on every path, so the heap-off reuse decisions changed. Heap programs need the flag, since their fault report is written through an address and the scan counts that as a store. ProgramStoresThroughAddresses scans classic programs as before and reads the flag only for heap programs, at all three sites. Restore main's scan tests, and check that a classic program storing through an address counts as storing whatever its flag says, and that a heap program follows its flag. --- .../Execution/src/Driver/Draw/Draw.cpp | 2 +- .../Graphics/include/ShaderResources.hpp | 2 + .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 2 +- .../Graphics/src/ShaderAddressResources.cpp | 42 ++++++- .../Graphics/src/ShaderResources.cpp | 2 +- .../libSceAgcDriver/tests/BdaContracts.cpp | 112 ++++++++++++++++++ 6 files changed, 158 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index d3f96eb94937..4a6f6deb3177 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -260,7 +260,7 @@ void noteHeld(HeldReason reason) { std::optional writesBeyondTargets(const ShaderRecompiler::RecompileResult& compiled) { using Role = ShaderRecompiler::DescriptorRole; for (const auto& binding : compiled.bindings) { - if (binding.role == Role::BdaPagetable && compiled.bdaStores) return HeldReason::Bda; + if (binding.role == Role::BdaPagetable && Graphics::ProgramStoresThroughAddresses(compiled)) return HeldReason::Bda; if (binding.role == Role::GuestBuffers) { for (std::uint32_t element = 0; element < binding.count; ++element) { if (element >= binding.bufferWritten.size() || binding.bufferWritten[element]) return HeldReason::Buffer; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index 37792e5d9b54..ae63188c6fba 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -83,6 +83,8 @@ std::shared_ptr CachedSampledTexture(const Context& context, std::span< bool SampledTexturesShareEntry(std::span first, std::span second); bool AnyPendingCpuWrites(const Context& context); bool CompletePendingCpuWrites(const Context& context, std::uint64_t address, std::size_t bytes); +bool SpirvStoresThroughAddresses(std::span words); +bool ProgramStoresThroughAddresses(const ShaderRecompiler::RecompileResult& program); bool SpirvFaultReportOnly(std::span words, std::uint32_t set, std::uint32_t binding); void LastRecordIndices(std::span logged, std::span objects, std::vector& indices); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index ed100573caf3..8e0a412fd453 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -2267,7 +2267,7 @@ AddressStages addressStages(std::span shaders) { auto stages = AddressStages::None; for (const auto& shader : shaders) { if (shader.program == nullptr || std::none_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable; })) continue; - if (shader.program->bdaStores) return AddressStages::Storing; + if (ProgramStoresThroughAddresses(*shader.program)) return AddressStages::Storing; stages = AddressStages::ReadOnly; } return stages; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp index d8dd6b58b0b6..7693369127a7 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderAddressResources.cpp @@ -109,6 +109,21 @@ bool forEachInstruction(std::span words, const TVisit& visi return true; } +bool storesThroughAddressesCached(const ShaderRecompiler::SharedSpirv& spirv) { + static std::mutex mutex; + static std::map, bool> known; + const auto hash = spirv.ContentHash(); + const std::pair key{hash.low, hash.high}; + { + std::lock_guard lock(mutex); + if (const auto found = known.find(key); found != known.end()) return found->second; + } + const bool stores = SpirvStoresThroughAddresses(spirv.Words()); + std::lock_guard lock(mutex); + known.emplace(key, stores); + return stores; +} + bool faultReportOnlyCached(const ShaderRecompiler::SharedSpirv& spirv, std::uint32_t set, std::uint32_t binding) { static std::mutex mutex; static std::map, bool> known; @@ -126,6 +141,31 @@ bool faultReportOnlyCached(const ShaderRecompiler::SharedSpirv& spirv, std::uint } +bool ProgramStoresThroughAddresses(const ShaderRecompiler::RecompileResult& program) { + return program.gpuResolvedImages ? program.bdaStores : storesThroughAddressesCached(program.spirv); +} + +bool SpirvStoresThroughAddresses(std::span words) { + if (words.size() < 5 || words[0] != spv::MagicNumber) return true; + std::unordered_set pointerTypes; + const bool readable = forEachInstruction(words, [&](std::uint32_t opcode, std::span instruction) { + if ((opcode == spv::OpTypePointer || opcode == spv::OpTypeUntypedPointerKHR) && instruction.size() > 2 && instruction[2] == spv::StorageClassPhysicalStorageBuffer) pointerTypes.insert(instruction[1]); + }); + if (!readable) return true; + if (pointerTypes.empty()) return false; + std::unordered_set pointers; + forEachInstruction(words, [&](std::uint32_t opcode, std::span instruction) { + if (instruction.size() > 2 && !definesNoPointerValue(opcode) && pointerTypes.contains(instruction[1])) pointers.insert(instruction[2]); + }); + bool stores = false; + forEachInstruction(words, [&](std::uint32_t opcode, std::span instruction) { + const auto pointer = pointerOperandStored(opcode, instruction); + const bool extendedWithPointer = opcode == spv::OpExtInst && std::any_of(instruction.begin() + static_cast(std::min(5u, instruction.size())), instruction.end(), [&](std::uint32_t operand) { return pointers.contains(operand); }); + stores = stores || extendedWithPointer || (pointer != 0 && pointers.contains(pointer)); + }); + return stores; +} + bool SpirvFaultReportOnly(std::span words, std::uint32_t set, std::uint32_t binding) { constexpr std::uint32_t reportWords = sizeof(ShaderRecompiler::BdaAbi::Fault) / sizeof(std::uint32_t); if (words.size() < 5 || words[0] != spv::MagicNumber) return false; @@ -186,7 +226,7 @@ void ShaderResources::prepareAddressBindings(std::span sha Require(shader.program->bdaAbiVersion == (faults == 0 ? 0u : ShaderRecompiler::BdaAbi::Version), "incompatible BDA ABI version"); // Rect-list validation needs a fault buffer, but never accesses guest addresses. usesBda = usesBda || tables != 0; - if (tables != 0 && shader.program->bdaStores) bdaReadOnly = false; + if (tables != 0 && ProgramStoresThroughAddresses(*shader.program)) bdaReadOnly = false; usesFaultBuffer = usesFaultBuffer || faults != 0; const bool tableFaultsOnly = std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [](const ShaderRecompiler::DescriptorBinding& binding) { return binding.role == ShaderRecompiler::DescriptorRole::ImageTableMap; }); faultChecks = faultChecks || tables != 0 || (faults != 0 && (!tableFaultsOnly || shader.program->imageTableFaults != 0 || shader.program->poisonedSrtReads != 0 || shader.program->windowLaneGuards != 0 || shader.program->descriptorFaults != 0 || loopGuarded)); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 233e0c2e6617..1ab90e2be6d0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -3292,7 +3292,7 @@ std::uint64_t ShaderResources::DepthGuardRefusals() { bool ShaderResources::NeverReusable(std::span shaders) { const bool loopGuard = LoopGuardEnabled(); return std::any_of(shaders.begin(), shaders.end(), [loopGuard](const CompiledShader& shader) { - return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [&](const ShaderRecompiler::DescriptorBinding& binding) { return (binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable && (SpaceReuseDisabled() || shader.program->bdaStores)) || (loopGuard && binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer); }); + return shader.program != nullptr && std::any_of(shader.program->bindings.begin(), shader.program->bindings.end(), [&](const ShaderRecompiler::DescriptorBinding& binding) { return (binding.role == ShaderRecompiler::DescriptorRole::BdaPagetable && (SpaceReuseDisabled() || ProgramStoresThroughAddresses(*shader.program))) || (loopGuard && binding.role == ShaderRecompiler::DescriptorRole::FaultBuffer); }); }); } diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp b/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp index 58a317311dc7..ed99ad4a7111 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaContracts.cpp @@ -2,12 +2,14 @@ #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "ControlFlow/RequestSerializer.hpp" #include "SpirvBackend/SpirvBda.hpp" +#include #include #include #include #include #include #include +#include namespace { @@ -26,6 +28,46 @@ struct ScanWords { } }; +enum ScanId : std::uint32_t { + IdVoid = 1, IdVoidFunction, IdUint, IdUlong, IdUintPointer, IdAddress, IdOne, IdDeviceScope, IdNoSemantics, IdPointerPointer, IdPointerFunction, IdBool, IdTrue, IdFloat, IdFloatPointer, IdGlsl, IdFunctionUintPointer, IdUntypedPointer, IdFloatOne, IdMain, IdMainLabel, IdPointer, IdHelper, IdHelperParameter, IdHelperLabel, IdBody, +}; + +bool ScanStores(const std::function& main, const std::function& after = {}) { + ScanWords module{{spv::MagicNumber, 0x00010500u, 0u, 200u, 0u}}; + module.Op(spv::OpCapability, {spv::CapabilityShader}); + module.Op(spv::OpCapability, {spv::CapabilityInt64}); + module.Op(spv::OpCapability, {spv::CapabilityPhysicalStorageBufferAddresses}); + module.OpString(spv::OpExtInstImport, {IdGlsl}, "GLSL.std.450"); + module.Op(spv::OpMemoryModel, {spv::AddressingModelPhysicalStorageBuffer64, spv::MemoryModelGLSL450}); + module.OpString(spv::OpEntryPoint, {spv::ExecutionModelGLCompute, IdMain}, "main"); + module.Op(spv::OpTypeVoid, {IdVoid}); + module.Op(spv::OpTypeFunction, {IdVoidFunction, IdVoid}); + module.Op(spv::OpTypeInt, {IdUint, 32u, 0u}); + module.Op(spv::OpTypeInt, {IdUlong, 64u, 0u}); + module.Op(spv::OpTypeFloat, {IdFloat, 32u}); + module.Op(spv::OpTypeBool, {IdBool}); + module.Op(spv::OpTypePointer, {IdUintPointer, spv::StorageClassPhysicalStorageBuffer, IdUint}); + module.Op(spv::OpTypePointer, {IdPointerPointer, spv::StorageClassPhysicalStorageBuffer, IdUintPointer}); + module.Op(spv::OpTypePointer, {IdFloatPointer, spv::StorageClassPhysicalStorageBuffer, IdFloat}); + module.Op(spv::OpTypePointer, {IdPointerFunction, spv::StorageClassFunction, IdUint}); + module.Op(spv::OpTypeUntypedPointerKHR, {IdUntypedPointer, spv::StorageClassPhysicalStorageBuffer}); + module.Op(spv::OpTypeFunction, {IdFunctionUintPointer, IdVoid, IdUintPointer}); + module.Op(spv::OpConstant, {IdUlong, IdAddress, 0x1000u, 0u}); + module.Op(spv::OpConstant, {IdUint, IdOne, 1u}); + module.Op(spv::OpConstant, {IdUint, IdDeviceScope, spv::ScopeDevice}); + module.Op(spv::OpConstant, {IdUint, IdNoSemantics, 0u}); + module.Op(spv::OpConstant, {IdFloat, IdFloatOne, 0x3f800000u}); + module.Op(spv::OpConstantTrue, {IdBool, IdTrue}); + module.Op(spv::OpFunction, {IdVoid, IdMain, spv::FunctionControlMaskNone, IdVoidFunction}); + module.Op(spv::OpLabel, {IdMainLabel}); + module.Op(spv::OpConvertUToPtr, {IdUintPointer, IdPointer, IdAddress}); + main(module); + module.Op(spv::OpReturn, {}); + module.Op(spv::OpFunctionEnd, {}); + if (after) after(module); + return AgcDriver::Graphics::SpirvStoresThroughAddresses(module.words); +} + enum FaultScanId : std::uint32_t { FaultVoid = 1, FaultVoidFunction, FaultUint, FaultWords, FaultBlock, FaultBlockPointer, FaultWordPointer, FaultHelperFunction, FaultVariable, FaultZero, FaultReportLast, FaultOverflowWord, FaultScope, FaultSemantics, FaultMain, FaultMainLabel, FaultHelper, FaultHelperParameter, FaultHelperLabel, FaultBody, }; @@ -95,6 +137,53 @@ void RunFaultReportScanTests() { }), "fault scan: the fault buffer handed to a function was not followed"); } +void RunAddressStoreScanTests() { + using AgcDriver::Graphics::Require; + Require(!ScanStores([](ScanWords& m) { m.Op(spv::OpLoad, {IdUint, IdBody, IdPointer}); }), "store scan: a load through a physical pointer was taken for a store"); + Require(!ScanStores([](ScanWords& m) { m.Op(spv::OpAtomicLoad, {IdUint, IdBody, IdPointer, IdDeviceScope, IdNoSemantics}); }), "store scan: an atomic load was taken for a store"); + Require(ScanStores([](ScanWords& m) { m.Op(spv::OpStore, {IdPointer, IdOne}); }), "store scan: a store was missed"); + Require(ScanStores([](ScanWords& m) { m.Op(spv::OpAtomicStore, {IdPointer, IdDeviceScope, IdNoSemantics, IdOne}); }), "store scan: an atomic store was missed"); + for (const auto opcode : {spv::OpAtomicExchange, spv::OpAtomicIAdd, spv::OpAtomicISub, spv::OpAtomicSMin, spv::OpAtomicUMin, spv::OpAtomicSMax, spv::OpAtomicUMax, spv::OpAtomicAnd, spv::OpAtomicOr, spv::OpAtomicXor}) { + Require(ScanStores([opcode](ScanWords& m) { m.Op(opcode, {IdUint, IdBody, IdPointer, IdDeviceScope, IdNoSemantics, IdOne}); }), "store scan: atomic opcode " + std::to_string(static_cast(opcode)) + " was missed"); + } + Require(ScanStores([](ScanWords& m) { m.Op(spv::OpAtomicIIncrement, {IdUint, IdBody, IdPointer, IdDeviceScope, IdNoSemantics}); }), "store scan: an atomic increment was missed"); + Require(ScanStores([](ScanWords& m) { m.Op(spv::OpAtomicCompareExchange, {IdUint, IdBody, IdPointer, IdDeviceScope, IdNoSemantics, IdNoSemantics, IdOne, IdOne}); }), "store scan: an atomic compare-exchange was missed"); + Require(ScanStores([](ScanWords& m) { + m.Op(spv::OpConvertUToPtr, {IdPointerPointer, IdBody, IdAddress}); + m.Op(spv::OpLoad, {IdUintPointer, IdBody + 1u, IdBody}); + m.Op(spv::OpStore, {IdBody + 1u, IdOne}); + }), "store scan: a store through a pointer loaded from guest memory was missed"); + Require(ScanStores([](ScanWords& m) { + m.Op(spv::OpSelect, {IdUintPointer, IdBody, IdTrue, IdPointer, IdPointer}); + m.Op(spv::OpStore, {IdBody, IdOne}); + }), "store scan: a store through a selected pointer was missed"); + Require(ScanStores([](ScanWords& m) { m.Op(spv::OpFunctionCall, {IdVoid, IdBody, IdHelper, IdPointer}); }, [](ScanWords& m) { + m.Op(spv::OpFunction, {IdVoid, IdHelper, spv::FunctionControlMaskNone, IdFunctionUintPointer}); + m.Op(spv::OpFunctionParameter, {IdUintPointer, IdHelperParameter}); + m.Op(spv::OpLabel, {IdHelperLabel}); + m.Op(spv::OpStore, {IdHelperParameter, IdOne}); + m.Op(spv::OpReturn, {}); + m.Op(spv::OpFunctionEnd, {}); + }), "store scan: a store through a pointer parameter of a called function was missed"); + Require(!ScanStores([](ScanWords& m) { + m.Op(spv::OpVariable, {IdPointerFunction, IdBody, spv::StorageClassFunction}); + m.Op(spv::OpCopyMemory, {IdBody, IdPointer}); + }), "store scan: a copy out of guest memory was taken for a store"); + Require(ScanStores([](ScanWords& m) { + m.Op(spv::OpVariable, {IdPointerFunction, IdBody, spv::StorageClassFunction}); + m.Op(spv::OpCopyMemory, {IdPointer, IdBody}); + }), "store scan: a copy into guest memory was missed"); + Require(ScanStores([](ScanWords& m) { + m.Op(spv::OpConvertUToPtr, {IdUntypedPointer, IdBody, IdAddress}); + m.Op(spv::OpStore, {IdBody, IdOne}); + }), "store scan: a store through an untyped physical pointer was missed"); + Require(ScanStores([](ScanWords& m) { + m.Op(spv::OpConvertUToPtr, {IdFloatPointer, IdBody, IdAddress}); + m.Op(spv::OpExtInst, {IdFloat, IdBody + 1u, IdGlsl, GLSLstd450Modf, IdFloatOne, IdBody}); + }), "store scan: an extended instruction writing through a physical pointer was missed"); + Require(ScanStores([](ScanWords& m) { m.Op(spv::OpCooperativeMatrixStoreKHR, {IdPointer, IdOne, IdNoSemantics}); }), "store scan: a cooperative matrix store was missed"); +} + template void reject(TAction action, const char* expected) { @@ -121,11 +210,34 @@ std::uint32_t CallSites(const std::vector& spirv, const char* nam void RunBdaContractTests() { using namespace ShaderRecompiler; + using AgcDriver::Graphics::SpirvStoresThroughAddresses; + RunAddressStoreScanTests(); RunFaultReportScanTests(); + AgcDriver::Graphics::Require(!SpirvStoresThroughAddresses(MakeBdaTestShader(0x1000, 32)), "a BDA read was taken for a store through an address"); + AgcDriver::Graphics::Require(!SpirvStoresThroughAddresses(MakeBdaDwordReadTestShader(0x1000, 4, false, false)), "BDA dword reads were taken for a store through an address"); + AgcDriver::Graphics::Require(SpirvStoresThroughAddresses(MakeBdaStoreTestShader(0x1000, 7, 32, false)), "a BDA store was not seen"); + AgcDriver::Graphics::Require(SpirvStoresThroughAddresses(MakeBdaWriteTestShader(0x1000, 7, 32, false)), "a BDA write was not seen"); + const std::array stored{7u, 9u}; + AgcDriver::Graphics::Require(SpirvStoresThroughAddresses(MakeBdaDwordWriteTestShader(0x1000, static_cast(stored.size()), stored.data())), "BDA dword writes were not seen"); const std::array headerOnly{spv::MagicNumber, 0x00010300u, 0u, 1u, 0u}; + AgcDriver::Graphics::Require(!SpirvStoresThroughAddresses(headerOnly), "a module without physical pointers was taken for one storing through addresses"); const std::array truncated{spv::MagicNumber, 0u}; + AgcDriver::Graphics::Require(SpirvStoresThroughAddresses(truncated), "an unreadable module was taken for one without stores"); auto unparsed = MakeBdaStoreTestShader(0x1000, 7, 32, false); unparsed[5] |= 0xffff0000u; + AgcDriver::Graphics::Require(SpirvStoresThroughAddresses(unparsed), "a module with an instruction past its end was taken for one without stores"); + RecompileResult classic; + classic.spirv = SharedSpirv(MakeBdaStoreTestShader(0x1000, 7, 32, false)); + AgcDriver::Graphics::Require(AgcDriver::Graphics::ProgramStoresThroughAddresses(classic), "a classic program's BDA store was taken from the emitter flag instead of its SPIR-V"); + classic.spirv = SharedSpirv(MakeBdaTestShader(0x1000, 32)); + classic.bdaStores = true; + AgcDriver::Graphics::Require(!AgcDriver::Graphics::ProgramStoresThroughAddresses(classic), "a classic program reading through an address was taken for one storing"); + RecompileResult heap; + heap.gpuResolvedImages = true; + heap.spirv = SharedSpirv(MakeBdaStoreTestShader(0x1000, 7, 32, false)); + AgcDriver::Graphics::Require(!AgcDriver::Graphics::ProgramStoresThroughAddresses(heap), "a heap program's stores were not taken from the emitter flag"); + heap.bdaStores = true; + AgcDriver::Graphics::Require(AgcDriver::Graphics::ProgramStoresThroughAddresses(heap), "a heap program's BDA store flag was ignored"); using AgcDriver::Graphics::SpirvFaultReportOnly; AgcDriver::Graphics::Require(SpirvFaultReportOnly(MakeBdaTestShader(0x1000, 32), 0, 1) && SpirvFaultReportOnly(MakeBdaDwordReadTestShader(0x1000, 4, false, false), 0, 1) && SpirvFaultReportOnly(MakeBdaFaultSequenceTestShader({BdaAbi::FaultReason::Unmapped, BdaAbi::FaultReason::Unaligned}), 0, 1), "a BDA read program, which writes only the fault report, was given a full fault buffer"); AgcDriver::Graphics::Require(!SpirvFaultReportOnly(MakeBdaStoreTestShader(0x1000, 7, 32, false), 0, 1) && !SpirvFaultReportOnly(MakeBdaWriteTestShader(0x1000, 7, 32, false), 0, 1), "a BDA store program, which records written pages, was given a report-only fault buffer"); From 80e7d90049afc8cdc5fb7746d2f866343acd77e3 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 05:05:54 +0530 Subject: [PATCH 247/269] fix(agc): request device addresses for the heap CMASK error buffer itself The buffer's address is queried for the heap CMASK pipeline. It got the device-address usage only because heap mode forces it on every storage buffer; ask for it where the heap pipeline exists. --- core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp index 0b3c601ad64c..79567f47b82f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/TextureDetiler.cpp @@ -548,7 +548,7 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask } context.Function("vkDestroyShaderModule")(context.device, cmaskModule, nullptr); Check(created, "vkCreateComputePipelines CMASK clear"); - cmaskErrors = std::make_unique(context, 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + cmaskErrors = std::make_unique(context, 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (cmaskHeapPipeline != VK_NULL_HANDLE ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u)); std::memset(cmaskErrors->Bytes().data(), 0, 4); } const auto cmaskAddress = cmaskHeapPipeline != VK_NULL_HANDLE && owner != nullptr ? bufferAddress(cmask) : 0; From 61b508ce05a6003dfa4455090223385f59ff98eb Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 05:05:55 +0530 Subject: [PATCH 248/269] fix(agc): decline misaligned heap walk reads and reset stale stage views readWalkWord recorded reads at any address, while the range copy sizes ranges in whole words and copies their bytes, so overlapping misaligned reads could write past the copy. Reject them as readWalkWords does; the walk then declines and the stage takes the per-draw capture. Also reset a stage's registered views and supplied blocks with its other capture fields, so a heap-direct stage does not keep the previous draw's. --- .../libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp | 2 ++ .../libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 6d9d773bf082..a00cfb4b1dd9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -369,6 +369,8 @@ std::shared_ptr Driver::materializeDraw stageCapture.origin = StageOrigin::Captured; stageCapture.heapReadWords.reset(); stageCapture.capture.reset(); + stageCapture.registeredViews.reset(); + stageCapture.supplied.clear(); stageCapture.forgetSerial = GuestMemory::ForgetSerial(); stageCapture.pushOffset = pushOffset; static const bool dumpGraphics = std::getenv("APS5_DUMP_GRAPHICS_SHADERS") != nullptr; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 1a386183e9d4..95f0b35cdb36 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -357,6 +357,10 @@ struct WalkReads { bool readWalkWord(void* context, std::uint64_t address, std::uint32_t* value) { auto& reads = *static_cast(context); + if (address % WordBytes != 0u) { + reads.failed = true; + return false; + } if (!reads.Verified(address, sizeof(*value))) { const auto page = address & ~(WalkPageBytes - 1u); const bool crossesPage = (address & (WalkPageBytes - 1u)) > WalkPageBytes - sizeof(*value); From 2ddef166a0aee0b0085ee49482ae4d75497159d3 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 05:05:55 +0530 Subject: [PATCH 249/269] fix(agc): tag heap retirements only after the submit succeeds Submitted gave the batch's retirements and pool blocks the next serial before vkQueueSubmit, so a failed submit left them waiting on a serial that never completes. --- core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 57d7cbf9ca7d..e9a2e2149c2d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -4730,7 +4730,6 @@ void Recorder::Submit() { VkSubmitInfo submission{VK_STRUCTURE_TYPE_SUBMIT_INFO}; submission.commandBufferCount = 1; submission.pCommandBuffers = &batch->commands; - if (auto* heap = DescriptorHeapEnabled() ? BindlessHeap::Existing(context) : nullptr; heap != nullptr) heap->Submitted(*this, submissions + 1); // The timeline reaches this batch's serial when it completes (see WaitSerial). const std::uint64_t serial = submissions + 1; if (CheckpointMarkersEnabled() && batch->queue == 0 && batch->predictedSerial != 0) { @@ -4777,6 +4776,7 @@ void Recorder::Submit() { if (batch->guestWork) LibcRunReportMilestone_nid_no_patch(2); batch->submitted = true; batch->serial = ++submissions; + if (auto* heap = DescriptorHeapEnabled() ? BindlessHeap::Existing(context) : nullptr; heap != nullptr) heap->Submitted(*this, batch->serial); batch->submittedAt = std::chrono::steady_clock::now(); CaptureTrace::Log("submit-confirmed batch=%llu tokens=%s", static_cast(batch->serial), tokensStr.c_str()); if (DrawProfiled()) { From e86466657ea0a92029a35d82b095e1246caa4cd0 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 05:05:55 +0530 Subject: [PATCH 250/269] fix(agc): lock the pipeline cache when creating heap stage pipelines CreateHeapStagePipeline used the pipeline cache without the use lock its neighbours take. The upscaler held that shared lock across its heap create, which would now take it twice, so its lock covers only the classic create. --- .../libSceAgcDriver/Execution/src/PresentationUpscaler.cpp | 6 ++++-- core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp index 996374c02445..fada79f48e68 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PresentationUpscaler.cpp @@ -314,8 +314,10 @@ const PresentationUpscaler::Target& PresentationUpscaler::target(VkFormat format pipelineInfo.pDynamicState = &dynamic; pipelineInfo.layout = pipelineLayout; pipelineInfo.renderPass = created.renderPass; - const auto lock = context.LockPipelineCacheForUse(); - Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.pipeline), "vkCreateGraphicsPipelines presentation upscaler"); + { + const auto lock = context.LockPipelineCacheForUse(); + Graphics::Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.pipeline), "vkCreateGraphicsPipelines presentation upscaler"); + } if (heap) { const auto mapping = Graphics::HeapPushSampledImageMapping(Graphics::BindlessHeap::For(context), 0, 0, offsetof(HeapPush, slot), samplerInfo); created.heapPipeline = Graphics::CreateHeapStagePipeline(context, pipelineInfo, 1, std::span(&mapping, 1), "vkCreateGraphicsPipelines presentation upscaler heap"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index 862f7e39455b..cb00754f0680 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -1499,6 +1499,7 @@ VkPipeline CreateHeapStagePipeline(const Context& context, VkGraphicsPipelineCre info.pNext = &heapFlags; info.layout = VK_NULL_HANDLE; VkPipeline pipeline = VK_NULL_HANDLE; + auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &info, nullptr, &pipeline), what); return pipeline; } From b65ae79b9c385083d36d4add6e62ec9d7e0bea3a Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 23:50:54 +0530 Subject: [PATCH 251/269] fix(agc): keep heap stage reads and queued writes consistent on the draw path A1: drop a stage's earlier heap-read regions from the draw's memory view before it is recaptured, so the spans never point into heapReadWords that the recapture resets. A2: the heap walk's pending-write check also runs on the draw finisher thread, where the thread-local pipeline flag is false, so a queued descriptor-table write is no longer missed. A new test enqueues a Queue0 write over the table and runs the walk on the finisher. A19: heap exclusion preparation for a dispatch runs inside the refused-dispatch handling, so a preparation exception is skipped or reported like the others. A20: a nonzero APS5_DUMP_DRAW_SHADERS or APS5_DUMP_DRAW_SLOT1 target forces a full capture without APS5_PROFILE_DRAW. --- .../src/Driver/Dispatch/Dispatch.cpp | 22 ++- .../Execution/src/Driver/Draw/DrawCapture.cpp | 10 +- .../Execution/src/Driver/Draw/HeapStages.cpp | 10 +- ...ver_heap_finisher_queued_write_tests.cmake | 3 + .../execution/HeapFinisherQueuedWrite.cpp | 141 ++++++++++++++++++ 5 files changed, 179 insertions(+), 7 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_heap_finisher_queued_write_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/HeapFinisherQueuedWrite.cpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index ba32f008a67b..4243745aca7f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -248,10 +248,24 @@ void Driver::dispatch(QueueState& queue, std::span packet, }; if (request.target.gpuResolvedImages && HeapStageExcluded(ShaderRecompiler::ShaderStage::Compute)) request.target.gpuResolvedImages = false; if (request.target.gpuResolvedImages && HeapClassesExcluded()) { - const auto invocation = InvocationFor(snapshot, codeOffset, request); - if (HeapExcludedFor(invocation)) { - Graphics::NoteHeapExcluded(Graphics::HeapExcluded::Dispatch); - request.target.gpuResolvedImages = false; + try { + const auto invocation = InvocationFor(snapshot, codeOffset, request); + if (HeapExcludedFor(invocation)) { + Graphics::NoteHeapExcluded(Graphics::HeapExcluded::Dispatch); + request.target.gpuResolvedImages = false; + } + } catch (const DrawCompilePending&) { + return; + } catch (const std::exception& error) { + std::string reason = error.what(); + if (const auto newline = reason.find('\n'); newline != std::string::npos) reason.resize(newline); + if (SkipRefusedDispatches()) { + ReportRefusedDispatch(address, reason); + return; + } + char where[96]; + std::snprintf(where, sizeof(where), "compute shader 0x%llx: ", static_cast(address)); + throw std::runtime_error(where + reason); } } static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index a00cfb4b1dd9..80562067849e 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -212,6 +212,13 @@ std::function reboundWork(const ShaderRecompiler::PreparedSha }; } +void dropHeapReadRegions(std::vector& memory, const StageCapture& stage) { + if (stage.heapReadWords == nullptr || stage.heapReadWords->empty()) return; + const auto* first = reinterpret_cast(stage.heapReadWords->data()); + const auto* last = first + stage.heapReadWords->size() * sizeof(std::uint32_t); + std::erase_if(memory, [&](const ShaderRecompiler::MemoryRegion& region) { return region.bytes.data() >= first && region.bytes.data() < last; }); +} + constexpr std::uint64_t HeapTemplateJob = std::uint64_t{1} << 63u; } @@ -340,6 +347,7 @@ std::shared_ptr Driver::materializeDraw PerformanceTimer timing("Shader.DrawStage"); using Stage = ShaderRecompiler::ShaderStage; context.phaseTiming.Phase(DrawRowVectors); + dropHeapReadRegions(context.memory, context.stageCaptures[i]); const auto& program = context.programs[i]; auto request = drawStageRequest(context, i, pushOffset, drawParameters); @@ -374,7 +382,7 @@ std::shared_ptr Driver::materializeDraw stageCapture.forgetSerial = GuestMemory::ForgetSerial(); stageCapture.pushOffset = pushOffset; static const bool dumpGraphics = std::getenv("APS5_DUMP_GRAPHICS_SHADERS") != nullptr; - const bool captured = dumpGraphics || traceCapSync() || (context.profile && (context.dumpTarget != 0 || context.dumpSlot1 != 0)); + const bool captured = dumpGraphics || traceCapSync() || context.dumpTarget != 0 || context.dumpSlot1 != 0; if (request.target.gpuResolvedImages && !captured) { if (materializeHeapDirect(context, i, invocation, request, timing)) return stageCapture.compiled; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp index 95f0b35cdb36..3b1f214b3074 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/HeapStages.cpp @@ -405,9 +405,15 @@ bool readWalkWords(void* context, std::uint64_t address, std::uint32_t* values, return true; } +bool queuedWriteOverlaps(std::span> ranges) { + if (!DrawPipeline::Active() && !DrawFinisher::OnFinisherThread()) return false; + auto& queue = DrawPipeline::Queue0(); + return queue.Busy() && queue.OverlapsAny(ranges); +} + bool walkPending(const WalkReads& reads, std::uint64_t address, std::uint64_t bytes) { const std::array range{std::pair{address, address + bytes}}; - const bool queuedWrite = DrawPipeline::Active() && DrawPipeline::Queue0().Busy() && DrawPipeline::Queue0().OverlapsAny(range); + const bool queuedWrite = queuedWriteOverlaps(range); return queuedWrite || !Graphics::Recorder::ReadsSettled(range, reads.before); } @@ -504,7 +510,7 @@ void copyRangeValues(const AddressRanges& ranges, std::span +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif + +namespace { + +using AgcDriver::Graphics::Require; +using namespace ShaderRecompiler; + +constexpr std::uint32_t Entries = 1024; +constexpr std::size_t BlockBytes = 65536; +constexpr std::array Code{0xbf068002u, 0xbf850013u, 0xf4080100u, 0xfa000000u, 0xf4080200u, 0xfa000010u, 0xf4080300u, 0xfa000020u, 0xf4080700u, 0xfa000030u, 0x7e200500u, 0x93109010u, + 0xf4200406u, 0x20000004u, 0x8f108510u, 0xf42c0502u, 0x20000000u, 0xf09c0f08u, 0x00450000u, 0xe0700000u, 0x80070000u, 0xbf810000u, 0xbf800000u}; +alignas(256) std::array, 3> Textures{}; +alignas(256) std::array Output{}; +alignas(256) std::array Srt{}; + +std::array Buffer(const void* pointer, std::uint32_t stride, std::uint32_t records) { + const auto address = reinterpret_cast(pointer); + return {static_cast(address), static_cast(address >> 32u) | (stride << 16u), records, stride == 0u ? 0x31016facu : 0x01016facu}; +} + +std::array Texture(std::uint32_t texture) { + const auto address = reinterpret_cast(Textures[texture].data()); + return {static_cast(address >> 8u), static_cast(address >> 40u) | ((texture == 1u ? 22u : 20u) << 20u) | (3u << 30u), 7u, 0x90000facu, 0u, 0u, 0u, 0u}; +} + +std::uint8_t* WatchedPages(std::size_t bytes) { +#ifdef _WIN32 + auto* data = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(bytes, BlockBytes)); + Require(data != nullptr, "heap finisher queued write: cannot allocate the table pages"); + GuestArena::GuestArenaCommit_nid_postfix(data, bytes, PAGE_READWRITE, bytes); + return data; +#else + void* mapped = mmap(nullptr, bytes + BlockBytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + Require(mapped != MAP_FAILED, "heap finisher queued write: cannot map the table pages"); + auto* data = reinterpret_cast((reinterpret_cast(mapped) + BlockBytes - 1u) & ~std::uintptr_t{BlockBytes - 1u}); + GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(data, bytes); + return data; +#endif +} + +void Run(AgcDriver::VulkanDevice& device) { + using namespace AgcDriver::DriverDetail; + constexpr std::size_t TableBytes = BlockBytes; + auto* base = WatchedPages(TableBytes * 2u); + auto* table = reinterpret_cast(base); + auto* material = reinterpret_cast(base + TableBytes); + for (std::uint32_t entry = 0; entry < Entries; ++entry) { + const auto descriptor = Texture(entry % 2u); + std::copy(descriptor.begin(), descriptor.end(), table + entry * 8u); + material[entry * 4u + 1u] = entry; + } + const auto tableBuffer = Buffer(table, 32u, Entries); + const auto materialBuffer = Buffer(material, 16u, Entries); + const auto output = Buffer(Output.data(), 0u, 256u); + std::copy(tableBuffer.begin(), tableBuffer.end(), Srt.begin()); + std::copy(materialBuffer.begin(), materialBuffer.end(), Srt.begin() + 8u); + std::copy(output.begin(), output.end(), Srt.begin() + 12u); + const auto srtAddress = reinterpret_cast(Srt.data()); + const std::vector userData{static_cast(srtAddress), static_cast(srtAddress >> 32u), 1u}; + const std::array regions{MemoryRegion{reinterpret_cast(Code.data()), std::as_bytes(std::span(Code))}}; + const ShaderComputeStageInfo compute{{std::min(32u, device.Target().subgroupSize), 1u, 1u}, 0u, {false, false, false}, false, 1u}; + auto target = device.Target(); + target.gpuResolvedImages = true; + std::vector prepared(regions.begin(), regions.end()); + RecompileRequest request{{ShaderStage::Compute, reinterpret_cast(Code.data()), Code, 0u, {}}, {32u, 0u, userData, compute, std::nullopt, std::nullopt, prepared}, target, {0u, 0u, 0u, 128u}}; + const auto handle = PrepareShader(request); + const auto invocation = PreparedShaderInvocation::TryCreate(request, handle); + Require(invocation.has_value(), "heap finisher queued write: the prepared table shader refused its own request"); + const auto walk = [&] { return MaterializeHeapStageSettled(*invocation, userData, regions, request.shader.codeAddress); }; + + const auto settled = walk(); + Require(settled.result != nullptr && settled.reads.complete, "heap finisher queued write: the heap walk declined the table stage with nothing queued"); + + const auto tableBegin = reinterpret_cast(table); + std::promise release; + const auto released = release.get_future().share(); + DrawPipeline::Queue0().Enqueue([released] { released.wait(); }, {{tableBegin + 5u * 8u * sizeof(std::uint32_t), tableBegin + 6u * 8u * sizeof(std::uint32_t)}}); + Require(DrawPipeline::Queue0().OverlapsAny(std::array{std::pair{tableBegin, tableBegin + TableBytes}}), "heap finisher queued write: the queued descriptor table write is not listed"); + + HeapStageMaterialized onFinisher; + bool ranOnFinisher = false; + std::exception_ptr failure; + DrawFinisher::Get().Enqueue([&] { + ranOnFinisher = DrawFinisher::OnFinisherThread(); + try { + onFinisher = walk(); + } catch (...) { + failure = std::current_exception(); + } + }); + DrawFinisher::Get().Drain(); + release.set_value(); + DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet); + if (failure != nullptr) std::rethrow_exception(failure); + Require(ranOnFinisher, "heap finisher queued write: the walk did not run on the finisher thread"); + Require(onFinisher.result == nullptr, "heap finisher queued write: a finisher walk read a descriptor table that a queued write overlaps"); + + const auto after = walk(); + Require(after.result != nullptr && after.reads.complete, "heap finisher queued write: the heap walk declined the table stage once the write retired"); +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) return VulkanTestSkipped; + Run(*device); + std::cout << "heap finisher queued write tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} From 875ebe853677e5f63db64b6bd612c607f3281e1e Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 23:50:54 +0530 Subject: [PATCH 252/269] fix(agc): cover uniform reads in dispatch barrier elision and skip heap compute capture A3: the trailing dispatch barrier makes uniform reads visible and the leading barrier is elided only when uniform reads are covered too. A4: heap compute pipelines are not captured, since a capture keeps neither their descriptor heap mappings nor the heap image slot specialization. A new run test dispatches a heap compute shader with the dump directory set and expects no capture. --- .../Execution/src/VulkanDevice.cpp | 6 ++-- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 2 +- .../tests/ComputePipelineCaptureHeapRun.cmake | 30 +++++++++++++++++++ .../agc_compute_pipeline_capture_tests.cmake | 8 +++++ 4 files changed, 42 insertions(+), 4 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/ComputePipelineCaptureHeapRun.cmake diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 4f790d301233..0f5f7d87564c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -6123,7 +6123,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { recorder.NotePendingRead(arguments, 12, Graphics::Recorder::ReadKind::Indirect); } // Results of earlier recorded work are visible to this dispatch, its own to everything after. - constexpr VkAccessFlags shaderAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + constexpr VkAccessFlags shaderAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_UNIFORM_READ_BIT; if (overlapped) { if (record.refreshed) { Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT); @@ -6293,7 +6293,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { resources.CopyBacksAfterRun(record.resources); } else { const auto trailingTiming = recorder.BeginGpuTiming(CommandClass::DispatchTrailing); - constexpr VkAccessFlags dispatchedAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; + constexpr VkAccessFlags dispatchedAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, dispatchedAccess); Graphics::Recorder::CountBarriers(CommandClass::DispatchTrailing); recorder.EndGpuTiming(trailingTiming); @@ -6364,7 +6364,7 @@ std::shared_ptr VulkanDevice::createComputePipeline(cons if (heapDevice) specialization.PlaceHeapImageSlots(Graphics::BindlessHeap::For(context).ImageSlots()); const auto subgroupSize = computeSubgroupSize(shader); const auto stageFlags = computeStageFlags(shader); - if (const auto* directory = ComputePipelineDumpDirectory(); directory != nullptr && *directory != 0 && !state->probingFloatControls && ComputePipelineCapture::OptionalEnabled() && CaptureComputePipeline(shader.spirv.size())) { + if (const auto* directory = ComputePipelineDumpDirectory(); directory != nullptr && *directory != 0 && !gpuMode && !state->probingFloatControls && ComputePipelineCapture::OptionalEnabled() && CaptureComputePipeline(shader.spirv.size())) { ComputePipelineCapture capture; capture.spirv = shader.spirv.Copy(); ComputeDescriptorSetLayout resourcesLayout; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 12f40592e07e..2751e6028bc4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -1933,7 +1933,7 @@ void Recorder::flushDeferredDispatch() { open->runAccess.clear(); auto after = std::move(open->afterRun); open->afterRun.clear(); - constexpr VkAccessFlags dispatchedAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; + constexpr VkAccessFlags dispatchedAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; recordBarrier(open->commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, dispatchedAccess); CountBarriers(CommandClass::DispatchTrailing); open->coveredAccess = dispatchedAccess; diff --git a/core/libs/prx/libSceAgcDriver/tests/ComputePipelineCaptureHeapRun.cmake b/core/libs/prx/libSceAgcDriver/tests/ComputePipelineCaptureHeapRun.cmake new file mode 100644 index 000000000000..13d4d8fc144a --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/ComputePipelineCaptureHeapRun.cmake @@ -0,0 +1,30 @@ +foreach(required IN ITEMS FIXTURE OUTPUT_ROOT) + if(NOT DEFINED ${required}) + message(FATAL_ERROR "Missing ${required}") + endif() +endforeach() +string(RANDOM LENGTH 16 ALPHABET 0123456789abcdef runId) +set(runDirectory "${OUTPUT_ROOT}/compute-capture-heap-${runId}") +set(captureDirectory "${runDirectory}/captures") +file(MAKE_DIRECTORY "${runDirectory}") +execute_process( + COMMAND "${CMAKE_COMMAND}" -E env "ANYPS5_REQUIRE_VULKAN=1" "ANYPS5_NO_SHADER_CACHE=1" "APS5_GPU_HEAP=1" "APS5_PIPELINE_STATS=0" "APS5_DUMP_COMPUTE_PIPELINES=${captureDirectory}" "APS5_DUMP_COMPUTE_MIN_WORDS=0" "${FIXTURE}" + WORKING_DIRECTORY "${runDirectory}" + RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error TIMEOUT 20 +) +file(WRITE "${runDirectory}/heap.log" "${output}\n${error}") +if(result STREQUAL "77") + message(STATUS "compute pipeline heap capture run: skipped, no usable Vulkan device") + file(REMOVE_RECURSE "${runDirectory}") + return() +endif() +if(NOT result STREQUAL "0" OR NOT output MATCHES "compute stages sampled their textures through the heap") + message(FATAL_ERROR "Heap compute fixture failed: ${result}\n${output}\n${error}") +endif() +file(GLOB captures "${captureDirectory}/compute-*/capture.aps5cp") +list(LENGTH captures count) +if(NOT count EQUAL 0) + message(FATAL_ERROR "Heap compute pipelines were captured, but a capture does not preserve their descriptor heap mappings: ${captures}") +endif() +message(STATUS "Heap compute fixture ran with no captured pipelines") +file(REMOVE_RECURSE "${runDirectory}") diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_compute_pipeline_capture_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_compute_pipeline_capture_tests.cmake index 2367926617c5..9361457b1440 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_compute_pipeline_capture_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_compute_pipeline_capture_tests.cmake @@ -27,3 +27,11 @@ if(BUILD_TESTING AND ANYPS5_ENABLE_SPIRV_TOOLS) -P ${CMAKE_CURRENT_SOURCE_DIR}/tests/ComputePipelineCaptureRun.cmake) set_tests_properties(agc_compute_pipeline_capture_run PROPERTIES TIMEOUT 30 SKIP_REGULAR_EXPRESSION "compute pipeline capture run: skipped, no usable Vulkan device") endif() + +if(BUILD_TESTING) + add_test(NAME agc_compute_pipeline_capture_heap_run COMMAND ${CMAKE_COMMAND} + -DFIXTURE=$ + -DOUTPUT_ROOT=${CMAKE_CURRENT_BINARY_DIR}/capture-tests + -P ${CMAKE_CURRENT_SOURCE_DIR}/tests/ComputePipelineCaptureHeapRun.cmake) + set_tests_properties(agc_compute_pipeline_capture_heap_run PROPERTIES TIMEOUT 30 SKIP_REGULAR_EXPRESSION "compute pipeline heap capture run: skipped") +endif() From 882d2c38f0e1dc597b59954f3cf48ef5627771e2 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 23:50:54 +0530 Subject: [PATCH 253/269] fix(agc): key descriptor heap object hooks and records by device A5: the real vkCreateImageView, vkDestroyImageView, vkCreateSampler and vkDestroySampler pointers are kept per VkDevice and each wrapper dispatches through the entry of its own device argument, instead of one process-wide pointer the last resolving device overwrote. A6: image view and sampler records, and the encoded descriptors kept with a view, are keyed by device and handle, and the lookup, copy and keep calls take the device. A new host-only test drives two fake devices through the hooks. --- .../include/DescriptorHeapObjects.hpp | 8 +- .../Graphics/src/BindlessHeap.cpp | 8 +- .../Graphics/src/DescriptorHeapObjects.cpp | 113 ++++++++++------- .../tests/BindlessHeapSlots.cpp | 4 +- .../tests/DescriptorHeapObjectDevices.cpp | 120 ++++++++++++++++++ ...descriptor_heap_object_devices_tests.cmake | 12 ++ 6 files changed, 212 insertions(+), 53 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_descriptor_heap_object_devices_tests.cmake diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp index ac2b8a2ff592..a765f9356227 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp @@ -28,10 +28,10 @@ struct SamplerRecord { }; PFN_vkVoidFunction DescriptorHeapObjectFunction(VkDevice device, PFN_vkGetDeviceProcAddr deviceProc, const char* name); -std::optional FindImageView(VkImageView view); -std::optional FindSampler(VkSampler sampler); -bool CopyEncodedImageView(VkImageView view, std::uint32_t key, std::span target); -void KeepEncodedImageView(VkImageView view, std::uint64_t generation, std::uint32_t key, std::span bytes); +std::optional FindImageView(VkDevice device, VkImageView view); +std::optional FindSampler(VkDevice device, VkSampler sampler); +bool CopyEncodedImageView(VkDevice device, VkImageView view, std::uint32_t key, std::span target); +void KeepEncodedImageView(VkDevice device, VkImageView view, std::uint64_t generation, std::uint32_t key, std::span bytes); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index cb00754f0680..dfc634ab8bbf 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -945,7 +945,7 @@ std::pair BindlessHeap::DataLocation(VkDeviceAddress add } void BindlessHeap::writeSamplerSlot(std::uint32_t slot, VkSampler sampler) { - auto record = FindSampler(sampler); + auto record = FindSampler(context.device, sampler); Require(record.has_value(), "a GPU heap sampler has no recorded create info"); const auto offset = static_cast(slot) * samplerHeapStride; Require(offset + samplerHeapStride <= samplerHeapUsed, "a GPU heap sampler slot lies outside the sampler heap"); @@ -965,11 +965,11 @@ void BindlessHeap::writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImag const bool storage = Abi::GpuHeapStorageKind(kind); const auto key = static_cast(layout) | (storage ? 0x80000000u : 0u); const auto stride = static_cast(imageHeapStride); - if (CopyEncodedImageView(view, key, std::span(target, stride))) { + if (CopyEncodedImageView(context.device, view, key, std::span(target, stride))) { ++counts.encodedCopies; return; } - auto record = FindImageView(view); + auto record = FindImageView(context.device, view); Require(record.has_value(), "a GPU heap image view has no recorded create info"); const VkImageDescriptorInfoEXT imageInfo{VK_STRUCTURE_TYPE_IMAGE_DESCRIPTOR_INFO_EXT, nullptr, record->Chain(), layout}; VkResourceDescriptorInfoEXT resource{VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT}; @@ -979,7 +979,7 @@ void BindlessHeap::writeImageSlot(std::uint32_t kind, std::uint32_t slot, VkImag const VkHostAddressRangeEXT range{encodeScratch.data(), stride}; Check(writeResourceDescriptors(context.device, 1, &resource, &range), "vkWriteResourceDescriptorsEXT"); std::memcpy(target, encodeScratch.data(), stride); - KeepEncodedImageView(view, record->generation, key, encodeScratch); + KeepEncodedImageView(context.device, view, record->generation, key, encodeScratch); ++counts.encodes; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp index fd62cf8ec388..cfae058435a1 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -11,16 +12,44 @@ namespace AgcDriver::Graphics { namespace { -std::atomic realCreateImageView{nullptr}; -std::atomic realDestroyImageView{nullptr}; -std::atomic realCreateSampler{nullptr}; -std::atomic realDestroySampler{nullptr}; +enum class Hook : std::size_t { CreateImageView, DestroyImageView, CreateSampler, DestroySampler, Count }; + +using RealFunctions = std::array(Hook::Count)>; std::mutex& recordsMutex() { static auto& mutex = *new std::mutex(); return mutex; } +std::unordered_map& realFunctions() { + static auto& map = *new std::unordered_map(); + return map; +} + +template +TFunction realFunction(VkDevice device, Hook hook) { + std::lock_guard lock(recordsMutex()); + const auto found = realFunctions().find(device); + if (found == realFunctions().end()) return nullptr; + return reinterpret_cast(found->second[static_cast(hook)]); +} + +template +struct DeviceHandle { + VkDevice device; + THandle handle; + bool operator==(const DeviceHandle& other) const { return device == other.device && handle == other.handle; } +}; + +template +struct DeviceHandleHash { + std::size_t operator()(const DeviceHandle& key) const { + const auto device = std::hash{}(key.device); + const auto handle = std::hash{}(key.handle); + return device ^ (handle + 0x9e3779b97f4a7c15ull + (device << 6u) + (device >> 2u)); + } +}; + struct EncodedImageView { std::uint32_t key = 0; std::vector bytes; @@ -31,13 +60,16 @@ struct ViewEntry { std::vector encoded; }; -std::unordered_map& views() { - static auto& map = *new std::unordered_map(); +using ViewKey = DeviceHandle; +using SamplerKey = DeviceHandle; + +std::unordered_map>& views() { + static auto& map = *new std::unordered_map>(); return map; } -std::unordered_map& samplers() { - static auto& map = *new std::unordered_map(); +std::unordered_map>& samplers() { + static auto& map = *new std::unordered_map>(); return map; } @@ -72,13 +104,15 @@ SamplerRecord recordOf(const VkSamplerCreateInfo& info) { VKAPI_ATTR VkResult VKAPI_CALL createImageView(VkDevice device, const VkImageViewCreateInfo* info, const VkAllocationCallbacks* allocator, VkImageView* view) { - const auto result = realCreateImageView.load(std::memory_order_acquire)(device, info, allocator, view); + const auto real = realFunction(device, Hook::CreateImageView); + if (real == nullptr) return VK_ERROR_INITIALIZATION_FAILED; + const auto result = real(device, info, allocator, view); if (result == VK_SUCCESS) { auto record = recordOf(*info); static std::atomic generations{0}; record.generation = generations.fetch_add(1, std::memory_order_relaxed) + 1u; std::lock_guard lock(recordsMutex()); - views()[*view] = ViewEntry{std::move(record), {}}; + views()[{device, *view}] = ViewEntry{std::move(record), {}}; } return result; } @@ -86,18 +120,20 @@ VKAPI_ATTR VkResult VKAPI_CALL createImageView(VkDevice device, const VkImageVie VKAPI_ATTR void VKAPI_CALL destroyImageView(VkDevice device, VkImageView view, const VkAllocationCallbacks* allocator) { { std::lock_guard lock(recordsMutex()); - views().erase(view); + views().erase({device, view}); } - realDestroyImageView.load(std::memory_order_acquire)(device, view, allocator); + if (const auto real = realFunction(device, Hook::DestroyImageView)) real(device, view, allocator); } VKAPI_ATTR VkResult VKAPI_CALL createSampler(VkDevice device, const VkSamplerCreateInfo* info, const VkAllocationCallbacks* allocator, VkSampler* sampler) { - const auto result = realCreateSampler.load(std::memory_order_acquire)(device, info, allocator, sampler); + const auto real = realFunction(device, Hook::CreateSampler); + if (real == nullptr) return VK_ERROR_INITIALIZATION_FAILED; + const auto result = real(device, info, allocator, sampler); if (result == VK_SUCCESS) { auto record = recordOf(*info); std::lock_guard lock(recordsMutex()); - samplers()[*sampler] = std::move(record); + samplers()[{device, *sampler}] = std::move(record); } return result; } @@ -105,35 +141,22 @@ VKAPI_ATTR VkResult VKAPI_CALL createSampler(VkDevice device, const VkSamplerCre VKAPI_ATTR void VKAPI_CALL destroySampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks* allocator) { { std::lock_guard lock(recordsMutex()); - samplers().erase(sampler); + samplers().erase({device, sampler}); } - realDestroySampler.load(std::memory_order_acquire)(device, sampler, allocator); -} - -template -bool resolve(std::atomic& real, VkDevice device, PFN_vkGetDeviceProcAddr deviceProc, const char* name) { - const auto function = reinterpret_cast(deviceProc(device, name)); - if (function == nullptr) return false; - real.store(function, std::memory_order_release); - return true; + if (const auto real = realFunction(device, Hook::DestroySampler)) real(device, sampler, allocator); } struct ObjectHook { const char* name; - bool (*resolveReal)(VkDevice, PFN_vkGetDeviceProcAddr, const char*); + Hook slot; PFN_vkVoidFunction hook; }; -template & Real> -bool resolveRealFunction(VkDevice device, PFN_vkGetDeviceProcAddr deviceProc, const char* name) { - return resolve(Real, device, deviceProc, name); -} - const std::array ObjectHooks{{ - {"vkCreateImageView", &resolveRealFunction, reinterpret_cast(&createImageView)}, - {"vkDestroyImageView", &resolveRealFunction, reinterpret_cast(&destroyImageView)}, - {"vkCreateSampler", &resolveRealFunction, reinterpret_cast(&createSampler)}, - {"vkDestroySampler", &resolveRealFunction, reinterpret_cast(&destroySampler)}, + {"vkCreateImageView", Hook::CreateImageView, reinterpret_cast(&createImageView)}, + {"vkDestroyImageView", Hook::DestroyImageView, reinterpret_cast(&destroyImageView)}, + {"vkCreateSampler", Hook::CreateSampler, reinterpret_cast(&createSampler)}, + {"vkDestroySampler", Hook::DestroySampler, reinterpret_cast(&destroySampler)}, }}; } @@ -164,14 +187,18 @@ PFN_vkVoidFunction DescriptorHeapObjectFunction(VkDevice device, PFN_vkGetDevice if (device == VK_NULL_HANDLE) return nullptr; for (const auto& entry : ObjectHooks) { if (std::strcmp(name, entry.name) != 0) continue; - return entry.resolveReal(device, deviceProc, name) ? entry.hook : nullptr; + const auto function = deviceProc(device, name); + if (function == nullptr) return nullptr; + std::lock_guard lock(recordsMutex()); + realFunctions()[device][static_cast(entry.slot)] = function; + return entry.hook; } return nullptr; } -bool CopyEncodedImageView(VkImageView view, std::uint32_t key, std::span target) { +bool CopyEncodedImageView(VkDevice device, VkImageView view, std::uint32_t key, std::span target) { std::lock_guard lock(recordsMutex()); - const auto found = views().find(view); + const auto found = views().find({device, view}); if (found == views().end()) return false; for (const auto& encoded : found->second.encoded) { if (encoded.key != key || encoded.bytes.size() != target.size()) continue; @@ -181,9 +208,9 @@ bool CopyEncodedImageView(VkImageView view, std::uint32_t key, std::span bytes) { +void KeepEncodedImageView(VkDevice device, VkImageView view, std::uint64_t generation, std::uint32_t key, std::span bytes) { std::lock_guard lock(recordsMutex()); - const auto record = views().find(view); + const auto record = views().find({device, view}); if (record == views().end() || record->second.record.generation != generation) return; auto& entries = record->second.encoded; for (auto& encoded : entries) { @@ -195,16 +222,16 @@ void KeepEncodedImageView(VkImageView view, std::uint64_t generation, std::uint3 entries.push_back({key, std::vector(bytes.begin(), bytes.end())}); } -std::optional FindImageView(VkImageView view) { +std::optional FindImageView(VkDevice device, VkImageView view) { std::lock_guard lock(recordsMutex()); - const auto found = views().find(view); + const auto found = views().find({device, view}); if (found == views().end()) return std::nullopt; return found->second.record; } -std::optional FindSampler(VkSampler sampler) { +std::optional FindSampler(VkDevice device, VkSampler sampler) { std::lock_guard lock(recordsMutex()); - const auto found = samplers().find(sampler); + const auto found = samplers().find({device, sampler}); if (found == samplers().end()) return std::nullopt; return found->second; } diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 7dbcdc391675..4674ba99a0cf 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -124,10 +124,10 @@ void encodedViews(const Context& context) { require(encodes() == 1u && copies() == 0u, "a view's first heap slot encodes its descriptor"); heap.AbsentSlot(Abi::FirstStorageImageBinding + 3u, view); require(encodes() == 1u && copies() == 1u, "another slot for the same view copies the encoded descriptor"); - require(CopyEncodedImageView(view, storageKey, bytes), "a live view keeps its encoded descriptor"); + require(CopyEncodedImageView(context.device, view, storageKey, bytes), "a live view keeps its encoded descriptor"); destroyed = view; } - require(!CopyEncodedImageView(destroyed, storageKey, bytes), "a destroyed view drops its encoded descriptor"); + require(!CopyEncodedImageView(context.device, destroyed, storageKey, bytes), "a destroyed view drops its encoded descriptor"); const PlaceholderImages again(context); heap.AbsentSlot(Abi::FirstStorageImageBinding + 4u, again.View(Abi::FirstStorageImageBinding)); require(encodes() == 2u && copies() == 1u, "a destroyed view's encoded descriptor is not copied to a new view"); diff --git a/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp b/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp new file mode 100644 index 000000000000..fbb2897d8365 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp @@ -0,0 +1,120 @@ +#include "prx/libSceAgcDriver/Graphics/include/DescriptorHeapObjects.hpp" +#include +#include +#include +#include + +namespace { + +using namespace AgcDriver::Graphics; + +void Require(bool value, const char* what) { + if (value) return; + std::fprintf(stderr, "FAIL: %s\n", what); + std::abort(); +} + +struct Fake { + VkDevice device; + int createViews = 0; + int destroyViews = 0; + int createSamplers = 0; + int destroySamplers = 0; + VkDevice lastDevice = VK_NULL_HANDLE; +}; + +Fake first{reinterpret_cast(0x1000)}; +Fake second{reinterpret_cast(0x2000)}; + +Fake& owner(VkDevice device) { + return device == first.device ? first : second; +} + +const std::uint64_t SharedView = 0x77; + +VKAPI_ATTR VkResult VKAPI_CALL fakeCreateView(VkDevice device, const VkImageViewCreateInfo*, const VkAllocationCallbacks*, VkImageView* view) { + auto& fake = owner(device); + ++fake.createViews; + fake.lastDevice = device; + *view = reinterpret_cast(SharedView); + return VK_SUCCESS; +} + +VKAPI_ATTR void VKAPI_CALL fakeDestroyView(VkDevice device, VkImageView, const VkAllocationCallbacks*) { + auto& fake = owner(device); + ++fake.destroyViews; + fake.lastDevice = device; +} + +VKAPI_ATTR VkResult VKAPI_CALL fakeCreateSampler(VkDevice device, const VkSamplerCreateInfo*, const VkAllocationCallbacks*, VkSampler* sampler) { + auto& fake = owner(device); + ++fake.createSamplers; + fake.lastDevice = device; + *sampler = reinterpret_cast(SharedView); + return VK_SUCCESS; +} + +VKAPI_ATTR void VKAPI_CALL fakeDestroySampler(VkDevice device, VkSampler, const VkAllocationCallbacks*) { + auto& fake = owner(device); + ++fake.destroySamplers; + fake.lastDevice = device; +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL fakeProc(VkDevice, const char* name) { + if (std::strcmp(name, "vkCreateImageView") == 0) return reinterpret_cast(&fakeCreateView); + if (std::strcmp(name, "vkDestroyImageView") == 0) return reinterpret_cast(&fakeDestroyView); + if (std::strcmp(name, "vkCreateSampler") == 0) return reinterpret_cast(&fakeCreateSampler); + if (std::strcmp(name, "vkDestroySampler") == 0) return reinterpret_cast(&fakeDestroySampler); + return nullptr; +} + +} + +int main() { + const auto createView = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc, "vkCreateImageView")); + const auto destroyView = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc, "vkDestroyImageView")); + const auto createSampler = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc, "vkCreateSampler")); + const auto destroySampler = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc, "vkDestroySampler")); + Require(createView != nullptr && destroyView != nullptr && createSampler != nullptr && destroySampler != nullptr, "the hooks resolve"); + Require(DescriptorHeapObjectFunction(second.device, fakeProc, "vkCreateImageView") == reinterpret_cast(createView), "the second device resolves the same hook"); + DescriptorHeapObjectFunction(second.device, fakeProc, "vkDestroyImageView"); + DescriptorHeapObjectFunction(second.device, fakeProc, "vkCreateSampler"); + DescriptorHeapObjectFunction(second.device, fakeProc, "vkDestroySampler"); + + VkImageViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + viewInfo.format = VK_FORMAT_R8G8B8A8_UNORM; + VkImageView view = VK_NULL_HANDLE; + Require(createView(first.device, &viewInfo, nullptr, &view) == VK_SUCCESS, "the first device creates a view"); + Require(first.createViews == 1 && second.createViews == 0 && first.lastDevice == first.device, "the first device's view goes through the first device's function"); + viewInfo.format = VK_FORMAT_B8G8R8A8_UNORM; + Require(createView(second.device, &viewInfo, nullptr, &view) == VK_SUCCESS, "the second device creates a view"); + Require(second.createViews == 1 && first.createViews == 1 && second.lastDevice == second.device, "the second device's view goes through the second device's function"); + + const auto recordFirst = FindImageView(first.device, view); + const auto recordSecond = FindImageView(second.device, view); + Require(recordFirst.has_value() && recordSecond.has_value(), "both devices keep a record for the same handle value"); + Require(recordFirst->info.format == VK_FORMAT_R8G8B8A8_UNORM && recordSecond->info.format == VK_FORMAT_B8G8R8A8_UNORM, "the records stay separate per device"); + + const std::byte bytes[4]{}; + KeepEncodedImageView(first.device, view, recordFirst->generation, 1u, bytes); + std::byte copy[4]{}; + Require(CopyEncodedImageView(first.device, view, 1u, copy), "the first device keeps its encoded view"); + Require(!CopyEncodedImageView(second.device, view, 1u, copy), "the second device's record has no encoding of the first's"); + + destroyView(second.device, view, nullptr); + Require(second.destroyViews == 1 && first.destroyViews == 0, "a destroy reaches the owning device's function"); + Require(!FindImageView(second.device, view).has_value(), "the destroyed record is gone"); + Require(FindImageView(first.device, view).has_value(), "destroying on one device keeps the other device's record"); + + VkSamplerCreateInfo samplerInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; + samplerInfo.maxLod = 3.0f; + VkSampler sampler = VK_NULL_HANDLE; + Require(createSampler(first.device, &samplerInfo, nullptr, &sampler) == VK_SUCCESS && first.createSamplers == 1, "the first device creates a sampler"); + samplerInfo.maxLod = 5.0f; + Require(createSampler(second.device, &samplerInfo, nullptr, &sampler) == VK_SUCCESS && second.createSamplers == 1, "the second device creates a sampler"); + Require(FindSampler(first.device, sampler)->info.maxLod == 3.0f && FindSampler(second.device, sampler)->info.maxLod == 5.0f, "sampler records stay separate per device"); + destroySampler(first.device, sampler, nullptr); + Require(first.destroySamplers == 1 && second.destroySamplers == 0, "a sampler destroy reaches the owning device's function"); + Require(!FindSampler(first.device, sampler).has_value() && FindSampler(second.device, sampler).has_value(), "destroying a sampler on one device keeps the other's record"); + std::puts("descriptor heap objects per device: ok"); +} diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_descriptor_heap_object_devices_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_descriptor_heap_object_devices_tests.cmake new file mode 100644 index 000000000000..66368de709bc --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_descriptor_heap_object_devices_tests.cmake @@ -0,0 +1,12 @@ +add_test_executable(agc_descriptor_heap_object_devices_tests EXCLUDE_FROM_ALL tests/DescriptorHeapObjectDevices.cpp) +target_include_directories(agc_descriptor_heap_object_devices_tests PRIVATE + ${LIBS_INCLUDE_DIR} + ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} +) +target_link_libraries(agc_descriptor_heap_object_devices_tests PRIVATE libSceAgcDriver libc) +set_target_properties(agc_descriptor_heap_object_devices_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_descriptor_heap_object_devices_tests) + +if(BUILD_TESTING) + agc_add_default_test(agc_descriptor_heap_object_devices_tests) +endif() From 2ece7ff969943ee364fa4473c3f34125bf3fcf8b Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 23:50:54 +0530 Subject: [PATCH 254/269] fix(agc): validate the heap timeline before submitting and keep the batch if the heap hook throws A10: the missing-timeline check for a heap batch runs before vkQueueSubmit. A failure of the heap submission hook after a successful submit no longer skips the bookkeeping: the batch enters inFlight and the error is rethrown afterwards, so the GPU's resources and completion actions are not lost. noTimelineFails now also expects that nothing was submitted. --- .../prx/libSceAgcDriver/Graphics/src/Recorder.cpp | 12 +++++++++++- .../prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp | 1 + 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 2751e6028bc4..eaa137cb99bb 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -4782,6 +4782,8 @@ void Recorder::Submit() { submission.pSignalSemaphores = &timeline; } if (hold != VK_NULL_HANDLE || timeline != VK_NULL_HANDLE) submission.pNext = &timelineInfo; + auto* const heapAtSubmit = DescriptorHeapEnabled() ? BindlessHeap::Existing(context) : nullptr; + if (heapAtSubmit != nullptr && !HasTimeline()) throw std::runtime_error("AGC bindless heap: a batch using the heap was submitted by a recorder without a timeline semaphore"); DestroyDeferredAtIdle(context); const auto submitStart = std::chrono::steady_clock::now(); batch->submitStarted.store(true, std::memory_order_release); @@ -4794,7 +4796,14 @@ void Recorder::Submit() { if (batch->guestWork) LibcRunReportMilestone_nid_no_patch(2); batch->submitted = true; batch->serial = ++submissions; - if (auto* heap = DescriptorHeapEnabled() ? BindlessHeap::Existing(context) : nullptr; heap != nullptr) heap->Submitted(*this, batch->serial); + std::exception_ptr heapFailure; + if (heapAtSubmit != nullptr) { + try { + heapAtSubmit->Submitted(*this, batch->serial); + } catch (...) { + heapFailure = std::current_exception(); + } + } batch->submittedAt = std::chrono::steady_clock::now(); CaptureTrace::Log("submit-confirmed batch=%llu tokens=%s", static_cast(batch->serial), tokensStr.c_str()); if (DrawProfiled()) { @@ -4819,6 +4828,7 @@ void Recorder::Submit() { inFlight.push_back(std::move(batch)); inFlightKeptBytes += inFlight.back()->keptBytes; if (activeRecorder == this) pendingLabelSince.store(NoPendingLabel, std::memory_order_release); + if (heapFailure != nullptr) std::rethrow_exception(heapFailure); } std::uint64_t Recorder::SubmitAndEpoch() { diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 4674ba99a0cf..1fd80bee8179 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -517,6 +517,7 @@ void noTimelineFails(const Context& context) { } } require(failed, "a heap batch from a recorder without a timeline, which could not wait for its slots, was accepted"); + require(recorder.Submissions() == 0u, "a heap batch from a recorder without a timeline was submitted before the failure"); BindlessHeap::Release(context.device); } From 3c0b9b806f60c2d836af6e5f2fddc629c698271b Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 23:50:54 +0530 Subject: [PATCH 255/269] fix(agc): shader resource build cleanup, array views, and plane tracking footprints A11: a failure after buildComplete, in the heap table layout or refresh, retires the heap tables and releases the descriptor resources before rethrowing, in both build and Complete. A13: MovedDispatchBuffers reads the guest buffer words through DrawGuestWords, which are the per-draw words of a heap stage. A15: heap sampled view selection uses ArrayView() for textures shared as an array partner, after the first-layer choice. A16: the cached shader data comparison builds its iterator only after the sizes matched. A17: the storage texture pending-overlap fast path checks all ranges against one registry snapshot and validates its version after the scan. A18: depth and stencil plane footprints of a multisampled target use the multisample footprint, single-sample targets keep DepthSliceBytes. --- .../Graphics/include/ShaderResources.hpp | 1 + .../Graphics/src/DepthSurface.cpp | 4 +-- .../Graphics/src/ShaderResources.cpp | 35 +++++++++++-------- .../libSceAgcDriver/Graphics/src/Texture.cpp | 13 +++++-- 4 files changed, 34 insertions(+), 19 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index ae63188c6fba..b4909b7212ef 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -666,6 +666,7 @@ class ShaderResources { void applySamplerVariants(); void forgetDeferredInputs(); void release() noexcept; + void completeBuild(std::span shaders); void prepareAddressBindings(std::span shaders, std::span snapshots); VkDescriptorBufferInfo descriptor(Allocation& allocation) { return descriptor(allocation, allocation.adjustment); } VkDescriptorBufferInfo descriptor(const Allocation& allocation, std::uint32_t& adjustment) const; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp index d79d9ddb7c81..77cd37454a20 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp @@ -1926,8 +1926,8 @@ class DepthSurface { const Context context; const DepthTarget target; const VkFormat hostFormat; - const std::uint64_t depthPlaneBytes = DepthSliceBytes(target.extent, target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT ? 2u : 4u); - const std::uint64_t stencilPlaneBytes = DepthSliceBytes(target.extent, 1u); + const std::uint64_t depthPlaneBytes = target.samples == 1u ? DepthSliceBytes(target.extent, target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT ? 2u : 4u) : MultisampledDepthBytes_nid_no_patch(target.extent, target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT ? 2u : 4u, target.samples); + const std::uint64_t stencilPlaneBytes = target.samples == 1u ? DepthSliceBytes(target.extent, 1u) : MultisampledDepthBytes_nid_no_patch(target.extent, 1u, target.samples); VkImage image = VK_NULL_HANDLE; VkImageView view = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index db97c08f4086..8aac5f80b8d3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -2067,14 +2067,24 @@ void ShaderResources::Complete() { prepareAddressBindings(shaders, deferredSnapshots); buildPrepare(shaders, nullptr, 0, 0, 0); } - buildComplete(); - if (heapStage) { - layOutHeapStages(shaders); - RefreshHeapStage(shaders); - } + completeBuild(shaders); forgetDeferredInputs(); } +void ShaderResources::completeBuild(std::span shaders) { + try { + buildComplete(); + if (heapStage) { + layOutHeapStages(shaders); + RefreshHeapStage(shaders); + } + } catch (...) { + retireHeapTables(); + release(); + throw; + } +} + void ShaderResources::forgetDeferredInputs() { // The compiled shader and the captured regions belong to the dispatch, which returns while this // object lives on in the resource cache and the recorder: nothing may reach for them after the @@ -2085,11 +2095,7 @@ void ShaderResources::forgetDeferredInputs() { void ShaderResources::build(std::span shaders, const ColorTarget* target, std::uint32_t colorAttachments, std::uint64_t indexAddress, std::size_t indexBytes) { buildPrepare(shaders, target, colorAttachments, indexAddress, indexBytes); - buildComplete(); - if (heapStage) { - layOutHeapStages(shaders); - RefreshHeapStage(shaders); - } + completeBuild(shaders); if (!GuestMemory::WriteIndexEnabled()) return; countIndex(IndexBuilds); subscribeBuilt(shaders); @@ -7405,9 +7411,10 @@ std::optional> ShaderResources::MovedD for (const auto& binding : shader.program->bindings) { if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue; const auto kept = std::find_if(bindings.begin(), bindings.end(), [&](const Binding& item) { return item.layout.binding == binding.binding; }); - if (kept == bindings.end() || kept->allocations.size() != binding.count || binding.guestDescriptor.size() != static_cast(binding.count) * 4u) return refuse(MoveRefusal::Shape); + const auto& guestWords = DrawGuestWords(shader, binding); + if (kept == bindings.end() || kept->allocations.size() != binding.count || guestWords.size() != static_cast(binding.count) * 4u) return refuse(MoveRefusal::Shape); for (std::uint32_t element = 0; element < binding.count; ++element) { - const auto* words = binding.guestDescriptor.data() + static_cast(element) * 4u; + const auto* words = guestWords.data() + static_cast(element) * 4u; const ShaderRecompiler::ShaderBufferResource descriptor{{words[0], words[1], words[2], words[3]}}; const auto address = descriptor.Base48(); const auto size = guestBufferBytes(std::span(words, 4)); @@ -8259,6 +8266,7 @@ VkImageView ShaderResources::heapSampledView(std::size_t index) const { if (textureSrgb[index]) return texture->SrgbView(textureFirstLayer[index], textureBaseLevel[index]); if (textureBaseLevel[index]) return texture->BaseLevelView(); if (textureFirstLayer[index]) return texture->FirstLayerView(); + if (arrayViewTextures.contains(index)) return texture->ArrayView(); return texture->View(); } @@ -8700,8 +8708,7 @@ void ShaderResources::writeHeapDataBinding(const BindlessHeap::SpanScope& spans, const bool sameWords = sameShape && (sameOrigin || std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)); if (verifySlots && sameOrigin && !std::equal(words.begin() + userFront, words.end(), stageState.dataInput.begin() + userFront)) throw std::runtime_error("AGC graphics: a GPU-mode stage's shader data differs from the data of the same origin"); - const auto userInput = stageState.dataInput.begin() + static_cast(words.size()); - const bool sameInput = sameWords && std::equal(userData.begin(), userData.end(), userInput); + const bool sameInput = sameWords && std::equal(userData.begin(), userData.end(), stageState.dataInput.begin() + static_cast(words.size())); if (shaderData && stageState.splitUser) { const auto [dataAddress, userAddress] = writeSplitHeapStage(spans, heap, shader, stageState, words, userData, sameWords, current); heapOffsets[dataIndex] = dataAddress; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index be9e95807fe7..de9114fd3a17 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -1920,6 +1920,15 @@ class PendingList { return current != nullptr && current->version == changes.load(std::memory_order_acquire) && !Overlaps(current->ranges, address, bytes); } + bool SurelyClearAll(std::span> wanted) const { + const auto current = published.load(std::memory_order_acquire); + if (current == nullptr) return false; + for (const auto& [begin, end] : wanted) { + if (end > begin && Overlaps(current->ranges, begin, static_cast(end - begin))) return false; + } + return current->version == changes.load(std::memory_order_acquire); + } + private: struct Snapshot { std::uint64_t version = 0; @@ -5975,9 +5984,7 @@ bool StorageTexture::AnyPendingOverlaps(std::span begin && !pending.textures.SurelyClear(begin, static_cast(end - begin))) return false; - } + if (!pending.textures.SurelyClearAll(ranges)) return false; return pending.flushingCount.load(std::memory_order_acquire) == 0; }; if (surelyClear()) return false; From a97ba5dfda5631c5adb6d40e0987925e7ebb2ac7 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 23:43:23 +0530 Subject: [PATCH 256/269] fix(shader): heap slot words, plan reads, optional user data and template budget B1: PipelineSpecialization::PlacePushData no longer rejects a placement that leaves the optional UserData root item without a push position; every other root item still needs one. B2: PreparedShaderInvocation::Plan returns a shared pointer copied under the source mutex instead of a reference to the member the writers reset, and MaterializeHeap compares the capture's plan through it. No caller holds the source mutex. B3: a registration-mode dynamic-mip storage image write read the first element's slot for every mip. Registration layouts now carry slot words for the storage image kinds (IrBindingLayout::HeapSlotWordKind), the binding builder fills them per element, and the emitter loads the word of each mip beyond the first. B4: OwnedBytes counts DescriptorBinding::samplerEmbedded and samplerEmbeddedWords and RecompileResult::pushedData. Tests: PushDataPlacements (B1), ShaderDiskCache (B2), ShaderMemory (B3) and HeapTemplateBudgetTests (B4) fail without the fix. --- .../include/PipelineSpecialization.hpp | 5 +- .../tests/PushDataPlacements.cpp | 40 ++++-- .../libSceAgcDriver/tests/ShaderDiskCache.cpp | 5 + .../libSceAgcDriver/tests/ShaderMemory.cpp | 117 ++++++++++++++++++ core/shader/recompiler/HeapTemplateBudget.hpp | 4 +- .../IrMetadata/DescriptorBinding.hpp | 3 + .../include/Optimization/ResourceProgram.hpp | 2 +- .../Optimization/src/BindingAllocator.cpp | 4 +- .../src/DescriptorBindingBuilder.cpp | 2 +- core/shader/recompiler/Recompiler.cpp | 13 +- .../src/SpirvMemory/SpirvDescriptors.cpp | 4 +- .../tests/HeapTemplateBudgetTests.cpp | 9 ++ 12 files changed, 184 insertions(+), 24 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp index b6cdb622bd40..aa3f3f70881b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp @@ -93,8 +93,9 @@ class PipelineSpecialization { if (constant.id >= Ids::BufferRootPosition && constant.id < Ids::BufferRootPosition + Ids::BufferRootCount) constant.value = placement.bufferRoots[constant.id - Ids::BufferRootPosition]; if (constant.id == Ids::BufferOverflowPosition) constant.value = placement.bufferOverflow; if (constant.id >= Ids::RootItemPositionBase && constant.id < Ids::RootItemPositionBase + ShaderRecompiler::RuntimeAbi::RootItemCount) { - constant.value = placement.items[constant.id - Ids::RootItemPositionBase]; - Require(constant.value != ShaderRecompiler::RuntimeAbi::NoPushPosition, "a stage reads a root item its pipeline's push layout does not hold"); + const auto item = constant.id - Ids::RootItemPositionBase; + constant.value = placement.items[item]; + Require(item == static_cast(ShaderRecompiler::RuntimeAbi::RootItem::UserData) || constant.value != ShaderRecompiler::RuntimeAbi::NoPushPosition, "a stage reads a root item its pipeline's push layout does not hold"); } } } diff --git a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp index 521ccef0ed7f..87b23f1f5fb2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PushDataPlacements.cpp @@ -1,4 +1,5 @@ #include +#include "prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp" #include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp" #include "PushDataLayout.hpp" #include "RuntimeAbi.hpp" @@ -55,16 +56,18 @@ std::vector place(const std::vector& stages) { void disjoint(const std::vector& stages, const std::vector& placements, std::uint64_t occupied, const char* what) { std::uint64_t used = occupied; - std::uint64_t globals = 0; + constexpr std::uint32_t NotGlobal = ~0u; + std::array globalOwner; + globalOwner.fill(NotGlobal); for (std::size_t index = 0; index < placements.size(); ++index) { - const auto claim = [&](std::uint32_t first, std::uint32_t width, bool shared) { + const auto claim = [&](std::uint32_t first, std::uint32_t width, std::uint32_t global) { for (auto dword = first; dword < first + width; ++dword) { require(dword < Abi::PushDataDwords, std::string("a push entry leaves the push data: ") + what); const auto bit = 1ull << dword; - if (shared && (globals & bit) != 0u) continue; + if (global != NotGlobal && globalOwner[dword] == global) continue; require((used & bit) == 0u, std::string("two push entries share a dword: ") + what); used |= bit; - if (shared) globals |= bit; + if (global != NotGlobal) globalOwner[dword] = global; } }; for (std::uint32_t item = 0; item < Abi::RootItemCount; ++item) { @@ -75,7 +78,7 @@ void disjoint(const std::vector& stages, const std::vector(item); if (Abi::RootAddressItem(kind)) require(position % 2u == 0u, std::string("a root address is not 8-byte aligned: ") + what); - claim(position, Abi::RootAddressItem(kind) ? 2u : 1u, static_cast(kind) < static_cast(Abi::RootItem::ShaderData)); + claim(position, Abi::RootAddressItem(kind) ? 2u : 1u, static_cast(kind) < static_cast(Abi::RootItem::ShaderData) ? item : NotGlobal); } const auto& placement = placements[index]; require(placement.pushedBuffers == stages[index].buffers, std::string("a stage's placement does not count its buffers: ") + what); @@ -86,14 +89,14 @@ void disjoint(const std::vector& stages, const std::vector(item); }; + module.specialization = {{rootItem(Item::UserData), Abi::NoPushPosition}, {rootItem(Item::ShaderData), 0u}}; + StagePushPlacement placement; + placement.items.fill(Abi::NoPushPosition); + placement.items[static_cast(Item::ShaderData)] = 4u; + AgcDriver::Graphics::PipelineSpecialization optionalUser(module); + optionalUser.PlacePushData(placement); + placement.items[static_cast(Item::ShaderData)] = Abi::NoPushPosition; + bool refused = false; + try { + AgcDriver::Graphics::PipelineSpecialization required(module); + required.PlacePushData(placement); + } catch (const std::runtime_error&) { + refused = true; + } + require(refused, "a stage reading a root item its pipeline's push layout does not hold was accepted"); + } std::puts("push data placements passed"); return 0; } catch (const std::exception& error) { diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp index ae084318af07..98abbdc3bf24 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp @@ -2512,7 +2512,12 @@ void verifyPlanRoundTrip() { const auto registeredHandle = PrepareShader(registeredRequest); const auto registeredPlan = GetResourcePlan(registeredRequest); ShaderDiskCache::Flush(); + const auto registeredInvocation = PreparedShaderInvocation::TryCreate(registeredRequest, registeredHandle); + require(registeredInvocation.has_value(), "the registered shader has no prepared invocation"); + const auto& heldPlan = registeredInvocation->Plan(); + require(heldPlan != nullptr, "a registered shader with a held plan returned none"); ReleaseUndrawnResourcePlan(*registeredHandle); + require(heldPlan != nullptr, "a plan returned by an invocation was cleared when its source released the plan"); const auto beforeReload = ShaderDiskCache::Totals(); const auto reloadedPlan = GetResourcePlan(registeredRequest); require(ShaderDiskCache::Totals().planHits == beforeReload.planHits + 1u, "a released registration plan was not reloaded from the disk cache"); diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 09ae3671ecbc..e9fbbbf516d1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -12908,6 +12908,122 @@ void verifyRuntimeImageSwitchDeduplication() { require(mipTargets.at(0u) != mipTargets.at(1u), "runtime image switch deduplication: storage image modes with different mip modes shared an OpSwitch target"); } +void verifyRegistrationStorageMipSlots() { + using namespace ShaderRecompiler; + constexpr std::uint32_t MetadataDword = 200u; + IrProgram program; + program.SetWaveSize(32u); + program.Resources().stage = IrShaderStage::Compute; + program.Resources().srtPlanComplete = true; + program.Resources().resourceTrackingComplete = true; + program.Metadata().shaderInfoComplete = true; + program.Metadata().bindingLayoutComplete = true; + auto& block = program.CreateBlock(); + program.SetEntryBlock(block); + program.BlockOrder().push_back(&block); + program.Metadata().blockInfo.emplace_back(); + auto& zero = program.CreateValue(IrOpcode::Void, IrType::U32); + zero.SetImmediateU32(0u); + auto& enabled = program.CreateValue(IrOpcode::Void, IrType::Bool); + enabled.SetImmediateBool(true); + auto& handle = program.CreateValue(IrOpcode::GetImageResource, IrType::ImageResource, 0u); + for (std::uint32_t i = 0u; i < 8u; ++i) handle.AddArgument(&zero); + block.AppendInstruction(&handle); + auto& address = program.CreateValue(IrOpcode::MakeImageAddress, IrType::ImageAddress); + for (std::uint32_t i = 0u; i < 13u; ++i) address.AddArgument(&zero); + block.AppendInstruction(&address); + MemoryInfo memory{}; + memory.kind = ResourceKind::Image; + memory.resource = 0u; + memory.imageDimension = RdnaImageDimension::Dim2D; + memory.imageAddressComponents = 2u; + memory.dmask = 0xfu; + memory.dataBits = 32u; + memory.dataDwords = 4u; + memory.componentCount = 4u; + program.Resources().memoryInfo.push_back(memory); + ImageResource image{}; + image.resourceClass = ImageResourceClass::Storage; + image.numericClass = IrTextureNumericClass::Float; + image.dimension = RdnaImageDimension::Dim2D; + image.mipMode = ImageMipMode::DynamicStorage; + image.mipCount = 3u; + image.written = true; + image.fmaskCompatible = false; + const auto modes = ResourceMaterializer::RuntimeImageModes(image); + const auto Mips = std::ranges::max(modes, {}, &ImageResource::mipCount).mipCount; + require(Mips > 1u, "registration slot words: a dynamic-mip storage image has no mip chain"); + program.Info().images.push_back(image); + program.Info().runtimeImageModes.push_back(modes); + auto& layout = program.Metadata().bindings; + layout.gpuResolvedImages = true; + layout.heapStorageImages = true; + layout.dataAddress = true; + layout.runtimeImageCount = 1u; + layout.memoryOffsetDword = MetadataDword; + for (const auto& mode : modes) { + const auto kind = DescriptorBindingForImage(mode); + if (std::ranges::none_of(layout.descriptors, [&](const IrDescriptorBinding& entry) { return entry.kind == kind; })) layout.descriptors.push_back({kind, std::vector(Mips, 0u)}); + } + for (const auto& descriptor : layout.descriptors) { + require(layout.HeapSlotWordKind(descriptor.kind), "registration slot words: a storage image kind has no slot words in a registration layout"); + layout.imageSlotDwords += static_cast(descriptor.resources.size()); + } + require(!layout.HeapSlotWordKind(static_cast(RuntimeAbi::FirstImageBinding)), "registration slot words: a sampled image kind has slot words in a registration layout"); + auto plain = layout; + plain.runtimeImageCount = 0u; + require(plain.HeapSlotWordKind(static_cast(RuntimeAbi::FirstImageBinding)), "registration slot words: a sampled image kind has no slot words outside a registration layout"); + ShaderComputeInputInfo compute{}; + compute.threadsNum[0] = 32u; + compute.threadsNum[1] = 1u; + compute.threadsNum[2] = 1u; + compute.hostSubgroupSize = 32u; + compute.waveSize = 32u; + ShaderStageInputInfo inputs{}; + inputs.compute = &compute; + auto& texel = program.CreateValue(IrOpcode::CompositeConstructU32x4, IrType::U32x4); + for (std::uint32_t i = 0u; i < 4u; ++i) texel.AddArgument(&zero); + block.AppendInstruction(&texel); + auto& store = program.CreateValue(IrOpcode::ImageWrite, IrType::Void); + store.AddArgument(&handle); + store.AddArgument(&address); + store.AddArgument(&texel); + store.AddArgument(&enabled); + block.AppendInstruction(&store); + CompiledBindingLayout bindings{}; + bindings.layout = layout; + SpirvTargetOptions target{}; + target.vulkanVersion = 0x00401000u; + target.spirvVersion = 0x00010300u; + target.subgroupSize = 32u; + target.registrationModules = true; + target.gpuResolvedImages = true; + const std::array capabilities{spv::CapabilityStorageImageArrayDynamicIndexing, spv::CapabilitySampledImageArrayDynamicIndexing, spv::CapabilityStorageImageWriteWithoutFormat}; + target.supportedCapabilities = capabilities; + const auto words = SpirvEmitter().Emit(program, inputs, bindings, target); + std::map definitions; + std::vector writes; + for (std::size_t cursor = 5u; cursor < words.size(); cursor += words[cursor] >> 16u) { + const auto count = words[cursor] >> 16u; + require(count != 0u && count <= words.size() - cursor, "registration slot words: truncated SPIR-V instruction"); + const auto opcode = words[cursor] & 0xffffu; + if (opcode == spv::OpImageWrite) writes.push_back(cursor); + if ((opcode == spv::OpLoad || opcode == spv::OpAccessChain) && count >= 4u) definitions[words[cursor + 2u]] = cursor; + } + const auto operandOf = [&](std::uint32_t id, std::uint32_t opcode, std::size_t operand) { + const auto found = definitions.find(id); + require(found != definitions.end() && (words[found->second] & 0xffffu) == opcode, "registration slot words: a storage image write does not take its descriptor through the image array"); + return words[found->second + operand]; + }; + std::set slotVariables; + for (const auto write : writes) { + const auto pointer = operandOf(words[write + 1u], spv::OpLoad, 3u); + const auto index = operandOf(pointer, spv::OpAccessChain, 4u); + slotVariables.insert(operandOf(index, spv::OpLoad, 3u)); + } + require(writes.size() >= Mips && slotVariables.size() >= Mips, "registration slot words: the storage image writes of a dynamic mip chain do not each read their own heap slot word"); +} + int main(int argc, char** argv) { try { #ifdef _WIN32 @@ -13185,6 +13301,7 @@ int main(int argc, char** argv) { verifyGcnDimensionQueries(); verifySrgbDepthCompareModes(); verifyRuntimeImageSwitchDeduplication(); + verifyRegistrationStorageMipSlots(); verifyQuadMaskNeighbourReads(); verifyPixelQuadPermReads(); verifyCoherentGds(); diff --git a/core/shader/recompiler/HeapTemplateBudget.hpp b/core/shader/recompiler/HeapTemplateBudget.hpp index 4aaadc627b3f..658ac5fa30f3 100644 --- a/core/shader/recompiler/HeapTemplateBudget.hpp +++ b/core/shader/recompiler/HeapTemplateBudget.hpp @@ -28,14 +28,14 @@ template return OwnedBytes(binding.guestDescriptor) + OwnedBytes(binding.samplerDepthCompare) + OwnedBytes(binding.imageWritten) + OwnedBytes(binding.imageDepthCompare) + OwnedBytes(binding.imageAtomic) + OwnedBytes(binding.imageAtomic64) + OwnedBytes(binding.imageShapes) + OwnedBytes(binding.bufferAtomic) + OwnedBytes(binding.bufferWritten) + OwnedBytes(binding.samplerUnnormalized) + OwnedBytes(binding.samplerIntegerBorder) + OwnedBytes(binding.samplerCoordinatesIgnored) + OwnedBytes(binding.imageUnnormalized) + OwnedBytes(binding.imageUnnormalizedBaseLevel) + OwnedBytes(binding.imageSamplers) + OwnedBytes(binding.bufferRead) + - OwnedBytes(binding.bufferExtent); + OwnedBytes(binding.bufferExtent) + OwnedBytes(binding.samplerEmbedded) + OwnedBytes(binding.samplerEmbeddedWords); } [[nodiscard]] inline std::uint64_t OwnedBytes(const RecompileResult& result) { std::uint64_t bytes = sizeof(RecompileResult) + OwnedBytes(result.vertexInputPatches) + OwnedBytes(result.runtimeImageResources) + OwnedBytes(result.vertexInputs) + OwnedBytes(result.parameterExports) + OwnedBytes(result.fragmentParameters) + OwnedBytes(result.stencilReferences) + OwnedBytes(result.specialization) + OwnedBytes(result.heapSlotWords) + OwnedBytes(result.bindings) + OwnedBytes(result.pushConstants) + OwnedBytes(result.vertexAttributes) + OwnedBytes(result.imageTablePoison) + OwnedBytes(result.imageTableRanges) + OwnedBytes(result.imageTableReadRanges) + - OwnedBytes(result.heapUserWords) + OwnedBytes(result.shaderDataUserWords); + OwnedBytes(result.heapUserWords) + OwnedBytes(result.shaderDataUserWords) + OwnedBytes(result.pushedData); if (result.meshBarycentrics.has_value()) bytes += OwnedBytes(result.meshBarycentrics->parameters); for (const auto& binding : result.bindings) bytes += OwnedBytes(binding); for (const auto& ranges : result.imageTableReadRanges) bytes += OwnedBytes(ranges); diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp index 40215a9ce071..abfc6051b710 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/DescriptorBinding.hpp @@ -79,6 +79,9 @@ struct IrBindingLayout { [[nodiscard]] std::uint32_t ShaderDataDwords() const { return BufferAddressDword() + bufferAddressDwords; } + [[nodiscard]] bool HeapSlotWordKind(DescriptorBindingKind kind) const { + return HeapImageKind(kind) && (runtimeImageCount == 0u || RuntimeAbi::GpuHeapStorageKind(static_cast(kind))); + } [[nodiscard]] bool HeapImageKind(DescriptorBindingKind kind) const { const auto value = static_cast(kind); return (value >= RuntimeAbi::FirstImageBinding && value < RuntimeAbi::FirstStorageImageBinding) || (heapStorageImages && RuntimeAbi::GpuHeapStorageKind(value)); diff --git a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp index 84f7963ad872..b1e8ff15b016 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/ResourceProgram.hpp @@ -75,7 +75,7 @@ class PreparedShaderInvocation { std::shared_ptr Capture(const SrtRuntime& runtime) const; std::shared_ptr Materialize(const ResourceCapture& capture) const; std::shared_ptr MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words, HeapTemplateMiss* miss = nullptr) const; - const std::shared_ptr& Plan() const; + std::shared_ptr Plan() const; std::shared_ptr LoadPlan() const; std::shared_ptr PlanOrLoad() const; std::uint64_t VariantId() const; diff --git a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp index 1dff5fd4a834..de5e63860fb0 100644 --- a/core/shader/recompiler/Optimization/src/BindingAllocator.cpp +++ b/core/shader/recompiler/Optimization/src/BindingAllocator.cpp @@ -173,9 +173,9 @@ BindingAllocationResult BindingAllocator::Allocate(IrProgram& program, const Bin } next.heapStorageImages = gpuResolvedImages && descriptorMemory; - if (gpuResolvedImages && !registrationModules) { + if (gpuResolvedImages) { for (const auto& descriptor : next.descriptors) { - if (next.HeapImageKind(descriptor.kind)) next.imageSlotDwords += static_cast(descriptor.resources.size()); + if (next.HeapSlotWordKind(descriptor.kind)) next.imageSlotDwords += static_cast(descriptor.resources.size()); } } if (descriptorMemory && gpuResolvedImages) next.bufferAddressDwords = static_cast(info.buffers.size()) * RuntimeAbi::BufferAddressWords; diff --git a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp index 2c7adbfc4aaa..b792c7eff08e 100644 --- a/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp +++ b/core/shader/recompiler/Optimization/src/DescriptorBindingBuilder.cpp @@ -566,7 +566,7 @@ DescriptorBindingPlan DescriptorBindingBuilder::Prepare(const IrBindingLayout& l for (const auto& logical : layout.descriptors) { const bool imageHeap = ImageBindingResourceClass(logical.kind) != ImageResourceClass::None; const bool samplerHeap = logical.kind == DescriptorBindingKind::Samplers; - const bool sampledSlots = slotWords && layout.HeapImageKind(logical.kind); + const bool sampledSlots = layout.gpuResolvedImages && layout.HeapSlotWordKind(logical.kind); IrDescriptorBinding compact{logical.kind, {}}; std::vector originals; std::vector inactive; diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index f7b281cc0c0f..42ce9136d319 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -2759,7 +2759,7 @@ void HeapBindingWords(const RecompileRequest& request, const CompiledVariant& va } std::shared_ptr PreparedShaderInvocation::MaterializeHeap(const ResourceCapture& capture, HeapStageWords& words, HeapTemplateMiss* miss) const { - if (capture.source != handle->source || capture.plan != handle->source->plan) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); + if (capture.source != handle->source || capture.plan != Plan()) throw std::runtime_error("ShaderRecompiler: resource capture belongs to another prepared shader"); const auto& variant = handle->artifact; if (!variant->artifact.gpuResolvedImages || !variant->artifact.registrationModule || variant->bindings.layout.UsesPushData()) return nullptr; const auto& snapshot = capture.snapshot; @@ -2850,9 +2850,10 @@ std::shared_ptr PreparedShaderInvocation::Materialize(con return Sealed(std::move(result)); } -const std::shared_ptr& PreparedShaderInvocation::Plan() const { - static const std::shared_ptr none; - return handle != nullptr && handle->source != nullptr ? handle->source->plan : none; +std::shared_ptr PreparedShaderInvocation::Plan() const { + if (handle == nullptr || handle->source == nullptr) return nullptr; + std::lock_guard lock(handle->source->mutex); + return handle->source->plan; } std::shared_ptr PreparedShaderInvocation::LoadPlan() const { @@ -2861,8 +2862,8 @@ std::shared_ptr PreparedShaderInvocation::LoadPlan() const } std::shared_ptr PreparedShaderInvocation::PlanOrLoad() const { - const auto& plan = Plan(); - return plan != nullptr ? plan : LoadPlan(); + auto plan = Plan(); + return plan != nullptr ? std::move(plan) : LoadPlan(); } std::uint64_t PreparedShaderInvocation::VariantId() const { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp index 1a70c04465ba..4c3d4eaa94cd 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp @@ -201,7 +201,7 @@ std::uint32_t HeapImageSlotWord(SpirvEmitterState& state, DescriptorBindingKind auto dword = layout.ImageSlotDword(); for (const auto& descriptor : layout.descriptors) { if (descriptor.kind == kind) break; - if (state.program.Metadata().bindings.HeapImageKind(descriptor.kind)) dword += static_cast(descriptor.resources.size()); + if (state.program.Metadata().bindings.HeapSlotWordKind(descriptor.kind)) dword += static_cast(descriptor.resources.size()); } dword += arrayIndex; if (dword >= layout.ShaderDataDwords()) ExitDescriptorBindingFailure(state, kind, resource, "image heap slot word lies outside the shader data"); @@ -213,7 +213,7 @@ std::uint32_t StorageElementPointer(SpirvEmitterState& state, std::uint32_t poin if (variable == 0) ExitDescriptorBindingFailure(state, kind, resource, "storage image heap array was not emitted"); RequireDynamicIndexing(state, spv::CapabilityStorageImageArrayDynamicIndexing, kind, resource, "the storage image heap needs storage image array dynamic indexing, which the device lacks"); const auto pointer = state.module.AllocateId(); - state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, variable, state.registrationModules ? HeapImageSlot(state, kind, resource) : HeapImageSlotWord(state, kind, resource, arrayIndex)); + state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, variable, state.registrationModules && arrayIndex == ResourceForDescriptor(state, kind, resource) ? HeapImageSlot(state, kind, resource) : HeapImageSlotWord(state, kind, resource, arrayIndex)); return pointer; } diff --git a/core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp b/core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp index 93b380a42883..55116ded878e 100644 --- a/core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp +++ b/core/shader/recompiler/tests/HeapTemplateBudgetTests.cpp @@ -59,6 +59,15 @@ void ChargesOwnedArrays() { result.bindings.resize(8); for (auto& binding : result.bindings) binding.guestDescriptor.resize(4096); Require(ShaderRecompiler::OwnedBytes(result) >= withRanges + arrays + 8u * 4096u * sizeof(std::uint32_t), "the guest descriptor words of a template's bindings were not charged"); + const auto bound = ShaderRecompiler::OwnedBytes(result); + for (auto& binding : result.bindings) { + binding.samplerEmbedded.resize(2048); + binding.samplerEmbeddedWords.resize(8192); + } + Require(ShaderRecompiler::OwnedBytes(result) >= bound + 8u * (2048u + 8192u) * sizeof(std::uint32_t), "the embedded sampler vectors of a template's bindings were not charged"); + const auto embedded = ShaderRecompiler::OwnedBytes(result); + result.pushedData.resize(4096); + Require(ShaderRecompiler::OwnedBytes(result) >= embedded + 4096u * sizeof(std::uint32_t), "a template's pushed data was not charged"); } } From cf8a7b0c66f1cd92689ae2ee06b83927eca64ad7 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 23:43:29 +0530 Subject: [PATCH 257/269] test(agc): fix review findings on heap, recorder and finisher tests B5: samplersEvicted submits once before the pressure check. B6: BindlessHeapSlots uses constructed Texture objects over real images, not byte storage. B7: Recorder compares the refreshed keys with DccKeys::Clear0000. B10, B19: tests that build their own recorder pass VulkanDevice::TimelineSemaphores() instead of true (ColorWriteMaskDynamic, CopyInputLifetime, DepthFastClearSubmit, MultisampledPassOrder, PassBreakReasons). B12: DrawPipelineStop waits for DrawPipeline::FullWaiters() instead of sleeping. B13: PushDataPlacements lets a position be shared only by the same root item. B14: DrawWriteRanges covers storage images whose words come from a heap stage. B15: FinisherHitLookup requires the draw cache hits to increase across the measured submission. B16: FinisherDispatchOrder samples the draws' color target, changing its color between passes. B17: HeapDrawBench drops the declarations it never uses. B18: HeapWalkThreads waits for a peer stage and releases both workers on failure. B20: PreparedGraphics picks the regular stage by role and checks the unchanged request first. B21: ImageTableCacheBounds StoreTable checks heap support before setup and dispatch. B8, B9 and B11 are not defects: heapViewTests returns the skip code 77 with a message, both --atomic-table and --store-table are implemented, and the fragment ShaderData binding is 1 * 66 + 62 = 128. --- .../include/Driver/Draw/DrawPipeline.hpp | 1 + .../Execution/include/VulkanDevice.hpp | 1 + .../src/Driver/Draw/DrawPipeline.cpp | 5 + .../Execution/src/VulkanDevice.cpp | 4 + .../tests/BindlessHeapSlots.cpp | 46 ++++++-- .../tests/DrawPipelineStop.cpp | 5 +- .../prx/libSceAgcDriver/tests/Recorder.cpp | 2 +- .../tests/execution/ColorWriteMaskDynamic.cpp | 2 +- .../tests/execution/CopyInputLifetime.cpp | 8 +- .../tests/execution/DepthFastClearSubmit.cpp | 14 +-- .../tests/execution/DrawWriteRanges.cpp | 26 +++++ .../tests/execution/FinisherDispatchOrder.cpp | 19 +++- .../tests/execution/FinisherHitLookup.cpp | 3 + .../tests/execution/HeapDrawBench.cpp | 104 ------------------ .../tests/execution/HeapWalkThreads.cpp | 24 +++- .../tests/execution/ImageTableCacheBounds.cpp | 8 +- .../tests/execution/MultisampledPassOrder.cpp | 2 +- .../tests/execution/PassBreakReasons.cpp | 2 +- .../tests/execution/PreparedGraphics.cpp | 6 +- 19 files changed, 135 insertions(+), 147 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp index 07ae0d1a3340..215296aef225 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp @@ -51,6 +51,7 @@ class DrawPipeline { static std::uint64_t DrainRequestsByOpcode(std::uint32_t opcode); static std::uint64_t DrainRequestsByReason(DrainReason reason); bool Busy() const; + std::uint32_t FullWaiters(); std::size_t Outstanding() const { return outstanding.load(std::memory_order_acquire); } bool Overlaps(std::uint64_t address, std::size_t bytes); bool OverlapsAny(std::span> ranges); diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp index bd753eecab0d..c24892fae8ab 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp @@ -394,6 +394,7 @@ class VulkanDevice { // The device's Graphics::Context: a copy of the one built at setup (its instance functions // resolved then, its function table filled then), or with APS5_NO_CONTEXT_CACHE=1 built anew. Graphics::Context graphicsContext() const; + bool TimelineSemaphores() const; VkPipelineCreateFlags computePipelineFlags() const; std::uint32_t computeSubgroupSize(const ShaderRecompiler::RecompileResult& shader) const; VkPipelineShaderStageCreateFlags computeStageFlags(const ShaderRecompiler::RecompileResult& shader) const; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp index 5eb4742a4359..2149866214e9 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp @@ -318,6 +318,11 @@ void DrawPipeline::rethrowFailure() { std::rethrow_exception(error); } +std::uint32_t DrawPipeline::FullWaiters() { + std::lock_guard lock(mutex); + return fullWaiters; +} + void DrawPipeline::Enqueue(Commit commit, std::vector writes, std::uint64_t labelAddress, std::vector labelBytes, std::vector reads, bool draw) { enqueue({std::move(commit), std::move(writes), labelAddress, std::move(labelBytes), std::move(reads), draw}); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 0f5f7d87564c..680e3b2e83b5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -4935,6 +4935,10 @@ const Graphics::Context& VulkanDevice::contextRef(std::optionaltimelineSemaphores; +} + Graphics::Context VulkanDevice::graphicsContext() const { std::optional scratch; return contextRef(scratch); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 1fd80bee8179..0d2b39136b73 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -33,23 +33,44 @@ struct FakeOwner : HeapSlotOwner { FakeOwner() = default; }; -alignas(Texture) std::array, 12> fakeTextures{}; - -std::shared_ptr fakeTexture(std::size_t index) { - return std::shared_ptr(reinterpret_cast(fakeTextures[index].data()), [](Texture*) {}); +std::shared_ptr fakeTexture(const Context& context, std::size_t) { + VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + info.imageType = VK_IMAGE_TYPE_2D; + info.format = VK_FORMAT_R8G8B8A8_UNORM; + info.extent = {1u, 1u, 1u}; + info.mipLevels = 1u; + info.arrayLayers = 1u; + info.samples = VK_SAMPLE_COUNT_1_BIT; + info.tiling = VK_IMAGE_TILING_OPTIMAL; + info.usage = VK_IMAGE_USAGE_SAMPLED_BIT; + info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + VkImage image = VK_NULL_HANDLE; + require(context.Function("vkCreateImage")(context.device, &info, nullptr, &image) == VK_SUCCESS, "a texture fixture image is created"); + std::unique_ptr texture; + try { + texture = std::make_unique(context, image, info.format, VK_IMAGE_ASPECT_COLOR_BIT, VkComponentMapping{}); + } catch (...) { + context.Function("vkDestroyImage")(context.device, image, nullptr); + throw; + } + return std::shared_ptr(texture.release(), [context, image](Texture* released) { + delete released; + context.Function("vkDestroyImage")(context.device, image, nullptr); + }); } void textureSlots(const Context& context, VkImageView view) { BindlessHeap heap(context); const auto kind = Abi::FirstImageBinding; - auto first = fakeTexture(0); + auto first = fakeTexture(context, 0); const auto slot = heap.TextureSlot(kind, first.get(), view, VK_IMAGE_LAYOUT_GENERAL); require(slot.has_value(), "the first texture takes a slot"); require(heap.SlotTexture(kind, *slot) == first.get(), "the slot names the first texture"); require(first.use_count() == 1, "a heap slot holds a reference to its texture"); const auto generation = heap.SlotGeneration(*slot); - auto second = fakeTexture(1); + auto second = fakeTexture(context, 1); require(!heap.TextureSlot(kind, second.get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "the slot of a live texture is not reused"); heap.ReleaseSlots(first.get()); const auto reused = heap.TextureSlot(kind, second.get(), view, VK_IMAGE_LAYOUT_GENERAL); @@ -59,7 +80,7 @@ void textureSlots(const Context& context, VkImageView view) { const auto counts = heap.Statistics(); require(counts.slotsFreed == 1u, "one slot freed"); - auto shared = fakeTexture(2); + auto shared = fakeTexture(context, 2); const auto otherKind = kind + 1u; require(!heap.TextureSlot(otherKind, shared.get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "another kind finds the capped heap's only slot taken"); @@ -311,7 +332,7 @@ void heapComesBack(const Context& context, VkImageView view) { const auto kind = Abi::FirstImageBinding; std::vector> held; for (std::size_t index = 0; index < 7u; ++index) { - held.push_back(fakeTexture(index)); + held.push_back(fakeTexture(context, index)); require(heap.TextureSlot(kind, held.back().get(), view, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture takes one of the eight capped slots"); } @@ -339,7 +360,7 @@ bool idleSlotsEvicted(const Context& context, VkImageView view) { std::vector slots; const auto take = [&](std::size_t index) { if (held.size() <= index) held.resize(index + 1u); - if (held[index] == nullptr) held[index] = fakeTexture(index); + if (held[index] == nullptr) held[index] = fakeTexture(context, index); std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); return heap.TextureSlot(kind, held[index].get(), view, VK_IMAGE_LAYOUT_GENERAL); }; @@ -412,7 +433,7 @@ void mixedComesBack(const Context& context, VkImageView sampledView, VkImageView auto& heap = BindlessHeap::For(context); std::vector> textures; for (std::size_t index = 0; index < 4u; ++index) { - textures.push_back(fakeTexture(index)); + textures.push_back(fakeTexture(context, index)); require(heap.TextureSlot(Abi::FirstImageBinding, textures.back().get(), sampledView, VK_IMAGE_LAYOUT_GENERAL).has_value(), "a texture takes one of the eight capped slots"); } @@ -470,7 +491,7 @@ bool slotPressureSubmits(const Context& context, VkImageView view) { std::vector> held; std::vector slots; for (std::size_t index = 0; index < 7u; ++index) { - held.push_back(fakeTexture(index)); + held.push_back(fakeTexture(context, index)); const auto slot = heap.TextureSlot(kind, held.back().get(), view, VK_IMAGE_LAYOUT_GENERAL); require(slot.has_value(), "a texture takes one of the eight capped slots"); slots.push_back(*slot); @@ -491,7 +512,7 @@ bool slotPressureSubmits(const Context& context, VkImageView view) { require(!heap.TakeSlotPressure() && !BindlessHeap::NearlyFull(), "slots the submission covers clear the nearly full state"); require(heap.SlotGeneration(slots[0]) != generation && heap.SlotTexture(kind, slots[0]) == nullptr, "an evicted slot moves its generation and names no texture"); for (std::size_t index = 7; index < 12u; ++index) { - held.push_back(fakeTexture(index)); + held.push_back(fakeTexture(context, index)); const auto slot = heap.TextureSlot(kind, held.back().get(), view, VK_IMAGE_LAYOUT_GENERAL); require(slot.has_value(), "a new texture takes a slot after the pressure submission, waiting for it when none is free"); } @@ -551,6 +572,7 @@ bool samplersEvicted(const Context& context) { slots.push_back(*slot); } require(BindlessHeap::NearlyFull(), "too few free sampler slots mark the heap nearly full"); + submit(); const auto generation = heap.SamplerGeneration(slots[0]); { std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); diff --git a/core/libs/prx/libSceAgcDriver/tests/DrawPipelineStop.cpp b/core/libs/prx/libSceAgcDriver/tests/DrawPipelineStop.cpp index 74656deafbcb..af6485e8930d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/DrawPipelineStop.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/DrawPipelineStop.cpp @@ -32,8 +32,9 @@ void TestStopReleasesFullProducer() { returned.store(true, std::memory_order_release); }); const auto producerId = producer.get_id(); - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - const bool waitedForRoom = !returned.load(std::memory_order_acquire); + const auto waiting = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (pipeline.FullWaiters() == 0 && !returned.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < waiting) std::this_thread::yield(); + const bool waitedForRoom = pipeline.FullWaiters() != 0 && !returned.load(std::memory_order_acquire); std::thread stopper([&] { pipeline.Stop(); }); const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); while (!returned.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < deadline) std::this_thread::sleep_for(std::chrono::milliseconds(1)); diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index 48ed37921423..a16be1478baf 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -10661,7 +10661,7 @@ bool refreshProofTests(const Device& device, Recorder& recorder) { std::memset(keys, 0x00, keyCount); Require(resources.Revalidate(std::span(&compute, 1), &report), "a set over a fast-cleared keyed storage image did not revalidate"); Require(report.path == ShaderResources::ProofPath::OwnRefreshed, "a fast clear of a storage image's keys took the full walk instead of the image's own refresh"); - Require(image->UploadedKeys() != DccKeys::Uncompressed, "the own refresh did not apply the fast clear"); + Require(image->UploadedKeys() == DccKeys::Clear0000, "the own refresh did not apply the fast clear"); Require(resources.Revalidate(std::span(&compute, 1), &report) && report.path == ShaderResources::ProofPath::Fast, "the set did not return to the fast proof after the fast clear"); recorder.Submit(); device.WaitQueue(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp index 67e13f5668c5..3ecd51769880 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp @@ -236,7 +236,7 @@ void RecordedMasks(AgcDriver::VulkanDevice& device, const Shaders& compiled, VkC const auto context = device.graphicsContext(); const auto shaders = Stages(device, compiled); const std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); - Recorder recorder(context, true); + Recorder recorder(context, device.TimelineSemaphores()); recorder.Activate(); const MaskTrace trace(context); const auto continued = [] { return DrawPassTotals()[0].passesContinued; }; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp index 5d29d6473a31..4aa730492930 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/CopyInputLifetime.cpp @@ -69,7 +69,7 @@ PFN_vkVoidFunction VKAPI_CALL Resolve(VkDevice device, const char* name) { return originalProc(device, name); } -void Scenario(Graphics::Context context, bool fail) { +void Scenario(Graphics::Context context, bool fail, bool timeline) { constexpr std::size_t blockBytes = 65536; constexpr auto usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; constexpr auto properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; @@ -94,7 +94,7 @@ void Scenario(Graphics::Context context, bool fail) { bool caught = false; bool earlyReuse = false; { - Graphics::Recorder recorder(context, true); + Graphics::Recorder recorder(context, timeline); recorder.Activate(); try { Graphics::GuestBufferMemory memory(context); @@ -151,8 +151,8 @@ int main() { originalFree = context.Function("vkFreeMemory"); originalCopy = context.Function("vkCmdCopyBuffer"); originalBarrier = context.Function("vkCmdPipelineBarrier"); - Scenario(context, false); - Scenario(context, true); + Scenario(context, false, device->TimelineSemaphores()); + Scenario(context, true, device->TimelineSemaphores()); return 0; } catch (const std::exception& error) { std::cerr << error.what() << '\n'; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp index d275bec8559b..781190ede731 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp @@ -411,8 +411,8 @@ void LiveRecorderMaskIsolation(AgcDriver::VulkanDevice& device) { auto* previous = Recorder::Active(); { auto& htile = NewBlock(); - Recorder first(context, true); - Recorder second(context, true); + Recorder first(context, device.TimelineSemaphores()); + Recorder second(context, device.TimelineSemaphores()); RecordHtileWords(context, first, htile, 0xf0u); NoteHtileMaskOnGpu(context, {htile.Address(), HtileBytes, 0x3f0u, 0u}); RecordHtileWords(context, second, htile, 0xfu); @@ -437,8 +437,8 @@ void MaskCleanupIsolation(AgcDriver::VulkanDevice& device, AgcDriver::VulkanDevi auto& firstHtile = NewBlock(); auto& secondHtile = NewBlock(); std::optional first; - first.emplace(context, true); - Recorder second(context, true); + first.emplace(context, device.TimelineSemaphores()); + Recorder second(context, device.TimelineSemaphores()); RecordHtileWords(context, *first, firstHtile, 0xf0u); NoteHtileMaskOnGpu(context, {firstHtile.Address(), HtileBytes, 0x3f0u, 0u}); RecordHtileWords(context, second, secondHtile, 0xf0u); @@ -450,9 +450,9 @@ void MaskCleanupIsolation(AgcDriver::VulkanDevice& device, AgcDriver::VulkanDevi auto& firstHtile = NewBlock(); auto& secondHtile = NewBlock(); auto& otherHtile = NewBlock(); - Recorder first(context, true); - Recorder second(context, true); - Recorder other(otherContext, true); + Recorder first(context, device.TimelineSemaphores()); + Recorder second(context, device.TimelineSemaphores()); + Recorder other(otherContext, otherDevice.TimelineSemaphores()); RecordHtileWords(context, first, firstHtile, 0xf0u); NoteHtileMaskOnGpu(context, {firstHtile.Address(), HtileBytes, 0x3f0u, 0u}); RecordHtileWords(context, second, secondHtile, 0xf0u); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawWriteRanges.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawWriteRanges.cpp index a9be10492ecc..fcca54218bba 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawWriteRanges.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawWriteRanges.cpp @@ -104,6 +104,32 @@ int main() { Require(typedBounded && Contains(typedRanges, written, written + surfaceBytes), "a dispatch whose written images are a real one and a TYPE 0 or 1 one lost the real one"); Require(!Touches(typedRanges, base, base + surfaceBytes), "a TYPE 0 or 1 storage image is a dispatch write range"); } + { + constexpr std::uint64_t heapWritten = 0x600000000ull; + constexpr std::uint64_t heapReadOnly = 0x700000000ull; + ShaderRecompiler::RecompileResult heapProgram; + heapProgram.gpuResolvedImages = true; + ShaderRecompiler::DescriptorBinding heapImages; + heapImages.kind = ShaderRecompiler::DescriptorKind::StorageImage; + heapImages.role = ShaderRecompiler::DescriptorRole::GuestImages; + heapImages.count = 2; + heapImages.imageWritten = {true, false}; + heapProgram.bindings.push_back(heapImages); + ShaderRecompiler::HeapStageWords heapWords; + heapWords.bindings.resize(1); + for (const auto base : {heapWritten, heapReadOnly}) { + const auto words = ImageWords(base, 256, 128); + heapWords.bindings[0].insert(heapWords.bindings[0].end(), words.begin(), words.end()); + } + const std::array heapStages{{{ShaderRecompiler::ShaderStage::Fragment, &heapProgram, 0, nullptr, &heapWords}}}; + const std::array bareStages{{{ShaderRecompiler::ShaderStage::Fragment, &heapProgram, 0}}}; + for (const bool exact : {false, true}) { + const auto ranges = DrawWriteRanges(state, heapStages, exact); + Require(Contains(ranges, heapWritten, heapWritten + surfaceBytes), "a heap-backed storage image the draw stores to is not a write range"); + Require(!Touches(ranges, heapReadOnly, heapReadOnly + surfaceBytes), "a heap-backed storage image the draw only reads is a write range"); + Require(!Touches(DrawWriteRanges(state, bareStages, exact), heapWritten, heapWritten + surfaceBytes), "a heap-backed stage's ranges came from somewhere other than its heap words"); + } + } AgcDriver::Graphics::State targets{}; targets.hasColorTarget = true; auto& color = targets.color; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp index 755ba1c1535f..8378eaa64787 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp @@ -30,7 +30,6 @@ alignas(256) constexpr std::array PixelCode{0xf4000100u, 0xfa alignas(256) std::array PixelConstant{}; alignas(256) std::array ColorMemory{}; constexpr std::uint32_t Rounds = 8; -alignas(256) std::array TextureMemory{}; alignas(4096) std::array, Rounds> Outputs{}; alignas(256) std::array SampleMemory{}; @@ -111,7 +110,7 @@ void Sample(std::vector& commands, float* output) { SetShaderRegister(commands, 0x212, 0); SetShaderRegister(commands, 0x213, 16u << 1u); std::uint32_t offset = 0x240; - for (const auto value : SampleUserData(TextureMemory.data(), output)) SetShaderRegister(commands, offset++, value); + for (const auto value : SampleUserData(ColorMemory.data(), output)) SetShaderRegister(commands, offset++, value); Append(commands, 0x15, {1, 1, 1, 0x8041u}); } @@ -136,10 +135,13 @@ int main() { Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2); Registered(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1); PixelConstant[0] = 0.25f; - FillTexels(TextureMemory, SampleTexel); for (auto& output : Outputs) output.fill(-1.0f); std::string drains; + constexpr std::array Constants{0.25f, 0.125f}; + unsigned expected = 0; for (std::uint32_t pass = 0; pass < 2; ++pass) { + PixelConstant[0] = Constants[pass]; + expected = static_cast((Constants[pass] + 0.25f) * 255.0f + 0.5f); static_cast(DrawFinisher::DrainText()); auto commands = Setup(); for (std::uint32_t round = 0; round < Rounds; ++round) { @@ -152,13 +154,18 @@ int main() { Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); AgcDriverWaitIdle_nid_postfix(); drains = DrawFinisher::DrainText(); + AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(Outputs.data()), sizeof(Outputs)); + for (std::uint32_t round = 0; round < Rounds; ++round) { + const auto where = "pass " + std::to_string(pass) + " round " + std::to_string(round); + const auto texel = [&](std::size_t channel) { return static_cast(Outputs[round][channel] * 255.0f + 0.5f); }; + Require(texel(0) + 1 >= expected && texel(0) <= expected + 1 && texel(3) + 1 >= expected && texel(3) <= expected + 1 && texel(1) == 0u && texel(2) == 0u, + "the dispatch after the draw in " + where + " sampled " + std::to_string(texel(0)) + "," + std::to_string(texel(1)) + "," + std::to_string(texel(2)) + "," + std::to_string(texel(3)) + " from the draw's target, expected " + std::to_string(expected) + ",0,0," + std::to_string(expected)); + } } - AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(Outputs.data()), sizeof(Outputs)); AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(ColorMemory.data()), ColorMemory.size()); - for (std::uint32_t round = 0; round < Rounds; ++round) RequireSampled(Outputs[round].data(), SampleTexel, "the dispatch after finisher draws in round " + std::to_string(round)); unsigned brightest = 0; for (const auto value : ColorMemory) brightest = std::max(brightest, static_cast(std::to_integer(value))); - Require(brightest + 2 >= 128 && brightest <= 130, "the draws around the dispatches wrote " + std::to_string(brightest) + ", expected 128"); + Require(brightest + 2 >= expected && brightest <= expected + 2, "the draws around the dispatches wrote " + std::to_string(brightest) + ", expected " + std::to_string(expected)); if (finisher) Require(drains.find(" 0x15 x") == std::string::npos, "a pipelined dispatch after a draw handed to the finisher drained the finisher:" + drains); if (finisher) Require(drains.find(" 0x46 x") == std::string::npos, "a sample dump after a draw handed to the finisher drained the finisher:" + drains); AgcDriverShutdown_nid_postfix(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/FinisherHitLookup.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherHitLookup.cpp index 7402a8e6c9a9..fe1fb6604bac 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/FinisherHitLookup.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherHitLookup.cpp @@ -129,8 +129,11 @@ int main() { PixelConstant[0] = 0.25f; SubmitDraws(8); static_cast(DrawFinisher::DrainText()); + const auto cacheBefore = AgcDriver::DriverDetail::Driver::Get().DrawCacheCounters(); SubmitDraws(64); + const auto cacheAfter = AgcDriver::DriverDetail::Driver::Get().DrawCacheCounters(); const auto drains = DrawFinisher::DrainText(); + Require(cacheAfter.hits > cacheBefore.hits, "the measured submission's repeated draws never hit the draw cache (" + std::to_string(cacheAfter.lookups - cacheBefore.lookups) + " lookups)"); AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(ColorMemory.data()), ColorMemory.size()); unsigned brightest = 0; for (const auto value : ColorMemory) brightest = std::max(brightest, static_cast(std::to_integer(value))); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp index 942771697240..e7d5e1d74d9a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapDrawBench.cpp @@ -43,7 +43,6 @@ namespace { using AgcDriver::Graphics::Require; -constexpr std::byte Kept{0x40}; constexpr std::array Texel{0x10u, 0x80u, 0xc0u, 0xffu}; alignas(256) constexpr std::array VertexCode{ @@ -53,55 +52,10 @@ alignas(256) constexpr std::array VertexCode{ alignas(256) constexpr std::array PixelCode{0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array ConstantSamplerPixelCode{ - 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, - 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; -alignas(256) constexpr std::array BorderSamplerPixelCode{ - 0xbe8803ffu, 6u | (6u << 3u) | (6u << 6u), 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, - 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; -alignas(256) constexpr std::array WrapSamplerPixelCode{ - 0xbe8803ffu, 0u, 0xbe8903ffu, 0u, 0xbe8a03ffu, 0u, 0xbe8b03ffu, 2u << 30u, - 0x7e0002f3u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u}; alignas(256) constexpr std::array BufferPixelCode{ 0x7e0002f0u, 0x7e0202f0u, 0xf4200506u, 0xfa000000u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e060214u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array GdsPixelCode{ - 0xbefc03ffu, 0x0000ffffu, 0x7e0002f0u, 0x7e0202f0u, 0xd8fa0010u, 0x04000000u, 0xf09c0f08u, 0x00400000u, - 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array StoragePixelCode{ - 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e100280u, 0x7e120280u, 0xf0201f08u, - 0x00040008u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array LdsPixelCode{ - 0x7e0002f0u, 0x7e0202f0u, 0xf09c0f08u, 0x00400000u, 0xbf8c0000u, 0x7e080280u, 0xd8344400u, 0x00000004u, - 0xbf8cc07fu, 0xd8d84400u, 0x00000004u, 0xbf8cc07fu, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; -alignas(4096) std::array StorageMemory{}; -alignas(256) constexpr std::array SamplingVertexCode{ - 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, 0x00820c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, - 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u, 0x7e060280u, - 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u, -}; -alignas(256) constexpr std::array InterpolantPixelCode{0xc8020002u, 0xc8060102u, 0xc80a0202u, 0xc80e0302u, - 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array BdaPixelCode{ - 0x7e0002f0u, 0x7e0202f0u, 0x7e08020cu, 0x7e0a020du, 0xdc308000u, 0x067d0004u, 0xf09c0f08u, 0x00400000u, - 0xbf8c0000u, 0x7e060306u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array TablePixelCode{ - 0xf4200404u, 0xfa000000u, 0xbf8cc07fu, 0x8f108510u, 0xf42c0500u, 0x20000000u, 0xbf8cc07fu, 0x7e0002f0u, - 0x7e0202f0u, 0xf09c0f08u, 0x00250000u, 0xbf8c0000u, 0xf800180fu, 0x03020100u, 0xbf810000u, 0xbf810000u}; -alignas(256) constexpr std::array TableVertexCode{ - 0xf4200508u, 0xfa000000u, 0xbf8cc07fu, 0x8f148514u, 0xf42c0604u, 0x28000000u, 0xbf8cc07fu, 0x7e1402f0u, 0x7e1602f0u, 0xf09c0f08u, - 0x00660c0au, 0xbf8c0000u, 0xf800020fu, 0x0f0e0d0cu, 0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, - 0x10040500u, 0x060404f3u, 0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u, 0xbf810000u, -}; -alignas(256) std::array TableMemory{}; -alignas(256) std::array FreshVertexCode{}; -alignas(256) std::array FreshPixelCode{}; -alignas(256) std::array MaterialMemory{}; -alignas(256) std::array OtherTextureMemory{}; constexpr float BufferAlpha = 0.2f; -constexpr std::uint8_t BufferAlphaByte = 51u; -constexpr float SecondAlpha = 0.6f; -constexpr std::uint8_t SecondAlphaByte = 153u; alignas(4096) std::array BufferMemory{}; alignas(256) std::array ColorMemory{}; @@ -128,7 +82,6 @@ std::span MergedTarget(std::size_t index) { }(); return {data[index], ColorMemory.size()}; } -alignas(256) std::array TextureMemory{}; struct Header { Shader shader{}; @@ -154,62 +107,6 @@ void Append(std::vector& commands, std::uint32_t opcode, std::ini commands.insert(commands.end(), payload); } -enum class Mode { Texture, Buffer, Storage, Gds, Vertex, Bda, Table, VertexTable, MovedBuffer, MovedTexture, PixelLds, ConstantSampler, BorderSampler, WrapSampler, MergedBlend, MergedBlendOther }; - -const std::uint32_t* VertexProgram(Mode mode) { - if (mode == Mode::VertexTable) return TableVertexCode.data(); - if (mode == Mode::Vertex) return SamplingVertexCode.data(); - return VertexCode.data(); -} - -std::uint32_t PixelUserWords(Mode mode, bool vertexSampling) { - switch (mode) { - case Mode::Storage: - return 24u; - case Mode::Buffer: - case Mode::MovedBuffer: - return 16u; - case Mode::Bda: - return 14u; - default: - return vertexSampling ? 0u : 12u; - } -} - -unsigned ExpectedChannel(Mode mode, bool buffer, std::size_t channel) { - if (mode == Mode::MovedTexture) return 0x33u; - if ((mode == Mode::Bda || mode == Mode::MovedBuffer) && channel == 3) return SecondAlphaByte; - if (buffer && channel == 3) return BufferAlphaByte; - if (mode == Mode::BorderSampler) return 0xffu; - if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return std::min(2u * Texel[channel] + static_cast(Kept), 0xffu); - return Texel[channel]; -} - -const char* DrawnWhat(Mode mode, bool buffer) { - if (mode == Mode::Bda) return " (texture and BDA)"; - if (mode == Mode::MovedBuffer) return " (texture and a buffer moved between two draws)"; - if (mode == Mode::MovedTexture) return " (a texture changed between two draws)"; - if (buffer) return " (texture and buffer)"; - if (mode == Mode::Table) return " (image table)"; - if (mode == Mode::ConstantSampler) return " (texture with a constant sampler)"; - if (mode == Mode::BorderSampler) return " (constant border-clamp sampler outside the texture)"; - if (mode == Mode::WrapSampler) return " (constant wrapping sampler outside the texture, after a border-clamp draw of the same shader)"; - if (mode == Mode::MergedBlend) return " (texture blended unclamped into the color target)"; - if (mode == Mode::MergedBlendOther) return " (texture blended unclamped into a second color target)"; - return " (texture)"; -} - -const char* TakenWhat(Mode mode, bool buffer) { - if (buffer) return " reading a buffer"; - if (mode == Mode::Vertex) return " (vertex stage)"; - if (mode == Mode::Bda) return " loading through BDA"; - if (mode == Mode::Table) return " reading an image table"; - if (mode == Mode::VertexTable) return " (vertex stage reading an image table)"; - if (mode == Mode::ConstantSampler || mode == Mode::BorderSampler || mode == Mode::WrapSampler) return " sampling with a constant sampler"; - if (mode == Mode::MergedBlend || mode == Mode::MergedBlendOther) return " merging into its color target"; - return ""; -} - std::array ImageDescriptor(const void* memory) { const auto address = static_cast(reinterpret_cast(memory)); return {static_cast(address >> 8u), @@ -228,7 +125,6 @@ std::array BufferDescriptor(const void* memory, std::size_t by 0xfacu}; } - constexpr std::size_t Textures = 16; constexpr std::size_t Buffers = 32; alignas(256) std::array, Textures> BenchTextures{}; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp index 20873caf175b..71f577ae5bea 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapWalkThreads.cpp @@ -6,6 +6,8 @@ #include "VulkanTestDevice.hpp" #include #include +#include +#include #include #include #include @@ -74,6 +76,7 @@ std::vector> Prepare(AgcDriver::VulkanDevice& device) { struct Inbox { std::mutex mutex; + std::condition_variable ready; std::deque stages; }; @@ -97,6 +100,7 @@ void Work(const std::vector>& variants, std::size_t fir std::lock_guard lock(peer.mutex); peer.stages.push_back(std::move(stage)); } + peer.ready.notify_one(); std::deque received; { std::lock_guard lock(own.mutex); @@ -107,13 +111,27 @@ void Work(const std::vector>& variants, std::size_t fir held.push_back(std::move(item)); } while (held.size() > Held) held.pop_front(); - if (failed.load(std::memory_order_relaxed)) return; + if (failed.load(std::memory_order_acquire)) return; } } - Require(touched != 0, "a heap walk thread received no stage from the other thread"); + while (touched == 0) { + std::deque received; + { + std::unique_lock lock(own.mutex); + own.ready.wait_for(lock, std::chrono::seconds(60), [&] { return !own.stages.empty() || failed.load(std::memory_order_acquire); }); + received.swap(own.stages); + } + if (failed.load(std::memory_order_acquire)) return; + Require(!received.empty(), "a heap walk thread received no stage from the other thread"); + for (auto& item : received) touched += Touch(item); + } } catch (const std::exception& caught) { error = caught.what(); - failed.store(true, std::memory_order_relaxed); + failed.store(true, std::memory_order_release); + for (auto* inbox : {&own, &peer}) { + std::lock_guard lock(inbox->mutex); + inbox->ready.notify_all(); + } } } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp index 55c8abadbc70..aa0006019a46 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageTableCacheBounds.cpp @@ -500,14 +500,14 @@ void AtomicTable(const GuestBlock& block) { } bool StoreTable(const GuestBlock& block) { - PrepareAtomicRecords(block, StoreTableCode.data(), sizeof(StoreTableCode), Format16x4Float, StoreSurfaceBytes, - [](std::uint32_t, std::uint8_t* surface) { std::memset(surface, 0, StoreSurfaceBytes); }); - const auto heapStages = AgcDriver::Graphics::HeapComputeStages(); - Dispatch(block, 0, AtomicKernelOffset); if (!AgcDriver::Graphics::DescriptorHeapEnabled()) { std::puts("image table store skipped: per-dispatch image tables have no uint storage view (docs/dev/debt/libSceAgcDriver.md)"); return false; } + PrepareAtomicRecords(block, StoreTableCode.data(), sizeof(StoreTableCode), Format16x4Float, StoreSurfaceBytes, + [](std::uint32_t, std::uint8_t* surface) { std::memset(surface, 0, StoreSurfaceBytes); }); + const auto heapStages = AgcDriver::Graphics::HeapComputeStages(); + Dispatch(block, 0, AtomicKernelOffset); std::array texels{}; AgcDriver::GuestMemory::Read(block.At(TexturesOffset + static_cast(AtomicElement) * StoreSurfaceBytes), std::as_writable_bytes(std::span(texels))); for (std::uint32_t texel = 0; texel < AtomicWidth; ++texel) { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampledPassOrder.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampledPassOrder.cpp index 784029cde215..4194ba49fedd 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/MultisampledPassOrder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/MultisampledPassOrder.cpp @@ -129,7 +129,7 @@ int main() { device->WaitIdle(); std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); const auto captured = Capture::Install(base); - Recorder recorder(captured, true); + Recorder recorder(captured, device->TimelineSemaphores()); recorder.Activate(); const auto depthA = reinterpret_cast(DepthA.data()); const auto depthB = reinterpret_cast(DepthB.data()); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PassBreakReasons.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PassBreakReasons.cpp index 0a51508a0621..6fb45ada82ac 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PassBreakReasons.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PassBreakReasons.cpp @@ -143,7 +143,7 @@ int main() { const auto shaders = Compile(*device); device->WaitIdle(); std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); - Recorder recorder(context, true); + Recorder recorder(context, device->TimelineSemaphores()); recorder.Activate(); Expect(MultisampledDepthBytes_nid_no_patch({Width, Height}, sizeof(float), Samples) == DepthA.Bytes().size(), "the depth backing differs from its multisample footprint"); const auto depthA = DepthA.Address(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp index 667ada19fd42..ad654dd338bd 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PreparedGraphics.cpp @@ -671,8 +671,12 @@ void CheckMergedHull(AgcDriver::VulkanDevice& device) { RecompileRequest request{program.binary, {64u, program.firstUserSgpr, program.userData, {}, std::nullopt, vertex, memory}, device.Target(), {0, 0, 0, 128u}, GraphicsCompileContext{program.firstUserSgpr, linked, std::nullopt, draw.state.stages.tessellation, {0, 3, 4, 1}}}; static_cast(InvocationFor(*program.snapshot, program.codeOffset, request)); Require(merged.snapshot->prepared->entries.size() == predicted, "a merged hull stage prepared at ABI resolution was prepared again at its draw"); + const auto wanted = index == 0u ? ShaderRecompiler::ShaderStage::Local : ShaderRecompiler::ShaderStage::TessellationControl; + const auto regular = std::find_if(stages.begin(), stages.end(), [&](const auto& stage) { return !stage.heapVariant && stage.stage == wanted; }); + Require(regular != stages.end(), "a merged hull draw prepared no regular stage for its program"); + Require(MatchesPreparedShader(request, *regular->entry.handle), "an unchanged merged hull request did not match its prepared artifact"); request.graphics->tessellation->mergedHull = false; - Require(!MatchesPreparedShader(request, *stages[index].entry.handle), "a separate hull configuration matched a merged hull artifact"); + Require(!MatchesPreparedShader(request, *regular->entry.handle), "a separate hull configuration matched a merged hull artifact"); } Fixture front; front.Initialize(5u); From 4b6c7b20b3339553f61bc432cbbf15630e8505c2 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Mon, 16 Nov 2026 23:43:29 +0530 Subject: [PATCH 258/269] docs(agc): heap mode has no per-draw fallback B22: ARCHITECTURE.md and the GPU descriptor heap debt entry now agree. Registration of a stage whose module does not map only skips its pipeline-library prebuild; RequireHeapStageMappable, the eligibility check and the mixed-draw check make the draw or dispatch throw. --- docs/dev/ARCHITECTURE.md | 2 +- docs/dev/debt/changes/fix-9508-review-b.md | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 docs/dev/debt/changes/fix-9508-review-b.md diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index c794c46fe420..3bb0cc927c59 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -148,7 +148,7 @@ flowchart LR - Queue 0's packet worker decodes, captures and prepares a draw and hands its recording (`Graphics::Draw` under the GPU lock) to a committer thread in [`DrawPipeline.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp), so the next packet is decoded while the previous draw is recorded. Each queued item carries the guest ranges it will write (`DrawWriteRanges`: written buffers and storage images, color targets with their DCC and CMASK, depth and stencil). A later packet that reads or writes one of those ranges, or that the pipeline can't order, drains it first; labels, submission ends, buffer fills and DMA packets are queued as items instead. With `APS5_PIPELINE_DISPATCH=1` (off by default), a `DISPATCH_DIRECT` whose dispatch-cache entry hits with a recipe is queued as an item too, carrying the dispatch's written buffers and storage images (`DispatchWriteRanges`); the capture and the cache lookup stay on the worker and the recipe is recorded on the committer. A dispatch still drains when its lookup misses, when what it reads overlaps a write still pending, when the hit is verified against data or when its writes cannot be ranged (bindless access, GDS, fault buffer). An indirect draw resolved on the CPU (its records read by the worker) drains only when its records or its count overlap a queued write; the records it draws inline drain first, and its last drawn record is queued like a direct draw (`APS5_NO_PIPELINED_INDIRECT=1` drains at every indirect draw). An exception thrown by a commit is rethrown on the worker at its next enqueue or drain, as an inline draw error would be. On by default; `APS5_PIPELINED_DRAWS=0` records every draw inline, and `APS5_EXACT_DRAW_WRITES=0` widens the color and depth ranges to estimates. - A dispatch's resource build runs stage A (binding plan, buffers, descriptor set) without the GPU lock and stage B (image lookups) under it. Between them `VulkanDevice::presync` waits, still without the lock, for recorded work that writes a surface stage B would read on the CPU and for recorded work that writes the DCC keys of an image the dispatch binds (`ShaderResources::PresyncSurfaces`), so the locked `WaitForKeyWriters` finds nothing pending to synchronize with. A key range is waited for only when recorded work writes it, the key-store memo does not give its value (`DccKeyWritersPending`, without the mutex) and the pending stores do not give it either (`DccKeyWriterNeedsSync`, under the mutex, the same test `WaitForKeyWriters` makes before it synchronizes). Stage A's own key scan runs before that wait, and stage B compares it with the keys it reads under the lock as before. `APS5_NO_DCC_PRESYNC=1` leaves the key ranges out; `APS5_NO_PRESYNC=1` disables the whole pre-sync. - `APS5_DRAW_PIPELINE` (any value turns it on, even `0`; off by default, meant with `APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1`) takes more of a draw off the worker. A `DrawFinisher` thread runs the second half of a direct pipelined draw (stage materialization, the draw cache insert and the hand-off to the committer) while the worker reads the next packets; the worker drains it before the next draw's cache lookup, before packets other than register writes and draws, and before guest reads, and finishes in place a draw whose stages may write memory (`ProgramWritesMemory`) or write through the BDA page table. The committer skips the storage-image layer scans whose inputs match its last commit (`CommitTrims`), and a resource or storage image proved current keeps its proof for the rest of the collect epoch until `GuestMemory::BreakProofs` (a CPU write, a write-back, a recorded write) moves `ProofSerial`. A draw that continues the open render pass with equal color and depth targets takes the previous draw's resident images and attachment views while the collect epoch, `ProofSerial`, `StorageTexture::PendingSerial`, each image's version and storage cache entry and the depth surface serials are unchanged; `APS5_NO_PASS_ATTACHMENT_MEMO=1` looks them up anew and `APS5_VERIFY_PASS_ATTACHMENTS=1` compares a hit with the full lookup. Color metadata passes go through the pipeline with their write ranges (`PipelinedColorMetadataPassWrites`) instead of draining it. A data-only hit whose shape entry belongs to an older draw replaces that entry in place at the second sight of the same read user words. On Linux the main image's pages get a page table entry, and capture pages are pooled across threads. `APS5_VERIFY_DRAW_PIPELINE=1` runs a full check next to 1 in 64 reused proofs and prints `[epoch-proofs]` counts. -- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 233472 image slots that every image binding kind shares, the first 57 holding each kind's absent descriptor, and 2048 sampler slots, per-draw shader data and flattened SRT in a host-visible data pool the shaders reach by address) instead of per-draw descriptor sets. Without the extension, or when the device's heaps cannot hold those slots, every stage takes the per-draw path. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; a stage stays GPU-mode only if its compiled module maps onto the heap and every stage of its draw is GPU-mode too; otherwise it is rebuilt on the per-draw path. A draw whose stages come out mixed is rebuilt once with what the first pass learned, and a stage pair that is still mixed takes the per-draw path from then on. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A heap slot holds no reference to its texture, storage image, view or sampler: the owner frees its slots when it is destroyed, and every batch that reads a slot keeps the owner alive through its draw's or dispatch's resources, so a slot is never reused while a batch can still read it. With fewer free image or sampler slots than the margin, stages take the per-draw path until released slots leave twice the margin free. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the data pool and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap is recompiled on the per-dispatch path. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the data pool per draw with its address in two more pushed dwords. Tables with image atomics index the heap too. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers through addresses in its push data instead of storage buffer descriptors, like vkd3d-proton's root descriptors: up to four records of 64-bit address and byte size map as storage buffers (or as uniform buffers when every access is a scalar load at a constant offset), the rest go to a per-draw overflow block; a draw whose buffers are snapshotted pushes the snapshot addresses. +- `APS5_GPU_HEAP=1` (off by default) binds the sampled images and samplers of eligible stages through the device's `VK_EXT_descriptor_heap` resource and sampler heaps ([`BindlessHeap.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp): 233472 image slots that every image binding kind shares, the first 57 holding each kind's absent descriptor, and 2048 sampler slots, per-draw shader data and flattened SRT in a host-visible data pool the shaders reach by address) instead of per-draw descriptor sets. Without the extension, or when the device's heaps cannot hold those slots, the switch has no effect and every draw and dispatch binds per-draw descriptor sets. A fragment or vertex stage whose plan allows it is recompiled in GPU mode (`gpuResolvedImages`): its image metadata names the binding element and the shader reads the heap slots from the shader data once, at its entry; with the switch on, every stage of every draw is GPU-mode and there is no per-draw fallback. A stage whose compiled module does not map onto the heap (`RequireHeapStageMappable`, called at draw capture and at dispatch), a stage whose plan is ineligible, a stage kind the heap does not take and a draw whose stages come out mixed make the draw or dispatch throw. Registration only skips the pipeline-library prebuild of a stage whose module does not map (`PrebuildStageLibrary`); the failure comes when a draw or dispatch uses the stage. `APS5_GPU_HEAP_EXCLUDE` is a debug aid that sends the stages it names through the per-draw path. A heap fragment or vertex stage keeps one compiled template per binding plan shape; each draw carries its own descriptor words, so draws whose buffers or textures change share the template. An address-based draw whose BDA accesses only read reuses its address space while the collect epoch and the host imports are unchanged (space reuse; with `APS5_DRAW_PIPELINE=1` its refreshed mirrors are reused within the epoch too). The pipeline journal describes the heap set layouts, so GPU-mode pipelines are replayed on the next run. `APS5_VERIFY_GPU_HEAP=1` checks the heap slots against the bound textures, rebuilds 1 in N GPU-mode stages on the per-draw path and compares them (`[heap-slots]`, `[gpu-heap]`). The storage images of GPU-mode stages take heap slots of their own. A heap slot holds no reference to its texture, storage image, view or sampler: the owner frees its slots when it is destroyed, and every batch that reads a slot keeps the owner alive through its draw's or dispatch's resources, so a slot is never reused while a batch can still read it. With fewer free image or sampler slots than the margin, the recorder submits its batch at the next draw and evicts the slots no pending batch reads (`TakeSlotPressure`); a stage that still finds no free slot throws. A GPU-mode stage reads its shader data and flattened SRT through five push constant dwords at its push offset (both GPU addresses in the data pool and the SRT's dword count, the offset a specialization like the existing push data), which the driver writes at every draw, so a draw binds no data set. The same five words are followed by the BDA page table's address and dword count and the fault buffer's address, so a heap draw binds no descriptor set. Sampling compute stages are GPU-mode stages under the switch too and bind the same way, with their workgroup memory reached by a pushed address; one whose module does not map onto the heap throws at its dispatch. Every vertex or fragment stage whose images all come from descriptors is a heap stage under the switch, stages without images included: a vertex stage reads its SRT constants through the pushed flattened SRT. Image, storage image and sampler tables index the heap: the table arrays alias the heap's first sampled, first storage and sampler bindings, the driver appends a sampled and a storage slot per element and a slot per table sampler to the map (from `HeaderElementBase`), and the map goes into the data pool per draw with its address in two more pushed dwords. Tables with image atomics index the heap too. A heap stage writes its resolved image and sampler slots into its shader data without registering lookup keys, and reads its guest buffers through addresses in its push data instead of storage buffer descriptors, like vkd3d-proton's root descriptors: up to four records of 64-bit address and byte size map as storage buffers (or as uniform buffers when every access is a scalar load at a constant offset), the rest go to a per-draw overflow block; a draw whose buffers are snapshotted pushes the snapshot addresses. - The shader registry maps a code address to every header registered for that code, in registration order. Static, graphics and rectangle ABI resolution pick the header at the bound address (or one equal to it, `SameHeader`, which also takes a hull header fused by `sceAgcFuseShaderHalves` (type 3) as the registered back half (type 7) it copies, the fused registers aside; graphics ABI resolution then uses the fused header's shader registers); draws and dispatches pick the program by the stage's binary type (`RegisteredProgram`), and a front entry matching both type 2 and type 4 throws. Within a type the last registration wins; re-registering an identical earlier header makes its snapshot current again without preparing it again, and changed code drops the older headers. - The snapshot is published as pending. `SourceHandleFor`, `InvocationFor` and `ShaderPreparationTransaction::Edit` / `Read` wait for the pending job before reading `PreparedShaders`, and rethrow its failure. `APS5_SYNC_SHADER_PREPARE=1` prepares on the registering thread instead. - `APS5_LAZY_SHADER_PREPARE=1` retains registration validation and decoding but discards the temporary plan without queueing preparation. The snapshot is deferred, not pending; draws and dispatches prepare and cache it on first use. A compute or pixel stage's explicit ABI resolution (`ResolveShaderAbi`) plans the stage with the ABI's state, records the ABI and leaves its preparation to the shader's first use, which prepares it with that state (`PreparedShaders::deferredAbis`), so a shader that never draws or dispatches stays unprepared; a graphics-stage ABI is still prepared when it is resolved. This opt-in mode takes precedence over synchronous registration preparation and trades background CPU/memory use for possible first-use stalls; disk caches and shader output are unchanged. diff --git a/docs/dev/debt/changes/fix-9508-review-b.md b/docs/dev/debt/changes/fix-9508-review-b.md new file mode 100644 index 000000000000..ac47ec04ce7f --- /dev/null +++ b/docs/dev/debt/changes/fix-9508-review-b.md @@ -0,0 +1,5 @@ +# libSceAgcDriver + +## change [GPU descriptor heap] + +- [GPU descriptor heap](../../../core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp) (`APS5_GPU_HEAP`) - opt-in, needs `VK_EXT_descriptor_heap` and timeline semaphores; without the extension it has no effect. Heap mode has no per-draw path: a stage that needs more image slots than the heap holds, whose module keeps a binding the heap does not map (`RequireHeapStageMappable`) or whose plan is ineligible, and a draw whose stages come out mixed, fail at the draw or dispatch, not at registration (only `APS5_GPU_HEAP_EXCLUDE` sends stages per-draw). With `APS5_HEAP_SLOT_CAP` far below the default, stages that each fit can still exhaust the heap between their compile and their bind. Heap stages report no BDA fault per use, so the address draw reuse test skips its fault-per-use case with `--heap-stages`. A reused address-based draw whose moved read-only buffer cannot be viewed in place is built again. From bb796287c4a5a445db786d28c44dffbbc40d65d1 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 17 Nov 2026 01:32:50 +0530 Subject: [PATCH 259/269] test(agc): cover a heap in-place moved buffer read behind a queued label store --- .../tests/execution/DrawRecipeMovedBuffer.cpp | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp index 0812a551aecb..c1d849dd5388 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp @@ -243,7 +243,7 @@ std::array BufferDescriptor(const void* memory, std::size_t by alignas(256) std::array SampledTexture{}; -std::vector Frame(std::span slices, std::optional filled = std::nullopt) { +std::vector Frame(std::span slices, std::optional filled = std::nullopt, std::optional stored = std::nullopt) { const auto color = reinterpret_cast(MergedTarget(0).data()); const std::vector> context{ {0x2d5, 0x2000}, @@ -317,6 +317,10 @@ std::vector Frame(std::span slices, std::optio const auto destination = reinterpret_cast(SliceAt(slice)); Append(commands, 0x50, {0u, static_cast(source), static_cast(source >> 32u), static_cast(destination), static_cast(destination >> 32u), 16u}); } + if (stored.has_value() && slice == *stored) { + const auto label = reinterpret_cast(SliceAt(slice)); + commands.insert(commands.end(), {0xc0033700u, 0x00100200u, static_cast(label), static_cast(label >> 32u), std::bit_cast(FilledAlpha)}); + } std::array words{}; const auto image = ImageDescriptor(SampledTexture.data()); std::copy(image.begin(), image.end(), words.begin()); @@ -340,9 +344,9 @@ unsigned DrawnAlpha() { throw std::runtime_error("the draws covered no pixel"); } -unsigned Submit(std::span slices, std::optional filled = std::nullopt) { +unsigned Submit(std::span slices, std::optional filled = std::nullopt, std::optional stored = std::nullopt) { std::ranges::fill(MergedTarget(0), Kept); - auto commands = Frame(slices, filled); + auto commands = Frame(slices, filled, stored); Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); AgcDriverWaitIdle_nid_postfix(); @@ -423,6 +427,13 @@ int main() { Require(shiftedAlpha == FilledAlphaByte, "a draw whose buffer moved to another view alignment behind a GPU copy did not read the copied value (alpha " + std::to_string(shiftedAlpha) + ")"); Require(AgcDriver::Graphics::ShaderResources::MovedBehindGpuWrites() == shiftedBefore, "a draw whose buffer moved to another view alignment was read in place through its template's view"); OtherMemory.fill(0.0f); + constexpr std::size_t Stored = First + 128; + BufferMemory[Stored] = 0.0f; + const std::array storedSlices{First, Stored}; + const auto storedAlpha = Submit(storedSlices, std::nullopt, Stored); + Require(storedAlpha == FilledAlphaByte, "a draw whose buffer moved onto a range a label store queued earlier in its batch did not read the stored value (alpha " + std::to_string(storedAlpha) + ")"); + BufferMemory[Stored] = 0.0f; + OtherMemory.fill(0.0f); std::puts("draws whose read-only buffer moved from their template's replayed recipes that read the buffer's current contents"); AgcDriverShutdown_nid_postfix(); return 0; From 3196e68e20d6dde0eb01f71126b608016450c191 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 17 Nov 2026 05:57:46 +0530 Subject: [PATCH 260/269] fix(agc): keep driver caches and heap stage preparation consistent - VariantValidation.cpp:172: the verify-skip check throws only while the pending image serial is still the one the cached proof was taken at, so a concurrent publication follows the existing PendingMoved path. - DrawCapture.cpp:406 (and the change checks at Draw.cpp:1445,1516,1543): a stage re-run from the indirect-draw patch loop keeps the read regions of every recompiled direct stage except its own, not only of earlier ones. - ShaderRegistry.cpp:1700 and :2405: a failed optional heap preparation is logged and skipped, keeping the ordinary entries; the graphics ABI path still throws when it is not deferring. - RecycledShared.hpp:33: a zero-capacity pool hands out the new object without retaining it instead of indexing an empty vector. - DispatchCache.cpp:71: variant byte accounting includes the retained ring template and its vectors, on add and on removal. --- .../include/Driver/Draw/RecycledShared.hpp | 2 +- .../src/Driver/Dispatch/DispatchCache.cpp | 5 +++++ .../src/Driver/Dispatch/VariantValidation.cpp | 2 +- .../Execution/src/Driver/Draw/DrawCapture.cpp | 2 +- .../src/Driver/Shaders/ShaderRegistry.cpp | 20 +++++++++++++++---- .../tests/LinkedCodeDependencies.cpp | 13 ++++++++++++ .../libSceAgcDriver/tests/RecycledShared.cpp | 11 ++++++++++ 7 files changed, 48 insertions(+), 7 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp index 25f97a12a458..bb59f1e2d1be 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/RecycledShared.hpp @@ -29,7 +29,7 @@ class RecycledShared { ++fresh; if (pool.size() < capacity) { pool.push_back(made); - } else { + } else if (!pool.empty()) { pool[cursor] = made; advance(); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp index 942a331a1463..dd6cdc7a1467 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCache.cpp @@ -69,6 +69,11 @@ Driver::DispatchCacheFootprint Driver::DispatchCacheSize() { std::uint64_t Driver::variantBytes(const DispatchVariant& variant) { const auto held = [](const auto& values) { return static_cast(values.capacity() * sizeof(values[0])); }; auto bytes = sizeof(DispatchVariant) + held(variant.runs) + held(variant.words) + held(variant.shared) + held(variant.dataPositions) + held(variant.dataSlots) + held(variant.runBases) + held(variant.shaderDataPatches) + held(variant.captured) + held(variant.spans) + (variant.registeredViews != nullptr ? held(*variant.registeredViews) : 0u) + (variant.vertexInfo != nullptr ? sizeof(ShaderRecompiler::ShaderVertexStageInfo) : 0) + (variant.memory != nullptr ? variant.memory->Bytes() : 0) + held(variant.ringDescriptorPatches) + held(variant.ringDataPatches); + if (variant.ringTemplate != nullptr) { + const auto& ring = *variant.ringTemplate; + bytes += sizeof(ring) + held(ring.userData) + held(ring.flattenedSrt) + held(ring.vertexAttributes) + held(ring.bindings); + for (const auto& words : ring.bindings) bytes += held(words); + } if (variant.linking != nullptr) { const auto& link = *variant.linking; bytes += sizeof(link) + held(link.callees) + held(link.code) + held(link.tableUserData) + held(link.dependencies); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp index c500b205694e..ae0264fde3fc 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/VariantValidation.cpp @@ -169,7 +169,7 @@ EntryOutcome Driver::validateVariant(std::uint64_t program, std::uint32_t queue, pendingOverlaps = Graphics::StorageTexture::AnyPendingOverlaps(runs); if (wholeRuns && !pendingOverlaps) variant.cleanPendingSerial.store(pendingSerial, std::memory_order_release); } else if (verifyPendingSerialSkip()) { - if (Graphics::StorageTexture::AnyPendingOverlaps(runs)) throw std::runtime_error("APS5_VERIFY_PENDING_SERIAL_SKIP: a dispatch variant skipped its pending image check at an unchanged serial while a pending image overlaps its runs"); + if (Graphics::StorageTexture::AnyPendingOverlaps(runs) && Graphics::StorageTexture::PendingSerial() == pendingSerial) throw std::runtime_error("APS5_VERIFY_PENDING_SERIAL_SKIP: a dispatch variant skipped its pending image check at an unchanged serial while a pending image overlaps its runs"); } if (pendingOverlaps || Graphics::AnyShadowedOverlaps(runs)) { vouched.clear(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 80562067849e..55d8f02a69ba 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -403,7 +403,7 @@ std::shared_ptr Driver::materializeDraw for (std::size_t j = 0; j < context.programs.size(); ++j) { if (context.matched[j] != nullptr && !context.recompiled[j] && (context.drawHit || j < i)) context.memory.insert(context.memory.end(), context.matchedRegions[j].begin(), context.matchedRegions[j].end()); - if (j < i && context.recompiled[j] && context.stageCaptures[j].Direct()) context.memory.insert(context.memory.end(), context.stageCaptures[j].regions.begin(), context.stageCaptures[j].regions.end()); + if (j != i && context.recompiled[j] && context.stageCaptures[j].Direct()) context.memory.insert(context.memory.end(), context.stageCaptures[j].regions.begin(), context.stageCaptures[j].regions.end()); } request.context.memory = context.memory; if (dumpGraphics) static_cast(dumpRequest(program.binary.codeAddress, request)); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp index 9dc6cedf3f5b..26a14944706a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp @@ -1697,9 +1697,14 @@ std::vector PrepareRegistered(RegisteredPreparation& pla auto heapRequest = request; heapRequest.target.gpuResolvedImages = true; PerformanceTimer timing("Shader.PrepareArtifact"); - entries.push_back({plan.codeOffset, PrepareShaderWithDiagnostics(heapRequest, &preparation)}); - prebuild(heapRequest, *entries.back().handle); - heapPrebuilt = request.target.descriptorMemory; + try { + auto heapHandle = PrepareShaderWithDiagnostics(heapRequest, &preparation); + entries.push_back({plan.codeOffset, std::move(heapHandle)}); + prebuild(heapRequest, *entries.back().handle); + heapPrebuilt = request.target.descriptorMemory; + } catch (const std::exception& error) { + APS5_LOG_OUT("heap shader preparation skipped: %s", error.what()); + } } } if (!heapPrebuilt) prebuild(request, *entries.front().handle); @@ -2402,7 +2407,14 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod if (!invocation || !HeapStageEligible(stage.stage, invocation->Plan().get()) || (HeapPreRasterStage(stage.stage) && !heapVertex)) return false; auto request = *requests[index]; request.target.gpuResolvedImages = true; - const auto handle = preparedHandle(*stage.snapshot, stage.entry.codeOffset, request); + std::shared_ptr handle; + try { + handle = preparedHandle(*stage.snapshot, stage.entry.codeOffset, request); + } catch (const std::exception& error) { + if (!deferUnprepared) throw; + APS5_LOG_OUT("heap graphics stage preparation skipped: %s", error.what()); + return false; + } heap.push_back({stage.snapshot, {stage.entry.codeOffset, handle}, stage.stage, stage.pushOffset, registrationFor(request, *handle), true}); return true; }; diff --git a/core/libs/prx/libSceAgcDriver/tests/LinkedCodeDependencies.cpp b/core/libs/prx/libSceAgcDriver/tests/LinkedCodeDependencies.cpp index 2e3e94cd978f..fc8eec46c8af 100644 --- a/core/libs/prx/libSceAgcDriver/tests/LinkedCodeDependencies.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/LinkedCodeDependencies.cpp @@ -24,6 +24,9 @@ namespace AgcDriver::DriverDetail { struct DriverTestAccess { + static std::uint64_t VariantBytes(const DispatchVariant& variant) { + return Driver::variantBytes(variant); + } static std::shared_ptr Insert(const std::shared_ptr& shader, const ShaderRecompiler::RecompileRequest& request, bool disabled = false, std::vector>* dependencies = nullptr) { auto& driver = Driver::Get(); auto memory = std::make_shared(request.context.memory); @@ -313,6 +316,16 @@ void Run(const std::string& mode, std::string_view watch) { const auto footprint = Driver::Get().DispatchCacheSize(); Require(footprint.entries == 1u && footprint.variantBytes >= 16u, "cached callee snapshots were not accounted"); Require(original->linking != nullptr && original->linking->dependencies.size() == 2u, "cached direct linking did not capture both callees"); + { + const auto bare = DriverTestAccess::VariantBytes(*original); + auto ring = std::make_shared(); + ring->userData.assign(256u, 1u); + ring->bindings.assign(4u, std::vector(128u, 2u)); + original->ringTemplate = ring; + const auto held = DriverTestAccess::VariantBytes(*original); + original->ringTemplate = nullptr; + Require(held >= bare + 256u * sizeof(std::uint32_t) + 4u * 128u * sizeof(std::uint32_t), "a retained ring template was left out of the dispatch-cache byte accounting"); + } std::vector> dependencies(original->linking->dependencies.begin(), original->linking->dependencies.end()); const auto linked = original->linking->linked; DriverTestAccess::Evict(); diff --git a/core/libs/prx/libSceAgcDriver/tests/RecycledShared.cpp b/core/libs/prx/libSceAgcDriver/tests/RecycledShared.cpp index 0cc0e1f760ad..081c26ab2700 100644 --- a/core/libs/prx/libSceAgcDriver/tests/RecycledShared.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/RecycledShared.cpp @@ -59,6 +59,16 @@ void fullPoolCyclesTests() { std::cout << "a full recycled pool replaces long-held objects with newer ones\n"; } +void zeroCapacityTests() { + RecycledShared> pool(0, 4); + for (std::uint32_t round = 0; round < 3; ++round) { + auto values = pool.Take([](std::vector& reused) { reused.clear(); }); + require(values != nullptr, "a zero-capacity pool returned no object"); + } + require(pool.Fresh() == 3 && pool.Reused() == 0, "a zero-capacity pool retained an object"); + std::cout << "a zero-capacity recycled pool hands out unretained objects\n"; +} + void stageWordsResetTests() { ShaderRecompiler::HeapStageWords words; words.userData = {1, 2, 3}; @@ -96,6 +106,7 @@ int main() { heldObjectsNotReusedTests(); releasedObjectsReusedTests(); fullPoolCyclesTests(); + zeroCapacityTests(); stageWordsResetTests(); std::cout << "recycled stage record tests passed\n"; return 0; From 40aacd65b2d0607ef784896876754de3bb0b7820 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 17 Nov 2026 05:57:54 +0530 Subject: [PATCH 261/269] fix(agc): return bindless heap slots on failure and track their recorder - BindlessHeap.cpp:407: a slot taken from the image or sampler pool goes back to its pool when encoding its descriptor throws. - BindlessHeap.cpp:1613: retiring slots remember the recorder whose batch assigned their serial and are reclaimed against that recorder's timeline. - BindlessHeap.cpp:1632: a destroyed recorder is detached from retiring slots, pool blocks and retired tables after its Sync(), so completion bookkeeping never dereferences it. - DescriptorHeapObjects.cpp:144: sampler records count creations per device and handle and are erased only on the last matching destruction. --- .../Graphics/include/BindlessHeap.hpp | 2 + .../Graphics/src/BindlessHeap.cpp | 70 ++++++++++++++----- .../Graphics/src/DescriptorHeapObjects.cpp | 18 +++-- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 3 + .../tests/BindlessHeapSlots.cpp | 22 ++++++ .../tests/DescriptorHeapObjectDevices.cpp | 9 +++ 6 files changed, 100 insertions(+), 24 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp index 310e1578927c..979794b46453 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BindlessHeap.hpp @@ -117,6 +117,7 @@ class BindlessHeap { static constexpr std::uint32_t SamplerKind = static_cast(ShaderRecompiler::RuntimeAbi::Binding::Samplers); void Submitted(Recorder& recorder, std::uint64_t serial); + void RecorderDestroyed(Recorder& recorder); bool TakeSlotPressure(); struct Counts { @@ -248,6 +249,7 @@ class BindlessHeap { std::uint32_t slot = 0; std::uint64_t serial = 0; bool sampler = false; + Recorder* recorder = nullptr; }; std::deque retiring; std::size_t retiringAssigned = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp index dfc634ab8bbf..88fc2ddf000f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BindlessHeap.cpp @@ -404,7 +404,12 @@ std::optional BindlessHeap::imageSlot(std::uint32_t kind, const H auto slot = imagePool.Take(); if (!slot && reclaimLocked(true)) slot = imagePool.Take(); if (!slot) return std::nullopt; - writeImageSlot(kind, *slot, view, layout); + try { + writeImageSlot(kind, *slot, view, layout); + } catch (...) { + imagePool.Free(*slot); + throw; + } claimSlotLocked(key, *slot).texture = texture; touchLocked(*slot); owner->heapSlotted.store(true, std::memory_order_release); @@ -603,26 +608,24 @@ void BindlessHeap::evictSamplersLocked(std::uint32_t idleSubmissions) { bool BindlessHeap::reclaimLocked(bool wait) { bool reclaimed = false; - while (!retiring.empty() && retiring.front().serial != 0u && submitter != nullptr) { - const auto serial = retiring.front().serial; - if (!submitter->WaitSerialFor(serial, 0u)) { - if (!wait || reclaimed || serial > submitter->Submissions()) break; - submitter->WaitSerial(serial); + while (!retiring.empty() && retiring.front().serial != 0u) { + const auto& front = retiring.front(); + if (front.recorder != nullptr && !front.recorder->WaitSerialFor(front.serial, 0u)) { + if (!wait || reclaimed || front.serial > front.recorder->Submissions()) break; + front.recorder->WaitSerial(front.serial); ++counts.evictionWaits; } - while (!retiring.empty() && retiring.front().serial != 0u && retiring.front().serial <= serial) { - const auto entry = retiring.front(); - retiring.pop_front(); - if (entry.sampler) { - samplerPool.free.push_back(entry.slot); - --retiringSamplers; - --samplerRetiringAssigned; - } else { - imagePool.free.push_back(entry.slot); - --retiringAssigned; - } - reclaimed = true; + const auto entry = front; + retiring.pop_front(); + if (entry.sampler) { + samplerPool.free.push_back(entry.slot); + --retiringSamplers; + --samplerRetiringAssigned; + } else { + imagePool.free.push_back(entry.slot); + --retiringAssigned; } + reclaimed = true; } if (reclaimed) noteReleasedLocked(); return reclaimed; @@ -704,7 +707,12 @@ std::optional BindlessHeap::samplerSlot(const std::shared_ptrHandle()); + try { + writeSamplerSlot(*slot, sampler->Handle()); + } catch (...) { + samplerPool.Free(*slot); + throw; + } const HeapSlotOwner* owner = sampler.get(); samplerSlots.emplace(owner, *slot); if (samplerOwners.size() <= *slot) { @@ -1616,6 +1624,7 @@ void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { if (refused && samplerPool.Unused() + retiringSamplers < 2u * SamplerSlotMargin) evictSamplersLocked(EvictIdleSubmissions); for (auto entry = retiring.rbegin(); entry != retiring.rend() && entry->serial == 0u; ++entry) { entry->serial = serial; + entry->recorder = &recorder; if (entry->sampler) ++samplerRetiringAssigned; else ++retiringAssigned; } @@ -1641,6 +1650,29 @@ void BindlessHeap::Submitted(Recorder& recorder, std::uint64_t serial) { trimPoolLocked(); } +void BindlessHeap::RecorderDestroyed(Recorder& recorder) { + { + std::lock_guard lock(mutex); + if (submitter == &recorder) submitter = nullptr; + for (auto& entry : retiring) { + if (entry.recorder == &recorder) entry.recorder = nullptr; + } + if (!retiring.empty()) reclaimLocked(false); + } + SpanScope scope(*this); + for (auto& block : poolBlocks) { + if (block.recorder != &recorder) continue; + block.recorder = nullptr; + block.serial = 0u; + } + for (auto& entry : retiredTables) { + if (entry.recorder != &recorder) continue; + entry.recorder = nullptr; + entry.serial = 0u; + } + reclaimTablesLocked(); +} + BindlessHeap::Counts& BindlessHeap::Counts::operator+=(const Counts& other) { encodes += other.encodes; encodedCopies += other.encodedCopies; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp index cfae058435a1..8844621d30db 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DescriptorHeapObjects.cpp @@ -60,6 +60,11 @@ struct ViewEntry { std::vector encoded; }; +struct SamplerEntry { + SamplerRecord record; + std::size_t creations = 0; +}; + using ViewKey = DeviceHandle; using SamplerKey = DeviceHandle; @@ -68,8 +73,8 @@ std::unordered_map>& views() { return map; } -std::unordered_map>& samplers() { - static auto& map = *new std::unordered_map>(); +std::unordered_map>& samplers() { + static auto& map = *new std::unordered_map>(); return map; } @@ -133,7 +138,9 @@ VKAPI_ATTR VkResult VKAPI_CALL createSampler(VkDevice device, const VkSamplerCre if (result == VK_SUCCESS) { auto record = recordOf(*info); std::lock_guard lock(recordsMutex()); - samplers()[{device, *sampler}] = std::move(record); + auto& entry = samplers()[{device, *sampler}]; + entry.record = std::move(record); + ++entry.creations; } return result; } @@ -141,7 +148,8 @@ VKAPI_ATTR VkResult VKAPI_CALL createSampler(VkDevice device, const VkSamplerCre VKAPI_ATTR void VKAPI_CALL destroySampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks* allocator) { { std::lock_guard lock(recordsMutex()); - samplers().erase({device, sampler}); + const auto found = samplers().find({device, sampler}); + if (found != samplers().end() && --found->second.creations == 0u) samplers().erase(found); } if (const auto real = realFunction(device, Hook::DestroySampler)) real(device, sampler, allocator); } @@ -233,7 +241,7 @@ std::optional FindSampler(VkDevice device, VkSampler sampler) { std::lock_guard lock(recordsMutex()); const auto found = samplers().find({device, sampler}); if (found == samplers().end()) return std::nullopt; - return found->second; + return found->second.record; } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 0917d83ac1fe..b7d8d6c84606 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -1442,6 +1442,9 @@ Recorder::~Recorder() { } catch (const std::exception& error) { std::fprintf(stderr, "[gpu] recorder teardown: %s\n", error.what()); } + if (DescriptorHeapEnabled()) { + if (auto* heap = BindlessHeap::Existing(context)) heap->RecorderDestroyed(*this); + } ForgetHtileMasks_nid_no_patch(id); progressWatcher.reset(); holdKept.clear(); diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 0d2b39136b73..251ae25f69b2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -313,6 +313,28 @@ bool dataPool(const Context& context) { const auto big = heap.AllocateTable(spans, AgcDriver::Graphics::BindlessHeap::TableBlockBytes, large); require(big.has_value() && big->words.size() == AgcDriver::Graphics::BindlessHeap::TableBlockBytes && heap.DataLocation(large.address).first != VK_NULL_HANDLE, "a table larger than a shared block gets a block of its own"); } + { + BindlessHeap heap(context); + for (int index = 0; index < 3; ++index) static_cast(heap.Allocate(blockWords - 64u)); + const BindlessHeap::SpanScope spans(heap); + BindlessHeap::TableMark table; + static_cast(heap.AllocateTable(spans, 40u, table)); + const auto address = table.address; + heap.RetireTable(spans, table); + { + Recorder gone(context, true); + heap.Submitted(gone, gone.Submissions() + (1ull << 40u)); + const auto made = heap.Statistics().poolBlocksMade; + static_cast(heap.Allocate(blockWords - 64u)); + require(heap.Statistics().poolBlocksRecycled == 0u && heap.Statistics().poolBlocksMade == made + 1u, "a block a live recorder's batch still reads is not reused"); + heap.RecorderDestroyed(gone); + } + const auto made = heap.Statistics().poolBlocksMade; + static_cast(heap.Allocate(blockWords - 64u)); + require(heap.Statistics().poolBlocksRecycled == 1u && heap.Statistics().poolBlocksMade == made, "a destroyed recorder's blocks are released without dereferencing it"); + BindlessHeap::TableMark after; + require(heap.AllocateTable(spans, 40u, after).has_value() && after.address == address, "a destroyed recorder's retired table is reusable without dereferencing it"); + } { BindlessHeap heap(context); const BindlessHeap::SpanScope spans(heap); diff --git a/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp b/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp index fbb2897d8365..cca53e9b51c3 100644 --- a/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp @@ -116,5 +116,14 @@ int main() { destroySampler(first.device, sampler, nullptr); Require(first.destroySamplers == 1 && second.destroySamplers == 0, "a sampler destroy reaches the owning device's function"); Require(!FindSampler(first.device, sampler).has_value() && FindSampler(second.device, sampler).has_value(), "destroying a sampler on one device keeps the other's record"); + destroySampler(second.device, sampler, nullptr); + Require(!FindSampler(second.device, sampler).has_value(), "the second device's sampler record is gone"); + VkSampler twin = VK_NULL_HANDLE; + samplerInfo.maxLod = 7.0f; + Require(createSampler(second.device, &samplerInfo, nullptr, &twin) == VK_SUCCESS && createSampler(second.device, &samplerInfo, nullptr, &twin) == VK_SUCCESS, "a device creates one sampler handle twice"); + destroySampler(second.device, twin, nullptr); + Require(FindSampler(second.device, twin).has_value() && FindSampler(second.device, twin)->info.maxLod == 7.0f, "destroying one of two creations of a sampler handle keeps its record"); + destroySampler(second.device, twin, nullptr); + Require(!FindSampler(second.device, twin).has_value(), "destroying the last creation of a sampler handle drops its record"); std::puts("descriptor heap objects per device: ok"); } From 2617675900dbca3d2be824138e6e84ce3ad9ba36 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 17 Nov 2026 05:57:54 +0530 Subject: [PATCH 262/269] fix(agc): keep heap draw resources consistent across stages - Draw.cpp:2402: the held-space guard is released only after RefreshHeapStage succeeds, so a failed refresh no longer leaves guest allocations pinned. - ShaderResources.cpp:2494: heap presence is decided across all shaders before any binding is processed, matching the set-layout producer. - ShaderResources.cpp:7617: a heap stage refuses (cache miss, rebuild) a moved buffer that a conventional binding shares and that is not read in place, instead of leaving that descriptor on the old allocation. - ShaderResources.cpp:8134: heap image table resolution selects the array view for entries recorded in arrayViewTextures. - ShaderValidation.cpp:715: a matched image table declaration is recorded in declared, so it is not counted again as an undeclared addressed binding. --- core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp | 2 +- .../prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp | 7 +++++-- .../prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp | 1 + 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 05946379ea35..7acbb0eb8d7b 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -2396,10 +2396,10 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat if (moved.has_value()) { if (trimKey) CheckBufferAliases(shaders, state.color, draw.indexAddress, indexBytes); if (counted && verifyAddressDrawReuse()) verifyServedSpace(context, state, draw, shaders, snapshots, indexBytes, *cached); - static_cast(heldSpace.release()); resolved.resources = std::move(cached); resolved.moved = std::move(*moved); if (resolved.resources->HeapStage()) resolved.resources->RefreshHeapStage(shaders); + static_cast(heldSpace.release()); outcome.addressBased = resolved.resources->HoldsLease(); outcome.kind = KindTemplateHit; countCache(&DrawProfile::cacheHits); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 75126b80df07..0b54e4f87276 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -2466,6 +2466,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons allocations.reserve(plannedAllocations); std::vector occupied; occupied.reserve(plannedBindings); + heapStage = AnyHeapShader(shaders); for (const auto& shader : shaders) { Require(shader.program != nullptr, "missing compiled shader"); ShaderRecompiler::RuntimeAbi::RequireVersion(shader.program->runtimeAbiVersion); @@ -7314,6 +7315,8 @@ std::optional> ShaderResources::MovedR const auto bytes = static_cast(GuestBufferMemory::ViewBytes(size, item.adjustment)); const bool behind = recorder.PendingWriteOverlaps(begin, bytes); const bool inPlace = (usesBda && heapStage) || (behind && heapShader && addressedBuffers); + const auto sharesClassic = [&] { return std::any_of(bindings.begin(), bindings.end(), [&](const Binding& other) { return !(other.heap && other.addressed) && std::find(other.allocations.begin(), other.allocations.end(), index) != other.allocations.end(); }); }; + if (heapStage && !inPlace && sharesClassic()) return refuse(MoveRefusal::SharedBinding); if (!inPlace && bytes > maxDrawSnapshotBytes - movedBytes) return refuse(MoveRefusal::Limit); if (!GuestMemory::Accessible(reinterpret_cast(begin), bytes)) return refuse(MoveRefusal::Inaccessible); if (guestMemory.WritesOverlap(begin, bytes) || PendingStorageOverlaps(begin, bytes, nullptr) || AnyShadowedOverlaps(begin, bytes)) return refuse(MoveRefusal::Overlap); @@ -7337,7 +7340,7 @@ std::optional> ShaderResources::MovedR VkDeviceAddress handle = 0; found = guestMemory.TryDescriptor(address, static_cast(size), adjustment, nullptr, &handle).has_value() && handle != 0; } - const bool classic = std::any_of(bindings.begin(), bindings.end(), [&](const Binding& other) { return !(other.heap && other.addressed) && std::find(other.allocations.begin(), other.allocations.end(), index) != other.allocations.end(); }); + const bool classic = sharesClassic(); if (!found) return refuse(MoveRefusal::NotImported); if (adjustment != item.adjustment) return refuse(MoveRefusal::Alignment); if (classic) return refuse(MoveRefusal::SharedBinding); @@ -8131,7 +8134,7 @@ void ShaderResources::buildHeapTableMap(std::vector& map, Bindles map.push_back(sampledAbsent); continue; } - const auto view = textureFirstLayer[index] ? textures[index]->FirstLayerView() : textures[index]->View(); + const auto view = textureFirstLayer[index] ? textures[index]->FirstLayerView() : arrayViewTextures.contains(index) ? textures[index]->ArrayView() : textures[index]->View(); map.push_back(image(takenSlot(heap.TextureSlot(Abi::FirstImageBinding, textures[index].get(), view, textures[index]->Layout()), "the global image heap is full"))); } const auto appendStorageSlots = [&](std::uint32_t kind, std::uint32_t absent, const char* full, const auto& wanted, const auto& viewOf) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index 6988f7adb150..d2e2ec6d35a8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -631,6 +631,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi Require(binding->kind == ShaderRecompiler::DescriptorKind::Sampler || binding->kind == ShaderRecompiler::DescriptorKind::SampledImage || binding->kind == ShaderRecompiler::DescriptorKind::StorageImage, "SPIR-V descriptor type disagrees with recompiler binding metadata"); if (binding->role == ShaderRecompiler::DescriptorRole::ImageTable || binding->role == ShaderRecompiler::DescriptorRole::ImageStorageTable || binding->role == ShaderRecompiler::DescriptorRole::SamplerTable) { Require(type.size() == 3 && (type[0] & 0xffffu) == spv::OpTypeRuntimeArray, "image table must be declared as a runtime descriptor array"); + declared.insert(&*binding); continue; } Require(type.size() == 4 && (type[0] & 0xffffu) == spv::OpTypeArray, "typed heap must be declared as a descriptor array"); From dab8ac6ebb3c276950679e7e3e5b94e904fc1643 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 17 Nov 2026 05:57:54 +0530 Subject: [PATCH 263/269] fix(agc): reject a heap limit hidden by a later option in shader replay ShaderReplay.cpp:114: the --no-gpu-heap precheck remembers the first nonzero --heap-data-uniform-dwords instead of only the last, so a later zero cannot hide the conflict of an earlier request. --- core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake | 1 + core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake b/core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake index dbf973729f4e..4652362aa1d6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderReplayTool.cmake @@ -118,6 +118,7 @@ expect_usage_error("--gpu-heap then --no-gpu-heap" "--gpu-heap and --no-gpu-heap expect_usage_error("--no-gpu-heap then --gpu-heap" "--gpu-heap and --no-gpu-heap conflict" --no-gpu-heap --gpu-heap "${CAPTURE}/lds.req") expect_usage_error("--no-gpu-heap with a limit" "--no-gpu-heap conflicts with --heap-data-uniform-dwords 4096" --no-gpu-heap --heap-data-uniform-dwords 4096 "${CAPTURE}/lds.req") expect_usage_error("a limit then --no-gpu-heap" "--no-gpu-heap conflicts with --heap-data-uniform-dwords 4096" --heap-data-uniform-dwords 4096 --no-gpu-heap "${CAPTURE}/lds.req") +expect_usage_error("a limit hidden by a later zero" "--no-gpu-heap conflicts with --heap-data-uniform-dwords 4096" --heap-data-uniform-dwords 4096 --no-gpu-heap --heap-data-uniform-dwords 0 "${CAPTURE}/lds.req") expect_usage_error("a missing limit" "needs an unsigned 32-bit number" --heap-data-uniform-dwords) expect_usage_error("an overflowing limit" "needs an unsigned 32-bit number" --heap-data-uniform-dwords 99999999999 "${CAPTURE}/lds.req") expect_usage_error("a negative limit" "needs an unsigned 32-bit number" --heap-data-uniform-dwords -1 "${CAPTURE}/lds.req") diff --git a/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp b/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp index c999243d9a8d..fc96f7439eb6 100644 --- a/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp +++ b/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp @@ -111,7 +111,10 @@ bool HeapFlagsConflict(int argc, char** argv) { const std::string argument = argv[i]; if (argument == "--gpu-heap") gpuHeap = true; else if (argument == "--no-gpu-heap") noGpuHeap = true; - else if (argument == "--heap-data-uniform-dwords") ParseHeapDataUniformDwords(i, argc, argv, dwords); + else if (argument == "--heap-data-uniform-dwords") { + std::uint32_t value = 0; + if (ParseHeapDataUniformDwords(i, argc, argv, value) && value != 0u && dwords == 0u) dwords = value; + } } if (gpuHeap && noGpuHeap) { std::fprintf(stderr, "--gpu-heap and --no-gpu-heap conflict\n"); From 8ace110d3d0e8805a493292baee06174ed4ce7f9 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 17 Nov 2026 05:52:27 +0530 Subject: [PATCH 264/269] fix(shader): fail sampler heap emission when dynamic indexing is unavailable SpirvDescriptors.cpp:289 (D2): the sampler heap emitted SampledImageArrayDynamicIndexing without checking the device, so a device lacking it failed later at pipeline creation. It now goes through RequireDynamicIndexing like the image heaps and reports an emission error naming the sampler binding. Test: HeapTableStageReuse compiles a table image with a heap sampler on a target stripped of the capability and requires the sampler heap error; it fails without the fix (no error at emission). --- .../tests/execution/HeapTableStageReuse.cpp | 26 +++++++++++++++++-- .../src/SpirvMemory/SpirvDescriptors.cpp | 2 +- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp index a12492ed5dfb..fdfb11756340 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapTableStageReuse.cpp @@ -10,6 +10,7 @@ #include "RuntimeAbi.hpp" #include "ImageTableAbi.hpp" #include "VulkanTestDevice.hpp" +#include #ifdef _WIN32 #ifndef NOMINMAX #define NOMINMAX @@ -31,6 +32,7 @@ #include #include #include +#include #include #include @@ -127,7 +129,7 @@ void Prepare(const GuestBlock& block, const GuestBlock& surfaces) { AgcDriver::GuestMemory::CollectWritesUncached(surfaces.At(0), SurfaceBlockBytes); } -ShaderRecompiler::RecompileResult Compile(const AgcDriver::VulkanDevice& device, const GuestBlock& block) { +ShaderRecompiler::RecompileResult Compile(const AgcDriver::VulkanDevice& device, const GuestBlock& block, std::optional withoutCapability = std::nullopt) { const auto srt = block.At(SrtOffset); const std::array userData{static_cast(srt), static_cast(srt >> 32u)}; const std::span code(block.Words(0), Code.size()); @@ -137,12 +139,17 @@ ShaderRecompiler::RecompileResult Compile(const AgcDriver::VulkanDevice& device, {block.At(HeapOffset), std::as_bytes(std::span(block.Words(HeapOffset), static_cast(Textures) * Stride / 4u))}, }}; const ShaderRecompiler::ShaderComputeStageInfo compute{{Lanes, 1, 1}, 0u, {false, false, false}, false, 1}; + auto target = device.ComputeTarget(Lanes); + std::vector capabilities(target.supportedCapabilities.begin(), target.supportedCapabilities.end()); + if (withoutCapability) capabilities.erase(std::remove(capabilities.begin(), capabilities.end(), *withoutCapability), capabilities.end()); + target.supportedCapabilities = capabilities; ShaderRecompiler::RecompileRequest request{ {ShaderStage::Compute, block.At(0), code, 0, {}}, {Lanes, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.ComputeTarget(Lanes), + target, {0, 0, 0, 128} }; + if (withoutCapability) request.useCache = false; return ShaderRecompiler::Recompile(request); } @@ -232,6 +239,20 @@ void RefreshAfterSlotReleased(const AgcDriver::VulkanDevice& device, const Guest std::puts("the heap table map was rebuilt after its texture's slot was released"); } +void SamplerHeapNeedsDynamicIndexing(const AgcDriver::VulkanDevice& device, const GuestBlock& block) { + const auto supported = Compile(device, block); + RequireHeapTable(supported); + std::string failure; + try { + static_cast(Compile(device, block, spv::CapabilitySampledImageArrayDynamicIndexing)); + } catch (const std::runtime_error& error) { + failure = error.what(); + } + Require(failure.find("the sampler heap needs sampler array dynamic indexing") != std::string::npos && failure.find("binding_kind=57") != std::string::npos, + "heap table stage reuse: a device without sampled image array dynamic indexing did not fail naming the sampler heap: " + failure); + std::puts("a sampler heap on a device without dynamic indexing failed at emission"); +} + } int main() { @@ -246,6 +267,7 @@ int main() { RefreshAfterOriginalDestroyed(*device, block, false); RefreshAfterOriginalDestroyed(*device, block, true); RefreshAfterSlotReleased(*device, block); + SamplerHeapNeedsDynamicIndexing(*device, block); std::puts("heap table stage reuse tests passed"); return 0; } catch (const std::exception& error) { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp index b3eb3f147f4b..bed4899f2225 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvDescriptors.cpp @@ -286,7 +286,7 @@ std::uint32_t LoadSamplerDescriptor(SpirvEmitterState& state, std::uint32_t samp pointer = variable; } else if (state.gpuResolvedImages) { if (state.samplerVariable == 0) ExitDescriptorBindingFailure(state, DescriptorBindingKind::Samplers, sampler, "sampler descriptor array was not emitted"); - state.module.EmitCapability(spv::CapabilitySampledImageArrayDynamicIndexing); + RequireDynamicIndexing(state, spv::CapabilitySampledImageArrayDynamicIndexing, DescriptorBindingKind::Samplers, sampler, "the sampler heap needs sampler array dynamic indexing, which the device lacks"); const auto slot = LoadHeapSlotWord(state, state.program.Metadata().bindings.SamplerSlotDword() + arrayIndex); pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, pointerType, pointer, state.samplerVariable, slot); From d8feba7a2dea61b62f37af3652ceaf3e3aa6640e Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 17 Nov 2026 05:52:27 +0530 Subject: [PATCH 265/269] test(agc): keep image table cache bounds registrations in their own fragment agc_shader_memory_tests.cmake:67 (D11): the agc_driver_image_table_atomics, agc_driver_image_table_atomics_gpu_heap and agc_driver_image_table_store_gpu_heap registrations run agc_driver_image_table_cache_bounds_tests, so they move to agc_driver_image_table_cache_bounds_tests.cmake with their arguments, environment and timeout unchanged. --- .../cmake/agc_driver_image_table_cache_bounds_tests.cmake | 6 ++++++ .../tests/cmake/agc_shader_memory_tests.cmake | 6 ------ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_cache_bounds_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_cache_bounds_tests.cmake index a3bf9bfb8051..f84b019c2489 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_cache_bounds_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_image_table_cache_bounds_tests.cmake @@ -1,3 +1,9 @@ if(BUILD_TESTING) agc_add_gpu_heap_test(agc_driver_image_table_cache_bounds) + agc_add_env_test(agc_driver_image_table_atomics agc_driver_image_table_cache_bounds_tests + ARGS --atomic-table ENV ANYPS5_NO_SHADER_CACHE=1 TIMEOUT 60) + agc_add_env_test(agc_driver_image_table_atomics_gpu_heap agc_driver_image_table_cache_bounds_tests + ARGS --atomic-table ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 TIMEOUT 60) + agc_add_env_test(agc_driver_image_table_store_gpu_heap agc_driver_image_table_cache_bounds_tests + ARGS --store-table ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 TIMEOUT 60) endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake index 1b3ae7619dc2..0522f9da79f9 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_shader_memory_tests.cmake @@ -64,12 +64,6 @@ if(BUILD_TESTING) set_tests_properties(agc_shader_table_snapshot_reuse_unmasked PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_MASKED_RESULT_MEMO=1" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") add_test(NAME agc_driver_image_table_vouched_lookups COMMAND agc_driver_image_table_cache_bounds_tests --vouched-lookups) set_tests_properties(agc_driver_image_table_vouched_lookups PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_WRITE_WATCH_IMPORTS=watch;APS5_NO_SPANNED_WAVE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) - agc_add_env_test(agc_driver_image_table_atomics agc_driver_image_table_cache_bounds_tests - ARGS --atomic-table ENV ANYPS5_NO_SHADER_CACHE=1 TIMEOUT 60) - agc_add_env_test(agc_driver_image_table_atomics_gpu_heap agc_driver_image_table_cache_bounds_tests - ARGS --atomic-table ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 TIMEOUT 60) - agc_add_env_test(agc_driver_image_table_store_gpu_heap agc_driver_image_table_cache_bounds_tests - ARGS --store-table ENV ANYPS5_NO_SHADER_CACHE=1 APS5_GPU_HEAP=1 APS5_VERIFY_GPU_HEAP=1 TIMEOUT 60) add_test(NAME agc_driver_image_table_vouch_queued_draws COMMAND agc_driver_image_table_cache_bounds_tests --queued-draws) set_tests_properties(agc_driver_image_table_vouch_queued_draws PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60) if(WIN32) From 5b92ffd965862ffe1763cdca107cd3bb99599f1b Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 17 Nov 2026 05:52:27 +0530 Subject: [PATCH 266/269] docs(user): say a GPU heap stage that cannot be mapped fails USAGE.md:583 (D17): the GPU descriptor heap section did not say that heap mode has no per-draw fallback. It now states that an ineligible or unmappable stage fails the draw or dispatch and that running without APS5_GPU_HEAP is the workaround. --- docs/user/USAGE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user/USAGE.md b/docs/user/USAGE.md index 20cdaeaaa78c..0a520156df28 100644 --- a/docs/user/USAGE.md +++ b/docs/user/USAGE.md @@ -580,7 +580,7 @@ Besides the recompiled shaders, the shader cache directory holds `pipelines.jour ### GPU descriptor heap -`APS5_GPU_HEAP=1` (off by default) binds the textures and samplers of most draws through one table the GPU indexes, instead of building them again for each draw. It needs a GPU driver with `VK_EXT_descriptor_heap`; without it the switch does nothing. Use it with `APS5_DRAW_PIPELINE=1` and the switches listed there. The first run with the switch compiles its own variant of each shader, so expect the same stutter as with an empty shader cache once. Wrong or missing textures or flicker that go away without the switch are bugs. `APS5_VERIFY_GPU_HEAP=1` checks the table against the bound textures, and builds some draws the old way and compares them; it prints `[heap-slots]` and `[gpu-heap]` lines (a slot holding another texture or a differing draw is a bug). +`APS5_GPU_HEAP=1` (off by default) binds the textures and samplers of most draws through one table the GPU indexes, instead of building them again for each draw. It needs a GPU driver with `VK_EXT_descriptor_heap`; without it the switch does nothing. Use it with `APS5_DRAW_PIPELINE=1` and the switches listed there. The first run with the switch compiles its own variant of each shader, so expect the same stutter as with an empty shader cache once. Wrong or missing textures or flicker that go away without the switch are bugs. `APS5_VERIFY_GPU_HEAP=1` checks the table against the bound textures, and builds some draws the old way and compares them; it prints `[heap-slots]` and `[gpu-heap]` lines (a slot holding another texture or a differing draw is a bug). With the switch on there is no per-draw fallback: a stage the heap cannot map (for example one that needs more image slots than the heap holds, or one whose plan is ineligible) fails the draw or dispatch instead of binding its resources the old way. If a title stops with such an error, run it without `APS5_GPU_HEAP`. ### Texture cache budget From 86f9fbc3836fc5ebf0dcce3b75de51a8b3d6d13c Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 17 Nov 2026 05:52:27 +0530 Subject: [PATCH 267/269] test(agc): fix review-2 test findings for the GPU heap tests BindlessHeapSlots.cpp:52 (D3): the texture fixture now allocates memory and binds it to the image before creating the view, and frees it with the image. DepthFastClearSubmit.cpp:368 (D4): both recreated recorders take device.TimelineSemaphores() instead of a hardcoded true. AddressDrawSpaceReuse.cpp:872 (D7): the pending-fill assertion expects Reused when HeapStages || inPlace; with APS5_NO_MOVED_BUFFERS_IN_PLACE=1 and --heap-stages the old expression fails. DescriptorHeapObjectDevices.cpp:63 (D8): each fake device now has its own callbacks that abort when called for another device, so a hook cache shared across devices fails; with the per-device map replaced by one slot the test aborts. ImageAtomics.cpp (D9): the contended add and umax cases run on device.ComputeTarget(waveSize) and check the stage's mode, and one Target() case keeps the plain path covered. DrawRecipeMovedBuffer.cpp:2 (D12): the heap variants skip (77) when the device lacks descriptor heaps; the _gpu_heap_unverified registration has no APS5_VERIFY_GPU_HEAP, so it could pass through descriptor sets. FinisherDispatchOrder.cpp:156 (D13): both drains are checked in each pass before the next pass overwrites them. HeapEmbeddedSampler.cpp:115 (D14): the embedded sampler count is compared with the parsed cap, so a nonzero cap passes and zero still requires no embedding. ScratchPool.cpp:268 (D15): the pipeline check is guarded by DescriptorHeapEnabled() instead of the requested heap mode. --- .../tests/BindlessHeapSlots.cpp | 17 +++++- .../tests/DescriptorHeapObjectDevices.cpp | 55 +++++++++++-------- .../tests/execution/AddressDrawSpaceReuse.cpp | 3 +- .../tests/execution/DepthFastClearSubmit.cpp | 4 +- .../tests/execution/DrawRecipeMovedBuffer.cpp | 1 + .../tests/execution/FinisherDispatchOrder.cpp | 8 +-- .../tests/execution/HeapEmbeddedSampler.cpp | 9 ++- .../tests/execution/ImageAtomics.cpp | 30 ++++++---- .../tests/execution/ScratchPool.cpp | 2 +- 9 files changed, 82 insertions(+), 47 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp index 251ae25f69b2..43641a33e2ac 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BindlessHeapSlots.cpp @@ -47,16 +47,29 @@ std::shared_ptr fakeTexture(const Context& context, std::size_t) { info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VkImage image = VK_NULL_HANDLE; require(context.Function("vkCreateImage")(context.device, &info, nullptr, &image) == VK_SUCCESS, "a texture fixture image is created"); + VkMemoryRequirements requirements{}; + context.Function("vkGetImageMemoryRequirements")(context.device, image, &requirements); + VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + allocation.allocationSize = requirements.size; + allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VkDeviceMemory memory = VK_NULL_HANDLE; + const auto release = [context, image, &memory] { + context.Function("vkDestroyImage")(context.device, image, nullptr); + if (memory != VK_NULL_HANDLE) context.Function("vkFreeMemory")(context.device, memory, nullptr); + }; std::unique_ptr texture; try { + require(context.Function("vkAllocateMemory")(context.device, &allocation, nullptr, &memory) == VK_SUCCESS, "a texture fixture image gets memory"); + require(context.Function("vkBindImageMemory")(context.device, image, memory, 0u) == VK_SUCCESS, "a texture fixture image binds its memory"); texture = std::make_unique(context, image, info.format, VK_IMAGE_ASPECT_COLOR_BIT, VkComponentMapping{}); } catch (...) { - context.Function("vkDestroyImage")(context.device, image, nullptr); + release(); throw; } - return std::shared_ptr(texture.release(), [context, image](Texture* released) { + return std::shared_ptr(texture.release(), [context, image, memory](Texture* released) { delete released; context.Function("vkDestroyImage")(context.device, image, nullptr); + context.Function("vkFreeMemory")(context.device, memory, nullptr); }); } diff --git a/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp b/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp index cca53e9b51c3..9e358dcd9d1d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/DescriptorHeapObjectDevices.cpp @@ -23,63 +23,72 @@ struct Fake { VkDevice lastDevice = VK_NULL_HANDLE; }; -Fake first{reinterpret_cast(0x1000)}; -Fake second{reinterpret_cast(0x2000)}; - -Fake& owner(VkDevice device) { - return device == first.device ? first : second; -} +Fake devices[2]{Fake{reinterpret_cast(0x1000)}, Fake{reinterpret_cast(0x2000)}}; +Fake& first = devices[0]; +Fake& second = devices[1]; const std::uint64_t SharedView = 0x77; +template +Fake& expect(VkDevice device) { + Require(device == devices[Index].device, "a call reached another device's function"); + return devices[Index]; +} + +template VKAPI_ATTR VkResult VKAPI_CALL fakeCreateView(VkDevice device, const VkImageViewCreateInfo*, const VkAllocationCallbacks*, VkImageView* view) { - auto& fake = owner(device); + auto& fake = expect(device); ++fake.createViews; fake.lastDevice = device; *view = reinterpret_cast(SharedView); return VK_SUCCESS; } +template VKAPI_ATTR void VKAPI_CALL fakeDestroyView(VkDevice device, VkImageView, const VkAllocationCallbacks*) { - auto& fake = owner(device); + auto& fake = expect(device); ++fake.destroyViews; fake.lastDevice = device; } +template VKAPI_ATTR VkResult VKAPI_CALL fakeCreateSampler(VkDevice device, const VkSamplerCreateInfo*, const VkAllocationCallbacks*, VkSampler* sampler) { - auto& fake = owner(device); + auto& fake = expect(device); ++fake.createSamplers; fake.lastDevice = device; *sampler = reinterpret_cast(SharedView); return VK_SUCCESS; } +template VKAPI_ATTR void VKAPI_CALL fakeDestroySampler(VkDevice device, VkSampler, const VkAllocationCallbacks*) { - auto& fake = owner(device); + auto& fake = expect(device); ++fake.destroySamplers; fake.lastDevice = device; } -VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL fakeProc(VkDevice, const char* name) { - if (std::strcmp(name, "vkCreateImageView") == 0) return reinterpret_cast(&fakeCreateView); - if (std::strcmp(name, "vkDestroyImageView") == 0) return reinterpret_cast(&fakeDestroyView); - if (std::strcmp(name, "vkCreateSampler") == 0) return reinterpret_cast(&fakeCreateSampler); - if (std::strcmp(name, "vkDestroySampler") == 0) return reinterpret_cast(&fakeDestroySampler); +template +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL fakeProc(VkDevice device, const char* name) { + Require(device == devices[Index].device, "a function was looked up through another device's loader"); + if (std::strcmp(name, "vkCreateImageView") == 0) return reinterpret_cast(&fakeCreateView); + if (std::strcmp(name, "vkDestroyImageView") == 0) return reinterpret_cast(&fakeDestroyView); + if (std::strcmp(name, "vkCreateSampler") == 0) return reinterpret_cast(&fakeCreateSampler); + if (std::strcmp(name, "vkDestroySampler") == 0) return reinterpret_cast(&fakeDestroySampler); return nullptr; } } int main() { - const auto createView = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc, "vkCreateImageView")); - const auto destroyView = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc, "vkDestroyImageView")); - const auto createSampler = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc, "vkCreateSampler")); - const auto destroySampler = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc, "vkDestroySampler")); + const auto createView = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc<0>, "vkCreateImageView")); + const auto destroyView = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc<0>, "vkDestroyImageView")); + const auto createSampler = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc<0>, "vkCreateSampler")); + const auto destroySampler = reinterpret_cast(DescriptorHeapObjectFunction(first.device, fakeProc<0>, "vkDestroySampler")); Require(createView != nullptr && destroyView != nullptr && createSampler != nullptr && destroySampler != nullptr, "the hooks resolve"); - Require(DescriptorHeapObjectFunction(second.device, fakeProc, "vkCreateImageView") == reinterpret_cast(createView), "the second device resolves the same hook"); - DescriptorHeapObjectFunction(second.device, fakeProc, "vkDestroyImageView"); - DescriptorHeapObjectFunction(second.device, fakeProc, "vkCreateSampler"); - DescriptorHeapObjectFunction(second.device, fakeProc, "vkDestroySampler"); + Require(DescriptorHeapObjectFunction(second.device, fakeProc<1>, "vkCreateImageView") == reinterpret_cast(createView), "the second device resolves the same hook"); + DescriptorHeapObjectFunction(second.device, fakeProc<1>, "vkDestroyImageView"); + DescriptorHeapObjectFunction(second.device, fakeProc<1>, "vkCreateSampler"); + DescriptorHeapObjectFunction(second.device, fakeProc<1>, "vkDestroySampler"); VkImageViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; viewInfo.format = VK_FORMAT_R8G8B8A8_UNORM; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp index 81227fbab8c0..d24b2f75e17e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/AddressDrawSpaceReuse.cpp @@ -869,7 +869,8 @@ void RingRefusals(Scene& scene) { } const auto color = scene.Color(); Require(color == 110, "address draw space reuse: the draw whose moved vertex buffer a pending fill completes read " + std::to_string(color) + " instead of 110: it did not see the vertex the GPU wrote"); - Require(outcomes[inPlace ? AddressDrawReuse::Reused : AddressDrawReuse::MovedBuffer] == 1 && outcomes.Total() == 1, "address draw space reuse: a draw whose moved vertex buffer a pending fill completes counted " + outcomes.Text() + (inPlace ? ", expected one reuse with the buffer read in place" : ", expected one refusal for a moved GuestBuffers element")); + const bool reused = HeapStages || inPlace; + Require(outcomes[reused ? AddressDrawReuse::Reused : AddressDrawReuse::MovedBuffer] == 1 && outcomes.Total() == 1, "address draw space reuse: a draw whose moved vertex buffer a pending fill completes counted " + outcomes.Text() + (reused ? ", expected one reuse with the buffer read in place" : ", expected one refusal for a moved GuestBuffers element")); } scene.Fetch(0); scene.cachedVertex = false; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp index 781190ede731..102d215b0df0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthFastClearSubmit.cpp @@ -365,14 +365,14 @@ void RecreatedRecorderReadsHtile(AgcDriver::VulkanDevice& device, bool clearSurf auto& htile = NewBlock(); const DepthTarget target{NewBlock().Address(), 0, {64, 32}, VK_FORMAT_D32_SFLOAT, 1.0f, 0, htile.Address(), false}; std::optional recorder; - recorder.emplace(context, true); + recorder.emplace(context, device.TimelineSemaphores()); const auto* address = &*recorder; RecordHtileWords(context, *recorder, htile, 0xf0u); const auto note = recorder->NewestWriteNote(htile.Address(), HtileBytes); NoteHtileMaskOnGpu(context, {htile.Address(), HtileBytes, 0x3f0u, 0u}); recorder.reset(); if (clearSurfaces) ClearDepthSurfaces(context.device); - recorder.emplace(context, true); + recorder.emplace(context, device.TimelineSemaphores()); Require(&*recorder == address, "the replacement recorder did not reuse the original storage"); RecordHtileWords(context, *recorder, htile, 0xfu); Require(recorder->NewestWriteNote(htile.Address(), HtileBytes) == note, "the replacement recorder did not reuse the original note"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp index c1d849dd5388..8601c576cc28 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawRecipeMovedBuffer.cpp @@ -360,6 +360,7 @@ int main() { { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; + if (AgcDriver::Graphics::GpuHeapEnabled() && SkipWithoutDescriptorHeap()) return VulkanTestSkipped; } { GuestAllocations::Mutation mutation; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp index 8378eaa64787..8a2430e93be1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/FinisherDispatchOrder.cpp @@ -136,7 +136,6 @@ int main() { Registered(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1); PixelConstant[0] = 0.25f; for (auto& output : Outputs) output.fill(-1.0f); - std::string drains; constexpr std::array Constants{0.25f, 0.125f}; unsigned expected = 0; for (std::uint32_t pass = 0; pass < 2; ++pass) { @@ -153,7 +152,10 @@ int main() { Packet packet{commands.data(), static_cast(commands.size()), 0, {}}; Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed"); AgcDriverWaitIdle_nid_postfix(); - drains = DrawFinisher::DrainText(); + const auto drains = DrawFinisher::DrainText(); + const auto passLabel = "pass " + std::to_string(pass) + ": "; + if (finisher) Require(drains.find(" 0x15 x") == std::string::npos, passLabel + "a pipelined dispatch after a draw handed to the finisher drained the finisher:" + drains); + if (finisher) Require(drains.find(" 0x46 x") == std::string::npos, passLabel + "a sample dump after a draw handed to the finisher drained the finisher:" + drains); AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast(Outputs.data()), sizeof(Outputs)); for (std::uint32_t round = 0; round < Rounds; ++round) { const auto where = "pass " + std::to_string(pass) + " round " + std::to_string(round); @@ -166,8 +168,6 @@ int main() { unsigned brightest = 0; for (const auto value : ColorMemory) brightest = std::max(brightest, static_cast(std::to_integer(value))); Require(brightest + 2 >= expected && brightest <= expected + 2, "the draws around the dispatches wrote " + std::to_string(brightest) + ", expected " + std::to_string(expected)); - if (finisher) Require(drains.find(" 0x15 x") == std::string::npos, "a pipelined dispatch after a draw handed to the finisher drained the finisher:" + drains); - if (finisher) Require(drains.find(" 0x46 x") == std::string::npos, "a sample dump after a draw handed to the finisher drained the finisher:" + drains); AgcDriverShutdown_nid_postfix(); std::cout << "dispatches and sample dumps after finisher draws " << (finisher ? "queued through the finisher" : "run in order") << "\n"; return 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp index 201e376efe21..19ea2cfb3863 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/HeapEmbeddedSampler.cpp @@ -112,11 +112,14 @@ int main() { RequireSampled(Outputs[2].data(), SampleTexel, "the wrapping constant sampler's texel", heap); RequireSampled(Outputs[3].data(), SampleTexel, "the mirroring constant sampler's texel", heap); if (embedding) { - const bool capped = std::getenv("APS5_EMBEDDED_SAMPLER_CAP") != nullptr; + const char* capText = std::getenv("APS5_EMBEDDED_SAMPLER_CAP"); + const bool capped = capText != nullptr; + const auto cap = capped ? static_cast(std::strtoul(capText, nullptr, 10)) : ~0u; const auto* heapObject = AgcDriver::Graphics::BindlessHeap::Existing(device->graphicsContext()); Require(heapObject != nullptr, "the heap dispatch left no descriptor heap"); - Require(capped ? heapObject->EmbeddedSamplerCount() == 0u : heapObject->EmbeddedSamplerCount() > embeddedBefore, - capped ? "a capped device embedded a sampler past its limit" : "the pipeline did not embed the constant sampler"); + const auto count = heapObject->EmbeddedSamplerCount(); + Require(count <= cap, "a capped device embedded a sampler past its limit"); + Require(cap == 0u || count > embeddedBefore, "the pipeline did not embed the constant sampler"); } const bool capped = std::getenv("APS5_EMBEDDED_SAMPLER_CAP") != nullptr; std::cout << "constant samplers sampled " << (!embedding ? "through descriptors" : capped ? "from sampler heap slots past the embedded sampler limit" : "as embedded samplers") << '\n'; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics.cpp index 1f1f0dfc73e6..9dde4f7b16d4 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ImageAtomics.cpp @@ -161,7 +161,7 @@ void Check(std::uint32_t format) { } } -void DispatchContention(AgcDriver::VulkanDevice& device, std::span code, std::uint32_t waveSize, std::uint32_t groups) { +void DispatchContention(AgcDriver::VulkanDevice& device, const ShaderRecompiler::SpirvTarget& target, std::span code, std::uint32_t waveSize, std::uint32_t groups) { std::vector userData(16, 0u); const auto input = BufferDescriptor(ContentionInput.data(), static_cast(ContentionInput.size() * 4u)); const auto output = BufferDescriptor(ContentionOutput.data(), static_cast(ContentionOutput.size() * 4u)); @@ -174,32 +174,33 @@ void DispatchContention(AgcDriver::VulkanDevice& device, std::span(code.data()), code, 0, {}}, {waveSize, 0, userData, compute, std::nullopt, std::nullopt, memory}, - device.Target(), + target, {0, 0, 0, 128} }; request.useCache = false; const auto result = ShaderRecompiler::Recompile(request); + Require(result.gpuResolvedImages == target.gpuResolvedImages, "the contended image atomic stage did not take its target's mode"); device.Dispatch(result, groups, 1, 1, {}, reinterpret_cast(code.data())); device.WaitIdle(); } -std::uint32_t Contend(AgcDriver::VulkanDevice& device, std::span code, std::uint32_t waveSize, std::uint32_t initial) { +std::uint32_t Contend(AgcDriver::VulkanDevice& device, const ShaderRecompiler::SpirvTarget& target, std::span code, std::uint32_t waveSize, std::uint32_t initial) { ContentionOutput.fill(0xdeadbeefu); ContentionTexels.fill(0u); ContentionTexels[0] = initial; - DispatchContention(device, code, waveSize, ContentionGroups); + DispatchContention(device, target, code, waveSize, ContentionGroups); const auto returned = ContentionOutput; ContentionOutput.fill(0xdeadbeefu); - DispatchContention(device, ReadBack, waveSize, 1u); + DispatchContention(device, target, ReadBack, waveSize, 1u); const auto final = ContentionOutput[0]; ContentionOutput = returned; return final; } -void CheckContendedAdd(AgcDriver::VulkanDevice& device, std::uint32_t waveSize) { +void CheckContendedAdd(AgcDriver::VulkanDevice& device, const ShaderRecompiler::SpirvTarget& target, std::uint32_t waveSize) { const auto name = "image_atomic_add contended by " + std::to_string(ContentionValues) + " wave" + std::to_string(waveSize) + " threads on one texel"; ContentionInput.fill(1u); - const auto final = Contend(device, ContentionAdd, waveSize, 0u); + const auto final = Contend(device, target, ContentionAdd, waveSize, 0u); std::vector seen(ContentionValues, false); for (std::uint32_t thread = 0; thread < ContentionValues; ++thread) { const auto returned = ContentionOutput[thread]; @@ -209,7 +210,7 @@ void CheckContendedAdd(AgcDriver::VulkanDevice& device, std::uint32_t waveSize) Require(final == ContentionValues, name + ": the texel holds " + std::to_string(final) + ", expected " + std::to_string(ContentionValues)); } -void CheckContendedUMax(AgcDriver::VulkanDevice& device, std::uint32_t waveSize) { +void CheckContendedUMax(AgcDriver::VulkanDevice& device, const ShaderRecompiler::SpirvTarget& target, std::uint32_t waveSize) { const auto name = "image_atomic_umax contended by " + std::to_string(ContentionValues) + " wave" + std::to_string(waveSize) + " threads on one texel"; constexpr std::uint32_t initial = 5u; std::uint64_t state = 0x2545f4914f6cdd1dull + waveSize; @@ -221,7 +222,7 @@ void CheckContendedUMax(AgcDriver::VulkanDevice& device, std::uint32_t waveSize) values.insert(value); expected = std::max(expected, value); } - const auto final = Contend(device, ContentionUMax, waveSize, initial); + const auto final = Contend(device, target, ContentionUMax, waveSize, initial); for (std::uint32_t thread = 0; thread < ContentionValues; ++thread) { const auto returned = ContentionOutput[thread]; Require(values.contains(returned) && returned <= expected, name + ": thread " + std::to_string(thread) + " returned " + std::to_string(returned) + ", which no thread stored"); @@ -241,8 +242,15 @@ int main() { Check(format); } for (const auto waveSize : {32u, 64u}) { - CheckContendedAdd(*device, waveSize); - CheckContendedUMax(*device, waveSize); + const auto heapTarget = device->ComputeTarget(waveSize); + Require(heapTarget.gpuResolvedImages == AgcDriver::Graphics::DescriptorHeapEnabled(), "the compute target does not follow the descriptor heap"); + CheckContendedAdd(*device, heapTarget, waveSize); + CheckContendedUMax(*device, heapTarget, waveSize); + } + { + const auto plainTarget = device->Target(); + CheckContendedAdd(*device, plainTarget, 32u); + CheckContendedUMax(*device, plainTarget, 32u); } std::puts("image atomics tests passed"); return 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp index 75cddfdce106..473e719ae1c4 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ScratchPool.cpp @@ -265,7 +265,7 @@ Facts Inspect(const ShaderRecompiler::RecompileResult& result) { } void RequireHeapPipeline(const AgcDriver::VulkanDevice& device, const ShaderRecompiler::RecompileResult& result, std::uint64_t before, const std::string& name) { - if (!AgcDriver::Graphics::GpuHeapEnabled()) return; + if (!AgcDriver::Graphics::DescriptorHeapEnabled()) return; Require(result.gpuResolvedImages, name + ": the scratch program is not GPU mode"); Require(device.DescriptorHeapComputePipelines() > before, name + ": the scratch program did not take the descriptor heap"); } From 6127b8d1ed7884f43bbde1d5d8dee2c6f69a0a51 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 17 Nov 2026 06:22:40 +0530 Subject: [PATCH 268/269] fix(agc): expect a verified relocated hit to be captured again in the relocation test APS5_VERIFY_DRAW_ENTRIES and APS5_VERIFY_DRAW_DATA_HITS turn a hit into a verify draw: lookupDraw clears drawHit, the draw builds in full, and cacheDrawStages inserts it. The second-moved-table check added by #19267 required zero inserts and so only held when the hit was served from the cache. The two verify tests registered by the GPU heap PR run that check in those modes, where the insert is the verify capture, not a lost hit. Require exactly one insert in those modes and none otherwise. --- .../libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp index a9df04944ba9..ed383d540006 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp @@ -410,7 +410,8 @@ void MovedForwardedWordReachesStageDataHit(bool libraries) { SecondOffsetTable[2] = data; const auto moved2 = draw(&SecondOffsetTable[2]); std::printf("%s: a draw through a second moved table at the same alignment: %llu lookups, %llu hits, %llu stage data hits, %llu inserts\n", mode.c_str(), static_cast(moved2.lookups - again.lookups), static_cast(moved2.hits - again.hits), static_cast(moved2.stageDataHits - again.stageDataHits), static_cast(moved2.inserts - again.inserts)); - Require(moved2.hits == again.hits + 1 && moved2.inserts == again.inserts, mode + ": a draw through a second moved table was not a relocated hit after its alias's entry was recaptured (" + std::to_string(moved2.hits - again.hits) + " hits, " + std::to_string(moved2.inserts - again.inserts) + " inserts)"); + const auto capturedAgain = std::getenv("APS5_VERIFY_DRAW_ENTRIES") != nullptr || std::getenv("APS5_VERIFY_DRAW_DATA_HITS") != nullptr; + Require(moved2.hits == again.hits + 1 && (capturedAgain ? moved2.inserts == again.inserts + 1 : moved2.inserts == again.inserts), mode + ": a draw through a second moved table was not a relocated hit after its alias's entry was recaptured (" + std::to_string(moved2.hits - again.hits) + " hits, " + std::to_string(moved2.inserts - again.inserts) + " inserts)"); const auto second = pixels({64, 255, 255, 64}); Require(second.empty(), mode + ": a draw through a second moved table drew wrong pixels: " + second); } From 7d4214c1f1f72298f18d204218b15d6f2d6fa945 Mon Sep 17 00:00:00 2001 From: raghav314 Date: Tue, 17 Nov 2026 06:24:16 +0530 Subject: [PATCH 269/269] test(agc): do not require a finisher restart for a relocated draw verified as a data hit With APS5_VERIFY_DRAW_DATA_HITS a relocated stage data hit is verified, not served (DrawLookup.cpp sets drawHit false), so a pipelined run never restarts it on the draw finisher. The finisher-restart requirement from #19267 now applies only when data hits are not verified; agc_driver_draw_cache_relocation_data_hits_verify_gpu_heap failed it under APS5_DRAW_PIPELINE=1 APS5_PIPELINED_DRAWS=32. --- .../libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp index ed383d540006..6a86c07117d9 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DrawCacheRelocation.cpp @@ -392,7 +392,8 @@ void MovedForwardedWordReachesStageDataHit(bool libraries) { AgcDriver::DriverDetail::Driver::SetCaptureCheckHook(nullptr); Require(!RestartArmed.load(), mode + ": the capture check did not run for the relocated draw"); const bool pipelined = DrawFinisher::Enabled() && DrawPipeline::Depth() != 0; - Require(!pipelined || RestartChecked.load(), mode + ": the pipelined relocated draw was checked on the queue worker, not the draw finisher, so its restart patch and skip count were not exercised"); + const bool dataHitsVerified = std::getenv("APS5_VERIFY_DRAW_DATA_HITS") != nullptr; + Require(!pipelined || dataHitsVerified || RestartChecked.load(), mode + ": the pipelined relocated draw was checked on the queue worker, not the draw finisher, so its restart patch and skip count were not exercised"); if (RestartChecked.load()) { const auto skipped = restartedCounters.restartPatchSkipped - counters.restartPatchSkipped; const auto expected = std::getenv("APS5_VERIFY_DRAW_RECIPE") != nullptr ? 1u : 0u;