navid/haze / commit

c9bc19ce0569

Navid M <navidmomtahen@gmail.com> · 2026-12-02

parents: 221433b37405

Browse files at this commit · Download source

all: rebranding
--- /dev/null+++ b/docs/HAZE_IMMIX_COLLECTOR_SPECIFICATION.md@@ -0,0 +1,1374 @@+# Haze Immix Collector Specification++*Draft 0.2 · C++23 runtime · UQBE backend*++## 1. Goals and non-goals++### Goals++- Precise, parallel, stop-the-world mark-region garbage collection.+- Opportunistic evacuation of fragmented blocks.+- Extremely cheap allocation through inline thread-local bump pointers.+- No write barrier for immutable heap objects.+- Dense side metadata with predictable memory overhead.+- Bounded allocation and collection overhead for heaps reaching tens of GiB.+- Native integration with UQBE without introducing an LLVM dependency.+- Portable runtime implementation across supported UQBE targets.++### Non-goals (v1)++- Concurrent marking.+- Conservative scanning.+- Finalizers.+- Interior pointers stored in heap objects.+- Pointer tagging exposed to Haze programs.+- Incremental collection.+- Concurrent evacuation.+- General-purpose weak references.++### Design principles++1. The compiler owns managed-pointer correctness.+2. The runtime owns heap management, tracing, evacuation, and reclamation.+3. UQBE generates ordinary machine-code calls, not GC-specific LLVM-style intrinsics.+4. Managed references are always identifiable as exact object-base pointers.+5. Every potential collection point has a compiler-generated root map.+6. The collector never needs to inspect arbitrary machine registers.++---++## 2. The key bet: immutability removes the write barrier++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:++- Older objects may reference older objects.+- Younger objects may reference older objects.+- Younger objects may reference younger objects created before them.+- Older objects cannot reference younger objects.++This provides two important properties:++- No write barrier is needed.+- No remembered set is needed for generational collection.++### Compiler enforcement++The compiler must guarantee that heap fields cannot be modified after object publication.++Object construction follows this sequence:++1. Allocate zero-initialized storage.+2. Initialize all scalar fields.+3. Initialize all managed references.+4. Publish the object.+5. Never modify its fields again.++The collector is permitted to modify object storage internally when rewriting references during evacuation.++### Future mutable objects++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:++1. Update the reference.+2. Set the `REMEMBERED` header flag.+3. Append the object to a per-thread remembered buffer.++Mutable objects must not bypass this API.++This is not required by v1.++---++## 3. Heap layout++### 3.1 Virtual reservation++The collector reserves one large contiguous virtual address range.++Default configuration:++- Reservation: 64 GiB.+- Alignment: 2 MiB.+- Block size: 32 KiB.+- Commitment: on demand.+- Huge pages: opportunistic.+- Unused memory: released or reclaimed using platform-specific virtual-memory operations.++The heap uses a single base address:++`heap_base`++Block lookup is a shift:++```cpp+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.++### 3.2 Object layout constants++| 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.++### 3.3 Side metadata++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.++```cpp+struct BlockMeta {+    u32 next;+    u16 holes;+    u16 marked_lines;+    u8  state;+    u8  generation;+    u8  flags;+    u8  age;+    u32 owner;+};+```++Block states:++```cpp+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:++- Line metadata: 512 MiB.+- Block metadata: 32 MiB.++Total: approximately 0.83% of the reserved heap.++### 3.4 Object header++```cpp+struct Header {+    u32 type_id;+    u8  mark;+    u8  flags;+    u16 aux;+};++static_assert(sizeof(Header) == 8);+```++Flags:++```cpp+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:++- Normal object header.+- Busy evacuation state.+- Forwarded object.++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.++### 3.5 Type descriptors++The runtime maintains a type descriptor table.++```cpp+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:++- Fixed-size structures.+- Arrays of scalar values.+- Arrays of managed references.+- Structures containing mixed scalar and reference fields.++All pointer fields contain exact managed object-base pointers.++The compiler and runtime must agree on the descriptor layout.++---++## 4. Allocation++### 4.1 Mutator state++Each mutator owns a cache-line-aligned `Mutator` structure.++```cpp+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.++### 4.2 Inline allocation++The common allocation path must be emitted directly by UQBE.++Conceptually:++```cpp+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:++- Performs no locking.+- Performs no system calls.+- Does not allocate auxiliary metadata.+- Does not call the runtime.+- Does not perform a collection.++Target: approximately six machine instructions on x86-64, excluding any required header initialization.++### 4.3 Slow allocation++The slow path follows this order:++1. Find another available hole in the current block.+2. Acquire a recyclable block from the mutator's local cache.+3. Refill the cache from global block lists.+4. Acquire a free block.+5. Acquire an additional committed block if permitted by the growth budget.+6. Trigger collection.+7. Retry allocation.++Global block lists must use a concurrency-safe algorithm.++A block must have exactly one allocating owner at any given time.++### 4.4 Zero initialization++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.++### 4.5 Prefetching++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.++### 4.6 Medium objects++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.++### 4.7 Large object space++Objects larger than 8 KiB use the large object space (LOS).++LOS objects:++- Are never evacuated.+- Have separate allocation metadata.+- Participate in normal marking.+- Are reclaimed during LOS sweeping.+- Are independently committed and released.++Large objects must not consume ordinary Immix blocks.++---++## 5. Collection++The collector uses parallel stop-the-world mark-region collection with opportunistic evacuation.++All collection workers operate against a stable heap.++### 5.1 Safepoint rendezvous++Every mutator periodically checks its safepoint poll flag.++The compiler inserts polls:++- At loop back-edges.+- At recursive function entry.+- At allocation slow paths.+- At calls that may trigger collection.++The fast poll is a single conditional branch.++When a collection is requested:++1. The collector sets the global collection request.+2. Mutators observe their poll flags.+3. Each mutator publishes its active root frame.+4. Mutators enter a parked state.+5. The collector begins once all required mutators are safe.++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:++# Haze Immix Collector Specification++*Draft 0.1 · C++23 runtime · LLVM statepoint backend*++## 1. Goals and non-goals++**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.++## 2. The key bet: immutability removes the barrier++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:++- no write barrier and no remembered set;+- sticky-mark-bit minor collections (section 6) that trace only from roots and stop at any already-marked object.++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.++## 3. Heap layout++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):++- *Line marks:* 1 byte per line (256 B per block). A line is live iff its byte equals the current epoch.+- *Block metadata:* 16 B per block: `state` (free, recyclable, full, evac-source, evac-target), `holes`, `marked_lines`, `age`, `next` (32-bit list link).++**Object header (8 B):**++```cpp+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.++## 4. Allocation++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).++```cpp+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:++1. Next hole in the current block, found with SIMD compare of line bytes against the epoch, then `countr_zero` on the movemask.+2. Next recyclable block from the thread's local cache, refilled in batches of 4 from the global lock-free lists.+3. A free block.+4. Trigger a collection.++**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.++## 5. Collection (parallel, stop-the-world)++1. **Rendezvous:** polls and handshakes bring mutators to safepoints. Threads in native code are marked `IN_NATIVE` with their last Haze frame published, so the GC does not wait for them.+2. **Choose evacuation set** (only if fragmented): from last cycle's histogram, take blocks with the most holes and least live data, until their live bytes fit in the reserved target space (≥ 2% of heap, minimum 8 blocks).+3. **Roots:** stack maps (section 7), the global root table, and the pinned set.+4. **Trace + evacuate in one pass.** Per-thread mark stacks (1K-entry chunks) with Chase-Lev work stealing, and an 8-entry prefetch FIFO between popping a reference and scanning the object.+   - Marking is test-then-CAS on `mark`, followed by relaxed line-mark stores.+   - If the object lies in an evac-source block and is not pinned: CAS the header to `BUSY`, copy into the thread's evac block, release-store the forwarding word; losers spin and follow it.+   - Every visited slot is rewritten in place with the new address.+5. **Sweep:** parallel over blocks, touching only the line-mark table (0.8% of heap). Count live lines with SIMD, reclassify the block, splice into per-thread lists, then merge. No object is touched. The epoch increments instead of clearing marks (clear only on wrap at 255).+6. **LOS sweep**, and release of surplus blocks (`MADV_FREE` after a lag).+7. **Resize:** target heap = max(64 MiB, live × 1.5), tunable.++A collection is triggered when free + recyclable blocks are exhausted and the growth budget is spent.++## 6. Generational mode (sticky Immix, v3)++- **Minor GC:** do not bump the epoch. Trace from roots and stop at any marked object. Survivors stay marked (old) and unmarked lines are reusable. No remembered set, no barrier.+- **Full GC:** bump the epoch, which implicitly unmarks everything, and run the normal cycle with evacuation.+- Minor GCs never evacuate. Trigger a full GC when old-generation growth exceeds a threshold or fragmentation does.++## 7. LLVM integration++- **Managed pointers** are `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.+- **Safepoint polls:** the frontend inserts them at loop back-edges and on entry to recursive functions: `if (tls->poll) haze_gc_poll()`. A guard-page poll is a later optimization.+- **Stack maps:** parse `.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)`.+- **Roots are stack slots only.** Keep the default of no GC pointers in callee-saved registers (`fixup-statepoint-caller-saved`), so every root is a spill slot.+- **Stack walking:** frame-pointer chain (`"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.+- **Allocation calls:** declare `@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.+- **Runtime entry points that can GC** (`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.+- **Dev builds:** LLVM is linked dynamically into the *compiler only*. The runtime is a static `libhazert.a` built without LLVM headers, and it parses the stack-map format itself.+- **Pin the LLVM version.** The statepoint intrinsics are still documented as experimental.++## 8. Runtime ABI++| 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 |++## 9. C++23 coding rules++- `-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.+- SIMD behind one small abstraction with AVX2, NEON, and scalar paths; verify all three agree in tests.++## 10. Verification and milestones++**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 |+++- Pin those objects.+- Use registered handles.+- Leave the native region before collection proceeds.++A collector must never move an object while native code may still be dereferencing its old address.++### 5.2 Evacuation-set selection++Evacuation is opportunistic.++The collector examines fragmentation statistics from the previous cycle.++Candidate blocks are ranked by:++1. Lowest live-line ratio.+2. Highest number of reusable holes.+3. Lowest evacuation cost.+4. Lowest number of pinned objects.++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:++- At least 2% of the heap.+- At least eight blocks.++Evacuation must be disabled when the available target capacity is insufficient.++### 5.3 Root discovery++Roots are obtained from:++1. Compiler-generated shadow-stack frames.+2. Global root registrations.+3. Registered native handles.+4. Pinned object registrations.+5. Runtime-owned roots.++No arbitrary register scanning is performed.++No arbitrary machine-stack scanning is performed.++The collector does not need to understand the machine register allocator.++### 5.4 Parallel marking++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:++1. Validate the object pointer.+2. Check its header.+3. Determine whether it has already been marked.+4. Atomically claim it if necessary.+5. Mark all intersecting lines.+6. Scan its pointer fields.+7. Push discovered references onto the worker's mark stack.++Object marking uses an atomic test-and-set or compare-and-exchange operation.++Line metadata updates must be atomic or otherwise synchronized between workers.++### 5.5 Evacuation++When an object belongs to an evacuation-source block:++1. Check whether it is pinned.+2. Atomically transition its header to `BUSY`.+3. Allocate destination storage.+4. Copy the object.+5. Publish the forwarding pointer with release semantics.+6. Return the destination address.++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.++### 5.6 Sweeping++Sweeping runs in parallel after marking and evacuation complete.++For each ordinary block:++1. Count live lines.+2. Identify contiguous dead-line regions.+3. Calculate the remaining hole count.+4. Update block state.+5. Reclassify the block.+6. Add reusable blocks or holes to the appropriate allocation lists.++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.++### 5.7 Epoch management++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.++### 5.8 LOS sweeping++LOS allocations are swept independently.++Unmarked objects are released.++Marked objects remain in place.++### 5.9 Heap resizing++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.++---++## 6. Generational mode (sticky Immix, v3)++Generational collection is an extension of the primary Immix collector.++It relies on the immutable-object construction rule.++### 6.1 Generational allocation++New objects are allocated into nursery blocks.++Objects in nursery blocks may reference:++- Earlier nursery objects.+- Existing old-generation objects.++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.++### 6.2 Minor collection++Minor collection:++1. Stops mutators.+2. Enumerates roots.+3. Traces nursery references.+4. Stops traversal at old-generation objects.+5. Marks live nursery objects.+6. Reclaims dead nursery lines.+7. Promotes surviving nursery blocks.+8. Reinitializes nursery allocation state.++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.++### 6.3 Promotion++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.++### 6.4 Full collection++Full collection:++- Advances the major epoch.+- Traces all reachable objects.+- Reclaims both generations.+- Performs normal evacuation.+- Promotes surviving objects into the old generation.++### 6.5 Collection triggers++A full collection is triggered when:++- Old-generation growth exceeds a configured threshold.+- Fragmentation exceeds a threshold.+- The heap growth budget is exhausted.+- A configurable number of minor collections have elapsed.++Generational mode is optional and should not complicate the initial implementation.++---++## 7. UQBE integration++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.++### 7.1 Backend model++The compilation pipeline is:++```text+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:++- SSA lowering.+- Register allocation.+- Instruction selection.+- Calling-convention lowering.+- Stack-frame generation.+- Native code emission.++The frontend handles GC-specific correctness.++### 7.2 No special GC instructions++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.++### 7.3 Shadow-stack root frames++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:++```cpp+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:++```cpp+haze_root_enter(&frame);+```++On function exit:++```cpp+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.++### 7.4 Root slots++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:++```text+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.++### 7.5 Root-map descriptors++Root maps are generated by the Haze frontend.++A descriptor contains:++- Number of root slots.+- Slot offsets or indices.+- Managed-reference type information where required.+- Frame size.+- Optional debugging metadata.++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.++### 7.6 UQBE stack slots++Root slots are represented using ordinary UQBE stack allocation.++For example, conceptually:++```text+%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.++### 7.7 Safepoint polls++The frontend inserts ordinary calls to:++```cpp+haze_gc_poll()+```++Polls are required at:++- Loop back-edges.+- Recursive function entry.+- Potentially unbounded execution paths.+- Allocation slow paths.+- Explicit runtime safepoints.++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.++### 7.8 Calls that may collect++Every function that may trigger collection must be identified by the frontend.++The compiler must distinguish:++- Functions that cannot collect.+- Functions that may collect.+- Functions that enter native code.+- Functions that allocate managed objects.++A function that calls another potentially collecting function must preserve all live managed references across that call.++This is ordinary interprocedural effect propagation.++### 7.9 Allocation lowering++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:++```cpp+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.++### 7.10 Derived pointers++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:++- Recompute it after the safepoint using the relocated base pointer.+- Preserve the base pointer and byte offset, then reconstruct the derived pointer.++The collector never needs to relocate arbitrary interior pointers.++### 7.11 Native ABI++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:++- System V AMD64.+- Microsoft x64.+- AArch64 platform ABIs.++The collector must not depend on a particular register assignment or machine stack layout.++### 7.12 Object files and linking++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.++---++## 8. Runtime ABI++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.++---++## 9. C++23 runtime implementation++### 9.1 Compilation++The runtime is built independently from the compiler.++Recommended flags:++```text+-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.++### 9.2 Memory management++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.++### 9.3 Layout++All layout constants are `constexpr`.++Use:++- `std::countr_zero` for bit operations.+- `std::bit_ceil` for capacity calculations.+- `std::memcpy` for object copying.+- Explicit atomic operations for concurrent metadata.+- `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.++### 9.4 SIMD++SIMD is implemented inside the C++ runtime.++The initial abstraction supports:++- AVX2.+- NEON.+- Scalar fallback.++SIMD is used for:++- Line metadata scanning.+- Hole discovery.+- Zeroing.+- Live-line counting.+- Selected bitmap operations.++UQBE does not need first-class vector instructions for the initial collector.++Architecture-specific SIMD code must be tested against the scalar implementation.++### 9.5 Concurrency++The collector uses:++- Atomic block ownership.+- Atomic object-marking state.+- Atomic forwarding publication.+- Parallel work-stealing queues.+- Stop-the-world synchronization.++The implementation must avoid ABA problems in global block lists.++Thread-local allocation state must be isolated to avoid false sharing.++---++## 10. Verification and testing++### 10.1 Debug modes++Environment variables:++```text+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.++### 10.2 Heap verification++The verifier checks:++- Every reachable reference points to a valid managed object.+- Every reachable object has a valid type descriptor.+- Every live object intersects appropriately marked lines.+- No object contains an invalid managed reference.+- No forwarded object contains an invalid forwarding address.+- No two mutators own the same allocation block.+- No live pinned object has moved.+- No evacuated source block is released while references to it remain.+- No root frame references invalid stack storage.++### 10.3 Stress testing++Tests must cover:++- Allocation without collection.+- Repeated full collections.+- Collection during recursive execution.+- Collection during nested function calls.+- Objects containing references.+- Arrays of references.+- Objects spanning multiple lines.+- Medium and large allocations.+- Fragmented heaps.+- Multiple mutators.+- Concurrent marking workers.+- Evacuation races.+- Pinning and unpinning.+- Native calls.+- Thread attachment and detachment.+- Heap exhaustion.+- Epoch wraparound.+- Generational promotion.+- Dead objects sharing lines with live objects.++### 10.4 Sanitizers++Development builds should support:++- AddressSanitizer.+- UndefinedBehaviorSanitizer.+- ThreadSanitizer.++ASan poisoning must be coordinated with the allocator and collector.++TSan builds should exercise concurrent marking, forwarding, and block ownership.++### 10.5 Determinism++A configurable deterministic seed controls work-stealing order and stress-test scheduling.++This allows GC failures to be reproduced more reliably.++---++## 11. Performance targets++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.++---++## 12. Implementation milestones++| 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 |++### M0 — Basic collector++Implement the heap reservation, block allocator, type descriptors, marking, and sweeping.++No evacuation or generational mode.++### M1 — UQBE integration++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.++### M2 — Multithreading++Implement mutator registration, safepoint rendezvous, thread-local allocation, and concurrent collector workers.++### M3 — Parallel collection++Introduce work stealing, parallel tracing, parallel sweeping, and SIMD line discovery.++### M4 — Evacuation++Implement forwarding, destination allocation, reference rewriting, and fragmentation-driven evacuation.++### M5 — Native interoperation++Implement pinning, native handles, native-region registration, and safe transitions between managed and native execution.++### M6 — Generational collection++Introduce nursery blocks, sticky marking, block promotion, and minor collection.++### M7 — Tuning++Optimize memory commitment, huge-page usage, NUMA placement, prefetching, and allocator locality.++---++## 13. Final architectural constraints++The following properties are mandatory:++1. The runtime must not depend on LLVM.+2. UQBE must not require LLVM-style statepoint support.+3. All managed roots must be explicitly published.+4. All heap references must be precise object-base pointers.+5. No managed pointer may remain hidden in an untracked register across a safepoint.+6. No object may be moved while native code can still dereference its old address.+7. No old-generation object may acquire a reference to a nursery object.+8. Allocation blocks must have exclusive mutator ownership.+9. Evacuation must never release a source block before all references have been rewritten.+10. The normal allocation path must remain independent of collector synchronization.++**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.**--- a/docs/XYZ_IMMIX_COLLECTOR_SPECIFICATION.md+++ /dev/null@@ -1,1372 +0,0 @@-# xyz Immix Collector Specification--*Draft 0.2 · C++23 runtime · UQBE backend*--## 1. Goals and non-goals--### Goals--- Precise, parallel, stop-the-world mark-region garbage collection.-- Opportunistic evacuation of fragmented blocks.-- Extremely cheap allocation through inline thread-local bump pointers.-- No write barrier for immutable heap objects.-- Dense side metadata with predictable memory overhead.-- Bounded allocation and collection overhead for heaps reaching tens of GiB.-- Native integration with UQBE without introducing an LLVM dependency.-- Portable runtime implementation across supported UQBE targets.--### Non-goals (v1)--- Concurrent marking.-- Conservative scanning.-- Finalizers.-- Interior pointers stored in heap objects.-- Pointer tagging exposed to xyz programs.-- Incremental collection.-- Concurrent evacuation.-- General-purpose weak references.--### Design principles--1. The compiler owns managed-pointer correctness.-2. The runtime owns heap management, tracing, evacuation, and reclamation.-3. UQBE generates ordinary machine-code calls, not GC-specific LLVM-style intrinsics.-4. Managed references are always identifiable as exact object-base pointers.-5. Every potential collection point has a compiler-generated root map.-6. The collector never needs to inspect arbitrary machine registers.-------## 2. The key bet: immutability removes the write barrier--xyz 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:--- Older objects may reference older objects.-- Younger objects may reference older objects.-- Younger objects may reference younger objects created before them.-- Older objects cannot reference younger objects.--This provides two important properties:--- No write barrier is needed.-- No remembered set is needed for generational collection.--### Compiler enforcement--The compiler must guarantee that heap fields cannot be modified after object publication.--Object construction follows this sequence:--1. Allocate zero-initialized storage.-2. Initialize all scalar fields.-3. Initialize all managed references.-4. Publish the object.-5. Never modify its fields again.--The collector is permitted to modify object storage internally when rewriting references during evacuation.--### Future mutable objects--If xyz eventually introduces mutable heap cells, such as `Ref` or lazy thunk updates, they must use an explicit mutation API:--`xyz_wb(obj, slot, value)`--This operation will:--1. Update the reference.-2. Set the `REMEMBERED` header flag.-3. Append the object to a per-thread remembered buffer.--Mutable objects must not bypass this API.--This is not required by v1.-------## 3. Heap layout--### 3.1 Virtual reservation--The collector reserves one large contiguous virtual address range.--Default configuration:--- Reservation: 64 GiB.-- Alignment: 2 MiB.-- Block size: 32 KiB.-- Commitment: on demand.-- Huge pages: opportunistic.-- Unused memory: released or reclaimed using platform-specific virtual-memory operations.--The heap uses a single base address:--`heap_base`--Block lookup is a shift:--```cpp-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.--### 3.2 Object layout constants--| 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.--### 3.3 Side metadata--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.--```cpp-struct BlockMeta {-    u32 next;-    u16 holes;-    u16 marked_lines;-    u8  state;-    u8  generation;-    u8  flags;-    u8  age;-    u32 owner;-};-```--Block states:--```cpp-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:--- Line metadata: 512 MiB.-- Block metadata: 32 MiB.--Total: approximately 0.83% of the reserved heap.--### 3.4 Object header--```cpp-struct Header {-    u32 type_id;-    u8  mark;-    u8  flags;-    u16 aux;-};--static_assert(sizeof(Header) == 8);-```--Flags:--```cpp-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:--- Normal object header.-- Busy evacuation state.-- Forwarded object.--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.--### 3.5 Type descriptors--The runtime maintains a type descriptor table.--```cpp-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:--- Fixed-size structures.-- Arrays of scalar values.-- Arrays of managed references.-- Structures containing mixed scalar and reference fields.--All pointer fields contain exact managed object-base pointers.--The compiler and runtime must agree on the descriptor layout.-------## 4. Allocation--### 4.1 Mutator state--Each mutator owns a cache-line-aligned `Mutator` structure.--```cpp-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.--### 4.2 Inline allocation--The common allocation path must be emitted directly by UQBE.--Conceptually:--```cpp-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:--- Performs no locking.-- Performs no system calls.-- Does not allocate auxiliary metadata.-- Does not call the runtime.-- Does not perform a collection.--Target: approximately six machine instructions on x86-64, excluding any required header initialization.--### 4.3 Slow allocation--The slow path follows this order:--1. Find another available hole in the current block.-2. Acquire a recyclable block from the mutator's local cache.-3. Refill the cache from global block lists.-4. Acquire a free block.-5. Acquire an additional committed block if permitted by the growth budget.-6. Trigger collection.-7. Retry allocation.--Global block lists must use a concurrency-safe algorithm.--A block must have exactly one allocating owner at any given time.--### 4.4 Zero initialization--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.--### 4.5 Prefetching--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.--### 4.6 Medium objects--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.--### 4.7 Large object space--Objects larger than 8 KiB use the large object space (LOS).--LOS objects:--- Are never evacuated.-- Have separate allocation metadata.-- Participate in normal marking.-- Are reclaimed during LOS sweeping.-- Are independently committed and released.--Large objects must not consume ordinary Immix blocks.-------## 5. Collection--The collector uses parallel stop-the-world mark-region collection with opportunistic evacuation.--All collection workers operate against a stable heap.--### 5.1 Safepoint rendezvous--Every mutator periodically checks its safepoint poll flag.--The compiler inserts polls:--- At loop back-edges.-- At recursive function entry.-- At allocation slow paths.-- At calls that may trigger collection.--The fast poll is a single conditional branch.--When a collection is requested:--1. The collector sets the global collection request.-2. Mutators observe their poll flags.-3. Each mutator publishes its active root frame.-4. Mutators enter a parked state.-5. The collector begins once all required mutators are safe.--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:# xyz Immix Collector Specification--*Draft 0.1 · C++23 runtime · LLVM statepoint backend*--## 1. Goals and non-goals--**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.--## 2. The key bet: immutability removes the barrier--xyz 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:--- no write barrier and no remembered set;-- sticky-mark-bit minor collections (section 6) that trace only from roots and stop at any already-marked object.--Any future mutable heap cell (`Ref`, lazy thunk update) must go through `xyz_wb(obj)`, which sets a `REMEMBERED` header bit and appends to a per-thread buffer. Nothing else in the design changes.--## 3. Heap layout--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):--- *Line marks:* 1 byte per line (256 B per block). A line is live iff its byte equals the current epoch.-- *Block metadata:* 16 B per block: `state` (free, recyclable, full, evac-source, evac-target), `holes`, `marked_lines`, `age`, `next` (32-bit list link).--**Object header (8 B):**--```cpp-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.--## 4. Allocation--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).--```cpp-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:--1. Next hole in the current block, found with SIMD compare of line bytes against the epoch, then `countr_zero` on the movemask.-2. Next recyclable block from the thread's local cache, refilled in batches of 4 from the global lock-free lists.-3. A free block.-4. Trigger a collection.--**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.--## 5. Collection (parallel, stop-the-world)--1. **Rendezvous:** polls and handshakes bring mutators to safepoints. Threads in native code are marked `IN_NATIVE` with their last Xyz frame published, so the GC does not wait for them.-2. **Choose evacuation set** (only if fragmented): from last cycle's histogram, take blocks with the most holes and least live data, until their live bytes fit in the reserved target space (≥ 2% of heap, minimum 8 blocks).-3. **Roots:** stack maps (section 7), the global root table, and the pinned set.-4. **Trace + evacuate in one pass.** Per-thread mark stacks (1K-entry chunks) with Chase-Lev work stealing, and an 8-entry prefetch FIFO between popping a reference and scanning the object.-   - Marking is test-then-CAS on `mark`, followed by relaxed line-mark stores.-   - If the object lies in an evac-source block and is not pinned: CAS the header to `BUSY`, copy into the thread's evac block, release-store the forwarding word; losers spin and follow it.-   - Every visited slot is rewritten in place with the new address.-5. **Sweep:** parallel over blocks, touching only the line-mark table (0.8% of heap). Count live lines with SIMD, reclassify the block, splice into per-thread lists, then merge. No object is touched. The epoch increments instead of clearing marks (clear only on wrap at 255).-6. **LOS sweep**, and release of surplus blocks (`MADV_FREE` after a lag).-7. **Resize:** target heap = max(64 MiB, live × 1.5), tunable.--A collection is triggered when free + recyclable blocks are exhausted and the growth budget is spent.--## 6. Generational mode (sticky Immix, v3)--- **Minor GC:** do not bump the epoch. Trace from roots and stop at any marked object. Survivors stay marked (old) and unmarked lines are reusable. No remembered set, no barrier.-- **Full GC:** bump the epoch, which implicitly unmarks everything, and run the normal cycle with evacuation.-- Minor GCs never evacuate. Trigger a full GC when old-generation growth exceeds a threshold or fragmentation does.--## 7. LLVM integration--- **Managed pointers** are `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.-- **Safepoint polls:** the frontend inserts them at loop back-edges and on entry to recursive functions: `if (tls->poll) xyz_gc_poll()`. A guard-page poll is a later optimization.-- **Stack maps:** parse `.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)`.-- **Roots are stack slots only.** Keep the default of no GC pointers in callee-saved registers (`fixup-statepoint-caller-saved`), so every root is a spill slot.-- **Stack walking:** frame-pointer chain (`"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.-- **Allocation calls:** declare `@xyz_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.-- **Runtime entry points that can GC** (`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.-- **Dev builds:** LLVM is linked dynamically into the *compiler only*. The runtime is a static `libxyzrt.a` built without LLVM headers, and it parses the stack-map format itself.-- **Pin the LLVM version.** The statepoint intrinsics are still documented as experimental.--## 8. Runtime ABI--| Symbol | Purpose |-| --- | --- |-| `xyz_alloc_slow(size, type_id)` | slow path allocation, may GC |-| `xyz_alloc_large(size, type_id)` | LOS allocation |-| `xyz_gc_poll()` | safepoint slow path |-| `xyz_thread_attach/detach()` | register a mutator |-| `xyz_native_enter/exit()` | publish frame, set `IN_NATIVE` |-| `xyz_pin(obj)` / `xyz_unpin(obj)` | set `PINNED`, for FFI |-| `xyz_root_add/remove(slot*)` | global roots |-| `xyz_wb(obj)` | only if mutable cells exist |--## 9. C++23 coding rules--- `-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.-- SIMD behind one small abstraction with AVX2, NEON, and scalar paths; verify all three agree in tests.--## 10. Verification and milestones--**Debug modes:** `XYZ_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 |---- Pin those objects.-- Use registered handles.-- Leave the native region before collection proceeds.--A collector must never move an object while native code may still be dereferencing its old address.--### 5.2 Evacuation-set selection--Evacuation is opportunistic.--The collector examines fragmentation statistics from the previous cycle.--Candidate blocks are ranked by:--1. Lowest live-line ratio.-2. Highest number of reusable holes.-3. Lowest evacuation cost.-4. Lowest number of pinned objects.--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:--- At least 2% of the heap.-- At least eight blocks.--Evacuation must be disabled when the available target capacity is insufficient.--### 5.3 Root discovery--Roots are obtained from:--1. Compiler-generated shadow-stack frames.-2. Global root registrations.-3. Registered native handles.-4. Pinned object registrations.-5. Runtime-owned roots.--No arbitrary register scanning is performed.--No arbitrary machine-stack scanning is performed.--The collector does not need to understand the machine register allocator.--### 5.4 Parallel marking--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:--1. Validate the object pointer.-2. Check its header.-3. Determine whether it has already been marked.-4. Atomically claim it if necessary.-5. Mark all intersecting lines.-6. Scan its pointer fields.-7. Push discovered references onto the worker's mark stack.--Object marking uses an atomic test-and-set or compare-and-exchange operation.--Line metadata updates must be atomic or otherwise synchronized between workers.--### 5.5 Evacuation--When an object belongs to an evacuation-source block:--1. Check whether it is pinned.-2. Atomically transition its header to `BUSY`.-3. Allocate destination storage.-4. Copy the object.-5. Publish the forwarding pointer with release semantics.-6. Return the destination address.--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.--### 5.6 Sweeping--Sweeping runs in parallel after marking and evacuation complete.--For each ordinary block:--1. Count live lines.-2. Identify contiguous dead-line regions.-3. Calculate the remaining hole count.-4. Update block state.-5. Reclassify the block.-6. Add reusable blocks or holes to the appropriate allocation lists.--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.--### 5.7 Epoch management--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.--### 5.8 LOS sweeping--LOS allocations are swept independently.--Unmarked objects are released.--Marked objects remain in place.--### 5.9 Heap resizing--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.-------## 6. Generational mode (sticky Immix, v3)--Generational collection is an extension of the primary Immix collector.--It relies on the immutable-object construction rule.--### 6.1 Generational allocation--New objects are allocated into nursery blocks.--Objects in nursery blocks may reference:--- Earlier nursery objects.-- Existing old-generation objects.--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.--### 6.2 Minor collection--Minor collection:--1. Stops mutators.-2. Enumerates roots.-3. Traces nursery references.-4. Stops traversal at old-generation objects.-5. Marks live nursery objects.-6. Reclaims dead nursery lines.-7. Promotes surviving nursery blocks.-8. Reinitializes nursery allocation state.--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.--### 6.3 Promotion--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.--### 6.4 Full collection--Full collection:--- Advances the major epoch.-- Traces all reachable objects.-- Reclaims both generations.-- Performs normal evacuation.-- Promotes surviving objects into the old generation.--### 6.5 Collection triggers--A full collection is triggered when:--- Old-generation growth exceeds a configured threshold.-- Fragmentation exceeds a threshold.-- The heap growth budget is exhausted.-- A configurable number of minor collections have elapsed.--Generational mode is optional and should not complicate the initial implementation.-------## 7. UQBE integration--This replaces the entire LLVM integration section.--UQBE is responsible for generating machine code and ordinary calls into the xyz runtime.--The collector does not depend on LLVM.--### 7.1 Backend model--The compilation pipeline is:--```text-xyz source-    |-    v-xyz frontend-    |-    v-xyz IR-    |-    +---- Type descriptors-    |-    +---- Managed-pointer liveness-    |-    +---- Safepoint identification-    |-    +---- Root-frame generation-    |-    v-UQBE IL-    |-    v-UQBE backend-    |-    v-Native object code-    |-    v-xyz linker-    |-    v-Executable + xyz runtime-```--UQBE continues to handle:--- SSA lowering.-- Register allocation.-- Instruction selection.-- Calling-convention lowering.-- Stack-frame generation.-- Native code emission.--The frontend handles GC-specific correctness.--### 7.2 No special GC instructions--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.--### 7.3 Shadow-stack root frames--Instead of parsing LLVM stack maps or attempting to reconstruct roots from arbitrary machine instructions, xyz uses explicit shadow-stack frames.--Each managed function that can participate in collection receives a compiler-generated root frame.--Conceptually:--```cpp-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:--```cpp-xyz_root_enter(&frame);-```--On function exit:--```cpp-xyz_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.--### 7.4 Root slots--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:--```text-store managed_pointer, root_slot--call xyz_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.--### 7.5 Root-map descriptors--Root maps are generated by the xyz frontend.--A descriptor contains:--- Number of root slots.-- Slot offsets or indices.-- Managed-reference type information where required.-- Frame size.-- Optional debugging metadata.--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.--### 7.6 UQBE stack slots--Root slots are represented using ordinary UQBE stack allocation.--For example, conceptually:--```text-%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.--### 7.7 Safepoint polls--The frontend inserts ordinary calls to:--```cpp-xyz_gc_poll()-```--Polls are required at:--- Loop back-edges.-- Recursive function entry.-- Potentially unbounded execution paths.-- Allocation slow paths.-- Explicit runtime safepoints.--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.--### 7.8 Calls that may collect--Every function that may trigger collection must be identified by the frontend.--The compiler must distinguish:--- Functions that cannot collect.-- Functions that may collect.-- Functions that enter native code.-- Functions that allocate managed objects.--A function that calls another potentially collecting function must preserve all live managed references across that call.--This is ordinary interprocedural effect propagation.--### 7.9 Allocation lowering--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:--```cpp-extern "C" void* xyz_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.--### 7.10 Derived pointers--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:--- Recompute it after the safepoint using the relocated base pointer.-- Preserve the base pointer and byte offset, then reconstruct the derived pointer.--The collector never needs to relocate arbitrary interior pointers.--### 7.11 Native ABI--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:--- System V AMD64.-- Microsoft x64.-- AArch64 platform ABIs.--The collector must not depend on a particular register assignment or machine stack layout.--### 7.12 Object files and linking--The collector runtime is a static library:--`libxyzrt.a`--The executable links against it using the normal xyz 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.-------## 8. Runtime ABI--The runtime exposes a small C-compatible interface.--| Symbol | Purpose |-|---|---|-| `xyz_alloc_slow(size, type_id)` | Slow managed allocation |-| `xyz_alloc_large(size, type_id)` | LOS allocation |-| `xyz_gc_poll()` | Safepoint poll |-| `xyz_gc_collect()` | Explicit collection request |-| `xyz_thread_attach()` | Register a mutator |-| `xyz_thread_detach()` | Unregister a mutator |-| `xyz_root_enter(frame)` | Register a shadow-stack frame |-| `xyz_root_leave(frame)` | Unregister a shadow-stack frame |-| `xyz_root_add(slot)` | Register a global root |-| `xyz_root_remove(slot)` | Remove a global root |-| `xyz_native_enter()` | Enter a GC-safe native region |-| `xyz_native_exit()` | Leave a GC-safe native region |-| `xyz_pin(obj)` | Pin a managed object |-| `xyz_unpin(obj)` | Unpin a managed object |-| `xyz_wb(obj, slot, value)` | Future mutable-object barrier |--All public entry points use C linkage.--The runtime must document which functions may trigger collection.-------## 9. C++23 runtime implementation--### 9.1 Compilation--The runtime is built independently from the compiler.--Recommended flags:--```text--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.--### 9.2 Memory management--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.--### 9.3 Layout--All layout constants are `constexpr`.--Use:--- `std::countr_zero` for bit operations.-- `std::bit_ceil` for capacity calculations.-- `std::memcpy` for object copying.-- Explicit atomic operations for concurrent metadata.-- `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.--### 9.4 SIMD--SIMD is implemented inside the C++ runtime.--The initial abstraction supports:--- AVX2.-- NEON.-- Scalar fallback.--SIMD is used for:--- Line metadata scanning.-- Hole discovery.-- Zeroing.-- Live-line counting.-- Selected bitmap operations.--UQBE does not need first-class vector instructions for the initial collector.--Architecture-specific SIMD code must be tested against the scalar implementation.--### 9.5 Concurrency--The collector uses:--- Atomic block ownership.-- Atomic object-marking state.-- Atomic forwarding publication.-- Parallel work-stealing queues.-- Stop-the-world synchronization.--The implementation must avoid ABA problems in global block lists.--Thread-local allocation state must be isolated to avoid false sharing.-------## 10. Verification and testing--### 10.1 Debug modes--Environment variables:--```text-XYZ_GC_STRESS=1-XYZ_GC_VERIFY=1-XYZ_GC_POISON=1-XYZ_GC_LOG=1-XYZ_GC_DISABLE_EVAC=1-XYZ_GC_DISABLE_GENERATIONAL=1-```--`XYZ_GC_STRESS` forces collection after a configurable number of allocations.--`XYZ_GC_VERIFY` enables heap verification before and after collection.--`XYZ_GC_POISON` poisons reclaimed memory.--`XYZ_GC_LOG` prints collection statistics.--### 10.2 Heap verification--The verifier checks:--- Every reachable reference points to a valid managed object.-- Every reachable object has a valid type descriptor.-- Every live object intersects appropriately marked lines.-- No object contains an invalid managed reference.-- No forwarded object contains an invalid forwarding address.-- No two mutators own the same allocation block.-- No live pinned object has moved.-- No evacuated source block is released while references to it remain.-- No root frame references invalid stack storage.--### 10.3 Stress testing--Tests must cover:--- Allocation without collection.-- Repeated full collections.-- Collection during recursive execution.-- Collection during nested function calls.-- Objects containing references.-- Arrays of references.-- Objects spanning multiple lines.-- Medium and large allocations.-- Fragmented heaps.-- Multiple mutators.-- Concurrent marking workers.-- Evacuation races.-- Pinning and unpinning.-- Native calls.-- Thread attachment and detachment.-- Heap exhaustion.-- Epoch wraparound.-- Generational promotion.-- Dead objects sharing lines with live objects.--### 10.4 Sanitizers--Development builds should support:--- AddressSanitizer.-- UndefinedBehaviorSanitizer.-- ThreadSanitizer.--ASan poisoning must be coordinated with the allocator and collector.--TSan builds should exercise concurrent marking, forwarding, and block ownership.--### 10.5 Determinism--A configurable deterministic seed controls work-stealing order and stress-test scheduling.--This allows GC failures to be reproduced more reliably.-------## 11. Performance targets--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.-------## 12. Implementation milestones--| 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 |--### M0 — Basic collector--Implement the heap reservation, block allocator, type descriptors, marking, and sweeping.--No evacuation or generational mode.--### M1 — UQBE integration--Implement root-frame generation in the xyz 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.--### M2 — Multithreading--Implement mutator registration, safepoint rendezvous, thread-local allocation, and concurrent collector workers.--### M3 — Parallel collection--Introduce work stealing, parallel tracing, parallel sweeping, and SIMD line discovery.--### M4 — Evacuation--Implement forwarding, destination allocation, reference rewriting, and fragmentation-driven evacuation.--### M5 — Native interoperation--Implement pinning, native handles, native-region registration, and safe transitions between managed and native execution.--### M6 — Generational collection--Introduce nursery blocks, sticky marking, block promotion, and minor collection.--### M7 — Tuning--Optimize memory commitment, huge-page usage, NUMA placement, prefetching, and allocator locality.-------## 13. Final architectural constraints--The following properties are mandatory:--1. The runtime must not depend on LLVM.-2. UQBE must not require LLVM-style statepoint support.-3. All managed roots must be explicitly published.-4. All heap references must be precise object-base pointers.-5. No managed pointer may remain hidden in an untracked register across a safepoint.-6. No object may be moved while native code can still dereference its old address.-7. No old-generation object may acquire a reference to a nursery object.-8. Allocation blocks must have exclusive mutator ownership.-9. Evacuation must never release a source block before all references have been rewritten.-10. The normal allocation path must remain independent of collector synchronization.--**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.**--- /dev/null+++ b/runtime/hazert.cpp@@ -0,0 +1,1028 @@+#include "hazert.h"++#include <cstdarg>+#include <cstddef>+#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <new>++#if defined(_WIN32)+#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#include <windows.h>+#else+#include <sys/mman.h>+#include <unistd.h>+#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)+#define MAP_ANONYMOUS MAP_ANON+#endif+#endif++namespace {++constexpr uint32_t GRANULE = 16;+constexpr uint32_t HEADER_SIZE = 8;+constexpr uint32_t LINE_SIZE = 128;+constexpr uint32_t BLOCK_SHIFT = 15;+constexpr uint32_t BLOCK_SIZE = 1u << BLOCK_SHIFT;+constexpr uint32_t LINES_PER_BLOCK = BLOCK_SIZE / LINE_SIZE;+constexpr uint32_t LARGE_THRESHOLD = 8192;+constexpr uint32_t NO_BLOCK = 0xffffffffu;+constexpr uint32_t MAX_TYPES = 1024;+constexpr uint32_t MAX_GLOBAL_ROOTS = 8192;+constexpr uint32_t MAX_PINNED = 8192;+constexpr uint32_t MAX_LARGE = 65536;+constexpr uint32_t MARK_STACK = 1u << 20;+constexpr uint64_t DEFAULT_HEAP = 64ull << 30;+constexpr uint64_t MIN_HEAP = 16ull << 20;++struct alignas(8) Header {+    uint32_t type_id;+    uint8_t mark;+    uint8_t flags;+    uint16_t aux;+};+static_assert(sizeof(Header) == 8, "Header must be 8 bytes");++enum HeaderFlags : uint8_t {+    PINNED = 1u << 0,+    REMEMBERED = 1u << 1,+    LARGE = 1u << 2,+};++enum class BlockState : uint8_t {+    FREE = 0,+    ALLOCATING,+    RECYCLABLE,+    FULL,+    EVAC_SOURCE,+    EVAC_TARGET,+    LOS_RESERVED,+};++struct BlockMeta {+    uint32_t next;+    uint16_t holes;+    uint16_t marked_lines;+    uint8_t state;+    uint8_t generation;+    uint8_t flags;+    uint8_t age;+    uint32_t owner;+};+static_assert(sizeof(BlockMeta) == 16, "BlockMeta must be 16 bytes");++struct TypeDesc {+    uint32_t size;+    uint16_t pointer_count;+    uint16_t flags;+    const uint32_t* pointer_offsets;+};++struct RootMap {+    uint32_t count;+    uint32_t frame_size;+    const uint32_t* offsets;+};++struct alignas(64) Mutator {+    void* cursor;+    void* limit;+    void* ocursor;+    void* olimit;+    void* nursery_cursor;+    void* nursery_limit;+    HazeRootFrame* root_frame;+    uint32_t thread_id;+    uint32_t flags;+    uint8_t poll;+    uint8_t reserved[7];+    uint32_t current_block;+    uint32_t overflow_block;+};++struct LargeObj {+    void* base;+    size_t size;+};++inline uint32_t align_up(uint32_t n, uint32_t a) {+    return (n + a - 1) & ~(a - 1);+}++inline uint64_t align_down64(uint64_t n, uint64_t a) {+    return n & ~(a - 1);+}++inline bool env_on(const char* name) {+    const char* v = std::getenv(name);+    return v && *v && std::strcmp(v, "0") != 0;+}++uint64_t env_u64(const char* name, uint64_t fallback) {+    const char* v = std::getenv(name);+    if (!v || !*v)+        return fallback;+    char* end = nullptr;+    unsigned long long n = std::strtoull(v, &end, 0);+    if (end == v)+        return fallback;+    if (*end == 'k' || *end == 'K')+        n <<= 10;+    else if (*end == 'm' || *end == 'M')+        n <<= 20;+    else if (*end == 'g' || *end == 'G')+        n <<= 30;+    return n;+}++#if defined(_WIN32)+void* os_reserve(size_t n) {+    return VirtualAlloc(nullptr, n, MEM_RESERVE, PAGE_NOACCESS);+}+bool os_commit(void* p, size_t n) {+    return VirtualAlloc(p, n, MEM_COMMIT, PAGE_READWRITE) != nullptr;+}+void* os_alloc_zeroed(size_t n) {+    return VirtualAlloc(nullptr, n, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);+}+void os_free(void* p, size_t) {+    if (p)+        VirtualFree(p, 0, MEM_RELEASE);+}+#else+void* os_reserve(size_t n) {+    int flags = MAP_PRIVATE | MAP_ANONYMOUS;+#ifdef MAP_NORESERVE+    flags |= MAP_NORESERVE;+#endif+    void* p = mmap(nullptr, n, PROT_NONE, flags, -1, 0);+    return p == MAP_FAILED ? nullptr : p;+}+bool os_commit(void* p, size_t n) {+    return mprotect(p, n, PROT_READ | PROT_WRITE) == 0;+}+void* os_alloc_zeroed(size_t n) {+    int flags = MAP_PRIVATE | MAP_ANONYMOUS;+#ifdef MAP_NORESERVE+    flags |= MAP_NORESERVE;+#endif+    void* p = mmap(nullptr, n, PROT_READ | PROT_WRITE, flags, -1, 0);+    return p == MAP_FAILED ? nullptr : p;+}+void os_free(void* p, size_t n) {+    if (p)+        munmap(p, n);+}+#endif++struct Heap {+    uint8_t* base = nullptr;+    size_t size = 0;+    uint32_t nblocks = 0;+    BlockMeta* meta = nullptr;+    uint8_t* line_marks = nullptr;+    uint32_t free_head = NO_BLOCK;+    uint32_t recyclable_head = NO_BLOCK;++    TypeDesc types[MAX_TYPES] = {};+    uint32_t ntypes = 1;++    uint8_t epoch = 1;+    bool initialized = false;+    bool log = false;+    bool verify_mode = false;+    bool poison = false;+    uint32_t stress_n = 0;+    uint32_t stress_counter = 0;+    uint64_t collections = 0;+    uint64_t allocations = 0;+    uint64_t live_lines_last = 0;++    Mutator main_mutator = {};+    Mutator* mutator = nullptr;++    LargeObj large[MAX_LARGE] = {};+    uint32_t nlarge = 0;++    void** global_roots[MAX_GLOBAL_ROOTS] = {};+    uint32_t nroots = 0;++    void* pinned[MAX_PINNED] = {};+    uint32_t npinned = 0;++    bool gc_requested = false;++    bool init();+    bool reserve_heap(size_t wanted);+    bool init_metadata();++    Mutator* current();+    uint32_t block_index(const void* p) const {+        return static_cast<uint32_t>((static_cast<const uint8_t*>(p) - base) >> BLOCK_SHIFT);+    }+    bool in_heap(const void* p) const {+        uintptr_t a = reinterpret_cast<uintptr_t>(p);+        uintptr_t b = reinterpret_cast<uintptr_t>(base);+        return p && a >= b && a < b + size;+    }+    bool is_large_object(const void* p) const {+        for (uint32_t i = 0; i < nlarge; i++)+            if (large[i].base == p)+                return true;+        return false;+    }++    uint32_t type_for_size(uint32_t total);+    uint32_t register_type(uint32_t total, uint32_t ptr_count, const uint32_t* offsets);++    void* allocate(uint32_t payload, uint32_t type_id);+    void* allocate_ordinary(uint32_t total, uint32_t type_id);+    void* allocate_large(uint32_t total, uint32_t type_id);+    uint32_t acquire_block();+    void push_free(uint32_t b);+    void push_recyclable(uint32_t b);+    bool try_alloc(Mutator* m, uint32_t total, uint32_t type_id, void** out);+    bool find_hole(Mutator* m, uint32_t total);++    void collect();+    void mark_roots();+    void mark_object(void* obj);+    void sweep();+    void reset_mutator(Mutator* m);+    void verify(bool after);++    void report(const char* fmt, ...);+};++Heap g_heap;+thread_local Mutator* tls_mutator = nullptr;++bool Heap::reserve_heap(size_t wanted) {+    size_t n = wanted;+    for (;;) {+        base = static_cast<uint8_t*>(os_reserve(n));+        if (base) {+            size = n;+            nblocks = static_cast<uint32_t>(n / BLOCK_SIZE);+            return true;+        }+        if (n <= MIN_HEAP)+            return false;+        n /= 2;+    }+}++bool Heap::init_metadata() {+    size_t line_bytes = static_cast<size_t>(nblocks) * LINES_PER_BLOCK;+    line_marks = static_cast<uint8_t*>(os_alloc_zeroed(line_bytes));+    meta =+        static_cast<BlockMeta*>(os_alloc_zeroed(static_cast<size_t>(nblocks) * sizeof(BlockMeta)));+    if (!line_marks || !meta)+        return false;++    for (uint32_t i = 0; i < nblocks; i++) {+        meta[i].next = (i + 1 < nblocks) ? i + 1 : NO_BLOCK;+        meta[i].state = static_cast<uint8_t>(BlockState::FREE);+        meta[i].owner = 0xffffffffu;+    }+    free_head = nblocks ? 0 : NO_BLOCK;+    recyclable_head = NO_BLOCK;++    types[0].size = 0;+    types[0].pointer_count = 0;+    types[0].flags = 0;+    types[0].pointer_offsets = nullptr;+    ntypes = 1;+    return true;+}++bool Heap::init() {+    if (initialized)+        return true;++    log = env_on("HAZE_GC_LOG");+    verify_mode = env_on("HAZE_GC_VERIFY");+    poison = env_on("HAZE_GC_POISON");+    stress_n = static_cast<uint32_t>(env_u64("HAZE_GC_STRESS", 0));++    uint64_t wanted = env_u64("HAZE_HEAP_SIZE", DEFAULT_HEAP);+    if (wanted < MIN_HEAP)+        wanted = MIN_HEAP;+    wanted = align_down64(wanted, BLOCK_SIZE);++    for (;;) {+        if (!reserve_heap(static_cast<size_t>(wanted))) {+            report("could not reserve a %llu-byte heap", static_cast<unsigned long long>(wanted));+            return false;+        }+        if (init_metadata())+            break;+        os_free(line_marks, static_cast<size_t>(nblocks) * LINES_PER_BLOCK);+        os_free(meta, static_cast<size_t>(nblocks) * sizeof(BlockMeta));+        line_marks = nullptr;+        meta = nullptr;+        os_free(base, size);+        base = nullptr;+        if (wanted <= MIN_HEAP) {+            report("could not allocate collector side metadata");+            return false;+        }+        wanted /= 2;+        wanted = align_down64(wanted, BLOCK_SIZE);+    }++    std::memset(&main_mutator, 0, sizeof(main_mutator));+    main_mutator.current_block = NO_BLOCK;+    main_mutator.overflow_block = NO_BLOCK;+    mutator = &main_mutator;+    tls_mutator = &main_mutator;+    initialized = true;++    if (log)+        report("heap: %llu bytes, %u blocks, %u lines/block", static_cast<unsigned long long>(size),+               nblocks, LINES_PER_BLOCK);+    return true;+}++Mutator* Heap::current() {+    if (!initialized)+        init();+    if (!tls_mutator) {+        tls_mutator = &main_mutator;+        mutator = &main_mutator;+    }+    return tls_mutator;+}++uint32_t Heap::type_for_size(uint32_t total) {+    total = align_up(total, GRANULE);+    for (uint32_t i = 1; i < ntypes; i++)+        if (types[i].size == total && types[i].pointer_count == 0)+            return i;+    if (ntypes >= MAX_TYPES) {+        report("type table exhausted");+        std::abort();+    }+    uint32_t id = ntypes++;+    types[id].size = total;+    types[id].pointer_count = 0;+    types[id].flags = 0;+    types[id].pointer_offsets = nullptr;+    return id;+}++uint32_t Heap::register_type(uint32_t total, uint32_t ptr_count, const uint32_t* offsets) {+    total = align_up(total, GRANULE);+    for (uint32_t i = 1; i < ntypes; i++)+        if (types[i].size == total && types[i].pointer_count == ptr_count &&+            types[i].pointer_offsets == offsets)+            return i;+    if (ntypes >= MAX_TYPES) {+        report("type table exhausted");+        std::abort();+    }+    uint32_t id = ntypes++;+    types[id].size = total;+    types[id].pointer_count = static_cast<uint16_t>(ptr_count);+    types[id].flags = 0;+    types[id].pointer_offsets = offsets;+    return id;+}++void Heap::push_free(uint32_t b) {+    meta[b].next = free_head;+    meta[b].state = static_cast<uint8_t>(BlockState::FREE);+    meta[b].holes = LINES_PER_BLOCK;+    meta[b].marked_lines = 0;+    free_head = b;+}++void Heap::push_recyclable(uint32_t b) {+    meta[b].next = recyclable_head;+    meta[b].state = static_cast<uint8_t>(BlockState::RECYCLABLE);+    recyclable_head = b;+}++uint32_t Heap::acquire_block() {+    Mutator* m = current();+    for (;;) {+        uint32_t b = NO_BLOCK;+        if (recyclable_head != NO_BLOCK) {+            b = recyclable_head;+            recyclable_head = meta[b].next;+            meta[b].next = NO_BLOCK;+        } else if (free_head != NO_BLOCK) {+            b = free_head;+            free_head = meta[b].next;+            meta[b].next = NO_BLOCK;++            uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;+            if (!os_commit(block, BLOCK_SIZE)) {+                report("could not commit block %u", b);+                std::abort();+            }+            std::memset(block, 0, BLOCK_SIZE);+            std::memset(line_marks + static_cast<size_t>(b) * LINES_PER_BLOCK, 0, LINES_PER_BLOCK);+            meta[b].holes = LINES_PER_BLOCK;+            meta[b].marked_lines = 0;+        } else {+            return NO_BLOCK;+        }++        meta[b].state = static_cast<uint8_t>(BlockState::ALLOCATING);+        meta[b].owner = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(m) & 0xffffffffu);+        meta[b].age = 0;++        uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;+        m->current_block = b;+        m->cursor = block;+        m->limit = block + BLOCK_SIZE;++        if (meta[b].marked_lines == 0) {+            std::memset(line_marks + static_cast<size_t>(b) * LINES_PER_BLOCK, 0, LINES_PER_BLOCK);+            return b;+        }++        /* A recyclable block: find a hole.  mark_hole() will fail and we move on+         * when every line is live. */+        return b;+    }+}++bool Heap::find_hole(Mutator* m, uint32_t total) {+    uint32_t b = m->current_block;+    if (b == NO_BLOCK)+        return false;+    uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;+    size_t off = static_cast<uint8_t*>(m->cursor) - block;+    if (off >= BLOCK_SIZE)+        return false;+    uint32_t line = static_cast<uint32_t>(off) / LINE_SIZE;+    uint32_t base_line = b * LINES_PER_BLOCK;++    while (line < LINES_PER_BLOCK) {+        if (line_marks[base_line + line] == epoch) {+            line++;+            continue;+        }+        uint32_t end = line;+        while (end < LINES_PER_BLOCK && line_marks[base_line + end] != epoch)+            end++;+        uint32_t bytes = (end - line) * LINE_SIZE;+        if (bytes >= total) {+            m->cursor = block + static_cast<size_t>(line) * LINE_SIZE;+            m->limit = block + static_cast<size_t>(end) * LINE_SIZE;+            return true;+        }+        line = end;+    }+    return false;+}++bool Heap::try_alloc(Mutator* m, uint32_t total, uint32_t type_id, void** out) {+    uint8_t* p = static_cast<uint8_t*>(m->cursor);+    if (!p || p + total > static_cast<uint8_t*>(m->limit))+        return false;++    uint32_t b = m->current_block;+    if (b == NO_BLOCK)+        return false;++    uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;+    uint32_t first_line = static_cast<uint32_t>(p - block) / LINE_SIZE;+    uint32_t last_line = static_cast<uint32_t>((p + total - 1) - block) / LINE_SIZE;+    uint32_t base_line = b * LINES_PER_BLOCK;++    m->cursor = p + total;++    Header* h = reinterpret_cast<Header*>(p);+    h->type_id = type_id;+    h->mark = 0;+    h->flags = 0;+    h->aux = 0;+    std::memset(p + HEADER_SIZE, 0, total - HEADER_SIZE);++    for (uint32_t line = first_line; line <= last_line; line++)+        line_marks[base_line + line] = epoch;++    meta[b].state = static_cast<uint8_t>(BlockState::ALLOCATING);+    allocations++;+    *out = p;+    return true;+}++void* Heap::allocate_large(uint32_t total, uint32_t type_id) {+    if (nlarge >= MAX_LARGE) {+        report("large object table exhausted");+        std::abort();+    }+    void* p = os_alloc_zeroed(total);+    if (!p)+        return nullptr;+    Header* h = static_cast<Header*>(p);+    h->type_id = type_id;+    h->mark = 0;+    h->flags = LARGE;+    h->aux = 0;+    large[nlarge].base = p;+    large[nlarge].size = total;+    nlarge++;+    allocations++;+    return p;+}++void* Heap::allocate_ordinary(uint32_t total, uint32_t type_id) {+    Mutator* m = current();++    for (uint32_t attempt = 0; attempt < 2; attempt++) {+        for (;;) {+            if (m->current_block != NO_BLOCK) {+                void* p = nullptr;+                if (try_alloc(m, total, type_id, &p))+                    return p;+                if (find_hole(m, total) && try_alloc(m, total, type_id, &p))+                    return p;+                meta[m->current_block].state = static_cast<uint8_t>(BlockState::FULL);+                m->current_block = NO_BLOCK;+                m->cursor = m->limit = nullptr;+            }++            uint32_t b = acquire_block();+            if (b == NO_BLOCK)+                break;+            m->current_block = b;+            uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;+            m->cursor = block;+            m->limit = block + BLOCK_SIZE;++            if (meta[b].marked_lines != 0) {+                void* p = nullptr;+                if (find_hole(m, total) && try_alloc(m, total, type_id, &p))+                    return p;+                meta[b].state = static_cast<uint8_t>(BlockState::FULL);+                m->current_block = NO_BLOCK;+                m->cursor = m->limit = nullptr;+                continue;+            }++            void* p = nullptr;+            if (try_alloc(m, total, type_id, &p))+                return p;+            meta[b].state = static_cast<uint8_t>(BlockState::FULL);+            m->current_block = NO_BLOCK;+            m->cursor = m->limit = nullptr;+        }+        collect();+    }+    return nullptr;+}++void* Heap::allocate(uint32_t payload, uint32_t type_id) {+    init();++    if (stress_n) {+        if (++stress_counter >= stress_n) {+            stress_counter = 0;+            collect();+        }+    }++    uint32_t total;+    if (type_id == 0) {+        total = align_up(HEADER_SIZE + payload, GRANULE);+        type_id = type_for_size(total);+    } else {+        total = types[type_id].size;+        if (total < align_up(HEADER_SIZE + payload, GRANULE))+            total = align_up(HEADER_SIZE + payload, GRANULE);+    }++    if (total > LARGE_THRESHOLD) {+        void* p = allocate_large(total, type_id);+        if (!p) {+            collect();+            p = allocate_large(total, type_id);+        }+        return p;+    }++    void* p = allocate_ordinary(total, type_id);+    if (!p) {+        collect();+        p = allocate_ordinary(total, type_id);+    }+    if (!p) {+        report("out of heap after collection");+        std::abort();+    }+    return p;+}++void Heap::mark_object(void* obj) {+    static void* stack[MARK_STACK];+    size_t sp = 0;++    if (!obj)+        return;+    stack[sp++] = obj;++    while (sp) {+        void* p = stack[--sp];+        bool large_object = is_large_object(p);+        if (!in_heap(p) && !large_object)+            continue;+        if (reinterpret_cast<uintptr_t>(p) & (GRANULE - 1))+            continue;++        Header* h = reinterpret_cast<Header*>(p);+        if (h->mark == epoch)+            continue;+        h->mark = epoch;++        if (!(h->flags & LARGE) && !large_object) {+            uint32_t b = block_index(p);+            uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;+            uint32_t first = static_cast<uint32_t>(static_cast<uint8_t*>(p) - block) / LINE_SIZE;+            uint32_t total = types[h->type_id].size;+            if (total == 0)+                continue;+            uint32_t last =+                static_cast<uint32_t>((static_cast<uint8_t*>(p) + total - 1) - block) / LINE_SIZE;+            uint32_t base_line = b * LINES_PER_BLOCK;+            for (uint32_t line = first; line <= last; line++)+                line_marks[base_line + line] = epoch;+        }++        const TypeDesc& td = types[h->type_id];+        if (td.pointer_count && td.pointer_offsets) {+            for (uint32_t i = 0; i < td.pointer_count; i++) {+                uint32_t off = td.pointer_offsets[i];+                void* child = nullptr;+                std::memcpy(&child, static_cast<uint8_t*>(p) + off, sizeof(child));+                if (child && sp < MARK_STACK)+                    stack[sp++] = child;+            }+        }+    }+}++void Heap::mark_roots() {+    Mutator* m = current();++    for (HazeRootFrame* f = m->root_frame; f; f = f->previous) {+        if (!f->descriptor || !f->slots)+            continue;+        const RootMap* map = reinterpret_cast<const RootMap*>(f->descriptor);+        for (uint32_t i = 0; i < map->count; i++)+            mark_object(f->slots[i]);+    }++    for (uint32_t i = 0; i < nroots; i++) {+        if (global_roots[i])+            mark_object(*global_roots[i]);+    }++    for (uint32_t i = 0; i < npinned; i++)+        mark_object(pinned[i]);+}++void Heap::sweep() {+    uint64_t live_total = 0;++    for (uint32_t b = 0; b < nblocks; b++) {+        uint8_t state = meta[b].state;+        if (state == static_cast<uint8_t>(BlockState::FREE) ||+            state == static_cast<uint8_t>(BlockState::LOS_RESERVED))+            continue;++        uint32_t base_line = b * LINES_PER_BLOCK;+        uint32_t live = 0;+        for (uint32_t i = 0; i < LINES_PER_BLOCK; i++)+            if (line_marks[base_line + i] == epoch)+                live++;++        live_total += live;++        if (live == 0) {+            if (poison) {+                uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;+                std::memset(block, 0xDD, BLOCK_SIZE);+            }+            push_free(b);+        } else if (live == LINES_PER_BLOCK) {+            meta[b].state = static_cast<uint8_t>(BlockState::FULL);+            meta[b].marked_lines = LINES_PER_BLOCK;+            meta[b].holes = 0;+        } else {+            uint32_t holes = 0;+            bool in_hole = false;+            for (uint32_t i = 0; i < LINES_PER_BLOCK; i++) {+                bool dead = line_marks[base_line + i] != epoch;+                if (dead && !in_hole) {+                    holes++;+                    in_hole = true;+                } else if (!dead) {+                    in_hole = false;+                }+            }+            meta[b].marked_lines = static_cast<uint16_t>(live);+            meta[b].holes = static_cast<uint16_t>(holes);+            push_recyclable(b);+        }+    }++    for (uint32_t i = 0; i < nlarge;) {+        Header* h = static_cast<Header*>(large[i].base);+        if (h->mark != epoch) {+            os_free(large[i].base, large[i].size);+            large[i] = large[--nlarge];+        } else {+            i++;+        }+    }++    live_lines_last = live_total;+}++void Heap::reset_mutator(Mutator* m) {+    m->cursor = nullptr;+    m->limit = nullptr;+    m->ocursor = nullptr;+    m->olimit = nullptr;+    m->current_block = NO_BLOCK;+    m->overflow_block = NO_BLOCK;+}++void Heap::collect() {+    if (!init())+        return;++    if (verify_mode)+        verify(false);++    collections++;++    if (epoch == 255) {+        std::memset(line_marks, 0, static_cast<size_t>(nblocks) * LINES_PER_BLOCK);+        epoch = 1;+    } else {+        epoch++;+    }++    for (uint32_t i = 0; i < nlarge; i++) {+        Header* h = static_cast<Header*>(large[i].base);+        h->mark = 0;+    }++    /* Invalidating mutator cursors first is what makes the collection+     * stop-the-world even in the single-threaded M0 implementation. */+    reset_mutator(current());+    recyclable_head = NO_BLOCK;++    mark_roots();+    sweep();++    gc_requested = false;++    if (verify_mode)+        verify(true);++    if (log)+        report("gc #%llu epoch=%u live_lines=%llu large=%u free_head=%u",+               static_cast<unsigned long long>(collections), epoch,+               static_cast<unsigned long long>(live_lines_last), nlarge, free_head);+}++void Heap::verify(bool after) {+    if (!initialized)+        return;++    auto fail = [](const char* what) {+        std::fprintf(stderr, "hazert: heap verification failed: %s\n", what);+        std::abort();+    };++    Mutator* m = current();++    for (HazeRootFrame* f = m->root_frame; f; f = f->previous) {+        if (!f->descriptor || !f->slots)+            fail("root frame has no descriptor or slots");+        const RootMap* map = reinterpret_cast<const RootMap*>(f->descriptor);+        for (uint32_t i = 0; i < map->count; i++) {+            void* p = f->slots[i];+            if (!p)+                continue;+            if (!in_heap(p) && !is_large_object(p))+                fail("root slot points outside the heap");+            if (reinterpret_cast<uintptr_t>(p) & (GRANULE - 1))+                fail("root slot is not granule aligned");+            Header* h = static_cast<Header*>(p);+            if (h->type_id == 0)+                fail("root slot has no type descriptor");+            if (after && h->mark != epoch)+                fail("live root was not marked");+        }+    }++    for (uint32_t i = 0; i < nroots; i++)+        if (global_roots[i] && *global_roots[i] && !in_heap(*global_roots[i]))+            fail("global root points outside the heap");++    for (uint32_t i = 0; i < nlarge; i++)+        if (reinterpret_cast<uintptr_t>(large[i].base) & (GRANULE - 1))+            fail("large object is not granule aligned");++    for (uint32_t b = 0; b < nblocks; b++) {+        uint8_t state = meta[b].state;+        if (state > static_cast<uint8_t>(BlockState::LOS_RESERVED))+            fail("invalid block state");+        if (state != static_cast<uint8_t>(BlockState::FREE) &&+            state != static_cast<uint8_t>(BlockState::LOS_RESERVED) && after &&+            meta[b].marked_lines == 0 && meta[b].holes == LINES_PER_BLOCK)+            fail("allocated block has no marked lines");+    }+}++void Heap::report(const char* fmt, ...) {+    va_list ap;+    va_start(ap, fmt);+    std::vfprintf(stderr, fmt, ap);+    va_end(ap);+    std::fputc('\n', stderr);+}++} // namespace++extern "C" {++void haze_runtime_init(void) {+    g_heap.init();+}++void* haze_alloc_slow(uint32_t payload_size, uint32_t type_id) {+    return g_heap.allocate(payload_size, type_id);+}++void* haze_alloc_large(uint32_t payload_size, uint32_t type_id) {+    g_heap.init();+    uint32_t total = align_up(HEADER_SIZE + payload_size, GRANULE);+    if (type_id == 0)+        type_id = g_heap.type_for_size(total);+    return g_heap.allocate_large(total, type_id);+}++uint32_t haze_type_for_size(uint32_t total_size) {+    g_heap.init();+    return g_heap.type_for_size(total_size);+}++uint32_t haze_register_type(uint32_t total_size, uint32_t pointer_count,+                           const uint32_t* pointer_offsets) {+    g_heap.init();+    return g_heap.register_type(total_size, pointer_count, pointer_offsets);+}++void haze_gc_request(void) {+    g_heap.gc_requested = true;+}++void haze_gc_poll(void) {+    if (g_heap.gc_requested)+        g_heap.collect();+}++void haze_gc_collect(void) {+    g_heap.collect();+}++void haze_gc_verify(void) {+    g_heap.verify(true);+}++int haze_gc_object_alive(void* object) {+    if (!g_heap.initialized || !object)+        return 0;+    if (!g_heap.in_heap(object) && !g_heap.is_large_object(object))+        return 0;+    Header* h = static_cast<Header*>(object);+    return h->mark == g_heap.epoch;+}++void haze_thread_attach(void) {+    g_heap.init();+    if (!tls_mutator) {+        Mutator* m = static_cast<Mutator*>(os_alloc_zeroed(sizeof(Mutator)));+        if (!m) {+            haze_panic("could not allocate mutator");+            return;+        }+        m->current_block = NO_BLOCK;+        m->overflow_block = NO_BLOCK;+        tls_mutator = m;+    }+}++void haze_thread_detach(void) {+    tls_mutator = nullptr;+}++void haze_root_enter(HazeRootFrame* frame) {+    if (!frame)+        return;+    Mutator* m = g_heap.current();+    frame->previous = m->root_frame;+    m->root_frame = frame;+}++void haze_root_leave(HazeRootFrame* frame) {+    if (!frame)+        return;+    Mutator* m = g_heap.current();+    if (m->root_frame == frame) {+        m->root_frame = frame->previous;+        return;+    }+    for (HazeRootFrame* f = m->root_frame; f; f = f->previous) {+        if (f->previous == frame) {+            f->previous = frame->previous;+            return;+        }+    }+}++void haze_root_add(void** slot) {+    g_heap.init();+    if (g_heap.nroots < MAX_GLOBAL_ROOTS)+        g_heap.global_roots[g_heap.nroots++] = slot;+}++void haze_root_remove(void** slot) {+    for (uint32_t i = 0; i < g_heap.nroots; i++) {+        if (g_heap.global_roots[i] == slot) {+            g_heap.global_roots[i] = g_heap.global_roots[--g_heap.nroots];+            return;+        }+    }+}++void haze_native_enter(void) {}+void haze_native_exit(void) {}++void haze_pin(void* object) {+    if (!object || !g_heap.in_heap(object))+        return;+    Header* h = static_cast<Header*>(object);+    h->flags |= PINNED;+    if (g_heap.npinned < MAX_PINNED)+        g_heap.pinned[g_heap.npinned++] = object;+}++void haze_unpin(void* object) {+    if (!object)+        return;+    Header* h = static_cast<Header*>(object);+    h->flags &= ~PINNED;+    for (uint32_t i = 0; i < g_heap.npinned; i++) {+        if (g_heap.pinned[i] == object) {+            g_heap.pinned[i] = g_heap.pinned[--g_heap.npinned];+            return;+        }+    }+}++void haze_wb(void* object, void** slot, void* value) {+    if (!object || !slot)+        return;+    *slot = value;+    Header* h = static_cast<Header*>(object);+    h->flags |= REMEMBERED;+}++void haze_print_i32(int32_t value) {+    std::printf("%d\n", value);+}++void haze_print_i64(int64_t value) {+    std::printf("%lld\n", static_cast<long long>(value));+}++void haze_print_bool(int32_t value) {+    std::fputs(value ? "true\n" : "false\n", stdout);+}++void haze_print_str(const char* value) {+    std::fputs(value ? value : "", stdout);+    std::fputc('\n', stdout);+}++void haze_panic(const char* message) {+    std::fprintf(stderr, "haze: %s\n", message ? message : "panic");+    std::fflush(stderr);+    std::exit(1);+}++} // extern "C"--- /dev/null+++ b/runtime/hazert.h@@ -0,0 +1,61 @@+#ifndef HAZERT_H+#define HAZERT_H++#include <stdint.h>++#ifdef __cplusplus+extern "C" {+#endif++typedef struct HazeRootMap {+    uint32_t count;+    uint32_t frame_size;+    const uint32_t* offsets;+} HazeRootMap;++typedef struct HazeRootFrame {+    struct HazeRootFrame* previous;+    const HazeRootMap* descriptor;+    void** slots;+} HazeRootFrame;++/* Collector entry points.  All of these use the C ABI. */+void haze_runtime_init(void);+void* haze_alloc_slow(uint32_t payload_size, uint32_t type_id);+void* haze_alloc_large(uint32_t payload_size, uint32_t type_id);+uint32_t haze_type_for_size(uint32_t total_size);+uint32_t haze_register_type(uint32_t total_size, uint32_t pointer_count,+                           const uint32_t* pointer_offsets);++void haze_gc_poll(void);+void haze_gc_request(void);+void haze_gc_collect(void);+void haze_gc_verify(void);+int haze_gc_object_alive(void* object);++void haze_thread_attach(void);+void haze_thread_detach(void);++void haze_root_enter(HazeRootFrame* frame);+void haze_root_leave(HazeRootFrame* frame);+void haze_root_add(void** slot);+void haze_root_remove(void** slot);++void haze_native_enter(void);+void haze_native_exit(void);+void haze_pin(void* object);+void haze_unpin(void* object);+void haze_wb(void* object, void** slot, void* value);++/* Small runtime used by generated programs. */+void haze_print_i32(int32_t value);+void haze_print_i64(int64_t value);+void haze_print_bool(int32_t value);+void haze_print_str(const char* value);+void haze_panic(const char* message);++#ifdef __cplusplus+}+#endif++#endif--- a/runtime/xyzrt.cpp+++ /dev/null@@ -1,1028 +0,0 @@-#include "xyzrt.h"--#include <cstdarg>-#include <cstddef>-#include <cstdint>-#include <cstdio>-#include <cstdlib>-#include <cstring>-#include <new>--#if defined(_WIN32)-#ifndef WIN32_LEAN_AND_MEAN-#define WIN32_LEAN_AND_MEAN-#endif-#include <windows.h>-#else-#include <sys/mman.h>-#include <unistd.h>-#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)-#define MAP_ANONYMOUS MAP_ANON-#endif-#endif--namespace {--constexpr uint32_t GRANULE = 16;-constexpr uint32_t HEADER_SIZE = 8;-constexpr uint32_t LINE_SIZE = 128;-constexpr uint32_t BLOCK_SHIFT = 15;-constexpr uint32_t BLOCK_SIZE = 1u << BLOCK_SHIFT;-constexpr uint32_t LINES_PER_BLOCK = BLOCK_SIZE / LINE_SIZE;-constexpr uint32_t LARGE_THRESHOLD = 8192;-constexpr uint32_t NO_BLOCK = 0xffffffffu;-constexpr uint32_t MAX_TYPES = 1024;-constexpr uint32_t MAX_GLOBAL_ROOTS = 8192;-constexpr uint32_t MAX_PINNED = 8192;-constexpr uint32_t MAX_LARGE = 65536;-constexpr uint32_t MARK_STACK = 1u << 20;-constexpr uint64_t DEFAULT_HEAP = 64ull << 30;-constexpr uint64_t MIN_HEAP = 16ull << 20;--struct alignas(8) Header {-    uint32_t type_id;-    uint8_t mark;-    uint8_t flags;-    uint16_t aux;-};-static_assert(sizeof(Header) == 8, "Header must be 8 bytes");--enum HeaderFlags : uint8_t {-    PINNED = 1u << 0,-    REMEMBERED = 1u << 1,-    LARGE = 1u << 2,-};--enum class BlockState : uint8_t {-    FREE = 0,-    ALLOCATING,-    RECYCLABLE,-    FULL,-    EVAC_SOURCE,-    EVAC_TARGET,-    LOS_RESERVED,-};--struct BlockMeta {-    uint32_t next;-    uint16_t holes;-    uint16_t marked_lines;-    uint8_t state;-    uint8_t generation;-    uint8_t flags;-    uint8_t age;-    uint32_t owner;-};-static_assert(sizeof(BlockMeta) == 16, "BlockMeta must be 16 bytes");--struct TypeDesc {-    uint32_t size;-    uint16_t pointer_count;-    uint16_t flags;-    const uint32_t* pointer_offsets;-};--struct RootMap {-    uint32_t count;-    uint32_t frame_size;-    const uint32_t* offsets;-};--struct alignas(64) Mutator {-    void* cursor;-    void* limit;-    void* ocursor;-    void* olimit;-    void* nursery_cursor;-    void* nursery_limit;-    XyzRootFrame* root_frame;-    uint32_t thread_id;-    uint32_t flags;-    uint8_t poll;-    uint8_t reserved[7];-    uint32_t current_block;-    uint32_t overflow_block;-};--struct LargeObj {-    void* base;-    size_t size;-};--inline uint32_t align_up(uint32_t n, uint32_t a) {-    return (n + a - 1) & ~(a - 1);-}--inline uint64_t align_down64(uint64_t n, uint64_t a) {-    return n & ~(a - 1);-}--inline bool env_on(const char* name) {-    const char* v = std::getenv(name);-    return v && *v && std::strcmp(v, "0") != 0;-}--uint64_t env_u64(const char* name, uint64_t fallback) {-    const char* v = std::getenv(name);-    if (!v || !*v)-        return fallback;-    char* end = nullptr;-    unsigned long long n = std::strtoull(v, &end, 0);-    if (end == v)-        return fallback;-    if (*end == 'k' || *end == 'K')-        n <<= 10;-    else if (*end == 'm' || *end == 'M')-        n <<= 20;-    else if (*end == 'g' || *end == 'G')-        n <<= 30;-    return n;-}--#if defined(_WIN32)-void* os_reserve(size_t n) {-    return VirtualAlloc(nullptr, n, MEM_RESERVE, PAGE_NOACCESS);-}-bool os_commit(void* p, size_t n) {-    return VirtualAlloc(p, n, MEM_COMMIT, PAGE_READWRITE) != nullptr;-}-void* os_alloc_zeroed(size_t n) {-    return VirtualAlloc(nullptr, n, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);-}-void os_free(void* p, size_t) {-    if (p)-        VirtualFree(p, 0, MEM_RELEASE);-}-#else-void* os_reserve(size_t n) {-    int flags = MAP_PRIVATE | MAP_ANONYMOUS;-#ifdef MAP_NORESERVE-    flags |= MAP_NORESERVE;-#endif-    void* p = mmap(nullptr, n, PROT_NONE, flags, -1, 0);-    return p == MAP_FAILED ? nullptr : p;-}-bool os_commit(void* p, size_t n) {-    return mprotect(p, n, PROT_READ | PROT_WRITE) == 0;-}-void* os_alloc_zeroed(size_t n) {-    int flags = MAP_PRIVATE | MAP_ANONYMOUS;-#ifdef MAP_NORESERVE-    flags |= MAP_NORESERVE;-#endif-    void* p = mmap(nullptr, n, PROT_READ | PROT_WRITE, flags, -1, 0);-    return p == MAP_FAILED ? nullptr : p;-}-void os_free(void* p, size_t n) {-    if (p)-        munmap(p, n);-}-#endif--struct Heap {-    uint8_t* base = nullptr;-    size_t size = 0;-    uint32_t nblocks = 0;-    BlockMeta* meta = nullptr;-    uint8_t* line_marks = nullptr;-    uint32_t free_head = NO_BLOCK;-    uint32_t recyclable_head = NO_BLOCK;--    TypeDesc types[MAX_TYPES] = {};-    uint32_t ntypes = 1;--    uint8_t epoch = 1;-    bool initialized = false;-    bool log = false;-    bool verify_mode = false;-    bool poison = false;-    uint32_t stress_n = 0;-    uint32_t stress_counter = 0;-    uint64_t collections = 0;-    uint64_t allocations = 0;-    uint64_t live_lines_last = 0;--    Mutator main_mutator = {};-    Mutator* mutator = nullptr;--    LargeObj large[MAX_LARGE] = {};-    uint32_t nlarge = 0;--    void** global_roots[MAX_GLOBAL_ROOTS] = {};-    uint32_t nroots = 0;--    void* pinned[MAX_PINNED] = {};-    uint32_t npinned = 0;--    bool gc_requested = false;--    bool init();-    bool reserve_heap(size_t wanted);-    bool init_metadata();--    Mutator* current();-    uint32_t block_index(const void* p) const {-        return static_cast<uint32_t>((static_cast<const uint8_t*>(p) - base) >> BLOCK_SHIFT);-    }-    bool in_heap(const void* p) const {-        uintptr_t a = reinterpret_cast<uintptr_t>(p);-        uintptr_t b = reinterpret_cast<uintptr_t>(base);-        return p && a >= b && a < b + size;-    }-    bool is_large_object(const void* p) const {-        for (uint32_t i = 0; i < nlarge; i++)-            if (large[i].base == p)-                return true;-        return false;-    }--    uint32_t type_for_size(uint32_t total);-    uint32_t register_type(uint32_t total, uint32_t ptr_count, const uint32_t* offsets);--    void* allocate(uint32_t payload, uint32_t type_id);-    void* allocate_ordinary(uint32_t total, uint32_t type_id);-    void* allocate_large(uint32_t total, uint32_t type_id);-    uint32_t acquire_block();-    void push_free(uint32_t b);-    void push_recyclable(uint32_t b);-    bool try_alloc(Mutator* m, uint32_t total, uint32_t type_id, void** out);-    bool find_hole(Mutator* m, uint32_t total);--    void collect();-    void mark_roots();-    void mark_object(void* obj);-    void sweep();-    void reset_mutator(Mutator* m);-    void verify(bool after);--    void report(const char* fmt, ...);-};--Heap g_heap;-thread_local Mutator* tls_mutator = nullptr;--bool Heap::reserve_heap(size_t wanted) {-    size_t n = wanted;-    for (;;) {-        base = static_cast<uint8_t*>(os_reserve(n));-        if (base) {-            size = n;-            nblocks = static_cast<uint32_t>(n / BLOCK_SIZE);-            return true;-        }-        if (n <= MIN_HEAP)-            return false;-        n /= 2;-    }-}--bool Heap::init_metadata() {-    size_t line_bytes = static_cast<size_t>(nblocks) * LINES_PER_BLOCK;-    line_marks = static_cast<uint8_t*>(os_alloc_zeroed(line_bytes));-    meta =-        static_cast<BlockMeta*>(os_alloc_zeroed(static_cast<size_t>(nblocks) * sizeof(BlockMeta)));-    if (!line_marks || !meta)-        return false;--    for (uint32_t i = 0; i < nblocks; i++) {-        meta[i].next = (i + 1 < nblocks) ? i + 1 : NO_BLOCK;-        meta[i].state = static_cast<uint8_t>(BlockState::FREE);-        meta[i].owner = 0xffffffffu;-    }-    free_head = nblocks ? 0 : NO_BLOCK;-    recyclable_head = NO_BLOCK;--    types[0].size = 0;-    types[0].pointer_count = 0;-    types[0].flags = 0;-    types[0].pointer_offsets = nullptr;-    ntypes = 1;-    return true;-}--bool Heap::init() {-    if (initialized)-        return true;--    log = env_on("XYZ_GC_LOG");-    verify_mode = env_on("XYZ_GC_VERIFY");-    poison = env_on("XYZ_GC_POISON");-    stress_n = static_cast<uint32_t>(env_u64("XYZ_GC_STRESS", 0));--    uint64_t wanted = env_u64("XYZ_HEAP_SIZE", DEFAULT_HEAP);-    if (wanted < MIN_HEAP)-        wanted = MIN_HEAP;-    wanted = align_down64(wanted, BLOCK_SIZE);--    for (;;) {-        if (!reserve_heap(static_cast<size_t>(wanted))) {-            report("could not reserve a %llu-byte heap", static_cast<unsigned long long>(wanted));-            return false;-        }-        if (init_metadata())-            break;-        os_free(line_marks, static_cast<size_t>(nblocks) * LINES_PER_BLOCK);-        os_free(meta, static_cast<size_t>(nblocks) * sizeof(BlockMeta));-        line_marks = nullptr;-        meta = nullptr;-        os_free(base, size);-        base = nullptr;-        if (wanted <= MIN_HEAP) {-            report("could not allocate collector side metadata");-            return false;-        }-        wanted /= 2;-        wanted = align_down64(wanted, BLOCK_SIZE);-    }--    std::memset(&main_mutator, 0, sizeof(main_mutator));-    main_mutator.current_block = NO_BLOCK;-    main_mutator.overflow_block = NO_BLOCK;-    mutator = &main_mutator;-    tls_mutator = &main_mutator;-    initialized = true;--    if (log)-        report("heap: %llu bytes, %u blocks, %u lines/block", static_cast<unsigned long long>(size),-               nblocks, LINES_PER_BLOCK);-    return true;-}--Mutator* Heap::current() {-    if (!initialized)-        init();-    if (!tls_mutator) {-        tls_mutator = &main_mutator;-        mutator = &main_mutator;-    }-    return tls_mutator;-}--uint32_t Heap::type_for_size(uint32_t total) {-    total = align_up(total, GRANULE);-    for (uint32_t i = 1; i < ntypes; i++)-        if (types[i].size == total && types[i].pointer_count == 0)-            return i;-    if (ntypes >= MAX_TYPES) {-        report("type table exhausted");-        std::abort();-    }-    uint32_t id = ntypes++;-    types[id].size = total;-    types[id].pointer_count = 0;-    types[id].flags = 0;-    types[id].pointer_offsets = nullptr;-    return id;-}--uint32_t Heap::register_type(uint32_t total, uint32_t ptr_count, const uint32_t* offsets) {-    total = align_up(total, GRANULE);-    for (uint32_t i = 1; i < ntypes; i++)-        if (types[i].size == total && types[i].pointer_count == ptr_count &&-            types[i].pointer_offsets == offsets)-            return i;-    if (ntypes >= MAX_TYPES) {-        report("type table exhausted");-        std::abort();-    }-    uint32_t id = ntypes++;-    types[id].size = total;-    types[id].pointer_count = static_cast<uint16_t>(ptr_count);-    types[id].flags = 0;-    types[id].pointer_offsets = offsets;-    return id;-}--void Heap::push_free(uint32_t b) {-    meta[b].next = free_head;-    meta[b].state = static_cast<uint8_t>(BlockState::FREE);-    meta[b].holes = LINES_PER_BLOCK;-    meta[b].marked_lines = 0;-    free_head = b;-}--void Heap::push_recyclable(uint32_t b) {-    meta[b].next = recyclable_head;-    meta[b].state = static_cast<uint8_t>(BlockState::RECYCLABLE);-    recyclable_head = b;-}--uint32_t Heap::acquire_block() {-    Mutator* m = current();-    for (;;) {-        uint32_t b = NO_BLOCK;-        if (recyclable_head != NO_BLOCK) {-            b = recyclable_head;-            recyclable_head = meta[b].next;-            meta[b].next = NO_BLOCK;-        } else if (free_head != NO_BLOCK) {-            b = free_head;-            free_head = meta[b].next;-            meta[b].next = NO_BLOCK;--            uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;-            if (!os_commit(block, BLOCK_SIZE)) {-                report("could not commit block %u", b);-                std::abort();-            }-            std::memset(block, 0, BLOCK_SIZE);-            std::memset(line_marks + static_cast<size_t>(b) * LINES_PER_BLOCK, 0, LINES_PER_BLOCK);-            meta[b].holes = LINES_PER_BLOCK;-            meta[b].marked_lines = 0;-        } else {-            return NO_BLOCK;-        }--        meta[b].state = static_cast<uint8_t>(BlockState::ALLOCATING);-        meta[b].owner = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(m) & 0xffffffffu);-        meta[b].age = 0;--        uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;-        m->current_block = b;-        m->cursor = block;-        m->limit = block + BLOCK_SIZE;--        if (meta[b].marked_lines == 0) {-            std::memset(line_marks + static_cast<size_t>(b) * LINES_PER_BLOCK, 0, LINES_PER_BLOCK);-            return b;-        }--        /* A recyclable block: find a hole.  mark_hole() will fail and we move on-         * when every line is live. */-        return b;-    }-}--bool Heap::find_hole(Mutator* m, uint32_t total) {-    uint32_t b = m->current_block;-    if (b == NO_BLOCK)-        return false;-    uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;-    size_t off = static_cast<uint8_t*>(m->cursor) - block;-    if (off >= BLOCK_SIZE)-        return false;-    uint32_t line = static_cast<uint32_t>(off) / LINE_SIZE;-    uint32_t base_line = b * LINES_PER_BLOCK;--    while (line < LINES_PER_BLOCK) {-        if (line_marks[base_line + line] == epoch) {-            line++;-            continue;-        }-        uint32_t end = line;-        while (end < LINES_PER_BLOCK && line_marks[base_line + end] != epoch)-            end++;-        uint32_t bytes = (end - line) * LINE_SIZE;-        if (bytes >= total) {-            m->cursor = block + static_cast<size_t>(line) * LINE_SIZE;-            m->limit = block + static_cast<size_t>(end) * LINE_SIZE;-            return true;-        }-        line = end;-    }-    return false;-}--bool Heap::try_alloc(Mutator* m, uint32_t total, uint32_t type_id, void** out) {-    uint8_t* p = static_cast<uint8_t*>(m->cursor);-    if (!p || p + total > static_cast<uint8_t*>(m->limit))-        return false;--    uint32_t b = m->current_block;-    if (b == NO_BLOCK)-        return false;--    uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;-    uint32_t first_line = static_cast<uint32_t>(p - block) / LINE_SIZE;-    uint32_t last_line = static_cast<uint32_t>((p + total - 1) - block) / LINE_SIZE;-    uint32_t base_line = b * LINES_PER_BLOCK;--    m->cursor = p + total;--    Header* h = reinterpret_cast<Header*>(p);-    h->type_id = type_id;-    h->mark = 0;-    h->flags = 0;-    h->aux = 0;-    std::memset(p + HEADER_SIZE, 0, total - HEADER_SIZE);--    for (uint32_t line = first_line; line <= last_line; line++)-        line_marks[base_line + line] = epoch;--    meta[b].state = static_cast<uint8_t>(BlockState::ALLOCATING);-    allocations++;-    *out = p;-    return true;-}--void* Heap::allocate_large(uint32_t total, uint32_t type_id) {-    if (nlarge >= MAX_LARGE) {-        report("large object table exhausted");-        std::abort();-    }-    void* p = os_alloc_zeroed(total);-    if (!p)-        return nullptr;-    Header* h = static_cast<Header*>(p);-    h->type_id = type_id;-    h->mark = 0;-    h->flags = LARGE;-    h->aux = 0;-    large[nlarge].base = p;-    large[nlarge].size = total;-    nlarge++;-    allocations++;-    return p;-}--void* Heap::allocate_ordinary(uint32_t total, uint32_t type_id) {-    Mutator* m = current();--    for (uint32_t attempt = 0; attempt < 2; attempt++) {-        for (;;) {-            if (m->current_block != NO_BLOCK) {-                void* p = nullptr;-                if (try_alloc(m, total, type_id, &p))-                    return p;-                if (find_hole(m, total) && try_alloc(m, total, type_id, &p))-                    return p;-                meta[m->current_block].state = static_cast<uint8_t>(BlockState::FULL);-                m->current_block = NO_BLOCK;-                m->cursor = m->limit = nullptr;-            }--            uint32_t b = acquire_block();-            if (b == NO_BLOCK)-                break;-            m->current_block = b;-            uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;-            m->cursor = block;-            m->limit = block + BLOCK_SIZE;--            if (meta[b].marked_lines != 0) {-                void* p = nullptr;-                if (find_hole(m, total) && try_alloc(m, total, type_id, &p))-                    return p;-                meta[b].state = static_cast<uint8_t>(BlockState::FULL);-                m->current_block = NO_BLOCK;-                m->cursor = m->limit = nullptr;-                continue;-            }--            void* p = nullptr;-            if (try_alloc(m, total, type_id, &p))-                return p;-            meta[b].state = static_cast<uint8_t>(BlockState::FULL);-            m->current_block = NO_BLOCK;-            m->cursor = m->limit = nullptr;-        }-        collect();-    }-    return nullptr;-}--void* Heap::allocate(uint32_t payload, uint32_t type_id) {-    init();--    if (stress_n) {-        if (++stress_counter >= stress_n) {-            stress_counter = 0;-            collect();-        }-    }--    uint32_t total;-    if (type_id == 0) {-        total = align_up(HEADER_SIZE + payload, GRANULE);-        type_id = type_for_size(total);-    } else {-        total = types[type_id].size;-        if (total < align_up(HEADER_SIZE + payload, GRANULE))-            total = align_up(HEADER_SIZE + payload, GRANULE);-    }--    if (total > LARGE_THRESHOLD) {-        void* p = allocate_large(total, type_id);-        if (!p) {-            collect();-            p = allocate_large(total, type_id);-        }-        return p;-    }--    void* p = allocate_ordinary(total, type_id);-    if (!p) {-        collect();-        p = allocate_ordinary(total, type_id);-    }-    if (!p) {-        report("out of heap after collection");-        std::abort();-    }-    return p;-}--void Heap::mark_object(void* obj) {-    static void* stack[MARK_STACK];-    size_t sp = 0;--    if (!obj)-        return;-    stack[sp++] = obj;--    while (sp) {-        void* p = stack[--sp];-        bool large_object = is_large_object(p);-        if (!in_heap(p) && !large_object)-            continue;-        if (reinterpret_cast<uintptr_t>(p) & (GRANULE - 1))-            continue;--        Header* h = reinterpret_cast<Header*>(p);-        if (h->mark == epoch)-            continue;-        h->mark = epoch;--        if (!(h->flags & LARGE) && !large_object) {-            uint32_t b = block_index(p);-            uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;-            uint32_t first = static_cast<uint32_t>(static_cast<uint8_t*>(p) - block) / LINE_SIZE;-            uint32_t total = types[h->type_id].size;-            if (total == 0)-                continue;-            uint32_t last =-                static_cast<uint32_t>((static_cast<uint8_t*>(p) + total - 1) - block) / LINE_SIZE;-            uint32_t base_line = b * LINES_PER_BLOCK;-            for (uint32_t line = first; line <= last; line++)-                line_marks[base_line + line] = epoch;-        }--        const TypeDesc& td = types[h->type_id];-        if (td.pointer_count && td.pointer_offsets) {-            for (uint32_t i = 0; i < td.pointer_count; i++) {-                uint32_t off = td.pointer_offsets[i];-                void* child = nullptr;-                std::memcpy(&child, static_cast<uint8_t*>(p) + off, sizeof(child));-                if (child && sp < MARK_STACK)-                    stack[sp++] = child;-            }-        }-    }-}--void Heap::mark_roots() {-    Mutator* m = current();--    for (XyzRootFrame* f = m->root_frame; f; f = f->previous) {-        if (!f->descriptor || !f->slots)-            continue;-        const RootMap* map = reinterpret_cast<const RootMap*>(f->descriptor);-        for (uint32_t i = 0; i < map->count; i++)-            mark_object(f->slots[i]);-    }--    for (uint32_t i = 0; i < nroots; i++) {-        if (global_roots[i])-            mark_object(*global_roots[i]);-    }--    for (uint32_t i = 0; i < npinned; i++)-        mark_object(pinned[i]);-}--void Heap::sweep() {-    uint64_t live_total = 0;--    for (uint32_t b = 0; b < nblocks; b++) {-        uint8_t state = meta[b].state;-        if (state == static_cast<uint8_t>(BlockState::FREE) ||-            state == static_cast<uint8_t>(BlockState::LOS_RESERVED))-            continue;--        uint32_t base_line = b * LINES_PER_BLOCK;-        uint32_t live = 0;-        for (uint32_t i = 0; i < LINES_PER_BLOCK; i++)-            if (line_marks[base_line + i] == epoch)-                live++;--        live_total += live;--        if (live == 0) {-            if (poison) {-                uint8_t* block = base + static_cast<size_t>(b) * BLOCK_SIZE;-                std::memset(block, 0xDD, BLOCK_SIZE);-            }-            push_free(b);-        } else if (live == LINES_PER_BLOCK) {-            meta[b].state = static_cast<uint8_t>(BlockState::FULL);-            meta[b].marked_lines = LINES_PER_BLOCK;-            meta[b].holes = 0;-        } else {-            uint32_t holes = 0;-            bool in_hole = false;-            for (uint32_t i = 0; i < LINES_PER_BLOCK; i++) {-                bool dead = line_marks[base_line + i] != epoch;-                if (dead && !in_hole) {-                    holes++;-                    in_hole = true;-                } else if (!dead) {-                    in_hole = false;-                }-            }-            meta[b].marked_lines = static_cast<uint16_t>(live);-            meta[b].holes = static_cast<uint16_t>(holes);-            push_recyclable(b);-        }-    }--    for (uint32_t i = 0; i < nlarge;) {-        Header* h = static_cast<Header*>(large[i].base);-        if (h->mark != epoch) {-            os_free(large[i].base, large[i].size);-            large[i] = large[--nlarge];-        } else {-            i++;-        }-    }--    live_lines_last = live_total;-}--void Heap::reset_mutator(Mutator* m) {-    m->cursor = nullptr;-    m->limit = nullptr;-    m->ocursor = nullptr;-    m->olimit = nullptr;-    m->current_block = NO_BLOCK;-    m->overflow_block = NO_BLOCK;-}--void Heap::collect() {-    if (!init())-        return;--    if (verify_mode)-        verify(false);--    collections++;--    if (epoch == 255) {-        std::memset(line_marks, 0, static_cast<size_t>(nblocks) * LINES_PER_BLOCK);-        epoch = 1;-    } else {-        epoch++;-    }--    for (uint32_t i = 0; i < nlarge; i++) {-        Header* h = static_cast<Header*>(large[i].base);-        h->mark = 0;-    }--    /* Invalidating mutator cursors first is what makes the collection-     * stop-the-world even in the single-threaded M0 implementation. */-    reset_mutator(current());-    recyclable_head = NO_BLOCK;--    mark_roots();-    sweep();--    gc_requested = false;--    if (verify_mode)-        verify(true);--    if (log)-        report("gc #%llu epoch=%u live_lines=%llu large=%u free_head=%u",-               static_cast<unsigned long long>(collections), epoch,-               static_cast<unsigned long long>(live_lines_last), nlarge, free_head);-}--void Heap::verify(bool after) {-    if (!initialized)-        return;--    auto fail = [](const char* what) {-        std::fprintf(stderr, "xyzrt: heap verification failed: %s\n", what);-        std::abort();-    };--    Mutator* m = current();--    for (XyzRootFrame* f = m->root_frame; f; f = f->previous) {-        if (!f->descriptor || !f->slots)-            fail("root frame has no descriptor or slots");-        const RootMap* map = reinterpret_cast<const RootMap*>(f->descriptor);-        for (uint32_t i = 0; i < map->count; i++) {-            void* p = f->slots[i];-            if (!p)-                continue;-            if (!in_heap(p) && !is_large_object(p))-                fail("root slot points outside the heap");-            if (reinterpret_cast<uintptr_t>(p) & (GRANULE - 1))-                fail("root slot is not granule aligned");-            Header* h = static_cast<Header*>(p);-            if (h->type_id == 0)-                fail("root slot has no type descriptor");-            if (after && h->mark != epoch)-                fail("live root was not marked");-        }-    }--    for (uint32_t i = 0; i < nroots; i++)-        if (global_roots[i] && *global_roots[i] && !in_heap(*global_roots[i]))-            fail("global root points outside the heap");--    for (uint32_t i = 0; i < nlarge; i++)-        if (reinterpret_cast<uintptr_t>(large[i].base) & (GRANULE - 1))-            fail("large object is not granule aligned");--    for (uint32_t b = 0; b < nblocks; b++) {-        uint8_t state = meta[b].state;-        if (state > static_cast<uint8_t>(BlockState::LOS_RESERVED))-            fail("invalid block state");-        if (state != static_cast<uint8_t>(BlockState::FREE) &&-            state != static_cast<uint8_t>(BlockState::LOS_RESERVED) && after &&-            meta[b].marked_lines == 0 && meta[b].holes == LINES_PER_BLOCK)-            fail("allocated block has no marked lines");-    }-}--void Heap::report(const char* fmt, ...) {-    va_list ap;-    va_start(ap, fmt);-    std::vfprintf(stderr, fmt, ap);-    va_end(ap);-    std::fputc('\n', stderr);-}--} // namespace--extern "C" {--void xyz_runtime_init(void) {-    g_heap.init();-}--void* xyz_alloc_slow(uint32_t payload_size, uint32_t type_id) {-    return g_heap.allocate(payload_size, type_id);-}--void* xyz_alloc_large(uint32_t payload_size, uint32_t type_id) {-    g_heap.init();-    uint32_t total = align_up(HEADER_SIZE + payload_size, GRANULE);-    if (type_id == 0)-        type_id = g_heap.type_for_size(total);-    return g_heap.allocate_large(total, type_id);-}--uint32_t xyz_type_for_size(uint32_t total_size) {-    g_heap.init();-    return g_heap.type_for_size(total_size);-}--uint32_t xyz_register_type(uint32_t total_size, uint32_t pointer_count,-                           const uint32_t* pointer_offsets) {-    g_heap.init();-    return g_heap.register_type(total_size, pointer_count, pointer_offsets);-}--void xyz_gc_request(void) {-    g_heap.gc_requested = true;-}--void xyz_gc_poll(void) {-    if (g_heap.gc_requested)-        g_heap.collect();-}--void xyz_gc_collect(void) {-    g_heap.collect();-}--void xyz_gc_verify(void) {-    g_heap.verify(true);-}--int xyz_gc_object_alive(void* object) {-    if (!g_heap.initialized || !object)-        return 0;-    if (!g_heap.in_heap(object) && !g_heap.is_large_object(object))-        return 0;-    Header* h = static_cast<Header*>(object);-    return h->mark == g_heap.epoch;-}--void xyz_thread_attach(void) {-    g_heap.init();-    if (!tls_mutator) {-        Mutator* m = static_cast<Mutator*>(os_alloc_zeroed(sizeof(Mutator)));-        if (!m) {-            xyz_panic("could not allocate mutator");-            return;-        }-        m->current_block = NO_BLOCK;-        m->overflow_block = NO_BLOCK;-        tls_mutator = m;-    }-}--void xyz_thread_detach(void) {-    tls_mutator = nullptr;-}--void xyz_root_enter(XyzRootFrame* frame) {-    if (!frame)-        return;-    Mutator* m = g_heap.current();-    frame->previous = m->root_frame;-    m->root_frame = frame;-}--void xyz_root_leave(XyzRootFrame* frame) {-    if (!frame)-        return;-    Mutator* m = g_heap.current();-    if (m->root_frame == frame) {-        m->root_frame = frame->previous;-        return;-    }-    for (XyzRootFrame* f = m->root_frame; f; f = f->previous) {-        if (f->previous == frame) {-            f->previous = frame->previous;-            return;-        }-    }-}--void xyz_root_add(void** slot) {-    g_heap.init();-    if (g_heap.nroots < MAX_GLOBAL_ROOTS)-        g_heap.global_roots[g_heap.nroots++] = slot;-}--void xyz_root_remove(void** slot) {-    for (uint32_t i = 0; i < g_heap.nroots; i++) {-        if (g_heap.global_roots[i] == slot) {-            g_heap.global_roots[i] = g_heap.global_roots[--g_heap.nroots];-            return;-        }-    }-}--void xyz_native_enter(void) {}-void xyz_native_exit(void) {}--void xyz_pin(void* object) {-    if (!object || !g_heap.in_heap(object))-        return;-    Header* h = static_cast<Header*>(object);-    h->flags |= PINNED;-    if (g_heap.npinned < MAX_PINNED)-        g_heap.pinned[g_heap.npinned++] = object;-}--void xyz_unpin(void* object) {-    if (!object)-        return;-    Header* h = static_cast<Header*>(object);-    h->flags &= ~PINNED;-    for (uint32_t i = 0; i < g_heap.npinned; i++) {-        if (g_heap.pinned[i] == object) {-            g_heap.pinned[i] = g_heap.pinned[--g_heap.npinned];-            return;-        }-    }-}--void xyz_wb(void* object, void** slot, void* value) {-    if (!object || !slot)-        return;-    *slot = value;-    Header* h = static_cast<Header*>(object);-    h->flags |= REMEMBERED;-}--void xyz_print_i32(int32_t value) {-    std::printf("%d\n", value);-}--void xyz_print_i64(int64_t value) {-    std::printf("%lld\n", static_cast<long long>(value));-}--void xyz_print_bool(int32_t value) {-    std::fputs(value ? "true\n" : "false\n", stdout);-}--void xyz_print_str(const char* value) {-    std::fputs(value ? value : "", stdout);-    std::fputc('\n', stdout);-}--void xyz_panic(const char* message) {-    std::fprintf(stderr, "xyz: %s\n", message ? message : "panic");-    std::fflush(stderr);-    std::exit(1);-}--} // extern "C"--- a/runtime/xyzrt.h+++ /dev/null@@ -1,61 +0,0 @@-#ifndef XYZRT_H-#define XYZRT_H--#include <stdint.h>--#ifdef __cplusplus-extern "C" {-#endif--typedef struct XyzRootMap {-    uint32_t count;-    uint32_t frame_size;-    const uint32_t* offsets;-} XyzRootMap;--typedef struct XyzRootFrame {-    struct XyzRootFrame* previous;-    const XyzRootMap* descriptor;-    void** slots;-} XyzRootFrame;--/* Collector entry points.  All of these use the C ABI. */-void xyz_runtime_init(void);-void* xyz_alloc_slow(uint32_t payload_size, uint32_t type_id);-void* xyz_alloc_large(uint32_t payload_size, uint32_t type_id);-uint32_t xyz_type_for_size(uint32_t total_size);-uint32_t xyz_register_type(uint32_t total_size, uint32_t pointer_count,-                           const uint32_t* pointer_offsets);--void xyz_gc_poll(void);-void xyz_gc_request(void);-void xyz_gc_collect(void);-void xyz_gc_verify(void);-int xyz_gc_object_alive(void* object);--void xyz_thread_attach(void);-void xyz_thread_detach(void);--void xyz_root_enter(XyzRootFrame* frame);-void xyz_root_leave(XyzRootFrame* frame);-void xyz_root_add(void** slot);-void xyz_root_remove(void** slot);--void xyz_native_enter(void);-void xyz_native_exit(void);-void xyz_pin(void* object);-void xyz_unpin(void* object);-void xyz_wb(void* object, void** slot, void* value);--/* Small runtime used by generated programs. */-void xyz_print_i32(int32_t value);-void xyz_print_i64(int64_t value);-void xyz_print_bool(int32_t value);-void xyz_print_str(const char* value);-void xyz_panic(const char* message);--#ifdef __cplusplus-}-#endif--#endifBinary files a/samples/baseline/01_hello and b/samples/baseline/01_hello differ--- /dev/null+++ b/samples/baseline/01_hello.hz@@ -0,0 +1,5 @@+// 01: the smallest program.++fn main() {+    print("hello, haze")       // hello, haze+}--- a/samples/baseline/01_hello.xyz+++ /dev/null@@ -1,5 +0,0 @@-// 01: the smallest program.--fn main() {-    print("hello, xyz")       // hello, xyz-}--- /dev/null+++ b/samples/baseline/02_values.hz@@ -0,0 +1,16 @@+// 02: constants, variables, integer arithmetic.++fn main() {+    const a = 7+    const b = 3+    var total = a + b * 2+    print(total)              // 13+    total = total - 1+    print(total)              // 12+    total += 10+    print(total)              // 22+    print(a / b)              // 2+    print(a % b)              // 1+    print(-a)                 // -7+    print("done")             // done+}--- a/samples/baseline/02_values.xyz+++ /dev/null@@ -1,16 +0,0 @@-// 02: constants, variables, integer arithmetic.--fn main() {-    const a = 7-    const b = 3-    var total = a + b * 2-    print(total)              // 13-    total = total - 1-    print(total)              // 12-    total += 10-    print(total)              // 22-    print(a / b)              // 2-    print(a % b)              // 1-    print(-a)                 // -7-    print("done")             // done-}Binary files a/samples/baseline/03_functions and b/samples/baseline/03_functions differ--- /dev/null+++ b/samples/baseline/03_functions.hz@@ -0,0 +1,22 @@+// 03: functions, expression bodies vs block bodies, calls.++fn add(a i32, b i32) i32 => a + b++fn square(x i32) i32 {+    return x * x+}++fn sum_of_squares(a i32, b i32) i32 => add(square(a), square(b))++fn greet(name str) {+    print("hello")+    print(name)+}++fn main() {+    print(add(2, 3))              // 5+    print(square(7))              // 49+    print(sum_of_squares(3, 4))   // 25+    greet("world")                // hello+                                  // world+}--- a/samples/baseline/03_functions.xyz+++ /dev/null@@ -1,22 +0,0 @@-// 03: functions, expression bodies vs block bodies, calls.--fn add(a i32, b i32) i32 => a + b--fn square(x i32) i32 {-    return x * x-}--fn sum_of_squares(a i32, b i32) i32 => add(square(a), square(b))--fn greet(name str) {-    print("hello")-    print(name)-}--fn main() {-    print(add(2, 3))              // 5-    print(square(7))              // 49-    print(sum_of_squares(3, 4))   // 25-    greet("world")                // hello-                                  // world-}--- /dev/null+++ b/samples/baseline/04_conditionals.hz@@ -0,0 +1,38 @@+// 04: if / else if / else, as a statement and as an expression.++fn abs(x i32) i32 {+    if x < 0 {+        return -x+    }+    return x+}++fn max(a i32, b i32) i32 => if a > b { a } else { b }++fn sign(x i32) i32 => if x < 0 { -1 } else if x == 0 { 0 } else { 1 }++fn is_even(n i32) bool => n % 2 == 0++fn in_range(x i32, lo i32, hi i32) bool => x >= lo && x <= hi++fn main() {+    print(abs(-5))                // 5+    print(abs(5))                 // 5+    print(max(3, 9))              // 9+    print(max(9, 3))              // 9+    print(sign(-4))               // -1+    print(sign(0))                // 0+    print(sign(12))               // 1++    if is_even(10) {+        print("even")             // even+    } else {+        print("odd")+    }++    if in_range(15, 1, 10) {+        print("in")+    } else {+        print("out")              // out+    }+}--- a/samples/baseline/04_conditionals.xyz+++ /dev/null@@ -1,38 +0,0 @@-// 04: if / else if / else, as a statement and as an expression.--fn abs(x i32) i32 {-    if x < 0 {-        return -x-    }-    return x-}--fn max(a i32, b i32) i32 => if a > b { a } else { b }--fn sign(x i32) i32 => if x < 0 { -1 } else if x == 0 { 0 } else { 1 }--fn is_even(n i32) bool => n % 2 == 0--fn in_range(x i32, lo i32, hi i32) bool => x >= lo && x <= hi--fn main() {-    print(abs(-5))                // 5-    print(abs(5))                 // 5-    print(max(3, 9))              // 9-    print(max(9, 3))              // 9-    print(sign(-4))               // -1-    print(sign(0))                // 0-    print(sign(12))               // 1--    if is_even(10) {-        print("even")             // even-    } else {-        print("odd")-    }--    if in_range(15, 1, 10) {-        print("in")-    } else {-        print("out")              // out-    }-}--- /dev/null+++ b/samples/baseline/05_loops.hz@@ -0,0 +1,44 @@+// 05: `for x in a..b` (half-open), `for cond`, break, continue.++fn sum_below(n i32) i32 {+    var total = 0+    for i in 0..n {+        total += i+    }+    return total+}++fn count_digits(n i32) i32 {+    var digits = 1+    var rest = n+    for rest >= 10 {+        rest = rest / 10+        digits+++    }+    return digits+}++fn first_square_over(limit i32) i32 {+    var i = 1+    for i * i <= limit {+        i+++    }+    return i * i+}++fn main() {+    print(sum_below(5))           // 10+    print(count_digits(12345))    // 5+    print(count_digits(7))        // 1+    print(first_square_over(50))  // 64++    for i in 0..10 {+        if i % 2 == 0 {+            continue+        }+        if i > 7 {+            break+        }+        print(i)                  // 1, 3, 5, 7 (one per line)+    }+}--- a/samples/baseline/05_loops.xyz+++ /dev/null@@ -1,44 +0,0 @@-// 05: `for x in a..b` (half-open), `for cond`, break, continue.--fn sum_below(n i32) i32 {-    var total = 0-    for i in 0..n {-        total += i-    }-    return total-}--fn count_digits(n i32) i32 {-    var digits = 1-    var rest = n-    for rest >= 10 {-        rest = rest / 10-        digits++-    }-    return digits-}--fn first_square_over(limit i32) i32 {-    var i = 1-    for i * i <= limit {-        i++-    }-    return i * i-}--fn main() {-    print(sum_below(5))           // 10-    print(count_digits(12345))    // 5-    print(count_digits(7))        // 1-    print(first_square_over(50))  // 64--    for i in 0..10 {-        if i % 2 == 0 {-            continue-        }-        if i > 7 {-            break-        }-        print(i)                  // 1, 3, 5, 7 (one per line)-    }-}--- /dev/null+++ b/samples/baseline/06_lists.hz@@ -0,0 +1,28 @@+// 06: list literals, .len, indexing, for-in.++fn sum(xs list[i32]) i32 {+    var total = 0+    for x in xs {+        total += x+    }+    return total+}++fn count_above(xs list[i32], limit i32) i32 {+    var n = 0+    for x in xs {+        if x > limit {+            n+++        }+    }+    return n+}++fn main() {+    const xs = [4, 8, 15, 16, 23, 42]+    print(xs.len)                 // 6+    print(xs[0])                  // 4+    print(xs[5])                  // 42+    print(sum(xs))                // 108+    print(count_above(xs, 15))    // 3+}--- a/samples/baseline/06_lists.xyz+++ /dev/null@@ -1,28 +0,0 @@-// 06: list literals, .len, indexing, for-in.--fn sum(xs list[i32]) i32 {-    var total = 0-    for x in xs {-        total += x-    }-    return total-}--fn count_above(xs list[i32], limit i32) i32 {-    var n = 0-    for x in xs {-        if x > limit {-            n++-        }-    }-    return n-}--fn main() {-    const xs = [4, 8, 15, 16, 23, 42]-    print(xs.len)                 // 6-    print(xs[0])                  // 4-    print(xs[5])                  // 42-    print(sum(xs))                // 108-    print(count_above(xs, 15))    // 3-}--- /dev/null+++ b/samples/baseline/07_records.hz@@ -0,0 +1,22 @@+// 07: records. Data is immutable: "changing" a value builds a new one.++type Point {+    x i32+    y i32+}++fn moved(p Point, dx i32, dy i32) Point => Point{ x = p.x + dx, y = p.y + dy }++fn add(a Point, b Point) Point => Point{ x = a.x + b.x, y = a.y + b.y }++fn dist2(p Point) i32 => p.x * p.x + p.y * p.y++fn main() {+    const p = Point{ x = 3, y = 4 }+    const q = moved(p, 1, 1)+    print(p.x)                    // 3   (p is unchanged)+    print(q.x)                    // 4+    print(q.y)                    // 5+    print(dist2(p))               // 25+    print(add(p, q).y)            // 9+}--- a/samples/baseline/07_records.xyz+++ /dev/null@@ -1,22 +0,0 @@-// 07: records. Data is immutable: "changing" a value builds a new one.--type Point {-    x i32-    y i32-}--fn moved(p Point, dx i32, dy i32) Point => Point{ x = p.x + dx, y = p.y + dy }--fn add(a Point, b Point) Point => Point{ x = a.x + b.x, y = a.y + b.y }--fn dist2(p Point) i32 => p.x * p.x + p.y * p.y--fn main() {-    const p = Point{ x = 3, y = 4 }-    const q = moved(p, 1, 1)-    print(p.x)                    // 3   (p is unchanged)-    print(q.x)                    // 4-    print(q.y)                    // 5-    print(dist2(p))               // 25-    print(add(p, q).y)            // 9-}--- /dev/null+++ b/samples/baseline/08_sum_types.hz@@ -0,0 +1,28 @@+// 08: sum types and match (as an expression and as a statement).++type Shape =+    | Square(side i32)+    | Rect(w i32, h i32)+    | Dot++fn area(s Shape) i32 => match s {+    Square(side) => side * side+    Rect(w, h)   => w * h+    Dot          => 0+}++fn describe(s Shape) {+    match s {+        Square(_)  => print("square")+        Rect(_, _) => print("rect")+        Dot        => print("dot")+    }+}++fn main() {+    print(area(Square(5)))        // 25+    print(area(Rect(3, 4)))       // 12+    print(area(Dot))              // 0+    describe(Rect(1, 2))          // rect+    describe(Dot)                 // dot+}--- a/samples/baseline/08_sum_types.xyz+++ /dev/null@@ -1,28 +0,0 @@-// 08: sum types and match (as an expression and as a statement).--type Shape =-    | Square(side i32)-    | Rect(w i32, h i32)-    | Dot--fn area(s Shape) i32 => match s {-    Square(side) => side * side-    Rect(w, h)   => w * h-    Dot          => 0-}--fn describe(s Shape) {-    match s {-        Square(_)  => print("square")-        Rect(_, _) => print("rect")-        Dot        => print("dot")-    }-}--fn main() {-    print(area(Square(5)))        // 25-    print(area(Rect(3, 4)))       // 12-    print(area(Dot))              // 0-    describe(Rect(1, 2))          // rect-    describe(Dot)                 // dot-}--- /dev/null+++ b/samples/baseline/09_contracts.hz@@ -0,0 +1,37 @@+// 09: inline contracts. One `: pre` / `: post` clause per line, before the `{`.+// A milestone-1 compiler can turn each clause into a runtime assertion.++fn clamp(x i32, lo i32, hi i32) i32+    : pre lo <= hi+    : post r => r >= lo && r <= hi+{+    if x < lo {+        return lo+    }+    if x > hi {+        return hi+    }+    return x+}++fn safe_div(a i32, b i32) i32+    : pre a >= 0+    : pre b > 0+    : post r => r >= 0 && r <= a+{+    return a / b+}++fn main() {+    print(clamp(15, 0, 10))       // 10+    print(clamp(-3, 0, 10))       // 0+    print(clamp(4, 0, 10))        // 4+    print(safe_div(17, 5))        // 3+    print(safe_div(0, 9))         // 0++    // Each of these must be rejected (compile time, or a runtime panic at milestone 1):+    //+    // clamp(1, 5, 2)             // pre `lo <= hi` violated+    // safe_div(10, 0)            // pre `b > 0` violated+    // safe_div(-1, 2)            // pre `a >= 0` violated+}--- a/samples/baseline/09_contracts.xyz+++ /dev/null@@ -1,37 +0,0 @@-// 09: inline contracts. One `: pre` / `: post` clause per line, before the `{`.-// A milestone-1 compiler can turn each clause into a runtime assertion.--fn clamp(x i32, lo i32, hi i32) i32-    : pre lo <= hi-    : post r => r >= lo && r <= hi-{-    if x < lo {-        return lo-    }-    if x > hi {-        return hi-    }-    return x-}--fn safe_div(a i32, b i32) i32-    : pre a >= 0-    : pre b > 0-    : post r => r >= 0 && r <= a-{-    return a / b-}--fn main() {-    print(clamp(15, 0, 10))       // 10-    print(clamp(-3, 0, 10))       // 0-    print(clamp(4, 0, 10))        // 4-    print(safe_div(17, 5))        // 3-    print(safe_div(0, 9))         // 0--    // Each of these must be rejected (compile time, or a runtime panic at milestone 1):-    //-    // clamp(1, 5, 2)             // pre `lo <= hi` violated-    // safe_div(10, 0)            // pre `b > 0` violated-    // safe_div(-1, 2)            // pre `a >= 0` violated-}--- /dev/null+++ b/samples/baseline/10_named_contracts.hz@@ -0,0 +1,47 @@+// 10: named contracts, pure functions in contracts, contract reuse.++pure fn even(n i32) bool => n % 2 == 0++contract Even(n i32) {+    pre even(n)+}++fn half(n i32) i32+    : Even(n)+    : post r => r * 2 == n+{+    return n / 2+}++// FactorialCond from the original sketch.+// Note: a static verifier cannot prove the multiplication stays in i32 from+// `r >= 1` alone; as runtime assertions it is checked on every call.+contract FactorialCond(n i32) {+    pre {+        n >= 0+        n <= 12+    }+    post r => r >= 1+}++fn factorial(n i32) i32+    : FactorialCond(n)+{+    if n <= 1 {+        return 1+    }+    return n * factorial(n - 1)+}++fn main() {+    print(half(10))               // 5+    print(factorial(0))           // 1+    print(factorial(5))           // 120+    print(factorial(12))          // 479001600++    // Must be rejected:+    //+    // half(7)                    // pre `even(n)` violated+    // factorial(13)              // pre `n <= 12` violated+    // factorial(-1)              // pre `n >= 0` violated+}--- a/samples/baseline/10_named_contracts.xyz+++ /dev/null@@ -1,47 +0,0 @@-// 10: named contracts, pure functions in contracts, contract reuse.--pure fn even(n i32) bool => n % 2 == 0--contract Even(n i32) {-    pre even(n)-}--fn half(n i32) i32-    : Even(n)-    : post r => r * 2 == n-{-    return n / 2-}--// FactorialCond from the original sketch.-// Note: a static verifier cannot prove the multiplication stays in i32 from-// `r >= 1` alone; as runtime assertions it is checked on every call.-contract FactorialCond(n i32) {-    pre {-        n >= 0-        n <= 12-    }-    post r => r >= 1-}--fn factorial(n i32) i32-    : FactorialCond(n)-{-    if n <= 1 {-        return 1-    }-    return n * factorial(n - 1)-}--fn main() {-    print(half(10))               // 5-    print(factorial(0))           // 1-    print(factorial(5))           // 120-    print(factorial(12))          // 479001600--    // Must be rejected:-    //-    // half(7)                    // pre `even(n)` violated-    // factorial(13)              // pre `n <= 12` violated-    // factorial(-1)              // pre `n >= 0` violated-}--- /dev/null+++ b/samples/baseline_2/main.hz@@ -0,0 +1,64 @@+// Functional chains and modules.+//+// Module rules used here:+//   - one file is one module, named after the file (no declaration line)+//   - items are private unless marked `pub`+//   - `import m`          gives qualified access only:       m::name+//   - `import m::{a, b}`  brings names into scope unqualified, so they work+//                         as plain calls and as dot-calls (UFCS): xs.a(...)+//   - `::` is for module paths; `.` stays for fields and UFCS++use seq+use seq {range, map, filter, fold, take, all}+use orders {Order, total, is_big}++fn add(a i32, b i32) i32 => a + b++fn main() {+    const squares = range(1, 11)+        .filter(fn(n) => n % 2 == 0)+        .map(fn(n) => n * n)+        .fold(0, add)+    print(squares)                                     // 220++    const orders = [+        Order{ id = 1, qty = 2,  price = 30 },+        Order{ id = 2, qty = 1,  price = 15 },+        Order{ id = 3, qty = 5,  price = 40 },+        Order{ id = 4, qty = 10, price = 2 },+    ]++    print(orders.map(total).fold(0, add))              // 295+    print(orders.filter(is_big).map(total).fold(0, add))   // 200++    const bulk_ids = orders+        .filter(fn(o) => o.qty > 1)+        .map(fn(o) => o.id)++    for id in bulk_ids {+        print(id)+    }++    const firsts = range(0, 100)+        .map(fn(n) => n * 3)+        .filter(fn(n) => n % 2 == 1)+        .take(4)++    for n in firsts {+        print(n)                                       // 3, 9, 15, 21 (one per line)+    }++    print(seq::fold(seq::range(1, 6), 1, fn(acc, n) => acc * n))   // 120++    if orders.all(fn(o) => o.qty > 0) {+        print("all positive")                          // all positive+    } else {+        print("some empty")+    }++    // Each of these must be rejected:+    //+    // orders::BIG_ORDER          // error: `BIG_ORDER` is private to `orders`+    // range(5, 1)                // pre `lo <= hi` violated+    // orders.take(-1)            // pre `n >= 0` violated+}--- a/samples/baseline_2/main.xyz+++ /dev/null@@ -1,64 +0,0 @@-// Functional chains and modules.-//-// Module rules used here:-//   - one file is one module, named after the file (no declaration line)-//   - items are private unless marked `pub`-//   - `import m`          gives qualified access only:       m::name-//   - `import m::{a, b}`  brings names into scope unqualified, so they work-//                         as plain calls and as dot-calls (UFCS): xs.a(...)-//   - `::` is for module paths; `.` stays for fields and UFCS--use seq-use seq {range, map, filter, fold, take, all}-use orders {Order, total, is_big}--fn add(a i32, b i32) i32 => a + b--fn main() {-    const squares = range(1, 11)-        .filter(fn(n) => n % 2 == 0)-        .map(fn(n) => n * n)-        .fold(0, add)-    print(squares)                                     // 220--    const orders = [-        Order{ id = 1, qty = 2,  price = 30 },-        Order{ id = 2, qty = 1,  price = 15 },-        Order{ id = 3, qty = 5,  price = 40 },-        Order{ id = 4, qty = 10, price = 2 },-    ]--    print(orders.map(total).fold(0, add))              // 295-    print(orders.filter(is_big).map(total).fold(0, add))   // 200--    const bulk_ids = orders-        .filter(fn(o) => o.qty > 1)-        .map(fn(o) => o.id)--    for id in bulk_ids {-        print(id)-    }--    const firsts = range(0, 100)-        .map(fn(n) => n * 3)-        .filter(fn(n) => n % 2 == 1)-        .take(4)--    for n in firsts {-        print(n)                                       // 3, 9, 15, 21 (one per line)-    }--    print(seq::fold(seq::range(1, 6), 1, fn(acc, n) => acc * n))   // 120--    if orders.all(fn(o) => o.qty > 0) {-        print("all positive")                          // all positive-    } else {-        print("some empty")-    }--    // Each of these must be rejected:-    //-    // orders::BIG_ORDER          // error: `BIG_ORDER` is private to `orders`-    // range(5, 1)                // pre `lo <= hi` violated-    // orders.take(-1)            // pre `n >= 0` violated-}--- /dev/null+++ b/samples/baseline_2/orders.hz@@ -0,0 +1,13 @@+// Module `orders`: a small domain model.++const BIG_ORDER i32 = 100            // private: not visible outside this file++pub type Order {+    id    i32+    qty   i32+    price i32+}++pub pure fn total(o Order) i32 => o.qty * o.price++pub pure fn is_big(o Order) bool => total(o) >= BIG_ORDER--- a/samples/baseline_2/orders.xyz+++ /dev/null@@ -1,13 +0,0 @@-// Module `orders`: a small domain model.--const BIG_ORDER i32 = 100            // private: not visible outside this file--pub type Order {-    id    i32-    qty   i32-    price i32-}--pub pure fn total(o Order) i32 => o.qty * o.price--pub pure fn is_big(o Order) bool => total(o) >= BIG_ORDER--- /dev/null+++ b/samples/baseline_2/seq.hz@@ -0,0 +1,77 @@+// Module `seq`: list functions, written in Haze itself (no stdlib assumed).+// Every `pub` item is exported; anything without `pub` is private to this file.+// A pub function's contract may only mention pub names, because callers have+// to be able to read and reason about it.++pub pure fn min(a i32, b i32) i32 => if a < b { a } else { b }++pub fn range(lo i32, hi i32) list[i32]+    : pre lo >= 0                    // keeps `hi - lo` from overflowing+    : pre lo <= hi+    : post r => r.len == hi - lo+{+    var out list[i32] = []+    for i in lo..hi+        : invariant out.len == i - lo+    {+        out = out + [i]+    }+    return out+}++pub fn map[T, U](xs list[T], f fn(T) U) list[U]+    : post r => r.len == xs.len+{+    var out list[U] = []+    for i in 0..xs.len+        : invariant out.len == i+    {+        out = out + [f(xs[i])]+    }+    return out+}++pub fn filter[T](xs list[T], keep fn(T) bool) list[T]+    : post r => r.len <= xs.len+{+    var out list[T] = []+    for i in 0..xs.len+        : invariant out.len <= i+    {+        if keep(xs[i]) {+            out = out + [xs[i]]+        }+    }+    return out+}++pub fn fold[T, A](xs list[T], init A, f fn(A, T) A) A {+    var acc = init+    for x in xs {+        acc = f(acc, x)+    }+    return acc+}++pub fn take[T](xs list[T], n i32) list[T]+    : pre n >= 0+    : post r => r.len == min(n, xs.len)+{+    const count = min(n, xs.len)+    var out list[T] = []+    for i in 0..count+        : invariant out.len == i+    {+        out = out + [xs[i]]+    }+    return out+}++pub fn all[T](xs list[T], ok fn(T) bool) bool {+    for x in xs {+        if !ok(x) {+            return false+        }+    }+    return true+}--- a/samples/baseline_2/seq.xyz+++ /dev/null@@ -1,77 +0,0 @@-// Module `seq`: list functions, written in xyz itself (no stdlib assumed).-// Every `pub` item is exported; anything without `pub` is private to this file.-// A pub function's contract may only mention pub names, because callers have-// to be able to read and reason about it.--pub pure fn min(a i32, b i32) i32 => if a < b { a } else { b }--pub fn range(lo i32, hi i32) list[i32]-    : pre lo >= 0                    // keeps `hi - lo` from overflowing-    : pre lo <= hi-    : post r => r.len == hi - lo-{-    var out list[i32] = []-    for i in lo..hi-        : invariant out.len == i - lo-    {-        out = out + [i]-    }-    return out-}--pub fn map[T, U](xs list[T], f fn(T) U) list[U]-    : post r => r.len == xs.len-{-    var out list[U] = []-    for i in 0..xs.len-        : invariant out.len == i-    {-        out = out + [f(xs[i])]-    }-    return out-}--pub fn filter[T](xs list[T], keep fn(T) bool) list[T]-    : post r => r.len <= xs.len-{-    var out list[T] = []-    for i in 0..xs.len-        : invariant out.len <= i-    {-        if keep(xs[i]) {-            out = out + [xs[i]]-        }-    }-    return out-}--pub fn fold[T, A](xs list[T], init A, f fn(A, T) A) A {-    var acc = init-    for x in xs {-        acc = f(acc, x)-    }-    return acc-}--pub fn take[T](xs list[T], n i32) list[T]-    : pre n >= 0-    : post r => r.len == min(n, xs.len)-{-    const count = min(n, xs.len)-    var out list[T] = []-    for i in 0..count-        : invariant out.len == i-    {-        out = out + [xs[i]]-    }-    return out-}--pub fn all[T](xs list[T], ok fn(T) bool) bool {-    for x in xs {-        if !ok(x) {-            return false-        }-    }-    return true-}--- /dev/null+++ b/samples/baseline_3/sample1.hz@@ -0,0 +1,27 @@+contract FactorialCond(n i32) {+    pre {+        n >= 0 &&+        n <= 12+    }+    post r => {+        r >= 1+    }+}++// The ':' means "conforms to" in this scenario+fn factorial(n i32) i32 : FactorialCond(n) {+    if n <= 1 {+        return 1+    }+    return n * factorial(n - 1)+}++fn main(args list[str]) {+    for arg in args {+        print(arg)+    }+    const doubled = [1, 2, 3, 4, 5]+            .map(fn(x) => x * 2)+            .filter(fn(x) => x > 4)+    print(doubled)+}--- a/samples/baseline_3/sample1.xyz+++ /dev/null@@ -1,27 +0,0 @@-contract FactorialCond(n i32) {-    pre {-        n >= 0 &&-        n <= 12-    }-    post r => {-        r >= 1-    }-}--// The ':' means "conforms to" in this scenario-fn factorial(n i32) i32 : FactorialCond(n) {-    if n <= 1 {-        return 1-    }-    return n * factorial(n - 1)-}--fn main(args list[str]) {-    for arg in args {-        print(arg)-    }-    const doubled = [1, 2, 3, 4, 5]-            .map(fn(x) => x * 2)-            .filter(fn(x) => x > 4)-    print(doubled)-}--- /dev/null+++ b/samples/baseline_3/sample2.hz@@ -0,0 +1,61 @@+type List[T] =+    | Nil+    | Cons(head T, tail List[T])++interface Ord {+    fn lt(self Self, other Self) bool+}++impl Ord with i32 {+    fn lt(self i32, other i32) bool => self < other+}++pure fn len[T](xs List[T]) i32 => match xs {+    Nil        => 0+    Cons(_, t) => 1 + len(t)+}++pure fn sorted[T Ord](xs List[T]) bool => match xs {+    Cons(a, Cons(b, _) as rest) => !b.lt(a) && sorted(rest)+    _                           => true+}++contract Inserted[T Ord](x T, xs List[T]) {+    pre sorted(xs)+    post r => {+        sorted(r)+        len(r) == len(xs) + 1+    }+}++// Do some stuff...+fn insert[T Ord](x T, xs List[T]) List[T] : Inserted(x, xs) => match xs {+    Nil => Cons(x, Nil)+    Cons(h, t) => {+        if x.lt(h) {+            return Cons(x, xs)+        }+        return Cons(h, insert(x, t))+    }+}++fn sort[T Ord](xs List[T]) List[T] : { post r => sorted(r) && len(r) == len(xs) } => match xs {+    Nil        => Nil+    Cons(h, t) => insert(h, sort(t))+}++fn print_list(xs List[i32]) {+    match xs {+        Nil        => print("end")+        Cons(h, t) => {+            print(h)+            print_list(t)+        }+    }+}++fn main() {+    const xs = Cons(3, Cons(1, Cons(2, Nil)))+    const ys = sort(xs)+    print_list(ys)+}--- a/samples/baseline_3/sample2.xyz+++ /dev/null@@ -1,61 +0,0 @@-type List[T] =-    | Nil-    | Cons(head T, tail List[T])--interface Ord {-    fn lt(self Self, other Self) bool-}--impl Ord with i32 {-    fn lt(self i32, other i32) bool => self < other-}--pure fn len[T](xs List[T]) i32 => match xs {-    Nil        => 0-    Cons(_, t) => 1 + len(t)-}--pure fn sorted[T Ord](xs List[T]) bool => match xs {-    Cons(a, Cons(b, _) as rest) => !b.lt(a) && sorted(rest)-    _                           => true-}--contract Inserted[T Ord](x T, xs List[T]) {-    pre sorted(xs)-    post r => {-        sorted(r)-        len(r) == len(xs) + 1-    }-}--// Do some stuff...-fn insert[T Ord](x T, xs List[T]) List[T] : Inserted(x, xs) => match xs {-    Nil => Cons(x, Nil)-    Cons(h, t) => {-        if x.lt(h) {-            return Cons(x, xs)-        }-        return Cons(h, insert(x, t))-    }-}--fn sort[T Ord](xs List[T]) List[T] : { post r => sorted(r) && len(r) == len(xs) } => match xs {-    Nil        => Nil-    Cons(h, t) => insert(h, sort(t))-}--fn print_list(xs List[i32]) {-    match xs {-        Nil        => print("end")-        Cons(h, t) => {-            print(h)-            print_list(t)-        }-    }-}--fn main() {-    const xs = Cons(3, Cons(1, Cons(2, Nil)))-    const ys = sort(xs)-    print_list(ys)-}--- /dev/null+++ b/samples/baseline_3/sample3.hz@@ -0,0 +1,49 @@+trait Ord {+    fn lt(self Self, other Self) bool+}++impl i32 : Ord {+    fn lt(self i32, other i32) bool => self < other+}++type Counter {+    count i32+    limit i32+}++fn bump(c Counter) : pre c.count < c.limit {+    c.count+++}++fn count_to(limit i32) i32 : pre limit >= 0 : post r => r == limit {+    var c = Counter{count = 0, limit = limit}+    for c.count < c.limit {+        bump(c)+    }+    return c.count+}++fn find(xs list[i32], target i32) i32 : { post r => r >= -1 && r < xs.len } {+    for i in 0..xs.len {+        if xs[i] == target {+            return i+        }+    }+    return -1+}++fn max[T Ord](a T, b T) T {+    if a.lt(b) { return b }+    return a+}++fn main() {+    var c = Counter{ count = 0, limit = 3 }+    bump(c)+    print(c.count)+    print(count_to(5))+    const xs = [4, 8, 15, 16, 23, 42]+    print(find(xs, 15))+    print(find(xs, 99))+    print(max(3, 7))+}--- a/samples/baseline_3/sample3.xyz+++ /dev/null@@ -1,49 +0,0 @@-trait Ord {-    fn lt(self Self, other Self) bool-}--impl i32 : Ord {-    fn lt(self i32, other i32) bool => self < other-}--type Counter {-    count i32-    limit i32-}--fn bump(c Counter) : pre c.count < c.limit {-    c.count++-}--fn count_to(limit i32) i32 : pre limit >= 0 : post r => r == limit {-    var c = Counter{count = 0, limit = limit}-    for c.count < c.limit {-        bump(c)-    }-    return c.count-}--fn find(xs list[i32], target i32) i32 : { post r => r >= -1 && r < xs.len } {-    for i in 0..xs.len {-        if xs[i] == target {-            return i-        }-    }-    return -1-}--fn max[T Ord](a T, b T) T {-    if a.lt(b) { return b }-    return a-}--fn main() {-    var c = Counter{ count = 0, limit = 3 }-    bump(c)-    print(c.count)-    print(count_to(5))-    const xs = [4, 8, 15, 16, 23, 42]-    print(find(xs, 15))-    print(find(xs, 99))-    print(max(3, 7))-}--- /dev/null+++ b/samples/baseline_3/sample4.hz@@ -0,0 +1,106 @@+// Bank account: contracts over immutable data, braced style.++const MAX_BALANCE i64 = 1_000_000_000++type Account {+    id      i32+    balance i64+}++type Transfer {+    src Account+    dst Account+}++pure fn solvent(a Account) bool => a.balance >= 0 && a.balance <= MAX_BALANCE++contract Solvent(a Account) {+    pre solvent(a)+}++contract Funded(a Account, amt i64) {+    pre {+        amt > 0+        amt <= a.balance+    }+}++contract Room(a Account, amt i64) {+    pre {+        amt > 0+        a.balance + amt <= MAX_BALANCE+    }+}++fn deposit(a Account, amt i64) Account+    : Solvent(a)+    : Room(a, amt)+    : post r => r.id == a.id+    : post r => r.balance == a.balance + amt+    : post r => solvent(r)+    =>  Account{ id = a.id, balance = a.balance + amt }++fn withdraw(a Account, amt i64) Account+    : Solvent(a)+    : Funded(a, amt)+    : post r => r.id == a.id+    : post r => r.balance == a.balance - amt+    : post r => solvent(r)+    => Account{ id = a.id, balance = a.balance - amt }++fn transfer(src Account, dst Account, amt i64) Transfer+    : Solvent(src)+    : Solvent(dst)+    : Funded(src, amt)+    : Room(dst, amt)+    : pre src.id != dst.id+    : post r => r.src.id == src.id && r.dst.id == dst.id+    : post r => r.src.balance == src.balance - amt+    : post r => r.dst.balance == dst.balance + amt+    : post r => solvent(r.src) && solvent(r.dst)+    => Transfer{ src = withdraw(src, amt), dst = deposit(dst, amt) }+++// Deposit `amt` once a month for `months` months.+fn save(a Account, amt i64, months i64) Account+    : Solvent(a)+    : pre amt > 0+    : pre months >= 0+    : pre a.balance + amt * months <= MAX_BALANCE+    : post r => r.id == a.id+    : post r => r.balance == a.balance + amt * months+    : post r => solvent(r)+{+    var acc = a+    for i in 0..months+        : invariant acc.balance == a.balance + amt * i+    {+        acc = deposit(acc, amt)+    }+    return acc+}++fn main() {+    const alice = Account{ id = 1, balance = 100 }+    const bob   = Account{ id = 2, balance = 50 }++    const a1 = deposit(alice, 25)+    print(a1.balance)               // 125++    const a2 = withdraw(a1, 100)+    print(a2.balance)               // 25++    const t = transfer(a2, bob, 20)+    print(t.src.balance)            // 5+    print(t.dst.balance)            // 70++    const s = save(t.src, 10, 3)+    print(s.balance)                // 35++    // Each of these should be rejected at compile time:+    //+    // withdraw(a2, 1000)           // pre `amt <= a.balance` not provable (a2.balance == 25)+    // transfer(a2, a2, 5)          // pre `src.id != dst.id` not provable+    // deposit(a2, 0)               // pre `amt > 0` not provable+    // save(a2, 1000000000, 2)      // pre `a.balance + amt * months <= MAX_BALANCE` not provable+}--- a/samples/baseline_3/sample4.xyz+++ /dev/null@@ -1,106 +0,0 @@-// Bank account: contracts over immutable data, braced style.--const MAX_BALANCE i64 = 1_000_000_000--type Account {-    id      i32-    balance i64-}--type Transfer {-    src Account-    dst Account-}--pure fn solvent(a Account) bool => a.balance >= 0 && a.balance <= MAX_BALANCE--contract Solvent(a Account) {-    pre solvent(a)-}--contract Funded(a Account, amt i64) {-    pre {-        amt > 0-        amt <= a.balance-    }-}--contract Room(a Account, amt i64) {-    pre {-        amt > 0-        a.balance + amt <= MAX_BALANCE-    }-}--fn deposit(a Account, amt i64) Account-    : Solvent(a)-    : Room(a, amt)-    : post r => r.id == a.id-    : post r => r.balance == a.balance + amt-    : post r => solvent(r)-    =>  Account{ id = a.id, balance = a.balance + amt }--fn withdraw(a Account, amt i64) Account-    : Solvent(a)-    : Funded(a, amt)-    : post r => r.id == a.id-    : post r => r.balance == a.balance - amt-    : post r => solvent(r)-    => Account{ id = a.id, balance = a.balance - amt }--fn transfer(src Account, dst Account, amt i64) Transfer-    : Solvent(src)-    : Solvent(dst)-    : Funded(src, amt)-    : Room(dst, amt)-    : pre src.id != dst.id-    : post r => r.src.id == src.id && r.dst.id == dst.id-    : post r => r.src.balance == src.balance - amt-    : post r => r.dst.balance == dst.balance + amt-    : post r => solvent(r.src) && solvent(r.dst)-    => Transfer{ src = withdraw(src, amt), dst = deposit(dst, amt) }---// Deposit `amt` once a month for `months` months.-fn save(a Account, amt i64, months i64) Account-    : Solvent(a)-    : pre amt > 0-    : pre months >= 0-    : pre a.balance + amt * months <= MAX_BALANCE-    : post r => r.id == a.id-    : post r => r.balance == a.balance + amt * months-    : post r => solvent(r)-{-    var acc = a-    for i in 0..months-        : invariant acc.balance == a.balance + amt * i-    {-        acc = deposit(acc, amt)-    }-    return acc-}--fn main() {-    const alice = Account{ id = 1, balance = 100 }-    const bob   = Account{ id = 2, balance = 50 }--    const a1 = deposit(alice, 25)-    print(a1.balance)               // 125--    const a2 = withdraw(a1, 100)-    print(a2.balance)               // 25--    const t = transfer(a2, bob, 20)-    print(t.src.balance)            // 5-    print(t.dst.balance)            // 70--    const s = save(t.src, 10, 3)-    print(s.balance)                // 35--    // Each of these should be rejected at compile time:-    //-    // withdraw(a2, 1000)           // pre `amt <= a.balance` not provable (a2.balance == 25)-    // transfer(a2, a2, 5)          // pre `src.id != dst.id` not provable-    // deposit(a2, 0)               // pre `amt > 0` not provable-    // save(a2, 1000000000, 2)      // pre `a.balance + amt * months <= MAX_BALANCE` not provable-}--- a/src/codegen.cpp+++ b/src/codegen.cpp@@ -1,10 +1,10 @@-#include "xyz.h"+#include "haze.h"  #include <cassert> #include <sstream> #include <utility> -namespace xyz {+namespace haze {  namespace { @@ -48,7 +48,7 @@             gen_function(*fn);          std::ostringstream out;-        out << "# generated by xyz from " << source_name_ << "\n\n";+        out << "# generated by haze from " << source_name_ << "\n\n";         out << data_.str();         out << funcs_.str();         return out.str();@@ -203,7 +203,7 @@         auto it = string_syms_.find(s);         if (it != string_syms_.end())             return it->second;-        std::string sym = "xyz_str_" + std::to_string(string_counter_++);+        std::string sym = "haze_str_" + std::to_string(string_counter_++);         data_ << "data $" << sym << " = { b";         if (s.empty()) {             data_ << " 0";@@ -219,7 +219,7 @@      void panic_block(const std::string& message) {         std::string sym = intern_string(message);-        emit("call $xyz_panic(l $" + sym + ")");+        emit("call $haze_panic(l $" + sym + ")");         emit("hlt");         blocks_[cur_].terminated = true;     }@@ -261,7 +261,7 @@             checking_post_ = false;         }         if (has_root_frame_)-            emit("call $xyz_root_leave(l " + root_frame_ + ")");+            emit("call $haze_root_leave(l " + root_frame_ + ")");         if (has_value)             emit("ret " + v.s);         else@@ -323,8 +323,8 @@     void emit_root_frame_init() {         root_frame_ = new_temp();         root_slots_ = new_temp();-        rootmap_sym_ = "xyz_rootmap_" + std::to_string(rootmap_counter_++);-        rootoffs_sym_ = "xyz_rootoffs_" + std::to_string(rootmap_counter_ - 1);+        rootmap_sym_ = "haze_rootmap_" + std::to_string(rootmap_counter_++);+        rootoffs_sym_ = "haze_rootoffs_" + std::to_string(rootmap_counter_ - 1);          allocs_.push_back(root_frame_ + " =l alloc16 24");         allocs_.push_back(root_slots_ + " =l alloc16 512");@@ -347,7 +347,7 @@         emit_entry(a + " =l add " + root_frame_ + ", 16");         emit_entry("storel " + root_slots_ + ", " + a); -        emit_entry("call $xyz_root_enter(l " + root_frame_ + ")");+        emit_entry("call $haze_root_enter(l " + root_frame_ + ")");     }      void emit_root_map() {@@ -469,7 +469,7 @@             f << "function";             if (fn.ret && fn.ret->kind != Type::Kind::Void)                 f << " " << qbe_type(fn.ret);-            f << " $xyz_" << fn.name << "(";+            f << " $haze_" << fn.name << "(";         }         for (size_t i = 0; i < fn.params.size(); i++) {             if (i)@@ -757,17 +757,17 @@         if (name == "print") {             TypePtr t = args[0].ty;             if (t->kind == Type::Kind::I32)-                return call("xyz_print_i32", {t_i32()}, t_void());+                return call("haze_print_i32", {t_i32()}, t_void());             if (t->kind == Type::Kind::I64)-                return call("xyz_print_i64", {t_i64()}, t_void());+                return call("haze_print_i64", {t_i64()}, t_void());             if (t->kind == Type::Kind::Bool)-                return call("xyz_print_bool", {t_bool()}, t_void());-            return call("xyz_print_str", {t_str()}, t_void());+                return call("haze_print_bool", {t_bool()}, t_void());+            return call("haze_print_str", {t_str()}, t_void());         }          if (name == "__gc_alloc") {             args.push_back(Value{t_i32(), "0", true});-            return call("xyz_alloc_slow", {t_i32(), t_i32()}, t_ptr());+            return call("haze_alloc_slow", {t_i32(), t_i32()}, t_ptr());         }          if (name == "__gc_store") {@@ -791,19 +791,19 @@         }          if (name == "__gc_alive")-            return call("xyz_gc_object_alive", {t_ptr()}, t_bool());+            return call("haze_gc_object_alive", {t_ptr()}, t_bool());          if (name == "__gc_collect")-            return call("xyz_gc_collect", {}, t_void());+            return call("haze_gc_collect", {}, t_void());          if (name == "__gc_verify")-            return call("xyz_gc_verify", {}, t_void());+            return call("haze_gc_verify", {}, t_void());          if (name == "__gc_pin")-            return call("xyz_pin", {t_ptr()}, t_void());+            return call("haze_pin", {t_ptr()}, t_void());          if (name == "__gc_unpin")-            return call("xyz_unpin", {t_ptr()}, t_void());+            return call("haze_unpin", {t_ptr()}, t_void());          auto it = sigs_.find(name);         if (it == sigs_.end())@@ -812,7 +812,7 @@         std::ostringstream s;         if (sig.ret->kind != Type::Kind::Void)             s << new_temp() << " =" << qbe_type(sig.ret) << " ";-        s << "call $" << (name == "main" ? "main" : ("xyz_" + name)) << "(";+        s << "call $" << (name == "main" ? "main" : ("haze_" + name)) << "(";         for (size_t i = 0; i < args.size(); i++) {             if (i)                 s << ", ";@@ -972,4 +972,4 @@     return g.run(); } -} // namespace xyz+} // namespace haze--- a/src/driver.cpp+++ b/src/driver.cpp@@ -1,5 +1,5 @@ #include "libqbe.h"-#include "xyz.h"+#include "haze.h"  #include <cctype> #include <cstdio>@@ -38,7 +38,7 @@ };  void usage(FILE* f) {-    std::fprintf(f, "usage: xyz [options] file.xyz\n"+    std::fprintf(f, "usage: hz [options] file.hz\n"                     "\n"                     "  -o file       output path\n"                     "  -target name  UQBE target (amd64_sysv, amd64_apple, amd64_win,\n"@@ -49,7 +49,7 @@                     "  -run          run the produced executable\n"                     "  -keep         keep temporary files\n"                     "  -cc path      C compiler used for assembly/linking\n"-                    "  -runtime path path to libxyzrt.a\n"+                    "  -runtime path path to libhazert.a\n"                     "  -v            print version\n"                     "  -h            print this help\n"); }@@ -192,7 +192,7 @@  fs::path executable_dir(const char* argv0) {     std::error_code ec;-    fs::path p = argv0 && *argv0 ? fs::path(argv0) : fs::path("xyz");+    fs::path p = argv0 && *argv0 ? fs::path(argv0) : fs::path("hz");     if (!p.has_parent_path()) {         std::string found = find_in_path(p.string());         if (!found.empty())@@ -200,7 +200,7 @@     }     p = fs::absolute(p, ec);     if (ec)-        p = fs::path(argv0 ? argv0 : "xyz");+        p = fs::path(argv0 ? argv0 : "hz");     p = fs::weakly_canonical(p, ec);     return p.parent_path(); }@@ -211,13 +211,13 @@             throw std::runtime_error("runtime archive not found: " + o.runtime);         return fs::absolute(o.runtime).string();     }-    if (const char* env = std::getenv("XYZ_RUNTIME")) {+    if (const char* env = std::getenv("HAZE_RUNTIME")) {         if (*env && is_executable_file(env))             return fs::absolute(env).string();     }-    std::vector<fs::path> dirs = {exe_dir, exe_dir / ".." / "lib", exe_dir / ".." / "lib" / "xyz",+    std::vector<fs::path> dirs = {exe_dir, exe_dir / ".." / "lib", exe_dir / ".." / "lib" / "haze",                                   fs::current_path()};-    const char* names[] = {"libxyzrt.a", "xyzrt.lib", "libxyzrt.lib", "xyzrt.o"};+    const char* names[] = {"libhazert.a", "hazert.lib", "libhazert.lib", "hazert.o"};     for (auto& d : dirs) {         for (const char* n : names) {             fs::path p = d / n;@@ -226,7 +226,7 @@                 return fs::weakly_canonical(p, ec).string();         }     }-    throw std::runtime_error("cannot find libxyzrt.a; build it with xmake or pass -runtime path");+    throw std::runtime_error("cannot find libhazert.a; build it with xmake or pass -runtime path"); }  std::string find_cc(const Options& o) {@@ -236,7 +236,7 @@             throw std::runtime_error("C compiler not found: " + o.cc);         return p;     }-    if (const char* env = std::getenv("XYZ_CC")) {+    if (const char* env = std::getenv("HAZE_CC")) {         if (*env) {             std::string p = find_in_path(env);             if (!p.empty())@@ -286,7 +286,7 @@     fs::path base = fs::temp_directory_path(ec);     if (ec)         base = fs::current_path();-    base /= "xyz";+    base /= "haze";     fs::create_directories(base, ec);     for (int i = 0; i < 1000; i++) {         fs::path p = base / ("work-" + std::to_string(process_id()) + "-" + std::to_string(i));@@ -296,7 +296,7 @@     throw std::runtime_error("cannot create temporary directory"); } -std::string format_error(const std::string& file, const xyz::Error& e) {+std::string format_error(const std::string& file, const haze::Error& e) {     std::ostringstream ss;     ss << file << ':' << e.pos.line << ':' << e.pos.col << ": error: " << e.what();     return ss.str();@@ -315,7 +315,7 @@             return 0;         }         if (a == "-v") {-            std::printf("xyz 0.1 (UQBE target %s)\n", qbe_default_target());+            std::printf("haze 0.1 (UQBE target %s)\n", qbe_default_target());             return 0;         }         if (a == "-S") {@@ -344,7 +344,7 @@         }         if (a == "-o" || a == "-target" || a == "-cc" || a == "-runtime") {             if (i + 1 >= argc) {-                std::fprintf(stderr, "xyz: missing value after %s\n", a.c_str());+                std::fprintf(stderr, "hz: missing value after %s\n", a.c_str());                 return 1;             }             std::string v = argv[++i];@@ -369,12 +369,12 @@         else if (!a.empty() && a[0] == '-') {             if (a.size() > 1 && a[1] == '-') {                 std::fprintf(stderr,-                             "xyz: GNU-style flag '%s' rejected; use single-dash "+                             "hz: GNU-style flag '%s' rejected; use single-dash "                              "Plan 9 flags such as -target\n",                              a.c_str());                 return 1;             }-            std::fprintf(stderr, "xyz: unknown flag '%s' (try -h)\n", a.c_str());+            std::fprintf(stderr, "hz: unknown flag '%s' (try -h)\n", a.c_str());             return 1;         } else {             positional.push_back(a);@@ -405,8 +405,8 @@         fs::path input(opt.input);         if (!fs::is_regular_file(input))             throw std::runtime_error("input file not found: " + opt.input);-        if (lower(input.extension().string()) != ".xyz")-            throw std::runtime_error("xyz expects a .xyz source file");+        if (lower(input.extension().string()) != ".hz")+            throw std::runtime_error("hz expects a .hz source file");          std::string target =             opt.target.empty() ? qbe_default_target() : canonical_target(opt.target);@@ -415,9 +415,9 @@                                      "'; supported: " + qbe_target_list());          std::string source = read_file(input);-        xyz::Program program = xyz::parse_program(source);-        xyz::check_program(program);-        std::string il = xyz::generate_qbe(program, input.filename().string());+        haze::Program program = haze::parse_program(source);+        haze::check_program(program);+        std::string il = haze::generate_qbe(program, input.filename().string());          if (opt.emit_il) {             std::string out = opt.output.empty() ? default_output(opt.input, ".ssa") : opt.output;@@ -426,7 +426,7 @@             else {                 write_file(out, il);                 if (opt.verbose)-                    std::fprintf(stderr, "xyz: wrote %s\n", out.c_str());+                    std::fprintf(stderr, "hz: wrote %s\n", out.c_str());             }             return 0;         }@@ -447,7 +447,7 @@             else                 fs::copy_file(asmpath, out, fs::copy_options::overwrite_existing);             if (opt.keep)-                std::fprintf(stderr, "xyz: kept %s\n", tmp.string().c_str());+                std::fprintf(stderr, "hz: kept %s\n", tmp.string().c_str());             else                 fs::remove_all(tmp);             return 0;@@ -464,7 +464,7 @@             if (rc != 0)                 throw std::runtime_error("assembler failed");             if (opt.keep)-                std::fprintf(stderr, "xyz: kept %s\n", tmp.string().c_str());+                std::fprintf(stderr, "hz: kept %s\n", tmp.string().c_str());             else                 fs::remove_all(tmp);             return 0;@@ -485,7 +485,7 @@             throw std::runtime_error("linker failed");          if (opt.keep)-            std::fprintf(stderr, "xyz: kept %s\n", tmp.string().c_str());+            std::fprintf(stderr, "hz: kept %s\n", tmp.string().c_str());         else             fs::remove_all(tmp); @@ -498,11 +498,11 @@             return run_tool({runpath}, opt.verbose);         }         return 0;-    } catch (const xyz::Error& e) {+    } catch (const haze::Error& e) {         std::fprintf(stderr, "%s\n", format_error(opt.input, e).c_str());         return 1;     } catch (const std::exception& e) {-        std::fprintf(stderr, "xyz: %s\n", e.what());+        std::fprintf(stderr, "hz: %s\n", e.what());         return 1;     } }--- /dev/null+++ b/src/haze.h@@ -0,0 +1,215 @@+#ifndef HAZE_H+#define HAZE_H++#include <cstdint>+#include <memory>+#include <stdexcept>+#include <string>+#include <unordered_map>+#include <unordered_set>+#include <vector>++namespace haze {++struct Pos {+    int line = 1;+    int col = 1;+};++struct Error : std::runtime_error {+    Pos pos;+    Error(Pos p, const std::string& msg) : std::runtime_error(msg), pos(p) {}+};++struct Type;+using TypePtr = std::shared_ptr<Type>;++struct Type {+    enum class Kind { Void, I32, I64, Bool, Str, Ptr, List, Unknown };+    Kind kind = Kind::Unknown;+    TypePtr elem;+    std::string name;+};++TypePtr t_void();+TypePtr t_i32();+TypePtr t_i64();+TypePtr t_bool();+TypePtr t_str();+TypePtr t_ptr();+TypePtr t_list(TypePtr elem);+TypePtr t_unknown(const std::string& name);+bool same_type(const TypePtr& a, const TypePtr& b);+bool is_int(const TypePtr& t);+bool is_managed(const TypePtr& t);+std::string type_name(const TypePtr& t);+std::string qbe_type(const TypePtr& t);+bool assignable(const TypePtr& to, const TypePtr& from);++enum class Tok {+    End,+    Ident,+    Int,+    Str,+    Arrow,+    EqEq,+    NotEq,+    Le,+    Ge,+    AndAnd,+    OrOr,+    Plus,+    Minus,+    Star,+    Slash,+    Percent,+    Assign,+    PlusEq,+    MinusEq,+    StarEq,+    SlashEq,+    PercentEq,+    PlusPlus,+    MinusMinus,+    Dot,+    DotDot,+    Comma,+    LParen,+    RParen,+    LBrace,+    RBrace,+    LBracket,+    RBracket,+    Colon,+    ColonColon,+    Pipe,+    Bang,+    Lt,+    Gt,+};++struct Token {+    Tok kind = Tok::End;+    std::string text;+    long long ival = 0;+    Pos pos;+};++std::vector<Token> lex(const std::string& src);++struct Expr;+using ExprPtr = std::unique_ptr<Expr>;++struct Block;+using BlockPtr = std::unique_ptr<Block>;++struct Expr {+    enum class Kind {+        Int,+        Bool,+        String,+        Var,+        Unary,+        Binary,+        Call,+        If,+        Block,+        List,+        Field,+        Index,+        Assign,+    };+    Kind kind = Kind::Int;+    Pos pos;+    TypePtr ty;+    long long ival = 0;+    bool bval = false;+    std::string text;+    std::string op;+    ExprPtr lhs;+    ExprPtr rhs;+    ExprPtr cond;+    ExprPtr then_e;+    ExprPtr else_e;+    std::vector<ExprPtr> args;+    BlockPtr block;+};++struct Stmt;+using StmtPtr = std::unique_ptr<Stmt>;++struct Stmt {+    enum class Kind {+        Let,+        Var,+        Assign,+        Return,+        ForRange,+        ForCond,+        Break,+        Continue,+        Expr,+        Block,+    };+    Kind kind = Kind::Expr;+    Pos pos;+    std::string name;+    std::string op;+    TypePtr decl_type;+    ExprPtr expr;+    ExprPtr rhs;+    ExprPtr cond;+    ExprPtr lo;+    ExprPtr hi;+    BlockPtr block;+};++struct Block {+    Pos pos;+    std::vector<StmtPtr> stmts;+};++struct Param {+    std::string name;+    TypePtr type;+    Pos pos;+};++struct Contract {+    enum class Kind { Pre, Post };+    Kind kind = Kind::Pre;+    std::string result_name;+    ExprPtr expr;+    Pos pos;+};++struct Function {+    std::string name;+    std::vector<Param> params;+    TypePtr ret;+    BlockPtr body;+    ExprPtr arrow;+    std::vector<Contract> contracts;+    bool pure = false;+    bool pub = false;+    Pos pos;+};++struct Program {+    std::vector<std::unique_ptr<Function>> functions;+};++Program parse_program(const std::string& src);+void check_program(Program& program);+std::string generate_qbe(Program& program, const std::string& source_name);++struct FuncSig {+    TypePtr ret;+    std::vector<TypePtr> params;+};++using SigMap = std::unordered_map<std::string, FuncSig>;++} // namespace haze++#endif--- a/src/lexer.cpp+++ b/src/lexer.cpp@@ -1,10 +1,10 @@-#include "xyz.h"+#include "haze.h"  #include <cctype> #include <cerrno> #include <cstdlib> -namespace xyz {+namespace haze {  namespace { class Lexer {@@ -272,4 +272,4 @@     return Lexer(src).run(); } -} // namespace xyz+} // namespace haze--- a/src/parser.cpp+++ b/src/parser.cpp@@ -1,8 +1,8 @@-#include "xyz.h"+#include "haze.h"  #include <utility> -namespace xyz {+namespace haze {  namespace { @@ -572,4 +572,4 @@     return p.program(); } -} // namespace xyz+} // namespace haze--- a/src/sema.cpp+++ b/src/sema.cpp@@ -1,9 +1,9 @@-#include "xyz.h"+#include "haze.h"  #include <algorithm> #include <climits> -namespace xyz {+namespace haze {  namespace { @@ -439,4 +439,4 @@     c.run(); } -} // namespace xyz+} // namespace haze--- a/src/types.cpp+++ b/src/types.cpp@@ -1,6 +1,6 @@-#include "xyz.h"+#include "haze.h" -namespace xyz {+namespace haze {  namespace { TypePtr make(Type::Kind k) {@@ -111,4 +111,4 @@     return false; } -} // namespace xyz+} // namespace haze--- a/src/xyz.h+++ /dev/null@@ -1,215 +0,0 @@-#ifndef XYZ_H-#define XYZ_H--#include <cstdint>-#include <memory>-#include <stdexcept>-#include <string>-#include <unordered_map>-#include <unordered_set>-#include <vector>--namespace xyz {--struct Pos {-    int line = 1;-    int col = 1;-};--struct Error : std::runtime_error {-    Pos pos;-    Error(Pos p, const std::string& msg) : std::runtime_error(msg), pos(p) {}-};--struct Type;-using TypePtr = std::shared_ptr<Type>;--struct Type {-    enum class Kind { Void, I32, I64, Bool, Str, Ptr, List, Unknown };-    Kind kind = Kind::Unknown;-    TypePtr elem;-    std::string name;-};--TypePtr t_void();-TypePtr t_i32();-TypePtr t_i64();-TypePtr t_bool();-TypePtr t_str();-TypePtr t_ptr();-TypePtr t_list(TypePtr elem);-TypePtr t_unknown(const std::string& name);-bool same_type(const TypePtr& a, const TypePtr& b);-bool is_int(const TypePtr& t);-bool is_managed(const TypePtr& t);-std::string type_name(const TypePtr& t);-std::string qbe_type(const TypePtr& t);-bool assignable(const TypePtr& to, const TypePtr& from);--enum class Tok {-    End,-    Ident,-    Int,-    Str,-    Arrow,-    EqEq,-    NotEq,-    Le,-    Ge,-    AndAnd,-    OrOr,-    Plus,-    Minus,-    Star,-    Slash,-    Percent,-    Assign,-    PlusEq,-    MinusEq,-    StarEq,-    SlashEq,-    PercentEq,-    PlusPlus,-    MinusMinus,-    Dot,-    DotDot,-    Comma,-    LParen,-    RParen,-    LBrace,-    RBrace,-    LBracket,-    RBracket,-    Colon,-    ColonColon,-    Pipe,-    Bang,-    Lt,-    Gt,-};--struct Token {-    Tok kind = Tok::End;-    std::string text;-    long long ival = 0;-    Pos pos;-};--std::vector<Token> lex(const std::string& src);--struct Expr;-using ExprPtr = std::unique_ptr<Expr>;--struct Block;-using BlockPtr = std::unique_ptr<Block>;--struct Expr {-    enum class Kind {-        Int,-        Bool,-        String,-        Var,-        Unary,-        Binary,-        Call,-        If,-        Block,-        List,-        Field,-        Index,-        Assign,-    };-    Kind kind = Kind::Int;-    Pos pos;-    TypePtr ty;-    long long ival = 0;-    bool bval = false;-    std::string text;-    std::string op;-    ExprPtr lhs;-    ExprPtr rhs;-    ExprPtr cond;-    ExprPtr then_e;-    ExprPtr else_e;-    std::vector<ExprPtr> args;-    BlockPtr block;-};--struct Stmt;-using StmtPtr = std::unique_ptr<Stmt>;--struct Stmt {-    enum class Kind {-        Let,-        Var,-        Assign,-        Return,-        ForRange,-        ForCond,-        Break,-        Continue,-        Expr,-        Block,-    };-    Kind kind = Kind::Expr;-    Pos pos;-    std::string name;-    std::string op;-    TypePtr decl_type;-    ExprPtr expr;-    ExprPtr rhs;-    ExprPtr cond;-    ExprPtr lo;-    ExprPtr hi;-    BlockPtr block;-};--struct Block {-    Pos pos;-    std::vector<StmtPtr> stmts;-};--struct Param {-    std::string name;-    TypePtr type;-    Pos pos;-};--struct Contract {-    enum class Kind { Pre, Post };-    Kind kind = Kind::Pre;-    std::string result_name;-    ExprPtr expr;-    Pos pos;-};--struct Function {-    std::string name;-    std::vector<Param> params;-    TypePtr ret;-    BlockPtr body;-    ExprPtr arrow;-    std::vector<Contract> contracts;-    bool pure = false;-    bool pub = false;-    Pos pos;-};--struct Program {-    std::vector<std::unique_ptr<Function>> functions;-};--Program parse_program(const std::string& src);-void check_program(Program& program);-std::string generate_qbe(Program& program, const std::string& source_name);--struct FuncSig {-    TypePtr ret;-    std::vector<TypePtr> params;-};--using SigMap = std::unordered_map<std::string, FuncSig>;--} // namespace xyz--#endif--- /dev/null+++ b/tests/m0_gc.hz@@ -0,0 +1,32 @@+// Internal M0 smoke test: ordinary, medium, and large allocation, with+// collections interleaved and the heap verifier enabled.++fn churn(count i32) {+    var i = 0+    for i < count {+        const p = __gc_alloc(64)+        __gc_store(p, 8, p)+        i+++    }+}++fn hold_big() ptr {+    const p = __gc_alloc(10000)+    return p+}++fn main() {+    const keep = hold_big()+    churn(2000)+    __gc_collect()+    __gc_verify()+    if __gc_alive(keep) {+        print("big alive")+    } else {+        print("big dead")+    }+    churn(1000)+    __gc_collect()+    __gc_verify()+    print("churn ok")+}--- a/tests/m0_gc.xyz+++ /dev/null@@ -1,32 +0,0 @@-// Internal M0 smoke test: ordinary, medium, and large allocation, with-// collections interleaved and the heap verifier enabled.--fn churn(count i32) {-    var i = 0-    for i < count {-        const p = __gc_alloc(64)-        __gc_store(p, 8, p)-        i++-    }-}--fn hold_big() ptr {-    const p = __gc_alloc(10000)-    return p-}--fn main() {-    const keep = hold_big()-    churn(2000)-    __gc_collect()-    __gc_verify()-    if __gc_alive(keep) {-        print("big alive")-    } else {-        print("big dead")-    }-    churn(1000)-    __gc_collect()-    __gc_verify()-    print("churn ok")-}--- /dev/null+++ b/tests/m1_roots.hz@@ -0,0 +1,21 @@+// Internal M1 smoke test: a managed reference must survive a collection+// across nested calls, and the shadow-stack frame must keep it alive.++fn allocate_and_collect() {+    const p = __gc_alloc(64)+    __gc_store(p, 8, p)+    __gc_collect()+    __gc_verify()+}++fn main() {+    const q = __gc_alloc(48)+    allocate_and_collect()+    __gc_collect()+    __gc_verify()+    if __gc_alive(q) {+        print("alive")+    } else {+        print("dead")+    }+}--- a/tests/m1_roots.xyz+++ /dev/null@@ -1,21 +0,0 @@-// Internal M1 smoke test: a managed reference must survive a collection-// across nested calls, and the shadow-stack frame must keep it alive.--fn allocate_and_collect() {-    const p = __gc_alloc(64)-    __gc_store(p, 8, p)-    __gc_collect()-    __gc_verify()-}--fn main() {-    const q = __gc_alloc(48)-    allocate_and_collect()-    __gc_collect()-    __gc_verify()-    if __gc_alive(q) {-        print("alive")-    } else {-        print("dead")-    }-}--- a/tests/runtime_test.cpp+++ b/tests/runtime_test.cpp@@ -1,4 +1,4 @@-#include "xyzrt.h"+#include "hazert.h"  #include <cstdio> #include <cstdlib>@@ -17,78 +17,78 @@ } // namespace  int main() {-    xyz_runtime_init();+    haze_runtime_init();      /* A descriptor with two managed pointer fields. */     static const uint32_t offsets[] = {8, 16};-    uint32_t parent_type = xyz_register_type(32, 2, offsets);+    uint32_t parent_type = haze_register_type(32, 2, offsets); -    void* child = xyz_alloc_slow(16, 0);-    void* parent = xyz_alloc_slow(16, parent_type);+    void* child = haze_alloc_slow(16, 0);+    void* parent = haze_alloc_slow(16, parent_type);     check(child && parent, "allocation");     *reinterpret_cast<void**>(static_cast<unsigned char*>(parent) + 8) = child;      void* root = parent;-    xyz_root_add(&root);-    xyz_gc_collect();-    xyz_gc_verify();-    check(xyz_gc_object_alive(parent), "parent kept by global root");-    check(xyz_gc_object_alive(child), "child traced through descriptor");+    haze_root_add(&root);+    haze_gc_collect();+    haze_gc_verify();+    check(haze_gc_object_alive(parent), "parent kept by global root");+    check(haze_gc_object_alive(child), "child traced through descriptor"); -    xyz_root_remove(&root);+    haze_root_remove(&root);     parent = nullptr;     child = nullptr;-    xyz_gc_collect();-    xyz_gc_verify();+    haze_gc_collect();+    haze_gc_verify();      /* Medium object. */-    void* medium = xyz_alloc_slow(4000, 0);+    void* medium = haze_alloc_slow(4000, 0);     check(medium != nullptr, "medium allocation");     root = medium;-    xyz_root_add(&root);-    xyz_gc_collect();-    check(xyz_gc_object_alive(medium), "medium object survives");-    xyz_root_remove(&root);+    haze_root_add(&root);+    haze_gc_collect();+    check(haze_gc_object_alive(medium), "medium object survives");+    haze_root_remove(&root);      /* Large object space. */-    void* large = xyz_alloc_large(10000, 0);+    void* large = haze_alloc_large(10000, 0);     check(large != nullptr, "large allocation");     root = large;-    xyz_root_add(&root);-    xyz_gc_collect();-    check(xyz_gc_object_alive(large), "large object survives");-    xyz_root_remove(&root);-    xyz_gc_collect();-    check(!xyz_gc_object_alive(large), "large object reclaimed");+    haze_root_add(&root);+    haze_gc_collect();+    check(haze_gc_object_alive(large), "large object survives");+    haze_root_remove(&root);+    haze_gc_collect();+    check(!haze_gc_object_alive(large), "large object reclaimed");      /* Shadow-stack frame. */     void* slot[1] = {nullptr};     static const uint32_t root_offsets[] = {0};-    XyzRootMap map = {1, 24, root_offsets};-    XyzRootFrame frame = {nullptr, &map, slot};-    slot[0] = xyz_alloc_slow(64, 0);-    xyz_root_enter(&frame);-    xyz_gc_collect();-    xyz_gc_verify();-    check(xyz_gc_object_alive(slot[0]), "object kept by root frame");-    xyz_root_leave(&frame);-    xyz_gc_collect();-    check(!xyz_gc_object_alive(slot[0]), "object collected after root leave");+    HazeRootMap map = {1, 24, root_offsets};+    HazeRootFrame frame = {nullptr, &map, slot};+    slot[0] = haze_alloc_slow(64, 0);+    haze_root_enter(&frame);+    haze_gc_collect();+    haze_gc_verify();+    check(haze_gc_object_alive(slot[0]), "object kept by root frame");+    haze_root_leave(&frame);+    haze_gc_collect();+    check(!haze_gc_object_alive(slot[0]), "object collected after root leave");      /* Epoch wraparound smoke test. */-    void* stable = xyz_alloc_slow(32, 0);+    void* stable = haze_alloc_slow(32, 0);     root = stable;-    xyz_root_add(&root);+    haze_root_add(&root);     for (int i = 0; i < 300; i++) {-        xyz_gc_collect();-        if (!xyz_gc_object_alive(stable)) {+        haze_gc_collect();+        if (!haze_gc_object_alive(stable)) {             check(false, "stable object survived epoch wrap");             break;         }     }-    xyz_root_remove(&root);-    xyz_gc_collect();-    check(!xyz_gc_object_alive(stable), "stable object reclaimed");+    haze_root_remove(&root);+    haze_gc_collect();+    check(!haze_gc_object_alive(stable), "stable object reclaimed");      if (failures) {         std::fprintf(stderr, "%d runtime test(s) failed\n", failures);--- a/xmake.lua+++ b/xmake.lua@@ -1,8 +1,8 @@ add_rules("mode.debug", "mode.release") set_languages("c99", "c++23") --- The xyz runtime: static archive linked into every produced executable.-target("xyzrt")+-- The Haze runtime: static archive linked into every produced executable.+target("hazert")     set_kind("static")     set_default(true)     add_files("runtime/*.cpp")@@ -12,16 +12,16 @@     else         add_cxxflags("-fno-exceptions", "-fno-rtti")     end-target("xyzrt_test")+target("hazert_test")     set_kind("binary")     set_default(false)     add_files("tests/runtime_test.cpp")     add_includedirs("runtime")-    add_deps("xyzrt")+    add_deps("hazert") --- The xyz compiler.  UQBE is compiled in as a library; main.c is replaced by+-- The Haze compiler.  UQBE is compiled in as a library; main.c is replaced by -- ../qbe/libqbe.c.-target("xyz")+target("hz")     set_kind("binary")     set_default(true)     add_files("src/*.cpp")