Files
psxrecomp/recompiler/src/control_flow.cpp
T
Matthew Stanley 80ff96780a recompiler: the overlay guard word is a delay-slot source, never a block leader
The overlay capture format DELIBERATELY appends one coherent guard instruction
past the end of a dirty-page run (overlay_capture.c write_json_window, `size
+= 4u`, pinned by runtime/tests/test_interpreter_perf_guards.py:47): a MIPS
branch sitting at the run's final word (...FFC) always executes its delay slot
in the next page (...000), and the shard must be able to emit and hash that
word. So a capture whose size is a page multiple PLUS 4 is a CORRECT capture --
N bytes of overlay plus one guard word. Measured: 36 of 36 Ape Escape
(SCUS-94423) vault records and 846 of 946 Tomba 2 (SCUS-94454) records are that
shape.

The recompiler was never taught the asymmetry: the guard word is a legal
DELAY-SLOT SOURCE but an ILLEGAL BLOCK LEADER, because the word after it does
not exist in the image. It had exactly one bound -- end_address() -- used both
to read words and to decide what is code.

MEASURED on Ape Escape, its own single-source vault at framework
v0.3.2-alpha-139-g1bf70960, 36 variants:

  PSX_SHARD_RESULT ok=50 failed=17 skipped=32 capacity_fastpath=0

  ! [recompiler] overlay 0x80136000 crc 4BAB23C9: what():  cannot emit control
    flow at 0x80138000: mandatory delay slot 0x80138004 is outside the input
    image
  + 16 x [fragment] interior 0x801360.. @region 0x00136000, identical message

One root cause, seventeen shards. The whole region then falls back to the
dirty-RAM interpreter forever, and nothing at runtime says so.

Causal chain, every step read in source:

  1. overlay_capture.c:349-361 appends the guard word; region 0x80136000 gets
     size 0x2004, so the image is [0x80136000, 0x80138004).
  2. compile_overlays.py make_psxexe wraps those bytes verbatim with text size
     = len(data), so PS1Executable::end_address() = 0x80138004.
  3. function_analysis.cpp in_exe / in_function admit 0x80138000 as ordinary
     code, and the walk reaches it by fall-through from 0x80137FFC
     (0x24022000, addiu -- not control flow), so func.end_addr becomes the
     image end.
  4. control_flow.cpp makes the final block end_addr = func.end_addr - 4 =
     0x80138000: the block LEADER is the guard word.
  5. control_flow.cpp's "Also check last instruction itself" promotion finds
     0x80137FFC is not control flow and therefore promotes read_word(end_addr)
     -- the guard word 0x1062005A, a beq -- to block.exit_instr, with
     has_delay_slot = true and address == end_addr. THIS IS THE DEFECT.
  6. code_generator.cpp computes delay_slot_addr = 0x80138004, read_word
     returns nullopt, and it throws.

THE THROW AT STEP 6 IS CORRECT AND IS PRESERVED. Emitting a control transfer
without its architectural delay slot silently corrupts guest state, which is
what the code did before that throw was added. The gap is step 5.

Fix: give the image view two distinct bounds.

  end_address()           READ bound -- every byte the image supplies, so a
                          mandatory delay slot living at a guard word resolves.
  analysis_end_address()  ANALYSIS bound -- one past the last byte that may be
                          discovered, made a block leader, or made a block's
                          exit instruction.

read_word() keeps the READ bound. Discovery and block construction move to the
ANALYSIS bound: function_analysis.cpp in_exe / in_exe_p3 / add_forced_entry /
every hard_cap that used to be the image end / the jr-table producer_hi
defaults / the static jr-ra and JAL sweeps; control_flow.cpp gains
analysis_walk_hi(func) and uses it for cfg.function_end, alias entries,
add_boundary, the scan loop, the final block's end_addr and in_func;
code_generator.cpp's mid-function split pre-pass; main_psx.cpp seed admission
and the data-scan pointer promotion; analysis_db.cpp, main_toml.cpp,
main_cli.cpp target/seed admission. The clamp is applied only when it leaves a
non-empty walk, so a degenerate function starting at or past the bound keeps
failing closed rather than silently producing an empty CFG.

HOW THE BOUND IS DERIVED -- the producer STATES it; the recompiler is told.

