perf
This commit is contained in:
197
src/codegen.zig
197
src/codegen.zig
@@ -104,6 +104,12 @@ pub const CodeGen = struct {
|
||||
module: c.LLVMModuleRef,
|
||||
builder: c.LLVMBuilderRef,
|
||||
allocator: std.mem.Allocator,
|
||||
// ORC ThreadSafeContext — wraps the LLVMContext for JIT compatibility
|
||||
ts_context: c.LLVMOrcThreadSafeContextRef = null,
|
||||
// Whether we still own the module (false after JIT takes ownership)
|
||||
module_owned: bool = true,
|
||||
// Cached target machine (created in init, reused by emitToFile)
|
||||
target_machine: c.LLVMTargetMachineRef = null,
|
||||
|
||||
// Symbol table: maps variable names to their alloca pointers
|
||||
named_values: std.StringHashMap(NamedValue),
|
||||
@@ -188,6 +194,16 @@ pub const CodeGen = struct {
|
||||
function_return_types: std.StringHashMap(Type),
|
||||
// Target configuration (triple, cpu, opt level, lib paths, linker)
|
||||
target_config: TargetConfig = .{},
|
||||
// Cached primitive LLVM types (initialized once in init(), avoids repeated FFI calls)
|
||||
cached_i1: c.LLVMTypeRef = null,
|
||||
cached_i8: c.LLVMTypeRef = null,
|
||||
cached_i16: c.LLVMTypeRef = null,
|
||||
cached_i32: c.LLVMTypeRef = null,
|
||||
cached_i64: c.LLVMTypeRef = null,
|
||||
cached_f32: c.LLVMTypeRef = null,
|
||||
cached_f64: c.LLVMTypeRef = null,
|
||||
cached_ptr: c.LLVMTypeRef = null,
|
||||
cached_void: c.LLVMTypeRef = null,
|
||||
|
||||
const DeferredFn = struct {
|
||||
fd: ast.FnDecl,
|
||||
@@ -311,12 +327,18 @@ pub const CodeGen = struct {
|
||||
};
|
||||
|
||||
pub fn init(allocator: std.mem.Allocator, module_name: [*:0]const u8, target_config: TargetConfig) CodeGen {
|
||||
const ctx = c.LLVMContextCreate();
|
||||
// Create context via ORC ThreadSafeContext for JIT compatibility
|
||||
const ts_ctx = c.LLVMOrcCreateNewThreadSafeContext();
|
||||
const ctx = c.LLVMOrcThreadSafeContextGetContext(ts_ctx);
|
||||
const module = c.LLVMModuleCreateWithNameInContext(module_name, ctx);
|
||||
const builder = c.LLVMCreateBuilderInContext(ctx);
|
||||
|
||||
// Initialize LLVM targets and set data layout early so alignment queries work
|
||||
llvm.initAllTargets();
|
||||
// Initialize LLVM targets — native-only when targeting host, all for cross-compilation
|
||||
if (target_config.triple == null) {
|
||||
llvm.initNativeTarget();
|
||||
} else {
|
||||
llvm.initAllTargets();
|
||||
}
|
||||
|
||||
const triple_owned = target_config.triple == null;
|
||||
const triple = target_config.triple orelse c.LLVMGetDefaultTargetTriple();
|
||||
@@ -326,8 +348,9 @@ pub const CodeGen = struct {
|
||||
|
||||
var target: c.LLVMTargetRef = null;
|
||||
var err_msg: [*c]u8 = null;
|
||||
var tm: c.LLVMTargetMachineRef = null;
|
||||
if (c.LLVMGetTargetFromTriple(triple, &target, &err_msg) == 0) {
|
||||
const tm = c.LLVMCreateTargetMachine(
|
||||
tm = c.LLVMCreateTargetMachine(
|
||||
target,
|
||||
triple,
|
||||
target_config.getCpu(),
|
||||
@@ -339,7 +362,6 @@ pub const CodeGen = struct {
|
||||
const dl = c.LLVMCreateTargetDataLayout(tm);
|
||||
c.LLVMSetModuleDataLayout(module, dl);
|
||||
c.LLVMDisposeTargetData(dl);
|
||||
c.LLVMDisposeTargetMachine(tm);
|
||||
} else {
|
||||
if (err_msg != null) c.LLVMDisposeMessage(err_msg);
|
||||
}
|
||||
@@ -348,6 +370,8 @@ pub const CodeGen = struct {
|
||||
.module = module,
|
||||
.builder = builder,
|
||||
.allocator = allocator,
|
||||
.ts_context = ts_ctx,
|
||||
.target_machine = tm,
|
||||
.named_values = std.StringHashMap(NamedValue).init(allocator),
|
||||
.type_registry = std.StringHashMap(TypeRegistryEntry).init(allocator),
|
||||
.flags_enum_types = std.StringHashMap(void).init(allocator),
|
||||
@@ -375,6 +399,15 @@ pub const CodeGen = struct {
|
||||
.global_mutable_vars = std.StringHashMap(NamedValue).init(allocator),
|
||||
.function_return_types = std.StringHashMap(Type).init(allocator),
|
||||
.target_config = target_config,
|
||||
.cached_i1 = c.LLVMInt1TypeInContext(ctx),
|
||||
.cached_i8 = c.LLVMInt8TypeInContext(ctx),
|
||||
.cached_i16 = c.LLVMInt16TypeInContext(ctx),
|
||||
.cached_i32 = c.LLVMInt32TypeInContext(ctx),
|
||||
.cached_i64 = c.LLVMInt64TypeInContext(ctx),
|
||||
.cached_f32 = c.LLVMFloatTypeInContext(ctx),
|
||||
.cached_f64 = c.LLVMDoubleTypeInContext(ctx),
|
||||
.cached_ptr = c.LLVMPointerTypeInContext(ctx, 0),
|
||||
.cached_void = c.LLVMVoidTypeInContext(ctx),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -396,8 +429,15 @@ pub const CodeGen = struct {
|
||||
self.foreign_libraries.deinit(self.allocator);
|
||||
self.foreign_fns.deinit();
|
||||
c.LLVMDisposeBuilder(self.builder);
|
||||
c.LLVMDisposeModule(self.module);
|
||||
c.LLVMContextDispose(self.context);
|
||||
if (self.target_machine) |tm| c.LLVMDisposeTargetMachine(tm);
|
||||
if (self.module_owned) {
|
||||
c.LLVMDisposeModule(self.module);
|
||||
}
|
||||
if (self.ts_context) |ts_ctx| {
|
||||
c.LLVMOrcDisposeThreadSafeContext(ts_ctx);
|
||||
} else {
|
||||
c.LLVMContextDispose(self.context);
|
||||
}
|
||||
}
|
||||
|
||||
fn getStructInfo(self: *CodeGen, name: []const u8) !StructInfo {
|
||||
@@ -510,8 +550,14 @@ pub const CodeGen = struct {
|
||||
|
||||
pub fn typeToLLVM(self: *CodeGen, ty: Type) c.LLVMTypeRef {
|
||||
return switch (ty) {
|
||||
.signed => |w| c.LLVMIntTypeInContext(self.context, w),
|
||||
.unsigned => |w| c.LLVMIntTypeInContext(self.context, w),
|
||||
.signed, .unsigned => |w| switch (w) {
|
||||
1 => self.cached_i1.?,
|
||||
8 => self.cached_i8.?,
|
||||
16 => self.cached_i16.?,
|
||||
32 => self.cached_i32.?,
|
||||
64 => self.cached_i64.?,
|
||||
else => c.LLVMIntTypeInContext(self.context, w),
|
||||
},
|
||||
.f32 => self.f32Type(),
|
||||
.f64 => self.f64Type(),
|
||||
.void_type => self.voidType(),
|
||||
@@ -736,15 +782,15 @@ pub const CodeGen = struct {
|
||||
return self.buildFatPointer(self.getStringStructType(), ptr, len_val);
|
||||
}
|
||||
|
||||
// LLVM type shortcuts
|
||||
fn i1Type(self: *CodeGen) c.LLVMTypeRef { return c.LLVMInt1TypeInContext(self.context); }
|
||||
fn i8Type(self: *CodeGen) c.LLVMTypeRef { return c.LLVMInt8TypeInContext(self.context); }
|
||||
fn i32Type(self: *CodeGen) c.LLVMTypeRef { return c.LLVMInt32TypeInContext(self.context); }
|
||||
fn i64Type(self: *CodeGen) c.LLVMTypeRef { return c.LLVMInt64TypeInContext(self.context); }
|
||||
fn f32Type(self: *CodeGen) c.LLVMTypeRef { return c.LLVMFloatTypeInContext(self.context); }
|
||||
fn f64Type(self: *CodeGen) c.LLVMTypeRef { return c.LLVMDoubleTypeInContext(self.context); }
|
||||
fn ptrType(self: *CodeGen) c.LLVMTypeRef { return c.LLVMPointerTypeInContext(self.context, 0); }
|
||||
fn voidType(self: *CodeGen) c.LLVMTypeRef { return c.LLVMVoidTypeInContext(self.context); }
|
||||
// LLVM type shortcuts (cached — no FFI call)
|
||||
fn i1Type(self: *CodeGen) c.LLVMTypeRef { return self.cached_i1.?; }
|
||||
fn i8Type(self: *CodeGen) c.LLVMTypeRef { return self.cached_i8.?; }
|
||||
fn i32Type(self: *CodeGen) c.LLVMTypeRef { return self.cached_i32.?; }
|
||||
fn i64Type(self: *CodeGen) c.LLVMTypeRef { return self.cached_i64.?; }
|
||||
fn f32Type(self: *CodeGen) c.LLVMTypeRef { return self.cached_f32.?; }
|
||||
fn f64Type(self: *CodeGen) c.LLVMTypeRef { return self.cached_f64.?; }
|
||||
fn ptrType(self: *CodeGen) c.LLVMTypeRef { return self.cached_ptr.?; }
|
||||
fn voidType(self: *CodeGen) c.LLVMTypeRef { return self.cached_void.?; }
|
||||
|
||||
fn gepArrayElement(self: *CodeGen, arr_ty: c.LLVMTypeRef, arr_ptr: c.LLVMValueRef, idx: c.LLVMValueRef, name: [*c]const u8) c.LLVMValueRef {
|
||||
var indices = [_]c.LLVMValueRef{ self.constInt32(0), idx };
|
||||
@@ -6206,13 +6252,16 @@ pub const CodeGen = struct {
|
||||
// Merge block
|
||||
self.positionAt(merge_bb);
|
||||
|
||||
// PHI node if both branches produced values
|
||||
// PHI node if both branches produced values (skip for void type)
|
||||
if (then_val != null and else_val != null) {
|
||||
const phi = c.LLVMBuildPhi(self.builder, c.LLVMTypeOf(then_val), "iftmp");
|
||||
var vals = [2]c.LLVMValueRef{ then_val, else_val };
|
||||
var blocks = [2]c.LLVMBasicBlockRef{ then_bb, else_bb };
|
||||
c.LLVMAddIncoming(phi, &vals, &blocks, 2);
|
||||
return phi;
|
||||
const ty = c.LLVMTypeOf(then_val);
|
||||
if (c.LLVMGetTypeKind(ty) != c.LLVMVoidTypeKind) {
|
||||
const phi = c.LLVMBuildPhi(self.builder, ty, "iftmp");
|
||||
var vals = [2]c.LLVMValueRef{ then_val, else_val };
|
||||
var blocks = [2]c.LLVMBasicBlockRef{ then_bb, else_bb };
|
||||
c.LLVMAddIncoming(phi, &vals, &blocks, 2);
|
||||
return phi;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -7176,39 +7225,12 @@ pub const CodeGen = struct {
|
||||
}
|
||||
|
||||
fn emitToFile(self: *CodeGen, output_path: [*:0]const u8, file_type: c.LLVMCodeGenFileType) !void {
|
||||
llvm.initAllTargets();
|
||||
const tm = self.target_machine orelse return self.emitError("no target machine available");
|
||||
|
||||
const cfg = self.target_config;
|
||||
const triple_owned = cfg.triple == null;
|
||||
const triple = cfg.triple orelse c.LLVMGetDefaultTargetTriple();
|
||||
defer if (triple_owned) c.LLVMDisposeMessage(@constCast(triple));
|
||||
|
||||
var target: c.LLVMTargetRef = null;
|
||||
var err_msg: [*c]u8 = null;
|
||||
|
||||
if (c.LLVMGetTargetFromTriple(triple, &target, &err_msg) != 0) {
|
||||
if (c.LLVMTargetMachineEmitToFile(tm, self.module, output_path, file_type, &err_msg) != 0) {
|
||||
defer c.LLVMDisposeMessage(err_msg);
|
||||
const msg = std.mem.span(err_msg);
|
||||
return self.emitErrorFmt("failed to get target: {s}", .{msg});
|
||||
}
|
||||
|
||||
const tm = c.LLVMCreateTargetMachine(
|
||||
target,
|
||||
triple,
|
||||
cfg.getCpu(),
|
||||
cfg.getFeatures(),
|
||||
cfg.opt_level.toLLVM(),
|
||||
c.LLVMRelocPIC,
|
||||
c.LLVMCodeModelDefault,
|
||||
);
|
||||
defer c.LLVMDisposeTargetMachine(tm);
|
||||
|
||||
c.LLVMSetTarget(self.module, triple);
|
||||
|
||||
var err_msg2: [*c]u8 = null;
|
||||
if (c.LLVMTargetMachineEmitToFile(tm, self.module, output_path, file_type, &err_msg2) != 0) {
|
||||
defer c.LLVMDisposeMessage(err_msg2);
|
||||
const msg = std.mem.span(err_msg2);
|
||||
return self.emitErrorFmt("failed to emit file: {s}", .{msg});
|
||||
}
|
||||
}
|
||||
@@ -7221,6 +7243,75 @@ pub const CodeGen = struct {
|
||||
return self.emitToFile(output_path, c.LLVMAssemblyFile);
|
||||
}
|
||||
|
||||
/// Emit the module as an object file to a memory buffer.
|
||||
/// Caller owns the returned buffer and must dispose or pass to JIT.
|
||||
pub fn emitObjectToMemory(self: *CodeGen) !c.LLVMMemoryBufferRef {
|
||||
const tm = self.target_machine orelse return self.emitError("no target machine available");
|
||||
var err_msg: [*c]u8 = null;
|
||||
var buf: c.LLVMMemoryBufferRef = null;
|
||||
if (c.LLVMTargetMachineEmitToMemoryBuffer(tm, self.module, c.LLVMObjectFile, &err_msg, &buf) != 0) {
|
||||
if (err_msg != null) {
|
||||
defer c.LLVMDisposeMessage(err_msg);
|
||||
const msg = std.mem.span(err_msg);
|
||||
return self.emitErrorFmt("failed to emit object to memory: {s}", .{msg});
|
||||
}
|
||||
return error.CompileError;
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
/// Execute a precompiled object file in-process using LLVM's ORC JIT.
|
||||
/// Takes ownership of obj_buf. Returns the exit code from main().
|
||||
pub fn runJITFromObject(obj_buf: c.LLVMMemoryBufferRef) !u8 {
|
||||
// Create LLJIT with default builder (no custom TM needed — .o is precompiled)
|
||||
var jit: c.LLVMOrcLLJITRef = null;
|
||||
var err = c.LLVMOrcCreateLLJIT(&jit, null);
|
||||
if (err != null) {
|
||||
const msg = c.LLVMGetErrorMessage(err);
|
||||
defer c.LLVMDisposeErrorMessage(msg);
|
||||
std.debug.print("JIT error: {s}\n", .{std.mem.span(msg)});
|
||||
return error.CompileError;
|
||||
}
|
||||
defer _ = c.LLVMOrcDisposeLLJIT(jit);
|
||||
|
||||
// Add process symbols so JIT can find libc (printf, write, etc.)
|
||||
const jd = c.LLVMOrcLLJITGetMainJITDylib(jit);
|
||||
const prefix = c.LLVMOrcLLJITGetGlobalPrefix(jit);
|
||||
var gen: c.LLVMOrcDefinitionGeneratorRef = null;
|
||||
err = c.LLVMOrcCreateDynamicLibrarySearchGeneratorForProcess(&gen, prefix, null, null);
|
||||
if (err != null) {
|
||||
const msg = c.LLVMGetErrorMessage(err);
|
||||
defer c.LLVMDisposeErrorMessage(msg);
|
||||
std.debug.print("JIT symbol gen error: {s}\n", .{std.mem.span(msg)});
|
||||
return error.CompileError;
|
||||
}
|
||||
c.LLVMOrcJITDylibAddGenerator(jd, gen);
|
||||
|
||||
// Add precompiled object file (transfers ownership of obj_buf)
|
||||
err = c.LLVMOrcLLJITAddObjectFile(jit, jd, obj_buf);
|
||||
if (err != null) {
|
||||
const msg = c.LLVMGetErrorMessage(err);
|
||||
defer c.LLVMDisposeErrorMessage(msg);
|
||||
std.debug.print("JIT add object error: {s}\n", .{std.mem.span(msg)});
|
||||
return error.CompileError;
|
||||
}
|
||||
|
||||
// Look up the "main" function
|
||||
var main_addr: c.LLVMOrcExecutorAddress = 0;
|
||||
err = c.LLVMOrcLLJITLookup(jit, &main_addr, "main");
|
||||
if (err != null) {
|
||||
const msg = c.LLVMGetErrorMessage(err);
|
||||
defer c.LLVMDisposeErrorMessage(msg);
|
||||
std.debug.print("JIT lookup error: {s}\n", .{std.mem.span(msg)});
|
||||
return error.CompileError;
|
||||
}
|
||||
|
||||
// Cast to function pointer and call
|
||||
const main_fn: *const fn () callconv(.c) i32 = @ptrFromInt(main_addr);
|
||||
const result = main_fn();
|
||||
return if (result >= 0 and result <= 255) @intCast(result) else 1;
|
||||
}
|
||||
|
||||
pub fn link(allocator: std.mem.Allocator, io: std.Io, output_obj: []const u8, output_bin: []const u8, libraries: []const []const u8, target_config: TargetConfig) !void {
|
||||
var argv = std.ArrayList([]const u8).empty;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user