LLVM IR
- Rust course
- Expert
- Lesson 3/46
- 4 min
Learn the LLVM backend and code generation pipeline.
LLVM IR
MIR is translated to LLVM's intermediate representation, where LLVM optimizations (inlining, constant folding, loop unrolling, vectorization) are applied; then machine code for the target processor is generated. The optimization level is chosen with opt-level: 0 in debug builds, 3 in release.
fn kare_toplam(n: u64) -> u64 {
(1..=n).map(|i| i * i).sum()
}
// in release, LLVM may turn this loop into the n(n+1)(2n+1)/6 formulaTo see the output: cargo rustc --release -- --emit=llvm-ir or Compiler Explorer (godbolt.org).
Debug versus release
In debug builds overflow checks and debug info are on and there's no optimization; in release it's the opposite. Performance must always be measured in a release build: the same code can be 10–100 times slower in debug. Intermediate options are set in Cargo.toml:
[profile.dev]
opt-level = 1 # a little optimization in debug
[profile.release]
debug = true # symbol info for profiling
codegen-units = 1 # better optimization, slower compilePractice Sum of squares
Write the kare_toplam function above. Print the result, passing the input through std::hint::black_box(10u64).
Starter code
fn main() {
// buraya yaz
}Sample solution
fn kare_toplam(n: u64) -> u64 {
(1..=n).map(|i| i * i).sum()
}
fn main() {
let n = std::hint::black_box(10u64);
println!("{}", kare_toplam(n));
}Expected output
385
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is <code>std::hint::black_box</code> used when writing benchmarks?
- To allocate memory
- For debugging
- To stop the compiler from treating the value as a known constant and deleting the computation Correct answer
- To speed the program up
Explanation: A pure function called with a constant input may be computed at compile time; the measured time wouldn't reflect reality.
2 Block the optimization
let n = std::hint::____(10u64);
println!("{}", kare_toplam(n));
let n = std::hint::black_box(10u64);
println!("{}", kare_toplam(n));
Explanation: black_box makes the value appear unknown to the compiler.
3 Setting and effect
| Term | Meaning |
|---|---|
opt-level = 0 |
No optimization |
opt-level = 3 |
Full optimization |
--emit=llvm-ir |
LLVM IR output |
black_box |
Prevents folding |