The alternative was for the recompiler to infer the count from `size % 4096 ==
4`. That fits every capture the current writer has ever produced, but it is a
consumer guessing at a producer's intent, and this tree already has the
counter-example: 52 of the 946 SCUS-94454 records have residues from 112 to
3996 bytes (one not even 4-byte aligned) because they come from the STATIC
extractor, which records an exact file extent and appends no guard word. A rule
keyed to the page-run shape is a rule that shifts the moment a producer
changes.

So the count travels with the image, in a magic-tagged field in the otherwise
zero-filled tail of the 2048-byte PS-EXE header (exe_tag in ps1_exe_parser.h:
"PSXRGRD1" at 0x7E0, uint32 count at 0x7E8). Putting it in the header rather
than on the command line means every consumer gets it automatically and no
future invocation path can forget to pass it -- compile_overlays has three
make_psxexe sites and five recompiler spawn sites. An absent or malformed tag
means ZERO guard bytes, which is exactly what every genuine PS-X EXE is: the
BIOS and every retail main executable have no guard word, their analysis bound
equals their read bound, and their analysis is bit-for-bit unchanged.

Producer side:
  overlay_capture.c    writes "guard_bytes": 4|0 per region -- the writer
                       stating its own intent, additive to the v2 schema and
                       preserved through coverage_vault.py compaction.
  compile_overlays.py  capture_guard_bytes(): prefer that field; for captures
                       recorded before it existed, reconstruct the single
                       shape write_json_window can produce (page multiple + 4)
                       and return 0 for everything else, which is the
                       fail-closed answer -- an unrecognised guard word is
                       analysed as code and the step-6 throw still fires
                       loudly at generation time.
  make_psxexe          guard_bytes is keyword-only with NO default, so a new
                       call site is a TypeError, not a silently mis-analysed
                       shard. The count is threaded through
                       compile_fragment_batch / compile_interior_fragment /
                       generate_interior_fragment_static and into the fragment
                       fail-memo key (bumped to v3, so a memo recorded under
                       the old analysis cannot suppress a retry under the
                       corrected one).

SECOND-ORDER DEFECT FIXED IN THE SAME PASS. generate_ranges_manifest extends a
range by +4 for any block whose exit instruction IS its last word, so the
cloned delay slot joins the candidate CRC and the page-generation watch. That
extension was unclamped. Reachable TODAY, independent of the guard word: a
branch-likely opcode (0x14-0x17, RESERVED on the R3000A) as the image's very
last word is short-circuited by translate_basic_block into an inline RI raise
BEFORE any delay slot is read, so generation succeeds and the manifest claims 4
bytes past the image end. Measured on origin/master with a 28-byte synthetic
image: `R 80010000 20` for an image ending at 0x8001001C. The cache would then
validate the shard against bytes the shard never saw. Now clamped to the READ
bound -- not the analysis bound, because a guard word genuinely IS compiled in
when it serves as a delay slot and must participate in the CRC.

DEAD CODE, documented rather than trusted: basic_block.cpp's BasicBlockAnalyzer
bounds its walk correctly but nothing in the tree constructs it. It is still
compiled and still hashed into the codegen tag, so a change there invalidates
caches without moving an emitted byte. Its bounds move to the analysis bound
too -- wiring it up must not reintroduce this defect -- and a header comment now
says where the live walker actually is.

TESTS. Both registered, so ctest runs them and the configure-time
registration guard is satisfied.

recompiler/tests/test_overlay_guard_word_analysis_bound.py drives
psxrecomp-game over five synthetic images:
  A  tagged, 2 pages + guard word, last real word not control flow, guard word
     IS a beq -- the measured Ape shape. Must generate; the guard word must not
     be emitted as an instruction; the block must publish 0x80012000 for the
     runtime to dispatch; no range may claim it.
  B  byte-for-byte the same payload with NO tag. Must still fail closed with
     the mandatory-delay-slot diagnostic naming 0x80012000. A and B differ only
     in the header tag, which proves the tag is what changed behaviour and that
     the throw was not weakened.
  B2 a misaligned declaration (6). Must be rejected and behave like B.
  C  tagged, with a real branch at the last analysable word. The guard word
     must be emitted AS the delay slot and must be covered by the manifest.
  D  branch-likely as the final word. Generation must succeed and no range may
     exceed the image end.

Against origin/master's psxrecomp-game the same file reports exactly the two
things this commit changes, and passes B, B2 and C:
  FAIL: tagged guard word still fails generation: what():  cannot emit control
        flow at 0x80012000: mandatory delay slot 0x80012004 is outside the
        input image
  FAIL: range [0x80010000,0x80010020) claims 4 byte(s) past the image end
        0x8001001C

