M5a: Thumb-2 direct-encoder feasibility
Decision
Keep the external clang/LLD backend for embedded indefinitely, with a small, version-pinned wrapper. Revisit a fixed-subset direct encoder only after M1–M4 run and measured toolchain independence justifies its ongoing cost. This is a feasibility decision, not a claim that M1 exists on this branch: EMBEDDED.md calls it planned. The direct path needs a 32-bit lowering and ABI, runtime, image layout, range handling and equivalent self-hosted implementation as well as instruction bits. Its reproducibility benefit is real, but pinned clang/LLD, deterministic inputs and reproducibility checks address the immediate need with a smaller maintenance surface. A direct writer can avoid tool version drift; it does not automatically make outputs reproducible or eliminate hardware and ABI validation. The estimates below exclude the common M0–M4 work.
Measured stage0 inventory
At commit 5a62fca, on an Apple arm64 host, build and capture the default macOS AArch64 output (not Linux and not an MCU backend):
mkdir -p build /tmp/m5a-thumb-evidence
rustc -O --edition 2021 -o build/kern-stage0 src/main.rs
printf 'fn main() {}\n' > /tmp/m5a-thumb-evidence/empty.kn
./build/kern-stage0 asm examples/wc.kn > /tmp/m5a-thumb-evidence/wc.s
./build/kern-stage0 asm examples/sieve.kn > /tmp/m5a-thumb-evidence/sieve.s
./build/kern-stage0 asm examples/calc > /tmp/m5a-thumb-evidence/calc.s
./build/kern-stage0 asm /tmp/m5a-thumb-evidence/empty.kn > /tmp/m5a-thumb-evidence/empty.s
Textual instruction-line counts, including emitted runtime and wrappers, are wc 332, sieve 363, calc 1,720 and empty 191. These are not executed instructions or final binary sizes. The runtime is emitted even for empty; its operations must not be mistaken for the minimum freestanding runtime. Inventory below is the union of the four outputs; * marks a group absent in one or more outputs.
| Group | Observed AArch64 mnemonics or forms | Thumb-2 implication |
|---|---|---|
| Moves / constants | mov; movz, movk* | Narrow movs for suitable low registers/immediates; high registers and larger constants need 32-bit mov.w, movw/movt, or a literal. Flags differ; do not blindly substitute movs. |
| Integer / logical | add, adds, sub, subs, neg, negs, mul, umulh, smulh, udiv, sdiv, msub, eor, orr* | Narrow low-register forms where legal; wide forms for other operands. Preserve carry/overflow and flag liveness. msub has a Thumb-2 form, or use multiply and subtract. High-half 64-bit multiply requires multiword lowering, not one umull. |
| Shifts | No standalone shift mnemonic; calc uses lsl #3/#4 in address/arithmetic operands and asr #63 in a signed multiply check. | Select shifted-operand forms or separate shifts as legal; add lsl, lsr, asr register/immediate forms when the subset requires them; 64-bit shifts require word-pair cases including shift counts 0, 32 and >=64 as defined by Kern. Do not infer general language coverage from this sample. |
| Compare / branches | cmp, cmn, cset, b, b.cs, b.eq, b.ge, b.hi, b.hs, b.le, b.lo, b.ls, b.lt, b.ne, b.vs, cbz, cbnz | cmp plus conditional branch; cset becomes conditional moves inside a valid it block or branches. Thumb cbz/cbnz are constrained (low registers, forward and short range): otherwise compare and branch. Condition aliases cs/hs are the same carry condition. |
| Loads / stores | ldr, ldrb, ldp, str, strb, stp, stack pre/post indexing | Select narrow low-register, scaled-offset encodings where legal; wide encodings or address materialization otherwise. Use 32-bit loads/stores and byte forms; pairs/prologues need correct ordering and alignment, possibly push/pop or multiple instructions. |
| Calls / returns | bl, ret; wrapper _main and k_main | bl, bx lr, saved LR and AAPCS32 frames. Calls clobber caller-saved registers; use r0–r3 for initial argument/result words and preserve required callee-saved registers. SP must be 8-byte aligned at public interfaces. 64-bit values occupy register pairs or stack according to ABI. |
| Syscalls / runtime | Calls _write, _exit, _mmap, _munmap, _open, _lseek, _read, _close; no svc in these macOS outputs | These are calls to hosted system-library symbols, not direct syscall instructions. A bare-metal target must reject unsupported file/heap operations and replace printing/trapping with explicit board hooks. Semihosting uses bkpt #0xab and a debugger/monitor contract; UART uses board-specific volatile MMIO. Neither is a general OS syscall. |
| Relocations / addresses | adrp symbol@PAGE + add ... symbol@PAGEOFF, bl to labels/external symbols | Replace Mach-O page fixups with Thumb address materialization and checked PC-relative or absolute fixups. Cross-object linking needs AAELF32 relocation semantics; a whole-program static image writer can resolve its own internal fixups and need not emit relocations in the final executable. |
| Data / directives | .section __TEXT,__text,regular,pure_instructions, .section __TEXT,__const, .data, .globl, .p2align, .byte, .quad | ELF32 sections/segments, byte data, 32-bit addresses, alignment and explicitly represented 64-bit data. A Cortex-M image additionally needs vectors, flash/RAM layout and startup. |
| Checked sequences / traps | adds + b.hs/b.cs for unsigned overflow; subs/adds + b.vs for signed overflow; umulh + mul + cbnz for unsigned multiply; smulh plus checks in calc; bounds compare/branch to kern_trap_* | On 32-bit values, adds + carry or overflow branch; umull high word must be zero for checked unsigned multiply, and signed smull high word must equal sign extension of low word. For 64-bit operands, pair arithmetic and full-width overflow detection require additional cross-products/checks or helpers. Preserve Kern's divide-by-zero, signed-minimum / -1, bounds and trap semantics explicitly. |
The hosted examples/sieve.kn uses alloc(n), free, u64, recursion and sieve(50000000). The proposed no-heap sieve is a new bounded fixed-buffer workload, not that example unchanged. M0's 32-bit pointer/word model, static storage, capability checks and M2/M3 runtime/MMIO are prerequisites. Even if generics are deferred, a source using them must be rejected rather than silently miscompiled; monomorphization itself does not require a special machine instruction.
Encoding and layout constraints
Thumb instructions are little-endian 16-bit halfwords; Thumb-2 mixes 16- and 32-bit instructions. Compact forms frequently restrict registers to r0–r7, immediate ranges and flag behavior; r13/SP, r14/LR and r15/PC have special rules. A correct selector can initially choose wider encodings and optimize size later. IT conditional execution is limited to the architecturally permitted instruction sequences; a branch-based lowering is simpler and avoids accidental flag changes within an IT block. Cortex-M3 implements hardware sdiv/udiv; do not promise these instructions on M0/M0+, and do not generalize availability to every later M-profile core without checking that target. The instruction does not itself establish Kern's checked division behavior.
For 64-bit operands, use pairs and carry chains for addition/subtraction, comparisons and shifts; umull/smull produce a 64-bit result from 32-bit operands. Full 64-bit multiply and overflow need partial products and overflow checks; 64-bit divide/remainder need a tested helper or equivalent implementation. This cost remains if the initial workload uses today's u64 by default. See Arm's Cortex-M3 instruction set and AAPCS32.
Literal loads have PC alignment and range constraints; pool placement must avoid execution falling into data. Branch displacements are relative to the architectural PC and vary by form: narrow conditional roughly ±256 bytes, narrow unconditional roughly ±2 KiB, wide conditional roughly ±1 MiB, and wide b/bl roughly ±16 MiB, with exact endpoints/alignment checked by the encoder. Relaxation can change later offsets, so use convergent layout or conservative wide branches; insert safe veneers for out-of-range calls/jumps or fail explicitly. Veneers must obey call-clobber/ABI rules. Test exact boundaries, including backward branches and pools.
For ELF32 Arm use correct endianness, machine/ABI flags, segment permissions and address/offset alignment. If producing relocatable objects, implement only documented needed relocations (for example R_ARM_ABS32, R_ARM_THM_CALL, and the applicable Thumb jump/mov relocations), their addends, Thumb state bit and overflow checks; compare against AAELF32. A closed static executable instead needs internal fixups, not a full linker. The vector table begins with the initial stack value and reset-handler address with Thumb bit set; provide board-required alignment and entries. Put initialized .data bytes in flash at a load address but give them RAM run addresses; reset code copies them and zeros .bss before calling main. Specify flash/RAM limits, stack reservation, overlaps and entry point, and fail on overflow. Semihosting is a separate opt-in debug capability (Arm semihosting specification); a real board need not have a debugger.
Reproducible encoding probe
Measured with Apple clang 21.0.0 and Homebrew LLVM 23.1.6. The requested thumbv7em triple with -mcpu=cortex-m3 selects the M3 CPU for this probe; use a consistent Cortex-M3 thumbv7m-none-eabi triple for the production target. Neither command demonstrates execution on hardware.
cat > /tmp/m5a-thumb-evidence/probe.c <<'C'
unsigned add_checked(unsigned a, unsigned b, unsigned *overflow) { unsigned r; *overflow = __builtin_add_overflow(a,b,&r); return r; }
unsigned long long product(unsigned a, unsigned b) { return (unsigned long long)a*b; }
unsigned divide(unsigned a, unsigned b) { return a/b; }
C
clang --target=thumbv7em-none-eabi -mcpu=cortex-m3 -O2 -S /tmp/m5a-thumb-evidence/probe.c -o /tmp/m5a-thumb-evidence/probe.s
cat > /tmp/m5a-thumb-evidence/probe-thumb.s <<'ASM'
.syntax unified
.thumb
adds r0, r0, r1
bcs.n overflow
umull r0, r1, r2, r3
smull r4, r5, r6, r7
udiv r0, r1, r2
sdiv r3, r4, r5
it eq
moveq r0, #1
ldr r0, [r1, #4]
str.w r8, [r9, #12]
bkpt #0xab
bx lr
overflow:
b .
ASM
llvm-mc -triple=thumbv7em -mcpu=cortex-m3 -show-encoding /tmp/m5a-thumb-evidence/probe-thumb.s
llvm-mc -triple=thumbv7em -mcpu=cortex-m3 -filetype=obj /tmp/m5a-thumb-evidence/probe-thumb.s -o /tmp/m5a-thumb-evidence/probe-thumb.o
llvm-objdump -d --triple=thumbv7em --mcpu=cortex-m3 /tmp/m5a-thumb-evidence/probe-thumb.o
Clang emits adds/adc for the overflow result, umull for the 32×32 product and udiv for division. llvm-mc gives these bytes in memory order:
| Instruction | Bytes | Width |
|---|---|---|
adds r0, r0, r1 | 40 18 | 16 |
umull r0, r1, r2, r3 | a2 fb 03 01 | 32 |
smull r4, r5, r6, r7 | 86 fb 07 45 | 32 |
udiv r0, r1, r2 | b1 fb f2 f0 | 32 |
sdiv r3, r4, r5 | 94 fb f5 f3 | 32 |
it eq; moveq r0, #1 | 08 bf 01 20 | two 16-bit instructions |
ldr r0, [r1, #4] | 48 68 | 16 |
str.w r8, [r9, #12] | c9 f8 0c 80 | 32 |
bkpt #0xab; bx lr | ab be 70 47 | two 16-bit instructions |
The local bcs.n overflow resolves to 0e d2 in this exact object; -show-encoding initially reports a fixup, not final bytes. Objdump must be given the M3 CPU/triple to decode these 32-bit instructions correctly.
Size and schedule estimate
Engineering estimates, not measurements or commitments; one experienced compiler engineer, including review and tests, assume M0–M4 supply correct 32-bit lowering, static storage, board description, runtime semantics and working external reference. LOC are new/changed production lines across Rust and self-hosted Kern, not generated code; ranges overlap and are not additive per workload. The M1 wrapper itself is estimated at 300–800 lines and 1–2 engineer-weeks after the common target/runtime work, with a pinned toolchain and linker script. This excludes acquiring/maintaining tool binaries and board support.
| Direct milestone, cumulative | Approx. production LOC | Incremental calendar effort | Scope |
|---|---|---|---|
empty | 1,500–2,500 | 3–5 engineer-weeks | Minimal Thumb selector/encoder, ABI/prologue, internal fixups, ELF32 image, vector/reset and deterministic output, both compiler implementations. |
hello + blinky | 2,000–3,500 | +2–3 weeks | Semihosting or one UART hook, MMIO, data copy/BSS and board map; exercise strings and volatile accesses. |
| bounded no-heap sieve | 3,000–5,000 | +3–5 weeks | Calls, loops, static buffer, indexed loads/stores, bounds and checked 32-bit operations, division if used, and tests. No promise for existing 50 MB hosted example. |
| 64-bit semantics if required by subset | +800–1,800 | +2–4 weeks | Pair operations and checked helpers including divide/remainder; overlaps existing lowering work only where already provided by M0–M4. |
Allow roughly 8–13 engineer-weeks total for the 32-bit subset and another 2–4 if full 64-bit behavior is required; integration uncertainty or missing prerequisites can materially increase this. Test code, board bring-up and long-term maintenance are additional; differential and runtime testing are included in the time ranges. The broad ranges reflect unknown reuse, not measured implementation throughput. Direct encoding is likely several times the wrapper effort even after shared prerequisites. Defer arenas/heap, tasks, floating point (currently absent), advanced generics support and general relocatable-object linking; reject unavailable features clearly. No instruction is inherently needed just because a source construct is generic, but expanded operations still require supported lowering.
Plan and acceptance gates
- M1 external reference: pin clang/LLD versions and flags, define board memory/linker script, wrapper, freestanding startup and capability errors. Build twice in clean environments, compare bytes, inspect ELF and run
empty, semihostedhelloandblinkyin QEMU. Validate board I/O separately on physical hardware. - M2–M4 semantics first: complete 32-bit data model, no-heap fixed-buffer sieve, overflow/bounds/division behavior, MMIO and flash/RAM/stack budgets. Compare expected outputs/traps and generated-size reports. Record precise compiler and target versions.
- Reassess M5: measure wrapper/toolchain distribution, reproducibility failures, size and maintenance. Only proceed if a concrete offline/tool-independence requirement outweighs cost. Fix a single M3 board/profile and unsupported-feature diagnostics before implementation.
- Optional direct prototype: encode instructions and internal fixups, then static ELF32/vector/startup; bring up
empty,hello,blinky, bounded sieve in that order against M1. Reject out-of-range or unsupported inputs until relaxation/veneers are implemented. Gate each step on differential and runtime evidence; byte-identical stage rebuilds and QEMU are separate checks, not physical qualification. - Parity and growth: port to the self-hosted compiler, run the self-host proof and full applicable suites, then add 64-bit operations and boards only with edge-case and resource evidence. Keep the external backend as a diagnostic oracle even if a direct path is later adopted.
For encoder tests, generate boundary and representative operand cases and compare bytes and rejection behavior with pinned llvm-mc; decode with llvm-objdump --triple=thumbv7em --mcpu=cortex-m3. Test every narrow/wide transition, immediate and register boundary, branch range and sign, relocations, literal placement, alignment, IT restrictions and veneers. Differential execution on QEMU must check results, flags as observed by subsequent branches, ABI register preservation, stack alignment, trap cases and startup data/BSS. Compare semantic behavior to the external reference, not necessarily identical optimized instruction streams. Add reproducibility checks for ELF headers, padding, section ordering and repeated self-host builds.
Likely files to change if M5 is authorized
src/a64.rsremains the AArch64 encoder; extract truly shared interfaces only if useful, without mixing Thumb encodings into it. Addsrc/thumb.rsfor Thumb instructions, fixups and validation.src/gen.rsandsrc/gen/*need target-aware 32-bit lowering, calling conventions, checks, runtime selection and board capabilities; avoid emitting hosted macOS/Linux calls onnone.src/elf.rscurrently writes Linux ELF64 and resolves AArch64/x64 image fixups. Factor shared image concepts or add a separate ELF32 writer; board flash/RAM layout, vector and load image need explicit representation. CLI/target dispatch insrc/main.rsand target definitions also change.- Self-hosted equivalents include
compiler/src/arm64/*(reference, not a Thumb encoder), newcompiler/src/thumb/*,compiler/src/backend/*,compiler/src/elf/*,compiler/src/image/*,compiler/src/runtime*,compiler/src/cli/*and target/toolchain selection. Keep Rust and Kern behavior and diagnostics in parity. - Add target-specific fixtures and differential tests under
tests/, board/linker/runtime files and QEMU runner, plus documentation and pinned toolchain configuration. Exact file boundaries depend on M1–M4; these are proposed changes, not existing features.