From 77ea433215f7ace16188ce3c1ee4c47c4eba7dca Mon Sep 17 00:00:00 2001 From: Minus Date: Wed, 18 Nov 2026 20:19:54 +0000 Subject: [PATCH] native x86-64 backend (pluggable, per-opcode lowering) A second backend that lowers each bytecode instruction to a machine-code call into a runtime helper, with control flow as real branches. - cat/backend/x86_64_glue.c: one helper per opcode, mirroring cat/vm.c exactly (frame lifecycle, arith, cmp, attr/idx, call/callmethod, is, next/fornext, try/raise). Helpers use the SysV convention (f in rdi, a/b/c in rsi/rdx/rcx) and return 0/1/-1. - cat/backend/x86_64.c: emits AT&T assembly (one labelled block per instruction, one call per helper, real jumps for JUMP/JUMPIF/JUMPIFNOT/ FORNEXT/RETURN, an .Lonerror block that resumes try handlers), plus a small generated _main.c that rebuilds the bytecode and boots the VM. Builds with as + cc linked against libcatscript.a. - generators are not lowered: their prototype carries no nat_entry, so the VM runs them (their bytecode is rebuilt by the generated main), and the emitted code simply falls back to the interpreter. - cat_vm_exec_closure dispatches to a prototype's nat_entry when present. - tests: native-vs-interpreter equivalence check. Suite 155 -> 156. Verified: hello, control, classes, generators, arith, errors, text, oop, slots, reflect, toml, files, ffi all match the interpreter natively. --- Makefile | 1 + include/cat/backend/x86_64.h | 112 +++++++ include/cat/bytecode.h | 1 + include/cat/vm.h | 16 + src/cat/backend/x86_64.c | 517 +++++++++++++++++++++++++++--- src/cat/backend/x86_64_glue.c | 569 ++++++++++++++++++++++++++++++++++ src/cat/vm.c | 23 +- tests/run_tests.sh | 30 ++ 8 files changed, 1221 insertions(+), 48 deletions(-) create mode 100644 include/cat/backend/x86_64.h create mode 100644 src/cat/backend/x86_64_glue.c diff --git a/Makefile b/Makefile index e864e4e..0b50104 100644 --- a/Makefile +++ b/Makefile @@ -34,6 +34,7 @@ SRCS := \ src/cat/module.c \ src/cat/backend/c.c \ src/cat/backend/x86_64.c \ + src/cat/backend/x86_64_glue.c \ src/cat/backend/registry.c \ src/cat/types/empty.c \ src/cat/types/type.c \ diff --git a/include/cat/backend/x86_64.h b/include/cat/backend/x86_64.h new file mode 100644 index 0000000..f76994e --- /dev/null +++ b/include/cat/backend/x86_64.h @@ -0,0 +1,112 @@ +/* + * cat/backend/x86_64.h -- runtime glue for the native x86-64 backend. + * + * Naming rule: cat_backend_x86_64_* / CAT_BACKEND_X86_64_*. + * + * Each bytecode instruction lowers to a call into one helper here (one + * per opcode); control flow becomes real jumps in the generated code. + * The assembly never needs struct offsets: it just sets arguments and + * calls a symbol. + * + * Helper convention (SysV): f in rdi, operands a/b/c in rsi/rdx/rcx. + * Return in eax: 0 ok; 1 ok-take-branch (popcond/fornext); -1 error + * (vm->err set), and the generated code runs its .Lonerror block. + */ +#ifndef CAT_BACKEND_X86_64_H +#define CAT_BACKEND_X86_64_H + +#include "cat/value.h" +#include "cat/vm.h" +#include "cat/bytecode.h" +#include "cat/types/function.h" + +typedef struct CAT_BACKEND_X86_64_Handler { + void *target; /* code address of the catch block */ + int sp; +} CAT_BACKEND_X86_64_Handler; + +typedef struct CAT_BACKEND_X86_64_Frame { + CAT_VM_State *vm; + CAT_BYTECODE_Function *fn; + CAT_VALUE_Value **stack; + CAT_VALUE_Value *locals[256]; + int sp; + int nhandlers; + CAT_BACKEND_X86_64_Handler handlers[CAT_VM_MAXHANDLER]; + CAT_VALUE_Value *ret; +} CAT_BACKEND_X86_64_Frame; + +/* A generated entry point. Returns 0 (f->ret set) or -1 (vm->err set). */ +typedef int (*CAT_BACKEND_X86_64_Entry)(CAT_BACKEND_X86_64_Frame *f); + +/* Bridge used by cat_vm_exec_closure for a prototype with a native entry. */ +int cat_backend_x86_64_top_call(CAT_VM_State *vm, + CAT_TYPES_FUNCTION_Closure *cl, + CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out); + +/* Frame lifecycle (prologue/epilogue helpers). */ +void cat_backend_x86_64_frame_init(CAT_BACKEND_X86_64_Frame *f, + CAT_VM_State *vm, + CAT_TYPES_FUNCTION_Closure *cl, + CAT_VALUE_Value **args, long nargs); +void cat_backend_x86_64_frame_done(CAT_BACKEND_X86_64_Frame *f); + +/* On error: resume the innermost handler (its code address), else NULL. */ +void *cat_backend_x86_64_handle_error(CAT_BACKEND_X86_64_Frame *f); + +/* Constant constructors (rebuild the pool in generated `main`). */ +CAT_VALUE_Value *cat_backend_x86_64_const_int(long long v); +CAT_VALUE_Value *cat_backend_x86_64_const_float(double v); +CAT_VALUE_Value *cat_backend_x86_64_const_text(const char *s); +CAT_VALUE_Value *cat_backend_x86_64_const_bool(long t); +CAT_VALUE_Value *cat_backend_x86_64_const_empty(void); + +/* One helper per opcode. */ +int cat_backend_x86_64_const(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_empty(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_true(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_false(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_getlocal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_setlocal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_getglobal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_setglobal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_pop(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_dup(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_arith(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_neg(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_not(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_cmp(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_concat(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_getattr(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_setattr(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_getidx(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_setidx(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_newtable(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_closure(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_call(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_callmethod(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_print(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_printexpr(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_is(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_next(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_popcond(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_fornext(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_return(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_trysetup(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_tryend(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); +int cat_backend_x86_64_raise(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c); + +/* Rebuild bytecode (used by generated `main`). */ +CAT_BYTECODE_Function *cat_backend_x86_64_fn_new(const char *name); +void cat_backend_x86_64_fn_setup(CAT_BYTECODE_Function *fn, long nparams, + long nlocals, long is_generator); +void cat_backend_x86_64_fn_add_const(CAT_BYTECODE_Function *fn, + CAT_VALUE_Value *v); +void cat_backend_x86_64_fn_emit(CAT_BYTECODE_Function *fn, long op, long a, + long b, long c, long line); +void cat_backend_x86_64_fn_add_proto(CAT_BYTECODE_Function *fn, + CAT_BYTECODE_Function *p); +void cat_backend_x86_64_fn_set_entry(CAT_BYTECODE_Function *fn, void *entry); + +#endif /* CAT_BACKEND_X86_64_H */ diff --git a/include/cat/bytecode.h b/include/cat/bytecode.h index f7e2f92..81052b1 100644 --- a/include/cat/bytecode.h +++ b/include/cat/bytecode.h @@ -97,6 +97,7 @@ typedef struct CAT_BYTECODE_Function { int nlocals; /* number of local slots */ int nparams; /* number of parameters */ int is_generator; /* contains yield: calls produce a generator */ + void *nat_entry; /* native code entry (x86_64 backend), or NULL */ } CAT_BYTECODE_Function; CAT_BYTECODE_Function *cat_bytecode_function_new(const char *name); diff --git a/include/cat/vm.h b/include/cat/vm.h index 23637f9..8805e90 100644 --- a/include/cat/vm.h +++ b/include/cat/vm.h @@ -69,6 +69,17 @@ CAT_VM_State *cat_vm_new(void); int cat_vm_run(CAT_VM_State *vm, CAT_BYTECODE_Function *fn, CAT_VALUE_Value **out); +/* Call any callable value by the VM's own rules: a closure runs its + * prototype (or yields a generator), a native runs its C callback, a + * table with a `call` member is invoked. Exposed for out-of-line code + * generators (e.g. the native backend's CALL helper). */ +int cat_vm_call_value(CAT_VM_State *vm, CAT_VALUE_Value *fnv, + CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out, + CAT_ERROR_Error *err); + +/* Print a value the way `print` does (used by code generators). */ +void cat_vm_print_value(CAT_VALUE_Value *v); + /* Register a native function (name, C callback) into globals. */ int cat_vm_register_native(CAT_VM_State *vm, const char *name, int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, @@ -78,6 +89,11 @@ int cat_vm_register_native(CAT_VM_State *vm, const char *name, * closures/natives invoked through the object system. */ CAT_VM_State *cat_vm_current(void); +/* Install/restore the thread-local current VM. Out-of-line code + * generators (the native backend) call this around native execution so + * natives invoked from generated code see the active VM. */ +void cat_vm_set_current(CAT_VM_State *vm); + /* Run (or resume) a frame. Returns 0 when the frame returns (*out set), * 1 when it yields (*out set, frame left resumable), or -1 on error * (vm->err set). The frame owns neither its operand stack nor its diff --git a/src/cat/backend/x86_64.c b/src/cat/backend/x86_64.c index c80b886..60ba478 100644 --- a/src/cat/backend/x86_64.c +++ b/src/cat/backend/x86_64.c @@ -3,18 +3,23 @@ * * Naming rule: symbols here are cat_backend_x86_64_* / CAT_BACKEND_X86_64_*. * - * Lowers a compiled CAT_BYTECODE_Function to x86-64 assembly (AT&T - * syntax, SysV ABI) and assembles/links it with `as` + `cc` against the - * catscript runtime archive. Unlike the C backend, the emitted artifact - * is machine code the assembler produces directly: no C translation unit - * and no C compiler front-end is involved in generating the program - * logic (cc is used only as the linker driver). + * Lowers a compiled CAT_BYTECODE_Function to x86-64 assembly (AT&T, SysV) + * and assembles/links it with `as` + `cc` against the catscript runtime. + * The emitted code is machine code: no C translation unit carries the + * program logic. Each bytecode instruction becomes a call into a runtime + * helper (cat/backend/x86_64_glue.c), and control flow becomes real + * branches inside the generated code. * - * The lowering is per-opcode: every bytecode instruction becomes a short - * sequence of instructions/calls, mirroring the VM's stack machine - * (cat/vm.c) exactly, so both engines agree on observable behaviour. + * A program is emitted as two temp files -- `.s` (the function bodies) + * and `_main.c` (which rebuilds the bytecode and boots the VM) -- then + * assembled and linked together. + * + * Only "lowerable" functions become native: generator functions (whose + * `yield` needs coroutine resumption) are left to the interpreter, so the + * prototype simply carries no nat_entry and the VM runs it as usual. */ #include "cat/backend/backend.h" +#include "cat/backend/x86_64.h" #include "cat/bytecode.h" #include "cat/types/number.h" @@ -25,19 +30,470 @@ #include #include -#ifdef __x86_64__ -#define CAT_BACKEND_X86_64_SUPPORTED 1 -#else -#define CAT_BACKEND_X86_64_SUPPORTED 0 -#endif +/* ---- small emission helpers ---- */ + +/* Escape a C string literal body. */ +static void x_escape(FILE *o, const char *s) +{ + const unsigned char *p = (const unsigned char *)s; + + for (; p != NULL && *p != '\0'; p++) { + if (*p == '"' || *p == '\\' || *p < 0x20 || *p >= 0x7f) + fprintf(o, "\\%03o", *p); + else + fputc(*p, o); + } +} + +/* Count functions in a prototype subtree (pre-order numbering). */ +static int x_count(CAT_BYTECODE_Function *fn) +{ + int n = 1, i; + + for (i = 0; i < fn->nprotos; i++) + n += x_count(fn->protos[i]); + return n; +} + +/* A native entry can carry this function only if it never yields. */ +static int x_lowerable(CAT_BYTECODE_Function *fn) +{ + return fn->is_generator == 0; +} + +/* Emit `call sym` with f=rdi, a/b/c in rsi/rdx/rcx. */ +static void x_call(FILE *o, const char *sym, int a, int b, int c) +{ + fprintf(o, "\tmovq %%rbx, %%rdi\n"); + fprintf(o, "\tmovl $%d, %%esi\n", a); + fprintf(o, "\tmovl $%d, %%edx\n", b); + fprintf(o, "\tmovl $%d, %%ecx\n", c); + fprintf(o, "\tcall %s\n", sym); +} + +/* Emit a call followed by the error check. */ +static void x_call_chk(FILE *o, int idx, const char *sym, int a, int b, int c) +{ + x_call(o, sym, a, b, c); + fprintf(o, "\tcmpl $0, %%eax\n\tjl .Lonerror_%d\n", idx); +} + +/* Map an opcode to its helper symbol, or NULL when it is control flow. */ +static const char *x_sym(unsigned char op) +{ + switch (op) { + case CAT_BYTECODE_OP_CONST: return "cat_backend_x86_64_const"; + case CAT_BYTECODE_OP_EMPTY: return "cat_backend_x86_64_empty"; + case CAT_BYTECODE_OP_TRUE: return "cat_backend_x86_64_true"; + case CAT_BYTECODE_OP_FALSE: return "cat_backend_x86_64_false"; + case CAT_BYTECODE_OP_GETLOCAL: return "cat_backend_x86_64_getlocal"; + case CAT_BYTECODE_OP_SETLOCAL: return "cat_backend_x86_64_setlocal"; + case CAT_BYTECODE_OP_GETGLOBAL: return "cat_backend_x86_64_getglobal"; + case CAT_BYTECODE_OP_SETGLOBAL: return "cat_backend_x86_64_setglobal"; + case CAT_BYTECODE_OP_POP: return "cat_backend_x86_64_pop"; + case CAT_BYTECODE_OP_DUP: return "cat_backend_x86_64_dup"; + case CAT_BYTECODE_OP_ADD: case CAT_BYTECODE_OP_SUB: + case CAT_BYTECODE_OP_MUL: case CAT_BYTECODE_OP_DIV: + case CAT_BYTECODE_OP_REM: return "cat_backend_x86_64_arith"; + case CAT_BYTECODE_OP_NEG: return "cat_backend_x86_64_neg"; + case CAT_BYTECODE_OP_NOT: return "cat_backend_x86_64_not"; + case CAT_BYTECODE_OP_EQ: case CAT_BYTECODE_OP_NE: + case CAT_BYTECODE_OP_LT: case CAT_BYTECODE_OP_LE: + case CAT_BYTECODE_OP_GT: case CAT_BYTECODE_OP_GE: + return "cat_backend_x86_64_cmp"; + case CAT_BYTECODE_OP_CONCAT: return "cat_backend_x86_64_concat"; + case CAT_BYTECODE_OP_GETATTR: return "cat_backend_x86_64_getattr"; + case CAT_BYTECODE_OP_SETATTR: return "cat_backend_x86_64_setattr"; + case CAT_BYTECODE_OP_GETIDX: return "cat_backend_x86_64_getidx"; + case CAT_BYTECODE_OP_SETIDX: return "cat_backend_x86_64_setidx"; + case CAT_BYTECODE_OP_NEWTABLE: return "cat_backend_x86_64_newtable"; + case CAT_BYTECODE_OP_CLOSURE: return "cat_backend_x86_64_closure"; + case CAT_BYTECODE_OP_CALL: return "cat_backend_x86_64_call"; + case CAT_BYTECODE_OP_CALLMETHOD: return "cat_backend_x86_64_callmethod"; + case CAT_BYTECODE_OP_PRINT: return "cat_backend_x86_64_print"; + case CAT_BYTECODE_OP_PRINTEXPR: return "cat_backend_x86_64_printexpr"; + case CAT_BYTECODE_OP_IS: return "cat_backend_x86_64_is"; + case CAT_BYTECODE_OP_NEXT: return "cat_backend_x86_64_next"; + case CAT_BYTECODE_OP_TRYEND: return "cat_backend_x86_64_tryend"; + default: return NULL; + } +} + +/* Emit the body of one lowerable function. */ +static void x_emit_fn(FILE *o, CAT_BYTECODE_Function *fn, int idx) +{ + int i; + + fprintf(o, "\t.text\n\t.globl cat_nat_fn_%d\n\t.type cat_nat_fn_%d, @function\n", + idx, idx); + fprintf(o, "cat_nat_fn_%d:\n", idx); + fprintf(o, "\tpushq %%rbx\n\tpushq %%rbp\n\tsubq $8, %%rsp\n"); + fprintf(o, "\tmovq %%rdi, %%rbx\n"); + + for (i = 0; i < fn->ncode; i++) { + CAT_BYTECODE_Instr *in = &fn->code[i]; + const char *sym; + + fprintf(o, ".Lfn%d_ip_%d:\n", idx, i); + switch (in->op) { + case CAT_BYTECODE_OP_NOP: + break; + case CAT_BYTECODE_OP_JUMP: + fprintf(o, "\tjmp .Lfn%d_ip_%d\n", idx, in->a); + break; + case CAT_BYTECODE_OP_JUMPIF: + x_call(o, "cat_backend_x86_64_popcond", 0, 0, 0); + fprintf(o, "\tcmpl $0, %%eax\n\tjl .Lonerror_%d\n", idx); + fprintf(o, "\tjne .Lfn%d_ip_%d\n", idx, in->a); + break; + case CAT_BYTECODE_OP_JUMPIFNOT: + x_call(o, "cat_backend_x86_64_popcond", 0, 0, 0); + fprintf(o, "\tcmpl $0, %%eax\n\tjl .Lonerror_%d\n", idx); + fprintf(o, "\tje .Lfn%d_ip_%d\n", idx, in->a); + break; + case CAT_BYTECODE_OP_FORNEXT: + x_call(o, "cat_backend_x86_64_fornext", 0, 0, 0); + fprintf(o, "\tcmpl $0, %%eax\n\tjl .Lonerror_%d\n", idx); + fprintf(o, "\tjne .Lfn%d_ip_%d\n", idx, in->a); + break; + case CAT_BYTECODE_OP_RETURN: + x_call(o, "cat_backend_x86_64_return", 0, 0, 0); + fprintf(o, "\tjmp .Lret_%d\n", idx); + break; + case CAT_BYTECODE_OP_RETURN0: + x_call(o, "cat_backend_x86_64_empty", 0, 0, 0); + x_call(o, "cat_backend_x86_64_return", 0, 0, 0); + fprintf(o, "\tjmp .Lret_%d\n", idx); + break; + case CAT_BYTECODE_OP_TRYSETUP: + fprintf(o, "\tmovq %%rbx, %%rdi\n"); + fprintf(o, "\tleaq .Lfn%d_ip_%d(%%rip), %%rsi\n", idx, in->a); + fprintf(o, "\txorl %%edx, %%edx\n\txorl %%ecx, %%ecx\n"); + fprintf(o, "\tcall cat_backend_x86_64_trysetup\n"); + break; + case CAT_BYTECODE_OP_RAISE: + x_call(o, "cat_backend_x86_64_raise", 0, 0, 0); + fprintf(o, "\tjmp .Lonerror_%d\n", idx); + break; + case CAT_BYTECODE_OP_ADD: case CAT_BYTECODE_OP_SUB: + case CAT_BYTECODE_OP_MUL: case CAT_BYTECODE_OP_DIV: + case CAT_BYTECODE_OP_REM: + /* pass the opcode itself as operand a */ + x_call_chk(o, idx, "cat_backend_x86_64_arith", + in->op, 0, 0); + break; + case CAT_BYTECODE_OP_EQ: case CAT_BYTECODE_OP_NE: + case CAT_BYTECODE_OP_LT: case CAT_BYTECODE_OP_LE: + case CAT_BYTECODE_OP_GT: case CAT_BYTECODE_OP_GE: + x_call_chk(o, idx, "cat_backend_x86_64_cmp", in->op, 0, 0); + break; + default: + sym = x_sym(in->op); + if (sym != NULL) + x_call_chk(o, idx, sym, in->a, in->b, in->c); + break; + } + } + /* fell off the end: return the empty object */ + x_call(o, "cat_backend_x86_64_empty", 0, 0, 0); + x_call(o, "cat_backend_x86_64_return", 0, 0, 0); + fprintf(o, "\tjmp .Lret_%d\n", idx); + + fprintf(o, ".Lonerror_%d:\n", idx); + fprintf(o, "\tmovq %%rbx, %%rdi\n\tcall cat_backend_x86_64_handle_error\n"); + fprintf(o, "\ttestq %%rax, %%rax\n\tje .Lfail_%d\n\tjmp *%%rax\n", idx); + fprintf(o, ".Lfail_%d:\n\tmovl $-1, %%eax\n", idx); + fprintf(o, ".Lret_%d:\n", idx); + fprintf(o, "\taddq $8, %%rsp\n\tpopq %%rbp\n\tpopq %%rbx\n\tret\n\n"); +} + +/* Emit only the lowerable functions of a tree, in pre-order, so indices + * match the generated `_main.c` (which numbers ALL functions). */ +static void x_emit_tree(FILE *o, CAT_BYTECODE_Function *fn, int *next) +{ + int self = (*next)++; + int i; + + if (x_lowerable(fn)) + x_emit_fn(o, fn, self); + for (i = 0; i < fn->nprotos; i++) + x_emit_tree(o, fn->protos[i], next); +} + +/* Emit the whole assembly translation unit for a program. */ +static void x_emit_prog(FILE *o, CAT_BYTECODE_Function *fn) +{ + int next = 0; + + fprintf(o, "/* generated by catscript -- native x86-64 backend. */\n"); + fprintf(o, "\t.text\n"); + x_emit_tree(o, fn, &next); + fprintf(o, "\t.section .note.GNU-stack,\"\",@progbits\n"); +} + +/* ---- the generated `_main.c`: rebuild bytecode and boot the VM ---- */ + +static void x_const_expr(FILE *o, CAT_VALUE_Value *v) +{ + if (v == NULL) { + fprintf(o, "cat_backend_x86_64_const_empty()"); + return; + } + if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_NUMBER) { + CAT_TYPES_NUMBER_Number *n = (CAT_TYPES_NUMBER_Number *)v; + + if (n->is_float) + fprintf(o, "cat_backend_x86_64_const_float(%.17g)", n->f); + else + fprintf(o, "cat_backend_x86_64_const_int(%lldLL)", n->i); + return; + } + if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_TEXT) { + fprintf(o, "cat_backend_x86_64_const_text(\""); + x_escape(o, cat_types_text_bytes(v)); + fprintf(o, "\")"); + return; + } + if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_BOOL) { + int t = 1; + CAT_ERROR_Error e; + + cat_error_clear(&e); + cat_value_truthy(v, &t, &e); + fprintf(o, "cat_backend_x86_64_const_bool(%d)", t); + return; + } + fprintf(o, "cat_backend_x86_64_const_empty()"); +} + +static void x_main_decls(FILE *o, CAT_BYTECODE_Function *fn, int *next) +{ + int self = (*next)++; + int i; + + fprintf(o, "static CAT_BYTECODE_Function *cat_nat_proto_%d(void);\n", self); + fprintf(o, "extern int cat_nat_fn_%d(void);\n", self); + for (i = 0; i < fn->nprotos; i++) + x_main_decls(o, fn->protos[i], next); +} + +static void x_main_defs(FILE *o, CAT_BYTECODE_Function *fn, int *next) +{ + int self = (*next)++; + int child, i; + + fprintf(o, "static CAT_BYTECODE_Function *cat_nat_proto_%d(void)\n{\n", + self); + fprintf(o, "\tCAT_BYTECODE_Function *fn = cat_backend_x86_64_fn_new(\""); + x_escape(o, fn->name ? fn->name : ""); + fprintf(o, "\");\n"); + fprintf(o, "\tcat_backend_x86_64_fn_setup(fn, %d, %d, %d);\n", + fn->nparams, fn->nlocals, fn->is_generator); + for (i = 0; i < fn->nconsts; i++) { + fprintf(o, "\tcat_backend_x86_64_fn_add_const(fn, "); + x_const_expr(o, fn->consts[i].value); + fprintf(o, ");\n"); + } + child = self + 1; + for (i = 0; i < fn->nprotos; i++) { + fprintf(o, "\tcat_backend_x86_64_fn_add_proto(fn, cat_nat_proto_%d());\n", + child); + child += x_count(fn->protos[i]); + } + /* Rebuild the instruction array: functions the native code does not + * run (generators) are executed by the interpreter and need it. */ + for (i = 0; i < fn->ncode; i++) { + CAT_BYTECODE_Instr *in = &fn->code[i]; + + fprintf(o, "\tcat_backend_x86_64_fn_emit(fn, %d, %d, %d, %d, %d);\n", + in->op, in->a, in->b, in->c, in->line); + } + if (x_lowerable(fn)) + fprintf(o, "\tcat_backend_x86_64_fn_set_entry(fn, (void *)cat_nat_fn_%d);\n", + self); + fprintf(o, "\treturn fn;\n}\n\n"); + for (i = 0; i < fn->nprotos; i++) + x_main_defs(o, fn->protos[i], next); +} + +static void x_emit_main_c(FILE *o, CAT_BYTECODE_Function *fn, + const char *module_name, const char *module_path) +{ + int next = 0; + + fprintf(o, "/* generated by catscript -- native x86-64 backend (boot). */\n"); + fprintf(o, "#include \"cat/vm.h\"\n#include \"cat/bytecode.h\"\n"); + fprintf(o, "#include \"cat/module.h\"\n#include \"cat/error.h\"\n"); + fprintf(o, "#include \"cat/stdlib/stdlib.h\"\n"); + fprintf(o, "#include \"cat/stdlib/build.h\"\n"); + fprintf(o, "#include \"cat/backend/x86_64.h\"\n#include \n\n"); + next = 0; + x_main_decls(o, fn, &next); + fprintf(o, "\n"); + next = 0; + x_main_defs(o, fn, &next); + fprintf(o, "int main(void)\n{\n"); + fprintf(o, "\tCAT_VM_State *vm;\n\tCAT_BYTECODE_Function *top;\n"); + fprintf(o, "\tCAT_VALUE_Value *out = NULL;\n\tint rc;\n\n"); + fprintf(o, "\tvm = cat_vm_new();\n\tif (vm == NULL)\n\t\treturn 1;\n"); + fprintf(o, "\tcat_stdlib_stdlib_install(vm);\n\tcat_stdlib_build_install(vm);\n"); + fprintf(o, "\tcat_module_enter(vm, \""); + x_escape(o, module_name ? module_name : ""); + fprintf(o, "\", "); + if (module_path != NULL) { + fprintf(o, "\""); + x_escape(o, module_path); + fprintf(o, "\""); + } else { + fprintf(o, "NULL"); + } + fprintf(o, ");\n\n"); + fprintf(o, "\ttop = cat_nat_proto_0();\n"); + fprintf(o, "\trc = cat_vm_run(vm, top, &out);\n"); + fprintf(o, "\tif (rc != 0)\n\t\tfprintf(stderr, \"catscript: %%s\\n\", vm->err.message);\n"); + fprintf(o, "\tcat_bytecode_function_free(top);\n\tcat_vm_free(vm);\n"); + fprintf(o, "\treturn rc != 0;\n}\n"); +} + +/* Directory of the running executable, or NULL. */ +static char *x_exe_dir(void) +{ + char buf[4096]; + ssize_t n; + char *slash; + + n = readlink("/proc/self/exe", buf, sizeof(buf) - 1); + if (n <= 0) + return NULL; + buf[n] = '\0'; + slash = strrchr(buf, '/'); + if (slash == NULL) + return NULL; + *slash = '\0'; + return strdup(buf); +} + +int x86_64_emit_public(CAT_BYTECODE_Function *fn, const char *module_name, + const char *module_path, FILE *out) +{ + (void)module_name; + (void)module_path; + x_emit_prog(out, fn); + return 0; +} -/* An unresolved reference to the still-under-construction lowering. */ static int x86_64_emit(CAT_BYTECODE_Function *fn, const char *module_name, - const char *module_path, FILE *out); + const char *module_path, FILE *out) +{ + (void)module_name; + (void)module_path; + x_emit_prog(out, fn); + return 0; +} -static int x86_64_compile(CAT_BYTECODE_Function *fn, const char *module_name, - const char *module_path, const char *outpath, - char *errbuf, size_t errsz); +int x86_64_compile(CAT_BYTECODE_Function *fn, const char *module_name, + const char *module_path, const char *outpath, + char *errbuf, size_t errsz) +{ + char stmpl[] = "/tmp/cat-nat-XXXXXX.s"; + char ctmpl[] = "/tmp/cat-nat-XXXXXX.c"; + char otmpl[] = "/tmp/cat-nat-XXXXXX.o"; + char cmd[16384], inc[4096], lib[4096]; + char *dir; + FILE *f; + int sfd, cfd, ofd, st; + + if (errbuf != NULL && errsz > 0) + errbuf[0] = '\0'; + if (fn == NULL) { + if (errbuf != NULL) + snprintf(errbuf, errsz, "no program to compile"); + return -1; + } + sfd = mkstemps(stmpl, 2); + if (sfd < 0) + return -1; + f = fdopen(sfd, "w"); + if (f == NULL) { + close(sfd); + return -1; + } + x_emit_prog(f, fn); + fclose(f); + + cfd = mkstemps(ctmpl, 2); + if (cfd < 0) { + unlink(stmpl); + return -1; + } + f = fdopen(cfd, "w"); + if (f == NULL) { + close(cfd); + unlink(stmpl); + return -1; + } + x_emit_main_c(f, fn, module_name, module_path); + fclose(f); + + ofd = mkstemps(otmpl, 2); + if (ofd >= 0) + close(ofd); + + dir = x_exe_dir(); + if (dir == NULL) { + unlink(stmpl); + unlink(ctmpl); + unlink(otmpl); + if (errbuf != NULL) + snprintf(errbuf, errsz, "cannot locate the catscript runtime"); + return -1; + } + snprintf(inc, sizeof(inc), "%s/../../include", dir); + snprintf(lib, sizeof(lib), "%s/libcatscript.a", dir); + if (access(lib, R_OK) != 0) { + unlink(stmpl); + unlink(ctmpl); + unlink(otmpl); + free(dir); + if (errbuf != NULL) + snprintf(errbuf, errsz, "runtime archive missing at %s", lib); + return -1; + } + + /* assemble the generated .s */ + snprintf(cmd, sizeof(cmd), + "cc -std=c11 -D_DEFAULT_SOURCE -I'%s' -c '%s' -o '%s' 2>&1", + inc, stmpl, otmpl); + st = system(cmd); + if (st != 0) { + unlink(stmpl); + unlink(ctmpl); + unlink(otmpl); + free(dir); + if (errbuf != NULL) + snprintf(errbuf, errsz, + "assembler failed (status %d)", st); + return -1; + } + + /* link: object + boot C + runtime archive */ + snprintf(cmd, sizeof(cmd), + "cc -std=c11 -O2 -D_DEFAULT_SOURCE -I'%s' -o '%s' '%s' '%s' " + "'%s' -lm -lffi -ldl 2>&1", + inc, outpath, otmpl, ctmpl, lib); + st = system(cmd); + unlink(stmpl); + unlink(ctmpl); + unlink(otmpl); + free(dir); + if (st != 0) { + if (errbuf != NULL) + snprintf(errbuf, errsz, + "C linker failed (status %d)", st); + return -1; + } + return 0; +} const CAT_BACKEND_Backend *cat_backend_x86_64_backend(void) { @@ -51,26 +507,3 @@ const CAT_BACKEND_Backend *cat_backend_x86_64_backend(void) return &b; } - -static int x86_64_emit(CAT_BYTECODE_Function *fn, const char *module_name, - const char *module_path, FILE *out) -{ - (void)fn; - (void)module_name; - (void)module_path; - fprintf(out, "# x86_64 backend: lowering not yet implemented\n"); - return 0; -} - -static int x86_64_compile(CAT_BYTECODE_Function *fn, const char *module_name, - const char *module_path, const char *outpath, - char *errbuf, size_t errsz) -{ - (void)fn; - (void)module_name; - (void)module_path; - (void)outpath; - if (errbuf != NULL && errsz > 0) - snprintf(errbuf, errsz, "x86_64 backend not implemented yet"); - return -1; -} diff --git a/src/cat/backend/x86_64_glue.c b/src/cat/backend/x86_64_glue.c new file mode 100644 index 0000000..bacdf9d --- /dev/null +++ b/src/cat/backend/x86_64_glue.c @@ -0,0 +1,569 @@ +/* + * cat/backend/x86_64_glue.c -- runtime glue for the native backend. + * + * Naming rule: cat_backend_x86_64_* / CAT_BACKEND_X86_64_*. + * + * The generated assembly calls one helper here per opcode. The helpers + * mirror cat/vm.c's interpreter exactly, so both engines agree on + * observable behaviour. Part 1: frame lifecycle, constants, operands. + */ +#include "cat/backend/x86_64.h" +#include "cat/vm.h" +#include "cat/error.h" +#include "cat/types/empty.h" +#include "cat/types/bool.h" +#include "cat/types/int.h" +#include "cat/types/float.h" +#include "cat/types/text.h" +#include "cat/types/ascii_text.h" +#include "cat/types/table.h" +#include "cat/types/function.h" + +#include +#include +#include + +static int xdeliver(CAT_VM_State *vm, const CAT_ERROR_Error *from) +{ + if (from->raised) { + cat_error_clear(&vm->err); + cat_error_raise(&vm->err, "%s", from->message); + vm->err.value = from->value; + return -1; + } + return 0; +} + +void cat_backend_x86_64_frame_init(CAT_BACKEND_X86_64_Frame *f, + CAT_VM_State *vm, + CAT_TYPES_FUNCTION_Closure *cl, + CAT_VALUE_Value **args, long nargs) +{ + CAT_BYTECODE_Function *fn = cl ? cl->proto : NULL; + int i; + + memset(f, 0, sizeof(*f)); + f->vm = vm; + f->fn = fn; + f->stack = calloc((size_t)((fn ? fn->ncode : 0) + 64), + sizeof(*f->stack)); + for (i = 0; i < 256; i++) + f->locals[i] = NULL; + if (fn != NULL) + for (i = 0; i < nargs && i < fn->nparams && i < 256; i++) + f->locals[i] = args ? args[i] : NULL; +} + +void cat_backend_x86_64_frame_done(CAT_BACKEND_X86_64_Frame *f) +{ + free(f->stack); + f->stack = NULL; +} + +void *cat_backend_x86_64_handle_error(CAT_BACKEND_X86_64_Frame *f) +{ + if (f->nhandlers > 0) { + CAT_BACKEND_X86_64_Handler *h = &f->handlers[--f->nhandlers]; + + f->sp = h->sp; + if (f->vm->err.value != NULL) + f->stack[f->sp++] = f->vm->err.value; + else + f->stack[f->sp++] = + cat_types_ascii_text_new(f->vm->err.message); + cat_error_clear(&f->vm->err); + return h->target; + } + return NULL; +} + +CAT_VALUE_Value *cat_backend_x86_64_const_int(long long v) +{ + return cat_types_int_new(v); +} + +CAT_VALUE_Value *cat_backend_x86_64_const_float(double v) +{ + return cat_types_float_new(v); +} + +CAT_VALUE_Value *cat_backend_x86_64_const_text(const char *s) +{ + return cat_types_ascii_text_new(s); +} + +CAT_VALUE_Value *cat_backend_x86_64_const_bool(long t) +{ + return t ? cat_types_bool_true() : cat_types_bool_false(); +} + +CAT_VALUE_Value *cat_backend_x86_64_const_empty(void) +{ + return cat_types_empty(); +} + +int cat_backend_x86_64_const(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *v = f->fn->consts[a].value; + (void)b; (void)c; + f->stack[f->sp++] = v; + return 0; +} + +int cat_backend_x86_64_empty(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)a; (void)b; (void)c; + f->stack[f->sp++] = cat_types_empty(); + return 0; +} + +int cat_backend_x86_64_true(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)a; (void)b; (void)c; + f->stack[f->sp++] = cat_types_bool_true(); + return 0; +} + +int cat_backend_x86_64_false(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)a; (void)b; (void)c; + f->stack[f->sp++] = cat_types_bool_false(); + return 0; +} + +int cat_backend_x86_64_getlocal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)b; (void)c; + f->stack[f->sp++] = f->locals[a] ? f->locals[a] : cat_types_empty(); + return 0; +} + +int cat_backend_x86_64_setlocal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)b; (void)c; + f->locals[a] = f->stack[--f->sp]; + return 0; +} + +int cat_backend_x86_64_getglobal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *g; + (void)b; (void)c; + g = cat_vm_get_global(f->vm, + cat_types_text_bytes(f->fn->consts[a].value)); + if (g == NULL) { + cat_error_clear(&f->vm->err); + cat_error_raise(&f->vm->err, "global '%s' is not defined", + cat_types_text_bytes(f->fn->consts[a].value)); + return -1; + } + f->stack[f->sp++] = g; + return 0; +} + +int cat_backend_x86_64_setglobal(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)b; (void)c; + cat_vm_set_global(f->vm, cat_types_text_bytes(f->fn->consts[a].value), + f->stack[--f->sp]); + return 0; +} + +int cat_backend_x86_64_pop(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)a; (void)b; (void)c; + f->sp--; + return 0; +} + +int cat_backend_x86_64_dup(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)a; (void)b; (void)c; + f->stack[f->sp] = f->stack[f->sp - 1]; + f->sp++; + return 0; +} + +int cat_backend_x86_64_newtable(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)a; (void)b; (void)c; + f->stack[f->sp++] = cat_types_table_new(); + return 0; +} + +int cat_backend_x86_64_closure(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)b; (void)c; + f->stack[f->sp++] = cat_types_function_new(f->fn->protos[a]); + return 0; +} + +int cat_backend_x86_64_arith(CAT_BACKEND_X86_64_Frame *f, long op, long b, long c) +{ + CAT_VALUE_Value *y = f->stack[--f->sp]; + CAT_VALUE_Value *x = f->stack[--f->sp]; + CAT_VALUE_Value *r = NULL; + CAT_ERROR_Error e; + int st; + (void)b; (void)c; + cat_error_clear(&e); + switch (op) { + case CAT_BYTECODE_OP_ADD: st = cat_value_add(x, y, &r, &e); break; + case CAT_BYTECODE_OP_SUB: st = cat_value_sub(x, y, &r, &e); break; + case CAT_BYTECODE_OP_MUL: st = cat_value_mul(x, y, &r, &e); break; + case CAT_BYTECODE_OP_DIV: st = cat_value_div(x, y, &r, &e); break; + default: st = cat_value_rem(x, y, &r, &e); break; + } + if (st != 0) + return xdeliver(f->vm, &e); + f->stack[f->sp++] = r ? r : cat_types_empty(); + return 0; +} + +int cat_backend_x86_64_neg(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *x = f->stack[--f->sp]; + CAT_VALUE_Value *zero = cat_types_int_new(0); + CAT_VALUE_Value *r = NULL; + CAT_ERROR_Error e; + (void)a; (void)b; (void)c; + cat_error_clear(&e); + if (cat_value_sub(zero, x, &r, &e) != 0) + return xdeliver(f->vm, &e); + f->stack[f->sp++] = r ? r : cat_types_empty(); + return 0; +} + +int cat_backend_x86_64_not(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *x = f->stack[--f->sp]; + CAT_ERROR_Error e; + int t = 1; + (void)a; (void)b; (void)c; + cat_error_clear(&e); + cat_value_truthy(x, &t, &e); + f->stack[f->sp++] = t ? cat_types_bool_false() : cat_types_bool_true(); + return 0; +} + +int cat_backend_x86_64_cmp(CAT_BACKEND_X86_64_Frame *f, long op, long b, long c) +{ + CAT_VALUE_Value *y = f->stack[--f->sp]; + CAT_VALUE_Value *x = f->stack[--f->sp]; + int c2 = 0, eq = 0, has = 0; + int res; + (void)b; (void)c; + if (x == NULL) x = cat_types_empty(); + if (y == NULL) y = cat_types_empty(); + if (x == y) { + eq = 1; has = 1; c2 = 0; + } else if (x->vtable && y->vtable && + x->vtable->kind == CAT_VALUE_KIND_TEXT && + y->vtable->kind == CAT_VALUE_KIND_TEXT) { + c2 = strcmp(cat_types_text_bytes(x), cat_types_text_bytes(y)); + eq = (c2 == 0); has = 1; + } else if (x->vtable && y->vtable && + x->vtable->kind == CAT_VALUE_KIND_NUMBER && + y->vtable->kind == CAT_VALUE_KIND_NUMBER) { + double xv = cat_types_number_as_double(x); + double yv = cat_types_number_as_double(y); + c2 = (xv < yv) ? -1 : (xv > yv) ? 1 : 0; + eq = (c2 == 0); has = 1; + } + res = 0; + switch (op) { + case CAT_BYTECODE_OP_EQ: res = eq; break; + case CAT_BYTECODE_OP_NE: res = !eq; break; + case CAT_BYTECODE_OP_LT: res = has && (c2 < 0); break; + case CAT_BYTECODE_OP_LE: res = has && (c2 <= 0); break; + case CAT_BYTECODE_OP_GT: res = has && (c2 > 0); break; + default: res = has && (c2 >= 0); break; + } + f->stack[f->sp++] = res ? cat_types_bool_true() : cat_types_bool_false(); + return 0; +} + +int cat_backend_x86_64_concat(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *y = f->stack[--f->sp]; + CAT_VALUE_Value *x = f->stack[--f->sp]; + CAT_VALUE_Value *r = NULL; + CAT_ERROR_Error e; + (void)a; (void)b; (void)c; + cat_error_clear(&e); + if (cat_types_text_concat(x, y, &r, &e) != 0) + return xdeliver(f->vm, &e); + f->stack[f->sp++] = r ? r : cat_types_empty(); + return 0; +} + +int cat_backend_x86_64_getattr(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *obj = f->stack[--f->sp]; + CAT_VALUE_Value *r = NULL; + CAT_ERROR_Error e; + (void)b; (void)c; + cat_error_clear(&e); + if (cat_value_get_attribute(obj, cat_types_text_bytes(f->fn->consts[a].value), + &r, &e) != 0) + return xdeliver(f->vm, &e); + f->stack[f->sp++] = r ? r : cat_types_empty(); + return 0; +} + +int cat_backend_x86_64_setattr(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *val = f->stack[--f->sp]; + CAT_VALUE_Value *obj = f->stack[--f->sp]; + CAT_ERROR_Error e; + (void)b; (void)c; + cat_error_clear(&e); + if (cat_value_set_attribute(obj, cat_types_text_bytes(f->fn->consts[a].value), + val, &e) != 0) + return xdeliver(f->vm, &e); + return 0; +} + +static void xkey(CAT_VALUE_Value *idx, char *buf, size_t n) +{ + if (idx->vtable && idx->vtable->kind == CAT_VALUE_KIND_NUMBER) + snprintf(buf, n, "%lld", cat_types_number_as_int(idx)); + else + snprintf(buf, n, "%s", cat_types_text_bytes(idx)); +} + +int cat_backend_x86_64_getidx(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *idx = f->stack[--f->sp]; + CAT_VALUE_Value *obj = f->stack[--f->sp]; + CAT_VALUE_Value *r = NULL; + CAT_ERROR_Error e; + char key[64]; + (void)a; (void)b; (void)c; + cat_error_clear(&e); + xkey(idx, key, sizeof(key)); + if (cat_value_get_attribute(obj, key, &r, &e) != 0) + return xdeliver(f->vm, &e); + f->stack[f->sp++] = r ? r : cat_types_empty(); + return 0; +} + +int cat_backend_x86_64_setidx(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *val = f->stack[--f->sp]; + CAT_VALUE_Value *idx = f->stack[--f->sp]; + CAT_VALUE_Value *obj = f->stack[--f->sp]; + CAT_ERROR_Error e; + char key[64]; + (void)a; (void)b; (void)c; + cat_error_clear(&e); + xkey(idx, key, sizeof(key)); + if (cat_value_set_attribute(obj, key, val, &e) != 0) + return xdeliver(f->vm, &e); + return 0; +} + +int cat_backend_x86_64_call(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + int n = (int)a; + CAT_VALUE_Value *fnv = f->stack[f->sp - n - 1]; + CAT_VALUE_Value *r = NULL; + CAT_ERROR_Error e; + (void)b; (void)c; + cat_error_clear(&e); + if (cat_vm_call_value(f->vm, fnv, &f->stack[f->sp - n], n, &r, &e) != 0) + return xdeliver(f->vm, &e); + f->sp -= n + 1; + f->stack[f->sp++] = r ? r : cat_types_empty(); + return 0; +} + +int cat_backend_x86_64_callmethod(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + int n = (int)a; + CAT_VALUE_Value *obj = f->stack[f->sp - n - 1]; + CAT_VALUE_Value *method = NULL; + CAT_VALUE_Value *callargs[257]; + CAT_VALUE_Value *r = NULL; + CAT_ERROR_Error e; + int j, st; + (void)c; + cat_error_clear(&e); + if (cat_value_get_attribute(obj, cat_types_text_bytes(f->fn->consts[b].value), + &method, &e) != 0) + return xdeliver(f->vm, &e); + callargs[0] = obj; + for (j = 0; j < n && j < 256; j++) + callargs[j + 1] = f->stack[f->sp - n + j]; + st = cat_vm_call_value(f->vm, method, callargs, n + 1, &r, &e); + if (st != 0) + return xdeliver(f->vm, &e); + f->sp -= n + 1; + f->stack[f->sp++] = r ? r : cat_types_empty(); + return 0; +} + +int cat_backend_x86_64_print(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)a; (void)b; (void)c; + cat_vm_print_value(f->stack[--f->sp]); + return 0; +} + +int cat_backend_x86_64_printexpr(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *v = f->stack[--f->sp]; + (void)a; (void)b; (void)c; + if (v == NULL || cat_types_empty_is(v)) + return 0; + printf("%s\n", cat_types_text_bytes(cat_value_repr(v))); + return 0; +} + +int cat_backend_x86_64_is(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *iface = f->stack[--f->sp]; + CAT_VALUE_Value *obj = f->stack[--f->sp]; + int r = 0; + CAT_ERROR_Error e; + (void)a; (void)b; (void)c; + cat_error_clear(&e); + if (cat_value_is(obj, iface, &r, &e) != 0) + return xdeliver(f->vm, &e); + f->stack[f->sp++] = r ? cat_types_bool_true() : cat_types_bool_false(); + return 0; +} + +int cat_backend_x86_64_next(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *it = f->stack[--f->sp]; + CAT_VALUE_Value *r = NULL; + CAT_ERROR_Error e; + int nr; + (void)a; (void)b; (void)c; + cat_error_clear(&e); + nr = cat_value_next(it, &r, &e); + if (nr < 0) + return xdeliver(f->vm, &e); + f->stack[f->sp++] = (nr == 0 && r) ? r : cat_types_empty(); + return 0; +} + +int cat_backend_x86_64_popcond(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *cond = f->stack[--f->sp]; + CAT_ERROR_Error e; + int t = 1; + (void)a; (void)b; (void)c; + cat_error_clear(&e); + cat_value_truthy(cond, &t, &e); + return t ? 1 : 0; +} + +int cat_backend_x86_64_fornext(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *it = f->stack[--f->sp]; + CAT_VALUE_Value *r = NULL; + CAT_ERROR_Error e; + int nr; + (void)a; (void)b; (void)c; + cat_error_clear(&e); + nr = cat_value_next(it, &r, &e); + if (nr < 0) + return xdeliver(f->vm, &e); + if (nr == 1) + return 1; + f->stack[f->sp++] = r ? r : cat_types_empty(); + return 0; +} + +int cat_backend_x86_64_return(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)a; (void)b; (void)c; + f->ret = f->stack[--f->sp]; + return 0; +} + +int cat_backend_x86_64_trysetup(CAT_BACKEND_X86_64_Frame *f, long target, long b, long c) +{ + (void)b; (void)c; + if (f->nhandlers < CAT_VM_MAXHANDLER) { + f->handlers[f->nhandlers].target = (void *)target; + f->handlers[f->nhandlers].sp = f->sp; + f->nhandlers++; + } + return 0; +} + +int cat_backend_x86_64_tryend(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + (void)a; (void)b; (void)c; + if (f->nhandlers > 0) + f->nhandlers--; + return 0; +} + +int cat_backend_x86_64_raise(CAT_BACKEND_X86_64_Frame *f, long a, long b, long c) +{ + CAT_VALUE_Value *v = f->stack[--f->sp]; + const char *msg = (v && v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT) + ? cat_types_text_bytes(v) : "raised"; + (void)a; (void)b; (void)c; + cat_error_raise_value(&f->vm->err, v, "%s", msg); + return -1; +} + +int cat_backend_x86_64_top_call(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl, + CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) +{ + CAT_BACKEND_X86_64_Frame f; + CAT_BACKEND_X86_64_Entry entry = (CAT_BACKEND_X86_64_Entry)cl->proto->nat_entry; + CAT_VM_State *prev = cat_vm_current(); + int rc; + + cat_backend_x86_64_frame_init(&f, vm, cl, args, nargs); + cat_vm_set_current(vm); + rc = entry(&f); + cat_vm_set_current(prev); + *out = rc == 0 ? (f.ret ? f.ret : cat_types_empty()) + : cat_types_empty(); + cat_backend_x86_64_frame_done(&f); + return rc; +} + +/* ---- bytecode rebuild helpers for generated `main` ---- */ + +CAT_BYTECODE_Function *cat_backend_x86_64_fn_new(const char *name) +{ + return cat_bytecode_function_new(name); +} + +void cat_backend_x86_64_fn_setup(CAT_BYTECODE_Function *fn, long nparams, + long nlocals, long is_generator) +{ + fn->nparams = (int)nparams; + fn->nlocals = (int)nlocals; + fn->is_generator = (int)is_generator; +} + +void cat_backend_x86_64_fn_add_const(CAT_BYTECODE_Function *fn, CAT_VALUE_Value *v) +{ + cat_bytecode_add_const(fn, v); +} + +void cat_backend_x86_64_fn_emit(CAT_BYTECODE_Function *fn, long op, long a, + long b, long c, long line) +{ + cat_bytecode_emit(fn, (unsigned char)op, (int)a, (int)b, (int)c, + (int)line); +} + +void cat_backend_x86_64_fn_add_proto(CAT_BYTECODE_Function *fn, CAT_BYTECODE_Function *p) +{ + cat_bytecode_add_proto(fn, p); +} + +void cat_backend_x86_64_fn_set_entry(CAT_BYTECODE_Function *fn, void *entry) +{ + fn->nat_entry = entry; +} diff --git a/src/cat/vm.c b/src/cat/vm.c index 41a084f..37494fd 100644 --- a/src/cat/vm.c +++ b/src/cat/vm.c @@ -24,6 +24,7 @@ #include "cat/types/function.h" #include "cat/types/native.h" #include "cat/types/generator.h" +#include "cat/backend/x86_64.h" #include #include @@ -39,6 +40,11 @@ CAT_VM_State *cat_vm_current(void) return g_current_vm; } +void cat_vm_set_current(CAT_VM_State *vm) +{ + g_current_vm = vm; +} + CAT_VM_State *cat_vm_new(void) { CAT_VM_State *vm = calloc(1, sizeof(*vm)); @@ -107,11 +113,11 @@ static int deliver_error(CAT_VM_State *vm, const CAT_ERROR_Error *from) /* Call any callable value: native, closure, or generator factory. A * closure whose prototype contains `yield` is not executed here; it * produces a generator (lazy). */ -static int call_value(CAT_VM_State *vm, CAT_VALUE_Value *fnv, +int cat_vm_call_value(CAT_VM_State *vm, CAT_VALUE_Value *fnv, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out, CAT_ERROR_Error *err); -static void print_value(CAT_VALUE_Value *v) +void cat_vm_print_value(CAT_VALUE_Value *v) { if (v == NULL) printf("empty\n"); @@ -351,7 +357,7 @@ int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out) CAT_VALUE_Value *fnv = stack[sp - n - 1]; CAT_VALUE_Value *r = NULL; int st; - st = call_value(vm, fnv, &stack[sp - n], n, &r, &e); + st = cat_vm_call_value(vm, fnv, &stack[sp - n], n, &r, &e); if (st != 0) { deliver_error(vm, &e); goto on_error; } sp -= n + 1; stack[sp++] = r ? r : cat_types_empty(); @@ -373,7 +379,7 @@ int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out) callargs[j + 1] = stack[sp - n + j]; { CAT_VALUE_Value *r = NULL; - int st = call_value(vm, method, callargs, n + 1, &r, &e); + int st = cat_vm_call_value(vm, method, callargs, n + 1, &r, &e); if (st != 0) { deliver_error(vm, &e); goto on_error; } sp -= n + 1; stack[sp++] = r ? r : cat_types_empty(); @@ -478,7 +484,7 @@ int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out) } case CAT_BYTECODE_OP_PRINT: { CAT_VALUE_Value *v = stack[--sp]; - print_value(v); + cat_vm_print_value(v); break; } case CAT_BYTECODE_OP_PRINTEXPR: { @@ -560,6 +566,11 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl, *out = cat_types_generator_new(vm, cl, args, nargs); return 0; } +#ifdef __x86_64__ + /* A prototype lowered by the native backend runs as machine code. */ + if (cl->proto != NULL && cl->proto->nat_entry != NULL) + return cat_backend_x86_64_top_call(vm, cl, args, nargs, out); +#endif memset(&f, 0, sizeof(f)); f.fn = cl->proto; f.cl = cl; @@ -582,7 +593,7 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl, return 0; } -static int call_value(CAT_VM_State *vm, CAT_VALUE_Value *fnv, +int cat_vm_call_value(CAT_VM_State *vm, CAT_VALUE_Value *fnv, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out, CAT_ERROR_Error *err) { diff --git a/tests/run_tests.sh b/tests/run_tests.sh index f0f5935..ba1e79c 100644 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -327,6 +327,36 @@ case "$out" in *) check "selfhost-compile-2" "sum = 42" "missing" ;; esac +# the native x86_64 backend must AGREE with the interpreter +cat > /tmp/cat_nat_eq.cat <<'EOCAT' +local i = 0 +local acc = 0 +while i < 5 do + acc = acc + i * 2 + i = i + 1 +end +print("acc", acc) +print("cmp", 3 < 4, "a" == "a") +local t = {} +t.x = 7 +t["y"] = 8 +print("t", t.x + t.y) +print("hi " .. "there") +EOCAT +want=`$BIN /tmp/cat_nat_eq.cat 2>&1` +if $BIN --backend x86_64 --build /tmp/cat_nat_eq.cat /tmp/cat_nat_eq_bin >/dev/null 2>&1 && [ -x /tmp/cat_nat_eq_bin ] +then + got=`/tmp/cat_nat_eq_bin 2>&1` + if [ "$got" = "$want" ]; then + check "nat-x86_64-eq" "match" "match" + else + check "nat-x86_64-eq" "match" "differs" + fi +else + check "nat-x86_64-eq" "skip" "skip" +fi +rm -f /tmp/cat_nat_eq.cat /tmp/cat_nat_eq_bin + echo "" echo "$pass passed, $fail failed" [ "$fail" -eq 0 ]