Repository navigation
Memory Model
H provides a hybrid memory model that combines garbage-collected ergonomics with deterministic, zero-GC systems primitives in the same codebase. Program entry initializes Boehm GC (libgc) via hl_init_args(argc, argv) -> GC_init(), while hot paths and FFI boundaries can opt into stack-allocated struct values, inline StaticArray[T, N], scoped bump arenas (with_arena), manual Heap allocation, and compile-time @[nogc] verification.
The following table documents the exact LLVM IR representation emitted by hlc on 64-bit targets (x86-64 and AArch64):
| H Type | LLVM IR Type | Size (64-bit) | Storage / Semantics |
|---|---|---|---|
Bool |
i1 |
1 byte | Value |
I8, U8
|
i8 |
1 byte | Value |
I16, U16
|
i16 |
2 bytes | Value |
I32, U32
|
i32 |
4 bytes | Value |
I64, U64, Usize
|
i64 |
8 bytes | Value |
F32 |
float |
4 bytes | Value |
F64 |
double |
8 bytes | Value |
String |
{ ptr, i64 } |
16 bytes | Immutable value; ptr points to base of .rodata or GC_malloc_atomic(len + 1) buffer |
Slice[T] |
{ ptr, i64 } |
16 bytes | Non-owning view { ptr, len }
|
Array[T] |
ptr |
8 bytes | Pointer to 24-byte GC-allocated HlArray { data: ptr, len: i64, cap: i64 }
|
StaticArray[T, N] |
[N x T] |
N * sizeof(T) |
Inline unboxed fixed-size array |
Ptr[T] |
ptr |
8 bytes | Non-nullable raw pointer |
Arena |
ptr |
8 bytes | Pointer to HlArena bump allocator header |
struct S |
%S = type { ... } |
Sum of aligned fields | Unboxed inline value (@[repr(C)] preserves C field order) |
class C |
ptr |
8 bytes | Pointer to GC-allocated %C = type { ... } object (GC_malloc) |
Simple enum
|
i32 |
4 bytes | 0-based variant tag |
Payload enum
|
{ i32, [W x i64] } |
8 + W * 8 bytes |
i32 tag plus 8-byte-aligned payload storage sized to largest variant |
@[nogc] Fn(...) -> R |
ptr |
8 bytes | Direct C-ABI function pointer |
Fn(...) -> R |
{ ptr, ptr } |
16 bytes | Fat closure { fn_ptr, env_ptr }; fn_ptr takes hidden env_ptr as arg 0 |
T? (NPO eligible) |
ptr |
8 bytes | Null-Pointer Optimization (null represents nil) |
T? (non-NPO) |
{ i1, T } |
align(T) + sizeof(T) |
Explicit presence flag + inner payload |
- Instances are allocated on the Boehm GC heap via
hl_gc_alloc(sizeof(C))(GC_malloc). - Values of type
Care 8-byte reference pointers; passing or assigning aclasscopies the pointer without cloning fields. - Methods always receive
selfas a pointer and may mutate@fielddirectly withoutmut def. - Because allocating a
classinvokes the GC,MyClass.new(...)is rejected inside@[nogc]functions.
- Instances are unboxed values allocated on the stack, inside registers, or embedded directly inside other aggregates,
StaticArrays, or arenas. - Constructing
Vec2.new(3.0, 4.0)performs zero heap allocation and is legal inside@[nogc]. - Adding
@[repr(C)]guarantees C-compatible field order and padding for FFI structs. -
Immutability by default:
structparameters and non-mutmethods cannot assign to@field. -
In-place mutation (
mut def): Declaring a methodmut def scale(factor: F64) -> Voidpassesselfas a hiddenPtr[Vec2]pointing to the caller's storage. Calling amut defmethod on aconstbinding or temporary rvalue (such asVec2.new(1.0, 2.0).scale(2.0)) is a compile-time error. -
Parameter passing ABI: In the bootstrap compiler (
src/codegen.zig), immutablestruct,StaticArray, andenumparameters<= 16bytes pass by value in registers while larger values (> 16bytes) pass via hidden const-pointer without copying.
@[repr(C)]
struct Vec2
x: F64
y: F64
@[nogc]
def dot(other: Vec2) -> F64
@x * other.x + @y * other.y
end
@[nogc]
mut def scale(factor: F64) -> Void
@x *= factor
@y *= factor
end
endString is an immutable 16-byte value { ptr: Ptr[U8], len: Usize } passed in two registers.
Every String.ptr obeys two invariants:
-
Base address only:
ptralways points to byte 0 of either a static.rodataliteral or a GC allocation — never an interior pointer offset. -
Pointer-free NUL-terminated buffer: Runtime-created strings are allocated via
hl_gc_alloc_atomic(len + 1)(GC_malloc_atomic+ zero-fill) withptr[len] == 0. Because atomic GC blocks are never scanned for pointers andptris never offset into the interior of a block, Boehm GC retention stays precise and scanning overhead is avoided.
Because String.ptr must remain a base pointer, s.slice(start, stop) validates bounds via hl_slice_check(start, stop, s.len) and returns a zero-copy Slice[U8] ({ ptr + start, stop - start }, not NUL-terminated) rather than a String. Materializing an owned String from a slice uses sub.to_string (which copies into a fresh NUL-terminated atomic GC buffer via hl_str_from_bytes).
| Form | Storage | Allowed in @[nogc]? |
Passing to C Ptr[U8]
|
|---|---|---|---|
Plain literal "hello\n"
|
Static .rodata (LLVMBuildGlobalStringPtr) |
Yes | Implicitly coerces to Ptr[U8] at compile time |
Interpolated "x=#{x}" or a + b
|
GC atomic heap (GC_malloc_atomic) |
No | Explicit s.cstr (O(1) extraction of s.ptr) |
String.from_cstr(p) / String.from_bytes(p, n)
|
GC atomic heap | No | Explicit s.cstr
|
When passing s.cstr to a C function, s must remain live for the duration of the C call.
with_arena(initial_cap) do |scratch| ... end creates a fast bump-pointer allocator backed by chained malloc blocks and destroys every block automatically when the scope exits (including via return, break, next, or ? propagation).
@[repr(C)]
struct HlArenaBlock
prev: Ptr[HlArenaBlock]?
cap: Usize
used: Usize
# Followed immediately at byte offset 24 by `cap` bytes of payload storage
end
@[repr(C)]
struct HlArena
current: Ptr[HlArenaBlock]?
default_block_size: Usize
end-
hl_arena_create(initial_cap)setsdefault_block_sizetoinitial_capif>= 256bytes, or4096bytes otherwise. -
arena.alloc[T]()callshl_arena_alloc(arena, sizeof(T), alignof(T)), bumpsblk.usedto the required alignment boundary (chaining a newHlArenaBlockif the current block overflows), zero-initializes the memory viamemset, and returnsPtr[T]. -
arena.alloc_slice[T](count)allocatescount * sizeof(T)aligned zeroed bytes and returnsSlice[T]. -
hl_arena_destroy(arena)walksblk.prevfreeing all blocks and theHlArenaheader.
All arena operations are @[nogc]:
@[nogc]
def build_buffer(n: Usize) -> I32
with_arena(1024) do |scratch|
pkt = scratch.alloc[Packet]()
pkt.id = 7
sl = scratch.alloc_slice[I32](n)
sl[0] = 42
return sl[0]
end
0
endFor long-lived allocations that must outlive a lexical scope without GC overhead (for example, OS synchronization primitives like pthread_mutex_t in std/thread whose address must not move or confuse GC), H provides @[nogc] manual heap intrinsics:
-
Heap.alloc[T]() -> Ptr[T]— callshl_manual_alloc(sizeof(T))(calloc(1, size), panicking on OOM). -
Heap.free(ptr) -> Void— callshl_manual_free(ptr)(free(ptr)).
Pair Heap.alloc with defer Heap.free(p) or an explicit destroy() method:
@[nogc]
def use_manual_slot() -> I64
slot = Heap.alloc[I64]()
defer Heap.free(slot)
slot.* = 99
slot.*
endPtr[T] is a non-nullable typed raw pointer (use Ptr[T]? when nil is possible).
-
Single-level auto-dereference: When
phas typePtr[StructType],p.fieldreads or writes the field andp.method(...)invokes the method by dereferencing one pointer level automatically ((*p).field). NestedPtr[Ptr[T]]does not auto-deref multiple levels. -
Explicit dereference (
p.*): Reads or writes the pointee (slot.* = 42,v = slot.*). DereferencingPtr[Void]is a compile-time error. -
Pointer indexing (
p[i]): Indexesielements fromp(unchecked C-style pointer arithmetic). -
Pointer arithmetic (
p.offset(delta: I64) -> Ptr[T]): Emits LLVMgetelementptrbydeltaelements of typeT. -
Reinterpretation casts:
-
p.as_ptr[U]() -> Ptr[U]— reinterprets a pointer to another element type (zero runtime cost under opaque LLVM pointers). -
p.as_fn[@[nogc] Fn(Args...) -> R]()— casts a raw code pointer (e.g., fromobjc_msg_lookupor CoreCLRhostfxr) into a callable raw function pointer. -
(&raw_fn).as_ptr[Void]()— casts a@[nogc]function pointer toPtr[Void]. -
int_val.as_ptr[T]()— converts an integer toPtr[T]viainttoptr(used for sentinel constants such as-1inhostfxr).
-
In compiler/codegen.hl, opt_uses_npo(inner) determines whether T? uses a compact 8-byte null-pointer encoding instead of a tagged { i1, T } struct:
def opt_uses_npo(inner: TypeRef) -> Bool
if inner.kind == TypeKind.ptr_t or inner.kind == TypeKind.array_t
return true
end
if inner.kind == TypeKind.fn_t and inner.fn_nogc
return true
end
self.is_class_type(inner)
end-
NPO types (8 bytes, zero tag overhead):
Ptr[T]?,Array[T]?,(@[nogc] Fn(...) -> R)?, andMyClass?. Checking!= nilemits a singleicmp ne ptr %v, null(LLVMBuildIsNotNull), and unwrapping is a zero-cost no-op. -
Tagged optionals (
{ i1, T }): Primitives (I64?,Bool?,F64?),String?,Slice[T]?,StaticArray[T, N]?,struct?,enum?, and general fatFn(...) -> R?. Presence is stored in field 0 (i1) and payload in field 1 (T).
Functions and methods annotated with @[nogc] are statically checked by mark_gc_op during compilation to guarantee zero Boehm GC allocations. Inside any @[nogc] function or method, the compiler rejects:
-
Calling non-
@[nogc]H code: Calling any H function, method, generic instantiation, orFncallback not marked@[nogc]. (extern "C"declarations are always permitted in@[nogc].) -
Class instantiation: Calling
ClassName.new(...)(which invokeshl_gc_alloc). -
GC string operations: String interpolation (
"#{...}"),Stringconcatenation (+),String.from_cstr(...),String.from_bytes(...), andSlice[U8].to_string. (Plain string literals in.rodata,s.len,s.cstr,s.slice(a, b), ands[i]are all@[nogc].) -
GC collection allocations: Heap
Arrayliterals ([1, 2, 3]without aStaticArray[T, N]type annotation),Array[T].new(), andarr.push(...). (UseStaticArray[T, N]orarena.alloc_slice[T](n)instead; readingarr.len,arr.cap,arr[i], andarr.pop()does not allocate.) -
Capturing closures: Any
fn(...) do ... endclosure that captures outer local variables (since its environment struct is allocated viahl_gc_alloc). Stateless closures with@[nogc]bodies,&nogc_fnfunction pointers, and inlineddo |x| ... endblocks (each,times,yield) are all permitted in@[nogc].
- A
@[nogc] Fn(A) -> Ris an 8-byte raw function pointer with signature(A) -> R, directly ABI-compatible with C function pointers. - A general
Fn(A) -> Ris a 16-byte struct{ fn_ptr: Ptr[Void], env_ptr: Ptr[Void]? }whosefn_ptraccepts(env_ptr: Ptr[Void]?, A) -> R. - When a raw
@[nogc] Fn(A) -> Ris passed where a generalFn(A) -> Ris expected,coerce_valautomatically synthesizes a lightweight wrapper thunk (__hl_raw_thunk_N) that discards theenv_ptrargument and forwards to the raw function pointer, returning{ thunk_ptr, null }.
Next: Generics and Interfaces