+3
-1
@@ -11,6 +11,7 @@ Checks: >
|
||||
-bugprone-assignment-in-if-condition,
|
||||
-bugprone-easily-swappable-parameters,
|
||||
-bugprone-multi-level-implicit-pointer-conversion,
|
||||
-bugprone-unintended-char-ostream-output,
|
||||
-readability-function-cognitive-complexity,
|
||||
-readability-magic-numbers,
|
||||
-readability-redundant-access-specifiers,
|
||||
@@ -28,7 +29,8 @@ Checks: >
|
||||
-cppcoreguidelines-macro-usage,
|
||||
-cppcoreguidelines-owning-memory,
|
||||
-cppcoreguidelines-non-private-member-variables-in-classes,
|
||||
-cppcoreguidelines-pro-bounds-avoid-unchecked-container-access
|
||||
-cppcoreguidelines-pro-bounds-avoid-unchecked-container-access,
|
||||
-cppcoreguidelines-pro-bounds-array-to-pointer-decay
|
||||
|
||||
WarningsAsErrors: "*"
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ public:
|
||||
ir_generator(const ir_generator&) = delete;
|
||||
ir_generator& operator=(const ir_generator&) = delete;
|
||||
public:
|
||||
furlang::ir::module&& move_module() { return std::move(m_module); }
|
||||
furlang::ir::mod&& move_module() { return std::move(m_module); }
|
||||
public:
|
||||
void visit(const ast::function_definition_node& funcDef) override;
|
||||
void visit(const ast::return_statement_node& returnStmt) override;
|
||||
@@ -45,7 +45,7 @@ private:
|
||||
|
||||
furlang::ir::block_index push_block(bool validate = true);
|
||||
private:
|
||||
furlang::ir::module m_module;
|
||||
furlang::ir::mod m_module;
|
||||
std::unique_ptr<furlang::ir::function> m_currentFunction;
|
||||
std::shared_ptr<furlang::ir::block> m_currentBlock;
|
||||
ir_register m_registerCounter = 0;
|
||||
|
||||
@@ -23,7 +23,7 @@ public:
|
||||
* @param filename Filename for debugging.
|
||||
* @param content Content.
|
||||
*/
|
||||
parser(std::string_view filename, std::string_view content);
|
||||
parser(furlang::arena& arena, std::string_view filename, std::string_view content);
|
||||
|
||||
/**
|
||||
* @brief Construct a new parser from file.
|
||||
@@ -32,7 +32,8 @@ public:
|
||||
*
|
||||
* @param filename Name of the file.
|
||||
*/
|
||||
parser(std::string_view filename);
|
||||
parser(furlang::arena& arena, std::string_view filename);
|
||||
|
||||
~parser() = default;
|
||||
|
||||
/**
|
||||
@@ -40,13 +41,12 @@ public:
|
||||
*/
|
||||
parser(parser&&) = default;
|
||||
|
||||
parser(const parser&) = delete;
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
parser& operator=(parser&&) = default;
|
||||
|
||||
parser(const parser&) = delete;
|
||||
parser& operator=(const parser&) = delete;
|
||||
public:
|
||||
/**
|
||||
@@ -73,7 +73,7 @@ private:
|
||||
std::string m_filename;
|
||||
std::string m_content;
|
||||
lexer m_lexer;
|
||||
furlang::arena m_arena;
|
||||
furlang::arena* m_arena;
|
||||
std::vector<token_r> m_peekBuffer;
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
#ifndef FURC_FRONT_POST_PROCESS_HPP
|
||||
#define FURC_FRONT_POST_PROCESS_HPP
|
||||
|
||||
#include "furlang/ir/module.hpp"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace furc {
|
||||
namespace front {
|
||||
|
||||
/**
|
||||
* @brief Post process pipeline.
|
||||
*/
|
||||
class post_process {
|
||||
public:
|
||||
enum stage { // NOLINT
|
||||
Ssa,
|
||||
Sccp,
|
||||
Adce,
|
||||
DeSsa,
|
||||
};
|
||||
public:
|
||||
post_process() = default;
|
||||
~post_process() = default;
|
||||
|
||||
post_process(post_process&&) noexcept = default;
|
||||
post_process& operator=(post_process&&) noexcept = default;
|
||||
post_process(const post_process&) = delete;
|
||||
post_process& operator=(const post_process&) = delete;
|
||||
public:
|
||||
void push_stage(stage stage) { m_stages.push_back(stage); }
|
||||
public:
|
||||
void process(furlang::ir::mod& mod);
|
||||
private:
|
||||
std::vector<stage> m_stages;
|
||||
};
|
||||
|
||||
} // namespace front
|
||||
} // namespace furc
|
||||
|
||||
#endif // FURC_FRONT_POST_PROCESS_HPP
|
||||
@@ -1,40 +0,0 @@
|
||||
#ifndef FURC_FRONT_SSA_HPP
|
||||
#define FURC_FRONT_SSA_HPP
|
||||
|
||||
#include "furlang/ir/function.hpp"
|
||||
#include "furlang/ir/instruction.hpp"
|
||||
#include "furlang/ir/module.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace furc {
|
||||
namespace front {
|
||||
|
||||
class ssa {
|
||||
using block_map_t = std::unordered_map<furlang::ir::block_index, std::vector<furlang::ir::block_index>>;
|
||||
public:
|
||||
static void optimize(furlang::ir::module& mod);
|
||||
private:
|
||||
static void optimize(const std::unique_ptr<furlang::ir::function>& func);
|
||||
|
||||
static void de_ssa(const std::unique_ptr<furlang::ir::function>& func);
|
||||
|
||||
static void constant_propagation(const std::unique_ptr<furlang::ir::function>& func);
|
||||
|
||||
static void dead_code_elimination(const std::unique_ptr<furlang::ir::function>& func);
|
||||
|
||||
static void copy_propagation(const std::unique_ptr<furlang::ir::function>& func);
|
||||
|
||||
static void dfs_rpo(furlang::ir::block_index block,
|
||||
const block_map_t& successors,
|
||||
std::unordered_set<furlang::ir::block_index>& visited,
|
||||
std::vector<furlang::ir::block_index>& rpo);
|
||||
};
|
||||
|
||||
} // namespace front
|
||||
} // namespace furc
|
||||
|
||||
#endif // FURC_FRONT_SSA_HPP
|
||||
+20
-20
@@ -16,11 +16,11 @@ namespace furc::front {
|
||||
|
||||
using namespace std::string_literals;
|
||||
|
||||
parser::parser(std::string_view filename, std::string_view content)
|
||||
: m_filename(filename), m_content(content), m_lexer(m_filename, m_content) {}
|
||||
parser::parser(furlang::arena& arena, std::string_view filename, std::string_view content)
|
||||
: m_filename(filename), m_content(content), m_lexer(m_filename, m_content), m_arena(&arena) {}
|
||||
|
||||
parser::parser(std::string_view filename)
|
||||
: m_filename(filename) {
|
||||
parser::parser(furlang::arena& arena, std::string_view filename)
|
||||
: m_filename(filename), m_arena(&arena) {
|
||||
std::ifstream file(m_filename, std::ios_base::binary | std::ios_base::ate);
|
||||
if (!file.is_open()) throw std::runtime_error("failed to open file "s.append(m_filename));
|
||||
std::streampos size = file.tellg();
|
||||
@@ -32,7 +32,7 @@ parser::parser(std::string_view filename)
|
||||
}
|
||||
|
||||
ast::program_node_r parser::parse() & {
|
||||
auto program = m_arena.allocate_shared<ast::program_node>(location{ m_filename });
|
||||
auto program = m_arena->allocate_shared<ast::program_node>(location{ m_filename });
|
||||
|
||||
while (peek_token().has_value()) {
|
||||
auto decl = parse_declaration();
|
||||
@@ -67,13 +67,13 @@ ast::declaration_node_r parser::parse_declaration() {
|
||||
case token_t::LBrace: {
|
||||
ast::body_r body = parse_body();
|
||||
if (body.has_error()) return ast::declaration_node_r(ast::error{ body.error().location });
|
||||
return m_arena.allocate_shared<ast::function_definition_node>(first->location,
|
||||
return m_arena->allocate_shared<ast::function_definition_node>(first->location,
|
||||
name->value.string,
|
||||
std::move(body.value()));
|
||||
}
|
||||
case token_t::Semicolon: {
|
||||
m_peekBuffer.clear();
|
||||
return m_arena.allocate_shared<ast::function_declaration_node>(first->location, name->value.string);
|
||||
return m_arena->allocate_shared<ast::function_declaration_node>(first->location, name->value.string);
|
||||
}
|
||||
default: return ast::declaration_node_r(ast::error{ tok->location });
|
||||
}
|
||||
@@ -109,13 +109,13 @@ ast::statement_node_r parser::parse_statement() {
|
||||
auto tok = next_token();
|
||||
if (peek_token()->type == token_t::Semicolon) {
|
||||
next_token();
|
||||
return m_arena.allocate_shared<ast::return_statement_node>(location);
|
||||
return m_arena->allocate_shared<ast::return_statement_node>(location);
|
||||
}
|
||||
|
||||
auto value = parse_expression();
|
||||
auto err = eat_token(token_t::Semicolon);
|
||||
if (err.has_error()) return ast::statement_node_r(ast::error{ err.error().location });
|
||||
return m_arena.allocate_shared<ast::return_statement_node>(location, std::move(value.value()));
|
||||
return m_arena->allocate_shared<ast::return_statement_node>(location, std::move(value.value()));
|
||||
}
|
||||
case keyword_token::If: {
|
||||
auto tok = next_token();
|
||||
@@ -136,13 +136,13 @@ ast::statement_node_r parser::parse_statement() {
|
||||
|
||||
auto elseBody = parse_statement();
|
||||
if (elseBody.has_error()) return ast::statement_node_r(ast::error{ elseBody.error().location });
|
||||
return m_arena.allocate_shared<ast::if_statement_node>(location,
|
||||
return m_arena->allocate_shared<ast::if_statement_node>(location,
|
||||
std::move(cond.value()),
|
||||
std::move(then.value()),
|
||||
std::move(elseBody.value()));
|
||||
}
|
||||
|
||||
return m_arena.allocate_shared<ast::if_statement_node>(location,
|
||||
return m_arena->allocate_shared<ast::if_statement_node>(location,
|
||||
std::move(cond.value()),
|
||||
std::move(then.value()));
|
||||
}
|
||||
@@ -160,7 +160,7 @@ ast::statement_node_r parser::parse_statement() {
|
||||
auto body = parse_statement();
|
||||
if (body.has_error()) return ast::statement_node_r(ast::error{ body.error().location });
|
||||
|
||||
return m_arena.allocate_shared<ast::while_statement_node>(location,
|
||||
return m_arena->allocate_shared<ast::while_statement_node>(location,
|
||||
std::move(cond.value()),
|
||||
std::move(body.value()));
|
||||
}
|
||||
@@ -172,7 +172,7 @@ ast::statement_node_r parser::parse_statement() {
|
||||
case token_t::LBrace: {
|
||||
auto body = parse_body();
|
||||
if (body.has_error()) return ast::statement_node_r(ast::error{ body.error().location });
|
||||
return m_arena.allocate_shared<ast::compound_statement_node>(location, std::move(body.value()));
|
||||
return m_arena->allocate_shared<ast::compound_statement_node>(location, std::move(body.value()));
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
@@ -204,7 +204,7 @@ ast::expression_node_r parser::parse_expression_primary() {
|
||||
case token_t::Identifier: {
|
||||
auto tok = next_token();
|
||||
if (tok.has_error()) return ast::expression_node_r(ast::error{ tok.error().location });
|
||||
return m_arena.allocate_shared<ast::var_read_expression_node>(tok->location, (*tok)->string);
|
||||
return m_arena->allocate_shared<ast::var_read_expression_node>(tok->location, (*tok)->string);
|
||||
}
|
||||
case token_t::LParen: {
|
||||
auto tok = next_token();
|
||||
@@ -216,12 +216,12 @@ ast::expression_node_r parser::parse_expression_primary() {
|
||||
case token_t::String: {
|
||||
auto tok = next_token();
|
||||
if (tok.has_error()) return ast::expression_node_r(ast::error{ tok.error().location });
|
||||
return m_arena.allocate_shared<ast::string_literal_node>(tok->location, (*tok)->string);
|
||||
return m_arena->allocate_shared<ast::string_literal_node>(tok->location, (*tok)->string);
|
||||
}
|
||||
case token_t::Integer: {
|
||||
auto tok = next_token();
|
||||
if (tok.has_error()) return ast::expression_node_r(ast::error{ tok.error().location });
|
||||
return m_arena.allocate_shared<ast::integer_literal_node>(tok->location, (*tok)->integer);
|
||||
return m_arena->allocate_shared<ast::integer_literal_node>(tok->location, (*tok)->integer);
|
||||
}
|
||||
default: {
|
||||
return ast::expression_node_r(ast::error{ tok->location });
|
||||
@@ -262,7 +262,7 @@ ast::expression_node_r parser::parse_expression_unary(std::uint32_t precedence)
|
||||
expression = std::move(std::move(expr.value()));
|
||||
}
|
||||
|
||||
result = m_arena.allocate_shared<ast::unary_op_expression_node>(token->location,
|
||||
result = m_arena->allocate_shared<ast::unary_op_expression_node>(token->location,
|
||||
current.type,
|
||||
std::move(expression));
|
||||
}
|
||||
@@ -389,18 +389,18 @@ ast::expression_node_r parser::parse_expression_rhs(ast::expression_node_p&& ini
|
||||
|
||||
switch (current.type) {
|
||||
case rhsop_info_t::Unaryop:
|
||||
lhs = m_arena.allocate_shared<ast::unary_op_expression_node>(opToken->location,
|
||||
lhs = m_arena->allocate_shared<ast::unary_op_expression_node>(opToken->location,
|
||||
current.unary,
|
||||
std::move(lhs));
|
||||
break;
|
||||
case rhsop_info_t::Binop:
|
||||
lhs = m_arena.allocate_shared<ast::binary_op_expression_node>(opToken->location,
|
||||
lhs = m_arena->allocate_shared<ast::binary_op_expression_node>(opToken->location,
|
||||
current.binary,
|
||||
std::move(lhs),
|
||||
std::move(rhs));
|
||||
break;
|
||||
case rhsop_info_t::Assignment:
|
||||
lhs = m_arena.allocate_shared<ast::var_assign_expression_node>(opToken->location,
|
||||
lhs = m_arena->allocate_shared<ast::var_assign_expression_node>(opToken->location,
|
||||
current.assignment,
|
||||
std::move(lhs),
|
||||
std::move(rhs));
|
||||
|
||||
@@ -0,0 +1,599 @@
|
||||
#include "furc/front/post_process.hpp"
|
||||
|
||||
#include "furlang/ir/function.hpp"
|
||||
#include "furlang/ir/instruction.hpp"
|
||||
#include "furlang/ir/operand.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <stack>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace furc::front {
|
||||
|
||||
using block_idx = furlang::ir::block_index;
|
||||
using register_t = furlang::ir::register_t;
|
||||
using register_op = furlang::ir::register_operand;
|
||||
|
||||
static constexpr block_idx INVALID_BLOCK = std::numeric_limits<block_idx>::max();
|
||||
|
||||
struct block_info {
|
||||
std::size_t rpoIndex{ 0 };
|
||||
|
||||
std::vector<block_idx> predecessors;
|
||||
std::vector<block_idx> successors;
|
||||
|
||||
block_idx idom = INVALID_BLOCK;
|
||||
std::vector<block_idx> doms;
|
||||
std::unordered_set<block_idx> domFrontiers;
|
||||
};
|
||||
|
||||
struct register_info {
|
||||
std::unordered_set<block_idx> defSites;
|
||||
std::stack<register_t> renameStack;
|
||||
std::uint32_t nextVersion{ 0 };
|
||||
};
|
||||
|
||||
struct function_context {
|
||||
explicit function_context(furlang::ir::function* function)
|
||||
: function(function) {
|
||||
build_cfg();
|
||||
compute_rpo();
|
||||
}
|
||||
|
||||
void build_cfg() {
|
||||
for (block_idx idx = 0; idx < function->blocks().size(); ++idx) {
|
||||
const auto& block = function->blocks()[idx];
|
||||
|
||||
for (const auto& instr : block->instructions()) {
|
||||
for (const auto& operand : instr->sources()) {
|
||||
if (operand->type() != furlang::ir::operand_t::Register) continue;
|
||||
auto reg = operand->reg();
|
||||
if (registers[reg].defSites.find(idx) != registers[reg].defSites.end()) continue;
|
||||
globalRegisters.insert(reg);
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& instr : block->instructions()) {
|
||||
if (!instr->has_destination() || instr->destination().type() != furlang::ir::operand_t::Register)
|
||||
continue;
|
||||
auto reg = instr->destination().reg();
|
||||
registers[reg].defSites.insert(idx);
|
||||
}
|
||||
|
||||
for (const auto& operand : block->exit()->sources()) {
|
||||
if (operand->type() != furlang::ir::operand_t::Register) continue;
|
||||
auto reg = operand->reg();
|
||||
if (registers[reg].defSites.find(idx) != registers[reg].defSites.end()) continue;
|
||||
globalRegisters.insert(reg);
|
||||
}
|
||||
|
||||
const auto& exit = block->exit();
|
||||
switch (exit->type()) {
|
||||
case furlang::ir::instruction_t::Branch: {
|
||||
const auto& br = dynamic_cast<const furlang::ir::branch_instruction&>(*exit);
|
||||
blocks[br.block()].predecessors.push_back(idx);
|
||||
blocks[idx].successors.push_back(br.block());
|
||||
} break;
|
||||
case furlang::ir::instruction_t::BranchCond: {
|
||||
const auto& br = dynamic_cast<const furlang::ir::branch_cond_instruction&>(*exit);
|
||||
blocks[br.if_block()].predecessors.push_back(idx);
|
||||
blocks[br.else_block()].predecessors.push_back(idx);
|
||||
blocks[idx].successors.push_back(br.if_block());
|
||||
blocks[idx].successors.push_back(br.else_block());
|
||||
} break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void compute_rpo() {
|
||||
std::unordered_set<block_idx> visited;
|
||||
|
||||
auto dfs = [&](auto& self, block_idx block) -> void {
|
||||
visited.insert(block);
|
||||
for (auto succ : blocks[block].successors) {
|
||||
if (visited.find(succ) != visited.end()) continue;
|
||||
self(self, succ);
|
||||
}
|
||||
rpoOrder.push_back(block);
|
||||
};
|
||||
|
||||
if (!function->blocks().empty()) dfs(dfs, 0);
|
||||
|
||||
std::reverse(rpoOrder.begin(), rpoOrder.end());
|
||||
for (std::size_t i = 0; i < rpoOrder.size(); ++i) {
|
||||
blocks[rpoOrder[i]].rpoIndex = i;
|
||||
}
|
||||
}
|
||||
|
||||
void compute_dominance() {
|
||||
if (rpoOrder.empty()) return;
|
||||
|
||||
const block_idx entry = rpoOrder.front();
|
||||
blocks[entry].idom = entry;
|
||||
|
||||
bool changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
|
||||
for (block_idx idx : rpoOrder) {
|
||||
if (idx == entry) continue;
|
||||
|
||||
block_idx newIdom = INVALID_BLOCK;
|
||||
bool found = false;
|
||||
for (auto pred : blocks[idx].predecessors) {
|
||||
if (blocks[pred].idom == INVALID_BLOCK) continue;
|
||||
if (found) {
|
||||
newIdom = intersect(pred, newIdom);
|
||||
} else {
|
||||
newIdom = pred;
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (blocks[idx].idom != newIdom) {
|
||||
blocks[idx].idom = newIdom;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (auto idx : rpoOrder) {
|
||||
if (idx == entry) continue;
|
||||
const block_idx parent = blocks[idx].idom;
|
||||
if (parent != INVALID_BLOCK) blocks[parent].doms.push_back(idx);
|
||||
}
|
||||
|
||||
for (auto idx : rpoOrder) {
|
||||
if (blocks[idx].predecessors.size() < 2) continue;
|
||||
for (auto cur : blocks[idx].predecessors) {
|
||||
while (cur != blocks[idx].idom) {
|
||||
blocks[cur].domFrontiers.insert(idx);
|
||||
cur = blocks[cur].idom;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
furlang::ir::function* function;
|
||||
std::vector<block_idx> rpoOrder;
|
||||
std::unordered_map<block_idx, block_info> blocks;
|
||||
std::unordered_map<register_t, register_info> registers;
|
||||
std::unordered_set<register_t> globalRegisters;
|
||||
private:
|
||||
block_idx intersect(block_idx block1, block_idx block2) {
|
||||
while (block1 != block2) {
|
||||
while (blocks[block1].rpoIndex > blocks[block2].rpoIndex)
|
||||
block1 = blocks[block1].idom;
|
||||
while (blocks[block2].rpoIndex > blocks[block1].rpoIndex)
|
||||
block2 = blocks[block2].idom;
|
||||
}
|
||||
return block1;
|
||||
}
|
||||
};
|
||||
|
||||
static void ssa_stage_rename_block(function_context& ctx,
|
||||
block_idx idx,
|
||||
std::unordered_map<register_t, std::uint32_t>& regVers,
|
||||
std::unordered_map<register_t, std::stack<std::uint32_t>>& regVerStacks) {
|
||||
std::unordered_map<register_t, std::uint32_t> pushed;
|
||||
|
||||
const auto& block = ctx.function->blocks()[idx];
|
||||
auto it = block->instructions().begin();
|
||||
for (; it != block->instructions().end(); ++it) {
|
||||
auto& instr = *it;
|
||||
if (instr->type() != furlang::ir::instruction_t::Phi) break;
|
||||
|
||||
const register_t orig = instr->destination().reg();
|
||||
const std::uint32_t newVer = regVers[orig]++;
|
||||
|
||||
instr->destination().reg().ver = newVer;
|
||||
regVerStacks[orig].push(newVer);
|
||||
++pushed[orig];
|
||||
}
|
||||
|
||||
for (; it != block->instructions().end(); ++it) {
|
||||
auto& instr = *it;
|
||||
for (auto& operand : instr->sources()) {
|
||||
if (operand->type() != furlang::ir::operand_t::Register) continue;
|
||||
|
||||
const register_t orig = operand->reg();
|
||||
if (regVerStacks[orig].empty()) continue;
|
||||
operand->reg().ver = regVerStacks[orig].top();
|
||||
}
|
||||
|
||||
if (instr->has_destination() && instr->destination().type() == furlang::ir::operand_t::Register) {
|
||||
const register_t orig = instr->destination().reg();
|
||||
const std::uint32_t newVer = regVers[orig]++;
|
||||
|
||||
instr->destination().reg().ver = newVer;
|
||||
regVerStacks[orig].push(newVer);
|
||||
++pushed[orig];
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& operand : block->exit()->sources()) {
|
||||
if (operand->type() != furlang::ir::operand_t::Register) continue;
|
||||
|
||||
const auto orig = operand->reg();
|
||||
if (regVerStacks[orig].empty()) continue;
|
||||
operand->reg().ver = regVerStacks[orig].top();
|
||||
}
|
||||
|
||||
for (auto succIdx : ctx.blocks[idx].successors) {
|
||||
const auto& succ = ctx.function->blocks()[succIdx];
|
||||
for (auto& instr : succ->instructions()) {
|
||||
if (instr->type() != furlang::ir::instruction_t::Phi) break;
|
||||
|
||||
auto& phi = dynamic_cast<furlang::ir::phi_instruction&>(*instr);
|
||||
for (auto& pair : phi.labels()) {
|
||||
if (pair.second != idx) continue;
|
||||
|
||||
auto orig = pair.first.reg();
|
||||
if (auto it = regVerStacks.find(orig); it != regVerStacks.end())
|
||||
pair.first.reg().ver = it->second.top();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& child : ctx.blocks[idx].doms) {
|
||||
ssa_stage_rename_block(ctx, child, regVers, regVerStacks);
|
||||
}
|
||||
|
||||
for (const auto& [reg, count] : pushed) {
|
||||
for (std::size_t i = 0; i < count; ++i)
|
||||
regVerStacks[reg].pop();
|
||||
}
|
||||
}
|
||||
|
||||
static void ssa_stage(function_context& ctx) {
|
||||
ctx.compute_dominance();
|
||||
|
||||
std::vector<block_idx> worklist;
|
||||
for (const auto& [reg, info] : ctx.registers) {
|
||||
if (info.defSites.size() < 2 || ctx.globalRegisters.find(reg) == ctx.globalRegisters.end()) continue;
|
||||
|
||||
worklist.clear();
|
||||
worklist.insert(worklist.end(), info.defSites.begin(), info.defSites.end());
|
||||
|
||||
std::unordered_set<block_idx> added;
|
||||
while (!worklist.empty()) {
|
||||
const auto idx = worklist.back();
|
||||
worklist.pop_back();
|
||||
for (auto frontier : ctx.blocks[idx].domFrontiers) {
|
||||
if (added.find(frontier) != added.end()) continue;
|
||||
added.insert(frontier);
|
||||
|
||||
const auto& target = ctx.function->blocks()[frontier];
|
||||
const auto& preds = ctx.blocks[frontier].predecessors;
|
||||
|
||||
auto instr = std::make_unique<furlang::ir::phi_instruction>(reg);
|
||||
for (auto pred : preds) {
|
||||
instr->labels().emplace_back(furlang::ir::operand::new_reg(reg), pred);
|
||||
}
|
||||
target->instructions().emplace(target->instructions().begin(), std::move(instr));
|
||||
|
||||
if (info.defSites.find(frontier) == info.defSites.end()) worklist.push_back(frontier);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::unordered_map<register_t, std::uint32_t> regVers;
|
||||
std::unordered_map<register_t, std::stack<std::uint32_t>> regVerStacks;
|
||||
ssa_stage_rename_block(ctx, ctx.rpoOrder.front(), regVers, regVerStacks);
|
||||
}
|
||||
|
||||
static void dessa_stage(function_context& ctx) {
|
||||
for (block_idx idx = 0; idx < ctx.function->blocks().size(); ++idx) {
|
||||
const auto& block = ctx.function->blocks()[idx];
|
||||
auto& instrs = block->instructions();
|
||||
for (auto it = instrs.begin(); it != instrs.end() && (*it)->type() == furlang::ir::instruction_t::Phi;
|
||||
it = instrs.erase(it)) {
|
||||
auto& phi = dynamic_cast<furlang::ir::phi_instruction&>(**it);
|
||||
auto dstReg = phi.destination().reg();
|
||||
for (auto& [srcOp, label] : phi.labels()) {
|
||||
ctx.function->blocks()[label]->instructions().push_back(
|
||||
std::make_unique<furlang::ir::assign_instruction>(furlang::ir::operand::new_reg(srcOp.reg()),
|
||||
furlang::ir::operand::new_reg(dstReg)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct sccp_lattice {
|
||||
enum lattice_t { // NOLINT
|
||||
Top,
|
||||
Constant,
|
||||
Bottom,
|
||||
} type = Top;
|
||||
std::uint64_t constant = 0;
|
||||
|
||||
bool operator==(const sccp_lattice& other) const {
|
||||
return type == other.type && (type != Constant || constant == other.constant);
|
||||
}
|
||||
|
||||
bool operator!=(const sccp_lattice& other) const { return !this->operator==(other); }
|
||||
};
|
||||
|
||||
sccp_lattice sccp_stage_get_lattice(std::unordered_map<register_op, sccp_lattice>& latticeValues,
|
||||
const furlang::ir::operand& op) {
|
||||
if (op.type() == furlang::ir::operand_t::Integer) {
|
||||
sccp_lattice lat;
|
||||
lat.type = sccp_lattice::Constant;
|
||||
lat.constant = op.integer();
|
||||
return lat;
|
||||
}
|
||||
if (op.type() == furlang::ir::operand_t::Register) {
|
||||
auto reg = op.reg();
|
||||
if (auto it = latticeValues.find(reg); it != latticeValues.end()) return it->second;
|
||||
return { sccp_lattice::Top };
|
||||
}
|
||||
return { sccp_lattice::Bottom };
|
||||
};
|
||||
|
||||
static void sccp_stage(function_context& ctx) {
|
||||
using lattice = sccp_lattice;
|
||||
|
||||
std::unordered_map<register_op, lattice> latticeValues;
|
||||
std::unordered_map<register_t, std::vector<furlang::ir::instruction*>> edges;
|
||||
std::unordered_set<block_idx> execBlocks;
|
||||
std::set<std::pair<block_idx, block_idx>> execEdges;
|
||||
|
||||
std::queue<std::pair<block_idx, block_idx>> cfgWorklist;
|
||||
std::queue<furlang::ir::instruction*> ssaWorklist;
|
||||
|
||||
std::unordered_map<furlang::ir::instruction*, block_idx> blockMap;
|
||||
|
||||
for (block_idx idx = 0; idx < ctx.function->blocks().size(); ++idx) {
|
||||
const auto& block = ctx.function->blocks()[idx];
|
||||
auto& instrs = block->instructions();
|
||||
for (auto it = instrs.begin(); it != instrs.end(); ++it) {
|
||||
const auto& instr = *it;
|
||||
blockMap[instr.get()] = idx;
|
||||
for (const auto& op : instr->sources()) {
|
||||
if (op->type() != furlang::ir::operand_t::Register) continue;
|
||||
edges[op->reg()].push_back(instr.get());
|
||||
}
|
||||
}
|
||||
|
||||
blockMap[block->exit().get()] = idx;
|
||||
for (const auto& op : block->exit()->sources()) {
|
||||
if (op->type() != furlang::ir::operand_t::Register) continue;
|
||||
edges[op->reg()].push_back(block->exit().get());
|
||||
}
|
||||
}
|
||||
|
||||
cfgWorklist.push({ 0, 0 });
|
||||
while (!cfgWorklist.empty() || !ssaWorklist.empty()) {
|
||||
if (!cfgWorklist.empty()) {
|
||||
auto edge = cfgWorklist.front();
|
||||
cfgWorklist.pop();
|
||||
block_idx from = edge.first;
|
||||
block_idx to = edge.second;
|
||||
|
||||
if (execEdges.count(edge) != 0) continue;
|
||||
execEdges.insert(edge);
|
||||
|
||||
bool firstVisit = (execBlocks.find(to) == execBlocks.end());
|
||||
execBlocks.insert(to);
|
||||
|
||||
const auto& block = ctx.function->blocks()[to];
|
||||
if (firstVisit) {
|
||||
for (auto& instr : block->instructions()) {
|
||||
ssaWorklist.push(instr.get());
|
||||
}
|
||||
ssaWorklist.push(block->exit().get());
|
||||
} else {
|
||||
for (auto& instr : block->instructions()) {
|
||||
if (instr->type() != furlang::ir::instruction_t::Phi) break;
|
||||
ssaWorklist.push(instr.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!ssaWorklist.empty()) {
|
||||
auto* instr = ssaWorklist.front();
|
||||
ssaWorklist.pop();
|
||||
|
||||
block_idx blockIdx = blockMap[instr];
|
||||
if (execBlocks.find(blockIdx) == execBlocks.end()) continue;
|
||||
|
||||
lattice newLat = { lattice::Top };
|
||||
|
||||
switch (instr->type()) {
|
||||
case furlang::ir::instruction_t::Phi: {
|
||||
auto& phi = dynamic_cast<furlang::ir::phi_instruction&>(*instr);
|
||||
for (const auto& [op, label] : phi.labels()) {
|
||||
if (execEdges.count({ label, blockIdx }) == 0) continue;
|
||||
lattice opLat = sccp_stage_get_lattice(latticeValues, op);
|
||||
if (opLat.type == lattice::Bottom) newLat.type = lattice::Bottom;
|
||||
if (opLat.type == lattice::Constant) {
|
||||
if (newLat.type == lattice::Top) {
|
||||
newLat = opLat;
|
||||
} else if (newLat.type == lattice::Constant && newLat.constant != opLat.constant) {
|
||||
newLat.type = lattice::Bottom;
|
||||
}
|
||||
}
|
||||
}
|
||||
} break;
|
||||
case furlang::ir::instruction_t::Assign: {
|
||||
newLat = sccp_stage_get_lattice(latticeValues, *instr->sources().front());
|
||||
} break;
|
||||
case furlang::ir::instruction_t::BinaryOp: {
|
||||
lattice lhs = sccp_stage_get_lattice(latticeValues, *instr->sources()[0]);
|
||||
lattice rhs = sccp_stage_get_lattice(latticeValues, *instr->sources()[1]);
|
||||
|
||||
if (lhs.type == lattice::Bottom || rhs.type == lattice::Bottom) {
|
||||
newLat.type = lattice::Bottom;
|
||||
} else if (lhs.type == lattice::Constant && rhs.type == lattice::Constant) {
|
||||
newLat.type = lattice::Constant;
|
||||
switch (dynamic_cast<const furlang::ir::binary_op_instruction&>(*instr).op_type()) {
|
||||
case furlang::ir::binary_op_instruction_t::Add:
|
||||
newLat.constant = lhs.constant + rhs.constant;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::Sub:
|
||||
newLat.constant = lhs.constant - rhs.constant;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::Mul:
|
||||
newLat.constant = lhs.constant * rhs.constant;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::Div:
|
||||
newLat.constant = lhs.constant / rhs.constant;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::Mod:
|
||||
newLat.constant = lhs.constant % rhs.constant;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::Eq:
|
||||
newLat.constant = (lhs.constant == rhs.constant) ? 1 : 0;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::NotEq:
|
||||
newLat.constant = (lhs.constant != rhs.constant) ? 1 : 0;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::LessThan:
|
||||
newLat.constant = (lhs.constant < rhs.constant) ? 1 : 0;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::GreaterThan:
|
||||
newLat.constant = (lhs.constant > rhs.constant) ? 1 : 0;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::LessEq:
|
||||
newLat.constant = (lhs.constant <= rhs.constant) ? 1 : 0;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::GreaterEq:
|
||||
newLat.constant = (lhs.constant >= rhs.constant) ? 1 : 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} break;
|
||||
default: break;
|
||||
}
|
||||
|
||||
if (instr->has_destination() && instr->destination().type() == furlang::ir::operand_t::Register) {
|
||||
auto dst = instr->destination().reg();
|
||||
if (!(latticeValues[dst] == newLat)) {
|
||||
latticeValues[dst] = newLat;
|
||||
for (auto* uInstr : edges[dst])
|
||||
ssaWorklist.push(uInstr);
|
||||
}
|
||||
}
|
||||
|
||||
if (instr == ctx.function->blocks()[blockIdx]->exit().get()) {
|
||||
auto* exit = ctx.function->blocks()[blockIdx]->exit().get();
|
||||
if (exit->type() == furlang::ir::instruction_t::Branch) {
|
||||
auto& br = dynamic_cast<furlang::ir::branch_instruction&>(*exit);
|
||||
cfgWorklist.push({ blockIdx, br.block() });
|
||||
} else if (exit->type() == furlang::ir::instruction_t::BranchCond) {
|
||||
auto& br = dynamic_cast<furlang::ir::branch_cond_instruction&>(*exit);
|
||||
lattice cond = sccp_stage_get_lattice(latticeValues, *exit->sources()[0]);
|
||||
|
||||
if (cond.type == lattice::Constant) {
|
||||
if (cond.constant != 0)
|
||||
cfgWorklist.push({ blockIdx, br.if_block() });
|
||||
else
|
||||
cfgWorklist.push({ blockIdx, br.else_block() });
|
||||
} else {
|
||||
cfgWorklist.push({ blockIdx, br.if_block() });
|
||||
cfgWorklist.push({ blockIdx, br.else_block() });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (block_idx i = 0; i < ctx.function->blocks().size(); ++i) {
|
||||
if (execBlocks.find(i) == execBlocks.end()) {
|
||||
ctx.function->blocks()[i]->instructions().clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto& block = ctx.function->blocks()[i];
|
||||
|
||||
for (auto& instr : block->instructions()) {
|
||||
for (auto& op : instr->sources()) {
|
||||
if (op->type() != furlang::ir::operand_t::Register) continue;
|
||||
auto reg = op->reg();
|
||||
if (latticeValues[reg].type != lattice::Constant) continue;
|
||||
*op = furlang::ir::operand::new_integer(latticeValues[reg].constant);
|
||||
}
|
||||
}
|
||||
|
||||
auto* exit = block->exit().get();
|
||||
if (exit->type() != furlang::ir::instruction_t::BranchCond) continue;
|
||||
auto& br = dynamic_cast<furlang::ir::branch_cond_instruction&>(*exit);
|
||||
lattice cond = sccp_stage_get_lattice(latticeValues, *exit->sources()[0]);
|
||||
if (cond.type != lattice::Constant) continue;
|
||||
block_idx target = (cond.constant != 0) ? br.if_block() : br.else_block();
|
||||
block->exit() = std::make_unique<furlang::ir::branch_instruction>(target);
|
||||
}
|
||||
}
|
||||
|
||||
static void adce_stage(function_context& ctx) {
|
||||
std::unordered_map<register_op, furlang::ir::instruction*> defMap;
|
||||
std::unordered_set<furlang::ir::instruction*> alive;
|
||||
std::queue<furlang::ir::instruction*> worklist;
|
||||
|
||||
for (block_idx blockIdx = 0; blockIdx < ctx.function->blocks().size(); ++blockIdx) {
|
||||
const auto& block = ctx.function->blocks()[blockIdx];
|
||||
|
||||
for (auto& instr : block->instructions()) {
|
||||
if (instr->has_destination() && instr->destination().type() == furlang::ir::operand_t::Register) {
|
||||
defMap[instr->destination().reg()] = instr.get();
|
||||
}
|
||||
}
|
||||
|
||||
auto* exit = block->exit().get();
|
||||
alive.insert(exit);
|
||||
worklist.push(exit);
|
||||
}
|
||||
|
||||
while (!worklist.empty()) {
|
||||
const auto* instr = worklist.front();
|
||||
worklist.pop();
|
||||
|
||||
for (const auto& op : instr->sources()) {
|
||||
if (op->type() != furlang::ir::operand_t::Register) continue;
|
||||
auto src = op->reg();
|
||||
|
||||
if (defMap.find(src) == defMap.end()) continue;
|
||||
auto* defInstr = defMap[src];
|
||||
if (alive.insert(defInstr).second) {
|
||||
worklist.push(defInstr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (block_idx blockIdx = 0; blockIdx < ctx.function->blocks().size(); ++blockIdx) {
|
||||
const auto& block = ctx.function->blocks()[blockIdx];
|
||||
auto& instrs = block->instructions();
|
||||
|
||||
auto it = instrs.begin();
|
||||
while (it != instrs.end()) {
|
||||
it = (alive.find(it->get()) != alive.end()) ? it + 1 : instrs.erase(it);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void post_process::process(furlang::ir::mod& mod) {
|
||||
for (const auto& func : mod.functions()) {
|
||||
if (!func || func->blocks().empty()) continue;
|
||||
function_context ctx{ func.get() };
|
||||
|
||||
for (const auto& stage : m_stages) {
|
||||
switch (stage) {
|
||||
case Ssa: ssa_stage(ctx); break;
|
||||
case Sccp: sccp_stage(ctx); break;
|
||||
case Adce: adce_stage(ctx); break;
|
||||
case DeSsa: dessa_stage(ctx); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace furc::front
|
||||
@@ -1,640 +0,0 @@
|
||||
#include "furc/front/ssa.hpp"
|
||||
|
||||
#include "furlang/ir/instruction.hpp"
|
||||
#include "furlang/ir/operand.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <stack>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace furc::front {
|
||||
|
||||
void ssa::optimize(furlang::ir::module& mod) {
|
||||
for (const auto& func : mod.functions()) {
|
||||
ssa::optimize(func);
|
||||
ssa::constant_propagation(func);
|
||||
ssa::dead_code_elimination(func);
|
||||
ssa::copy_propagation(func);
|
||||
ssa::dead_code_elimination(func);
|
||||
ssa::de_ssa(func);
|
||||
}
|
||||
}
|
||||
|
||||
void ssa::optimize(const std::unique_ptr<furlang::ir::function>& func) {
|
||||
block_map_t predecessors;
|
||||
block_map_t successors;
|
||||
|
||||
std::unordered_map<furlang::ir::register_t, std::unordered_set<furlang::ir::block_index>> regSites;
|
||||
|
||||
std::unordered_map<furlang::ir::block_index, furlang::ir::block_index> idoms;
|
||||
|
||||
std::unordered_map<furlang::ir::register_t, std::uint32_t> regVers;
|
||||
std::unordered_map<furlang::ir::register_t, std::stack<std::uint32_t>> regVerStacks;
|
||||
std::unordered_map<furlang::ir::block_index, std::vector<furlang::ir::block_index>> domTree;
|
||||
|
||||
for (furlang::ir::block_index i = 0; i < func->blocks().size(); ++i) {
|
||||
const auto& block = func->blocks()[i];
|
||||
|
||||
for (const auto& instr : block->instructions()) {
|
||||
if (instr->has_destination()) {
|
||||
if (instr->destination().type() == furlang::ir::operand_t::Register) {
|
||||
regSites[instr->destination().reg()].insert(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const auto& exit = block->exit();
|
||||
switch (exit->type()) {
|
||||
case furlang::ir::instruction_t::Branch: {
|
||||
const auto& br = dynamic_cast<const furlang::ir::branch_instruction&>(*exit);
|
||||
predecessors[br.block()].push_back(i);
|
||||
successors[i].push_back(br.block());
|
||||
} break;
|
||||
case furlang::ir::instruction_t::BranchCond: {
|
||||
const auto& br = dynamic_cast<const furlang::ir::branch_cond_instruction&>(*exit);
|
||||
predecessors[br.if_block()].push_back(i);
|
||||
predecessors[br.else_block()].push_back(i);
|
||||
successors[i].push_back(br.if_block());
|
||||
successors[i].push_back(br.else_block());
|
||||
} break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
std::unordered_set<furlang::ir::register_t> globalRegs;
|
||||
for (furlang::ir::block_index i = 0; i < func->blocks().size(); ++i) {
|
||||
const auto& block = func->blocks()[i];
|
||||
for (const auto& instr : block->instructions()) {
|
||||
for (const auto& operand : instr->sources()) {
|
||||
if (operand->type() == furlang::ir::operand_t::Register) {
|
||||
auto reg = operand->reg();
|
||||
if (regSites[reg].find(i) == regSites[reg].end()) {
|
||||
globalRegs.insert(reg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const auto& operand : block->exit()->sources()) {
|
||||
if (operand->type() == furlang::ir::operand_t::Register) {
|
||||
auto reg = operand->reg();
|
||||
if (regSites[reg].find(i) == regSites[reg].end()) {
|
||||
globalRegs.insert(reg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::unordered_set<furlang::ir::block_index> visited;
|
||||
std::vector<furlang::ir::block_index> rpoOrder;
|
||||
dfs_rpo(0, successors, visited, rpoOrder);
|
||||
std::reverse(rpoOrder.begin(), rpoOrder.end());
|
||||
|
||||
std::unordered_map<furlang::ir::block_index, std::size_t> rpoIndex;
|
||||
for (std::size_t i = 0; i < rpoOrder.size(); ++i) {
|
||||
rpoIndex[rpoOrder[i]] = i;
|
||||
}
|
||||
|
||||
auto intersect = [&](furlang::ir::block_index block1, furlang::ir::block_index block2) {
|
||||
while (block1 != block2) {
|
||||
while (rpoIndex[block1] > rpoIndex[block2]) {
|
||||
block1 = idoms[block1];
|
||||
}
|
||||
while (rpoIndex[block2] > rpoIndex[block1]) {
|
||||
block2 = idoms[block2];
|
||||
}
|
||||
}
|
||||
return block1;
|
||||
};
|
||||
|
||||
if (rpoOrder.empty()) return;
|
||||
auto entry = rpoOrder.front();
|
||||
idoms[entry] = entry;
|
||||
|
||||
bool changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
|
||||
for (std::size_t i = 1; i < rpoOrder.size(); ++i) {
|
||||
auto block = rpoOrder[i];
|
||||
|
||||
furlang::ir::block_index newIdom = 0;
|
||||
bool found = false;
|
||||
for (auto pred : predecessors[block]) {
|
||||
if (idoms.find(pred) == idoms.end()) continue;
|
||||
if (!found) {
|
||||
newIdom = pred;
|
||||
found = true;
|
||||
} else {
|
||||
newIdom = intersect(pred, newIdom);
|
||||
}
|
||||
}
|
||||
|
||||
if (idoms.find(block) == idoms.end() || idoms[block] != newIdom) {
|
||||
idoms[block] = newIdom;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::unordered_map<furlang::ir::block_index, std::unordered_set<furlang::ir::block_index>> df;
|
||||
for (auto block : rpoOrder) {
|
||||
df[block] = std::unordered_set<furlang::ir::block_index>{};
|
||||
}
|
||||
|
||||
for (auto block : rpoOrder) {
|
||||
if (predecessors[block].size() < 2) continue;
|
||||
|
||||
for (auto pred : predecessors[block]) {
|
||||
auto runner = pred;
|
||||
while (runner != idoms[block]) {
|
||||
df[runner].insert(block);
|
||||
runner = idoms[runner];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::unordered_map<furlang::ir::block_index, std::unordered_set<furlang::ir::register_t>> phis;
|
||||
|
||||
for (const auto& [reg, blocks] : regSites) {
|
||||
if (globalRegs.find(reg) == globalRegs.end()) continue;
|
||||
|
||||
std::vector<furlang::ir::block_index> worklist(blocks.begin(), blocks.end());
|
||||
std::unordered_set<furlang::ir::block_index> added;
|
||||
while (!worklist.empty()) {
|
||||
auto block = worklist.back();
|
||||
worklist.pop_back();
|
||||
for (auto frontier : df[block]) {
|
||||
if (added.find(frontier) != added.end()) continue;
|
||||
phis[frontier].insert(reg);
|
||||
added.insert(frontier);
|
||||
if (blocks.find(frontier) == blocks.end()) {
|
||||
worklist.push_back(frontier);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (furlang::ir::block_index i = 0; i < func->blocks().size(); ++i) {
|
||||
if (phis.find(i) == phis.end()) continue;
|
||||
const auto& block = func->blocks()[i];
|
||||
const auto& preds = predecessors[i];
|
||||
|
||||
for (auto reg : phis[i]) {
|
||||
auto phiInstr = std::make_unique<furlang::ir::phi_instruction>(reg);
|
||||
for (auto pred : preds) {
|
||||
phiInstr->labels().emplace_back(furlang::ir::operand::new_reg(reg), pred);
|
||||
}
|
||||
block->instructions().emplace(block->instructions().begin(), std::move(phiInstr));
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& [block, idom] : idoms) {
|
||||
if (block != idom) domTree[idom].push_back(block);
|
||||
}
|
||||
|
||||
std::function<void(furlang::ir::block_index)> renameBlock = [&](furlang::ir::block_index blockIndex) -> void {
|
||||
std::unordered_map<furlang::ir::register_t, std::uint32_t> pushed;
|
||||
|
||||
const auto& block = func->blocks()[blockIndex];
|
||||
for (auto& instr : block->instructions()) {
|
||||
if (instr->type() != furlang::ir::instruction_t::Phi) continue;
|
||||
auto orig = instr->destination().reg();
|
||||
std::uint32_t newVer = regVers[orig]++;
|
||||
instr->destination().reg().ver = newVer;
|
||||
regVerStacks[orig].push(newVer);
|
||||
++pushed[orig];
|
||||
}
|
||||
|
||||
for (auto& instr : block->instructions()) {
|
||||
if (instr->type() == furlang::ir::instruction_t::Phi) continue;
|
||||
|
||||
for (auto& operand : instr->sources()) {
|
||||
if (operand->type() != furlang::ir::operand_t::Register) continue;
|
||||
auto orig = operand->reg();
|
||||
if (!regVerStacks[orig].empty()) {
|
||||
operand->reg().ver = regVerStacks[orig].top();
|
||||
}
|
||||
}
|
||||
|
||||
if (instr->has_destination() && instr->destination().type() == furlang::ir::operand_t::Register) {
|
||||
auto orig = instr->destination().reg();
|
||||
std::uint32_t newVer = regVers[orig]++;
|
||||
instr->destination().reg().ver = newVer;
|
||||
regVerStacks[orig].push(newVer);
|
||||
++pushed[orig];
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& operand : block->exit()->sources()) {
|
||||
if (operand->type() != furlang::ir::operand_t::Register) continue;
|
||||
auto orig = operand->reg();
|
||||
if (!regVerStacks[orig].empty()) {
|
||||
operand->reg().ver = regVerStacks[orig].top();
|
||||
}
|
||||
}
|
||||
|
||||
for (auto succIndex : successors[blockIndex]) {
|
||||
const auto& succ = func->blocks()[succIndex];
|
||||
for (auto& instr : succ->instructions()) {
|
||||
if (instr->type() != furlang::ir::instruction_t::Phi) break;
|
||||
auto& phi = dynamic_cast<furlang::ir::phi_instruction&>(*instr);
|
||||
for (auto& [op, bl] : phi.labels()) {
|
||||
if (bl != blockIndex) continue;
|
||||
if (regVerStacks[op.reg()].empty()) continue;
|
||||
op.reg().ver = regVerStacks[op.reg()].top();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& child : domTree[blockIndex]) {
|
||||
renameBlock(child);
|
||||
}
|
||||
|
||||
for (const auto& [reg, count] : pushed) {
|
||||
for (std::uint32_t i = 0; i < count; ++i) {
|
||||
regVerStacks[reg].pop();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
renameBlock(entry);
|
||||
}
|
||||
|
||||
void ssa::de_ssa(const std::unique_ptr<furlang::ir::function>& func) {
|
||||
using namespace furlang::ir;
|
||||
|
||||
std::unordered_map<block_index, std::vector<std::unique_ptr<instruction>>> copies;
|
||||
for (block_index blockIdx = 0; blockIdx < func->blocks().size(); ++blockIdx) {
|
||||
const auto& block = func->blocks()[blockIdx];
|
||||
auto& instrs = block->instructions();
|
||||
for (auto it = instrs.begin(); it != instrs.end();) {
|
||||
if ((*it)->type() != furlang::ir::instruction_t::Phi) {
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
auto& phi = dynamic_cast<phi_instruction&>(**it);
|
||||
auto dstReg = phi.destination().reg();
|
||||
for (auto& [srcOp, label] : phi.labels()) {
|
||||
copies[label].emplace_back(
|
||||
std::make_unique<assign_instruction>(std::move(srcOp), operand::new_reg(dstReg)));
|
||||
}
|
||||
it = instrs.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& [blockIdx, cpys] : copies) {
|
||||
if (blockIdx >= func->blocks().size()) continue;
|
||||
const auto& block = func->blocks()[blockIdx];
|
||||
auto& instrs = block->instructions();
|
||||
for (auto& copy : cpys) {
|
||||
instrs.push_back(std::move(copy));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum class lattice_t {
|
||||
Top,
|
||||
Constant,
|
||||
Bottom,
|
||||
};
|
||||
|
||||
struct lattice {
|
||||
lattice_t type = lattice_t::Top;
|
||||
std::uint64_t value = 0;
|
||||
|
||||
bool operator==(const lattice& rhs) const {
|
||||
if (type != rhs.type) return false;
|
||||
return type != lattice_t::Constant || value == rhs.value;
|
||||
}
|
||||
};
|
||||
|
||||
void ssa::constant_propagation(const std::unique_ptr<furlang::ir::function>& func) {
|
||||
using block_idx = furlang::ir::block_index;
|
||||
using reg_t = furlang::ir::register_operand;
|
||||
using reg2_t = furlang::ir::register_t;
|
||||
|
||||
std::unordered_map<reg_t, lattice> latVals;
|
||||
std::unordered_map<reg2_t, std::vector<furlang::ir::instruction*>> edges;
|
||||
std::unordered_set<block_idx> executableBlocks;
|
||||
std::set<std::pair<block_idx, block_idx>> executedEdges;
|
||||
|
||||
std::queue<std::pair<block_idx, block_idx>> cfgWorklist;
|
||||
std::queue<furlang::ir::instruction*> ssaWorklist;
|
||||
|
||||
std::unordered_map<furlang::ir::instruction*, block_idx> blockMap;
|
||||
|
||||
auto getOperandLattice = [&](const furlang::ir::operand& op) -> lattice {
|
||||
if (op.type() == furlang::ir::operand_t::Integer) {
|
||||
lattice lat;
|
||||
lat.type = lattice_t::Constant;
|
||||
lat.value = op.integer();
|
||||
return lat;
|
||||
}
|
||||
if (op.type() == furlang::ir::operand_t::Register) {
|
||||
auto reg = op.reg();
|
||||
if (latVals.find(reg) == latVals.end()) return { lattice_t::Top };
|
||||
return latVals[reg];
|
||||
}
|
||||
return { lattice_t::Bottom };
|
||||
};
|
||||
|
||||
for (block_idx blockIdx = 0; blockIdx < func->blocks().size(); ++blockIdx) {
|
||||
const auto& block = func->blocks()[blockIdx];
|
||||
auto& instrs = block->instructions();
|
||||
for (auto it = instrs.begin(); it != instrs.end(); ++it) {
|
||||
const auto& instr = *it;
|
||||
blockMap[instr.get()] = blockIdx;
|
||||
for (const auto& op : instr->sources()) {
|
||||
if (op->type() != furlang::ir::operand_t::Register) continue;
|
||||
edges[op->reg()].push_back(instr.get());
|
||||
}
|
||||
}
|
||||
|
||||
blockMap[block->exit().get()] = blockIdx;
|
||||
for (const auto& op : block->exit()->sources()) {
|
||||
if (op->type() != furlang::ir::operand_t::Register) continue;
|
||||
edges[op->reg()].push_back(block->exit().get());
|
||||
}
|
||||
}
|
||||
|
||||
cfgWorklist.push({ 0, 0 });
|
||||
while (!cfgWorklist.empty() || !ssaWorklist.empty()) {
|
||||
if (!cfgWorklist.empty()) {
|
||||
auto edge = cfgWorklist.front();
|
||||
cfgWorklist.pop();
|
||||
block_idx from = edge.first;
|
||||
block_idx to = edge.second;
|
||||
|
||||
if (executedEdges.count(edge) != 0) continue;
|
||||
executedEdges.insert(edge);
|
||||
|
||||
bool firstVisit = (executableBlocks.find(to) == executableBlocks.end());
|
||||
executableBlocks.insert(to);
|
||||
|
||||
const auto& block = func->blocks()[to];
|
||||
if (firstVisit) {
|
||||
for (auto& instr : block->instructions()) {
|
||||
ssaWorklist.push(instr.get());
|
||||
}
|
||||
ssaWorklist.push(block->exit().get());
|
||||
} else {
|
||||
for (auto& instr : block->instructions()) {
|
||||
if (instr->type() != furlang::ir::instruction_t::Phi) break;
|
||||
ssaWorklist.push(instr.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!ssaWorklist.empty()) {
|
||||
auto* instr = ssaWorklist.front();
|
||||
ssaWorklist.pop();
|
||||
|
||||
block_idx blockIdx = blockMap[instr];
|
||||
if (executableBlocks.find(blockIdx) == executableBlocks.end()) continue;
|
||||
|
||||
lattice newLat = { lattice_t::Top };
|
||||
|
||||
switch (instr->type()) {
|
||||
case furlang::ir::instruction_t::Phi: {
|
||||
auto& phi = dynamic_cast<furlang::ir::phi_instruction&>(*instr);
|
||||
for (const auto& [op, label] : phi.labels()) {
|
||||
if (executedEdges.count({ label, blockIdx }) == 0) continue;
|
||||
lattice opLat = getOperandLattice(op);
|
||||
if (opLat.type == lattice_t::Bottom) newLat.type = lattice_t::Bottom;
|
||||
if (opLat.type == lattice_t::Constant) {
|
||||
if (newLat.type == lattice_t::Top) {
|
||||
newLat = opLat;
|
||||
} else if (newLat.type == lattice_t::Constant && newLat.value != opLat.value) {
|
||||
newLat.type = lattice_t::Bottom;
|
||||
}
|
||||
}
|
||||
}
|
||||
} break;
|
||||
case furlang::ir::instruction_t::Assign: {
|
||||
newLat = getOperandLattice(*instr->sources().front());
|
||||
} break;
|
||||
case furlang::ir::instruction_t::BinaryOp: {
|
||||
lattice lhs = getOperandLattice(*instr->sources()[0]);
|
||||
lattice rhs = getOperandLattice(*instr->sources()[1]);
|
||||
|
||||
if (lhs.type == lattice_t::Bottom || rhs.type == lattice_t::Bottom) {
|
||||
newLat.type = lattice_t::Bottom;
|
||||
} else if (lhs.type == lattice_t::Constant && rhs.type == lattice_t::Constant) {
|
||||
newLat.type = lattice_t::Constant;
|
||||
switch (dynamic_cast<const furlang::ir::binary_op_instruction&>(*instr).op_type()) {
|
||||
case furlang::ir::binary_op_instruction_t::Add: newLat.value = lhs.value + rhs.value; break;
|
||||
case furlang::ir::binary_op_instruction_t::Sub: newLat.value = lhs.value - rhs.value; break;
|
||||
case furlang::ir::binary_op_instruction_t::Mul: newLat.value = lhs.value * rhs.value; break;
|
||||
case furlang::ir::binary_op_instruction_t::Div: newLat.value = lhs.value / rhs.value; break;
|
||||
case furlang::ir::binary_op_instruction_t::Mod: newLat.value = lhs.value % rhs.value; break;
|
||||
case furlang::ir::binary_op_instruction_t::Eq:
|
||||
newLat.value = (lhs.value == rhs.value) ? 1 : 0;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::NotEq:
|
||||
newLat.value = (lhs.value != rhs.value) ? 1 : 0;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::LessThan:
|
||||
newLat.value = (lhs.value < rhs.value) ? 1 : 0;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::GreaterThan:
|
||||
newLat.value = (lhs.value > rhs.value) ? 1 : 0;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::LessEq:
|
||||
newLat.value = (lhs.value <= rhs.value) ? 1 : 0;
|
||||
break;
|
||||
case furlang::ir::binary_op_instruction_t::GreaterEq:
|
||||
newLat.value = (lhs.value >= rhs.value) ? 1 : 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} break;
|
||||
default: break;
|
||||
}
|
||||
|
||||
if (instr->has_destination() && instr->destination().type() == furlang::ir::operand_t::Register) {
|
||||
auto dst = instr->destination().reg();
|
||||
if (!(latVals[dst] == newLat)) {
|
||||
latVals[dst] = newLat;
|
||||
for (auto* uInstr : edges[dst])
|
||||
ssaWorklist.push(uInstr);
|
||||
}
|
||||
}
|
||||
|
||||
if (instr == func->blocks()[blockIdx]->exit().get()) {
|
||||
auto* exit = func->blocks()[blockIdx]->exit().get();
|
||||
if (exit->type() == furlang::ir::instruction_t::Branch) {
|
||||
auto& br = dynamic_cast<furlang::ir::branch_instruction&>(*exit);
|
||||
cfgWorklist.push({ blockIdx, br.block() });
|
||||
} else if (exit->type() == furlang::ir::instruction_t::BranchCond) {
|
||||
auto& br = dynamic_cast<furlang::ir::branch_cond_instruction&>(*exit);
|
||||
lattice cond = getOperandLattice(*exit->sources()[0]);
|
||||
|
||||
if (cond.type == lattice_t::Constant) {
|
||||
if (cond.value != 0)
|
||||
cfgWorklist.push({ blockIdx, br.if_block() });
|
||||
else
|
||||
cfgWorklist.push({ blockIdx, br.else_block() });
|
||||
} else {
|
||||
cfgWorklist.push({ blockIdx, br.if_block() });
|
||||
cfgWorklist.push({ blockIdx, br.else_block() });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (block_idx i = 0; i < func->blocks().size(); ++i) {
|
||||
if (executableBlocks.find(i) == executableBlocks.end()) {
|
||||
func->blocks()[i]->instructions().clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto& block = func->blocks()[i];
|
||||
|
||||
for (auto& instr : block->instructions()) {
|
||||
for (auto& op : instr->sources()) {
|
||||
if (op->type() != furlang::ir::operand_t::Register) continue;
|
||||
auto reg = op->reg();
|
||||
if (latVals[reg].type != lattice_t::Constant) continue;
|
||||
*op = furlang::ir::operand::new_integer(latVals[reg].value);
|
||||
}
|
||||
}
|
||||
|
||||
auto* exit = block->exit().get();
|
||||
if (exit->type() != furlang::ir::instruction_t::BranchCond) continue;
|
||||
auto& br = dynamic_cast<furlang::ir::branch_cond_instruction&>(*exit);
|
||||
lattice cond = getOperandLattice(*exit->sources()[0]);
|
||||
if (cond.type != lattice_t::Constant) continue;
|
||||
block_idx target = (cond.value != 0) ? br.if_block() : br.else_block();
|
||||
block->exit() = std::make_unique<furlang::ir::branch_instruction>(target);
|
||||
}
|
||||
}
|
||||
|
||||
void ssa::dead_code_elimination(const std::unique_ptr<furlang::ir::function>& func) {
|
||||
using block_idx = furlang::ir::block_index;
|
||||
using reg_t = furlang::ir::register_operand;
|
||||
|
||||
std::unordered_map<reg_t, furlang::ir::instruction*> defMap;
|
||||
std::unordered_set<furlang::ir::instruction*> alive;
|
||||
std::queue<furlang::ir::instruction*> worklist;
|
||||
|
||||
for (block_idx blockIdx = 0; blockIdx < func->blocks().size(); ++blockIdx) {
|
||||
const auto& block = func->blocks()[blockIdx];
|
||||
|
||||
for (auto& instr : block->instructions()) {
|
||||
if (instr->has_destination() && instr->destination().type() == furlang::ir::operand_t::Register) {
|
||||
defMap[instr->destination().reg()] = instr.get();
|
||||
}
|
||||
}
|
||||
|
||||
auto* exit = block->exit().get();
|
||||
alive.insert(exit);
|
||||
worklist.push(exit);
|
||||
}
|
||||
|
||||
while (!worklist.empty()) {
|
||||
const auto* instr = worklist.front();
|
||||
worklist.pop();
|
||||
|
||||
for (const auto& op : instr->sources()) {
|
||||
if (op->type() != furlang::ir::operand_t::Register) continue;
|
||||
auto src = op->reg();
|
||||
|
||||
if (defMap.find(src) == defMap.end()) continue;
|
||||
auto* defInstr = defMap[src];
|
||||
if (alive.insert(defInstr).second) {
|
||||
worklist.push(defInstr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (block_idx blockIdx = 0; blockIdx < func->blocks().size(); ++blockIdx) {
|
||||
const auto& block = func->blocks()[blockIdx];
|
||||
auto& instrs = block->instructions();
|
||||
|
||||
for (auto it = instrs.begin(); it != instrs.end();) {
|
||||
if (alive.find(it->get()) == alive.end()) {
|
||||
it = instrs.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ssa::copy_propagation(const std::unique_ptr<furlang::ir::function>& func) {
|
||||
using block_idx = furlang::ir::block_index;
|
||||
using reg_t = furlang::ir::register_operand;
|
||||
|
||||
std::unordered_map<reg_t, reg_t> aliasMap;
|
||||
|
||||
std::function<reg_t(const reg_t&)> findRep = [&](const reg_t& reg) -> reg_t {
|
||||
auto it = aliasMap.find(reg);
|
||||
if (it == aliasMap.end()) return reg;
|
||||
reg_t act = findRep(it->second);
|
||||
aliasMap[reg] = act;
|
||||
return act;
|
||||
};
|
||||
|
||||
for (block_idx blockIdx = 0; blockIdx < func->blocks().size(); ++blockIdx) {
|
||||
const auto& block = func->blocks()[blockIdx];
|
||||
for (auto& instr : block->instructions()) {
|
||||
if (instr->type() != furlang::ir::instruction_t::Assign) continue;
|
||||
auto& srcOp = *instr->sources().front();
|
||||
if (srcOp.type() != furlang::ir::operand_t::Register ||
|
||||
instr->destination().type() != furlang::ir::operand_t::Register)
|
||||
continue;
|
||||
reg_t dstReg = instr->destination().reg();
|
||||
reg_t srcReg = srcOp.reg();
|
||||
reg_t repSrc = findRep(srcReg);
|
||||
reg_t repDst = findRep(dstReg);
|
||||
if (repSrc == repDst) continue;
|
||||
aliasMap[repDst] = repSrc;
|
||||
}
|
||||
}
|
||||
|
||||
for (block_idx blockIdx = 0; blockIdx < func->blocks().size(); ++blockIdx) {
|
||||
const auto& block = func->blocks()[blockIdx];
|
||||
for (auto& instr : block->instructions()) {
|
||||
for (auto& op : instr->sources()) {
|
||||
if (op->type() != furlang::ir::operand_t::Register) continue;
|
||||
op->reg() = findRep(op->reg());
|
||||
}
|
||||
if (instr->type() != furlang::ir::instruction_t::Phi) continue;
|
||||
auto& phi = dynamic_cast<furlang::ir::phi_instruction&>(*instr);
|
||||
for (auto& [op, label] : phi.labels()) {
|
||||
if (op.type() != furlang::ir::operand_t::Register) continue;
|
||||
op.reg() = findRep(op.reg());
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& op : block->exit()->sources()) {
|
||||
if (op->type() != furlang::ir::operand_t::Register) continue;
|
||||
op->reg() = findRep(op->reg());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ssa::dfs_rpo(furlang::ir::block_index block,
|
||||
const block_map_t& successors,
|
||||
std::unordered_set<furlang::ir::block_index>& visited,
|
||||
std::vector<furlang::ir::block_index>& rpo) {
|
||||
visited.insert(block);
|
||||
if (auto it = successors.find(block); it != successors.end()) {
|
||||
for (auto successor : it->second) {
|
||||
if (visited.find(successor) == visited.end()) {
|
||||
dfs_rpo(successor, successors, visited, rpo);
|
||||
}
|
||||
}
|
||||
}
|
||||
rpo.push_back(block);
|
||||
}
|
||||
|
||||
} // namespace furc::front
|
||||
+13
-5
@@ -3,7 +3,8 @@
|
||||
#include "furc/ast/program.hpp"
|
||||
#include "furc/front/ir_generator.hpp"
|
||||
#include "furc/front/parser.hpp"
|
||||
#include "furc/front/ssa.hpp"
|
||||
#include "furc/front/post_process.hpp"
|
||||
#include "furlang/arena.hpp"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
@@ -19,7 +20,8 @@ int main(void) {
|
||||
}
|
||||
}
|
||||
)";
|
||||
furc::front::parser parser("<TEMP>", programStr);
|
||||
furlang::arena arena{};
|
||||
furc::front::parser parser(arena, "<TEMP>", programStr);
|
||||
furc::front::ir_generator generator;
|
||||
|
||||
auto programResult = parser.parse();
|
||||
@@ -30,11 +32,17 @@ int main(void) {
|
||||
const auto& program = *programResult;
|
||||
program->accept(generator);
|
||||
|
||||
auto module = std::move(generator.move_module());
|
||||
furc::front::ssa::optimize(module);
|
||||
auto mod = std::move(generator.move_module());
|
||||
|
||||
furc::front::post_process postProcess;
|
||||
postProcess.push_stage(furc::front::post_process::Ssa);
|
||||
postProcess.push_stage(furc::front::post_process::Sccp);
|
||||
postProcess.push_stage(furc::front::post_process::Adce);
|
||||
postProcess.push_stage(furc::front::post_process::DeSsa);
|
||||
postProcess.process(mod);
|
||||
|
||||
std::cout << "Generated IR:\n";
|
||||
for (const auto& function : module.functions()) {
|
||||
for (const auto& function : mod.functions()) {
|
||||
std::cout << function->name() << ":\n";
|
||||
furlang::ir::block_index blockIndex = 0;
|
||||
for (const auto& block : function->blocks()) {
|
||||
|
||||
@@ -106,6 +106,55 @@ private:
|
||||
region* m_tail = nullptr;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class arena_allocator {
|
||||
template <typename>
|
||||
friend class arena_allocator;
|
||||
public:
|
||||
using value_type = T;
|
||||
public:
|
||||
explicit arena_allocator(arena& arena) noexcept
|
||||
: m_arena(&arena) {}
|
||||
|
||||
template <typename U>
|
||||
arena_allocator(const arena_allocator<U>& other) noexcept
|
||||
: m_arena(other.m_arena) {}
|
||||
|
||||
template <typename U>
|
||||
arena_allocator& operator=(const arena_allocator<U>& other) noexcept {
|
||||
if (this == &other) return *this;
|
||||
m_arena = other.m_arena;
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename U>
|
||||
arena_allocator(arena_allocator<U>&& other) noexcept
|
||||
: m_arena(std::move(other.m_arena)) {}
|
||||
|
||||
template <typename U>
|
||||
arena_allocator& operator=(arena_allocator<U>&& other) noexcept {
|
||||
if (this == &other) return *this;
|
||||
m_arena = std::move(other.m_arena);
|
||||
return *this;
|
||||
}
|
||||
public:
|
||||
[[nodiscard]] T* allocate(std::size_t count = 1) { return m_arena->allocate<T>(count); }
|
||||
|
||||
void deallocate(T* ptr, std::size_t count) noexcept {}
|
||||
public:
|
||||
template <typename U>
|
||||
bool operator==(const arena_allocator<U>& other) const noexcept {
|
||||
return m_arena == other.m_arena;
|
||||
}
|
||||
|
||||
template <typename U>
|
||||
bool operator!=(const arena_allocator<U>& other) const noexcept {
|
||||
return m_arena != other.m_arena;
|
||||
}
|
||||
private:
|
||||
arena* m_arena;
|
||||
};
|
||||
|
||||
} // namespace furlang
|
||||
|
||||
#endif // FURLANG_ARENA_HPP
|
||||
@@ -12,11 +12,11 @@ namespace ir {
|
||||
/**
|
||||
* @brief IR module
|
||||
*/
|
||||
class module {
|
||||
class mod {
|
||||
public:
|
||||
using value_type = std::unique_ptr<function>; /**< Value type. */
|
||||
public:
|
||||
module() = default;
|
||||
mod() = default;
|
||||
public:
|
||||
/**
|
||||
* @brief Pushes and returns a new IR function.
|
||||
|
||||
@@ -1,49 +1,13 @@
|
||||
#ifndef FURVM_CONSTANT_HPP
|
||||
#define FURVM_CONSTANT_HPP
|
||||
|
||||
#include "furvm/exceptions.hpp"
|
||||
#include "furvm/fwd.hpp"
|
||||
|
||||
#include <exception>
|
||||
#include <string_view>
|
||||
|
||||
namespace furvm {
|
||||
|
||||
/**
|
||||
* @brief Bad constant access exception.
|
||||
*/
|
||||
class bad_constant_access : public std::exception {
|
||||
public:
|
||||
bad_constant_access() = default;
|
||||
~bad_constant_access() override = default;
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
bad_constant_access(bad_constant_access&&) noexcept = default;
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
bad_constant_access& operator=(bad_constant_access&&) noexcept = default;
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
bad_constant_access(const bad_constant_access&) = default;
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
bad_constant_access& operator=(const bad_constant_access&) = default;
|
||||
public:
|
||||
/**
|
||||
* @brief Returns a C-style string describing the cause of the error.
|
||||
*
|
||||
* @return The cause of the error.
|
||||
*/
|
||||
const char* what() const noexcept override { return "bad constant access"; }
|
||||
};
|
||||
|
||||
enum class constant_t : std::uint8_t {
|
||||
String, /**< String constant. */
|
||||
};
|
||||
|
||||
+124
-57
@@ -2,21 +2,26 @@
|
||||
#define FURVM_CONTEXT_HPP
|
||||
|
||||
#include "furlang/arena.hpp"
|
||||
#include "furvm/executor.hpp"
|
||||
#include "furvm/fwd.hpp"
|
||||
#include "furvm/module.hpp"
|
||||
#include "furvm/handle.hpp"
|
||||
#include "furvm/module.hpp" // IWYU pragma: keep
|
||||
#include "furvm/thing.hpp" // IWYU pragma: keep
|
||||
|
||||
#include <queue>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
#include <cstddef>
|
||||
#include <utility>
|
||||
|
||||
namespace furvm {
|
||||
|
||||
class context {
|
||||
public:
|
||||
friend class executor;
|
||||
friend class thing;
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a context.
|
||||
*/
|
||||
context();
|
||||
|
||||
~context() = default;
|
||||
|
||||
/**
|
||||
@@ -33,79 +38,141 @@ public:
|
||||
context& operator=(const context&) = delete;
|
||||
public:
|
||||
/**
|
||||
* @brief Adds a module to this context.
|
||||
* @brief Emplaces a module in the context.
|
||||
*
|
||||
* @param args Arguments to forward to module's constructor.
|
||||
* @return An index to the emplaced module.
|
||||
* @param args Arguments forwarded to the module constructor.
|
||||
* @return The emplaced module.
|
||||
*/
|
||||
template <typename... Args, typename = std::enable_if_t<std::is_constructible_v<mod, module_handle, Args...>>>
|
||||
constexpr const auto& emplace(Args&&... args) {
|
||||
module_handle id = static_cast<module_handle>(m_modules.size());
|
||||
return m_modules.emplace_back(std::make_unique<mod>(id, std::forward<Args>(args)...));
|
||||
template <typename... Args>
|
||||
auto emplace_module(Args&&... args) {
|
||||
return m_modules.emplace(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Erases a module from this context.
|
||||
* @brief Returns a module from the context.
|
||||
*
|
||||
* @param index Index to the module.
|
||||
* @return Old value.
|
||||
* @param args Module's id.
|
||||
* @return A handle to the module.
|
||||
*/
|
||||
mod_p erase(module_handle index) {
|
||||
if (index >= m_modules.size()) return nullptr;
|
||||
return std::move(m_modules[index]);
|
||||
template <typename... Args>
|
||||
auto module_at(Args&&... args) {
|
||||
return m_modules.at(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a module of this context.
|
||||
* @brief Returns a module from the context.
|
||||
*
|
||||
* @param index Position of the module.
|
||||
* @return The module.
|
||||
* @param args Module's id.
|
||||
* @return A handle to the module.
|
||||
*/
|
||||
constexpr mod_p& operator[](module_handle index) { return m_modules[index]; }
|
||||
template <typename... Args>
|
||||
auto module_at(Args&&... args) const {
|
||||
return m_modules.at(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a module of this context.
|
||||
* @brief Erases a module from the context.
|
||||
*
|
||||
* @param index Position of the module.
|
||||
* @return The module.
|
||||
* @param args Module's id.
|
||||
*/
|
||||
constexpr const mod_p& operator[](module_handle index) const { return m_modules[index]; }
|
||||
|
||||
/**
|
||||
* @brief Returns a module of this context.
|
||||
*
|
||||
* @param index Position of the module.
|
||||
* @return The module.
|
||||
*/
|
||||
constexpr mod_p& at(module_handle index) { return m_modules.at(index); }
|
||||
|
||||
/**
|
||||
* @brief Returns a module of this context.
|
||||
*
|
||||
* @param index Position of the module.
|
||||
* @return The module.
|
||||
*/
|
||||
constexpr const mod_p& at(module_handle index) const { return m_modules.at(index); }
|
||||
|
||||
/**
|
||||
* @brief Returns how many does this context have modules.
|
||||
*
|
||||
* @return The module count.
|
||||
*/
|
||||
constexpr size_t size() const { return m_modules.size(); }
|
||||
template <typename... Args>
|
||||
void erase_module(Args&&... args) {
|
||||
m_modules.erase(std::forward<Args>(args)...);
|
||||
}
|
||||
public:
|
||||
/**
|
||||
* @brief Removes unreferenced things from the thing list.
|
||||
* @brief Emplaces an executor in the context.
|
||||
*
|
||||
* @param args Arguments forwarded to executor's constructor.
|
||||
* @return A handle to the emplaced executor.
|
||||
*/
|
||||
void collect();
|
||||
private:
|
||||
std::vector<mod_p> m_modules;
|
||||
std::vector<thing_p> m_things;
|
||||
std::vector<executor_p> m_executors;
|
||||
template <typename... Args>
|
||||
auto emplace_executor(Args&&... args) {
|
||||
return m_executors.emplace_back(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns an executor from the context.
|
||||
*
|
||||
* @param args Id of the executor.
|
||||
* @return A handle to the executor.
|
||||
*/
|
||||
template <typename... Args>
|
||||
auto executor_at(Args&&... args) {
|
||||
return m_executors.at(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns an executor from the context.
|
||||
*
|
||||
* @param args Id of the executor.
|
||||
* @return A handle to the executor.
|
||||
*/
|
||||
template <typename... Args>
|
||||
auto executor_at(Args&&... args) const {
|
||||
return m_executors.at(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Erases an executor from the context.
|
||||
*
|
||||
* @param args Id of the executor.
|
||||
*/
|
||||
template <typename... Args>
|
||||
void erase_executor(Args&&... args) {
|
||||
m_executors.erase(std::forward<Args>(args)...);
|
||||
}
|
||||
public:
|
||||
template <typename... Args>
|
||||
auto emplace_thing(Args&&... args) {
|
||||
return m_things.emplace_back(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a thing from the context.
|
||||
*
|
||||
* @param args Id of the thing.
|
||||
* @return A handle to the thing.
|
||||
*/
|
||||
template <typename... Args>
|
||||
auto thing_at(Args&&... args) {
|
||||
return m_things.at(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a thing from the context.
|
||||
*
|
||||
* @param args Id of the thing.
|
||||
* @return A handle to the thing.
|
||||
*/
|
||||
template <typename... Args>
|
||||
auto thing_at(Args&&... args) const {
|
||||
return m_things.at(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Erases a thing from the context.
|
||||
*
|
||||
* @param args Id of the thing.
|
||||
*/
|
||||
template <typename... Args>
|
||||
void erase_thing(Args&&... args) {
|
||||
m_things.erase(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns context's thing allocator.
|
||||
*
|
||||
* @return The thing allocator.
|
||||
*/
|
||||
thing_allocator<std::byte> thing_alloc() const { return m_thingAllocator; }
|
||||
private:
|
||||
handle_container<mod_h> m_modules;
|
||||
handle_container<thing_h> m_things;
|
||||
handle_container<executor_h> m_executors;
|
||||
|
||||
std::queue<thing_handle> m_deadThings;
|
||||
std::vector<void*> m_deadThingData;
|
||||
furlang::arena m_thingArena;
|
||||
thing_allocator<std::byte> m_thingAllocator;
|
||||
};
|
||||
|
||||
} // namespace furvm
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
#ifndef FURVM_DETAIL_HANDLE_HPP
|
||||
#define FURVM_DETAIL_HANDLE_HPP
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
namespace furvm {
|
||||
namespace detail {
|
||||
|
||||
/**
|
||||
* @brief Default specialization for header_has_refcount type trait.
|
||||
*/
|
||||
template <typename Header, typename = void>
|
||||
struct header_has_refcount : std::false_type {};
|
||||
|
||||
/**
|
||||
* @brief Specialization for header_has_refcount type trait.
|
||||
*/
|
||||
template <typename Header>
|
||||
struct header_has_refcount<Header,
|
||||
std::void_t<decltype(std::declval<Header&>().acquire()),
|
||||
decltype(std::declval<Header&>().release()),
|
||||
decltype(std::declval<Header&>().reference_count())>> : std::true_type {};
|
||||
|
||||
/**
|
||||
* @brief An alias for header_has_refcount's value.
|
||||
*/
|
||||
template <typename Header>
|
||||
static constexpr auto header_has_refcount_v = header_has_refcount<Header>::value;
|
||||
|
||||
} // namespace detail
|
||||
} // namespace furvm
|
||||
|
||||
#endif // FURVM_DETAIL_HANDLE_HPP
|
||||
@@ -0,0 +1,79 @@
|
||||
#ifndef FURVM_DETAIL_SERIALIZATION_HPP
|
||||
#define FURVM_DETAIL_SERIALIZATION_HPP
|
||||
|
||||
#include <cstdint>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
|
||||
namespace furvm {
|
||||
namespace detail {
|
||||
|
||||
/**
|
||||
* @brief Serializes an integer.
|
||||
*
|
||||
* @param os Output stream.
|
||||
* @param value Integer.
|
||||
* @return The output stream.
|
||||
*/
|
||||
std::ostream& serialize(std::ostream& os, std::int8_t value);
|
||||
std::ostream& serialize(std::ostream& os, std::int16_t value);
|
||||
|
||||
/**
|
||||
* @brief Serializes an integer.
|
||||
*
|
||||
* @param os Output stream.
|
||||
* @param value Integer.
|
||||
* @return The output stream.
|
||||
*/
|
||||
std::ostream& serialize(std::ostream& os, std::int32_t value);
|
||||
std::ostream& serialize(std::ostream& os, std::int64_t value);
|
||||
|
||||
/**
|
||||
* @brief Serializes an integer.
|
||||
*
|
||||
* @param os Output stream.
|
||||
* @param value Integer.
|
||||
* @return The output stream.
|
||||
*/
|
||||
std::ostream& serialize(std::ostream& os, std::uint8_t value);
|
||||
|
||||
/**
|
||||
* @brief Serializes an integer.
|
||||
*
|
||||
* @param os Output stream.
|
||||
* @param value Integer.
|
||||
* @return The output stream.
|
||||
*/
|
||||
std::ostream& serialize(std::ostream& os, std::uint16_t value);
|
||||
|
||||
/**
|
||||
* @brief Serializes an integer.
|
||||
*
|
||||
* @param os Output stream.
|
||||
* @param value Integer.
|
||||
* @return The output stream.
|
||||
*/
|
||||
std::ostream& serialize(std::ostream& os, std::uint32_t value);
|
||||
|
||||
/**
|
||||
* @brief Serializes an integer.
|
||||
*
|
||||
* @param os Output stream.
|
||||
* @param value Integer.
|
||||
* @return The output stream.
|
||||
*/
|
||||
std::ostream& serialize(std::ostream& os, std::uint64_t value);
|
||||
|
||||
/**
|
||||
* @brief Serializes a string.
|
||||
*
|
||||
* @param os Output stream.
|
||||
* @param value String.
|
||||
* @return The output stream.
|
||||
*/
|
||||
std::ostream& serialize(std::ostream& os, const std::string& value);
|
||||
|
||||
} // namespace detail
|
||||
} // namespace furvm
|
||||
|
||||
#endif // FURVM_DETAIL_SERIALIZATION_HPP
|
||||
@@ -5,6 +5,75 @@
|
||||
|
||||
namespace furvm {
|
||||
|
||||
class bad_thing_access : public std::exception {
|
||||
public:
|
||||
bad_thing_access() = default;
|
||||
~bad_thing_access() override = default;
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
bad_thing_access(bad_thing_access&&) noexcept = default;
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
bad_thing_access& operator=(bad_thing_access&&) noexcept = default;
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
bad_thing_access(const bad_thing_access&) = default;
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
bad_thing_access& operator=(const bad_thing_access&) = default;
|
||||
public:
|
||||
/**
|
||||
* @brief Returns a C-style string describing the cause of the error.
|
||||
*
|
||||
* @return The cause of the error.
|
||||
*/
|
||||
const char* what() const noexcept override { return "bad thing access"; }
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Bad constant access exception.
|
||||
*/
|
||||
class bad_constant_access : public std::exception {
|
||||
public:
|
||||
bad_constant_access() = default;
|
||||
~bad_constant_access() override = default;
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
bad_constant_access(bad_constant_access&&) noexcept = default;
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
bad_constant_access& operator=(bad_constant_access&&) noexcept = default;
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
bad_constant_access(const bad_constant_access&) = default;
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
bad_constant_access& operator=(const bad_constant_access&) = default;
|
||||
public:
|
||||
/**
|
||||
* @brief Returns a C-style string describing the cause of the error.
|
||||
*
|
||||
* @return The cause of the error.
|
||||
*/
|
||||
const char* what() const noexcept override { return "bad constant access"; }
|
||||
};
|
||||
|
||||
class stack_underflow : public std::exception {
|
||||
public:
|
||||
stack_underflow() = default;
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
#define FURVM_EXECUTOR_HPP
|
||||
|
||||
#include "furvm/fwd.hpp"
|
||||
#include "furvm/module.hpp" // IWYU pragma: keep
|
||||
#include "furvm/thing.hpp" // IWYU pragma: keep
|
||||
|
||||
#include <stack>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace furvm {
|
||||
@@ -26,15 +29,6 @@ static inline executor_flags operator~(executor_flags flags) {
|
||||
}
|
||||
|
||||
class executor {
|
||||
private:
|
||||
/**
|
||||
* @brief A private token for the private constructor.
|
||||
*
|
||||
* Also `egzekutor` in Polish translates to `executor` I think.
|
||||
*/
|
||||
struct egzekutor {
|
||||
explicit egzekutor() = default;
|
||||
};
|
||||
public:
|
||||
/**
|
||||
* @brief Executor frame.
|
||||
@@ -42,22 +36,22 @@ public:
|
||||
* Call frame.
|
||||
*/
|
||||
struct frame {
|
||||
mod_p mod; /**< Shared pointer to a module with the bytecode. */
|
||||
mod_h mod; /**< Handle to the frame's module. */
|
||||
std::size_t position; /**< Cursor to a current instruction in the bytecode. */
|
||||
std::size_t stackBase; /**< Snapshot of the stack size before this frame. */
|
||||
|
||||
std::vector<thing_p> variables; /**< Frame variables. */
|
||||
std::vector<thing_h> variables; /**< Frame variables. */
|
||||
};
|
||||
public:
|
||||
/**
|
||||
* @brief Private constructor.
|
||||
* @brief Returns a new executor.
|
||||
*
|
||||
* @param id
|
||||
* @param context
|
||||
* @param context Context.
|
||||
*/
|
||||
executor(egzekutor, executor_handle id, const context_p& context);
|
||||
executor(const context_p& context)
|
||||
: m_context(context) {}
|
||||
|
||||
~executor();
|
||||
~executor() = default;
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
@@ -69,24 +63,16 @@ public:
|
||||
*/
|
||||
executor& operator=(executor&&) noexcept = default;
|
||||
|
||||
executor(const executor&) = delete;
|
||||
executor& operator=(const executor&) = delete;
|
||||
public:
|
||||
/**
|
||||
* @brief Returns a new executor.
|
||||
*
|
||||
* @param context Furvm context.
|
||||
* @return Shared pointer to the new executor.
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
static executor_p create(const context_p& context);
|
||||
public:
|
||||
/**
|
||||
* @brief Returns an id of this executor.
|
||||
*
|
||||
* @return The id.
|
||||
*/
|
||||
executor_handle id() const { return m_id; }
|
||||
executor(const executor&) = default;
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
executor& operator=(const executor&) = default;
|
||||
public:
|
||||
/**
|
||||
* @brief Returns flags of this executor.
|
||||
*
|
||||
@@ -97,9 +83,10 @@ public:
|
||||
/**
|
||||
* @brief Pushes a new frame.
|
||||
*
|
||||
* @param function Function.
|
||||
* @param mod Handle to the frame's module.
|
||||
* @param function Frame's function.
|
||||
*/
|
||||
void push_frame(const function_p& function);
|
||||
void push_frame(const mod_h& mod, function function);
|
||||
|
||||
/**
|
||||
* @brief Pops the top frame.
|
||||
@@ -116,68 +103,73 @@ public:
|
||||
frame frame() const;
|
||||
public:
|
||||
/**
|
||||
* @brief Pushes a thing onto the stack.
|
||||
* @brief Pushes a thing handle onto the stack.
|
||||
*
|
||||
* @param thing The thing to push.
|
||||
* @param handle Thing handle.
|
||||
*/
|
||||
void push_thing(const thing_p& thing);
|
||||
template <typename HandleFwd>
|
||||
void push_thing(HandleFwd&& handle) {
|
||||
m_stack.emplace(std::forward<HandleFwd>(handle));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Pushes a thing onto the stack.
|
||||
*
|
||||
* @param thing The thing to push.
|
||||
* Registers a new thing and pushes its handle onto the stack.
|
||||
*
|
||||
* @param thing Thing.
|
||||
* @return The pushed handle.
|
||||
*/
|
||||
void push_thing(thing_p&& thing);
|
||||
thing_h push_thing(class thing<>&& thing);
|
||||
|
||||
/**
|
||||
* @brief Pops a thing from the stack.
|
||||
*
|
||||
* @return The popped thing.
|
||||
* @return A handle to the popped thing.
|
||||
*/
|
||||
thing_p pop_thing();
|
||||
thing_h pop_thing();
|
||||
|
||||
/**
|
||||
* @brief Returns the top thing on the stack.
|
||||
*
|
||||
* @return The thing.
|
||||
* @return A handle to the top thing.
|
||||
*/
|
||||
thing_p thing() const;
|
||||
thing_h thing() const;
|
||||
public:
|
||||
/**
|
||||
* @brief Stores a thing in a variable.
|
||||
* @brief Stores a thing in a frame variable.
|
||||
*
|
||||
* @param variable Variable to store the thing in.
|
||||
* @param thing Thing to store.
|
||||
* @param variable Id of the variable in which the handle will be put.
|
||||
* @param thing Thing handle.
|
||||
*/
|
||||
void store_thing(variable_t variable, const thing_p& thing);
|
||||
void store_thing(variable_t variable, const thing_h& thing);
|
||||
|
||||
/**
|
||||
* @brief Stores a thing in a variable.
|
||||
* @brief Stores a thing in a frame variable.
|
||||
*
|
||||
* @param variable Variable to store the thing in.
|
||||
* @param thing Thing to store.
|
||||
* @param variable Id of the variable in which the handle will be put.
|
||||
* @param thing Thing handle.
|
||||
*/
|
||||
void store_thing(variable_t variable, thing_p&& thing);
|
||||
void store_thing(variable_t variable, thing_h&& thing);
|
||||
|
||||
/**
|
||||
* @brief Returns a thing stored in a variable.
|
||||
*
|
||||
* @param variable Variable where the thing is stored.
|
||||
* @return The thing stored in the variable.
|
||||
* @param variable Id of the variable from which the handle will be fetched.
|
||||
* @return A handle stored in the variable.
|
||||
*/
|
||||
thing_p load_thing(variable_t variable) const;
|
||||
thing_h load_thing(variable_t variable) const;
|
||||
public:
|
||||
/**
|
||||
* @brief Executes next instruction.
|
||||
*/
|
||||
void step();
|
||||
private:
|
||||
executor_handle m_id;
|
||||
executor_flags m_flags{}; // NOLINT(bugprone-invalid-enum-default-initialization)
|
||||
context_p m_context;
|
||||
|
||||
std::stack<struct frame> m_frames;
|
||||
std::stack<thing_p> m_stack;
|
||||
std::stack<thing_h> m_stack;
|
||||
};
|
||||
|
||||
} // namespace furvm
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
#define FURVM_FUNCTION_HPP
|
||||
|
||||
#include "furvm/fwd.hpp"
|
||||
#include "furvm/module.hpp" // IWYU pragma: keep
|
||||
|
||||
#include <functional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace furvm {
|
||||
|
||||
@@ -15,38 +16,55 @@ enum class function_t : std::uint8_t {
|
||||
Import, /**< A function imported from another module. */
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief A native function.
|
||||
*/
|
||||
using native_function = std::function<void(executor&)>;
|
||||
|
||||
class function {
|
||||
private:
|
||||
/**
|
||||
* @brief A private token for the private constructor.
|
||||
*
|
||||
* Also `funkcja` in Polish translates to `function` from what I heard.
|
||||
* @brief A function import.
|
||||
*/
|
||||
struct funkcja {
|
||||
explicit funkcja() = default;
|
||||
struct import_function {
|
||||
mod_id mod;
|
||||
function_id function;
|
||||
};
|
||||
|
||||
class function {
|
||||
public:
|
||||
/**
|
||||
* @brief Private constructor.
|
||||
* @brief Constructs a normal function.
|
||||
*
|
||||
* @param id
|
||||
* @param position
|
||||
* @param mod
|
||||
* @param name Name of the function.
|
||||
* @param position Offset in bytecode of the function.
|
||||
*/
|
||||
function(funkcja, function_handle id, std::size_t position, const mod_p& mod);
|
||||
template <typename Name>
|
||||
function(Name&& name, bytecode_pos position)
|
||||
: m_name(std::forward<Name>(name)), m_type(function_t::Normal), m_value(position) {}
|
||||
|
||||
/**
|
||||
* @brief Private constructor.
|
||||
* @brief Constructs a native function.
|
||||
*
|
||||
* @param id
|
||||
* @param native
|
||||
* @param mod
|
||||
* @param name Name of the function.
|
||||
* @param native Native function.
|
||||
*/
|
||||
function(funkcja, function_handle id, const native_function& native, const mod_p& mod);
|
||||
template <typename Name>
|
||||
function(Name&& name, const native_function& native)
|
||||
: m_name(std::forward<Name>(name)), m_type(function_t::Native), m_value(native) {}
|
||||
|
||||
~function() = default;
|
||||
/**
|
||||
* @brief Constructs an import function.
|
||||
*
|
||||
* @param name Name of the function.
|
||||
* @param imp Import function.
|
||||
*/
|
||||
template <typename Name>
|
||||
function(Name&& name, const import_function& imp)
|
||||
: m_name(std::forward<Name>(name)), m_type(function_t::Import), m_value(imp) {}
|
||||
|
||||
/**
|
||||
* @brief Destructs a function.
|
||||
*/
|
||||
~function();
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
@@ -58,32 +76,22 @@ public:
|
||||
*/
|
||||
function& operator=(function&&) noexcept;
|
||||
|
||||
function(const function&) = delete;
|
||||
function& operator=(const function&) = delete;
|
||||
public:
|
||||
/**
|
||||
* @brief Returns a new function.
|
||||
*
|
||||
* @param mod Module.
|
||||
* @param args Arguments to pass to the function constructor.
|
||||
* @return The new function.
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
template <typename... Args,
|
||||
typename = std::enable_if_t<std::is_constructible_v<function, funkcja, function_handle, Args..., const mod_p&>>>
|
||||
static function_p create(const mod_p& mod, Args&&... args) {
|
||||
function_handle id = mod->m_functions.size();
|
||||
function(const function&);
|
||||
|
||||
auto func = std::make_shared<function>(funkcja{}, id, std::forward<Args>(args)..., mod);
|
||||
mod->m_functions.emplace(mod->m_functions.begin() + id, func);
|
||||
return std::move(func);
|
||||
}
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
function& operator=(const function&);
|
||||
public:
|
||||
/**
|
||||
* @brief Returns an id of this function.
|
||||
* @brief Returns a name of this function.
|
||||
*
|
||||
* @return The id.
|
||||
* @return The name.
|
||||
*/
|
||||
constexpr function_handle id() const { return m_id; }
|
||||
constexpr const std::string& name() const { return m_name; }
|
||||
|
||||
/**
|
||||
* @brief Returns a type of this function.
|
||||
@@ -91,16 +99,9 @@ public:
|
||||
* @return The type.
|
||||
*/
|
||||
constexpr function_t type() const { return m_type; }
|
||||
|
||||
/**
|
||||
* @brief Returns a parent module of this function.
|
||||
*
|
||||
* @return A shared pointer to the module.
|
||||
*/
|
||||
const mod_p& mod() const { return m_module; }
|
||||
public:
|
||||
/**
|
||||
* @brief Returns a value for normal function.
|
||||
* @brief Returns normal function's value.
|
||||
*
|
||||
* @return The value.
|
||||
*/
|
||||
@@ -110,7 +111,7 @@ public:
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a value for native function.
|
||||
* @brief Returns native function's value.
|
||||
*
|
||||
* @return The value.
|
||||
*/
|
||||
@@ -120,36 +121,22 @@ public:
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a module of imported function.
|
||||
* @brief Returns import function's value.
|
||||
*
|
||||
* @return A handle to the module.
|
||||
* @return The name.
|
||||
*/
|
||||
module_handle imported_module() const {
|
||||
const import_function& imp() const {
|
||||
if (m_type != function_t::Import) throw std::runtime_error("function type mismatch");
|
||||
return m_value.imp.mod;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a module of imported function.
|
||||
*
|
||||
* @return A handle to the module.
|
||||
*/
|
||||
function_handle imported_function() const {
|
||||
if (m_type != function_t::Import) throw std::runtime_error("function type mismatch");
|
||||
return m_value.imp.function;
|
||||
return m_value.imp;
|
||||
}
|
||||
private:
|
||||
function_handle m_id;
|
||||
std::string m_name;
|
||||
function_t m_type;
|
||||
mod_p m_module;
|
||||
|
||||
union value {
|
||||
std::size_t position = 0;
|
||||
native_function native;
|
||||
struct {
|
||||
module_handle mod;
|
||||
function_handle function;
|
||||
} imp;
|
||||
import_function imp;
|
||||
|
||||
value() = default;
|
||||
|
||||
@@ -159,8 +146,8 @@ private:
|
||||
value(const native_function& native)
|
||||
: native(native) {}
|
||||
|
||||
value(module_handle mod, function_handle function)
|
||||
: imp({ mod, function }) {}
|
||||
value(const import_function& imp)
|
||||
: imp(imp) {}
|
||||
|
||||
~value() {}
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
#ifndef FURVM_HPP
|
||||
#define FURVM_HPP
|
||||
|
||||
#include "furvm/context.hpp" // IWYU pragma: export
|
||||
#include "furvm/executor.hpp" // IWYU pragma: export
|
||||
#include "furvm/function.hpp" // IWYU pragma: export
|
||||
#include "furvm/fwd.hpp" // IWYU pragma: export
|
||||
#include "furvm/handle.hpp" // IWYU pragma: export
|
||||
#include "furvm/instruction.hpp" // IWYU pragma: export
|
||||
#include "furvm/thing.hpp" // IWYU pragma: export
|
||||
|
||||
#endif // FURVM_HPP
|
||||
+64
-15
@@ -4,6 +4,7 @@
|
||||
#include <cstddef> // IWYU pragma: export
|
||||
#include <cstdint> // IWYU pragma: export
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
* @brief Furlang's virtual machine.
|
||||
@@ -17,6 +18,40 @@ namespace furvm {
|
||||
*/
|
||||
using byte = std::uint8_t;
|
||||
|
||||
/**
|
||||
* @brief An offset into bytecode.
|
||||
*/
|
||||
using bytecode_pos = std::uint64_t;
|
||||
|
||||
/**
|
||||
* @brief Handle header with reference count.
|
||||
*/
|
||||
template <typename Id>
|
||||
class refcount_header;
|
||||
|
||||
/**
|
||||
* @brief Generic handle header.
|
||||
*/
|
||||
template <typename Id>
|
||||
class generic_header;
|
||||
|
||||
/**
|
||||
* @brief Generic furvm object handle.
|
||||
*
|
||||
* @tparam Value Type of the handle's value.
|
||||
* @tparam Header Type of the handle's header.
|
||||
*/
|
||||
template <typename Value, typename Header>
|
||||
class handle;
|
||||
|
||||
/**
|
||||
* @brief Container for the handles.
|
||||
*
|
||||
* @tparam Handle Type of the container's handle.
|
||||
*/
|
||||
template <typename Handle, typename = void>
|
||||
class handle_container;
|
||||
|
||||
// constant.hpp
|
||||
|
||||
/**
|
||||
@@ -68,15 +103,15 @@ enum class function_t : std::uint8_t;
|
||||
*/
|
||||
class function;
|
||||
|
||||
/**
|
||||
* @brief An alias to a function shared pointer.
|
||||
*/
|
||||
using function_p = std::shared_ptr<function>;
|
||||
|
||||
/**
|
||||
* @brief Furvm function's index.
|
||||
*/
|
||||
using function_handle = std::uint16_t;
|
||||
using function_id = std::uint16_t;
|
||||
|
||||
/**
|
||||
* @brief A handle to a furvm function.
|
||||
*/
|
||||
using function_h = handle<function, refcount_header<function_id>>;
|
||||
|
||||
// module.hpp
|
||||
|
||||
@@ -94,9 +129,14 @@ class mod;
|
||||
using mod_p = std::shared_ptr<mod>;
|
||||
|
||||
/**
|
||||
* @brief Furvm module's index.
|
||||
* @brief An alias for a module's identifier.
|
||||
*/
|
||||
using module_handle = std::uint32_t;
|
||||
using mod_id = std::string;
|
||||
|
||||
/**
|
||||
* @brief A handle to a furvm module.
|
||||
*/
|
||||
using mod_h = handle<mod, refcount_header<mod_id>>;
|
||||
|
||||
// thing.hpp
|
||||
|
||||
@@ -112,23 +152,27 @@ enum class thing_t : std::uint8_t;
|
||||
*/
|
||||
class bad_thing_access;
|
||||
|
||||
template <typename T>
|
||||
class thing_allocator;
|
||||
|
||||
/**
|
||||
* @class thing
|
||||
* @brief Furvm thing.
|
||||
*
|
||||
* A stack element. Think of it like of a value in C++ or I guess a class in java.
|
||||
*/
|
||||
template <template <typename> typename Allocator = thing_allocator>
|
||||
class thing;
|
||||
|
||||
/**
|
||||
* @brief An alias to a thing shared pointer.
|
||||
*/
|
||||
using thing_p = std::shared_ptr<thing>;
|
||||
|
||||
/**
|
||||
* @brief Furvm thing's index.
|
||||
*/
|
||||
using thing_handle = std::uint32_t;
|
||||
using thing_id = std::uint32_t;
|
||||
|
||||
/**
|
||||
* @brief A handle to a thing.
|
||||
*/
|
||||
using thing_h = handle<thing<thing_allocator>, refcount_header<thing_id>>;
|
||||
|
||||
// executor.hpp
|
||||
|
||||
@@ -159,7 +203,12 @@ using executor_p = std::shared_ptr<executor>;
|
||||
/**
|
||||
* @brief Furvm executor's index.
|
||||
*/
|
||||
using executor_handle = std::uint32_t;
|
||||
using executor_id = std::uint32_t;
|
||||
|
||||
/**
|
||||
* @brief A handle to an executor.
|
||||
*/
|
||||
using executor_h = handle<executor, refcount_header<executor_id>>;
|
||||
|
||||
// context.hpp
|
||||
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
#ifndef FURVM_HANDLE_HPP
|
||||
#define FURVM_HANDLE_HPP
|
||||
|
||||
#include "furvm/detail/handle.hpp"
|
||||
#include "furvm/fwd.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace furvm {
|
||||
|
||||
// TODO: Implement generational indexes
|
||||
|
||||
template <typename Id>
|
||||
class refcount_header {
|
||||
public:
|
||||
using id_type = Id; /**< Id type. */
|
||||
using refcount_type = std::uint32_t; /**< Reference count type. */
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a reference counting header.
|
||||
*
|
||||
* @param id Identifier of the handle's value.
|
||||
* @param refCount Handle's reference count.
|
||||
* @param onRelease Callback function.
|
||||
*/
|
||||
template <typename IdFwd, typename Func>
|
||||
refcount_header(IdFwd&& id, refcount_type refCount, Func&& onRelease)
|
||||
: m_id(std::forward<IdFwd>(id)), m_refCount(refCount), m_onRelease(std::forward<Func>(onRelease)) {}
|
||||
public:
|
||||
/**
|
||||
* @brief Returns the header's reference count.
|
||||
*
|
||||
* @return The reference count.
|
||||
*/
|
||||
refcount_type reference_count() const { return m_refCount; }
|
||||
|
||||
/**
|
||||
* @brief Increments the header's reference count.
|
||||
*/
|
||||
void acquire() { ++m_refCount; }
|
||||
|
||||
/**
|
||||
* @brief Decrements the header's reference count.
|
||||
*
|
||||
* If the reference count reaches 0, the onRelease callback passed in the constructor will be called.
|
||||
*/
|
||||
void release() {
|
||||
--m_refCount;
|
||||
if (m_refCount == 0) m_onRelease(m_id);
|
||||
}
|
||||
public:
|
||||
/**
|
||||
* @brief Returns the header's identifier.
|
||||
*
|
||||
* @return The identifier.
|
||||
*/
|
||||
id_type id() const { return m_id; }
|
||||
private:
|
||||
id_type m_id;
|
||||
std::atomic<refcount_type> m_refCount;
|
||||
std::function<void(const id_type&)> m_onRelease;
|
||||
};
|
||||
|
||||
template <typename Id>
|
||||
class generic_header {
|
||||
public:
|
||||
using id_type = Id; /**< Id type. */
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a generic header.
|
||||
*
|
||||
* @param id Identifier of the handle.
|
||||
*/
|
||||
generic_header(id_type id)
|
||||
: m_id(id) {}
|
||||
public:
|
||||
/**
|
||||
* @brief Returns the header's identifier.
|
||||
*/
|
||||
id_type id() const { return m_id; }
|
||||
private:
|
||||
id_type m_id;
|
||||
};
|
||||
|
||||
template <typename Value, typename Header = refcount_header<std::uint32_t>>
|
||||
class handle {
|
||||
public:
|
||||
using value_type = Value; /** Value type. */
|
||||
using reference = Value&; /** Reference type. */
|
||||
using const_reference = const Value&; /** Constant reference type. */
|
||||
using pointer = Value*; /** Pointer type. */
|
||||
using const_pointer = const Value*; /** Constant pointer type. */
|
||||
public:
|
||||
using id_type = typename Header::id_type; /** Id type of the header. */
|
||||
public:
|
||||
using pair_type = std::pair<Header, Value>; /** Type of a header-value pair. */
|
||||
public:
|
||||
handle() = default;
|
||||
|
||||
/**
|
||||
* @brief Constructs a handle.
|
||||
*
|
||||
* @param value A pointer to the header-value pair.
|
||||
*/
|
||||
handle(pair_type* value)
|
||||
: m_value(value) {
|
||||
if constexpr (detail::header_has_refcount_v<Header>) {
|
||||
m_value->first.acquire();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Destructs a handle.
|
||||
*/
|
||||
~handle() {
|
||||
if constexpr (detail::header_has_refcount_v<Header>) {
|
||||
if (m_value != nullptr) m_value->first.release();
|
||||
}
|
||||
m_value = nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
handle(handle&& other) noexcept
|
||||
: m_value(other.m_value) {
|
||||
other.m_value = nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
handle& operator=(handle&& other) noexcept {
|
||||
if (this == &other) return *this;
|
||||
m_value = other.m_value;
|
||||
other.m_value = nullptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
handle(const handle& other)
|
||||
: m_value(other.m_value) {
|
||||
m_value->first.acquire();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
handle& operator=(const handle& other) {
|
||||
if (this == &other) return *this;
|
||||
m_value = other.m_value;
|
||||
m_value->first.acquire();
|
||||
return *this;
|
||||
}
|
||||
public:
|
||||
/**
|
||||
* @brief Returns an identifier of the handle's header.
|
||||
*
|
||||
* @return The header's identifier.
|
||||
*/
|
||||
id_type id() const { return m_value->first.id(); }
|
||||
|
||||
/**
|
||||
* @brief Returns whether the handle is empty.
|
||||
*
|
||||
* @return true if the handle is empty.
|
||||
*/
|
||||
bool empty() const { return m_value == nullptr; }
|
||||
|
||||
/**
|
||||
* @brief Returns the handle's header reference count.
|
||||
*
|
||||
* @return The reference count.
|
||||
*/
|
||||
template <typename ReferenceCount = typename Header::refcount_type>
|
||||
ReferenceCount reference_count() const {
|
||||
return m_value->first.reference_count();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a pointer to the handle's value.
|
||||
*
|
||||
* @return The value pointer.
|
||||
*/
|
||||
pointer operator->() { return &m_value->second; }
|
||||
|
||||
/**
|
||||
* @brief Returns a pointer to the handle's value.
|
||||
*
|
||||
* @return The value pointer.
|
||||
*/
|
||||
const_pointer operator->() const { return &m_value->second; }
|
||||
|
||||
/**
|
||||
* @brief Returns a reference to the handle's value.
|
||||
*
|
||||
* @return The value reference.
|
||||
*/
|
||||
reference operator*() { return m_value->second; }
|
||||
|
||||
/**
|
||||
* @brief Returns a reference to the handle's value.
|
||||
*
|
||||
* @return The value reference.
|
||||
*/
|
||||
const_reference operator*() const { return m_value->second; }
|
||||
|
||||
/**
|
||||
* @brief Returns a reference to the handle's value.
|
||||
*
|
||||
* @return The value reference.
|
||||
*/
|
||||
reference value() { return m_value->second; }
|
||||
|
||||
/**
|
||||
* @brief Returns a reference to the handle's value.
|
||||
*
|
||||
* @return The value reference.
|
||||
*/
|
||||
const_reference value() const { return m_value->second; }
|
||||
private:
|
||||
pair_type* m_value = nullptr;
|
||||
};
|
||||
|
||||
template <typename Handle>
|
||||
class handle_container<Handle, std::enable_if_t<!std::is_integral_v<typename Handle::id_type>>> {
|
||||
private:
|
||||
using pair_type = typename Handle::pair_type; /**< Handle's pair type. */
|
||||
public:
|
||||
using value_type = std::remove_cv_t<std::remove_reference_t<Handle>>; /**< Handle type. */
|
||||
using const_value = std::add_const_t<value_type>; /**< Constant handle type. */
|
||||
|
||||
using id_type = typename Handle::id_type; /**< Handle's header identifier type. */
|
||||
public:
|
||||
handle_container() = default;
|
||||
~handle_container() = default;
|
||||
|
||||
handle_container(handle_container&&) noexcept = default;
|
||||
handle_container& operator=(handle_container&&) noexcept = default;
|
||||
|
||||
handle_container(const handle_container&) = delete;
|
||||
handle_container& operator=(const handle_container&) = delete;
|
||||
public:
|
||||
/**
|
||||
* @brief Emplaces a new value.
|
||||
*
|
||||
* @param id Identifier of the emplaced value.
|
||||
* @param args Arguments passed to the Handle's value type constructor.
|
||||
* @return A handle to the emplaced value.
|
||||
*/
|
||||
template <typename IdFwd,
|
||||
typename... Args,
|
||||
typename = std::enable_if_t<std::is_constructible_v<typename pair_type::second_type, Args...>>>
|
||||
value_type emplace(IdFwd&& id, Args&&... args) {
|
||||
id_type idFwd = std::forward<IdFwd>(id);
|
||||
if (auto it = m_pairs.find(idFwd); it != m_pairs.end()) delete it->second;
|
||||
auto pair = new pair_type(std::piecewise_construct,
|
||||
std::forward_as_tuple(idFwd, 0, [&](const id_type& id) { erase(id); }),
|
||||
std::forward_as_tuple(std::forward<Args>(args)...));
|
||||
m_pairs.emplace(std::move(idFwd), pair);
|
||||
return { pair };
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a handle to the container's value.
|
||||
*
|
||||
* @param id Idenfifier of the value.
|
||||
* @return The value.
|
||||
*/
|
||||
template <typename IdFwd>
|
||||
value_type at(IdFwd&& id) {
|
||||
return { m_pairs.at(std::forward<IdFwd>(id)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a handle to the container's value.
|
||||
*
|
||||
* @param id Idenfifier of the value.
|
||||
* @return The value.
|
||||
*/
|
||||
template <typename IdFwd>
|
||||
const_value at(IdFwd&& id) const {
|
||||
return { m_pairs.at(std::forward<IdFwd>(id)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Erases a value from the container.
|
||||
*
|
||||
* @param id Identifier of the value.
|
||||
*/
|
||||
template <typename IdFwd>
|
||||
void erase(IdFwd&& id) {
|
||||
auto it = m_pairs.find(std::forward<IdFwd>(id));
|
||||
if (it == m_pairs.end()) return;
|
||||
delete it->second;
|
||||
m_pairs.erase(it);
|
||||
}
|
||||
private:
|
||||
std::unordered_map<id_type, pair_type*> m_pairs;
|
||||
};
|
||||
|
||||
template <typename Handle>
|
||||
class handle_container<Handle, std::enable_if_t<std::is_integral_v<typename Handle::id_type>>> {
|
||||
private:
|
||||
using pair_type = typename Handle::pair_type; /**< Handle's pair type. */
|
||||
public:
|
||||
using value_type = std::remove_cv_t<std::remove_reference_t<Handle>>; /**< Handle type. */
|
||||
using const_value = std::add_const_t<value_type>; /**< Constant handle type. */
|
||||
|
||||
using id_type = typename Handle::id_type; /**< Handle's header identifier type. */
|
||||
public:
|
||||
handle_container() = default;
|
||||
~handle_container() = default;
|
||||
|
||||
handle_container(handle_container&&) noexcept = default;
|
||||
handle_container& operator=(handle_container&&) noexcept = default;
|
||||
|
||||
handle_container(const handle_container&) = delete;
|
||||
handle_container& operator=(const handle_container&) = delete;
|
||||
public:
|
||||
/**
|
||||
* @brief Emplaces a new value.
|
||||
*
|
||||
* @param id Identifier of the emplaced value.
|
||||
* @param args Arguments passed to the Handle's value type constructor.
|
||||
* @return A handle to the emplaced value.
|
||||
*/
|
||||
template <typename... Args,
|
||||
typename = std::enable_if_t<std::is_constructible_v<typename pair_type::second_type, Args...>>>
|
||||
value_type emplace(id_type id, Args&&... args) {
|
||||
if (id >= m_pairs.size()) {
|
||||
m_pairs.resize(id + 1, nullptr);
|
||||
} else if (m_pairs[id] != nullptr) {
|
||||
delete m_pairs[id];
|
||||
}
|
||||
|
||||
pair_type* newPair = new pair_type(std::piecewise_construct,
|
||||
std::forward_as_tuple(id, 0, [&](const id_type& id) { erase(id); }),
|
||||
std::forward_as_tuple(std::forward<Args>(args)...));
|
||||
|
||||
m_pairs[id] = newPair;
|
||||
return { newPair };
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Emplaces a new value.
|
||||
*
|
||||
* Emplaces a new value with an automatically-assigned identifier.
|
||||
*
|
||||
* @param args Arguments passed to the Handle's value type constructor.
|
||||
* @return A handle to the emplaced value.
|
||||
*/
|
||||
template <typename... Args,
|
||||
typename = std::enable_if_t<std::is_constructible_v<typename Handle::pair_type::second_type, Args...>>>
|
||||
value_type emplace_back(Args&&... args) {
|
||||
return emplace(static_cast<id_type>(m_pairs.size()), std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a handle to a value.
|
||||
*
|
||||
* @param id Identifier of the value.
|
||||
* @return The value.
|
||||
*/
|
||||
value_type at(id_type id) { return { m_pairs.at(id) }; }
|
||||
|
||||
/**
|
||||
* @brief Returns a handle to a value.
|
||||
*
|
||||
* @param id Identifier of the value.
|
||||
* @return The value.
|
||||
*/
|
||||
const_value at(id_type id) const { return { m_pairs.at(id) }; }
|
||||
|
||||
/**
|
||||
* @brief Erases a value from the container.
|
||||
*
|
||||
* @param id Identifier of the value.
|
||||
*/
|
||||
void erase(id_type id) {
|
||||
if (id >= m_pairs.size()) return;
|
||||
delete m_pairs[id];
|
||||
m_pairs[id] = nullptr;
|
||||
}
|
||||
private:
|
||||
std::vector<pair_type*> m_pairs;
|
||||
};
|
||||
|
||||
} // namespace furvm
|
||||
|
||||
#endif // FURVM_HANDLE_HPP
|
||||
+102
-18
@@ -1,8 +1,14 @@
|
||||
#ifndef FURVM_MODULE_HPP
|
||||
#define FURVM_MODULE_HPP
|
||||
|
||||
#include "furvm/function.hpp"
|
||||
#include "furvm/fwd.hpp"
|
||||
#include "furvm/handle.hpp"
|
||||
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace furvm {
|
||||
@@ -12,16 +18,18 @@ class mod {
|
||||
friend class serializer;
|
||||
public:
|
||||
using bytecode_t = std::vector<byte>; /**< An alias to a vector of bytes. */
|
||||
|
||||
static constexpr char MAGIC[4] = { 'F', 'u', 'r', 'M' }; /** Furvm module file magic. */
|
||||
public:
|
||||
/**
|
||||
* @brief Construct a new module.
|
||||
* @brief Constructs a module.
|
||||
*
|
||||
* @param id Id of this module.
|
||||
* @param args Arguments to forward to bytecode's constructor.
|
||||
* @param name Name of the module.
|
||||
* @param args Arguments forwarded to bytecode's constructor.
|
||||
*/
|
||||
template <typename... Args, typename = std::enable_if_t<std::is_constructible_v<bytecode_t, Args...>>>
|
||||
mod(module_handle id, Args&&... args)
|
||||
: m_id(id), m_bytecode(std::forward<Args>(args)...) {}
|
||||
mod(Args&&... args)
|
||||
: m_bytecode(std::forward<Args>(args)...) {}
|
||||
|
||||
~mod() = default;
|
||||
|
||||
@@ -38,13 +46,6 @@ public:
|
||||
mod(const mod&) = delete;
|
||||
mod& operator=(const mod&) = delete;
|
||||
public:
|
||||
/**
|
||||
* @brief Returns an id of this module.
|
||||
*
|
||||
* @return The id.
|
||||
*/
|
||||
constexpr module_handle id() const { return m_id; }
|
||||
|
||||
/**
|
||||
* @brief Returns a byte from bytecode of this module.
|
||||
*
|
||||
@@ -52,18 +53,101 @@ public:
|
||||
* @return The byte.
|
||||
*/
|
||||
constexpr byte byte(std::size_t offset) const { return m_bytecode.at(offset); }
|
||||
|
||||
/**
|
||||
* @brief Returns the module's bytecode.
|
||||
*
|
||||
* @return A reference to the bytecode.
|
||||
*/
|
||||
constexpr bytecode_t& bytecode() { return m_bytecode; }
|
||||
|
||||
/**
|
||||
* @brief Returns the module's bytecode.
|
||||
*
|
||||
* @return A constant reference to the bytecode.
|
||||
*/
|
||||
constexpr const bytecode_t& bytecode() const { return m_bytecode; }
|
||||
public:
|
||||
/**
|
||||
* @brief Returns a function from this module.
|
||||
* @brief Emplaces a function in the module's function container.
|
||||
*
|
||||
* @param id Id of the function.
|
||||
* @return The function.
|
||||
* @param args Arguments forwarded into the container's emplace_back function.
|
||||
* @return A handle to the emplaced function.
|
||||
*/
|
||||
constexpr const function_p& function_at(function_handle id) const { return m_functions.at(id); }
|
||||
template <typename... Args>
|
||||
function_h emplace_function(Args&&... args) {
|
||||
function_h function = m_functions.emplace_back(std::forward<Args>(args)...);
|
||||
m_functionMap[function->name()] = function.id();
|
||||
return std::move(function);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Inserts a function in the module's function container.
|
||||
*
|
||||
* @param function Function to insert.
|
||||
*/
|
||||
template <typename Function>
|
||||
void push_back(Function&& function) {
|
||||
m_functions.emplace_back(std::forward<Function>(function));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a function from the module.
|
||||
*
|
||||
* @param id Identifier of the function.
|
||||
* @return A handle to the function.
|
||||
*/
|
||||
auto function_at(function_id id) { return m_functions.at(id); }
|
||||
|
||||
/**
|
||||
* @brief Returns a function from the module.
|
||||
*
|
||||
* @param id Identifier of the function.
|
||||
* @return A handle to the function.
|
||||
*/
|
||||
auto function_at(function_id id) const { return m_functions.at(id); }
|
||||
|
||||
/**
|
||||
* @brief Returns a function from the module.
|
||||
*
|
||||
* @param name Name of the function.
|
||||
* @return A handle to the function.
|
||||
*/
|
||||
template <typename NameFwd>
|
||||
auto function_at(NameFwd&& name) {
|
||||
return function_at(m_functionMap.at(std::forward<NameFwd>(name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a function from the module.
|
||||
*
|
||||
* @param name Name of the function.
|
||||
* @return A handle to the function.
|
||||
*/
|
||||
template <typename NameFwd>
|
||||
auto function_at(NameFwd&& name) const {
|
||||
return function_at(m_functionMap.at(std::forward<NameFwd>(name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Erases a function from the module's function container.
|
||||
*
|
||||
* @param id Identifier of the function.
|
||||
*/
|
||||
void erase_function(function_id id) { m_functions.erase(id); }
|
||||
public:
|
||||
/**
|
||||
* @brief Prints the module in a bytecode form to an output stream.
|
||||
*
|
||||
* @param os Output stream.
|
||||
* @return The output stream.
|
||||
*/
|
||||
std::ostream& serialize(std::ostream& os) const;
|
||||
private:
|
||||
module_handle m_id;
|
||||
bytecode_t m_bytecode;
|
||||
std::vector<function_p> m_functions;
|
||||
|
||||
std::unordered_map<std::string, function_id> m_functionMap;
|
||||
handle_container<function_h> m_functions;
|
||||
};
|
||||
|
||||
} // namespace furvm
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
#ifndef FURVM_SERIALIZER_HPP
|
||||
#define FURVM_SERIALIZER_HPP
|
||||
|
||||
#include "furvm/fwd.hpp"
|
||||
|
||||
#include <ostream>
|
||||
|
||||
namespace furvm {
|
||||
|
||||
class serializer {
|
||||
public:
|
||||
static constexpr byte MODULE_MAGIC[4] = { 'F', 'u', 'r', 'M' };
|
||||
static constexpr std::uint32_t VERSION = 0;
|
||||
public:
|
||||
static bool serialize_module(std::ostream& os, const mod_p& mod);
|
||||
};
|
||||
|
||||
} // namespace furvm
|
||||
|
||||
#endif // FURVM_SERIALIZER_HPP
|
||||
+295
-203
@@ -1,9 +1,17 @@
|
||||
#ifndef FURVM_THING_HPP
|
||||
#define FURVM_THING_HPP
|
||||
|
||||
#include "furvm/context.hpp" // IWYU pragma: keep
|
||||
#include "furlang/arena.hpp"
|
||||
#include "furvm/exceptions.hpp"
|
||||
#include "furvm/fwd.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace furvm {
|
||||
|
||||
enum class thing_t : std::uint8_t {
|
||||
@@ -11,252 +19,336 @@ enum class thing_t : std::uint8_t {
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Returns data size of a thing.
|
||||
* @brief Returns how many bytes a thing would take up.
|
||||
*
|
||||
* @param type Type of the thing.
|
||||
* @return The data size of the thing.
|
||||
* @return The byte count.
|
||||
*/
|
||||
std::size_t thing_type_size(thing_t type);
|
||||
|
||||
class bad_thing_access : public std::exception {
|
||||
public:
|
||||
bad_thing_access() = default;
|
||||
~bad_thing_access() override = default;
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
bad_thing_access(bad_thing_access&&) noexcept = default;
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
bad_thing_access& operator=(bad_thing_access&&) noexcept = default;
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
bad_thing_access(const bad_thing_access&) = default;
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
bad_thing_access& operator=(const bad_thing_access&) = default;
|
||||
public:
|
||||
/**
|
||||
* @brief Returns a C-style string describing the cause of the error.
|
||||
*
|
||||
* @return The cause of the error.
|
||||
*/
|
||||
const char* what() const noexcept override { return "bad thing access"; }
|
||||
};
|
||||
static inline std::size_t thing_type_size(thing_t type) {
|
||||
switch (type) {
|
||||
case thing_t::Int32: return sizeof(std::int32_t);
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
template <template <typename> typename Allocator>
|
||||
class thing final {
|
||||
friend class executor;
|
||||
private:
|
||||
/**
|
||||
* @brief A private token for the private constructor.
|
||||
*
|
||||
* Also `rzecz` in Polish translates to `thing` I think.
|
||||
*/
|
||||
struct rzecz {
|
||||
explicit rzecz() = default;
|
||||
};
|
||||
public:
|
||||
using nref_t = std::size_t; /**< Type of reference count. */
|
||||
|
||||
static constexpr thing_handle GENERATION_SIZE = 12; /**< Bit size of generation part in thing_handle. */
|
||||
using allocator_type = Allocator<std::byte>; /**< Allocator type. */
|
||||
public:
|
||||
/**
|
||||
* @brief Private constructor.
|
||||
* @brief Constructs a thing.
|
||||
*
|
||||
* @param id
|
||||
* @param type
|
||||
* @param context
|
||||
* @param type Type of the thing.
|
||||
* @param allocator Allocator for the thing's data.
|
||||
*/
|
||||
thing(rzecz, thing_handle id, thing_t type, const context_p& context);
|
||||
thing(thing_t type, const allocator_type& allocator = {})
|
||||
: m_type(type), m_allocator(allocator) {
|
||||
m_data = m_allocator.allocate(thing_type_size(type));
|
||||
}
|
||||
|
||||
~thing();
|
||||
/**
|
||||
* @brief Destructs a thing.
|
||||
*/
|
||||
~thing() {
|
||||
if (m_data != nullptr) m_allocator.deallocate(m_data, thing_type_size(thing_t::Int32));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
thing(thing&&) noexcept;
|
||||
thing(thing&& other) noexcept
|
||||
: m_type(other.m_type), m_data(other.m_data), m_allocator(std::move(other.m_allocator)) {
|
||||
other.m_type = {};
|
||||
other.m_data = nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
thing& operator=(thing&&) noexcept;
|
||||
thing& operator=(thing&& other) noexcept {
|
||||
if (this == &other) return *this;
|
||||
m_type = other.m_type;
|
||||
m_data = other.m_data;
|
||||
m_allocator = std::move(other.m_allocator);
|
||||
other.m_type = {};
|
||||
other.m_data = nullptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
thing(const thing&) = delete;
|
||||
thing& operator=(const thing&) = delete;
|
||||
public:
|
||||
/**
|
||||
* @brief Adds two things together.
|
||||
*
|
||||
* @param lhs Left-hand-side thing.
|
||||
* @param rhs Right-hand-side thing.
|
||||
* @return Shared pointer to result thing.
|
||||
*/
|
||||
friend thing_p operator+(const thing_p& lhs, const thing_p& rhs);
|
||||
|
||||
/**
|
||||
* @brief Subtracts two things together.
|
||||
*
|
||||
* @param lhs Left-hand-side thing.
|
||||
* @param rhs Right-hand-side thing.
|
||||
* @return Shared pointer to result thing.
|
||||
*/
|
||||
friend thing_p operator-(const thing_p& lhs, const thing_p& rhs);
|
||||
|
||||
/**
|
||||
* @brief Multiplies two things together.
|
||||
*
|
||||
* @param lhs Left-hand-side thing.
|
||||
* @param rhs Right-hand-side thing.
|
||||
* @return Shared pointer to result thing.
|
||||
*/
|
||||
friend thing_p operator*(const thing_p& lhs, const thing_p& rhs);
|
||||
|
||||
/**
|
||||
* @brief Divides two things together.
|
||||
*
|
||||
* @param lhs Left-hand-side thing.
|
||||
* @param rhs Right-hand-side thing.
|
||||
* @return Shared pointer to result thing.
|
||||
*/
|
||||
friend thing_p operator/(const thing_p& lhs, const thing_p& rhs);
|
||||
|
||||
/**
|
||||
* @brief Modulos two things together.
|
||||
*
|
||||
* @param lhs Left-hand-side thing.
|
||||
* @param rhs Right-hand-side thing.
|
||||
* @return Shared pointer to result thing.
|
||||
*/
|
||||
friend thing_p operator%(const thing_p& lhs, const thing_p& rhs);
|
||||
|
||||
/**
|
||||
* @brief Compares two things for equality.
|
||||
*
|
||||
* @param lhs Left-hand-side thing.
|
||||
* @param rhs Right-hand-side thing.
|
||||
* @return Shared pointer to result thing.
|
||||
*/
|
||||
friend thing_p operator==(const thing_p& lhs, const thing_p& rhs);
|
||||
|
||||
/**
|
||||
* @brief Compares two things for equality.
|
||||
*
|
||||
* @param lhs Left-hand-side thing.
|
||||
* @param rhs Right-hand-side thing.
|
||||
* @return Shared pointer to result thing.
|
||||
*/
|
||||
friend thing_p operator!=(const thing_p& lhs, const thing_p& rhs);
|
||||
/**
|
||||
* @brief Compares if the left thing is less than the right thing.
|
||||
*
|
||||
* @param lhs Left-hand-side thing.
|
||||
* @param rhs Right-hand-side thing.
|
||||
* @return Shared pointer to result thing.
|
||||
*/
|
||||
friend thing_p operator<(const thing_p& lhs, const thing_p& rhs);
|
||||
|
||||
/**
|
||||
* @brief Compares if the left thing is greater than the right thing.
|
||||
*
|
||||
* @param lhs Left-hand-side thing.
|
||||
* @param rhs Right-hand-side thing.
|
||||
* @return Shared pointer to result thing.
|
||||
*/
|
||||
friend thing_p operator>(const thing_p& lhs, const thing_p& rhs);
|
||||
|
||||
/**
|
||||
* @brief Compares if the left thing is less than or equal to the right thing.
|
||||
*
|
||||
* @param lhs Left-hand-side thing.
|
||||
* @param rhs Right-hand-side thing.
|
||||
* @return Shared pointer to result thing.
|
||||
*/
|
||||
friend thing_p operator<=(const thing_p& lhs, const thing_p& rhs);
|
||||
|
||||
/**
|
||||
* @brief Compares if the left thing is greater than or equal to the right thing.
|
||||
*
|
||||
* @param lhs Left-hand-side thing.
|
||||
* @param rhs Right-hand-side thing.
|
||||
* @return Shared pointer to result thing.
|
||||
*/
|
||||
friend thing_p operator>=(const thing_p& lhs, const thing_p& rhs);
|
||||
public:
|
||||
/**
|
||||
* @brief Returns a new thing.
|
||||
*
|
||||
* @param context Furvm context.
|
||||
* @param args Arguments to forward to the thing constructor.
|
||||
* @return Shared pointer to the new thing.
|
||||
*/
|
||||
template <typename... Args,
|
||||
typename = std::enable_if_t<std::is_constructible_v<thing, rzecz, thing_handle, Args..., const context_p&>>>
|
||||
static thing_p create(const context_p& context, Args&&... args) {
|
||||
thing_handle id = context->m_things.size();
|
||||
if (!context->m_deadThings.empty()) {
|
||||
id = context->m_deadThings.front();
|
||||
context->m_deadThings.pop();
|
||||
id += 1 << GENERATION_SIZE;
|
||||
}
|
||||
thing_handle idx = id & ((1ULL << ((sizeof(id) * 8) - GENERATION_SIZE)) - 1);
|
||||
|
||||
auto th = std::make_shared<thing>(rzecz{}, id, std::forward<Args>(args)..., context);
|
||||
context->m_things.emplace(context->m_things.begin() + idx, th);
|
||||
return std::move(th);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a clone of the thing.
|
||||
*
|
||||
* @param thing Thing to clone.
|
||||
* @return Shared pointer to a clone of the thing.
|
||||
* @return A clone of this thing.
|
||||
*/
|
||||
static thing_p clone(const thing_p& thing);
|
||||
thing clone() const {
|
||||
class thing res(m_type, m_allocator);
|
||||
switch (m_type) {
|
||||
default: {
|
||||
std::memcpy(res.m_data, m_data, thing_type_size(m_type));
|
||||
} break;
|
||||
}
|
||||
return std::move(res);
|
||||
}
|
||||
public:
|
||||
/**
|
||||
* @brief Returns an int32 value from this thing.
|
||||
* @brief Returns the thing's int32 value.
|
||||
*
|
||||
* @return The value.
|
||||
*/
|
||||
std::int32_t& int32();
|
||||
std::int32_t& int32() {
|
||||
if (m_type != thing_t::Int32) throw bad_thing_access();
|
||||
return *reinterpret_cast<std::int32_t*>(m_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns an int32 value from this thing.
|
||||
* @brief Returns the thing's int32 value.
|
||||
*
|
||||
* @return The value.
|
||||
*/
|
||||
const std::int32_t& int32() const;
|
||||
const std::int32_t& int32() const {
|
||||
if (m_type != thing_t::Int32) throw bad_thing_access();
|
||||
return *reinterpret_cast<std::int32_t*>(m_data);
|
||||
}
|
||||
public:
|
||||
/**
|
||||
* @brief Increments reference count of this thing by one.
|
||||
*/
|
||||
void add_reference() { ++m_refCount; }
|
||||
|
||||
/**
|
||||
* @brief Decrements reference count of this thing by one.
|
||||
*/
|
||||
void remove_reference() { --m_refCount; }
|
||||
|
||||
/**
|
||||
* @brief Returns reference count of this thing.
|
||||
* @brief Returns a sum of two things.
|
||||
*
|
||||
* @return The reference count.
|
||||
* @param rhs Thing to sum with this thing (right-hand-side).
|
||||
* @return The sum.
|
||||
*/
|
||||
constexpr nref_t reference_count() const { return m_refCount; }
|
||||
thing add(const thing& rhs) const {
|
||||
thing res(m_type, m_allocator);
|
||||
res.int32() = int32() + rhs.int32();
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a difference of two things.
|
||||
*
|
||||
* @param rhs Thing to subtract from this thing (right-hand-side).
|
||||
* @return The sum.
|
||||
*/
|
||||
thing sub(const thing& rhs) const {
|
||||
thing res(m_type, m_allocator);
|
||||
res.int32() = int32() - rhs.int32();
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a product of two things.
|
||||
*
|
||||
* @param rhs Thing to multiply with this thing (right-hand-side).
|
||||
* @return The product.
|
||||
*/
|
||||
thing mul(const thing& rhs) const {
|
||||
thing res(m_type, m_allocator);
|
||||
res.int32() = int32() * rhs.int32();
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a quotient of two things.
|
||||
*
|
||||
* @param rhs Thing to divide this thing by (right-hand-side).
|
||||
* @return The quotient.
|
||||
*/
|
||||
thing div(const thing& rhs) const {
|
||||
thing res(m_type, m_allocator);
|
||||
res.int32() = int32() / rhs.int32();
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns a remainder of two things.
|
||||
*
|
||||
* @param rhs Thing to divide this thing by (right-hand-side).
|
||||
* @return The remainder.
|
||||
*/
|
||||
thing mod(const thing& rhs) const {
|
||||
thing res(m_type, m_allocator);
|
||||
res.int32() = int32() % rhs.int32();
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compares two things for equality.
|
||||
*
|
||||
* @param rhs Thing to compare this thing with (right-hand-side).
|
||||
* @return A boolean result of the comparison in a thing form.
|
||||
*/
|
||||
thing equals(const thing& rhs) const {
|
||||
thing res(m_type, m_allocator);
|
||||
res.int32() = int32() == rhs.int32();
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compares two things for inequality.
|
||||
*
|
||||
* @param rhs Thing to compare this thing with (right-hand-side).
|
||||
* @return A boolean result of the comparison in a thing form.
|
||||
*/
|
||||
thing not_equals(const thing& rhs) const {
|
||||
thing res(m_type, m_allocator);
|
||||
res.int32() = int32() != rhs.int32();
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compares if this thing is less than an another thing.
|
||||
*
|
||||
* @param rhs The another thing.
|
||||
* @return A boolean result of the comparison in a thing form.
|
||||
*/
|
||||
thing less_than(const thing& rhs) const {
|
||||
thing res(m_type, m_allocator);
|
||||
res.int32() = int32() < rhs.int32();
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compares if this thing is greater than an another thing.
|
||||
*
|
||||
* @param rhs The another thing.
|
||||
* @return A boolean result of the comparison in a thing form.
|
||||
*/
|
||||
thing greater_than(const thing& rhs) const {
|
||||
thing res(m_type, m_allocator);
|
||||
res.int32() = int32() > rhs.int32();
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compares if this thing is less than or equal to an another thing.
|
||||
*
|
||||
* @param rhs The another thing.
|
||||
* @return A boolean result of the comparison in a thing form.
|
||||
*/
|
||||
thing less_equals(const thing& rhs) const {
|
||||
thing res(m_type, m_allocator);
|
||||
res.int32() = int32() <= rhs.int32();
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compares if this thing is greater than or equal to an another thing.
|
||||
*
|
||||
* @param rhs The another thing.
|
||||
* @return A boolean result of the comparison in a thing form.
|
||||
*/
|
||||
thing greater_equals(const thing& rhs) const {
|
||||
thing res(m_type, m_allocator);
|
||||
res.int32() = int32() >= rhs.int32();
|
||||
return res;
|
||||
}
|
||||
private:
|
||||
thing_handle m_id;
|
||||
thing_t m_type;
|
||||
context_p m_context;
|
||||
thing_t m_type{};
|
||||
std::byte* m_data;
|
||||
|
||||
nref_t m_refCount = 0;
|
||||
void* m_data = nullptr;
|
||||
allocator_type m_allocator;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class thing_allocator {
|
||||
template <typename>
|
||||
friend class thing_allocator;
|
||||
|
||||
using dead_things = std::vector<std::pair<T*, std::size_t>>;
|
||||
public:
|
||||
using value_type = T; /**< Value type. */
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a thing allocator.
|
||||
*
|
||||
* @param arena Base arena allocator.
|
||||
*/
|
||||
explicit thing_allocator(furlang::arena& arena) noexcept
|
||||
: m_arena(&arena), m_deadThings(std::make_shared<dead_things>()) {}
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
template <typename U>
|
||||
thing_allocator(thing_allocator<U>&& other) noexcept
|
||||
: m_arena(std::move(other.m_arena)), m_deadThings(std::move(other.m_deadThings)) {}
|
||||
|
||||
/**
|
||||
* @brief Move constructor.
|
||||
*/
|
||||
template <typename U>
|
||||
thing_allocator& operator=(thing_allocator<U>&& other) noexcept {
|
||||
if (this == &other) return *this;
|
||||
m_arena = std::move(other.m_arena);
|
||||
m_deadThings = std::move(other.m_deadThings);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
template <typename U>
|
||||
thing_allocator(const thing_allocator<U>& other) noexcept
|
||||
: m_arena(other.m_arena), m_deadThings(other.m_deadThings) {}
|
||||
|
||||
/**
|
||||
* @brief Copy constructor.
|
||||
*/
|
||||
template <typename U>
|
||||
thing_allocator& operator=(const thing_allocator<U>& other) noexcept {
|
||||
if (this == &other) return *this;
|
||||
m_arena = other.m_arena;
|
||||
m_deadThings = other.m_deadThings;
|
||||
return *this;
|
||||
}
|
||||
public:
|
||||
/**
|
||||
* @brief Returns a free chunk of memory.
|
||||
*
|
||||
* @param count Count of the things that must fit inside the chunk.
|
||||
* @return The chunk.
|
||||
*/
|
||||
[[nodiscard]] T* allocate(std::size_t count = 1) {
|
||||
for (auto it = m_deadThings->begin(); it != m_deadThings->end(); ++it) {
|
||||
if (it->second != count) continue;
|
||||
m_deadThings->erase(it);
|
||||
return it->first;
|
||||
}
|
||||
return m_arena->allocate<T>(count);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Recycles the pointer.
|
||||
*/
|
||||
void deallocate(T* ptr, std::size_t count) noexcept { m_deadThings->emplace_back(ptr, count); }
|
||||
public:
|
||||
/**
|
||||
* @brief Compares two thing allocators for equality.
|
||||
*
|
||||
* @return true if the two things are equal.
|
||||
*/
|
||||
template <typename U>
|
||||
bool operator==(const thing_allocator<U>& other) const noexcept {
|
||||
return m_arena == other.m_arena && m_deadThings == other.m_deadThings;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compares two thing allocators for inequality.
|
||||
*
|
||||
* @return true if the two things are not equal.
|
||||
*/
|
||||
template <typename U>
|
||||
bool operator!=(const thing_allocator<U>& other) const noexcept {
|
||||
return m_arena != other.m_arena || m_deadThings != other.m_deadThings;
|
||||
}
|
||||
private:
|
||||
furlang::arena* m_arena;
|
||||
|
||||
std::shared_ptr<dead_things> m_deadThings;
|
||||
};
|
||||
|
||||
} // namespace furvm
|
||||
|
||||
@@ -4,13 +4,7 @@
|
||||
|
||||
namespace furvm {
|
||||
|
||||
context::context() {}
|
||||
|
||||
void context::collect() {
|
||||
for (auto& ref : m_things) {
|
||||
if (ref->reference_count() != 0) continue;
|
||||
ref = nullptr;
|
||||
}
|
||||
}
|
||||
context::context()
|
||||
: m_thingAllocator(m_thingArena) {}
|
||||
|
||||
} // namespace furvm
|
||||
@@ -0,0 +1,49 @@
|
||||
#include "furvm/detail/serialization.hpp"
|
||||
|
||||
#include <ostream>
|
||||
|
||||
namespace furvm::detail {
|
||||
|
||||
std::ostream& serialize(std::ostream& os, std::int8_t value) {
|
||||
return os << (char)((value >> 0ULL) & 0xFF);
|
||||
}
|
||||
|
||||
std::ostream& serialize(std::ostream& os, std::int16_t value) {
|
||||
return os << (char)((value >> 0ULL) & 0xFF) << (char)((value >> 8ULL) & 0xFF);
|
||||
}
|
||||
|
||||
std::ostream& serialize(std::ostream& os, std::int32_t value) {
|
||||
return os << (char)((value >> 0ULL) & 0xFF) << (char)((value >> 8ULL) & 0xFF) << (char)((value >> 16ULL) & 0xFF)
|
||||
<< (char)((value >> 24ULL) & 0xFF);
|
||||
}
|
||||
|
||||
std::ostream& serialize(std::ostream& os, std::int64_t value) {
|
||||
return os << (char)((value >> 0ULL) & 0xFF) << (char)((value >> 8ULL) & 0xFF) << (char)((value >> 16ULL) & 0xFF)
|
||||
<< (char)((value >> 24ULL) & 0xFF) << (char)((value >> 32ULL) & 0xFF) << (char)((value >> 40ULL) & 0xFF)
|
||||
<< (char)((value >> 48ULL) & 0xFF) << (char)((value >> 56ULL) & 0xFF);
|
||||
}
|
||||
|
||||
std::ostream& serialize(std::ostream& os, std::uint8_t value) {
|
||||
return os << (char)((value >> 0ULL) & 0xFF);
|
||||
}
|
||||
|
||||
std::ostream& serialize(std::ostream& os, std::uint16_t value) {
|
||||
return os << (char)((value >> 0ULL) & 0xFF) << (char)((value >> 8ULL) & 0xFF);
|
||||
}
|
||||
|
||||
std::ostream& serialize(std::ostream& os, std::uint32_t value) {
|
||||
return os << (char)((value >> 0ULL) & 0xFF) << (char)((value >> 8ULL) & 0xFF) << (char)((value >> 16ULL) & 0xFF)
|
||||
<< (char)((value >> 24ULL) & 0xFF);
|
||||
}
|
||||
|
||||
std::ostream& serialize(std::ostream& os, std::uint64_t value) {
|
||||
return os << (char)((value >> 0ULL) & 0xFF) << (char)((value >> 8ULL) & 0xFF) << (char)((value >> 16ULL) & 0xFF)
|
||||
<< (char)((value >> 24ULL) & 0xFF) << (char)((value >> 32ULL) & 0xFF) << (char)((value >> 40ULL) & 0xFF)
|
||||
<< (char)((value >> 48ULL) & 0xFF) << (char)((value >> 56ULL) & 0xFF);
|
||||
}
|
||||
|
||||
std::ostream& serialize(std::ostream& os, const std::string& value) {
|
||||
return serialize(os, std::uint16_t(value.size())).write(value.data(), static_cast<std::streamsize>(value.size()));
|
||||
}
|
||||
|
||||
} // namespace furvm::detail
|
||||
+35
-60
@@ -12,22 +12,17 @@
|
||||
|
||||
namespace furvm {
|
||||
|
||||
executor::executor(egzekutor, executor_handle id, const context_p& context)
|
||||
: m_id(id), m_context(context) {}
|
||||
|
||||
executor::~executor() {
|
||||
m_context->m_executors[m_id] = nullptr;
|
||||
void executor::push_frame(const mod_h& mod, function function) {
|
||||
while (function.type() == function_t::Import) {
|
||||
function = *m_context->module_at(function.imp().mod)->function_at(function.imp().function);
|
||||
}
|
||||
|
||||
executor_p executor::create(const context_p& context) {
|
||||
auto ex = std::make_shared<executor>(egzekutor{}, context->m_executors.size(), context);
|
||||
context->m_executors.push_back(ex);
|
||||
return std::move(ex);
|
||||
switch (function.type()) {
|
||||
case function_t::Normal: {
|
||||
m_frames.emplace((struct executor::frame){ mod, function.position(), m_stack.size() });
|
||||
} break;
|
||||
case function_t::Native:
|
||||
default: throw std::runtime_error("unexpected function type");
|
||||
}
|
||||
|
||||
void executor::push_frame(const function_p& function) {
|
||||
if (function->type() != function_t::Normal) return;
|
||||
m_frames.emplace((struct executor::frame){ function->mod(), function->position(), m_stack.size() });
|
||||
}
|
||||
|
||||
struct executor::frame executor::pop_frame() {
|
||||
@@ -41,50 +36,35 @@ struct executor::frame executor::frame() const {
|
||||
return m_frames.top();
|
||||
}
|
||||
|
||||
void executor::push_thing(const thing_p& thing) {
|
||||
thing->add_reference();
|
||||
m_stack.push(thing);
|
||||
thing_h executor::push_thing(::furvm::thing<>&& thing) {
|
||||
return m_stack.emplace(m_context->emplace_thing(std::move(thing)));
|
||||
}
|
||||
|
||||
void executor::push_thing(thing_p&& thing) {
|
||||
thing->add_reference();
|
||||
m_stack.push(std::move(thing));
|
||||
}
|
||||
|
||||
thing_p executor::pop_thing() {
|
||||
thing_h executor::pop_thing() {
|
||||
if (m_frames.top().stackBase >= m_stack.size()) throw stack_underflow();
|
||||
thing_p top = std::move(m_stack.top());
|
||||
thing_h top = std::move(m_stack.top());
|
||||
m_stack.pop();
|
||||
top->remove_reference();
|
||||
return top;
|
||||
}
|
||||
|
||||
thing_p executor::thing() const {
|
||||
thing_h executor::thing() const {
|
||||
if (m_frames.top().stackBase >= m_stack.size()) throw stack_underflow();
|
||||
return m_stack.top();
|
||||
}
|
||||
|
||||
void executor::store_thing(variable_t variable, const thing_p& thing) {
|
||||
void executor::store_thing(variable_t variable, const thing_h& thing) {
|
||||
auto& frame = m_frames.top();
|
||||
frame.variables.resize(variable + 1);
|
||||
if (frame.variables[variable] != nullptr) {
|
||||
frame.variables[variable]->remove_reference();
|
||||
}
|
||||
frame.variables[variable] = thing;
|
||||
thing->add_reference();
|
||||
}
|
||||
|
||||
void executor::store_thing(variable_t variable, thing_p&& thing) {
|
||||
void executor::store_thing(variable_t variable, thing_h&& thing) {
|
||||
auto& frame = m_frames.top();
|
||||
frame.variables.resize(variable + 1);
|
||||
if (frame.variables[variable] != nullptr) {
|
||||
frame.variables[variable]->remove_reference();
|
||||
}
|
||||
thing->add_reference();
|
||||
frame.variables[variable] = std::move(thing);
|
||||
}
|
||||
|
||||
thing_p executor::load_thing(variable_t variable) const {
|
||||
thing_h executor::load_thing(variable_t variable) const {
|
||||
const auto& frame = m_frames.top();
|
||||
return frame.variables[variable];
|
||||
}
|
||||
@@ -94,13 +74,11 @@ void executor::step() {
|
||||
|
||||
struct frame& frame = m_frames.top();
|
||||
|
||||
instruction_t instr = static_cast<instruction_t>(frame.mod->byte(frame.position++));
|
||||
instruction_t instr = static_cast<instruction_t>((*frame.mod).byte(frame.position++));
|
||||
switch (instr) {
|
||||
case instruction_t::NoOperation: break;
|
||||
case instruction_t::PushB2I: {
|
||||
auto thing = thing::create(m_context, thing_t::Int32);
|
||||
thing->int32() = frame.mod->byte(frame.position++);
|
||||
push_thing(std::move(thing));
|
||||
push_thing({ thing_t::Int32, m_context->thing_alloc() })->int32() = frame.mod->byte(frame.position++);
|
||||
} break;
|
||||
case instruction_t::Drop: {
|
||||
pop_thing();
|
||||
@@ -109,62 +87,62 @@ void executor::step() {
|
||||
push_thing(thing());
|
||||
} break;
|
||||
case instruction_t::Clone: {
|
||||
push_thing(std::move(thing::clone(thing())));
|
||||
push_thing(std::move(thing()->clone()));
|
||||
} break;
|
||||
case instruction_t::Add: {
|
||||
auto rhs = pop_thing();
|
||||
auto lhs = pop_thing();
|
||||
push_thing(lhs + rhs);
|
||||
push_thing(lhs->add(*rhs));
|
||||
} break;
|
||||
case instruction_t::Sub: {
|
||||
auto rhs = pop_thing();
|
||||
auto lhs = pop_thing();
|
||||
push_thing(lhs - rhs);
|
||||
push_thing(lhs->sub(*rhs));
|
||||
} break;
|
||||
case instruction_t::Mul: {
|
||||
auto rhs = pop_thing();
|
||||
auto lhs = pop_thing();
|
||||
push_thing(lhs * rhs);
|
||||
push_thing(lhs->mul(*rhs));
|
||||
} break;
|
||||
case instruction_t::Div: {
|
||||
auto rhs = pop_thing();
|
||||
auto lhs = pop_thing();
|
||||
push_thing(lhs / rhs);
|
||||
push_thing(lhs->div(*rhs));
|
||||
} break;
|
||||
case instruction_t::Mod: {
|
||||
auto rhs = pop_thing();
|
||||
auto lhs = pop_thing();
|
||||
push_thing(lhs % rhs);
|
||||
push_thing(lhs->mod(*rhs));
|
||||
} break;
|
||||
case instruction_t::Equals: {
|
||||
auto rhs = pop_thing();
|
||||
auto lhs = pop_thing();
|
||||
push_thing(lhs == rhs);
|
||||
push_thing(lhs->equals(*rhs));
|
||||
} break;
|
||||
case instruction_t::NotEquals: {
|
||||
auto rhs = pop_thing();
|
||||
auto lhs = pop_thing();
|
||||
push_thing(lhs != rhs);
|
||||
push_thing(lhs->not_equals(*rhs));
|
||||
} break;
|
||||
case instruction_t::LessThan: {
|
||||
auto rhs = pop_thing();
|
||||
auto lhs = pop_thing();
|
||||
push_thing(lhs < rhs);
|
||||
push_thing(lhs->less_than(*rhs));
|
||||
} break;
|
||||
case instruction_t::GreaterThan: {
|
||||
auto rhs = pop_thing();
|
||||
auto lhs = pop_thing();
|
||||
push_thing(lhs > rhs);
|
||||
push_thing(lhs->greater_than(*rhs));
|
||||
} break;
|
||||
case instruction_t::LessEqual: {
|
||||
auto rhs = pop_thing();
|
||||
auto lhs = pop_thing();
|
||||
push_thing(lhs <= rhs);
|
||||
push_thing(lhs->less_equals(*rhs));
|
||||
} break;
|
||||
case instruction_t::GreaterEqual: {
|
||||
auto rhs = pop_thing();
|
||||
auto lhs = pop_thing();
|
||||
push_thing(lhs >= rhs);
|
||||
push_thing(lhs->greater_equals(*rhs));
|
||||
} break;
|
||||
case instruction_t::Load: {
|
||||
variable_t variable = static_cast<std::uint16_t>(frame.mod->byte(frame.position)) |
|
||||
@@ -179,18 +157,15 @@ void executor::step() {
|
||||
store_thing(variable, std::move(pop_thing()));
|
||||
} break;
|
||||
case instruction_t::Call: {
|
||||
function_handle funcId = static_cast<std::uint16_t>(frame.mod->byte(frame.position)) |
|
||||
function_id funcId = static_cast<std::uint16_t>(frame.mod->byte(frame.position)) |
|
||||
(static_cast<std::uint16_t>(frame.mod->byte(frame.position + 1)) << 8);
|
||||
frame.position += 2;
|
||||
|
||||
const function_p& function = frame.mod->function_at(funcId);
|
||||
const function_h& function = frame.mod->function_at(funcId);
|
||||
switch (function->type()) {
|
||||
case function_t::Normal: push_frame(function); break;
|
||||
case function_t::Normal:
|
||||
case function_t::Import: push_frame(frame.mod, *function); break;
|
||||
case function_t::Native: function->native()(*this); break;
|
||||
case function_t::Import: {
|
||||
const mod_p& impMod = m_context->m_modules.at(function->imported_module());
|
||||
push_frame(impMod->function_at(function->imported_function()));
|
||||
} break;
|
||||
}
|
||||
} break;
|
||||
case instruction_t::Jump: {
|
||||
|
||||
+51
-12
@@ -1,15 +1,22 @@
|
||||
#include "furvm/function.hpp"
|
||||
|
||||
#include <utility>
|
||||
|
||||
namespace furvm {
|
||||
|
||||
function::function(funkcja, function_handle id, std::size_t position, const mod_p& mod)
|
||||
: m_id(id), m_type(function_t::Normal), m_module(mod), m_value(position) {}
|
||||
|
||||
function::function(funkcja, function_handle id, const native_function& native, const mod_p& mod)
|
||||
: m_id(id), m_type(function_t::Native), m_module(mod), m_value(native) {}
|
||||
function::~function() {
|
||||
switch (m_type) {
|
||||
case function_t::Normal:
|
||||
case function_t::Native:
|
||||
default: break;
|
||||
case function_t::Import: {
|
||||
m_value.imp.~import_function();
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
function::function(function&& other) noexcept
|
||||
: m_id(other.m_id), m_type(other.m_type), m_module(std::move(other.m_module)) {
|
||||
: m_name(std::move(other.m_name)), m_type(other.m_type) {
|
||||
switch (m_type) {
|
||||
case function_t::Normal: {
|
||||
m_value.position = other.m_value.position;
|
||||
@@ -18,8 +25,7 @@ function::function(function&& other) noexcept
|
||||
new (&m_value.native) native_function(std::move(other.m_value.native));
|
||||
} break;
|
||||
case function_t::Import: {
|
||||
m_value.imp.mod = other.m_value.imp.mod;
|
||||
m_value.imp.function = other.m_value.imp.function;
|
||||
m_value.imp = std::move(other.m_value.imp);
|
||||
} break;
|
||||
}
|
||||
other.m_value.position = 0;
|
||||
@@ -28,9 +34,8 @@ function::function(function&& other) noexcept
|
||||
function& function::operator=(function&& other) noexcept {
|
||||
if (this == &other) return *this;
|
||||
|
||||
m_id = other.m_id;
|
||||
m_name = std::move(other.m_name);
|
||||
m_type = other.m_type;
|
||||
m_module = std::move(other.m_module);
|
||||
switch (m_type) {
|
||||
case function_t::Normal: {
|
||||
m_value.position = other.m_value.position;
|
||||
@@ -39,8 +44,7 @@ function& function::operator=(function&& other) noexcept {
|
||||
new (&m_value.native) native_function(std::move(other.m_value.native));
|
||||
} break;
|
||||
case function_t::Import: {
|
||||
m_value.imp.mod = other.m_value.imp.mod;
|
||||
m_value.imp.function = other.m_value.imp.function;
|
||||
m_value.imp = std::move(other.m_value.imp);
|
||||
} break;
|
||||
}
|
||||
other.m_value.position = 0;
|
||||
@@ -48,4 +52,39 @@ function& function::operator=(function&& other) noexcept {
|
||||
return *this;
|
||||
}
|
||||
|
||||
function::function(const function& other)
|
||||
: m_name(other.m_name), m_type(other.m_type) {
|
||||
switch (m_type) {
|
||||
case function_t::Normal: {
|
||||
m_value.position = other.m_value.position;
|
||||
} break;
|
||||
case function_t::Native: {
|
||||
new (&m_value.native) native_function(other.m_value.native);
|
||||
} break;
|
||||
case function_t::Import: {
|
||||
m_value.imp = other.m_value.imp;
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
function& function::operator=(const function& other) {
|
||||
if (this == &other) return *this;
|
||||
|
||||
m_name = other.m_name;
|
||||
m_type = other.m_type;
|
||||
switch (m_type) {
|
||||
case function_t::Normal: {
|
||||
m_value.position = other.m_value.position;
|
||||
} break;
|
||||
case function_t::Native: {
|
||||
new (&m_value.native) native_function(other.m_value.native);
|
||||
} break;
|
||||
case function_t::Import: {
|
||||
m_value.imp = other.m_value.imp;
|
||||
} break;
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
} // namespace furvm
|
||||
|
||||
+6
-15
@@ -1,11 +1,6 @@
|
||||
#ifndef LIBFURVM
|
||||
|
||||
#include "furvm/context.hpp"
|
||||
#include "furvm/executor.hpp"
|
||||
#include "furvm/function.hpp"
|
||||
#include "furvm/instruction.hpp"
|
||||
#include "furvm/serializer.hpp"
|
||||
#include "furvm/thing.hpp"
|
||||
#include "furvm/furvm.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
@@ -24,22 +19,18 @@ static constexpr std::array<furvm::byte, 8> s_bytecode = {
|
||||
int main(void) {
|
||||
auto context = std::make_shared<furvm::context>();
|
||||
|
||||
auto mainModule = context->emplace(s_bytecode.begin(), s_bytecode.end());
|
||||
furvm::mod_h mainModule = context->emplace_module("main", s_bytecode.begin(), s_bytecode.end());
|
||||
furvm::function_h mainFunc = mainModule->emplace_function("main", 0);
|
||||
|
||||
auto mainFunction = furvm::function::create(mainModule, 0);
|
||||
mainModule->serialize(std::cout);
|
||||
|
||||
std::ofstream file("./test.furm", std::ios::binary);
|
||||
furvm::serializer::serialize_module(file, mainModule);
|
||||
|
||||
auto executor = furvm::executor::create(context);
|
||||
executor->push_frame(mainFunction);
|
||||
furvm::executor_h executor = context->emplace_executor(context);
|
||||
executor->push_frame(mainModule, *mainFunc);
|
||||
|
||||
static constexpr std::size_t FPC = 3; // Frames per collection
|
||||
|
||||
std::size_t count = 0;
|
||||
while ((executor->flags() & furvm::executor_flags::Done) != furvm::executor_flags::Done) {
|
||||
executor->step();
|
||||
if ((++count % FPC) == 0) context->collect();
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
+32
-1
@@ -1,3 +1,34 @@
|
||||
#include "furvm/module.hpp"
|
||||
|
||||
namespace furvm {}
|
||||
#include "furvm/detail/serialization.hpp"
|
||||
#include "furvm/fwd.hpp"
|
||||
|
||||
#include <ios>
|
||||
|
||||
namespace furvm {
|
||||
|
||||
std::ostream& mod::serialize(std::ostream& os) const {
|
||||
os << MAGIC;
|
||||
detail::serialize(os, std::uint32_t(0)); // version
|
||||
|
||||
detail::serialize(os, function_id(m_functionMap.size()));
|
||||
for (const auto& [name, id] : m_functionMap) {
|
||||
detail::serialize(os, name);
|
||||
function_h func = m_functions.at(id);
|
||||
detail::serialize(os, std::uint8_t(func->type()));
|
||||
switch (func->type()) {
|
||||
case function_t::Normal: {
|
||||
detail::serialize(os, func->position());
|
||||
} break;
|
||||
case function_t::Native: break;
|
||||
case function_t::Import: {
|
||||
detail::serialize(os, func->imp().mod);
|
||||
detail::serialize(os, func->imp().function);
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
detail::serialize(os, std::uint64_t(m_bytecode.size()));
|
||||
return os.write(reinterpret_cast<const char*>(m_bytecode.data()), static_cast<std::streamsize>(m_bytecode.size()));
|
||||
}
|
||||
} // namespace furvm
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
#include "furvm/serializer.hpp"
|
||||
|
||||
#include "furvm/function.hpp" // IWYU pragma: keep
|
||||
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <istream>
|
||||
#include <optional>
|
||||
#include <ostream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace furvm {
|
||||
|
||||
template <typename T>
|
||||
static inline void write_raw(std::ostream& os, const T& value) {
|
||||
os.write(reinterpret_cast<const char*>(&value), sizeof(T));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
static inline void read_raw(std::istream& is, T& value) {
|
||||
is.read(reinterpret_cast<char*>(&value), sizeof(T));
|
||||
}
|
||||
|
||||
static inline void write_u64(std::ostream& os, std::uint64_t value) {
|
||||
os.put(static_cast<char>((value >> 0ULL) & 0xFF));
|
||||
os.put(static_cast<char>((value >> 8ULL) & 0xFF));
|
||||
os.put(static_cast<char>((value >> 16ULL) & 0xFF));
|
||||
os.put(static_cast<char>((value >> 24ULL) & 0xFF));
|
||||
os.put(static_cast<char>((value >> 32ULL) & 0xFF));
|
||||
os.put(static_cast<char>((value >> 40ULL) & 0xFF));
|
||||
os.put(static_cast<char>((value >> 48ULL) & 0xFF));
|
||||
os.put(static_cast<char>((value >> 56ULL) & 0xFF));
|
||||
}
|
||||
|
||||
static inline void read_u64(std::istream& is, std::uint64_t& value) {
|
||||
value = (static_cast<std::uint64_t>(is.get()) << 0) | (static_cast<std::uint64_t>(is.get()) << 8) |
|
||||
(static_cast<std::uint64_t>(is.get()) << 16) | (static_cast<std::uint64_t>(is.get()) << 24) |
|
||||
(static_cast<std::uint64_t>(is.get()) << 32) | (static_cast<std::uint64_t>(is.get()) << 40) |
|
||||
(static_cast<std::uint64_t>(is.get()) << 48) | (static_cast<std::uint64_t>(is.get()) << 56);
|
||||
}
|
||||
|
||||
static inline void write_u32(std::ostream& os, std::uint32_t value) {
|
||||
os.put(static_cast<char>((value >> 0ULL) & 0xFF));
|
||||
os.put(static_cast<char>((value >> 8ULL) & 0xFF));
|
||||
os.put(static_cast<char>((value >> 16ULL) & 0xFF));
|
||||
os.put(static_cast<char>((value >> 24ULL) & 0xFF));
|
||||
}
|
||||
|
||||
static inline void read_u32(std::istream& is, std::uint32_t& value) {
|
||||
value = static_cast<std::uint32_t>(is.get() << 0) | static_cast<std::uint32_t>(is.get() << 8) |
|
||||
static_cast<std::uint32_t>(is.get() << 16) | static_cast<std::uint32_t>(is.get() << 24);
|
||||
}
|
||||
|
||||
static inline void write_u16(std::ostream& os, std::uint16_t value) {
|
||||
os.put(static_cast<char>((value >> 0ULL) & 0xFF));
|
||||
os.put(static_cast<char>((value >> 8ULL) & 0xFF));
|
||||
}
|
||||
|
||||
static inline void read_u16(std::istream& is, std::uint16_t& value) {
|
||||
value = static_cast<std::uint16_t>(is.get() << 0) | static_cast<std::uint16_t>(is.get() << 8);
|
||||
}
|
||||
|
||||
static inline void write_u8(std::ostream& os, std::uint8_t value) {
|
||||
os.put(static_cast<char>((value >> 0ULL) & 0xFF));
|
||||
}
|
||||
|
||||
static inline void read_u8(std::istream& is, std::uint8_t& value) {
|
||||
value = static_cast<std::uint8_t>(is.get() << 0);
|
||||
}
|
||||
|
||||
bool serializer::serialize_module(std::ostream& os, const mod_p& mod) {
|
||||
os.write(reinterpret_cast<const char*>(MODULE_MAGIC), sizeof(MODULE_MAGIC));
|
||||
write_u32(os, VERSION);
|
||||
|
||||
write_u32(os, mod->m_functions.size());
|
||||
for (const auto& func : mod->m_functions) {
|
||||
write_u16(os, func->id());
|
||||
write_u8(os, static_cast<std::uint8_t>(func->type()));
|
||||
switch (func->type()) {
|
||||
case function_t::Normal: {
|
||||
write_u64(os, func->position());
|
||||
} break;
|
||||
case function_t::Native: {
|
||||
// TODO: Replace with a reference to the function's name from constant pool
|
||||
throw std::runtime_error("cannot serialize native functions yet");
|
||||
} break;
|
||||
case function_t::Import: {
|
||||
// TODO: Replace with a reference to the module's and function's name from constant pool
|
||||
throw std::runtime_error("cannot serialize import functions yet");
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
write_u64(os, mod->m_bytecode.size());
|
||||
os.write(reinterpret_cast<const char*>(mod->m_bytecode.data()),
|
||||
static_cast<std::streamsize>(mod->m_bytecode.size()));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace furvm
|
||||
@@ -1,243 +0,0 @@
|
||||
// NOLINTBEGIN(cppcoreguidelines-no-malloc)
|
||||
|
||||
#include "furvm/thing.hpp"
|
||||
|
||||
#include "furvm/context.hpp" // IWYU pragma: keep
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace furvm {
|
||||
|
||||
std::size_t thing_type_size(thing_t type) {
|
||||
switch (type) {
|
||||
case thing_t::Int32: return 4;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
thing::thing(rzecz, thing_handle id, thing_t type, const context_p& context)
|
||||
: m_id(id), m_type(type), m_context(context) {
|
||||
std::size_t size = thing_type_size(type);
|
||||
std::byte* data = nullptr;
|
||||
if (!m_context->m_deadThingData.empty()) {
|
||||
thing_t itType{};
|
||||
for (auto it = m_context->m_deadThingData.rbegin(); it != m_context->m_deadThingData.rend(); ++it) {
|
||||
std::memcpy(&itType, static_cast<std::byte*>(*it) - sizeof(itType), sizeof(itType));
|
||||
if (size == thing_type_size(itType)) {
|
||||
data = static_cast<std::byte*>(*it);
|
||||
m_context->m_deadThingData.erase(std::next(it).base());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (data == nullptr) data = m_context->m_thingArena.allocate<std::byte>(sizeof(type) + size);
|
||||
|
||||
if (data == nullptr) throw std::runtime_error("failed to allocate data for new thing");
|
||||
std::memcpy(data, &type, sizeof(type));
|
||||
m_data = data + sizeof(type);
|
||||
|
||||
switch (m_type) {
|
||||
// Primitives are zero-initialized.
|
||||
default:
|
||||
case thing_t::Int32: std::memset(m_data, 0, size);
|
||||
}
|
||||
}
|
||||
|
||||
thing::~thing() {
|
||||
switch (m_type) {
|
||||
// Primitives are not destructed.
|
||||
default:
|
||||
case thing_t::Int32: break;
|
||||
}
|
||||
|
||||
m_context->m_deadThingData.push_back(m_data);
|
||||
}
|
||||
|
||||
thing::thing(thing&& other) noexcept
|
||||
: m_id(other.m_id),
|
||||
m_type(other.m_type),
|
||||
m_context(std::move(other.m_context)),
|
||||
m_refCount(other.m_refCount),
|
||||
m_data(other.m_data) {
|
||||
other.m_id = {};
|
||||
other.m_type = {};
|
||||
other.m_refCount = {};
|
||||
other.m_data = nullptr;
|
||||
}
|
||||
|
||||
thing& thing::operator=(thing&& other) noexcept {
|
||||
if (this == &other) return *this;
|
||||
m_id = other.m_id;
|
||||
m_type = other.m_type;
|
||||
m_context = std::move(other.m_context);
|
||||
m_refCount = other.m_refCount;
|
||||
m_data = other.m_data;
|
||||
|
||||
other.m_id = {};
|
||||
other.m_type = {};
|
||||
other.m_refCount = {};
|
||||
other.m_data = nullptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
static constexpr std::uint16_t thing_type_pair(thing_t lhs, thing_t rhs) {
|
||||
return (static_cast<std::uint16_t>(lhs) << 8) | static_cast<std::uint16_t>(rhs);
|
||||
}
|
||||
|
||||
thing_p operator+(const thing_p& lhs, const thing_p& rhs) {
|
||||
switch (thing_type_pair(lhs->m_type, rhs->m_type)) {
|
||||
case thing_type_pair(thing_t::Int32, thing_t::Int32): {
|
||||
auto res = thing::create(lhs->m_context, thing_t::Int32);
|
||||
res->int32() = lhs->int32() + rhs->int32();
|
||||
return res;
|
||||
}
|
||||
default: throw std::runtime_error("unexpected operator");
|
||||
}
|
||||
}
|
||||
|
||||
thing_p operator-(const thing_p& lhs, const thing_p& rhs) {
|
||||
switch (thing_type_pair(lhs->m_type, rhs->m_type)) {
|
||||
case thing_type_pair(thing_t::Int32, thing_t::Int32): {
|
||||
auto res = thing::create(lhs->m_context, thing_t::Int32);
|
||||
res->int32() = lhs->int32() - rhs->int32();
|
||||
return res;
|
||||
}
|
||||
default: throw std::runtime_error("unexpected operator");
|
||||
}
|
||||
}
|
||||
|
||||
thing_p operator*(const thing_p& lhs, const thing_p& rhs) {
|
||||
switch (thing_type_pair(lhs->m_type, rhs->m_type)) {
|
||||
case thing_type_pair(thing_t::Int32, thing_t::Int32): {
|
||||
auto res = thing::create(lhs->m_context, thing_t::Int32);
|
||||
res->int32() = lhs->int32() * rhs->int32();
|
||||
return res;
|
||||
}
|
||||
default: throw std::runtime_error("unexpected operator");
|
||||
}
|
||||
}
|
||||
|
||||
thing_p operator/(const thing_p& lhs, const thing_p& rhs) {
|
||||
switch (thing_type_pair(lhs->m_type, rhs->m_type)) {
|
||||
case thing_type_pair(thing_t::Int32, thing_t::Int32): {
|
||||
auto res = thing::create(lhs->m_context, thing_t::Int32);
|
||||
res->int32() = lhs->int32() / rhs->int32();
|
||||
return res;
|
||||
}
|
||||
default: throw std::runtime_error("unexpected operator");
|
||||
}
|
||||
}
|
||||
|
||||
thing_p operator%(const thing_p& lhs, const thing_p& rhs) {
|
||||
switch (thing_type_pair(lhs->m_type, rhs->m_type)) {
|
||||
case thing_type_pair(thing_t::Int32, thing_t::Int32): {
|
||||
auto res = thing::create(lhs->m_context, thing_t::Int32);
|
||||
res->int32() = lhs->int32() % rhs->int32();
|
||||
return res;
|
||||
}
|
||||
default: throw std::runtime_error("unexpected operator");
|
||||
}
|
||||
}
|
||||
|
||||
thing_p operator==(const thing_p& lhs, const thing_p& rhs) {
|
||||
switch (thing_type_pair(lhs->m_type, rhs->m_type)) {
|
||||
case thing_type_pair(thing_t::Int32, thing_t::Int32): {
|
||||
auto res = thing::create(lhs->m_context, thing_t::Int32);
|
||||
res->int32() = static_cast<std::int32_t>(lhs->int32() == rhs->int32());
|
||||
return res;
|
||||
}
|
||||
default: throw std::runtime_error("unexpected operator");
|
||||
}
|
||||
}
|
||||
|
||||
thing_p operator!=(const thing_p& lhs, const thing_p& rhs) {
|
||||
switch (thing_type_pair(lhs->m_type, rhs->m_type)) {
|
||||
case thing_type_pair(thing_t::Int32, thing_t::Int32): {
|
||||
auto res = thing::create(lhs->m_context, thing_t::Int32);
|
||||
res->int32() = static_cast<std::int32_t>(lhs->int32() != rhs->int32());
|
||||
return res;
|
||||
}
|
||||
default: throw std::runtime_error("unexpected operator");
|
||||
}
|
||||
}
|
||||
|
||||
thing_p operator<(const thing_p& lhs, const thing_p& rhs) {
|
||||
switch (thing_type_pair(lhs->m_type, rhs->m_type)) {
|
||||
case thing_type_pair(thing_t::Int32, thing_t::Int32): {
|
||||
auto res = thing::create(lhs->m_context, thing_t::Int32);
|
||||
res->int32() = static_cast<std::int32_t>(lhs->int32() < rhs->int32());
|
||||
return res;
|
||||
}
|
||||
default: throw std::runtime_error("unexpected operator");
|
||||
}
|
||||
}
|
||||
|
||||
thing_p operator>(const thing_p& lhs, const thing_p& rhs) {
|
||||
switch (thing_type_pair(lhs->m_type, rhs->m_type)) {
|
||||
case thing_type_pair(thing_t::Int32, thing_t::Int32): {
|
||||
auto res = thing::create(lhs->m_context, thing_t::Int32);
|
||||
res->int32() = static_cast<std::int32_t>(lhs->int32() > rhs->int32());
|
||||
return res;
|
||||
}
|
||||
default: throw std::runtime_error("unexpected operator");
|
||||
}
|
||||
}
|
||||
|
||||
thing_p operator<=(const thing_p& lhs, const thing_p& rhs) {
|
||||
switch (thing_type_pair(lhs->m_type, rhs->m_type)) {
|
||||
case thing_type_pair(thing_t::Int32, thing_t::Int32): {
|
||||
auto res = thing::create(lhs->m_context, thing_t::Int32);
|
||||
res->int32() = static_cast<std::int32_t>(lhs->int32() <= rhs->int32());
|
||||
return res;
|
||||
}
|
||||
default: throw std::runtime_error("unexpected operator");
|
||||
}
|
||||
}
|
||||
|
||||
thing_p operator>=(const thing_p& lhs, const thing_p& rhs) {
|
||||
switch (thing_type_pair(lhs->m_type, rhs->m_type)) {
|
||||
case thing_type_pair(thing_t::Int32, thing_t::Int32): {
|
||||
auto res = thing::create(lhs->m_context, thing_t::Int32);
|
||||
res->int32() = static_cast<std::int32_t>(lhs->int32() >= rhs->int32());
|
||||
return res;
|
||||
}
|
||||
default: throw std::runtime_error("unexpected operator");
|
||||
}
|
||||
}
|
||||
|
||||
thing_p thing::clone(const thing_p& thing) {
|
||||
thing_handle id = thing->m_context->m_things.size();
|
||||
if (!thing->m_context->m_deadThings.empty()) {
|
||||
id = thing->m_context->m_deadThings.front();
|
||||
thing->m_context->m_deadThings.pop();
|
||||
id += 1 << GENERATION_SIZE;
|
||||
}
|
||||
thing_handle idx = id & ((1ULL << ((sizeof(id) * 8) - GENERATION_SIZE)) - 1);
|
||||
|
||||
auto th = std::make_shared<class thing>(rzecz{}, id, thing->m_type, thing->m_context);
|
||||
switch (thing->m_type) {
|
||||
// Primitives
|
||||
default: {
|
||||
memcpy(th->m_data, thing->m_data, thing_type_size(thing->m_type));
|
||||
}
|
||||
}
|
||||
|
||||
thing->m_context->m_things.emplace(thing->m_context->m_things.begin() + idx, th);
|
||||
return std::move(th);
|
||||
}
|
||||
|
||||
std::int32_t& thing::int32() {
|
||||
if (m_type != thing_t::Int32) throw bad_thing_access();
|
||||
return *static_cast<std::int32_t*>(m_data);
|
||||
}
|
||||
|
||||
const std::int32_t& thing::int32() const {
|
||||
if (m_type != thing_t::Int32) throw bad_thing_access();
|
||||
return *static_cast<std::int32_t*>(m_data);
|
||||
}
|
||||
|
||||
} // namespace furvm
|
||||
|
||||
// NOLINTEND(cppcoreguidelines-no-malloc)
|
||||
Reference in New Issue
Block a user