From b57ab5a0e9f1919af291c58016662bf368d9a0f7 Mon Sep 17 00:00:00 2001 From: Dean Galvin Date: Tue, 29 Sep 2026 13:19:01 +1300 Subject: [PATCH] feat(recompiler): structurize externally entered selection regions by cloning or route variables A selection whose region (the blocks reachable from its arms before its merge) is also entered from outside the header cannot be expressed as a SPIR-V selection construct, and the structurizer gave up with "semantic block cloning is disabled". Pixel shaders hit this through a shared discard tail (s_mov_b64 exec, 0 / exp null / s_endpgm) that several selections branch to, compute shaders through short-circuit conditions that jump into a shared body, and ray-traced compute passes through an s_cbranch_execz that skips past a join into the middle of a selection. Such a region is made single-entry in one of two ways, chosen per region by its estimated translated size: - Cloning (node splitting): the blocks the outside edges reach inside the region are copied and the outside edges redirected to the copies. When the header's merge is a shared linear return tail, giving the header a private copy of that tail is tried first. Each block now carries an estimate of the SPIR-V words it translates to. The per-instruction weights come from a fit of the recompiler's per-block output (before spirv-opt, phis excluded) over 8,300 blocks of captured shaders: VALU 60, buffer and flat 120, SMEM 180, image 220, LDS 400. SALU (8) and exports (20) fit near zero and keep a small weight. Lane ops (120) and image_bvh_intersect_ray (2000) were too rare there to fit and are weighted for the wave and traversal expansions they need. A region is cloned only when it is at most 1024 estimated words and at most an eighth of the program (at least 256), and while all clones stay within a quarter of the program. - Routing through a junction, for larger regions: every edge into the entered part (from outside, and from the header's own arms) and every edge from the arms to the merge is sent through a new empty junction block. Each rerouted edge first passes empty blocks that assign Boolean route variables (the IR's goto variables); the junction tests them in order to reach the edge's original target. The entered part then follows the junction and is emitted once. Branch conditions are still evaluated only at the end of their original blocks: a route variable records the edge a block already took, so a later SCC, VCC or EXEC write cannot change the route, and in the two-lane wave64 layout the source branch is combined across both halves as before while the route variable holds the same constant in both. Routing is refused when a rerouted edge is a back edge or leaves an indirect branch, when the region wraps around to a dominating block, or when it would change the natural loops or make the graph irreducible; cloning bounded by the program's estimated size is the fallback, and otherwise it throws with the header, the entered block and both reasons. Selections whose arms only meet again after private return tails had no post-dominator merge. When the existing rules find none, the merge is now looked up with edges into private return tails ignored, or taken as the other arm when one arm only returns; the candidate must still exit the construct only through the merge. applyBlockOrder also remaps indirect branch targets. agc_shader_control_flow_tests (under ctest) covers hand-assembled gfx1030 programs: the cloned shapes above, and routed ones (an s_cbranch_execz into an expensive region with a loop, a region inside a loop, nested entered regions, a shared body reached after SCC is overwritten, early returns beside an entered region, an arm that only returns). It checks that every selection construct exits only through its merge, follows route variables to check that the structured graph runs the same instruction ranges under the same branch conditions as the original, bounds the cloned instructions, recompiles each program for 64- and 32-lane subgroups, and keeps the routed execz program within 10% of the SPIR-V of the same program without the entering branch. Given .req files it checks their graphs instead. agc_shader_replay --cfg prints a request's graph, now with each block's estimate, before and after structurization. --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 10 +- .../prx/libSceAgcDriver/tests/ControlFlow.cpp | 610 ++++++++++++++++++ .../libSceAgcDriver/tools/ShaderReplay.cpp | 21 +- .../include/ControlFlow/ControlFlowGraph.hpp | 1 + .../include/ControlFlow/Structurizer.hpp | 1 + .../ControlFlow/src/ControlFlowGraph.cpp | 3 +- .../ControlFlow/src/GraphBuilder.cpp | 53 ++ .../ControlFlow/src/Structurizer.cpp | 531 ++++++++++++++- 8 files changed, 1217 insertions(+), 13 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/ControlFlow.cpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index fdb83b071..5793c9835 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -181,6 +181,14 @@ target_link_libraries(agc_shader_disk_cache_tests PRIVATE shader_recompiler_agc_ set_target_properties(agc_shader_disk_cache_tests PROPERTIES CXX_EXTENSIONS OFF) configure_windows_unwind(agc_shader_disk_cache_tests) +add_executable(agc_shader_control_flow_tests EXCLUDE_FROM_ALL + tests/ControlFlow.cpp +) +target_include_directories(agc_shader_control_flow_tests PRIVATE ${LIBS_INCLUDE_DIR}) +target_link_libraries(agc_shader_control_flow_tests PRIVATE shader_recompiler_agc_driver libc) +set_target_properties(agc_shader_control_flow_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_shader_control_flow_tests) + add_executable(agc_driver_flip_tests EXCLUDE_FROM_ALL tests/Flip.cpp ) @@ -324,7 +332,7 @@ set_target_properties(agc_driver_mesh_tests PROPERTIES CXX_EXTENSIONS OFF) configure_windows_unwind(agc_driver_mesh_tests) if(BUILD_TESTING) - foreach(agcTest IN ITEMS agc_driver_tests agc_shader_memory_tests agc_structurizer_tests agc_dpp_write_tests agc_shader_disk_cache_tests agc_driver_flip_tests agc_driver_pm4_tests agc_driver_graphics_tests) + foreach(agcTest IN ITEMS agc_driver_tests agc_shader_memory_tests agc_structurizer_tests agc_dpp_write_tests agc_shader_disk_cache_tests agc_shader_control_flow_tests agc_driver_flip_tests agc_driver_pm4_tests agc_driver_graphics_tests) string(REGEX REPLACE "_tests$" "" agcTestName "${agcTest}") set_target_properties(${agcTest} PROPERTIES EXCLUDE_FROM_ALL OFF) add_test(NAME ${agcTestName} COMMAND ${agcTest}) diff --git a/core/libs/prx/libSceAgcDriver/tests/ControlFlow.cpp b/core/libs/prx/libSceAgcDriver/tests/ControlFlow.cpp new file mode 100644 index 000000000..35336e904 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/ControlFlow.cpp @@ -0,0 +1,610 @@ +#include "ControlFlow/GraphBuilder.hpp" +#include "ControlFlow/RequestSerializer.hpp" +#include "ControlFlow/Structurizer.hpp" +#include "RdnaDecoder/RdnaInstructionDecoder.hpp" +#include "Recompiler.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace ShaderRecompiler; + +enum class Split { + Clone, + Route +}; + +struct Program { + std::string_view name; + std::string_view source; + std::vector code; + Split split; + std::size_t clonedLimit = 0; + std::vector reference = {}; +}; + +using RouteState = std::map; + +void require(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +std::vector constructBlocks(const ControlFlowGraph& graph, std::uint32_t header, std::uint32_t exclude) { + std::vector blocks; + for (const auto& block : graph.blocks) { + if (graph.Dominates(header, block.id) && (exclude == InvalidControlFlowId || !graph.Dominates(exclude, block.id))) { + blocks.push_back(block.id); + } + } + return blocks; +} + +void verifyStructured(const std::string& prefix, const ControlFlowGraph& graph) { + std::map mergeOwners; + std::vector> loopExits; + for (const auto& block : graph.blocks) { + const auto& terminator = block.terminator; + if (terminator.mergeBlock == InvalidControlFlowId) continue; + require(mergeOwners.emplace(terminator.mergeBlock, block.id).second, prefix + "block " + std::to_string(terminator.mergeBlock) + " merges two constructs"); + if (terminator.loopHeader) loopExits.emplace_back(terminator.mergeBlock, terminator.continueBlock); + } + for (const auto& block : graph.blocks) { + const auto& terminator = block.terminator; + if (terminator.loopHeader || terminator.mergeBlock == InvalidControlFlowId) continue; + for (const auto member : constructBlocks(graph, block.id, terminator.mergeBlock)) { + for (const auto successor : graph.FindBlock(member).successors) { + if (successor == terminator.mergeBlock || (graph.Dominates(block.id, successor) && !graph.Dominates(terminator.mergeBlock, successor))) continue; + const bool loopExit = std::any_of(loopExits.begin(), loopExits.end(), [&](const auto& exits) { return successor == exits.first || successor == exits.second; }); + require(loopExit, prefix + "block " + std::to_string(member) + " of the selection at block " + std::to_string(block.id) + " branches to block " + std::to_string(successor) + " outside the construct"); + } + } + } +} + +std::uint32_t followEmptyBlocks(const std::string& prefix, const ControlFlowGraph& graph, std::uint32_t blockId, RouteState& routes) { + for (std::size_t steps = 0; steps <= graph.blocks.size(); ++steps) { + const auto& block = graph.FindBlock(blockId); + const auto& terminator = block.terminator; + const bool empty = block.instructionBegin == block.instructionEnd; + require(terminator.gotoValue < 0 || empty, prefix + "block " + std::to_string(block.id) + " sets a route variable after guest instructions"); + if (terminator.gotoValue >= 0) routes[terminator.gotoVariable] = terminator.gotoValue != 0; + if (!empty) return blockId; + if (terminator.kind == TerminatorKind::Branch) { + blockId = terminator.trueBlock; + } else if (terminator.kind == TerminatorKind::ConditionalBranch && terminator.condition == BranchCondition::GotoVariable) { + const auto route = routes.find(terminator.gotoVariable); + require(route != routes.end(), prefix + "block " + std::to_string(block.id) + " reads route variable " + std::to_string(terminator.gotoVariable) + " before any path sets it"); + blockId = route->second ? terminator.trueBlock : terminator.falseBlock; + } else { + return blockId; + } + } + throw std::runtime_error(prefix + "a cycle of empty blocks"); +} + +void verifySameExecutions(const std::string& prefix, const ControlFlowGraph& original, const ControlFlowGraph& structured) { + std::vector> pending{{structured.blocks.front().id, original.entryBlock, {}}}; + std::vector> visited; + RouteState none; + while (!pending.empty()) { + auto [structuredId, originalId, routes] = pending.back(); + pending.pop_back(); + const auto copyId = followEmptyBlocks(prefix, structured, structuredId, routes); + const auto sourceId = followEmptyBlocks(prefix, original, originalId, none); + auto state = std::make_tuple(copyId, sourceId, routes); + if (std::find(visited.begin(), visited.end(), state) != visited.end()) continue; + visited.push_back(state); + const auto& copy = structured.FindBlock(copyId); + const auto& source = original.FindBlock(sourceId); + require(copy.instructionBegin == source.instructionBegin && copy.instructionEnd == source.instructionEnd, prefix + "block " + std::to_string(copy.id) + " runs other instructions than block " + std::to_string(source.id)); + require(copy.terminator.kind == source.terminator.kind && copy.terminator.condition == source.terminator.condition, prefix + "block " + std::to_string(copy.id) + " branches differently from block " + std::to_string(source.id)); + if (source.terminator.kind == TerminatorKind::Branch || source.terminator.kind == TerminatorKind::ConditionalBranch) pending.emplace_back(copy.terminator.trueBlock, source.terminator.trueBlock, routes); + if (source.terminator.kind == TerminatorKind::ConditionalBranch) pending.emplace_back(copy.terminator.falseBlock, source.terminator.falseBlock, routes); + } +} + +std::size_t clonedInstructions(const ControlFlowGraph& graph) { + std::map, std::size_t> copies; + std::size_t cloned = 0; + for (const auto& block : graph.blocks) { + if (block.instructionBegin != block.instructionEnd && copies[{block.instructionBegin, block.instructionEnd}]++ != 0) cloned += block.instructionEnd - block.instructionBegin; + } + return cloned; +} + +std::size_t routeVariables(const ControlFlowGraph& graph) { + std::vector variables; + for (const auto& block : graph.blocks) { + if (block.terminator.condition == BranchCondition::GotoVariable && std::find(variables.begin(), variables.end(), block.terminator.gotoVariable) == variables.end()) variables.push_back(block.terminator.gotoVariable); + } + return variables.size(); +} + +struct Structured { + std::size_t addedBlocks; + std::size_t clonedInstructions; + std::size_t routeVariables; +}; + +Structured verifyGraph(const std::string& name, std::span code) { + const std::string prefix = name + ": "; + const auto decoded = RdnaInstructionDecoder{}.Decode(code); + const auto original = GraphBuilder{}.Build(decoded); + auto graph = original; + Structurizer{}.Structurize(graph); + verifyStructured(prefix, graph); + verifySameExecutions(prefix, original, graph); + return {graph.blocks.size() - original.blocks.size(), clonedInstructions(graph), routeVariables(graph)}; +} + +std::vector Store(std::vector code) { + code.insert(code.end(), {0xe0700000u, 0x80000100u, 0xbf810000u}); + return code; +} + +void verifyRequest(const char* path) { + std::ifstream file(path, std::ios::binary); + std::ostringstream text; + text << file.rdbuf(); + const auto request = RequestSerializer{}.Deserialize(text.str()); + const auto result = verifyGraph(path, request.request.shader.code); + std::printf("%s: structured with %zu added blocks, %zu cloned instructions, %zu route variables\n", path, result.addedBlocks, result.clonedInstructions, result.routeVariables); +} + +std::size_t recompile(const std::string& name, std::span code, std::uint32_t subgroupSize) { + const std::array userData{0x10000000u, 0x00100000u, 0x40u, 0x00027facu}; + const std::array capabilities{1u, 61u}; + const std::array extensions{"SPV_KHR_storage_buffer_storage_class"}; + RecompileRequest request{}; + request.shader = {ShaderStage::Compute, 0x20000u, code, 0, {}}; + request.context.waveSize = 64; + request.context.userDataBaseRegister = 0; + request.context.userData = userData; + request.context.compute = ShaderComputeStageInfo{{64u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; + request.target.vulkanVersion = 0x00403000u; + request.target.spirvVersion = 0x00010600u; + request.target.subgroupSize = subgroupSize; + request.target.bdaAbiVersion = 1; + request.target.supportedCapabilities = capabilities; + request.target.supportedExtensions = extensions; + request.target.maxWorkgroupSize = {1024u, 1024u, 64u}; + request.target.maxWorkgroupInvocations = 1024; + request.target.maxWorkgroupSharedMemoryBytes = 49152; + request.layout = {0, 0, 0, 128}; + request.useCache = false; + const auto result = Recompile(request); + require(!result.spirv.empty(), name + ": no SPIR-V for a " + std::to_string(subgroupSize) + "-lane subgroup"); + return result.spirv.size(); +} + +void verifyProgram(const Program& program) { + const std::string name(program.name); + const auto result = verifyGraph(name, program.code); + if (program.split == Split::Clone) { + require(result.clonedInstructions != 0 && result.routeVariables == 0, name + ": expected a clone, got " + std::to_string(result.clonedInstructions) + " cloned instructions and " + std::to_string(result.routeVariables) + " route variables"); + } else { + require(result.clonedInstructions <= program.clonedLimit && result.routeVariables != 0, name + ": expected routing with at most " + std::to_string(program.clonedLimit) + " cloned instructions, got " + std::to_string(result.clonedInstructions) + " cloned instructions and " + std::to_string(result.routeVariables) + " route variables"); + } + const auto words = recompile(name, program.code, 64u); + static_cast(recompile(name, program.code, 32u)); + if (!program.reference.empty()) { + const auto reference = recompile(name, program.reference, 64u); + require(words * 10u <= reference * 11u, name + ": " + std::to_string(words) + " SPIR-V words, more than 10% over the " + std::to_string(reference) + " of the program without the entering branch"); + } +} + +} + +int main(int argc, char** argv) { + if (argc > 1) { + int failures = 0; + for (int i = 1; i < argc; ++i) { + try { + verifyRequest(argv[i]); + } catch (const std::exception& error) { + std::fprintf(stderr, "%s: %s\n", argv[i], error.what()); + ++failures; + } + } + return failures == 0 ? 0 : 1; + } + const std::vector programs{ + {"shared tail", R"( + v_cmp_gt_u32 vcc, 16, v0 + s_cbranch_vccz outer_else + v_cmp_gt_u32 vcc, 8, v0 + s_cbranch_vccnz tail + v_add_nc_u32 v1, 1, v0 + s_branch done +outer_else: + v_add_nc_u32 v1, 2, v0 +tail: + v_add_nc_u32 v1, 3, v1 +done: + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm)", + Store({0x7d880090u, 0xbf860004u, 0x7d880088u, 0xbf870003u, 0x4a020081u, 0xbf820002u, 0x4a020082u, 0x4a020283u}), Split::Clone}, + {"shared tail with a selection", R"( + v_cmp_gt_u32 vcc, 16, v0 + s_cbranch_vccz outer_else + v_cmp_gt_u32 vcc, 8, v0 + s_cbranch_vccnz tail + v_add_nc_u32 v1, 1, v0 + s_branch done +outer_else: + v_add_nc_u32 v1, 2, v0 +tail: + v_cmp_gt_u32 vcc, 4, v0 + s_cbranch_vccz tail_join + v_add_nc_u32 v1, 5, v1 +tail_join: + v_add_nc_u32 v1, 3, v1 +done: + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm)", + Store({0x7d880090u, 0xbf860004u, 0x7d880088u, 0xbf870003u, 0x4a020081u, 0xbf820005u, 0x4a020082u, 0x7d880084u, 0xbf860001u, 0x4a020285u, 0x4a020283u}), Split::Clone}, + {"shared tail in a loop", R"( + s_mov_b32 s8, 0 + v_mov_b32 v1, 0 +loop: + v_cmp_gt_u32 vcc, s8, v0 + s_cbranch_vccz outer_else + v_cmp_gt_u32 vcc, 8, v0 + s_cbranch_vccnz tail + v_add_nc_u32 v1, 1, v1 + s_branch latch +outer_else: + v_add_nc_u32 v1, 2, v1 +tail: + v_add_nc_u32 v1, 3, v1 +latch: + s_add_u32 s8, s8, 16 + s_cmp_lt_u32 s8, 64 + s_cbranch_scc1 loop + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm)", + Store({0xbe880380u, 0x7e020280u, 0x7d880008u, 0xbf860004u, 0x7d880088u, 0xbf870003u, 0x4a020281u, 0xbf820002u, 0x4a020282u, 0x4a020283u, 0x80089008u, 0xbf0ac008u, 0xbf85fff5u}), Split::Clone}, + {"shared early exit", R"( + v_mov_b32 v1, 0 + v_cmp_gt_u32 vcc, 16, v0 + s_and_saveexec_b64 s[8:9], vcc + s_cbranch_execz join + v_cmp_gt_u32 vcc, 4, v0 + s_cbranch_vccz early_exit + v_add_nc_u32 v1, 1, v0 +join: + s_mov_b64 exec, s[8:9] + v_cmp_gt_u32 vcc, 32, v0 + s_cbranch_vccz early_exit + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm +early_exit: + s_mov_b64 exec, 0 + s_endpgm)", + {0x7e020280u, 0x7d880090u, 0xbe88246au, 0xbf880003u, 0x7d880084u, 0xbf860007u, 0x4a020081u, 0xbefe0408u, 0x7d8800a0u, 0xbf860003u, 0xe0700000u, 0x80000100u, 0xbf810000u, 0xbefe0480u, 0xbf810000u}, Split::Clone}, + {"short-circuit condition", R"( + v_cmp_gt_u32 vcc, 16, v0 + s_cbranch_vccz body + v_cmp_gt_u32 vcc, 8, v0 + s_cbranch_vccnz done +body: + v_add_nc_u32 v1, 1, v0 + v_cmp_gt_u32 vcc, 4, v0 + s_cbranch_vccz done + v_add_nc_u32 v1, 2, v1 +done: + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm)", + Store({0x7d880090u, 0xbf860002u, 0x7d880088u, 0xbf870004u, 0x4a020081u, 0x7d880084u, 0xbf860001u, 0x4a020282u}), Split::Clone}, + {"entered region with an expensive body", R"( + v_mov_b32 v1, 0 + v_cmp_gt_u32 vcc, 16, v0 + s_and_saveexec_b64 s[8:9], vcc + s_cbranch_execz body + v_add_nc_u32 v1, 1, v0 + v_cmp_gt_u32 vcc, 8, v1 + s_cbranch_vccnz done +body: + s_mov_b32 s10, 0 +loop: + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 + s_add_u32 s10, s10, 1 + s_cmp_lt_u32 s10, 4 + s_cbranch_scc1 loop + s_mov_b64 exec, s[8:9] + buffer_store_dword v1, off, s[0:3], 0 +done: + s_endpgm)", + {0x7e020280u, 0x7d880090u, 0xbe88246au, 0xbf880003u, 0x4a020081u, 0x7d880288u, 0xbf870015u, 0xbe8a0380u, 0xe0300000u, 0x80000200u, + 0x10060302u, 0x06060503u, 0x3a020303u, 0x7e160501u, 0x4a02020bu, 0xe0300000u, 0x80000200u, 0x10060302u, 0x06060503u, 0x3a020303u, + 0x7e160501u, 0x4a02020bu, 0x800a810au, 0xbf0a840au, 0xbf85ffefu, 0xbefe0408u, 0xe0700000u, 0x80000100u, 0xbf810000u}, + Split::Route, 0, + {0x7e020280u, 0x7d880090u, 0xbe88246au, 0xbf800000u, 0x4a020081u, 0x7d880288u, 0xbf870015u, 0xbe8a0380u, 0xe0300000u, 0x80000200u, + 0x10060302u, 0x06060503u, 0x3a020303u, 0x7e160501u, 0x4a02020bu, 0xe0300000u, 0x80000200u, 0x10060302u, 0x06060503u, 0x3a020303u, + 0x7e160501u, 0x4a02020bu, 0x800a810au, 0xbf0a840au, 0xbf85ffefu, 0xbefe0408u, 0xe0700000u, 0x80000100u, 0xbf810000u}}, + {"return tail past an entered region", R"( + v_mov_b32 v1, 0 + v_cmp_gt_u32 vcc, 16, v0 + s_and_saveexec_b64 s[8:9], vcc + s_cbranch_execz body + v_cmp_gt_u32 vcc, 8, v0 + s_cbranch_vccnz done + v_add_nc_u32 v1, 1, v0 + s_mov_b64 exec, s[8:9] +body: + s_mov_b32 s10, 0 +loop: + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 + s_add_u32 s10, s10, 1 + s_cmp_lt_u32 s10, 4 + s_cbranch_scc1 loop + buffer_store_dword v1, off, s[0:3], 0 +done: + s_endpgm)", + {0x7e020280u, 0x7d880090u, 0xbe88246au, 0xbf880004u, 0x7d880088u, 0xbf870016u, 0x4a020081u, 0xbefe0408u, 0xbe8a0380u, 0xe0300000u, + 0x80000200u, 0x10060302u, 0x06060503u, 0x3a020303u, 0x7e160501u, 0x4a02020bu, 0xe0300000u, 0x80000200u, 0x10060302u, 0x06060503u, + 0x3a020303u, 0x7e160501u, 0x4a02020bu, 0x800a810au, 0xbf0a840au, 0xbf85ffefu, 0xe0700000u, 0x80000100u, 0xbf810000u}, + Split::Clone}, + {"entered region in a loop", R"( + s_mov_b32 s12, 0 + v_mov_b32 v1, 0 +outer: + v_cmp_gt_u32 vcc, s12, v0 + s_cbranch_vccz body + v_cmp_gt_u32 vcc, 8, v0 + s_cbranch_vccnz join + v_add_nc_u32 v1, 1, v1 +body: + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 +join: + v_add_nc_u32 v1, 2, v1 + s_add_u32 s12, s12, 16 + s_cmp_lt_u32 s12, 64 + s_cbranch_scc0 exit_loop + s_branch outer +exit_loop: + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm)", + {0xbe8c0380u, 0x7e020280u, 0x7d88000cu, 0xbf860003u, 0x7d880088u, 0xbf87000fu, 0x4a020281u, 0xe0300000u, 0x80000200u, 0x10060302u, + 0x06060503u, 0x3a020303u, 0x7e160501u, 0x4a02020bu, 0xe0300000u, 0x80000200u, 0x10060302u, 0x06060503u, 0x3a020303u, 0x7e160501u, + 0x4a02020bu, 0x4a020282u, 0x800c900cu, 0xbf0ac00cu, 0xbf840001u, 0xbf82ffe8u, 0xe0700000u, 0x80000100u, 0xbf810000u}, + Split::Route}, + {"nested entered regions", R"( + v_mov_b32 v1, 0 + v_cmp_gt_u32 vcc, 16, v0 + s_and_saveexec_b64 s[8:9], vcc + s_cbranch_execz outer_body + v_add_nc_u32 v1, 1, v0 + v_cmp_gt_u32 vcc, 8, v1 + s_cbranch_vccnz done +outer_body: + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 + s_cmp_eq_u32 s11, 64 + s_cbranch_scc0 inner_body + v_add_nc_u32 v1, 2, v1 + v_cmp_gt_u32 vcc, 4, v1 + s_cbranch_vccz done +inner_body: + s_mov_b32 s10, 0 +inner_loop: + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 + s_add_u32 s10, s10, 1 + s_cmp_lt_u32 s10, 4 + s_cbranch_scc1 inner_loop + s_mov_b64 exec, s[8:9] + buffer_store_dword v1, off, s[0:3], 0 +done: + s_endpgm)", + {0x7e020280u, 0x7d880090u, 0xbe88246au, 0xbf880003u, 0x4a020081u, 0x7d880288u, 0xbf87001au, 0xe0300000u, 0x80000200u, 0x10060302u, + 0x06060503u, 0x3a020303u, 0x7e160501u, 0x4a02020bu, 0xbf06c00bu, 0xbf840003u, 0x4a020282u, 0x7d880284u, 0xbf86000eu, 0xbe8a0380u, + 0xe0300000u, 0x80000200u, 0x10060302u, 0x06060503u, 0x3a020303u, 0x7e160501u, 0x4a02020bu, 0x800a810au, 0xbf0a840au, 0xbf85fff6u, + 0xbefe0408u, 0xe0700000u, 0x80000100u, 0xbf810000u}, + Split::Route}, + {"shared body after an overwritten condition", R"( + v_mov_b32 v1, 0 + s_cmp_eq_u32 s2, 64 + s_cbranch_scc0 shared + v_add_nc_u32 v1, 1, v0 + s_cmp_eq_u32 s3, 0 + s_cbranch_scc1 done +shared: + s_cbranch_scc1 store + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 +store: + buffer_store_dword v1, off, s[0:3], 0 +done: + s_endpgm)", + {0x7e020280u, 0xbf06c002u, 0xbf840003u, 0x4a020081u, 0xbf068003u, 0xbf850011u, 0xbf85000eu, 0xe0300000u, 0x80000200u, 0x10060302u, + 0x06060503u, 0x3a020303u, 0x7e160501u, 0x4a02020bu, 0xe0300000u, 0x80000200u, 0x10060302u, 0x06060503u, 0x3a020303u, 0x7e160501u, + 0x4a02020bu, 0xe0700000u, 0x80000100u, 0xbf810000u}, + Split::Route}, + {"entered region beside early returns", R"( + v_mov_b32 v1, 0 + v_cmp_gt_u32 vcc, 16, v0 + s_cbranch_vccz body + v_add_nc_u32 v1, 1, v0 + v_cmp_gt_u32 vcc, 8, v1 + s_cbranch_vccnz tail + v_readfirstlane_b32 s11, v1 + s_cmp_eq_u32 s11, 12 + s_cbranch_scc0 done + s_cmp_eq_u32 s11, 38 + s_cbranch_scc1 done +body: + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 +tail: + v_add_nc_u32 v1, 1, v1 + v_xor_b32 v1, v3, v1 + v_add_nc_u32 v1, 2, v1 + v_xor_b32 v1, v3, v1 + v_add_nc_u32 v1, 3, v1 + v_xor_b32 v1, v3, v1 + v_add_nc_u32 v1, 4, v1 + v_xor_b32 v1, v3, v1 + v_add_nc_u32 v1, 5, v1 + v_xor_b32 v1, v3, v1 + v_add_nc_u32 v1, 6, v1 + v_xor_b32 v1, v3, v1 + v_add_nc_u32 v1, 7, v1 + v_xor_b32 v1, v3, v1 + v_add_nc_u32 v1, 8, v1 + v_xor_b32 v1, v3, v1 + v_add_nc_u32 v1, 9, v1 + v_xor_b32 v1, v3, v1 + v_add_nc_u32 v1, 10, v1 + v_xor_b32 v1, v3, v1 +done: + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm)", + {0x7e020280u, 0x7d880090u, 0xbf860008u, 0x4a020081u, 0x7d880288u, 0xbf870013u, 0x7e160501u, 0xbf068c0bu, 0xbf840024u, 0xbf06a60bu, + 0xbf850022u, 0xe0300000u, 0x80000200u, 0x10060302u, 0x06060503u, 0x3a020303u, 0x7e160501u, 0x4a02020bu, 0xe0300000u, 0x80000200u, + 0x10060302u, 0x06060503u, 0x3a020303u, 0x7e160501u, 0x4a02020bu, 0x4a020281u, 0x3a020303u, 0x4a020282u, 0x3a020303u, 0x4a020283u, + 0x3a020303u, 0x4a020284u, 0x3a020303u, 0x4a020285u, 0x3a020303u, 0x4a020286u, 0x3a020303u, 0x4a020287u, 0x3a020303u, 0x4a020288u, + 0x3a020303u, 0x4a020289u, 0x3a020303u, 0x4a02028au, 0x3a020303u, 0xe0700000u, 0x80000100u, 0xbf810000u}, + Split::Route, 4}, + {"selection arm that only returns", R"( + s_cbranch_execz inner + s_cbranch_scc1 done +inner: + v_cmp_gt_u32 vcc, 3, v1 + s_cbranch_vccnz second + v_mul_f32 v3, v2, v1 + s_cbranch_vccz join +second: + s_cbranch_vccnz done +join: + v_add_nc_u32 v1, 2, v1 +done: + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm)", + {0xbf880001u, 0xbf850006u, 0x7d880283u, 0xbf870002u, 0x10060302u, 0xbf860001u, 0xbf870001u, 0x4a020282u, 0xe0700000u, 0x80000100u, + 0xbf810000u}, + Split::Route, 9}, + {"shared early exit beside an expensive region", R"( + v_mov_b32 v1, 0 + v_cmp_gt_u32 vcc, 16, v0 + s_and_saveexec_b64 s[8:9], vcc + s_cbranch_execz join + v_cmp_gt_u32 vcc, 4, v0 + s_cbranch_vccz early_exit + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 +join: + s_mov_b64 exec, s[8:9] + v_cmp_gt_u32 vcc, 32, v0 + s_cbranch_vccz early_exit + buffer_load_dword v2, off, s[0:3], 0 + v_mul_f32 v3, v2, v1 + v_add_f32 v3, v3, v2 + v_xor_b32 v1, v3, v1 + v_readfirstlane_b32 s11, v1 + v_add_nc_u32 v1, s11, v1 + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm +early_exit: + s_mov_b64 exec, 0 + s_endpgm)", + {0x7e020280u, 0x7d880090u, 0xbe88246au, 0xbf88000eu, 0x7d880084u, 0xbf860019u, 0xe0300000u, 0x80000200u, 0x10060302u, 0x06060503u, + 0x3a020303u, 0x7e160501u, 0x4a02020bu, 0xe0300000u, 0x80000200u, 0x10060302u, 0x06060503u, 0x3a020303u, 0xbefe0408u, 0x7d8800a0u, + 0xbf86000au, 0xe0300000u, 0x80000200u, 0x10060302u, 0x06060503u, 0x3a020303u, 0x7e160501u, 0x4a02020bu, 0xe0700000u, 0x80000100u, + 0xbf810000u, 0xbefe0480u, 0xbf810000u}, + Split::Clone}, + }; + int failures = 0; + for (const auto& program : programs) { + try { + verifyProgram(program); + } catch (const std::exception& error) { + std::fprintf(stderr, "%s\n%.*s\n", error.what(), static_cast(program.source.size()), program.source.data()); + ++failures; + } + } + if (failures != 0) return 1; + std::puts("Control flow structurization tests passed"); + return 0; +} diff --git a/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp b/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp index de5b97b7a..9b0c1ce2c 100644 --- a/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp +++ b/core/libs/prx/libSceAgcDriver/tools/ShaderReplay.cpp @@ -1,6 +1,8 @@ // agc_shader_replay ...: replays compute recompile requests the driver saved with // APS5_DUMP_SHADERS=1, running the same resource analysis and recompile steps without the game. +#include "ControlFlow/GraphBuilder.hpp" #include "ControlFlow/RequestSerializer.hpp" +#include "ControlFlow/Structurizer.hpp" #include "Optimization/ResourceMaterializer.hpp" #include "Optimization/ResourceProgram.hpp" #include "Recompiler.hpp" @@ -39,6 +41,7 @@ bool g_disassemble = false; bool g_assembly = false; bool g_memory = false; bool g_spirv = false; +bool g_graph = false; bool Replay(const char* path) { const auto request = ShaderRecompiler::RequestSerializer{}.Deserialize(ReadText(path)); @@ -76,6 +79,18 @@ bool Replay(const char* path) { // Raw first words carry what the text omits (branch offsets, waitcnt fields). for (const auto& instruction : program.instructions) std::printf("raw=%08x %s\n", instruction.rawWords[0], ShaderRecompiler::RdnaInstructionToString(instruction).c_str()); } + if (g_graph) { + const auto program = ShaderRecompiler::RdnaInstructionDecoder{}.Decode(request.request.shader.code); + auto graph = ShaderRecompiler::GraphBuilder{}.Build(program); + std::printf("control flow graph:\n%s", ShaderRecompiler::GraphToString(graph).c_str()); + try { + ShaderRecompiler::Structurizer{}.Structurize(graph); + std::printf("structured control flow graph:\n%s", ShaderRecompiler::GraphToString(graph).c_str()); + } catch (const std::exception& error) { + std::printf(" structurization failed: %s\n", FirstLine(error.what()).c_str()); + return false; + } + } try { auto program = ShaderRecompiler::PrepareResourceProgram(request.request); constexpr ShaderRecompiler::ResourceMaterializer materializer; @@ -122,7 +137,7 @@ bool Replay(const char* path) { int main(int argc, char** argv) { if (argc < 2) { - std::fprintf(stderr, "usage: agc_shader_replay [--dis] [--asm] [--mem] [--spv] ...\n the driver writes shader_
.req files when APS5_DUMP_SHADERS is set\n"); + std::fprintf(stderr, "usage: agc_shader_replay [--dis] [--asm] [--cfg] [--mem] [--spv] ...\n the driver writes shader_
.req files when APS5_DUMP_SHADERS is set\n"); return 2; } int failures = 0; @@ -135,6 +150,10 @@ int main(int argc, char** argv) { g_assembly = true; continue; } + if (std::string(argv[i]) == "--cfg") { + g_graph = true; + continue; + } if (std::string(argv[i]) == "--mem") { g_memory = true; continue; diff --git a/core/shader/recompiler/ControlFlow/include/ControlFlow/ControlFlowGraph.hpp b/core/shader/recompiler/ControlFlow/include/ControlFlow/ControlFlowGraph.hpp index ec77a1990..dc1eccdff 100644 --- a/core/shader/recompiler/ControlFlow/include/ControlFlow/ControlFlowGraph.hpp +++ b/core/shader/recompiler/ControlFlow/include/ControlFlow/ControlFlowGraph.hpp @@ -66,6 +66,7 @@ struct BasicBlock { std::uint32_t endProgramCounter = 0; std::uint32_t instructionBegin = 0; std::uint32_t instructionEnd = 0; + std::uint32_t estimatedSpirvWords = 0; std::vector predecessors; std::vector successors; std::vector dominators; diff --git a/core/shader/recompiler/ControlFlow/include/ControlFlow/Structurizer.hpp b/core/shader/recompiler/ControlFlow/include/ControlFlow/Structurizer.hpp index d2e209964..d643041ac 100644 --- a/core/shader/recompiler/ControlFlow/include/ControlFlow/Structurizer.hpp +++ b/core/shader/recompiler/ControlFlow/include/ControlFlow/Structurizer.hpp @@ -19,6 +19,7 @@ private: void canonicalizeNaturalLoops(ControlFlowGraph& graph) const; void splitSharedMergeBlocks(ControlFlowGraph& graph) const; void isolateSemanticLoopHeaders(ControlFlowGraph& graph) const; + void orderByDominance(ControlFlowGraph& graph) const; void clearStructuredTerminators(ControlFlowGraph& graph) const; void verifyReducibility(const ControlFlowGraph& graph) const; }; diff --git a/core/shader/recompiler/ControlFlow/src/ControlFlowGraph.cpp b/core/shader/recompiler/ControlFlow/src/ControlFlowGraph.cpp index 7a3e337d7..4caff5564 100644 --- a/core/shader/recompiler/ControlFlow/src/ControlFlowGraph.cpp +++ b/core/shader/recompiler/ControlFlow/src/ControlFlowGraph.cpp @@ -143,7 +143,8 @@ std::string GraphToString(const ControlFlowGraph& graph) { text += "block_" + std::to_string(block.id); text += " pc=" + toHexString(block.startProgramCounter); text += " end=" + toHexString(block.endProgramCounter); - text += " inst=[" + std::to_string(block.instructionBegin) + "," + std::to_string(block.instructionEnd) + ")\n"; + text += " inst=[" + std::to_string(block.instructionBegin) + "," + std::to_string(block.instructionEnd) + ")"; + text += " words=" + std::to_string(block.estimatedSpirvWords) + "\n"; text += " predecessors=[" + joinIds(block.predecessors) + "]"; text += " successors=[" + joinIds(block.successors) + "]\n"; text += " dominators=[" + joinIds(block.dominators) + "]"; diff --git a/core/shader/recompiler/ControlFlow/src/GraphBuilder.cpp b/core/shader/recompiler/ControlFlow/src/GraphBuilder.cpp index d7c81793b..f483e799a 100644 --- a/core/shader/recompiler/ControlFlow/src/GraphBuilder.cpp +++ b/core/shader/recompiler/ControlFlow/src/GraphBuilder.cpp @@ -42,6 +42,54 @@ void remapIds(std::vector& values, const std::vector& instructionProgramCounters, std::uint32_t firstProgramCounter, std::uint32_t endProgramCounter) { return target == endProgramCounter || (target >= firstProgramCounter && instructionProgramCounters.contains(target)); } @@ -327,6 +375,11 @@ ControlFlowGraph GraphBuilder::Build(const RdnaProgram& program) const { linkBlocks(graph.blocks, program); graph.entryBlock = 0; pruneUnreachableBlocks(graph); + for (auto& block : graph.blocks) { + for (auto index = block.instructionBegin; index < block.instructionEnd; ++index) { + block.estimatedSpirvWords += estimatedSpirvWords(program.instructions[index]); + } + } return graph; } diff --git a/core/shader/recompiler/ControlFlow/src/Structurizer.cpp b/core/shader/recompiler/ControlFlow/src/Structurizer.cpp index 9a138a090..983df6988 100644 --- a/core/shader/recompiler/ControlFlow/src/Structurizer.cpp +++ b/core/shader/recompiler/ControlFlow/src/Structurizer.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include namespace ShaderRecompiler { @@ -116,6 +117,12 @@ std::vector applyBlockOrder(ControlFlowGraph& graph, std::vector< block.terminator.falseBlock = remapId(block.terminator.falseBlock, idMap); block.terminator.mergeBlock = remapId(block.terminator.mergeBlock, idMap); block.terminator.continueBlock = remapId(block.terminator.continueBlock, idMap); + for (auto& target : block.terminator.indirectTargets) { + target = remapId(target, idMap); + } + for (auto& target : block.terminator.indirectSelectorTargets) { + target = remapId(target, idMap); + } } return idMap; @@ -307,6 +314,118 @@ bool reachesWithinIteration(const ControlFlowGraph& graph, const NaturalLoop& lo return false; } +std::vector linearTail(const ControlFlowGraph& graph, std::uint32_t start) { + std::vector tail; + for (auto blockId = start; !contains(tail, blockId);) { + tail.push_back(blockId); + const auto& block = graph.FindBlock(blockId); + if (block.successors.size() != 1u) { + break; + } + blockId = block.successors.front(); + } + return tail; +} + +std::uint32_t mergeBesideReturns(const ControlFlowGraph& graph, const BasicBlock& header) { + const auto reach = [&](std::uint32_t start) { + std::vector reached; + std::vector pending = {start}; + while (!pending.empty()) { + const auto blockId = pending.back(); + pending.pop_back(); + if (blockId == header.id || contains(reached, blockId)) { + continue; + } + reached.push_back(blockId); + const auto& successors = graph.FindBlock(blockId).successors; + pending.insert(pending.end(), successors.begin(), successors.end()); + } + sortUnique(reached); + return reached; + }; + const auto trueReach = reach(header.terminator.trueBlock); + const auto falseReach = reach(header.terminator.falseBlock); + if (intersectSorted(trueReach, falseReach).empty()) { + const auto returnsWithin = [&](const std::vector& reached) { + return std::all_of(reached.begin(), reached.end(), [&](std::uint32_t blockId) { return graph.Dominates(header.id, blockId); }); + }; + if (returnsWithin(trueReach) && graph.Dominates(header.id, header.terminator.falseBlock)) { + return header.terminator.falseBlock; + } + if (returnsWithin(falseReach) && graph.Dominates(header.id, header.terminator.trueBlock)) { + return header.terminator.trueBlock; + } + } + const auto count = static_cast(graph.blocks.size()); + const auto returns = [&](std::uint32_t blockId) { + if (!graph.Dominates(header.id, blockId) || !hasLinearPathToTerminal(graph, blockId)) { + return false; + } + const auto tail = linearTail(graph, blockId); + return std::all_of(tail.begin(), tail.end(), [&](std::uint32_t member) { return graph.FindBlock(member).predecessors.size() == 1u; }); + }; + std::vector> kept(count); + std::vector> postDominators(count, allBlockIds(count)); + for (const auto& block : graph.blocks) { + for (const auto successor : block.successors) { + if (!returns(successor)) { + kept[block.id].push_back(successor); + } + } + if (kept[block.id].empty()) { + postDominators[block.id] = {block.id}; + } + } + for (bool changed = true; changed;) { + changed = false; + for (const auto& block : graph.blocks) { + if (kept[block.id].empty()) { + continue; + } + auto next = postDominators[kept[block.id].front()]; + for (std::size_t i = 1; i < kept[block.id].size(); ++i) { + next = intersectSorted(next, postDominators[kept[block.id][i]]); + } + addUnique(next, block.id); + sortUnique(next); + if (next != postDominators[block.id]) { + postDominators[block.id] = std::move(next); + changed = true; + } + } + } + const auto common = intersectSorted(postDominators[header.terminator.trueBlock], postDominators[header.terminator.falseBlock]); + const auto merge = std::find_if(common.begin(), common.end(), [&](std::uint32_t candidate) { + return std::all_of(common.begin(), common.end(), [&](std::uint32_t other) { return contains(postDominators[candidate], other); }); + }); + if (merge == common.end() || *merge == header.id) { + return InvalidControlFlowId; + } + const auto inConstruct = [&](std::uint32_t blockId) { + return blockId != *merge && graph.Dominates(header.id, blockId) && !graph.Dominates(*merge, blockId); + }; + for (const auto& block : graph.blocks) { + if (block.id == header.id || !inConstruct(block.id)) { + continue; + } + for (const auto successor : block.successors) { + if (successor != *merge && !inConstruct(successor)) { + return InvalidControlFlowId; + } + } + } + if (canReachBefore(graph, *merge, header.id, InvalidControlFlowId)) { + return InvalidControlFlowId; + } + for (const auto& block : graph.blocks) { + if (block.id != header.id && inConstruct(block.id) && canReachBefore(graph, *merge, block.id, header.id)) { + return InvalidControlFlowId; + } + } + return *merge; +} + std::uint32_t findSelectionMerge(const ControlFlowGraph& graph, const BasicBlock& block) { const auto globalMerge = graph.FindNearestCommonPostDominator(block.terminator.trueBlock, block.terminator.falseBlock); const auto* loop = findInnermostContainingLoop(graph, block.id); @@ -333,6 +452,7 @@ std::uint32_t findSelectionMerge(const ControlFlowGraph& graph, const BasicBlock if (graph.Dominates(block.id, trueTarget) && hasLinearPathToTerminal(graph, falseTarget)) { return trueTarget; } + return mergeBesideReturns(graph, block); } } return globalMerge; @@ -461,7 +581,374 @@ std::vector selectionRegion(const ControlFlowGraph& graph, const return region; } -bool splitOneSelectionMerge(ControlFlowGraph& graph) { +constexpr std::uint32_t CloneWordLimit = 1024u; +constexpr std::uint32_t CloneWordFloor = 256u; +constexpr std::uint32_t CloneShareDivisor = 8u; +constexpr std::uint32_t CloneBudgetDivisor = 4u; + +struct SplitBudget { + std::uint32_t programWords = 0; + std::uint32_t remainingCloneWords = 0; + std::uint32_t remainingFallbackWords = 0; + std::uint32_t nextGotoVariable = 0; +}; + +void redirectEdge(BasicBlock& block, std::uint32_t oldTarget, std::uint32_t newTarget) { + replaceValue(block.successors, oldTarget, newTarget); + replaceTerminatorTarget(block.terminator, oldTarget, newTarget); + for (auto& target : block.terminator.indirectTargets) { + if (target == oldTarget) { + target = newTarget; + } + } + for (auto& target : block.terminator.indirectSelectorTargets) { + if (target == oldTarget) { + target = newTarget; + } + } +} + +std::vector reversePostOrder(const ControlFlowGraph& graph) { + std::vector postOrder; + std::vector visited(graph.blocks.size(), false); + std::vector> stack = {{graph.entryBlock, 0u}}; + visited[graph.entryBlock] = true; + while (!stack.empty()) { + auto& [blockId, next] = stack.back(); + const auto& successors = graph.FindBlock(blockId).successors; + if (next < successors.size()) { + const auto successor = successors[next++]; + if (!visited[successor]) { + visited[successor] = true; + stack.emplace_back(successor, 0u); + } + continue; + } + postOrder.push_back(blockId); + stack.pop_back(); + } + return {postOrder.rbegin(), postOrder.rend()}; +} + +using Edge = std::pair; + +std::vector externalEntryEdges(const ControlFlowGraph& graph, std::uint32_t header, const std::vector& region) { + std::vector edges; + for (const auto member : region) { + for (const auto predecessor : graph.FindBlock(member).predecessors) { + if (predecessor == header || contains(region, predecessor)) { + continue; + } + if (graph.Dominates(member, predecessor)) { + throw std::runtime_error("selection header block " + std::to_string(header) + " region block " + std::to_string(member) + " is entered by a back edge from block " + std::to_string(predecessor)); + } + edges.emplace_back(predecessor, member); + } + } + return edges; +} + +std::vector reachableWithin(const ControlFlowGraph& graph, const std::vector& entryEdges, const std::vector& region) { + std::vector reached; + std::vector pending; + for (const auto& edge : entryEdges) { + pending.push_back(edge.second); + } + while (!pending.empty()) { + const auto blockId = pending.back(); + pending.pop_back(); + if (contains(reached, blockId)) { + continue; + } + reached.push_back(blockId); + for (const auto successor : graph.FindBlock(blockId).successors) { + if (contains(region, successor)) { + pending.push_back(successor); + } + } + } + sortUnique(reached); + return reached; +} + +std::uint32_t estimatedSpirvWords(const ControlFlowGraph& graph, const std::vector& blocks) { + std::uint32_t words = 0; + for (const auto blockId : blocks) { + words += graph.FindBlock(blockId).estimatedSpirvWords; + } + return words; +} + +std::string cloneCostRefusal(const SplitBudget& budget, std::uint32_t words) { + const auto shareLimit = std::max(CloneWordFloor, budget.programWords / CloneShareDivisor); + const auto prefix = "cloning an estimated " + std::to_string(words) + " SPIR-V words exceeds "; + if (words > CloneWordLimit) { + return prefix + "the clone limit of " + std::to_string(CloneWordLimit); + } + if (words > shareLimit) { + return prefix + std::to_string(shareLimit) + ", the share of the program's " + std::to_string(budget.programWords) + " a clone may take"; + } + if (words > budget.remainingCloneWords) { + return prefix + "the remaining clone budget of " + std::to_string(budget.remainingCloneWords); + } + return {}; +} + +std::string cloneRefusal(const ControlFlowGraph& graph, std::uint32_t header, const std::vector& blocks) { + for (const auto blockId : blocks) { + const auto& block = graph.FindBlock(blockId); + if (graph.Dominates(blockId, header)) { + return "the region wraps around to dominating block " + std::to_string(blockId); + } + if (block.terminator.kind == TerminatorKind::IndirectBranch || block.terminator.kind == TerminatorKind::Unsupported) { + return "block " + std::to_string(blockId) + " ends in an indirect or unsupported branch"; + } + } + for (const auto& loop : graph.naturalLoops) { + const bool headerCloned = contains(blocks, loop.headerBlock); + for (const auto member : loop.blocks) { + if (headerCloned && !contains(blocks, member)) { + return "loop " + std::to_string(loop.headerBlock) + " would be cloned without its body block " + std::to_string(member); + } + } + if (!headerCloned && contains(blocks, loop.continueBlock)) { + return "the continue block " + std::to_string(loop.continueBlock) + " of loop " + std::to_string(loop.headerBlock) + " would be cloned without its header"; + } + } + return {}; +} + +void cloneBlocks(ControlFlowGraph& graph, const std::vector& blocks, const std::vector& entryEdges) { + std::map cloneOf; + for (const auto blockId : blocks) { + cloneOf.emplace(blockId, static_cast(graph.blocks.size() + cloneOf.size())); + } + std::vector clones; + clones.reserve(blocks.size()); + for (const auto blockId : blocks) { + BasicBlock copy = graph.FindBlock(blockId); + copy.id = cloneOf.at(blockId); + copy.predecessors.clear(); + copy.dominators.clear(); + copy.postDominators.clear(); + for (const auto& [original, clone] : cloneOf) { + redirectEdge(copy, original, clone); + } + clones.push_back(std::move(copy)); + } + for (auto& clone : clones) { + graph.blocks.push_back(std::move(clone)); + } + for (const auto& [predecessor, entry] : entryEdges) { + redirectEdge(graph.FindBlock(predecessor), entry, cloneOf.at(entry)); + } + rebuildPredecessors(graph); + + const auto firstClone = static_cast(graph.blocks.size() - blocks.size()); + std::vector ordered; + ordered.reserve(graph.blocks.size()); + for (std::uint32_t blockId = 0; blockId < firstClone; ++blockId) { + ordered.push_back(graph.blocks[blockId]); + } + for (const auto blockId : reversePostOrder(graph)) { + if (blockId >= firstClone) { + ordered.push_back(graph.blocks[blockId]); + } + } + if (ordered.size() != graph.blocks.size()) { + throw std::runtime_error("a cloned control flow block is unreachable"); + } + applyBlockOrder(graph, std::move(ordered)); +} + +std::optional privatizeMergeTail(const ControlFlowGraph& graph, std::uint32_t header, std::uint32_t merge, std::uint32_t& cost, const std::function& recompute) { + const auto& headerBlock = graph.FindBlock(header); + if ((headerBlock.terminator.trueBlock != merge && headerBlock.terminator.falseBlock != merge) || graph.FindBlock(merge).predecessors.size() < 2u || !hasLinearPathToTerminal(graph, merge)) { + return std::nullopt; + } + const auto tail = linearTail(graph, merge); + if (!cloneRefusal(graph, header, tail).empty()) { + return std::nullopt; + } + auto candidate = graph; + cloneBlocks(candidate, tail, {{header, merge}}); + recompute(candidate); + if (candidate.irreducible || findSelectionMerge(candidate, candidate.FindBlock(header)) == InvalidControlFlowId) { + return std::nullopt; + } + cost = estimatedSpirvWords(graph, tail); + return candidate; +} + +std::vector loopEdges(const ControlFlowGraph& graph) { + std::vector edges; + for (const auto& loop : graph.naturalLoops) { + edges.emplace_back(loop.headerBlock, loop.latchBlock); + } + std::sort(edges.begin(), edges.end()); + return edges; +} + +std::string junctionRefusal(const ControlFlowGraph& graph, std::uint32_t header, const std::vector& entered, const std::vector& routed) { + for (const auto blockId : entered) { + if (graph.Dominates(blockId, header)) { + return "the region wraps around to dominating block " + std::to_string(blockId); + } + } + for (const auto& [source, target] : routed) { + const auto kind = graph.FindBlock(source).terminator.kind; + if (kind != TerminatorKind::Branch && kind != TerminatorKind::ConditionalBranch) { + return "block " + std::to_string(source) + " ends in an indirect or unsupported branch"; + } + if (graph.Dominates(target, source)) { + return "the edge from block " + std::to_string(source) + " to block " + std::to_string(target) + " is a back edge"; + } + } + return {}; +} + +std::uint32_t appendRouteBlock(ControlFlowGraph& graph, std::uint32_t positionBlock) { + const auto& position = graph.FindBlock(positionBlock); + BasicBlock block; + block.id = static_cast(graph.blocks.size()); + block.startProgramCounter = position.startProgramCounter; + block.endProgramCounter = position.startProgramCounter; + block.instructionBegin = position.instructionBegin; + block.instructionEnd = position.instructionBegin; + graph.blocks.push_back(std::move(block)); + return graph.blocks.back().id; +} + +void setBranch(BasicBlock& block, std::uint32_t target) { + block.successors = {target}; + block.terminator.kind = TerminatorKind::Branch; + block.terminator.condition = BranchCondition::Always; + block.terminator.trueBlock = target; +} + +std::optional routeThroughJunction(const ControlFlowGraph& graph, std::uint32_t header, std::uint32_t merge, const std::vector& region, const std::vector& entered, const std::vector& entryEdges, SplitBudget& budget, const std::function& recompute, std::string& refusal) { + std::vector routed = entryEdges; + std::vector sources = {header}; + for (const auto member : region) { + if (!contains(entered, member)) { + sources.push_back(member); + } + } + for (const auto source : sources) { + for (const auto successor : graph.FindBlock(source).successors) { + if (successor == merge || contains(entered, successor)) { + routed.emplace_back(source, successor); + } + } + } + refusal = junctionRefusal(graph, header, entered, routed); + if (!refusal.empty()) { + return std::nullopt; + } + + const auto order = reversePostOrder(graph); + const auto orderOf = [&](std::uint32_t blockId) { + return std::distance(order.begin(), std::find(order.begin(), order.end(), blockId)); + }; + std::vector targets; + bool reachesMerge = false; + for (const auto& edge : routed) { + if (edge.second == merge) { + reachesMerge = true; + } else { + addUnique(targets, edge.second); + } + } + std::sort(targets.begin(), targets.end(), [&](std::uint32_t lhs, std::uint32_t rhs) { return orderOf(lhs) < orderOf(rhs); }); + if (reachesMerge) { + targets.push_back(merge); + } + + auto candidate = graph; + const auto variableCount = static_cast(targets.size() - 1u); + const auto firstVariable = budget.nextGotoVariable; + auto next = targets.back(); + for (auto index = variableCount; index-- > 0u;) { + const auto dispatch = appendRouteBlock(candidate, targets[index]); + auto& block = candidate.FindBlock(dispatch); + block.successors = {targets[index], next}; + block.terminator.kind = TerminatorKind::ConditionalBranch; + block.terminator.condition = BranchCondition::GotoVariable; + block.terminator.trueBlock = targets[index]; + block.terminator.falseBlock = next; + block.terminator.gotoVariable = firstVariable + index; + next = dispatch; + } + const auto junction = appendRouteBlock(candidate, targets.front()); + setBranch(candidate.FindBlock(junction), next); + + for (const auto& [source, target] : routed) { + const auto targetIndex = static_cast(std::distance(targets.begin(), std::find(targets.begin(), targets.end(), target))); + auto entry = junction; + for (auto index = std::min(targetIndex + 1u, variableCount); index-- > 0u;) { + const auto assignment = appendRouteBlock(candidate, target); + auto& block = candidate.FindBlock(assignment); + setBranch(block, entry); + block.terminator.gotoVariable = firstVariable + index; + block.terminator.gotoValue = index == targetIndex ? 1 : 0; + entry = assignment; + } + redirectEdge(candidate.FindBlock(source), target, entry); + } + rebuildPredecessors(candidate); + recompute(candidate); + if (candidate.irreducible || candidate.unsupported) { + refusal = "routing through a junction would make the graph irreducible"; + return std::nullopt; + } + if (loopEdges(candidate) != loopEdges(graph)) { + refusal = "routing through a junction would change the natural loops"; + return std::nullopt; + } + budget.nextGotoVariable += variableCount; + return candidate; +} + +bool structurizeEnteredRegion(ControlFlowGraph& graph, std::uint32_t header, std::uint32_t merge, const std::vector& region, SplitBudget& budget, const std::function& recompute) { + const auto entryEdges = externalEntryEdges(graph, header, region); + if (entryEdges.empty()) { + return false; + } + const auto entered = reachableWithin(graph, entryEdges, region); + const auto enteredWords = estimatedSpirvWords(graph, entered); + const auto structuralReason = cloneRefusal(graph, header, entered); + auto cloneReason = structuralReason.empty() ? cloneCostRefusal(budget, enteredWords) : structuralReason; + + std::uint32_t tailWords = 0; + if (auto privatized = privatizeMergeTail(graph, header, merge, tailWords, recompute); privatized && cloneCostRefusal(budget, tailWords).empty() && (!cloneReason.empty() || tailWords <= enteredWords)) { + budget.remainingCloneWords -= tailWords; + budget.remainingFallbackWords -= std::min(tailWords, budget.remainingFallbackWords); + graph = std::move(*privatized); + return true; + } + if (cloneReason.empty()) { + budget.remainingCloneWords -= enteredWords; + budget.remainingFallbackWords -= std::min(enteredWords, budget.remainingFallbackWords); + cloneBlocks(graph, entered, entryEdges); + return true; + } + std::string junctionReason; + if (auto routed = routeThroughJunction(graph, header, merge, region, entered, entryEdges, budget, recompute, junctionReason)) { + graph = std::move(*routed); + return true; + } + if (structuralReason.empty() && enteredWords <= budget.remainingFallbackWords) { + budget.remainingFallbackWords -= enteredWords; + cloneBlocks(graph, entered, entryEdges); + return true; + } + if (structuralReason.empty()) { + cloneReason += " and the fallback budget of " + std::to_string(budget.remainingFallbackWords); + } + throw std::runtime_error("selection header block " + std::to_string(header) + " has externally entered region block " + std::to_string(entryEdges.front().second) + " (from block " + std::to_string(entryEdges.front().first) + "): " + cloneReason + "; " + junctionReason); +} + +bool splitOneSelectionMerge(ControlFlowGraph& graph, SplitBudget& budget, const std::function& recompute) { std::vector loopHeaders; loopHeaders.reserve(graph.naturalLoops.size()); for (const auto& loop : graph.naturalLoops) { @@ -492,14 +979,8 @@ bool splitOneSelectionMerge(ControlFlowGraph& graph) { } const auto region = selectionRegion(graph, block, merge); - const auto external = std::find_if(region.begin(), region.end(), [&](std::uint32_t member) { - const auto& memberBlock = graph.FindBlock(member); - return std::any_of(memberBlock.predecessors.begin(), memberBlock.predecessors.end(), [&](std::uint32_t predecessor) { - return predecessor != blockId && !contains(region, predecessor); - }); - }); - if (external != region.end()) { - throw std::runtime_error("selection header block " + std::to_string(blockId) + " has externally entered region block " + std::to_string(*external) + "; semantic block cloning is disabled"); + if (structurizeEnteredRegion(graph, blockId, merge, region, budget, recompute)) { + return true; } const auto constructBlocks = dominatedBlocks(graph, blockId, merge); @@ -610,6 +1091,7 @@ void Structurizer::Structurize(ControlFlowGraph& graph) const { canonicalizeNaturalLoops(graph); splitSharedMergeBlocks(graph); isolateSemanticLoopHeaders(graph); + orderByDominance(graph); clearStructuredTerminators(graph); std::map mergeHeaders; @@ -858,12 +1340,21 @@ void Structurizer::canonicalizeNaturalLoops(ControlFlowGraph& graph) const { void Structurizer::splitSharedMergeBlocks(ControlFlowGraph& graph) const { const auto originalBlockCount = static_cast(graph.blocks.size()); const auto splitBudget = std::max(16u, originalBlockCount * 4u); + const auto programWords = estimatedSpirvWords(graph, allBlockIds(originalBlockCount)); + std::uint32_t nextGotoVariable = 0; + for (const auto& block : graph.blocks) { + if (block.terminator.gotoVariable != InvalidControlFlowId) { + nextGotoVariable = std::max(nextGotoVariable, block.terminator.gotoVariable + 1u); + } + } + SplitBudget budget{programWords, std::max(CloneWordLimit, programWords / CloneBudgetDivisor), std::max(CloneWordLimit, programWords), nextGotoVariable}; for (std::uint32_t splits = 0; splits < splitBudget; ++splits) { - if (!splitOneLoopMerge(graph) && !splitOneSelectionMerge(graph)) { + if (!splitOneLoopMerge(graph) && !splitOneSelectionMerge(graph, budget, [this](ControlFlowGraph& candidate) { recomputeAnalyses(candidate); })) { return; } rebuildPredecessors(graph); recomputeAnalyses(graph); + verifyReducibility(graph); } throw std::runtime_error("CFG shared merge splitting exceeded budget: originalBlocks=" + std::to_string(originalBlockCount) + " currentBlocks=" + std::to_string(graph.blocks.size()) + " splitBudget=" + std::to_string(splitBudget)); @@ -888,6 +1379,26 @@ void Structurizer::isolateSemanticLoopHeaders(ControlFlowGraph& graph) const { throw std::runtime_error("CFG semantic loop-header isolation exceeded rewrite budget"); } +void Structurizer::orderByDominance(ControlFlowGraph& graph) const { + const bool ordered = std::all_of(graph.blocks.begin(), graph.blocks.end(), [](const BasicBlock& block) { + return std::all_of(block.dominators.begin(), block.dominators.end(), [&](std::uint32_t dominator) { return dominator <= block.id; }); + }); + if (ordered) { + return; + } + const auto order = reversePostOrder(graph); + if (order.size() != graph.blocks.size()) { + throw std::runtime_error("control flow graph has unreachable blocks"); + } + std::vector blocks; + blocks.reserve(order.size()); + for (const auto blockId : order) { + blocks.push_back(graph.blocks[blockId]); + } + applyBlockOrder(graph, std::move(blocks)); + recomputeAnalyses(graph); +} + void Structurizer::clearStructuredTerminators(ControlFlowGraph& graph) const { for (auto& block : graph.blocks) { block.terminator.mergeBlock = InvalidControlFlowId;