Native binary with LLVM: Write yourself a compiler, Part VII
So far, our every compiler produced non-standalone binaries. Even .class files created last time still require Java Virtual Machine to interpret them. I think it’s about time to actually produce self-sufficient binary which only needs an operating system and not much more than that to run. In general, this means producing machine code which target CPU/OS can run directly, not via some intermediate layer.
Historically, that’d mean our compiler must produce valid assembly/machine code. Moreover, the compiler must be capable of producing valid, efficient code for each architecture (x86, ARM, Risc V, WebAssembly…) That’s how many compilers (like Go) work. But these days we have a simpler option.
LLVM frontend
LLVM is a set of tools helping to implement any compiler for any architecture. Compilers for languages like C, C++, Objective-C (via clang), Swift, Rust and many more, use it to produce binaries. In general, compilers built on top of LLVM implement so-called LLVM frontend. It’s a bespoke code which translates language-specific source code into LLVM intermediate representation (IR). The concept of IR (or bytecode) is familiar to us. But in this case, the IR is not the final product, it’s just intermediate artifact. Then, IR is immediately compiled into platform-dependent machine code using LLVM backend
LLVM backend
LLVM provides dozens of backends, each one targeting a different platform. x86, ARM, RISC-V, PowerPC… WebAssembly, eBPF programs - you name it. As long as you produced valid IR, LLVM will do its best to compile it to a target machine. Moreover, LLVM backend has a set of platform-agnostic and platform-dependent optimizations. If your IR code is inefficient, it’ll be heavily optimized as part of the compilation process.
This separation of concerns (frontend and backend) has two great benefits:
- if you want to implement a new programming language, just write a new frontend and you immediately get a compiler for every obscure hardware platform on the planet
- if a new, even more obscure platform appears, new LLVM backend will open that platform for every single programming language out there having an LLVM frontend
This separation means we no longer duplicate machine code generation work for each language and platform. That’s an extremely hard work, better left to professionals with real hardware sympathy.
Limitations
Just because LLVM backend exists, doesn’t mean you can take any frontend producing IR and run it on any platform. Also, LLVM doesn’t provide higher-level concepts like garbage collection. That’s still on you. Last but not least, bespoke compiler might be faster than a collection of chained LLVM tools. That was historically the reason why Go doesn’t use it.
Our first LLVM IR
Before jumping into the implementation of our custom LLVM frontend, let’s see it’s results in action. Here, we consume the simplest 2 + 40 “program” into valid LLVM IR via echo '2 + 40' | llvm-compiler:
1
2
3
4
5
6
7
8
9
10
11
@format = constant [4 x i8] c"%d\0A\00"
declare i32 @printf(i8* %format, ...)
define i32 @main() {
main-block:
%0 = add i32 2, 40
%1 = getelementptr [4 x i8], [4 x i8]* @format, i32 0, i32 0
%2 = call i32 (i8*, ...) @printf(i8* %1, i32 %0)
ret i32 0
}
The only thing to care about from the snippet above is:
1
%0 = add i32 2, 40
It’s the actual 2 + 40 part. The rest is just IR boilerplate and printf boilerplate needed to put the result on screen. At this point, we can take this IR and compile it to native binary:
1
2
3
4
5
opt -O3 -S expression.ll -o expression.opt.ll
llc -O3 -filetype=asm -mcpu=native expression.opt.ll -o expression.s
as -arch arm64 expression.s -o expression.o
ld expression.o -o expression -lSystem -syslibroot "$(xcrun --show-sdk-path)" -arch arm64 -dead_strip
./expression
OK, a lot is going on here. For clarity, I split every processing step, so you can see intermediate artifacts.
Unoptimized LLVM IR
First, we translate our “program” into unoptimized LLVM IR:
1
echo "40 + 2" | ./llvm-compiler > expression.ll
Keep in mind that we don’t have the llvm-compiler implemented yet, but I’m just foreshadowing it. Anyway, our 40 + 2 “program” is being translated into .ll file already shown above. Except some boilerplate, this is the crucial line:
1
%0 = add i32 40, 2
Optimized IR
The only reason I’m bringing this up again is because the next step… removes this line altogether! That’s right, if you know anything about compilers, the 40 + 2 expression is constant, and its value is known at compile time. Why computing it at runtime, if we can just hard-code the result?
1
opt -O3 -S expression.ll -o expression.opt.ll
This is platform-agnostic LLVM optimizer opt. It takes our naive IR and turns it into optimized IR, stripped down to the important bits:
1
2
%0 = tail call i32 (ptr, ...) @printf(ptr nonnull dereferenceable(1) @format, i32 42)
ret i32 0
Yup, there’s no addition. Just hard-coded printf(42), because why not? Of course, in real life scenarios, the optimizations are way more sophisticated. But you get the idea.
Generating assembly
Now THE LLVM compiler, that is, the backend. It takes our shiny, optimized IR and produces (finally!) proper assembly:
1
llc -O3 -filetype=asm -mcpu=native expression.opt.ll -o expression.s
This takes the optimized LLVM IR and produces machine code:
1
2
3
4
5
6
7
8
9
adrp x0, _format@PAGE
add x0, x0, _format@PAGEOFF
mov w8, #42 ; =0x2a
str x8, [sp]
bl _printf
...
_format:
.asciz "%d\n"
This is way more obscure, and even worse, architecture-specific (here it’s ARM on MacOS). But we can see some familiar parts, like 42 constant and calling _printf with "%d\n" formatting. The bottom line: generating optimized assembly for each and every architecture is hard. LLVM does that.
Compiling assembly and linking
The rest is history, we just need to translate assembly into machine code (binary, using as) and link it to standalone binary:
1
2
as -arch arm64 expression.s -o expression.o
ld expression.o -o expression -lSystem -syslibroot "$(xcrun --show-sdk-path)" -arch arm64 -dead_strip
And just like that, we finally have a stand-alone binary which, one called, prints 42. Finally, the answer! I know it’s a lot of steps:
- source code
- LLVM IR
- optimized LLVM IR
- assembly
- machine code obj
- linking.
In reality we’d just wrap the entire chain into a single compiler command. But! We still haven’t seen the actual copmiler (first step)!
LLVM frontend compiler (source code)
The frontend part of the compiler is surprisingly simple. First of all, we’ll use existing LLVM library for Go, github.com/llir/llvm/ir. It provides high-level API for generating textual IR, so we don’t have to
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
func compile(expr expression) (*ir.Module, error) {
module := ir.NewModule()
format := module.NewGlobalDef("format", constant.NewCharArrayFromString("%d\n\x00"))
format.Immutable = true
printf := module.NewFunc("printf", types.I32, ir.NewParam("format", types.NewPointer(types.I8)))
printf.Sig.Variadic = true
main := module.NewFunc("main", types.I32)
entry := main.NewBlock("main-block")
left := constant.NewInt(types.I32, int64(expr.left))
right := constant.NewInt(types.I32, int64(expr.right))
var result value.Value
switch expr.op {
case '+':
result = entry.NewAdd(left, right)
case '-':
result = entry.NewSub(left, right)
case '*':
result = entry.NewMul(left, right)
case '/':
result = entry.NewSDiv(left, right)
default:
return nil, fmt.Errorf("error: unsupported operator %q", expr.op)
}
formatPtr := entry.NewGetElementPtr(
format.ContentType,
format,
constant.NewInt(types.I32, 0),
constant.NewInt(types.I32, 0),
)
entry.NewCall(printf, formatPtr, result)
entry.NewRet(constant.NewInt(types.I32, 0))
return module, nil
}
This takes a source code (number op number) and generated textual representation of LLVM IR. Everything else is open source LLVM toolchain doing its magic. We didn’t even have to remove the pointless, hardcoded arithmetic. The optimizer does that for us.
Check out the full source code on GitHub (part-vii). And see you in the next installment, where we’ll finally implement more complex expressions!