From 1571ec69142db2ff900df1b54c53c88abf53923f Mon Sep 17 00:00:00 2001 From: SamG-Coder <13449963+SamG-Coder@users.noreply.github.com> Date: Tue, 29 Sep 2026 11:45:15 +1000 Subject: [PATCH] feat(shader): lower bounded PC-relative jump tables --- .../include/ControlFlow/ControlFlowGraph.hpp | 6 + .../ControlFlow/src/ControlFlowGraph.cpp | 1 + .../ControlFlow/src/GraphBuilder.cpp | 144 +++++++++++++++++- .../SpirvBackend/src/SpirvFlowEmitter.cpp | 2 +- .../Translation/TranslationContext.hpp | 1 + .../Translation/src/InstructionTranslator.cpp | 3 + .../ScalarBufferInstructions.cpp | 13 ++ .../src/TranslationContext/ExecMask.cpp | 9 ++ 8 files changed, 176 insertions(+), 3 deletions(-) diff --git a/core/shader/recompiler/ControlFlow/include/ControlFlow/ControlFlowGraph.hpp b/core/shader/recompiler/ControlFlow/include/ControlFlow/ControlFlowGraph.hpp index dc1eccdff..3891e7860 100644 --- a/core/shader/recompiler/ControlFlow/include/ControlFlow/ControlFlowGraph.hpp +++ b/core/shader/recompiler/ControlFlow/include/ControlFlow/ControlFlowGraph.hpp @@ -19,6 +19,7 @@ enum class BranchCondition { ExecZero, ExecNonZero, ScalarInstruction, + IndirectTarget, GotoVariable, Unknown }; @@ -96,11 +97,16 @@ struct StronglyConnectedComponent { }; struct ControlFlowGraph { + struct CodeTableLoad { + std::uint32_t programCounter = 0; + std::vector values; + }; std::vector blocks; std::vector naturalLoops; std::vector backEdges; std::vector components; std::vector codeTableLoadProgramCounters; + std::vector codeTableLoads; std::uint32_t entryBlock = InvalidControlFlowId; bool irreducible = false; bool unsupported = false; diff --git a/core/shader/recompiler/ControlFlow/src/ControlFlowGraph.cpp b/core/shader/recompiler/ControlFlow/src/ControlFlowGraph.cpp index 4caff5564..12ebb915d 100644 --- a/core/shader/recompiler/ControlFlow/src/ControlFlowGraph.cpp +++ b/core/shader/recompiler/ControlFlow/src/ControlFlowGraph.cpp @@ -107,6 +107,7 @@ std::string BranchConditionToString(BranchCondition condition) { case BranchCondition::ExecZero: return "execz"; case BranchCondition::ExecNonZero: return "execnz"; case BranchCondition::ScalarInstruction: return "scalar_instruction"; + case BranchCondition::IndirectTarget: return "indirect_target"; case BranchCondition::GotoVariable: return "goto_variable"; case BranchCondition::Unknown: return "unknown"; } diff --git a/core/shader/recompiler/ControlFlow/src/GraphBuilder.cpp b/core/shader/recompiler/ControlFlow/src/GraphBuilder.cpp index f483e799a..aa8f07281 100644 --- a/core/shader/recompiler/ControlFlow/src/GraphBuilder.cpp +++ b/core/shader/recompiler/ControlFlow/src/GraphBuilder.cpp @@ -1,5 +1,6 @@ #include "ControlFlow/GraphBuilder.hpp" #include +#include #include #include #include @@ -143,6 +144,92 @@ bool resolveSetpcTarget(const RdnaProgram& program, std::uint32_t setpcIndex, st return false; } +struct BoundedJumpTable { + ControlFlowGraph::CodeTableLoad load; + std::vector targets; + std::uint32_t firstProgramCounter = 0; +}; + +bool sameRegister(const RdnaOperand& first, const RdnaOperand& second) { + return first.kind == second.kind && first.reg == second.reg && + (first.kind == RdnaOperandKind::ScalarRegister || first.kind == RdnaOperandKind::VccLo); +} + +bool addsRegister(const RdnaInstruction& instruction, std::uint32_t reg, const RdnaOperand& other) { + return isRegister(instruction.destination, RdnaOperandKind::ScalarRegister, reg) && + ((isRegister(instruction.source0, RdnaOperandKind::ScalarRegister, reg) && sameRegister(instruction.source1, other)) || + (isRegister(instruction.source1, RdnaOperandKind::ScalarRegister, reg) && sameRegister(instruction.source0, other))); +} + +bool addsImmediate(const RdnaInstruction& instruction, std::uint32_t reg, std::uint32_t& immediate) { + return isRegister(instruction.destination, RdnaOperandKind::ScalarRegister, reg) && + ((isRegister(instruction.source0, RdnaOperandKind::ScalarRegister, reg) && isImmediate(instruction.source1, immediate)) || + (isRegister(instruction.source1, RdnaOperandKind::ScalarRegister, reg) && isImmediate(instruction.source0, immediate))); +} + +bool resolveJumpTable(const RdnaProgram& program, std::uint32_t index, BoundedJumpTable& result) { + if (index < 9u) return false; + const auto& branch = program.instructions[index]; + if (branch.source0.kind != RdnaOperandKind::ScalarRegister) return false; + const auto pcReg = branch.source0.reg; + const auto& pc = program.instructions[index - 3u]; + const auto& low = program.instructions[index - 2u]; + const auto& high = program.instructions[index - 1u]; + if (pc.op != RdnaOpcode::SGetpcB64 || !isRegister(pc.destination, RdnaOperandKind::ScalarRegister, pcReg) || + low.op != RdnaOpcode::SAddU32 || high.op != RdnaOpcode::SAddcU32) return false; + for (std::uint32_t loadIndex = index - 3u; loadIndex-- > 5u;) { + const auto& load = program.instructions[loadIndex]; + if (load.op != RdnaOpcode::SLoadDwordx2) { + if (load.op == RdnaOpcode::SWaitcnt) continue; + if (load.family == RdnaInstructionFamily::VOP1 || load.family == RdnaInstructionFamily::VOP2 || + load.family == RdnaInstructionFamily::VOP3 || load.family == RdnaInstructionFamily::VOPC) { + if (load.destination.kind != RdnaOperandKind::ScalarRegister && load.destination2.kind != RdnaOperandKind::ScalarRegister) continue; + } + return false; + } + if (load.destination.kind != RdnaOperandKind::ScalarRegister || load.source0.kind != RdnaOperandKind::ScalarRegister) return false; + auto loadedHigh = load.destination; + ++loadedHigh.reg; + if (!addsRegister(low, pcReg, load.destination) || !addsRegister(high, pcReg + 1u, loadedHigh)) return false; + if (pcReg <= loadedHigh.reg && load.destination.reg <= pcReg + 1u) return false; + const auto& basePc = program.instructions[loadIndex - 3u]; + const auto& baseLow = program.instructions[loadIndex - 2u]; + const auto& baseHigh = program.instructions[loadIndex - 1u]; + const auto& shift = program.instructions[loadIndex - 4u]; + const auto& bound = program.instructions[loadIndex - 5u]; + const auto baseReg = load.source0.reg; + std::uint32_t displacement = 0, carry = 0, shiftAmount = 0, maximum = 0; + if (basePc.op != RdnaOpcode::SGetpcB64 || !isRegister(basePc.destination, RdnaOperandKind::ScalarRegister, baseReg) || + baseLow.op != RdnaOpcode::SAddU32 || !addsImmediate(baseLow, baseReg, displacement) || + baseHigh.op != RdnaOpcode::SAddcU32 || !addsImmediate(baseHigh, baseReg + 1u, carry) || carry != 0u || + shift.op != RdnaOpcode::SLshlB32 || !sameRegister(shift.destination, load.source1) || + !sameRegister(shift.source0, load.source1) || !isImmediate(shift.source1, shiftAmount) || shiftAmount != 3u || + bound.op != RdnaOpcode::SMinU32 || !sameRegister(bound.destination, load.source1) || + !sameRegister(bound.source0, load.source1) || !isImmediate(bound.source1, maximum) || maximum > 255u) return false; + if (load.source1.kind == RdnaOperandKind::ScalarRegister && load.source1.reg >= baseReg && load.source1.reg <= baseReg + 1u) return false; + for (const auto& instruction : program.instructions) { + if (IsDirectBranchOpcode(instruction.op) && instruction.branchTarget > bound.programCounter && instruction.branchTarget <= branch.programCounter) return false; + } + const std::uint64_t table = static_cast(instructionEndProgramCounter(basePc)) + displacement + load.memoryOffset; + const std::uint64_t byteCount = (static_cast(maximum) + 1u) * 8u; + if ((table & 3u) != 0u || table > program.code.size_bytes() || byteCount > program.code.size_bytes() - table) return false; + result.load.programCounter = load.programCounter; + result.firstProgramCounter = bound.programCounter; + for (std::uint32_t entry = 0; entry <= maximum; ++entry) { + const auto word = static_cast(table / 4u) + entry * 2u; + const std::uint64_t value = program.code[word] | (static_cast(program.code[word + 1u]) << 32u); + const auto offset = std::bit_cast(value); + if (offset < -static_cast(instructionEndProgramCounter(pc)) || offset > UINT32_MAX) return false; + const auto target = static_cast(static_cast(instructionEndProgramCounter(pc)) + offset); + if (target < instructionEndProgramCounter(branch) || target > UINT32_MAX || (target & 3u) != 0u) return false; + result.load.values.push_back(value); + result.targets.push_back(static_cast(target)); + } + return true; + } + return false; +} + BranchCondition conditionForOpcode(RdnaOpcode opcode) { switch (opcode) { case RdnaOpcode::SBranch: return BranchCondition::Always; @@ -255,7 +342,14 @@ std::vector GraphBuilder::splitIntoBlocks(const RdnaProgram& program } else if (instruction.op == RdnaOpcode::SSetpcB64) { std::uint32_t target = 0; if (!resolveSetpcTarget(program, index, target)) { - throw std::invalid_argument("unsupported dynamic s_setpc_b64 at program counter " + toHexString(instruction.programCounter)); + BoundedJumpTable table; + if (!resolveJumpTable(program, index, table)) throw std::invalid_argument("unsupported dynamic s_setpc_b64 at program counter " + toHexString(instruction.programCounter)); + for (const auto tableTarget : table.targets) { + if (!instructionProgramCounters.contains(tableTarget)) throw std::invalid_argument("jump table targets invalid instruction boundary " + toHexString(tableTarget)); + labels.insert(tableTarget); + } + labels.insert(nextProgramCounter); + continue; } if (!isValidTarget(target, instructionProgramCounters, firstProgramCounter, endProgramCounter)) { throw std::invalid_argument("s_setpc_b64 at program counter " + toHexString(instruction.programCounter) + " targets invalid program counter " + toHexString(target)); @@ -315,7 +409,17 @@ void GraphBuilder::linkBlocks(std::vector& blocks, const RdnaProgram } else if (last.op == RdnaOpcode::SSetpcB64) { std::uint32_t target = 0; if (!resolveSetpcTarget(program, block.instructionEnd - 1u, target)) { - throw std::invalid_argument("unsupported dynamic s_setpc_b64 at program counter " + toHexString(last.programCounter)); + BoundedJumpTable table; + if (!resolveJumpTable(program, block.instructionEnd - 1u, table)) throw std::invalid_argument("unsupported dynamic s_setpc_b64 at program counter " + toHexString(last.programCounter)); + block.terminator.kind = TerminatorKind::IndirectBranch; + block.terminator.indirectPcSgpr = last.source0.reg; + sortUnique(table.targets); + for (const auto tableTarget : table.targets) { + block.terminator.indirectTargetProgramCounters.push_back(tableTarget); + block.terminator.indirectTargets.push_back(programCounterToBlock.at(tableTarget)); + addUnique(block.successors, programCounterToBlock.at(tableTarget)); + } + continue; } block.terminator.kind = TerminatorKind::Branch; block.terminator.condition = BranchCondition::Always; @@ -373,6 +477,42 @@ ControlFlowGraph GraphBuilder::Build(const RdnaProgram& program) const { ControlFlowGraph graph; graph.blocks = splitIntoBlocks(program); linkBlocks(graph.blocks, program); + const auto originalSize = graph.blocks.size(); + for (std::uint32_t id = 0; id < originalSize; ++id) { + const auto term = graph.blocks[id].terminator; + if (term.kind != TerminatorKind::IndirectBranch) continue; + BoundedJumpTable table; + if (!resolveJumpTable(program, graph.blocks[id].instructionEnd - 1u, table)) throw std::logic_error("jump table resolution changed"); + if (table.firstProgramCounter < graph.blocks[id].startProgramCounter) throw std::invalid_argument("jump table bound does not dominate its branch in the same block"); + graph.codeTableLoadProgramCounters.push_back(table.load.programCounter); + graph.codeTableLoads.push_back(std::move(table.load)); + auto current = id; + for (std::size_t entry = 0; entry < term.indirectTargets.size(); ++entry) { + const bool last = entry + 1u == term.indirectTargets.size(); + const auto next = static_cast(graph.blocks.size()); + auto& block = graph.blocks[current]; + block.terminator = Terminator{}; + block.terminator.kind = last ? TerminatorKind::Branch : TerminatorKind::ConditionalBranch; + block.terminator.condition = last ? BranchCondition::Always : BranchCondition::IndirectTarget; + block.terminator.trueBlock = term.indirectTargets[entry]; + block.terminator.indirectPcSgpr = term.indirectPcSgpr; + block.terminator.indirectTargetProgramCounters = {term.indirectTargetProgramCounters[entry]}; + block.successors = {term.indirectTargets[entry]}; + if (!last) { + block.terminator.falseBlock = next; + block.successors.push_back(next); + BasicBlock comparison; + comparison.id = next; + comparison.startProgramCounter = block.endProgramCounter; + comparison.endProgramCounter = block.endProgramCounter; + comparison.instructionBegin = block.instructionEnd; + comparison.instructionEnd = block.instructionEnd; + graph.blocks.push_back(std::move(comparison)); + current = next; + } + } + } + rebuildPredecessors(graph); graph.entryBlock = 0; pruneUnreachableBlocks(graph); for (auto& block : graph.blocks) { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp index 8162a4551..a4624f0ea 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp @@ -120,7 +120,7 @@ bool IsContinueTarget(const IrProgram& program, std::uint32_t block) { } std::uint32_t EmitBranchCondition(SpirvValueEmitContext& ctx, const BlockInfo& info) { - if (ctx.otherHalf == nullptr || info.terminator.condition == BranchCondition::ScalarInstruction || info.terminator.condition == BranchCondition::GotoVariable) { + if (ctx.otherHalf == nullptr || info.terminator.condition == BranchCondition::ScalarInstruction || info.terminator.condition == BranchCondition::GotoVariable || info.terminator.condition == BranchCondition::IndirectTarget) { return ctx.Def(info.condition); } auto& state = ctx.state; diff --git a/core/shader/recompiler/Translation/include/Translation/TranslationContext.hpp b/core/shader/recompiler/Translation/include/Translation/TranslationContext.hpp index 73e1d092e..b0371fbf3 100644 --- a/core/shader/recompiler/Translation/include/Translation/TranslationContext.hpp +++ b/core/shader/recompiler/Translation/include/Translation/TranslationContext.hpp @@ -15,6 +15,7 @@ public: void SetPixelInput(const ShaderPixelInputInfo* info) { pixelInput = info; } void TranslateEmbeddedFetch(const RdnaInstruction& instruction, std::uint32_t attribute, std::uint32_t componentCount, const ShaderBufferResource& resource); void AddBranchCondition(const BasicBlock& source, BlockInfo& info); + void TranslateCodeTableLoad(const RdnaInstruction& instruction, const ControlFlowGraph::CodeTableLoad& table); private: struct AddressOperands { diff --git a/core/shader/recompiler/Translation/src/InstructionTranslator.cpp b/core/shader/recompiler/Translation/src/InstructionTranslator.cpp index 7f898e969..e0739b5fe 100644 --- a/core/shader/recompiler/Translation/src/InstructionTranslator.cpp +++ b/core/shader/recompiler/Translation/src/InstructionTranslator.cpp @@ -443,6 +443,9 @@ IrProgram InstructionTranslator::Translate(const RdnaProgram& decoded, const Con for (std::uint32_t index = cfgBlock.instructionBegin; index < cfgBlock.instructionEnd; index++) { const auto& instruction = decoded.instructions[index]; if (isCodeTableLoad(cfg, instruction.programCounter)) { + const auto table = std::find_if(cfg.codeTableLoads.begin(), cfg.codeTableLoads.end(), [&](const auto& entry) { return entry.programCounter == instruction.programCounter; }); + if (table == cfg.codeTableLoads.end()) throw std::runtime_error("missing shader code table values"); + context.TranslateCodeTableLoad(instruction, *table); continue; } const auto* embedded = findEmbeddedFetchLoad(options.embeddedFetch, instruction.programCounter); diff --git a/core/shader/recompiler/Translation/src/MemoryInstructions/ScalarBufferInstructions.cpp b/core/shader/recompiler/Translation/src/MemoryInstructions/ScalarBufferInstructions.cpp index 7ae52737c..d97478e6b 100644 --- a/core/shader/recompiler/Translation/src/MemoryInstructions/ScalarBufferInstructions.cpp +++ b/core/shader/recompiler/Translation/src/MemoryInstructions/ScalarBufferInstructions.cpp @@ -52,4 +52,17 @@ bool TranslationContext::sLoad(const RdnaInstruction& inst, bool raw) { return true; } +void TranslationContext::TranslateCodeTableLoad(const RdnaInstruction& instruction, const ControlFlowGraph::CodeTableLoad& table) { + if (table.values.empty()) throw std::runtime_error("empty shader code table"); + const IrU32 index = readRawU32(instruction.source1); + IrU32 low(ir.Constant(static_cast(table.values.back()))); + IrU32 high(ir.Constant(static_cast(table.values.back() >> 32u))); + for (std::size_t entry = table.values.size() - 1u; entry-- > 0u;) { + auto& matches = ir.IEqual(index.Value(), ir.Constant(static_cast(entry * 8u))); + low = IrU32(ir.Select(matches, ir.Constant(static_cast(table.values[entry])), low.Value())); + high = IrU32(ir.Select(matches, ir.Constant(static_cast(table.values[entry] >> 32u)), high.Value())); + } + writeU32Pair(instruction.destination, {low, high}); +} + } diff --git a/core/shader/recompiler/Translation/src/TranslationContext/ExecMask.cpp b/core/shader/recompiler/Translation/src/TranslationContext/ExecMask.cpp index 07068c4c1..26e4a0c88 100644 --- a/core/shader/recompiler/Translation/src/TranslationContext/ExecMask.cpp +++ b/core/shader/recompiler/Translation/src/TranslationContext/ExecMask.cpp @@ -146,6 +146,15 @@ void TranslationContext::AddBranchCondition(const BasicBlock& source, BlockInfo& case BranchCondition::VccNonZero: condition = IrU1(ir.GetVcc()); break; case BranchCondition::ExecZero: condition = IrU1(ir.LogicalNot(ir.GetExec())); break; case BranchCondition::ExecNonZero: condition = IrU1(ir.GetExec()); break; + case BranchCondition::IndirectTarget: { + if (source.terminator.indirectTargetProgramCounters.size() != 1u || source.terminator.indirectPcSgpr == InvalidControlFlowId) { + throw std::runtime_error("invalid lowered indirect branch"); + } + auto& base = ir.Emit(IrOpcode::GetShaderBase, IrType::U64, {}); + const IrU64 target(ir.Emit(IrOpcode::IAdd64, IrType::U64, {&base, &ir.ConstantU64(source.terminator.indirectTargetProgramCounters.front())})); + condition = IrU1(ir.IEqual(ir.GetScalarReg(static_cast(source.terminator.indirectPcSgpr)), extractU64(target)[0].Value())); + break; + } case BranchCondition::ScalarInstruction: if (instructionBranchCondition.Value().IsEmpty()) { throw std::runtime_error("TranslationContext::AddBranchCondition block " + std::to_string(source.id) + " has no scalar branch condition");