Skip to content

Commit b369dcb

Browse files
committed
add a bit on llvm
1 parent c52d026 commit b369dcb

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed

src/codegen.md

+48-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,48 @@
1-
# Generating LLVM IR
1+
# Code generation
2+
3+
Code generation or "codegen" is the part of the compiler that actually generates
4+
an executable binary. rustc uses LLVM for code generation.
5+
6+
## What is LLVM?
7+
8+
All of the preceeding chapters of this guide have one thing in common: we never
9+
generated any executable machine code at all! With this chapter, all of that
10+
changes.
11+
12+
Like most compilers, rustc is composed of a "frontend" and a "backend". The
13+
"frontend" is responsible for taking raw source code, checking it for
14+
correctness, and getting it into a format `X` from which we can generate
15+
executable machine code. The "backend" then takes that format `X` and produces
16+
(possibly optimized) executable machine code for some platform. All of the
17+
previous chapters deal with rustc's frontend.
18+
19+
rustc's backend is [LLVM](https://llvm.org), "a collection of modular and
20+
reusable compiler and toolchain technologies". In particular, the LLVM project
21+
contains a pluggable compiler backend (also called "LLVM"), which is used by
22+
many compiler projects, including the `clang` C compiler and our beloved
23+
`rustc`.
24+
25+
LLVM's "format `X`" is called LLVM IR. It is basically assembly code with
26+
additional low-level types and annotations added. These annotations are helpful
27+
for doing optimizations on the LLVM IR and outputed machine code. The end result
28+
of all this is (at long last) something executable (e.g. an ELF object or wasm).
29+
30+
There are a few benefits to using LLVM:
31+
32+
- We don't have to write a whole compiler backend. This reduces implementation
33+
and maintainance burden.
34+
- We benefit from the large suite of advanced optimizations that the LLVM
35+
project has been collecting.
36+
- We automatically can compile Rust to any of the platforms for which LLVM has
37+
support. For example, as soon as LLVM added support for wasm, voila! rustc,
38+
clang, and a bunch of other languages were able to compile to wasm! (Well,
39+
there was some extra stuff to be done, but we were 90% there anyway).
40+
- We and other compiler projects benefit from each other. For example, when the
41+
[Spectre and Meltdown security vulnerabilities][spectre] were discovered, only LLVM
42+
needed to be patched.
43+
44+
[spectre]: https://meltdownattack.com/
45+
46+
## Generating LLVM IR
47+
48+
TODO

0 commit comments

Comments
 (0)