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