tools/tests/test_overlay_guard_bytes_declaration.py pins the producer half:
field precedence, the reconstruction table, rejection of nonsense
declarations, the tag's byte offsets, that make_psxexe with guard_bytes=0 is
byte-identical to the pre-fix wrapper, and that overlay_capture.c both appends
the guard word and now declares it.

MEASURED OUTCOME, Ape Escape, same vault, same flags, fresh cache:
  before  PSX_SHARD_RESULT ok=50 failed=17 skipped=32 capacity_fastpath=0
  after   PSX_SHARD_RESULT ok=31 failed=0  skipped=57 capacity_fastpath=0

ok falls because 19 isolated island fragment shards at 0x00136000 are no longer
needed once the region variant compiles as one shard. Coverage is what matters,
and it is measured from the DLL exports: 349 -> 361 unique func_XXXXXXXX
entries, ZERO lost, 12 gained -- 0x80136140, 0x8013614C, 0x80136154,
0x80136238, 0x801362D4, 0x801362DC, 0x801362F0, 0x80136324, 0x80136370,
0x80136400, 0x80136480, 0x80137950, all from the failure list. The other four
failing PCs were already served by a sibling variant's shard.

INERTNESS.
  BIOS (SCPH1001, psxrecomp-bios --config bios/SCPH1001.toml): all four
  generated artifacts BYTE-IDENTICAL, verified by sha256 rather than by exit
  code, because tools/regen_bios.sh exits 0 on failure.
  Tomba 2 main EXE (psxrecomp-game --config game.toml): all nine generated
  artifacts BYTE-IDENTICAL, and the console log is identical too.
  Tomba 2 overlays, 82 variants over 6 regions from its own vault: identical
  result line (ok=98 failed=0 skipped=103) and identical shard identity set,
  4901 unique func exports on both sides -- zero gained, zero lost. 97 of 98
  range manifests are byte-identical. The one that differs is region
  0x8010A000 variant A32DB188, size 0x2004, whose last function's range goes
  from 0x218 to 0x214 bytes: its guard word (0x24840008, addiu) had been
  emitted as an ordinary instruction and hashed, and now is not. That is
  precisely the intended change and nothing else moved.

Bead beads-eio.3.100.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 15:35:24 -07:00

544 lines
20 KiB
C++

