65

I've recently been looking at the Rust programming language. How does it work? Rust code seems to be compiled into ELF or PE (etc) binaries, but I've not been able to find any information on how that's done? Is it compiled to an intermediate format then compiled the rest of the way with gxx for example? Any help (or links) would be really appreciated.

2
  • The Rust compiler uses LLVM as backend, like other compilers do (clang, Swift and others). Does that answer your question? It is unclear what you are asking
    – aochagavia
    Apr 13, 2017 at 6:38
  • 5
    @aochagavia I think it is very clear what he is asking. Great question helped me a lot. Jun 27, 2019 at 15:11

1 Answer 1

192

The code-generation phase of the Rust compiler is mainly done by LLVM. LLVM is a set of tools for building a compiler, most notably used by the C[++] Compiler clang[++].

First, the Rust compiler (just like clang, for example) does all the Rust specific stuff like type and borrow checking; in the end, it generates LLVM-IR. IR stands for intermediate representation and it's... comparable to assembly, but a tiny bit more high level and most importantly: platform independent. Then the Rust compiler just calls ☏ LLVM and says:

Hey buddy, could you please take this IR and generate machine code for the current platform? That would be fantastic ◕ ◡ ◕

To which LLVM responds:

🌈 Sure, no problem, new friend. Here is your highly optimized machine code for [e.g.] x86_64! ♫♪♫

Afterwards they invite a few more friends to wrap it all up in a nice little [e.g.] ELF package and beautifully place it in the users file system. (and the user is like...)


Information like this can be found in the official FAQ which contains a lot of interesting information anyway. For more in-depth details on the Rust compiler, you can read the "Rustc Guide". For this question, the chapter "High Level Overview" is pretty interesting.

4
  • 79
    The various parts of the compilation process are so polite to one another. Apr 13, 2017 at 7:19
  • 4
    This is a really succinct yet entertaining analogy. May 18, 2019 at 21:01
  • Howto describe LLVM in ... some lines, but not a lot.
    – mslot
    Mar 7, 2020 at 13:20
  • Where is the LLVM generating code?
    – Lance
    Feb 13, 2022 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.