Moonbit version of LLVM, A Tiny, Friendly Companion to LLVM
Dependencies
moon update
moon add Kaida-Amethyst/MoonLLVMfn main {
// 1. 设置上下文、程序(模块)和 IR 构建器。
let ctx = @IR.Context::new()
let mod = ctx.addModule("my_module")
let builder = IRBuilder::new()
// 2. 定义函数签名:i32 add(i32, i32)。
let i32_t = ctx.getInt32Ty()
let f_type = ctx.getFunctionType(i32_t, [i32_t, i32_t])
// 3. 将函数添加到模块,并创建入口基本块。
let f = mod.addFunction(f_type, "add")
let bb = f.addBasicBlock("entry")
builder.setInsertPoint(bb)
// 4. 获取函数参数并命名。
let x = f.getArg(0).unwrap()
x.setName("x")
let y = f.getArg(1).unwrap()
y.setName("y")
// 5. 创建加法指令和返回指令。
let sum = builder.createAdd(x, y, "sum")
builder.createRet(sum)
// 6. 将生成的 LLVM IR 打印到控制台。
println(prog)
}moon run main.mbt > add.ll这会生成一个名为 add.ll 的文件,内容如下:; ModuleID = 'my_module'
source_filename = "my_module"
define i32 @add(i32 %x, i32 %y) {
entry:
%sum = add i32 %x, %y
ret i32 %sum
}llc -o add.s add.ll这会生成 add.s 文件,其中包含适用于您目标架构的汇编代码。moon update
moon add Kaida-Amethyst/MoonLLVMfn main {
// 1. Set up the context, program (module), and IR builder.
let ctx = @IR.LLVMContext::new()
let prog = ctx.addProgram("my_module")
let builder = IRBuilder::new()
// 2. Define the function signature: i32 add(i32, i32).
let i32_t = ctx.getInt32Ty()
let f_type = ctx.getFunctionType(i32_t, [i32_t, i32_t])
// 3. Add the function to the module and create an entry basic block.
let f = prog.addFunction(f_type, "add")
let bb = f.addBasicBlock("entry")
builder.setInsertPoint(bb)
// 4. Get the function's arguments and name them.
let x = f.getArg(0).unwrap()
x.setName("x")
let y = f.getArg(1).unwrap()
y.setName("y")
// 5. Create the add instruction and a return instruction.
let sum = builder.createAdd(x, y, "sum")
builder.createRet(sum)
// 6. Print the generated LLVM IR to the console.
println(prog)
}moon run main.mbt > add.llThis will generate a file named add.ll with the following content:; ModuleID = 'my_module'
source_filename = "my_module"
define i32 @add(i32 %x, i32 %y) {
entry:
%sum = add i32 %x, %y
ret i32 %sum
}llc -o add.s add.llThis will produce add.s containing the assembly code for your target architecture.Moonbit version of LLVM, A Tiny, Friendly Companion to LLVM
Dependencies