diff options
| author | Baitinq <[email protected]> | 2025-01-23 23:30:54 +0100 |
|---|---|---|
| committer | Baitinq <[email protected]> | 2025-01-23 23:30:54 +0100 |
| commit | 05cb23e8bec0ad1fa9841e9d08ab6ca010868d44 (patch) | |
| tree | 4b990cfad3a9687f30cf252879133067ee4d76be /src/codegen.zig | |
| parent | Misc: Add llvm zig bindings and dependency (diff) | |
| download | pry-lang-05cb23e8bec0ad1fa9841e9d08ab6ca010868d44.tar.gz pry-lang-05cb23e8bec0ad1fa9841e9d08ab6ca010868d44.tar.bz2 pry-lang-05cb23e8bec0ad1fa9841e9d08ab6ca010868d44.zip | |
Misc: Add example llvm code
Diffstat (limited to 'src/codegen.zig')
| -rw-r--r-- | src/codegen.zig | 39 |
1 files changed, 38 insertions, 1 deletions
diff --git a/src/codegen.zig b/src/codegen.zig index a3fc681..5951141 100644 --- a/src/codegen.zig +++ b/src/codegen.zig @@ -1,4 +1,41 @@ const std = @import("std"); const parser = @import("parser.zig"); +const llvm = @import("llvm"); +const target = llvm.target; +const types = llvm.types; +const core = llvm.core; -pub const CodeGen = struct {}; +pub const CodeGen = struct { + pub fn generate() void { + // Initialize LLVM + _ = target.LLVMInitializeNativeTarget(); + _ = target.LLVMInitializeNativeAsmPrinter(); + _ = target.LLVMInitializeNativeAsmParser(); + + // Create a new LLVM module + const module: types.LLVMModuleRef = core.LLVMModuleCreateWithName("sum_module"); + var params: [2]types.LLVMTypeRef = [_]types.LLVMTypeRef{ + core.LLVMInt32Type(), + core.LLVMInt32Type(), + }; + + // Create a function that computes the sum of two integers + const func_type: types.LLVMTypeRef = core.LLVMFunctionType(core.LLVMInt32Type(), ¶ms, 2, 0); + const sum_func: types.LLVMValueRef = core.LLVMAddFunction(module, "sum", func_type); + const entry: types.LLVMBasicBlockRef = core.LLVMAppendBasicBlock(sum_func, "entry"); + const builder: types.LLVMBuilderRef = core.LLVMCreateBuilder(); + core.LLVMPositionBuilderAtEnd(builder, entry); + const arg1: types.LLVMValueRef = core.LLVMGetParam(sum_func, 0); + const arg2: types.LLVMValueRef = core.LLVMGetParam(sum_func, 1); + const sum: types.LLVMValueRef = core.LLVMBuildAdd(builder, arg1, arg2, "sum"); + _ = core.LLVMBuildRet(builder, sum); + + // Dump the LLVM module to stdout + core.LLVMDumpModule(module); + + // Clean up LLVM resources + core.LLVMDisposeBuilder(builder); + core.LLVMDisposeModule(module); + core.LLVMShutdown(); + } +}; |