Skip to content
This repository was archived by the owner on Nov 16, 2026. It is now read-only.
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions include/rex/codegen/config.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ struct FunctionConfig {
uint32_t end = 0; // End address, exclusive (mutually exclusive with size)
std::string name; // Custom symbol name (empty = auto-generate sub_XXXXXXXX)
uint32_t parent = 0; // Parent function address (0 = standalone, non-zero = chunk)
// Keep this entry callable, but start at its exact address in the named
// owner's emitted body. Intended for explicit interior entry points.
uint32_t bodyOwner = 0;

// Keep non-volatiles in ctx instead of localizing them. Marks an MSVC SEH
// funclet, which reads the registers its owner left live and would see a zero
Expand Down
8 changes: 6 additions & 2 deletions include/rex/codegen/function_graph.h
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class FunctionGraph {

// Add a function to the graph.
// Returns the new node, or existing node if already present (higher authority wins).
// Notifies all PENDING functions to try resolution against the new entry.
// Notifies PENDING functions with unresolved jumps against the new entry.
// hasXrefs: true if this is a known call target (bl target, etc.)
FunctionNode* addFunction(uint32_t base, uint32_t size, FunctionAuthority authority,
bool hasXrefs = false);
Expand Down Expand Up @@ -199,7 +199,11 @@ class FunctionGraph {
std::vector<std::pair<uint32_t, uint32_t>> chunks_; // base, size pairs
MemoryReader memoryReader_;

// Notify all PENDING functions that a new function was added
// Only these entries can benefit from registration notifications. Entry
// addresses remain valid across graph moves and never retain replaced nodes.
std::unordered_set<uint32_t> unresolvedFunctionEntries_;

// Notify indexed PENDING functions that a new function was added
void notifyFunctionAdded(FunctionNode* newFunction);
};

Expand Down
7 changes: 5 additions & 2 deletions include/rex/codegen/function_node.h
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,12 @@ class FunctionNode {
//=========================================================================

/// Emit C++ code for this function
/// Requires: state() == kSealed
/// Requires discovered blocks; the writer validates deferred interior branches.
/// For imports: emits REX_IMPORT macro
/// For normal functions: emits REX_FUNC with blocks and instructions
std::string emitCpp(const EmitContext& ctx) const;
// An alternate entry retains its own symbol while using this node's body
// and call metadata, plus any additional blocks found from that entry.
std::string emitCpp(const EmitContext& ctx, const FunctionNode* entry = nullptr) const;

//=========================================================================
// Instruction access (valid after discover)
Expand Down Expand Up @@ -175,6 +177,7 @@ class FunctionNode {

// Internal helper
void removeUnresolvedJump(uint32_t site);
std::string emitCppForEntry(const EmitContext& ctx, const FunctionNode& entry) const;

//=========================================================================
// State
Expand Down
20 changes: 18 additions & 2 deletions resources/templates/codegen/register_cpp.inja
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@

#include "{{ project }}_init.h"
#include <rex/system/function_dispatcher.h>
#include <array>

namespace {
struct FunctionRegistration {
uint32_t guest_address;
::PPCFunc* host_function;
};

// Keep registrations as constant data. A game may contain hundreds of
// thousands of entries; emitting that many calls in one body overwhelms
// compiler optimization and instruction selection.
constexpr std::array<FunctionRegistration, {{ length(registrations) }}> kFunctionRegistrations = {
{% for fn in registrations %} FunctionRegistration{ {{ fn.address }}, {{ fn.name }} },
{% endfor %}};
} // namespace

{% if is_dll %}
#ifdef _WIN32
Expand All @@ -17,8 +32,9 @@ void ReXModule_Register(rex::runtime::IModuleRegistrar* registrar) {
{% else %}
void {{ project }}_RegisterFunctions(rex::runtime::IModuleRegistrar* registrar) {
{% endif %}
{% for fn in functions %}{% if not fn.below_code_base or fn.is_import %} registrar->SetFunction({{ fn.address }}, {{ fn.name }});
{% endif %}{% endfor %}}
for (const auto& entry : kFunctionRegistrations)
registrar->SetFunction(entry.guest_address, entry.host_function);
}

{% if is_dll %}
// The runtime uses this baked layout for the dispatch table. It must match the
Expand Down
128 changes: 127 additions & 1 deletion src/codegen/codegen_writer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,120 @@

namespace {

bool ValidateFunctionBodies(const rex::codegen::RecompilerConfig& config,
const rex::codegen::FunctionGraph& graph,
const rex::codegen::BinaryView& binary) {
for (const auto& [address, function] : config.functions) {
if (!function.bodyOwner)
continue;
auto reject = [&](std::string_view reason) {
REXCODEGEN_ERROR("Function 0x{:08X} body 0x{:08X}: {}", address,
function.bodyOwner, reason);
return false;
};
if ((address & 3) || (function.bodyOwner & 3) || function.parent ||
address == function.bodyOwner)
return reject("body requires a distinct aligned owner and cannot be a chunk");
if (config.ctrAsLocalVariable || config.xerAsLocalVariable ||
config.reservedRegisterAsLocalVariable || config.crRegistersAsLocalVariables ||
config.nonArgumentRegistersAsLocalVariables || config.nonVolatileRegistersAsLocalVariables)
return reject("interior body entries require all register localization options disabled");
auto ownerConfig = config.functions.find(function.bodyOwner);
if (ownerConfig != config.functions.end() && ownerConfig->second.bodyOwner)
return reject("nested or cyclic body owners are unsupported");
const auto* entry = graph.getFunction(address);
const auto* owner = graph.getFunction(function.bodyOwner);
if (!entry || !owner || entry->isRegistered() || owner->isRegistered() ||
entry->isImport() || owner->isImport() || owner->blocks().empty() ||
entry->blocks().empty()) {
REXCODEGEN_ERROR("Body node states: entry present={} state={} import={} unresolved={}; owner present={} state={} import={} unresolved={}",
entry != nullptr, entry ? int(entry->state()) : -1, entry && entry->isImport(),
entry ? entry->unresolvedJumps().size() : 0, owner != nullptr,
owner ? int(owner->state()) : -1, owner && owner->isImport(),
owner ? owner->unresolvedJumps().size() : 0);
return reject("entry and owner must have discovered non-import instruction blocks");
}
if (std::any_of(config.rexcrtFunctions.begin(), config.rexcrtFunctions.end(),
[&](const auto& crt) {
return crt.second == address || crt.second == function.bodyOwner;
}))
return reject("body entries cannot replace a rexcrt mapping");
bool contained = std::any_of(owner->blocks().begin(), owner->blocks().end(),
[&](const rex::codegen::Block& block) {
return address >= block.base && uint64_t(address) + 4 <= uint64_t(block.base) + block.size;
});
if (!contained || !binary.translate(address))
return reject("entry instruction is missing from the owner's actual blocks");
// The emission union must never wrap an address or import unmapped bytes.
for (const auto* node : {owner, entry}) {
for (const auto& block : node->blocks()) {
const auto* section = binary.findSection(block.base);
if (!block.size || (block.base & 3) || (block.size & 3) ||
block.base < owner->base() || !section || !section->executable ||
uint64_t(block.base) + block.size > UINT32_MAX ||
uint64_t(block.base) + block.size > uint64_t(section->baseAddress) + section->size)
return reject("body has an invalid or unmapped instruction block");
}
}
auto inBody = [&](uint32_t instruction) {
if (instruction & 3) return false;
for (const auto* node : {owner, entry}) {
for (const auto& block : node->blocks()) {
if (instruction >= block.base &&
uint64_t(instruction) + 4 <= uint64_t(block.base) + block.size)
return true;
}
}
return false;
};
auto resolvedAt = [&](uint32_t site) -> const rex::codegen::CallTarget* {
// Match the emission union's owner-first precedence exactly.
for (const auto* node : {owner, entry}) {
for (const auto* edges : {&node->calls(), &node->tailCalls()}) {
for (const auto& edge : *edges)
if (edge.site == site) return &edge.target;
}
}
return nullptr;
};
for (const auto* node : {owner, entry}) {
for (const auto& jump : node->unresolvedJumps()) {
if (!inBody(jump.site)) return reject("pending branch site is outside the actual body");
const auto* bytes = binary.translate(jump.site);
uint32_t instruction = (uint32_t(bytes[0]) << 24) | (uint32_t(bytes[1]) << 16) |
(uint32_t(bytes[2]) << 8) | bytes[3];
uint32_t opcode = instruction >> 26;
if ((opcode != 16 && opcode != 18) || bool(instruction & 1) != jump.isCall ||
(opcode == 16) != jump.isConditional)
return reject("pending branch metadata does not match its instruction");
unsigned width = opcode == 16 ? 16 : 26;
uint32_t displacementBits = instruction & ((uint32_t(1) << width) - 4);
int64_t displacement = displacementBits;
if (displacementBits & (uint32_t(1) << (width - 1)))
displacement -= int64_t(1) << width;
uint32_t target = static_cast<uint32_t>(displacement +
((instruction & 2) ? 0 : int64_t(jump.site)));
if (target != jump.target) return reject("pending branch target does not match its instruction");
const auto* call = resolvedAt(jump.site);
bool mapped = call && ((call->isFunction() && call->asFunction() &&
call->asFunction()->base() == target) ||
(call->isImport() &&
std::get<rex::codegen::CallTarget::ToImport>(call->value).address == target));
if (mapped) continue;
if (jump.isCall || !inBody(target))
return reject("pending branch has no actual local instruction or resolved call target");
// Conditional local branches use owner labels. An unconditional jump
// to a graph entry still requires call metadata with the current builder.
auto kind = graph.classifyTarget(target, jump.site, false);
if (!jump.isConditional && (kind == rex::codegen::TargetKind::Function ||
kind == rex::codegen::TargetKind::Import))
return reject("pending unconditional branch conflicts with another graph entry");
}
}
}
return true;
}

nlohmann::json buildTemplateData(const rex::codegen::CodegenContext& ctx,
const std::vector<const rex::codegen::FunctionNode*>& functions,
const std::unordered_map<uint32_t, std::string>& rexcrtByAddr) {
Expand All @@ -54,6 +168,7 @@ nlohmann::json buildTemplateData(const rex::codegen::CodegenContext& ctx,

// Build functions JSON array
nlohmann::json functionsJson = nlohmann::json::array();
nlohmann::json registrationsJson = nlohmann::json::array();
for (const auto* fn : functions) {
std::string funcName;
bool isRexcrt = false;
Expand All @@ -77,6 +192,11 @@ nlohmann::json buildTemplateData(const rex::codegen::CodegenContext& ctx,
{"below_code_base", (fn->base() < codeMin)},
{"is_import", fn->authority() == rex::codegen::FunctionAuthority::IMPORT},
});
// Preserve the registration order and filtering used by the mapping
// table, including import thunks below the executable code range.
if (fn->base() >= codeMin || fn->authority() == rex::codegen::FunctionAuthority::IMPORT)
registrationsJson.push_back({{"address", fmt::format("0x{:X}", fn->base())},
{"name", funcName}});
}

// Build config flags
Expand All @@ -103,6 +223,7 @@ nlohmann::json buildTemplateData(const rex::codegen::CodegenContext& ctx,
{"is_dll", ctx.isDllModule()},
{"config_flags", configFlags},
{"functions", functionsJson},
{"registrations", registrationsJson},
{"recomp_files", nlohmann::json::array()},
};
}
Expand Down Expand Up @@ -173,6 +294,8 @@ bool CodegenWriter::write(bool force) {
ctx_.errors.Count());
return false;
}
if (!ValidateFunctionBodies(config(), graph(), binary()))
return false;

// --- Output directory setup (from recompile.cpp) ---
std::filesystem::path outputPath = ctx_.configDir() / config().outDirectoryPath;
Expand Down Expand Up @@ -264,7 +387,10 @@ bool CodegenWriter::write(bool force) {
emitCtx.referenced = &referenced;
for (const auto* fn : functions) {
referenced.clear();
std::string code = fn->emitCpp(emitCtx);
const auto configured = config().functions.find(fn->base());
const auto* body = configured != config().functions.end() && configured->second.bodyOwner
? graph().getFunction(configured->second.bodyOwner) : fn;
std::string code = body->emitCpp(emitCtx, body == fn ? nullptr : fn);
if (code.size() > maxFileBytes) {
REXCODEGEN_WARN("Function 0x{:08X} is {} bytes, exceeds max_file_size_bytes ({})", fn->base(),
code.size(), maxFileBytes);
Expand Down
14 changes: 11 additions & 3 deletions src/codegen/config.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ void MergeBool(bool& dst, bool src, bool present, const char* name) {
// Apply a single parsed TOML table onto the config (merge semantics)
// ---------------------------------------------------------------------------

void ApplyToml(const toml::table& toml, RecompilerConfig& cfg, const std::string& filePath) {
bool ApplyToml(const toml::table& toml, RecompilerConfig& cfg, const std::string& filePath) {
// --- Scalars: last wins ---

// String scalars (only override if present in this file)
Expand Down Expand Up @@ -197,6 +197,14 @@ void ApplyToml(const toml::table& toml, RecompilerConfig& cfg, const std::string
fcfg.end = (*table)["end"].value_or(0u);
fcfg.name = (*table)["name"].value_or(std::string{});
fcfg.parent = (*table)["parent"].value_or(0u);
fcfg.bodyOwner = (*table)["body"].value_or(0u);
if ((*table)["body"] &&
(!(*table)["body"].value<uint32_t>() || !fcfg.bodyOwner ||
(fcfg.bodyOwner & 3) != 0 || fcfg.bodyOwner == address || fcfg.parent)) {
REXCODEGEN_ERROR("Function 0x{:08X}: 'body' requires a different aligned owner address and cannot be combined with 'parent'",
address);
return false;
}
fcfg.shareRegisters = (*table)["share_registers"].value_or(false);

if (fcfg.size && fcfg.end) {
Expand Down Expand Up @@ -381,6 +389,7 @@ void ApplyToml(const toml::table& toml, RecompilerConfig& cfg, const std::string
}
}
}
return true;
}

bool ApplyTableWithIncludes(const toml::table& tbl, const std::filesystem::path& base_dir,
Expand Down Expand Up @@ -440,8 +449,7 @@ bool ApplyTableWithIncludes(const toml::table& tbl, const std::filesystem::path&
}
}
}
ApplyToml(tbl, cfg, description);
return true;
return ApplyToml(tbl, cfg, description);
}

} // namespace
Expand Down
Loading