36#include <gtest/gtest.h>
70 std::string stdout_text;
71 std::string stderr_text;
89 function.
name =
"choose";
96 flag.
kind = Compiler_IR_Slot_Kind::Parameter;
102 value.kind = Compiler_IR_Slot_Kind::Local;
103 value.name =
"value";
108 entry.
label =
"entry";
111 zero.
kind = Compiler_IR_Instruction_Kind::Constant;
117 init_store.
kind = Compiler_IR_Instruction_Kind::Store;
123 load_flag.
kind = Compiler_IR_Instruction_Kind::Load;
133 auto exit = make_exit_block();
134 exit.predecessors.append(3);
138 then_block.
label =
"if.then.0";
141 one.
kind = Compiler_IR_Instruction_Kind::Constant;
147 then_store.
kind = Compiler_IR_Instruction_Kind::Store;
158 join_block.
label =
"if.end.0";
161 load_value.
kind = Compiler_IR_Instruction_Kind::Load;
174 else_block.
label =
"if.else.0";
177 two.
kind = Compiler_IR_Instruction_Kind::Constant;
183 else_store.
kind = Compiler_IR_Instruction_Kind::Store;
192 function.
blocks.append(entry);
194 function.
blocks.append(then_block);
195 function.
blocks.append(join_block);
196 function.
blocks.append(else_block);
205 function.
name =
"add_one";
212 param.
kind = Compiler_IR_Slot_Kind::Parameter;
218 local.
kind = Compiler_IR_Slot_Kind::Local;
224 entry.
label =
"entry";
227 constant.
kind = Compiler_IR_Instruction_Kind::Constant;
233 store.
kind = Compiler_IR_Instruction_Kind::Store;
239 load_x.
kind = Compiler_IR_Instruction_Kind::Load;
245 load_tmp.
kind = Compiler_IR_Instruction_Kind::Load;
251 add.kind = Compiler_IR_Instruction_Kind::Binary;
253 add.op = Compiler_Operator_Kind::Plus;
254 add.operands.append(2);
255 add.operands.append(3);
262 auto exit = make_exit_block();
263 exit.predecessors.append(0);
265 function.
blocks.append(entry);
271 make_module_with_top_level_call()
277 global.kind = Compiler_IR_Slot_Kind::Global;
278 global.name =
"answer";
279 module.global_slots.append(global);
282 module.functions.append(function);
286 top->name =
"<top-level>";
287 top->entry_block = 0;
289 top->next_value_id = 3;
293 entry.
label =
"entry";
296 function_ref.
kind = Compiler_IR_Instruction_Kind::Function_Ref;
302 constant.
kind = Compiler_IR_Instruction_Kind::Constant;
304 constant.
text =
"41";
308 call.kind = Compiler_IR_Instruction_Kind::Call;
310 call.operands.append(1);
311 call.operands.append(2);
315 store_global.
kind = Compiler_IR_Instruction_Kind::Store;
323 auto exit = make_exit_block();
324 exit.predecessors.append(0);
326 top->blocks.append(entry);
327 top->blocks.append(
exit);
328 module.top_level = top;
333 make_divide_by_zero_top_level_module()
339 top->name =
"<top-level>";
340 top->entry_block = 0;
342 top->next_value_id = 3;
346 entry.
label =
"entry";
349 lhs.
kind = Compiler_IR_Instruction_Kind::Constant;
355 rhs.
kind = Compiler_IR_Instruction_Kind::Constant;
361 div.kind = Compiler_IR_Instruction_Kind::Binary;
363 div.op = Compiler_Operator_Kind::Slash;
364 div.operands.append(1);
365 div.operands.append(2);
372 auto exit = make_exit_block();
373 exit.predecessors.append(0);
375 top->blocks.append(entry);
376 top->blocks.append(
exit);
377 module.top_level = top;
382 read_text(
const std::filesystem::path & path)
384 std::ifstream in(path);
385 return std::string((std::istreambuf_iterator<char>(in)),
386 std::istreambuf_iterator<char>());
390 write_text(
const std::filesystem::path & path,
391 const std::string & text)
393 std::ofstream
out(path);
400 std::string quoted =
"'";
401 for (
const char ch : text)
406 quoted.push_back(ch);
408 quoted.push_back(
'\'');
415 return std::system(
"command -v cc >/dev/null 2>&1") == 0;
419 long long process_id() noexcept
422 return static_cast<long long>(_getpid());
424 return static_cast<long long>(getpid());
428 std::filesystem::path
429 unique_temp_path(
const std::string & stem,
430 const std::string & extension)
439 static std::atomic<unsigned long long>
counter{0};
440 const auto nonce = std::to_string(
441 std::chrono::steady_clock::now().time_since_epoch().
count()) +
442 "_" + std::to_string(process_id()) +
443 "_" + std::to_string(
counter++);
444 return std::filesystem::temp_directory_path()
449 run_command(
const std::string & command)
451 Command_Result result;
452 const auto stdout_path = unique_temp_path(
"aleph_backend_stdout",
".txt");
453 const auto stderr_path = unique_temp_path(
"aleph_backend_stderr",
".txt");
454 const auto full_command = command
458 result.status = std::system(full_command.c_str());
459 result.stdout_text = read_text(stdout_path);
460 result.stderr_text = read_text(stderr_path);
461 std::error_code ignore_error;
462 std::filesystem::remove(stdout_path, ignore_error);
463 std::filesystem::remove(stderr_path, ignore_error);
469 const std::string & extra_c =
"")
471 const auto source_path = unique_temp_path(
"aleph_backend_generated",
".c");
472 const auto exe_path = unique_temp_path(
"aleph_backend_generated",
".out");
474 write_text(source_path, emission.
source +
"\n" + extra_c);
475 const auto compile = run_command(
476 "cc -std=c11 -Wall -Wextra -pedantic "
480 if (compile.status != 0)
483 const auto executed = run_command(
shell_quote(exe_path.string()));
484 std::error_code ignore_error;
485 std::filesystem::remove(source_path, ignore_error);
486 std::filesystem::remove(exe_path, ignore_error);
491TEST(CompilerBackendC, EmitsReadableGotoBasedC)
494 auto source = make_branch_ir();
495 module.functions.append(&source);
501 ASSERT_TRUE(emitted.valid);
502 EXPECT_NE(emitted.source.find(
"goto " + emitted.c_prefix +
"_B3"), std::string::npos);
503 EXPECT_NE(emitted.source.find(
"if ("), std::string::npos);
504 EXPECT_NE(emitted.source.find(
"static " + emitted.value_type_name), std::string::npos);
505 EXPECT_NE(emitted.source.find(emitted.function_symbols.access(0)), std::string::npos);
506 EXPECT_NE(emitted.source.find(
"choose"), std::string::npos);
509TEST(CompilerBackendC, StandaloneGeneratedCCompilesAndRunsTopLevel)
511 if (not host_has_cc())
512 GTEST_SKIP() <<
"No se encontró `cc` en el host";
514 auto module = make_module_with_top_level_call();
521 ASSERT_TRUE(emitted.valid);
523 const auto executed = compile_and_run(emitted);
524 EXPECT_EQ(executed.status, 0);
525 EXPECT_NE(executed.stdout_text.find(
"Result = Unit"), std::string::npos);
526 EXPECT_NE(executed.stdout_text.find(
"g0 answer = Int(42)"), std::string::npos);
527 EXPECT_TRUE(executed.stderr_text.empty());
529 delete module.functions.access(0);
530 delete module.top_level;
533TEST(CompilerBackendC, LibraryStyleEmissionCanCallFunctionsDirectly)
535 if (not host_has_cc())
536 GTEST_SKIP() <<
"No se encontró `cc` en el host";
539 auto source = make_branch_ir();
540 module.functions.append(&source);
545 ASSERT_TRUE(emitted.valid);
550 " " + emitted.module_struct_name +
" module;\n"
551 " " + emitted.module_init_symbol +
"(&module);\n"
552 " " + emitted.value_type_name +
" args[1];\n"
553 " args[0] = " + emitted.c_prefix +
"_make_bool(false);\n"
554 " " + emitted.value_type_name +
" result = "
555 + emitted.function_symbols.access(0) +
"(&module, args, 1u);\n"
556 " " + emitted.print_value_symbol +
"(stdout, result);\n"
557 " fputc('\\n', stdout);\n"
561 const auto executed = compile_and_run(emitted, harness);
562 EXPECT_EQ(executed.status, 0);
563 EXPECT_EQ(executed.stdout_text,
"Int(2)\n");
564 EXPECT_TRUE(executed.stderr_text.empty());
567TEST(CompilerBackendC, GeneratedCRuntimeChecksSurfaceErrors)
569 if (not host_has_cc())
570 GTEST_SKIP() <<
"No se encontró `cc` en el host";
572 auto module = make_divide_by_zero_top_level_module();
579 ASSERT_TRUE(emitted.valid);
581 const auto executed = compile_and_run(emitted);
582 EXPECT_NE(executed.status, 0);
583 EXPECT_NE(executed.stderr_text.find(
"division by zero"), std::string::npos);
585 delete module.top_level;
591 struct Engine_Outcome
593 bool overflowed =
false;
598 struct Lowered_Program
610 std::vector<std::unique_ptr<Compiler_IR_Function>> optimized_functions;
612 explicit Lowered_Program(
const std::string & source)
616 const auto *
module = parser.parse_module();
617 typed.analyze_module(module);
618 EXPECT_FALSE(dx.has_errors()) << source;
621 hir_module = hir_lowering.lower_module(module);
623 ir_module = ir_lowering.lower_module(hir_module);
626 optimized = *ir_module;
629 optimized_functions.push_back(std::make_unique<Compiler_IR_Function>(
631 return optimized_functions.back().get();
633 for (
size_t i = 0; i < optimized.
functions.size(); ++i)
639 Engine_Outcome run_hir()
642 const auto evaluated = runtime.evaluate_module(hir_module);
643 if (not evaluated.ok())
644 return {evaluated.error.code ==
"RUN013"
645 and evaluated.error.message ==
"integer overflow",
646 evaluated.error.code +
": " + evaluated.error.message};
655 const auto executed = vm.run_top_level();
656 if (not executed.ok())
657 return {executed.error.code ==
"BCV023"
658 and executed.error.message ==
"integer overflow",
659 executed.error.code +
": " + executed.error.message};
660 return {
false, vm.dump_globals()};
669 EXPECT_TRUE(emitted.valid);
670 const auto executed = compile_and_run(emitted);
671 if (executed.status != 0)
672 return {executed.stderr_text.find(
"integer overflow") != std::string::npos,
673 executed.stderr_text};
674 return {
false, executed.stdout_text};
684TEST(CompilerBackendC, IntegerBoundariesAreTheSameInEveryEngine)
688 const char * expression;
693 const Case cases[] = {
694 {
"9223372036854775807 + 1",
true, 0},
695 {
"9223372036854775807 + 0",
false, LLONG_MAX},
696 {
"-9223372036854775807 - 1",
false, LLONG_MIN},
697 {
"-9223372036854775807 - 2",
true, 0},
698 {
"9223372036854775807 - -1",
true, 0},
699 {
"4611686018427387904 * 2",
true, 0},
700 {
"3037000499 * 3037000499",
false, 3037000499LL * 3037000499LL},
701 {
"(-9223372036854775807 - 1) * -1",
true, 0},
702 {
"(-9223372036854775807 - 1) * 1",
false, LLONG_MIN},
703 {
"(-9223372036854775807 - 1) / -1",
true, 0},
704 {
"(-9223372036854775807 - 1) / 1",
false, LLONG_MIN},
705 {
"(-9223372036854775807 - 1) % -1",
false, 0},
706 {
"-(-9223372036854775807 - 1)",
true, 0},
707 {
"-9223372036854775807",
false, -LLONG_MAX},
708 {
"-7 / 2",
false, -3},
709 {
"-7 % 2",
false, -1},
712 const bool with_c = host_has_cc();
713 for (
const auto & c : cases)
714 for (
const bool dead : {
false,
true})
717 const std::string source = dead
718 ? std::string(
"fn f() {\n let unused = ") + c.expression
719 +
";\n return 0;\n}\nlet value = f();\n"
720 : std::string(
"let value = ") + c.expression +
";\n";
722 =
"value = Int(" + std::to_string(dead ? 0 : c.value) +
")";
723 Lowered_Program program(source);
725 std::vector<std::pair<std::string, Engine_Outcome>> outcomes;
726 outcomes.emplace_back(
"HIR", program.run_hir());
727 outcomes.emplace_back(
"VM", Lowered_Program::run_vm(*program.ir_module));
728 outcomes.emplace_back(
"optimized VM", Lowered_Program::run_vm(program.optimized));
731 outcomes.emplace_back(
"C", Lowered_Program::run_c(*program.ir_module));
732 outcomes.emplace_back(
"optimized C", Lowered_Program::run_c(program.optimized));
735 for (
const auto & [
engine, outcome] : outcomes)
737 EXPECT_EQ(outcome.overflowed, c.overflows)
738 <<
engine <<
":\n" << source << outcome.globals;
740 EXPECT_NE(outcome.globals.find(
expected), std::string::npos)
741 <<
engine <<
":\n" << source << outcome.globals;
Reusable bytecode format and lowering from Compiler_IR_Model.H.
Simple portable VM for executing the register bytecode in Bytecode.H.
Portable C backend that emits standalone C from Compiler_IR_Model.H.
Reusable dataflow analyses and dead-code elimination over Compiler_IR_Model.H.
Compatibility umbrella for the reusable HIR model and the MVP lowering.
Compatibility umbrella for the reusable IR model and the MVP lowering.
Recursive-descent parser for the compiler-support MVP grammar.
Typed semantic pass connecting the AST, the name pass, and type constraints.
Reusable runtime and structured evaluator for HIR-based interpreters.
size_t size_t int32_t value
size_t size_t int32_t * out
Arena-backed ownership context for AST nodes.
Arena-backed ownership context for bytecode functions and modules.
Lowers explicit IR into register-based bytecode.
Small portable VM for executing one Compiler_Bytecode_Module.
Arena-backed ownership context for HIR nodes.
Lowers the MVP typed AST into HIR.
Arena-backed ownership context for IR nodes.
Lowers typed HIR into explicit-value IR.
Recursive-descent parser that produces an AST in Compiler_Ast_Context.
Inference-oriented semantic pass for the MVP compiler front-end.
Diagnostic accumulator and renderer.
T & append()
Allocate a new entry to the end of array.
Structured runtime for executing typed HIR.
Stores source files and resolves offsets into human-readable data.
Source_File_Id add_virtual_file(const std::string &name, const std::string &text)
Registers an in-memory source file.
Minimal std::expected-style result type for C++20.
std::string shell_quote(const std::string &s)
const char * extension(Frame_Output_Format format) noexcept
Compiler_SSA_Block & block(Compiler_SSA_Function &function, const Compiler_SSA_Block_Id id)
Main namespace for Aleph-w library functions.
void exit(const char *file, int line, const char *format,...)
Print a message and exit the program.
constexpr size_t compiler_ir_invalid_id() noexcept
Returns the sentinel invalid IR id.
and
Check uniqueness with explicit hash + equality functors.
Compiler_Dead_Code_Elimination_Result eliminate_dead_code(const Compiler_IR_Function &function)
Eliminates unreachable blocks, dead pure instructions, dead local stores, and folds constant-conditio...
std::string interpreter_dump_globals(const Interpreter_Runtime &runtime)
Dumps the globals currently installed in one runtime.
Compiler_C_Backend_Emission compiler_emit_c_module(const Compiler_IR_Module *module, const Compiler_C_Backend_Options &options={}, const Compiler_Type_Context *types=nullptr)
Convenience wrapper that emits one IR module to portable C.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
double add(double a, double b)
double div(double a, double b)
static struct argp_option options[]
Result of one C backend emission request.
std::string source
Final generated C translation unit.
Options that control one C backend emission request.
std::string module_name
Prefix used to derive stable C identifiers.
Compiler_IR_Function function
Optimized function copy.
One basic block of IR instructions.
std::string label
Deterministic debug label.
Compiler_IR_Terminator terminator
Explicit block terminator.
DynArray< Compiler_IR_Block_Id > predecessors
Predecessor block ids.
DynArray< Compiler_IR_Instruction > instructions
Linear instruction list.
Compiler_IR_Block_Id id
Stable block id.
Lowered IR for one function or top-level body.
Compiler_IR_Value_Id next_value_id
Next value id to allocate while lowering.
DynArray< Compiler_IR_Block > blocks
Basic blocks in deterministic id order.
std::string name
Debug or source-level name.
Compiler_IR_Block_Id exit_block
Canonical exit block.
Compiler_IR_Block_Id entry_block
Canonical entry block.
DynArray< Compiler_IR_Slot > local_slots
Parameter/local slots in stable order.
Compiler_IR_Function_Id id
Stable function id within the module.
One instruction producing an optional explicit result value.
std::string text
Constant spelling or debug payload.
Compiler_IR_Instruction_Kind kind
Instruction category.
Compiler_IR_Value_Id result_id
Produced value id, or 0 for void instructions.
DynArray< Compiler_IR_Value_Id > operands
Input values in deterministic order.
Compiler_IR_Local_Slot_Id local_slot_id
Referenced local/parameter slot, when relevant.
Compiler_IR_Function_Id function_id
Referenced function id, when relevant.
Compiler_IR_Global_Slot_Id global_slot_id
Referenced global slot, when relevant.
Lowered IR module with shared global slots and functions.
DynArray< Compiler_IR_Function * > functions
Lowered non-top-level functions.
Compiler_IR_Function * top_level
Optional top-level body lowered as a function.
One storage slot used by the IR.
std::string name
Debug name of the slot.
size_t id
Stable slot id within its storage space.
Compiler_IR_Slot_Kind kind
Slot storage category.
Compiler_IR_Terminator_Kind kind
Terminator category.
DynArray< Compiler_IR_Block_Id > successors
Successor blocks in deterministic order.
Compiler_IR_Value_Id condition_value
Branch condition value, if any.
Compiler_IR_Value_Id return_value
Return value, if any.
Compiler_SSA_Block_Id id
Dense SSA block id.
std::string label
Deterministic debug label.
Compiler_SSA_Terminator terminator
Explicit block terminator.
Compiler_IR_Terminator_Kind kind
Terminator category.