
프로그래밍 언어론
LLVM Intermediate RepresentationLLVM IR
LLVM IR(Intermediate Representation)은 LLVM 컴파일러 인프라의 중간 표현 언어로, 프론트엔드(언어)와 백엔드(아키텍처)를 분리하는 플랫폼 독립적 저수준 표현이다.
LLVM 컴파일 파이프라인
소스 코드 (C/C++/Rust/Swift/...)
↓ 파싱 + 의미 분석
AST (추상 구문 트리)
↓ IR 생성
LLVM IR (.ll 텍스트 / .bc 비트코드)
↓ IR 최적화 (Pass Pipeline)
최적화된 LLVM IR
↓ 코드 생성
기계어 코드 (x86, ARM, RISC-V, ...)
언어별 프론트엔드:
- Clang (C/C++/ObjC)
- rustc (Rust)
- swiftc (Swift)
- kotlinc (Kotlin Native)LLVM IR 예시
llvm
; C 함수: int add(int a, int b) { return a + b; }
define i32 @add(i32 %a, i32 %b) {
entry:
%result = add i32 %a, %b
ret i32 %result
}
; 조건 분기
define i32 @abs_val(i32 %x) {
entry:
%cmp = icmp slt i32 %x, 0 ; x < 0?
br i1 %cmp, label %negative, label %positive
negative:
%neg = sub i32 0, %x ; 0 - x
ret i32 %neg
positive:
ret i32 %x
}
; 루프 (phi 노드 - SSA 형식)
define i32 @sum_to_n(i32 %n) {
entry:
br label %loop
loop:
%i = phi i32 [ 0, %entry ], [ %i_next, %loop ]
%sum = phi i32 [ 0, %entry ], [ %sum_next, %loop ]
%sum_next = add i32 %sum, %i
%i_next = add i32 %i, 1
%done = icmp eq i32 %i_next, %n
br i1 %done, label %exit, label %loop
exit:
ret i32 %sum_next
}LLVM Python 바인딩 (llvmlite)
python
from llvmlite import ir, binding
# 모듈 생성
module = ir.Module(name="mymodule")
i32 = ir.IntType(32)
# 함수 선언
func_type = ir.FunctionType(i32, [i32, i32])
func = ir.Function(module, func_type, name="add")
a, b = func.args
# IR 생성
block = func.append_basic_block(name="entry")
builder = ir.IRBuilder(block)
result = builder.add(a, b, name="result")
builder.ret(result)
# JIT 컴파일 및 실행
binding.initialize()
target = binding.Target.from_default_triple()
machine = target.create_target_machine()
mod = binding.parse_assembly(str(module))
engine = binding.create_mcjit_compiler(mod, machine)
func_ptr = engine.get_function_address("add")
import ctypes
add_fn = ctypes.CFUNCTYPE(ctypes.c_int32, ctypes.c_int32, ctypes.c_int32)(func_ptr)
print(add_fn(3, 4)) # 7