Draft 0.2 · C++23 runtime · UQBE backend
Haze heap objects are immutable after construction.
An object can only reference objects that already existed when it was constructed. Consequently, an older object can never acquire a reference to a younger object.
The resulting graph has a useful directional property:
This provides two important properties:
The compiler must guarantee that heap fields cannot be modified after object publication.
Object construction follows this sequence:
The collector is permitted to modify object storage internally when rewriting references during evacuation.
If Haze eventually introduces mutable heap cells, such as
Ref or lazy thunk updates, they must use an explicit
mutation API:
haze_wb(obj, slot, value)
This operation will:
REMEMBERED header flag.Mutable objects must not bypass this API.
This is not required by v1.
The collector reserves one large contiguous virtual address range.
Default configuration:
The heap uses a single base address:
heap_base
Block lookup is a shift:
constexpr u32 BLOCK_SHIFT = 15;
constexpr u64 BLOCK_SIZE = 1ull << BLOCK_SHIFT;
inline u32 block_index(const void* ptr) {
return (static_cast<const u8*>(ptr) -
heap_base) >> BLOCK_SHIFT;
}The implementation must validate that the pointer belongs to the managed reservation before performing this calculation.
| Constant | Value | Description |
|---|---|---|
| Granule | 16 B | Minimum object alignment |
| Header | 8 B | Object metadata |
| Line | 128 B | Allocation/reclamation granularity |
| Block | 32 KiB | Immix allocation unit |
| Lines per block | 256 | Fixed |
| Small object | ≤128 B | Normal allocation |
| Medium object | ≤8 KiB | Multi-line allocation |
| Large object | >8 KiB | Large object space |
Object sizes include their headers and are rounded up to 16-byte alignment.
Small objects may span two lines. An object is live only when its header has been marked; every line it intersects is subsequently marked live.
The collector must not assume that an object occupies exactly one line.
Metadata is allocated separately from object storage.
Line metadata
One byte per line.
256 bytes per block.
A line is considered live when its metadata byte equals the current collection epoch.
During allocation, the relevant line metadata is also updated to reflect the current allocation epoch.
The collector uses line metadata to determine which regions of a block can be reused.
Importantly, line-level reclamation is conservative: a line containing even one live object cannot be reclaimed.
Block metadata
16 bytes per block.
struct BlockMeta {
u32 next;
u16 holes;
u16 marked_lines;
u8 state;
u8 generation;
u8 flags;
u8 age;
u32 owner;
};Block states:
enum class BlockState : u8 {
FREE,
ALLOCATING,
RECYCLABLE,
FULL,
EVAC_SOURCE,
EVAC_TARGET,
LOS_RESERVED
};generation identifies whether the block belongs to the
nursery or old generation.
owner identifies the mutator responsible for the block.
Unowned blocks use a reserved identifier.
Metadata reservation
At the default 64 GiB heap size:
Total: approximately 0.83% of the reserved heap.
struct Header {
u32 type_id;
u8 mark;
u8 flags;
u16 aux;
};
static_assert(sizeof(Header) == 8);Flags:
enum HeaderFlags : u8 {
PINNED = 1 << 0,
REMEMBERED = 1 << 1,
LARGE = 1 << 2
};The header is eight-byte aligned and accessed atomically when concurrent collector workers may inspect it.
The header has three logical states:
Forwarding replaces the complete 64-bit header with:
new_address | 1
The low bit is available because managed objects are at least 16-byte aligned.
A forwarded object must never be interpreted as a normal header.
The collector uses acquire/release operations when publishing and consuming forwarding pointers.
The runtime maintains a type descriptor table.
struct TypeDesc {
u32 size;
u16 pointer_count;
u16 flags;
const u32* pointer_offsets;
};Pointer offsets are relative to the beginning of the object.
For larger structures, descriptors may use compressed pointer-offset sequences or bitmaps.
Arrays contain their element type and length in their allocation metadata.
The collector must support:
All pointer fields contain exact managed object-base pointers.
The compiler and runtime must agree on the descriptor layout.
Each mutator owns a cache-line-aligned Mutator
structure.
struct Mutator {
void* cursor;
void* limit;
void* ocursor;
void* olimit;
void* nursery_cursor;
void* nursery_limit;
RootFrame* root_frame;
u32 thread_id;
u32 flags;
u8 poll;
u8 reserved[7];
};The normal allocation region uses the current block’s available lines.
The overflow allocator handles medium allocations.
The nursery allocator is used when generational mode is enabled.
The mutator structure is accessed through thread-local storage.
The common allocation path must be emitted directly by UQBE.
Conceptually:
inline void* alloc(Mutator& m, u32 size, u32 type) {
auto p = m.cursor;
auto n = static_cast<u8*>(p) + size;
if (n > m.limit)
return alloc_slow(m, size, type);
m.cursor = n;
store_header(p, type);
return p;
}The compiler supplies a compile-time object size whenever possible.
The fast path:
Target: approximately six machine instructions on x86-64, excluding any required header initialization.
The slow path follows this order:
Global block lists must use a concurrency-safe algorithm.
A block must have exactly one allocating owner at any given time.
All allocated object storage is zero-initialized.
Freshly committed pages are already zeroed by the operating system.
Reused holes are cleared when acquired.
Zeroing occurs outside the inline fast path.
The runtime may use architecture-specific vectorized clearing.
When acquiring a new hole, the allocator may prefetch 256 bytes ahead of the allocation cursor.
Prefetching must remain an optimization, not a correctness requirement.
Medium allocations use whole-line regions.
An allocation that cannot fit in the current hole must not consume unrelated remaining space.
Medium allocations are placed into dedicated multi-line regions or blocks obtained from the overflow allocator.
Objects larger than 8 KiB use the large object space (LOS).
LOS objects:
Large objects must not consume ordinary Immix blocks.
The collector uses parallel stop-the-world mark-region collection with opportunistic evacuation.
All collection workers operate against a stable heap.
Every mutator periodically checks its safepoint poll flag.
The compiler inserts polls:
The fast poll is a single conditional branch.
When a collection is requested:
Threads executing native code require special handling.
A thread may be excluded from the rendezvous only if it has entered a GC-safe native region and guarantees that it holds no unpinned managed pointers.
Otherwise, the collector must wait for it to reach a safepoint.
A native thread holding managed references must either:
Draft 0.1 · C++23 runtime · LLVM statepoint backend
Goals: precise, parallel, stop-the-world mark-region collector with opportunistic evacuation; the cheapest possible allocation (inline bump pointer); no write barrier; dense side metadata; predictable pauses for heaps up to tens of GiB.
Non-goals (v1): concurrent marking, conservative scanning, finalizers, interior pointers stored in the heap, pointer tagging.
Haze heap data is immutable (no mut), so an object can
only point to objects that existed before it. Old objects therefore
never point to young ones. This gives two things for free:
Any future mutable heap cell (Ref, lazy thunk update)
must go through haze_wb(obj), which sets a
REMEMBERED header bit and appends to a per-thread buffer.
Nothing else in the design changes.
One large PROT_NONE virtual reservation (default 64 GiB,
2 MiB aligned, MADV_HUGEPAGE), committed on demand. Block
lookup is a shift:
idx = (addr - heap_base) >> 15.
| Constant | Value | Notes |
|---|---|---|
| Granule / alignment | 16 B | all objects, minimum object 16 B |
| Line | 128 B | 8 granules |
| Block | 32 KiB | 256 lines |
| Small | ≤ 128 B | marks one line (+ implicit next line) |
| Medium | ≤ 8 KiB | marks every spanned line; uses overflow allocator |
| Large | > 8 KiB | large object space (LOS), never moved |
Side tables (separate reservation, never interleaved with objects):
state (free,
recyclable, full, evac-source, evac-target), holes,
marked_lines, age, next (32-bit
list link).Object header (8 B):
struct Header { // little-endian, 8 bytes
u32 type_id; // index into the type table
u8 mark; // == epoch when marked
u8 flags; // PINNED | REMEMBERED | LARGE
u16 aux; // e.g. small array length
}; // forwarded: whole word = (new_addr | 1)The type table entry holds size, a pointer count, and a
pointer bitmap (up to 62 words) or run-length offsets. Arrays carry
{elem_type_id, len} after the header. Heap fields hold base
pointers only.
Each mutator owns a Mutator struct (TLS,
initial-exec, cache-line aligned) holding two bump regions:
cursor/limit for the current hole and
ocursor/olimit for overflow (medium objects).
inline void* alloc(Mutator& m, u32 size, u32 type) { // size: constexpr, 16-aligned
auto p = m.cursor, n = p + size;
if (n > m.limit) [[unlikely]] return alloc_slow(m, size, type);
m.cursor = n;
store_header(p, type);
return p; // payload already zero
}The compiler emits this inline as IR (about 6 instructions). The slow path, in order:
countr_zero on the
movemask.Zeroing happens per hole at acquisition
(memset; fresh mmap pages are already zero).
Prefetch-for-write 256 B ahead of cursor when entering a
hole. Medium objects that don’t fit the hole go to the overflow
allocator, which uses whole free blocks, so holes are not burned.
IN_NATIVE
with their last Haze frame published, so the GC does not wait for
them.mark, followed by relaxed
line-mark stores.BUSY, copy into the thread’s evac block,
release-store the forwarding word; losers spin and follow it.MADV_FREE after a lag).A collection is triggered when free + recyclable blocks are exhausted and the growth budget is spent.
ptr addrspace(1).
Functions carry gc "statepoint-example", and the
RewriteStatepointsForGC pass converts calls to
gc.statepoint with gc.relocate /
gc.result. Derived pointers are handled by LLVM as (base,
derived) pairs.if (tls->poll) haze_gc_poll(). A guard-page poll is a
later optimization..llvm_stackmaps (v3)
once at startup into an open-addressing hash from return address to
record. Per statepoint record: skip the 3 leading constants and the
deopt operands, then read the (base, derived) location pairs. After
relocation, rewrite
derived = new_base + (derived - old_base).fixup-statepoint-caller-saved), so every root is a spill
slot."frame-pointer"="all" on every function). The caller’s SP
at a call site is callee_FP + 16; resolve
Indirect [SP + off] locations from that.@haze_alloc_slow with
allockind("alloc,zeroed"), allocsize(0) and
noalias return, so LLVM can delete dead allocations and
forward stores. Do escape analysis in the frontend and stack-allocate
non-escaping values.alloc_slow, poll) are ordinary statepoint
calls. On entry they record the caller’s FP and return address in
Mutator, so the collector can start walking.libhazert.a
built without LLVM headers, and it parses the stack-map format
itself.| Symbol | Purpose |
|---|---|
haze_alloc_slow(size, type_id) |
slow path allocation, may GC |
haze_alloc_large(size, type_id) |
LOS allocation |
haze_gc_poll() |
safepoint slow path |
haze_thread_attach/detach() |
register a mutator |
haze_native_enter/exit() |
publish frame, set IN_NATIVE |
haze_pin(obj) / haze_unpin(obj) |
set PINNED, for FFI |
haze_root_add/remove(slot*) |
global roots |
haze_wb(obj) |
only if mutable cells exist |
-fno-exceptions -fno-rtti, no libstdc++ allocation on
any GC path; the runtime owns its memory via mmap.constexpr for all layout constants. Use
std::countr_zero and std::bit_ceil for line
and block math.[[likely]]/[[unlikely]] and
[[assume]] (alignment) on hot paths;
std::unreachable() in impossible states.std::expected for OS failures;
std::start_lifetime_as for header and side-table views
where the toolchain supports it.alignas(std::hardware_destructive_interference_size) on
per-thread state and deques.Debug modes: HAZE_GC_STRESS=n (collect
every n allocations), poison freed lines (0xDD) and
ASan-poison them, a heap verifier run before and after every GC (every
reachable reference points into a live line, no dangling forwards, line
marks cover all live objects), and a deterministic seed for
work-stealing order.
| Milestone | Scope |
|---|---|
| M0 | Single-threaded, non-moving, full GC, statepoints and stack maps working |
| M1 | Parallel marking and sweep, SIMD hole finding |
| M2 | Opportunistic evacuation, pinning |
| M3 | Sticky minor GCs, no barrier |
| M4 | Tuning: huge pages, prefetch depth, NUMA-aware block caches |
A collector must never move an object while native code may still be dereferencing its old address.
Evacuation is opportunistic.
The collector examines fragmentation statistics from the previous cycle.
Candidate blocks are ranked by:
Blocks containing pinned objects may be excluded.
The collector selects blocks until their live data fits into the available evacuation target space.
Default target reserve:
Evacuation must be disabled when the available target capacity is insufficient.
Roots are obtained from:
No arbitrary register scanning is performed.
No arbitrary machine-stack scanning is performed.
The collector does not need to understand the machine register allocator.
Each collector worker owns a mark stack.
Stacks use 1K-entry chunks.
Workers use a Chase-Lev work-stealing deque.
An eight-entry prefetch FIFO may be used between popping a reference and scanning its object.
The marking procedure:
Object marking uses an atomic test-and-set or compare-and-exchange operation.
Line metadata updates must be atomic or otherwise synchronized between workers.
When an object belongs to an evacuation-source block:
BUSY.Other workers encountering BUSY wait until forwarding is
published.
Workers encountering a forwarded object follow its forwarding pointer.
Objects outside evacuation-source blocks are marked in place.
Every scanned reference slot is rewritten to the resolved address.
Root slots are also rewritten.
The collector must ensure that each object is scanned exactly once after its final address has been resolved.
Sweeping runs in parallel after marking and evacuation complete.
For each ordinary block:
Sweeping primarily operates on side metadata.
Object headers are not individually inspected during ordinary sweeping unless required for verification or block-specific processing.
Partially live lines are retained.
This is an intentional property of line-granularity reclamation.
The collector increments the major collection epoch after a successful full collection.
An epoch wrap requires clearing the affected metadata before reusing the epoch value.
The implementation must ensure that epoch reuse cannot cause stale marks to be interpreted as current marks.
LOS allocations are swept independently.
Unmarked objects are released.
Marked objects remain in place.
The target heap size is:
max(64 MiB, live_bytes * 1.5)
The multiplier is configurable.
The collector may retain surplus committed blocks for subsequent allocations.
Unused pages are released after a configurable retention period.
Generational collection is an extension of the primary Immix collector.
It relies on the immutable-object construction rule.
New objects are allocated into nursery blocks.
Objects in nursery blocks may reference:
Old-generation objects cannot reference nursery objects.
Blocks have a generation field.
A block is promoted as a unit.
This avoids introducing mixed-generation object tracking into the line allocator.
Minor collection:
Old-generation objects are not recursively scanned.
No remembered set is needed because old objects cannot reference nursery objects.
Minor collections do not evacuate objects.
Promotion happens at block granularity.
If a nursery block contains surviving objects, the entire block becomes old-generation storage.
Unmarked lines can be reused according to normal Immix reclamation rules.
This may retain some dead space when live and dead objects share lines.
That trade-off is intentional.
Full collection:
A full collection is triggered when:
Generational mode is optional and should not complicate the initial implementation.
This replaces the entire LLVM integration section.
UQBE is responsible for generating machine code and ordinary calls into the Haze runtime.
The collector does not depend on LLVM.
The compilation pipeline is:
Haze source
|
v
Haze frontend
|
v
Haze IR
|
+---- Type descriptors
|
+---- Managed-pointer liveness
|
+---- Safepoint identification
|
+---- Root-frame generation
|
v
UQBE IL
|
v
UQBE backend
|
v
Native object code
|
v
Haze linker
|
v
Executable + Haze runtime
UQBE continues to handle:
The frontend handles GC-specific correctness.
The initial implementation requires no GC-specific UQBE IL instructions.
All collector operations are represented through ordinary function calls and stack-slot operations.
This is deliberate.
QBE’s existing scalar IL is sufficient for the required integration.
Architecture-specific optimizations remain inside UQBE or the C++ runtime.
Instead of parsing LLVM stack maps or attempting to reconstruct roots from arbitrary machine instructions, Haze uses explicit shadow-stack frames.
Each managed function that can participate in collection receives a compiler-generated root frame.
Conceptually:
struct RootFrame {
RootFrame* previous;
const RootMap* descriptor;
void** slots;
};The descriptor identifies the managed-reference slots.
The frame is linked into the current mutator’s root chain.
On function entry:
haze_root_enter(&frame);On function exit:
haze_root_leave(&frame);The runtime maintains the root-frame chain in thread-local mutator state.
The frame must remain valid for the complete duration of its registration.
Every managed reference that must survive a safepoint has an associated root slot.
The compiler emits stores into those slots before a potentially collecting call.
After the call, relocated references are reloaded into their corresponding SSA values.
Conceptually:
store managed_pointer, root_slot
call haze_alloc_slow
managed_pointer = load root_slot
The runtime updates the root slots during evacuation.
This guarantees that register allocation cannot accidentally hide a managed pointer from the collector.
The compiler must calculate liveness at each safepoint and ensure every live managed reference is represented.
Dead references need not be published.
Root maps are generated by the Haze frontend.
A descriptor contains:
A static descriptor is emitted into the executable’s read-only data section.
The runtime receives a pointer to this descriptor when entering a root frame.
There is no runtime stack-map parser.
There is no return-address hash table.
There is no LLVM .llvm_stackmaps section.
Root slots are represented using ordinary UQBE stack allocation.
For example, conceptually:
%root =l alloc8 8
storel %object, %root
The frontend must ensure that root slots are not optimized away or invalidated before a collection.
This requires treating the root-frame registration and root-slot accesses as observable memory operations.
If necessary, the frontend should introduce explicit runtime calls around safepoints to prevent invalid compiler transformations.
The UQBE optimizer must preserve the required memory dependencies.
The frontend inserts ordinary calls to:
haze_gc_poll()Polls are required at:
The fast path reads a thread-local poll flag and returns immediately when no collection is requested.
A guard-page implementation may be introduced later.
Every function that may trigger collection must be identified by the frontend.
The compiler must distinguish:
A function that calls another potentially collecting function must preserve all live managed references across that call.
This is ordinary interprocedural effect propagation.
Managed allocations use two paths.
Inline allocation
The frontend emits direct cursor/limit operations against the current mutator.
The generated code initializes the object header and returns the managed pointer.
Slow allocation
The frontend emits an ordinary call:
extern "C" void* haze_alloc_slow(
u32 size,
u32 type_id
);The function may collect.
All live managed references must be published before entering it.
Unlike LLVM, UQBE does not need allocation-specific attributes or
allockind metadata.
Escape analysis remains a frontend optimization.
Non-escaping objects may be stack-allocated when their lifetimes and semantics permit it.
Managed references stored in the heap and shadow stack are always object-base pointers.
Interior pointers are not permitted to survive safepoints.
If the compiler generates a temporary derived pointer into an object payload, it must either:
The collector never needs to relocate arbitrary interior pointers.
The runtime is compiled independently from UQBE.
The frontend and runtime agree on the platform’s C ABI.
UQBE is responsible for selecting the correct target calling convention.
The runtime must support the calling conventions implemented by the corresponding UQBE target, including:
The collector must not depend on a particular register assignment or machine stack layout.
The collector runtime is a static library:
libhazert.a
The executable links against it using the normal Haze linking pipeline.
The runtime does not link against UQBE.
UQBE does not link against the collector.
This preserves the separation between compiler, backend, and runtime.
The runtime exposes a small C-compatible interface.
| Symbol | Purpose |
|---|---|
haze_alloc_slow(size, type_id) |
Slow managed allocation |
haze_alloc_large(size, type_id) |
LOS allocation |
haze_gc_poll() |
Safepoint poll |
haze_gc_collect() |
Explicit collection request |
haze_thread_attach() |
Register a mutator |
haze_thread_detach() |
Unregister a mutator |
haze_root_enter(frame) |
Register a shadow-stack frame |
haze_root_leave(frame) |
Unregister a shadow-stack frame |
haze_root_add(slot) |
Register a global root |
haze_root_remove(slot) |
Remove a global root |
haze_native_enter() |
Enter a GC-safe native region |
haze_native_exit() |
Leave a GC-safe native region |
haze_pin(obj) |
Pin a managed object |
haze_unpin(obj) |
Unpin a managed object |
haze_wb(obj, slot, value) |
Future mutable-object barrier |
All public entry points use C linkage.
The runtime must document which functions may trigger collection.
The runtime is built independently from the compiler.
Recommended flags:
-std=c++23
-fno-exceptions
-fno-rtti
No LLVM headers or libraries are required.
The runtime must not use general-purpose standard-library allocation on collector-critical paths.
Memory ownership is handled through platform virtual-memory primitives.
The runtime uses:
mmap / munmap on Linux.VirtualAlloc / VirtualFree on
Windows.mmap / munmap on macOS.Platform-specific functionality is isolated behind a small memory abstraction.
OS failures are reported through an explicit error mechanism.
std::expected may be used for non-critical
initialization and configuration paths.
All layout constants are constexpr.
Use:
std::countr_zero for bit operations.std::bit_ceil for capacity calculations.std::memcpy for object copying.alignas(std::hardware_destructive_interference_size)
for per-thread state.Use std::start_lifetime_as where supported and
appropriate.
Do not assume that C++ object lifetime rules automatically permit arbitrary typed access to reserved virtual memory.
SIMD is implemented inside the C++ runtime.
The initial abstraction supports:
SIMD is used for:
UQBE does not need first-class vector instructions for the initial collector.
Architecture-specific SIMD code must be tested against the scalar implementation.
The collector uses:
The implementation must avoid ABA problems in global block lists.
Thread-local allocation state must be isolated to avoid false sharing.
Environment variables:
HAZE_GC_STRESS=1
HAZE_GC_VERIFY=1
HAZE_GC_POISON=1
HAZE_GC_LOG=1
HAZE_GC_DISABLE_EVAC=1
HAZE_GC_DISABLE_GENERATIONAL=1
HAZE_GC_STRESS forces collection after a configurable
number of allocations.
HAZE_GC_VERIFY enables heap verification before and
after collection.
HAZE_GC_POISON poisons reclaimed memory.
HAZE_GC_LOG prints collection statistics.
The verifier checks:
Tests must cover:
Development builds should support:
ASan poisoning must be coordinated with the allocator and collector.
TSan builds should exercise concurrent marking, forwarding, and block ownership.
A configurable deterministic seed controls work-stealing order and stress-test scheduling.
This allows GC failures to be reproduced more reliably.
These are engineering targets, not guaranteed performance claims.
| Metric | Target |
|---|---|
| Inline allocation | Approximately 6 instructions |
| Small-object allocation | No locks |
| Fast safepoint poll | One predictable branch |
| Side metadata | Approximately 0.83% of reserved heap |
| Marking | Parallel |
| Sweeping | Parallel |
| Evacuation | Opportunistic |
| Write barriers | None for immutable objects |
| Runtime LLVM dependency | None |
| Stack-map parsing | None |
| Register scanning | None |
The most important optimization priority is maintaining a cheap allocation path.
Collection throughput is secondary to avoiding unnecessary overhead on ordinary object creation.
| Milestone | Scope |
|---|---|
| M0 | Single-threaded, non-moving full Immix collector |
| M1 | UQBE shadow-stack integration and compiler-generated root maps |
| M2 | Safepoint rendezvous and multi-threaded allocation |
| M3 | Parallel marking and sweeping |
| M4 | Opportunistic evacuation and forwarding |
| M5 | Pinning and native interoperation |
| M6 | Sticky generational collection |
| M7 | Huge pages, prefetching, SIMD tuning, NUMA-aware block caches |
Implement the heap reservation, block allocator, type descriptors, marking, and sweeping.
No evacuation or generational mode.
Implement root-frame generation in the Haze frontend.
Generate ordinary UQBE stack-slot operations and calls to the runtime.
Verify that a managed reference survives a collection across nested function calls.
This milestone establishes the compiler/runtime contract.
Implement mutator registration, safepoint rendezvous, thread-local allocation, and concurrent collector workers.
Introduce work stealing, parallel tracing, parallel sweeping, and SIMD line discovery.
Implement forwarding, destination allocation, reference rewriting, and fragmentation-driven evacuation.
Implement pinning, native handles, native-region registration, and safe transitions between managed and native execution.
Introduce nursery blocks, sticky marking, block promotion, and minor collection.
Optimize memory commitment, huge-page usage, NUMA placement, prefetching, and allocator locality.
The following properties are mandatory:
The collector is a runtime subsystem, not a compiler backend feature. UQBE only needs to generate the correct allocation operations, root-frame accesses, and safepoint calls.