O1c: self-hosted backend optimizer audit
Scope: o1c-audit at 5a62fca, macOS arm64, examples/sieve.kn.
No compiler source was changed. The requested binaries are absent in this worktree.
The dumps were generated from the primary checkout's existing binaries, with this
worktree as the current directory:
/Users/franciscosainzwilliams/Documents/GitHub/llm-lang/build/kern asm examples/sieve.kn > /tmp/o1c-self.s
/Users/franciscosainzwilliams/Documents/GitHub/llm-lang/build/kern-stage0 asm examples/sieve.kn > /tmp/o1c-stage0.s
The primary checkout is clean and at the same commit. The last commit touching
compiler/src, src, or this example is 80c9276 at 23:01:35; the binaries
were last modified at 23:03:36 and 23:20:38 respectively. This is supporting
provenance, not a reproducible-build proof: the pre-existing executables were
not rebuilt or independently verified. SHA-256: self b2f1f1d29940351ccba9bba4c089a560095cc27925835a59709b36eb689d78e1,
stage0 0e4232a7778e78a7aafac71856c83f88fb24bb488cfd990c6d18bf82ed3520ec.
kf0/kf1 are self-hosted sieve/fib; stage0 names them k_sieve/k_fib.
Counts and hot paths
Counts are dynamic instructions executed on the stated non-trapping path,
not static block sizes, bytes, cycles, or benchmark speedups. Labels/directives
and trap stubs are excluded; taken and untaken branches each count as one.
A loop iteration includes its condition and back edge. Callee execution is
excluded from fib, but bl, entry, and return are included. The final false
loop test and one-time loop setup are excluded. Labels below identify the
boundaries in the generated dumps, not source labels.
| Path | Self | Stage0 | Difference | Boundaries and choices |
|---|---|---|---|---|
Mark flags[j]=1; j+=i | 46 | 12 | +34 | self L13→L13; stage0 L8→L8 via L9; successful bounds and checked add |
Outer, composite (flags[i]!=0) | 67 | 15 | +52 | self L1→L1, stage0 L3→L3; skip inner loop |
| Outer, prime, excluding inner iterations | 83 | 19 | +64 | self L1→L13 plus L15→L1; stage0 L3→L9 plus L10→L3; includes j=i*i setup. Add the inner count for each marking iteration and the terminating inner condition separately |
Count, prime (flags[k]==0) | 59 | 18 | +41 | self L21→L21, stage0 L15→L15; includes stats updates |
| Count, composite | 39 | 8 | +31 | same boundaries, skip stats updates |
| Fib, recursive activation | 63 | 27 | +36 | kf1/k_fib entry through return; both recursive calls return normally; excludes their bodies |
| Fib, base activation | 30 | 13 | +17 | entry through return, n<2 |
For the self mark path, 16 instructions evaluate the successful j<n
condition and 30 perform the body/back edge. Stage0 uses 2 and 10. The
self-hosted sequence repeatedly computes sp+offset, loads, stores to a
node-specific temporary, then reloads. For example, j is fetched through an
address and temporary both for the condition and index, while the compound
assignment spills the destination pointer. Stage0 retains n, slice pointer
and length, i, and j in registers; it still spills a constant and an addend.
flags bounds checks remain in both outputs. Checked j += i, i*i, and
stats increments remain observable trap points in both; their existence is
not itself redundant. Stage0's range increment is unchecked; equality there
requires a range proof, not imitation without proof.
Where the work comes from
| Pattern | Source and causal mechanism |
|---|---|
| Slot spills / frame reloads | compiler/src/backend/state.kn:90 monotonic frame allocation, :108 per-expression slots, :150 per-local slots; compiler/src/backend/expressions.kn:6, :12, :35, :132 materialize literals, loads, operands and results into slots. compiler/src/backend/machine.kn:72, :93, :206 implement loads/stores and slot copies. |
| Address materialization | compiler/src/backend/places.kn:4, :8, :13 return a pointer in the first scratch register even for a plain frame local; compiler/src/backend/expressions.kn:35 then dereferences it. Field offsets use places.kn:21; assignment spills the pointer at compiler/src/backend/statements.kn:79, :99. Direct frame loads/stores can remove the address and indirection for eligible locals. |
| Bounds and element address | compiler/src/backend/places.kn:31, :34, :37, :51, :69 reload slice/index, check index against length, and form an address. compiler/src/backend/expressions.kn:172 also checks subslices. A bounds check is removable only when the exact slice length, index, mutation/alias state, and trap ordering are proven. |
| Checked arithmetic / boolean materialization | compiler/src/backend/arithmetic.kn:34, :39, :51, :86 emit comparison booleans and checked arithmetic, including high-half multiplication. compiler/src/backend/loops.kn:25 and compiler/src/backend/statements.kn:29 reload the resulting boolean and compare it to zero. A direct conditional branch removes boolean traffic without removing the check. |
| Loops and control flow | compiler/src/backend/loops.kn:15, :25, :57, :59, :82 copy bounds, reload loop values, increment, and branch; compiler/src/backend/statements.kn:29 emits both arms and an unconditional jump. Preserve break/continue targets and evaluation order. |
| Calls and recursion | compiler/src/backend/calls.kn:6, :9, :34, :69, :91, :122 stage up to six argument words, reload ABI registers and capture results/errors in slots. compiler/src/backend/functions.kn:30, :42 sizes the frame and stores parameters. Calls clobber caller-saved registers; first fib result must survive the second call. |
| Match | compiler/src/backend/matches.kn:4, :24, :40 repeatedly reloads discriminants and copies bindings. Not exercised by sieve; optimize only with equivalent enum/error binding and arm behavior. |
Ordered work
Instruction deltas below are local, illustrative opportunities, not additive: allocation, control-flow selection and later peepholes overlap. Recount after each change on all targets. O0 parity is an implementation target, not a license to inherit any stage0 semantic defect.
| Order / class | Change and estimated effect | Risk | Proof/test |
|---|---|---|---|
| 1. O0 parity | Distinguish local register/frame locations and use direct frame access; avoid add sp + indirect local loads. Roughly one instruction saved per direct local access; eliminate temporary copies where lifetime permits. | Aliases, address escape and clobbers | Mutable/immutable locals, &mut, field/index writes, calls and nested loops; compare outputs and traps. |
| 2. O0 parity | Allocate non-address-taken scalar locals/parameters to ABI-safe registers, with explicit spill/reload at calls and joins. Largest opportunity toward the 34-instruction mark-loop gap; no guaranteed full 34-instruction saving. | Liveness, callee saves, joins, recursion | Register pressure, recursion, call clobbers, loop-carried values, early return and both branch arms on arm64 and x64. |
| 3. O0 parity | Feed scalar values and immediates directly to operations and call arguments where evaluation order permits. Each avoided store/reload pair saves about 2 instructions; fib must preserve its first result across the second bl. | Evaluation order, overlapping arguments, errors/aggregates | Side-effecting arguments, nested calls, fallible calls, aggregates and recursion. |
| 4. True optimizer | Branch directly on comparisons used only as conditions. Avoid boolean construction, spill, reload and zero test; several instructions per condition (path dependent). | Short circuit, signedness, flags clobber | All six comparisons, signed/unsigned boundaries, and/or side effects, if/while and trap ordering. |
| 5. True optimizer | Local copy/constant propagation, redundant load/store and jump cleanup; reuse a valid discriminant and address. Savings depend on liveness and intervening effects. | Memory alias and volatile/effect barriers | Overlapping &mut, calls, branches, match bindings and trace/error paths. |
| 6. True optimizer | Prove range-based check elimination and loop-invariant values, then hoist/eliminate only proven checks/duplicate i*i. Bounds check can save compare/branch; reuse multiply saves its full checked computation when safe. | Trap timing, overflow, changed slice/view, zero trips | Boundary and zero-trip loops, mutation/invalidation, multiple possible traps and exact diagnostic location/order. |
Minimal location abstraction
Sketch only, using Kern enum syntax; this is not compiled. Keep multiword,
address-taken, indirect and escaping values in memory first. A Memory place
means an already computed pointer, distinct from a frame offset. Reg is only
valid for a scalar with an assigned, live register. Do not silently take its
address: allocation must force addressable locals to a frame before emission.
enum Slot { Frame(u64), Reg(Register) }
enum Place { Local(Slot), Memory(Register) }
fn place(program: model.Program, state: &mut own State, node: u64)
-> Place ! diagnostic.Diagnostic
Add typed load/store helpers for Place and value Slot; make their clobbers
explicit. state.local_offsets needs location metadata (state.kn:29, :157),
while value_slot and consumers initially remain frame-based; use a separate
scalar value location only when step 3 is implemented. Change the recursive
field/index/fallback paths in places.kn:17, :21, :31, :47 to demand an
addressable base or use a memory place. Change expressions.kn:35 and
statements.kn:79 to load/store through the result; calls.kn:34 must request
an actual address for references/aggregate arguments, never a register address.
Update local initialization, loop variables, match bindings, parameter ingress,
return handling and any direct offset users (statements.kn:17, loops.kn:15,
matches.kn:40, functions.kn:42, statements.kn:117). Include live-range,
call-clobber, alias and escape rules before mapping a local to Reg.
Equality gates for each change
Run identical programs through the baseline and candidate on macOS arm64, Linux arm64, and Linux x64. Compare stdout, exit status, return values and observable memory effects; for failures compare trap kind, source location and first observable trap, not merely that both failed. When a reference backend differs, resolve against language semantics rather than declaring either right.
| Area | Required comparisons and existing anchors |
|---|---|
| Traps and arithmetic | Signed/unsigned overflow, underflow, multiply, division by zero and MIN/-1; side effects before competing traps. Existing tests/traps/overflow_add_u64.kn, overflow_mul_i64.kn, div_literal_zero.kn. |
| Bounds | Empty, index equal to length, huge index, read/write, nested loop and mutable parameter; subslice bounds and zero-trip loops. tests/traps/bounds_read_empty.kn, bounds_read_at_len.kn, bounds_write_in_loop.kn, bounds_write_via_mut_param.kn. |
| Ownership and views | Moves/borrows and aliasing diagnostics must remain equal; a live view invalidated by mutation/free must retain the specified rejection or runtime behavior. Exercise paths around calls and loop joins. tests/test_ownership.sh. |
| Contracts | Preconditions, postconditions, assertions and failure locations/order, including side effects and early returns. tests/test_contracts.sh, tests/traps/assert_in_loop.kn. |
| Control and ABI | Recursive calls, register pressure, call clobbers, argument order, aggregate and error returns, short circuit, match binding, break/continue, both branch arms. |
| Regression suites | .cip/unit.sh, sh tests/run.sh --host-only build/kern, .cip/features.sh build/kern (runner, audit, structure, ownership, generics, contracts, writers, runtime, system, safe OS); self-host proof sh tests/test_selfhost_cli.sh build/kern-stage0 --host-only. Run when resources permit, on baseline and candidate where meaningful. |
This audit ran assembly generation and source inspection only; no feature suite, self-host proof, benchmark, runtime equivalence test, or fresh compiler build was run. Counts therefore describe the named existing binaries and selected paths.
Aggregate dead stores and shared literals (2026-11-24)
- A
letwith a struct field or an index as its initializer copies the words into the local directly. - The peephole removes stores to frame words that no instruction reads. An address makes its whole object visible.
- 64-bit loads through a pointer are removed when their register is dead. Bounds checks stay.
- Equal string literals share one copy.
Byte counts of a build of the same compiler source (before, after) are in the change description.
The largest read-only item is kern_unwind_table (728816 bytes on Linux x64); this change does not touch it.