The code is available in calculator/examples/llvm/src/main.rs
. Because my llvm-config --version
shows 10.0.0
so I'm using features = ["llvm10-0"]
in inkwell
inkwell = { git = "https://github.com/TheDan64/inkwell", branch = "master", features = ["llvm10-0"] }
Go to calculator/examples/llvm
sub-crate and cargo run
.
We want to define an add function like
add(x: i32, y: i32) -> i32 { x + y }
but using the LLVM language and JIT it. For that, we need to define every bit of what makes up a function through LLVM basic constructs such as context, module, function signature setups, argument types, basic block, etc.
Here is how to stitch our add function in LLVM
- We start by creating a
context
, adding theaddition
module and setting up the data type we want to usei32_type
of typeIntType
{{#include ../../../calculator/examples/llvm/src/main.rs:first}}
- We define the signature of
add(i32, i32) -> i32
, add the function to our module, create a basic block entry point and a builder to add later parts
{{#include ../../../calculator/examples/llvm/src/main.rs:second}}
- We create the arguments
x
andy
and add them to thebuilder
to make up the return instruction
{{#include ../../../calculator/examples/llvm/src/main.rs:third}}
- Finally, we create a JIT execution engine (with no optimization for now) and let LLVM handle rest of the work for us
{{#include ../../../calculator/examples/llvm/src/main.rs:fourth}}
Yes! all of this just to add two integers.