Smallest-first plan: Kern on microcontrollers
Status (updated on top of fd2afa7; all numbers below directly measured from the repo scripts):
- O0–O2 done: register-local allocation, value-flow/branch optimization, peepholes, O2 inlining +
-Os, andkern sizeELF32/ELF64/Mach-O reporting (e07de68,cd22f0f). - M0 done (
48eb6db): 32-bit target profiles (thumbv7m-none,thumbv7em-none,riscv32imc-none,riscv32imac-none),targets/*.target+kern.target,--board,i32/u32/usize, E170–E179 capability/MMIO-window/recursion/wide diagnostics (41 checks intests/embedded/caps/check.py). - M1 done: external toolchain Cortex-M3 probe (
scripts/mcu-probe.sh); native direct encoders now handle MCU ELF32 output without external tools. - M2 partial: C-side runtime probes (
scripts/mcu/runtime-probe.sh,scripts/mcu/runtime-probe-rv32.sh) and compiler-emitted.data/.bss/trap/SysTick runtime exist; full compiler-side 32-bit structs/arenas/stack-proof/heap lowering is separate. - M3 done (
e95bf26): volatile MMIO (read{8,16,32}/write{8,16,32}),[T; N]arrays &.data/.bssstatics,interrupt fn, nestablecritical,fence(),raise(), SysTickclock_ms/clock_ns/sleep_ms, and source-located_kern_trap_hook. - M4 done (
e07de68,scripts/mcu-size.sh): Thumb-2 MCU size budgets passing across all 17 fixtures inbench/size_mcu_budgets.json— e.g.empty124 B flash (0 B.data/.bss),hello155 B flash,mmio_hello292 B flash,blinky412 B flash,fib572 B flash,sieve928 B flash (4096 B.bss),systick_sleep1312 B flash (8 B.bss),irq_critical1344 B flash (24 B.bss). - M5 done (
scripts/mcu-native.sh,scripts/mcu-rv32-native.sh): direct Thumb-2 (EM_ARM) and RV32IMAC/RV32IMC (EM_RISCV) encoders + ELF32 writers build zero-external-tool binaries with byte-identical rebuilds and zero<unknown>instructions inllvm-objdump -d. Observed RV32IMAC QEMUvirtsizes:empty148 B.text,hello224 B.text/ 39 B.rodata,blinky440 B.text/ 74 B.rodata,fib652 B.text/ 148 B.rodata,sieve1096 B.text/ 108 B.rodata/ 4096 B.bss,mmio924 B.text/ 235 B.rodata,critical+fence496 B.text/ 386 B.rodata/ 4 B.bss. - M6 not started: design only (
M6-TASKS.md). - M7 done (
scripts/mcu-boards.sh): parameterized@ kern:memoryflash/RAM maps across Thumb-2 and RV32 (elf32),thumbv7em-nonerouting, RV32critical/fencelowering, CImcujob wiring, and all 5 board profiles verified withkern size(and QEMU execution forqemu-mps2-an385+qemu-sifive-e):stm32f103(examples/mcu/stm32f103_blinky): 799 B flash / 12 B RAM (64 KiB / 20 KiB budget,e_entry = 0x8000041)stm32f407(examples/mcu/stm32f407_uart): 690 B flash / 4 B RAM (1 MiB / 192 KiB budget,e_entry = 0x8000041)qemu-mps2-an385(examples/mcu/mps2_irq_demo): 1266 B flash / 8 B RAM (4 MiB / 4 MiB budget,e_entry = 0x45, QEMU exit 0)esp32c3(examples/mcu/esp32c3_blinky): 1156 B flash / 4 B RAM (4 MiB / 400 KiB budget,e_entry = 0x42000000)qemu-sifive-e(profile + QEMU XIP probe): 958 B flash / 4 B RAM (4 MiB / 16 KiB budget,e_entry = 0x20000000; live0x20400000XIP UART0 boot onqemu-system-riscv32 -M sifive_e)
Design law: every feature is designed as if it must run on a microcontroller with a few tens of kilobytes of RAM, a few hundred kilobytes of flash and no operating system. Hosted features are opt-in capabilities, never assumptions.
This is not only an embedded port. It is a filter applied to the whole language and runtime.
0. Priority
MCU usefulness first; concurrency later.
- O0 — self-hosted register-local parity. Evidence:
build/kern-stage0 asm examples/sieve.knkeeps locals inx19+;build/kern asm examples/sieve.knspills every local to[sp,#…].compiler/src/backend/state.kn:150allocates every local a frame offset and never assigns a register. This is a parity bug before it is an optimisation, and it is the first task. - O1 — optimizer core on hosted targets: peephole, permanent register residency for address-free
locals, redundant bounds/overflow-check elimination, dead-code and constant folding,
-Os. - O2 — size mode, size report and CI budgets.
- M0-M3 — 32-bit model, external toolchain + QEMU, freestanding runtime, MMIO/interrupts.
- M4 — apply O1/O2 to the 32-bit backend and enforce MCU size budgets.
- M5-M6 — direct encoders, then cooperative tasks on MCU.
- Concurrency C0+ — only after MCU usefulness ships.
1. The ten rules
- Bounded by construction. Every operation has a static bound on stack, code and memory. No hidden heap allocation, no unbounded queue, no background thread, no lazy initialisation.
- Static memory is the default.
.data/.bss, caller-provided buffers and arenas.allocis an opt-in capability that requires a declared heap; on a bare-metal target the default heap is zero bytes. - No hidden startup. No constructors, no runtime initialisation beyond copying
.data, zeroing.bssand setting the stack. The reset vector callsmain. - Zero-cost abstraction. Generics are monomorphised, interfaces are static, there are no vtables. Runtime helpers are emitted only when used (already true: arena, I/O, system, image code are flags).
- Errors are values.
!,failandtryonly; no unwinding, no exceptions. A trap is a few instructions to a board hook (UART, semihosting or halt). - Deterministic. No GC, no async runtime, no scheduler unless tasks are used. Interrupts are the only asynchronous events, and they are declared.
- 32-bit first. On MCU targets the pointer and
usizeare 32 bits, slots are 4 bytes, and slices are(ptr32, len32).i64/u64remain available but are not the default. - Capabilities, not platforms. Files, processes, clocks, threads and heap are declared capabilities. A bare-metal target rejects a program that uses one it did not grant (new diagnostics E170-E179).
- Size is a gate. Each example and each feature has a flash/RAM budget. A regression fails CI, the same way a test failure does.
- Every feature ships a
nonetest. No feature is done until it runs under QEMU with no OS and no libc.
These rules already fit Kern's foundations: no GC, no exceptions, explicit ownership, arenas, checked arithmetic, direct writers, per-feature runtime. The gaps are 32-bit codegen, a freestanding runtime, MMIO/interrupts and size optimisation.
2. What must change in the language
| Area | Today | Smallest-first change |
|---|---|---|
| Word/pointer size | 64-bit only (SPEC.md) | Target word size; usize is 32 bits on MCU; slice length is usize |
| Integer types | i64, u64, u8 | Add i32/u32; keep 64-bit as opt-in; checked 32-bit arithmetic |
| Fixed arrays | only alloc[T](n) | stack arrays [T; N] and static BUF: [T; N] |
| MMIO | none | volatile read/write builtins with compile-time addresses |
| Interrupts | none | interrupt fn handlers and a vector table declared per board |
| Recursion | allowed | MCU profile forbids recursion (or enforces a stack budget); hard rule |
| Heap | alloc = mmap | memory provider: OS heap when hosted, static arena or none when bare metal |
| Files/processes | always available | compile-time capabilities; absent on none targets |
| Floats | absent | stays absent (soft-float is opt-in later) |
| Panic/trap output | stderr | board hook: semihosting, UART or halt |
Stage0 thumbv7m-none lowers 64-bit +, - and ordering with the low word in r0 and the high word
in r1; multiplication, division and 64-bit parameters or return values stay rejected with E091.
Open decision: usize as a new type, or make u64 the word type and emulate it on 32-bit. The first is
more work but is the only version that meets the size and speed goals.
3. Targets
| Target | Core | Why |
|---|---|---|
QEMU mps2-an385 | Cortex-M3 | bring-up and CI without hardware |
QEMU netduinoplus2 | Cortex-M4F | FPU-less profile initially |
QEMU sifive_e / virt | RV32IMAC | RISC-V bring-up |
| STM32F103 | Cortex-M3, 64 KiB flash / 20 KiB RAM | the smallest real board |
| STM32F407 | Cortex-M4F, 1 MiB / 192 KiB | common hobby board |
| ESP32-C3 | RV32IMC, 400 KiB SRAM | Wi-Fi part with a tractable ISA |
| ESP32-S3 | Xtensa LX7 | later; needs the Espressif toolchain or a new backend |
Xtensa is deliberately last: upstream LLVM has no Xtensa backend, so it depends on a vendor toolchain or a large encoder project. RISC-V C3 gives an ESP32-class target without that dependency.
4. Phases
The optimizer runs first, on the hosted targets, because it is also the foundation for MCU size and the fastest way to validate O0-O2. The 32-bit work follows; M4 then applies the same optimizer to MCU code.
| Phase | Deliverable | Acceptance |
|---|---|---|
| O0 | Self-hosted register-local parity with stage0 | build/kern asm examples/sieve.kn uses x19+ like stage0; full suite and self-host proof pass |
| O1 | Peephole, register residency, redundant check elimination, DCE/folding, -Os | sieve benchmark improves; size drops; no behaviour change |
| O2 | Size report and per-example budgets on hosted targets | kern size prints flash/RAM class; budgets enforced in CI |
| M0 | 32-bit target model, usize, i32/u32, 4-byte slots, capability diagnostics | kern check rejects files/processes on --target thumbv7em-none with E170 |
| M1 | External-toolchain build (clang/LLD + linker script) and QEMU runner | hello and blinky run under QEMU with semihosting exit |
| M2 | Freestanding runtime: vectors, reset, .data/.bss, trap hook, SysTick, static arena, no heap | tests/embedded/ pass on QEMU for M3 and RV32 |
| M3 | Fixed arrays, static buffers, MMIO builtins, interrupt fn, critical sections | GPIO/UART interrupt example on QEMU; no dynamic allocation |
| M4 | Apply O1/O2 to the 32-bit backend and enforce MCU size budgets | flash/RAM budgets pass; code size within 1.5x of C -Os on the corpus |
| M5 | Direct Thumb-2 and RV32 encoders + ELF writer (no external tools) | byte-identical rebuilds; kern --no-cc build on QEMU |
| M6 | Cooperative tasks on MCU: static stack pool, no heap, interrupts as preemption | concurrency tests under QEMU within RAM budget |
| M7 | Board support: STM32F103/F407, ESP32-C3; QEMU CI; size report | CI green on QEMU, size table published |
M1 uses an external toolchain on purpose: it validates the language and runtime semantics before the
much larger direct-encoder work. The hosted targets keep the no-external-tools guarantee; only the
embedded profile starts with clang/LLD.
5. Runtime and memory layout
flash: .vectors | .text | .rodata | .data (load image)
ram: .data | .bss | heap (optional) | static task stacks | main stack
- No heap by default.
alloclinks only when the board declares a heap. The first allocator is a first-fit free list over a static byte array; the desktopmmapallocator stays for hosted targets. - Arenas are the preferred structure: a fixed buffer plus
arena_new, typed handles, no fragmentation. - Stacks: main stack size is a linker symbol; each task stack comes from a static pool. The compiler reports per-function stack use and the maximum call chain. Recursion is rejected in the MCU profile.
- Traps call one board hook (
kern_trap_hook); the default writes to semihosting/UART and halts. - Time is SysTick-based
clock_ns;sleep_msyields to the scheduler or enters a low-power wait. - Atomics: single-core MCUs use interrupt masking (
critical { ... }), not lock-prefixed atomics.
6. Capability model
A project declares what the target grants:
// kern.target (sketch)
target = "thumbv7em-none"
memory = { flash = 64K, ram = 20K, heap = 0, stack = 2K }
capabilities = [gpio, uart, systick]
The checker rejects every builtin outside the granted set with a source-located error. This replaces the
current "everything is available on every target" assumption and keeps a typo from pulling in read_file
or spawn_process on a board that cannot support it.
7. Size and speed budgets
The following MCU budgets are targets for the future 32-bit backend and are not yet measured or checked in CI:
| Program | Flash budget | RAM budget |
|---|---|---|
empty main | 512 B | 256 B |
| hello over UART | 2 KiB | 1 KiB |
| blinky + SysTick | 3 KiB | 1 KiB |
| arenas + handles demo | 6 KiB | 2 KiB |
| cooperative tasks (2 tasks, 2 channels) | 10 KiB | 4 KiB |
Hosted size baseline
Measured on macOS arm64 at commit 5a62fca with
python3 bench/size.py --stage0 build/kern-stage0. These hosted executable file sizes are a baseline, not a gate or a proxy for MCU
flash/RAM usage. Both compilers were built with .cip/build-kern.sh. Sizes are bytes:
| Program | Self-hosted file | Self-hosted text | Self-hosted data | Stage0 file | Stage0 text | Stage0 data |
|---|---|---|---|---|---|---|
| empty main | 36816 | 7995 | 336 | 33904 | 892 | 80 |
| wc | 37040 | 9954 | 336 | 33952 | 1581 | 80 |
| sieve | 37360 | 11046 | 336 | 34016 | 1799 | 80 |
| calc | 55952 | 24603 | 336 | 34720 | 7503 | 80 |
The file size includes headers, padding and other metadata. On macOS, text is the sum of sections in
__TEXT, data is the sum in __DATA*, including zero-fill sections; reserved segments such as
__PAGEZERO are excluded. On Linux, GNU size -A text covers .text* and .rodata*; data covers
.data*, .bss*, .sdata*, .sbss*, .tdata* and .tbss*, including zero-fill. Other sections
are excluded. These platform-specific totals are not directly comparable. Missing or unsupported
size output is shown as - (JSON null). The empty program disables its empty-body and formatting
rules; the examples retain their own rules. No blinky example exists yet.
Compile speed matters less than size here, but the 32-bit backend should keep the current ~5k lines/s class of throughput on a laptop.
8. Testing
tests/embedded/— one folder per board profile, withexpectfiles for flash/RAM and semihosting output.tests/run_embedded.sh— builds each case, runs QEMU, checks exit code and size, prints one PASS line.- CI job
embedded(not queue-safe on hosted runners unless QEMU is installed): M3 and RV32 only at first. - A size report in
build/embedded-size.json, committed as a baseline; a >5% growth fails. - Optional hardware-in-the-loop job for one STM32 and one ESP32-C3 later.
9. Risks
- 32-bit backend is invasive. Slots, ABI, slices, checked arithmetic and
usizetouch every phase. - No libc on Linux. The current Linux runtime is already raw syscalls; the MCU runtime must avoid both libc and syscalls, using only memory-mapped registers and inline assembly.
- Xtensa. Deferred until RISC-V C3 works; do not block the plan on it.
- Size without an optimiser. The current codegen is deliberately naive (2.4x C
-O0on sieve). M4 is therefore on the critical path for MCU usefulness. - Toolchain drift. M1 depends on clang/LLD; pin versions and keep the direct encoder as the endgame.
- Recursion ban may be too strict for some algorithms; provide an explicit opt-out with a stack budget.
10. Relation to the concurrency plan
CONCURRENCY.md already assumes the smallest-first rules: single-threaded v1, bounded channels, fixed
stacks, cooperative cancellation, no hidden heap. On MCU:
- task stacks come from a static pool, not
mmap; - channel buffers come from the scope's static arena;
sleep_mswaits on SysTick;- interrupts are the only preemption; the loop poll stays for cooperative fairness;
Shared/Atomicuse interrupt masking, not lock-prefixed instructions.