Okay, let's define an Intermediate Representation (IR) for Flux, sitting between the high-level Flux language and LLVM IR. We'll call it Flux Intermediate Representation (FIR).
FIR is a Static Single Assignment (SSA) based intermediate representation designed to facilitate optimizations specific to Flux's memory model and type system before generating LLVM IR. It abstracts away source-level syntax while retaining enough semantic information for effective analysis and transformation.
Key Goals of FIR:
Decoupling: Separate front-end (parsing, semantic analysis) from back-end (LLVM codegen).
Flux-Specific Optimizations: Enable optimizations that leverage Flux's ownership and arena allocation model (e.g., dead allocation elimination, lifetime analysis).
Simplicity: Keep the IR relatively high-level compared to LLVM IR, avoiding premature lowering of types and control flow.
Fast Compilation: Designed to be generated and processed quickly.
2. Core Concepts
SSA (Static Single Assignment): Every variable (virtual register) is assigned a value exactly once. This simplifies dataflow analysis. Phi nodes (phi) are used to merge values from different control flow paths.
Virtual Registers: All intermediate computation results are stored in virtual registers, prefixed with % (e.g., %v0, %temp_sum).
Basic Blocks: A sequence of instructions with a single entry point and a single exit point. Each block ends with a terminator instruction (branch, conditional branch, return).
Types: FIR maintains Flux's high-level type system (structs, slices, optionals) as much as possible, mapping them to LLVM's types during the final codegen phase.
No Reference Counting or GC Instructions: FIR does not contain instructions for reference counting or garbage collection. Memory management is handled by:
Stack Allocation (alloca): For local variables, automatically deallocated on function exit.
Arena Allocation (arena.alloc): Explicit calls to a runtime arena_alloc function. The defer arena.free() ensures a call arena.free() instruction is emitted at the scope exit.
Ownership/Borrowing: Primarily enforced by the Flux front-end. Moves become bit-for-bit copies, and borrows are pointer passes. The FIR implicitly assumes ownership rules are met.
3. FIR Type System
FIR types broadly mirror Flux types, but with explicit representations for slices, optionals, and results.
Primitive Types:
iN: Signed integer (e.g., i8, i32, i64, isize).
uN: Unsigned integer (e.g., u8, u32, u64, usize).
f32, f64: Floating-point numbers.
bool: Boolean.
char: Unicode character (e.g., u32).
void: For functions that return nothing.
Compound Types:
ptr<T>: Pointer to type T.
array<N, T>: Fixed-size array of N elements of type T.
slice<T>: A dynamic slice of type T. Represented internally as struct { ptr: ptr<T>, len: usize }. str is slice<u8>.
option<T>: Optional type. Represented internally as struct { has_value: bool, value: T }. The value field might be aligned for optimal layout.
result<OkT, ErrT>: Result type. Represented internally as struct { is_ok: bool, ok_value: OkT, err_value: ErrT }.
4. FIR Program Structure
A FIR program is a collection of function definitions and global variable declarations.
code
// Global variable declaration
global @my_global_var: i32 = 10
// Function definition
func @function_name(param1: Type1, param2: Type2) -> ReturnType {
// Basic blocks
block.entry:
// Instructions
...
br block.exit
block.exit:
ret %some_value
}
5. FIR Instructions
Instructions operate on virtual registers and literals. Each instruction produces a result stored in a new virtual register, adhering to SSA.
5.1. Memory Instructions
alloca <type> -> %reg: ptr<type>:
Allocates space for <type> on the stack. The returned register holds a pointer to the allocated memory.
load <ptr_reg>: ptr<type> -> %reg: type:
Loads a value from the memory address pointed to by <ptr_reg>.
store <value_reg>: type, <ptr_reg>: ptr<type>:
Stores <value_reg> into the memory address pointed to by <ptr_reg>.
getelementptr <ptr_reg>: ptr<aggregate_type>, <indices>... -> %reg: ptr<element_type>:
Calculates the address of a field within a struct or an element within an array/slice.
getelementptr %struct_ptr, field_idx 0 (for first field of struct)
arena.alloc <arena_ptr>: ptr<Arena>, <size_bytes>: usize -> %reg: ptr<u8>:
Allocates raw memory from the specified arena. The arena_alloc runtime function typically returns a ptr<u8>. Type casting would be applied subsequently.
5.2. Arithmetic and Logic Instructions
add <op1_reg>: T, <op2_reg>: T -> %reg: T
sub <op1_reg>: T, <op2_reg>: T -> %reg: T
mul <op1_reg>: T, <op2_reg>: T -> %reg: T
div <op1_reg>: T, <op2_reg>: T -> %reg: T
mod <op1_reg>: T, <op2_reg>: T -> %reg: T
and <op1_reg>: T, <op2_reg>: T -> %reg: T
or <op1_reg>: T, <op2_reg>: T -> %reg: T
xor <op1_reg>: T, <op2_reg>: T -> %reg: T
shl <op1_reg>: T, <op2_reg>: T -> %reg: T (Shift Left)
shr <op1_reg>: T, <op2_reg>: T -> %reg: T (Shift Right, arithmetic or logical as per type)
neg <op_reg>: T -> %reg: T (Negation)
not <op_reg>: T -> %reg: T (Bitwise Not for integers, Logical Not for bool)
5.3. Comparison Instructions
cmp.<cond> <op1_reg>: T, <op2_reg>: T -> %reg: bool:
Compares two values. <cond> can be:
eq (equal)
ne (not equal)
lt (less than)
le (less than or equal)
gt (greater than)
ge (greater than or equal)
5.4. Control Flow Instructions (Terminators)
br <label>:
Unconditional branch to <label>.
cond_br <cond_reg>: bool, <true_label>, <false_label>:
Conditional branch. If <cond_reg> is true, jump to <true_label>, otherwise to <false_label>.
ret <value_reg>: Type:
Returns <value_reg> from the current function.
ret void:
Returns from the current function (no value).
5.5. Function Call Instructions
call @function_name(<arg1>, <arg2>, ...) -> %reg: ReturnType:
Calls a function by its global name.
call_intrinsic @intrinsic_name(<arg1>, ...) -> %reg: ReturnType:
Calls a compiler intrinsic function (e.g., memcpy, memset, sqrt).
5.6. Type Conversion Instructions
cast.<from_type>.<to_type> <op_reg>: from_type -> %reg: to_type:
Performs type casting. Examples:
cast.i32.f32 %int_val (integer to float)
cast.f64.i64 %float_val (float to integer, truncation)
cast.ptr<i8>.ptr<u8> %char_ptr (pointer cast)
cast.usize.i32 %size_val
5.7. Struct and Slice Instructions
struct_create <struct_type>, { <field1_reg>, <field2_reg>, ... } -> %reg: struct_type:
Creates a new struct instance with provided field values.
struct_extract <struct_reg>: struct_type, <field_idx>: int -> %reg: field_type:
Extracts a field value from a struct instance (by value).
struct_insert <struct_reg>: struct_type, <field_idx>: int, <value_reg>: field_type -> %reg: struct_type:
Creates a new struct instance with one field updated. (SSA friendly, immutable struct modification).
slice_create <ptr_reg>: ptr<T>, <len_reg>: usize -> %reg: slice<T>:
Creates a new slice value from a raw pointer and length.
slice_len <slice_reg>: slice<T> -> %reg: usize:
Returns the length of a slice.
slice_ptr <slice_reg>: slice<T> -> %reg: ptr<T>:
Returns the raw data pointer of a slice.
5.8. Optional and Result Instructions
option_some <value_reg>: T -> %reg: option<T>:
Creates an option<T> value indicating presence.
option_none <type>: T -> %reg: option<T>:
Creates an option<T> value indicating absence.
option_has_value <option_reg>: option<T> -> %reg: bool:
Checks if an optional value is present.
option_get_value <option_reg>: option<T> -> %reg: T:
Extracts the value from an optional. Requires prior option_has_value check in higher level language logic.
result_ok <ok_value_reg>: OkT, <err_type>: ErrT -> %reg: result<OkT, ErrT>:
Creates a result<OkT, ErrT> value indicating success.
result_err <err_value_reg>: ErrT, <ok_type>: OkT -> %reg: result<OkT, ErrT>:
Creates a result<OkT, ErrT> value indicating error.
result_is_ok <result_reg>: result<OkT, ErrT> -> %reg: bool:
Checks if a result value is success.
func @calculate_dist() -> f64 {
block.entry:
// p1 := Point{x: 1.0, y: 2.0}
%p1_x_lit = f64_literal 1.0
%p1_y_lit = f64_literal 2.0
%p1_val = struct_create @Point, { %p1_x_lit, %p1_y_lit }
// p2 := Point{x: 4.0, y: 6.0}
%p2_x_lit = f64_literal 4.0
%p2_y_lit = f64_literal 6.0
%p2_val = struct_create @Point, { %p2_x_lit, %p2_y_lit }
// p1 is passed by reference (ownership) for 'self'
// This typically means we allocate p1 on the stack and pass its address.
%p1_alloca = alloca @Point
store %p1_val: @Point, %p1_alloca: ptr<@Point>
// dist := p1.distance(p2)
// The 'self' argument becomes a pointer to p1_alloca
%dist = call @Point.distance(%p1_alloca: ptr<@Point>, %p2_val: @Point)
ret %dist: f64
}
7. FIR to LLVM IR Mapping Considerations
FIR Types to LLVM Types:
iN, uN, f32, f64, bool: Map directly to LLVM iN, float, double, i1.
ptr<T>: Maps to LLVM ptr<LLVM_T>.
array<N, T>: Maps to LLVM [N x LLVM_T].
slice<T>: Maps to LLVM { ptr<LLVM_T>, iN } (where iN is usize).
struct<Name, ...>: Maps to LLVM %{Name} = type { ... }.
option<T>: Maps to LLVM { i1, LLVM_T }.
result<OkT, ErrT>: Maps to LLVM { i1, LLVM_OkT, LLVM_ErrT }. Careful padding might be needed.
FIR Instructions to LLVM Instructions:
Most arithmetic, logic, and comparison operations have direct LLVM equivalents (add, fsub, icmp eq, etc.).
alloca, load, store: Direct LLVM counterparts.
getelementptr: Direct LLVM getelementptr.
br, cond_br, ret, call: Direct LLVM counterparts.
cast: Maps to LLVM bitcast, fptoui, uitofp, trunc, zext, etc., depending on the specific cast.
phi: Maps directly to LLVM phi.
Struct/Slice manipulation: These often desugar into getelementptr, load, store, or insertvalue/extractvalue instructions on LLVM aggregate types. struct_create will typically involve alloca for the struct and then store operations for each field.
arena.alloc: This will map to an LLVM call instruction to a runtime function (e.g., _flux_rt_arena_alloc).
Intrinsic calls: Map to LLVM intrinsic calls (e.g., llvm.memcpy.p0i8.p0i8.i64).
This FIR provides a robust intermediate step, allowing Flux's unique memory management and type system features to be represented and optimized before the final translation to the lower-level, more general LLVM IR.