#include "control_flow.h"
#include <algorithm>
#include <fmt/format.h>
namespace PSXRecomp {
ControlFlowAnalyzer::ControlFlowAnalyzer(const PS1Executable& exe) : exe_(exe) {}
bool ControlFlowAnalyzer::is_control_flow(uint32_t instr) {
uint32_t opcode = (instr >> 26) & 0x3F;
// SPECIAL opcode (0x00) - check funct for jr/jalr
if (opcode == 0x00) {
uint32_t funct = instr & 0x3F;
return (funct == 0x08 || funct == 0x09); // jr or jalr
}
// REGIMM opcode (0x01) - bltz, bgez, bltzal, bgezal
if (opcode == 0x01) {
return true;
}
// Branch instructions
if (opcode >= 0x04 && opcode <= 0x07) {
return true; // beq, bne, blez, bgtz
}
// Branch likely variants (0x14-0x17)
if (opcode >= 0x14 && opcode <= 0x17) {
return true; // beql, bnel, blezl, bgtzl
}
// Jump instructions
if (opcode == 0x02 || opcode == 0x03) {
return true; // j, jal
}
return false;
}
uint32_t ControlFlowAnalyzer::get_branch_target(uint32_t pc, uint32_t instr) {
// Branch target = (PC + 4) + (sign_extend(offset) << 2)
int16_t offset = (int16_t)(instr & 0xFFFF);
int32_t byte_offset = ((int32_t)offset) << 2;
return (pc + 4) + byte_offset;
}
uint32_t ControlFlowAnalyzer::get_jump_target(uint32_t pc, uint32_t instr) {
// Jump target = (PC+4)[31:28] | (instr_index << 2)
uint32_t instr_index = instr & 0x03FFFFFF;
uint32_t target = (instr_index << 2);
uint32_t upper_bits = (pc + 4) & 0xF0000000;
return upper_bits | target;
}
ControlFlowInstr ControlFlowAnalyzer::analyze_instruction(uint32_t addr, uint32_t instr) {
ControlFlowInstr cf;
cf.address = addr;
cf.instruction = instr;
cf.type = ControlFlowType::None;
cf.target = 0;
cf.has_delay_slot = false;
cf.is_likely = false;
uint32_t opcode = (instr >> 26) & 0x3F;
uint32_t rs = (instr >> 21) & 0x1F;
uint32_t rt = (instr >> 16) & 0x1F;
uint32_t funct = instr & 0x3F;
// SPECIAL opcode - jr/jalr
if (opcode == 0x00) {
if (funct == 0x08) { // jr
cf.type = (rs == 31) ? ControlFlowType::Return : ControlFlowType::JumpRegister;
cf.has_delay_slot = true;
cf.mnemonic = "jr";
return cf;
} else if (funct == 0x09) { // jalr
cf.type = ControlFlowType::JumpLinkReg;
cf.has_delay_slot = true;
cf.mnemonic = "jalr";
return cf;
}
}
// REGIMM opcode - bltz, bgez, bltzal, bgezal
if (opcode == 0x01) {
cf.type = ControlFlowType::Branch;
cf.target = get_branch_target(addr, instr);
cf.has_delay_slot = true;
cf.mnemonic = (rt == 0x00) ? "bltz" :
(rt == 0x01) ? "bgez" :
(rt == 0x10) ? "bltzal" : "bgezal";
return cf;
}
// Branch instructions
switch (opcode) {
case 0x04: // beq
cf.type = ControlFlowType::Branch;
cf.target = get_branch_target(addr, instr);
cf.has_delay_slot = true;
cf.mnemonic = "beq";
break;
case 0x05: // bne
cf.type = ControlFlowType::Branch;
cf.target = get_branch_target(addr, instr);
cf.has_delay_slot = true;
cf.mnemonic = "bne";
break;
case 0x06: // blez
cf.type = ControlFlowType::Branch;
cf.target = get_branch_target(addr, instr);
cf.has_delay_slot = true;
cf.mnemonic = "blez";
break;
case 0x07: // bgtz
cf.type = ControlFlowType::Branch;
cf.target = get_branch_target(addr, instr);
cf.has_delay_slot = true;
cf.mnemonic = "bgtz";
break;
// Branch likely variants
case 0x14: // beql
cf.type = ControlFlowType::Branch;
cf.target = get_branch_target(addr, instr);
cf.has_delay_slot = true;
cf.is_likely = true;
cf.mnemonic = "beql";
break;
case 0x15: // bnel
cf.type = ControlFlowType::Branch;
cf.target = get_branch_target(addr, instr);
cf.has_delay_slot = true;
cf.is_likely = true;
cf.mnemonic = "bnel";
break;
case 0x16: // blezl
cf.type = ControlFlowType::Branch;
cf.target = get_branch_target(addr, instr);
cf.has_delay_slot = true;
cf.is_likely = true;
cf.mnemonic = "blezl";
break;
case 0x17: // bgtzl
cf.type = ControlFlowType::Branch;
cf.target = get_branch_target(addr, instr);
cf.has_delay_slot = true;
cf.is_likely = true;
cf.mnemonic = "bgtzl";
break;
// Jump instructions
case 0x02: // j
cf.type = ControlFlowType::Jump;
cf.target = get_jump_target(addr, instr);
cf.has_delay_slot = true;
cf.mnemonic = "j";
break;
case 0x03: // jal
cf.type = ControlFlowType::JumpLink;
cf.target = get_jump_target(addr, instr);
cf.has_delay_slot = true;
cf.mnemonic = "jal";
break;
}
return cf;
}
uint32_t ControlFlowAnalyzer::analysis_walk_hi(const Function& func) const {
const uint32_t analysis_hi = exe_.analysis_end_address();
const uint32_t walk_lo =
func.alias_walk_lo ? func.alias_walk_lo : func.start_addr;
// Only clamp when the clamp still leaves a non-empty walk. A function that
// begins at or past the analysis bound is a degenerate discovery artefact;
// leave its range alone so the emitter's mandatory-delay-slot check keeps
// failing closed on it rather than silently producing an empty CFG.
if (func.end_addr > analysis_hi && analysis_hi > walk_lo) return analysis_hi;
return func.end_addr;
}
// NOTE: find_block_boundaries / build_basic_blocks / link_basic_blocks /
// detect_loops below are NOT on the live path — analyze_function does its own
// single-pass walk (see the comment there). They are kept in sync with the
// analysis bound anyway so wiring them up can never reintroduce the
// guard-word-as-block-leader defect.
std::set<uint32_t> ControlFlowAnalyzer::find_block_boundaries(const Function& func) {
std::set<uint32_t> boundaries;
const uint32_t walk_hi = analysis_walk_hi(func);
// Function start is always a boundary
boundaries.insert(func.start_addr);
// Scan all instructions in function
uint32_t addr = func.start_addr;
while (addr < walk_hi) {
auto instr_opt = exe_.read_word(addr);
if (!instr_opt.has_value()) {
break;
}
uint32_t instr = *instr_opt;
if (is_control_flow(instr)) {
ControlFlowInstr cf = analyze_instruction(addr, instr);
// If branch/jump has a target, target is a boundary
if (cf.target != 0 && cf.target >= func.start_addr && cf.target < walk_hi) {
boundaries.insert(cf.target);
}
// Instruction after delay slot is a boundary (for branches, not jumps)
if (cf.type == ControlFlowType::Branch ||
cf.type == ControlFlowType::JumpLink ||
cf.type == ControlFlowType::JumpLinkReg) {
uint32_t fall_through = addr + 8; // After delay slot
if (fall_through < walk_hi) {
boundaries.insert(fall_through);
}
}
// For unconditional jump/return, next instruction is unreachable
// (unless it's a jump target from elsewhere)
if (cf.type == ControlFlowType::Jump ||
cf.type == ControlFlowType::JumpRegister ||
cf.type == ControlFlowType::Return) {
uint32_t after_delay = addr + 8;
if (after_delay < walk_hi) {
boundaries.insert(after_delay);
}
}
}
addr += 4;
}
return boundaries;
}
std::map<uint32_t, BasicBlock> ControlFlowAnalyzer::build_basic_blocks(
const Function& func,
const std::set<uint32_t>& boundaries) {
std::map<uint32_t, BasicBlock> blocks;
const uint32_t walk_hi = analysis_walk_hi(func);
std::vector<uint32_t> boundary_vec(boundaries.begin(), boundaries.end());
std::sort(boundary_vec.begin(), boundary_vec.end());
for (size_t i = 0; i < boundary_vec.size(); i++) {
BasicBlock block;
block.start_addr = boundary_vec[i];
if (i + 1 < boundary_vec.size()) {
block.end_addr = boundary_vec[i + 1] - 4;
} else {
block.end_addr = walk_hi - 4;
}
if (block.end_addr < block.start_addr) continue;
block.instruction_count = (block.end_addr - block.start_addr) / 4 + 1;
block.is_entry = (block.start_addr == func.start_addr);
block.is_exit = false;
block.is_loop_header = false;
// Analyze exit instruction (last instruction in block)
auto exit_instr_opt = exe_.read_word(block.end_addr);
if (exit_instr_opt.has_value()) {
block.exit_instr = analyze_instruction(block.end_addr, *exit_instr_opt);
// If last instruction is not control flow, check if it's a delay slot
// (i.e., the instruction before it is a branch/jump with delay slot)
if (block.exit_instr.type == ControlFlowType::None &&
block.end_addr > block.start_addr) {
auto branch_instr_opt = exe_.read_word(block.end_addr - 4);
if (branch_instr_opt.has_value()) {
ControlFlowInstr branch_cf = analyze_instruction(block.end_addr - 4, *branch_instr_opt);
if (branch_cf.type != ControlFlowType::None && branch_cf.has_delay_slot) {
block.exit_instr = branch_cf;
}
}
}
block.is_exit = (block.exit_instr.type == ControlFlowType::Return);
} else {
block.exit_instr.type = ControlFlowType::None;
}
blocks[block.start_addr] = block;
}
return blocks;
}
void ControlFlowAnalyzer::link_basic_blocks(std::map<uint32_t, BasicBlock>& blocks) {
for (auto& [addr, block] : blocks) {
ControlFlowInstr& cf = block.exit_instr;
// Add successors based on control flow type
if (cf.type == ControlFlowType::Branch) {
// Branch has two successors: target and fall-through
if (cf.target != 0 && blocks.count(cf.target)) {
block.successors.push_back(cf.target);
blocks[cf.target].predecessors.push_back(addr);
}
// Fall-through (after delay slot)
uint32_t fall_through = cf.address + 8;
if (blocks.count(fall_through)) {
block.successors.push_back(fall_through);
blocks[fall_through].predecessors.push_back(addr);
}
} else if (cf.type == ControlFlowType::Jump) {
// Unconditional jump - only target
if (cf.target != 0 && blocks.count(cf.target)) {
block.successors.push_back(cf.target);
blocks[cf.target].predecessors.push_back(addr);
}
} else if (cf.type == ControlFlowType::JumpLink || cf.type == ControlFlowType::JumpLinkReg) {
// Function call - continues after delay slot
uint32_t fall_through = cf.address + 8;
if (blocks.count(fall_through)) {
block.successors.push_back(fall_through);
blocks[fall_through].predecessors.push_back(addr);
}
} else if (cf.type == ControlFlowType::JumpRegister && cf.type != ControlFlowType::Return) {
// Register jump (not return) - unknown target, no successors
} else if (cf.type == ControlFlowType::Return) {
// Return - no successors
} else {
// No control flow - fall through to next block
uint32_t next_block = block.end_addr + 4;
if (blocks.count(next_block)) {
block.successors.push_back(next_block);
blocks[next_block].predecessors.push_back(addr);
}
}
}
}
std::vector<std::pair<uint32_t, uint32_t>> ControlFlowAnalyzer::detect_loops(
const std::map<uint32_t, BasicBlock>& blocks) {
std::vector<std::pair<uint32_t, uint32_t>> loops;
for (const auto& [addr, block] : blocks) {
// Check each successor
for (uint32_t successor : block.successors) {
// Back edge: successor address < current block address
if (successor <= addr) {
loops.push_back({successor, addr}); // (header, back_edge_source)
// Mark loop header
if (blocks.count(successor)) {
const_cast<BasicBlock&>(blocks.at(successor)).is_loop_header = true;
}
}
}
}
return loops;
}
ControlFlowGraph ControlFlowAnalyzer::analyze_function(const Function& func) {
ControlFlowGraph cfg;
// Alias entries cover their HOST's full range so backward branches, shared
// epilogues, and jr jump tables (whose setup may precede the alias entry)
// all stay intra-function. The emitted alias enters via goto to its
// start_addr block; walk_lo is the host's start.
uint32_t walk_lo = func.alias_walk_lo ? func.alias_walk_lo : func.start_addr;
// Discovery/block-construction bound. Normally exactly func.end_addr; on
// an overlay capture that carries trailing delay-slot guard words it stops
// short of them, so the guard word can never become a block leader or a
// block's exit instruction (its own delay slot does not exist). It stays
// READABLE: a transfer at walk_hi - 4 still emits its slot from the guard.
const uint32_t walk_hi = analysis_walk_hi(func);
cfg.function_start = walk_lo;
cfg.function_end = walk_hi;
cfg.producer_lo = func.producer_lo;
cfg.producer_hi = func.producer_hi;
// Simplified single-pass analysis: scan instructions to find block boundaries
// without building full CFG. This avoids the crash in build_basic_blocks.
std::vector<uint32_t> boundary_vec;
boundary_vec.push_back(walk_lo);
if (func.alias_walk_lo) {
// Every alias entry point of this host must be a block leader so the
// shared body's entry switch has labels to land on — and so sibling
// aliases produce identical CFGs.
boundary_vec.push_back(func.start_addr);
for (uint32_t e : func.alias_group_entries) {
if (e >= walk_lo && e < walk_hi) boundary_vec.push_back(e);
}
}
auto add_boundary = [&](uint32_t target) {
if (target >= walk_lo && target < walk_hi) {
boundary_vec.push_back(target);
}
};
// Scan instructions for branches/jumps to find block starts
for (uint32_t addr = walk_lo; addr < walk_hi; addr += 4) {
auto instr_opt = exe_.read_word(addr);
if (!instr_opt) continue;
uint32_t instr = *instr_opt;
if (is_control_flow(instr)) {
ControlFlowInstr cf = analyze_instruction(addr, instr);
if (cf.target != 0 && cf.target >= walk_lo && cf.target < walk_hi) {
add_boundary(cf.target);
}
// After delay slot is a new block
uint32_t after_delay = addr + 8;
if (after_delay < walk_hi) {
add_boundary(after_delay);
}
}
}
// Build blocks from boundaries
std::sort(boundary_vec.begin(), boundary_vec.end());
boundary_vec.erase(std::unique(boundary_vec.begin(), boundary_vec.end()), boundary_vec.end());
for (size_t i = 0; i < boundary_vec.size(); i++) {
BasicBlock block;
block.start_addr = boundary_vec[i];
block.end_addr = (i + 1 < boundary_vec.size()) ? boundary_vec[i + 1] - 4 : walk_hi - 4;
if (block.end_addr < block.start_addr) continue;
block.instruction_count = (block.end_addr - block.start_addr) / 4 + 1;
block.is_entry = (block.start_addr == walk_lo);
block.is_exit = false;
block.is_loop_header = false;
// Find exit instruction: scan backward from end to find last branch/jump
block.exit_instr.type = ControlFlowType::None;
block.exit_instr.address = block.end_addr;
block.exit_instr.instruction = 0;
block.exit_instr.target = 0;
block.exit_instr.has_delay_slot = false;
block.exit_instr.is_likely = false;
// Check if the instruction before the last (the branch, not delay slot) is CF
if (block.end_addr > block.start_addr) {
auto prev_opt = exe_.read_word(block.end_addr - 4);
if (prev_opt && is_control_flow(*prev_opt)) {
block.exit_instr = analyze_instruction(block.end_addr - 4, *prev_opt);
block.is_exit = (block.exit_instr.type == ControlFlowType::Return);
}
}
// Also check last instruction itself
if (block.exit_instr.type == ControlFlowType::None) {
auto last_opt = exe_.read_word(block.end_addr);
if (last_opt && is_control_flow(*last_opt)) {
block.exit_instr = analyze_instruction(block.end_addr, *last_opt);
block.is_exit = (block.exit_instr.type == ControlFlowType::Return);
}
}
// Add successors — only targets within this function's block set
auto in_func = [&](uint32_t addr) {
return addr >= walk_lo &&
addr < walk_hi &&
std::binary_search(boundary_vec.begin(), boundary_vec.end(), addr);
};
if (block.exit_instr.type == ControlFlowType::Branch) {
if (block.exit_instr.target != 0 && in_func(block.exit_instr.target))
block.successors.push_back(block.exit_instr.target);
uint32_t ft = block.exit_instr.address + 8;
if (in_func(ft)) block.successors.push_back(ft);
} else if (block.exit_instr.type == ControlFlowType::Jump) {
if (block.exit_instr.target != 0 && in_func(block.exit_instr.target))
block.successors.push_back(block.exit_instr.target);
} else if (block.exit_instr.type == ControlFlowType::JumpLink ||
block.exit_instr.type == ControlFlowType::JumpLinkReg) {
uint32_t ft = block.exit_instr.address + 8;
if (in_func(ft)) block.successors.push_back(ft);
} else if (block.exit_instr.type != ControlFlowType::Return &&
block.exit_instr.type != ControlFlowType::JumpRegister) {
uint32_t next = block.end_addr + 4;
if (in_func(next)) block.successors.push_back(next);
}
cfg.blocks[block.start_addr] = block;
}
// Detect back-edges (loops)
for (const auto& [addr, block] : cfg.blocks) {
for (uint32_t succ : block.successors) {
if (succ <= addr) {
cfg.loops.push_back({succ, addr});
if (cfg.blocks.count(succ)) {
cfg.blocks[succ].is_loop_header = true;
}
}
}
}
cfg.loop_count = static_cast<int>(cfg.loops.size());
for (const auto& [addr, block] : cfg.blocks) {
cfg.block_order.push_back(addr);
}
std::sort(cfg.block_order.begin(), cfg.block_order.end());
return cfg;
}
std::map<uint32_t, ControlFlowGraph> ControlFlowAnalyzer::analyze_all_functions(
const std::vector<Function>& functions) {
std::map<uint32_t, ControlFlowGraph> all_cfgs;
fmt::print("\n=== Control Flow Analysis ===\n\n");
fmt::print("Analyzing {} functions...\n", functions.size());
int total_blocks = 0;
int total_loops = 0;
for (const Function& func : functions) {
ControlFlowGraph cfg = analyze_function(func);
total_blocks += static_cast<int>(cfg.blocks.size());
total_loops += cfg.loop_count;
all_cfgs[func.start_addr] = cfg;
}
fmt::print("✓ Created {} basic blocks\n", total_blocks);
fmt::print("✓ Detected {} loops\n", total_loops);
fmt::print("✓ Average {:.1f} blocks per function\n\n",
static_cast<double>(total_blocks) / functions.size());
return all_cfgs;
}
} // namespace PSXRecomp