gruel_codegen_llvm/lib.rs
1//! LLVM-based code generation for the Gruel compiler.
2//!
3//! This crate converts CFG (Control Flow Graph) to native object code via LLVM IR,
4//! using the `inkwell` crate as safe Rust bindings to LLVM's C API.
5//!
6//! ## Build requirements
7//!
8//! LLVM 22 must be installed and `LLVM_SYS_221_PREFIX` or a system `llvm-config`
9//! must be available.
10//!
11//! - On macOS: `brew install llvm`
12//! - On Linux: `apt install llvm-22-dev`
13//!
14//! ## Pipeline
15//!
16//! ```text
17//! CFG → LLVM IR (via inkwell) → [opt passes] → object file bytes
18//! ```
19
20mod codegen;
21mod types;
22
23use gruel_air::TypeInternPool;
24use gruel_cfg::{Cfg, OptLevel};
25use gruel_error::CompileResult;
26use lasso::ThreadedRodeo;
27
28/// Generate a native object file from a collection of function CFGs using LLVM.
29///
30/// All functions are compiled into a single LLVM module, which is then lowered
31/// to an object file via LLVM's backend. The returned bytes can be written to a
32/// `.o` file and passed to a system linker.
33///
34/// At `-O1` and above the LLVM mid-end pipeline (`default<OX>`) is run before
35/// emission, enabling InstCombine, GVN, SCCP, ADCE, SimplifyCFG, and more.
36///
37/// # Errors
38///
39/// Returns an error if an LLVM compilation error occurs.
40pub fn generate(
41 functions: &[&Cfg],
42 type_pool: &TypeInternPool,
43 strings: &[String],
44 interner: &ThreadedRodeo,
45 opt_level: OptLevel,
46) -> CompileResult<Vec<u8>> {
47 codegen::generate(functions, type_pool, strings, interner, opt_level)
48}
49
50/// Generate LLVM textual IR from a collection of function CFGs.
51///
52/// Returns the LLVM IR in human-readable `.ll` format. Used by `--emit asm`
53/// to produce inspectable IR in place of native assembly. At `-O1+` the
54/// returned IR is the post-optimization form.
55pub fn generate_ir(
56 functions: &[&Cfg],
57 type_pool: &TypeInternPool,
58 strings: &[String],
59 interner: &ThreadedRodeo,
60 opt_level: OptLevel,
61) -> CompileResult<String> {
62 codegen::generate_ir(functions, type_pool, strings, interner, opt_level)
63}