Aula 20: Introdução ao LLVM IR
Objetivos
- Conhecer a infraestrutura LLVM.
- Ler e escrever LLVM IR básico.
Conteúdo
O LLVM (Low Level Virtual Machine) não é apenas uma VM, mas um “toolkit” para construção de compiladores. Sua maior contribuição é a LLVM IR, uma linguagem intermediária baseada em SSA que se tornou o padrão de facto para pesquisa e indústria.
Anatomia da LLVM IR
É um Assembly portável, tipado e SSA. - Tipos: i32 (inteiro 32 bits), float, ptr (ponteiro), <4 x float> (vetor SIMD). - Registradores Virtuais: Infinitos, começam com %. %1, %a. - Sintaxe:
define i32 @fatorial(i32 %n) {
entry:
%cmp = icmp eq i32 %n, 0
br i1 %cmp, label %base, label %recurse
base:
ret i32 1
recurse:
%sub = sub i32 %n, 1
%call = call i32 @fatorial(i32 %sub)
%res = mul i32 %n, %call
ret i32 %res
}O Pipeline LLVM
- Frontend (Clang, Rustc): Fonte \(\to\) LLVM IR.
- Optimizer (opt): LLVM IR \(\to\) LLVM IR (melhorada). Passadas como
-mem2reg,-instcombine. - Backend (llc): LLVM IR \(\to\) Assembly Nativo (.s) ou Objeto (.o).
Referências
- Aho, A. V., Lam, M. S., Sethi, R., & Ullman, J. D. (2006). Compilers: Principles, Techniques, and Tools.
- Cooper, K., & Torczon, L. (2011). Engineering a Compiler.