bootcc: A TinyCC-0.9.27-compatible C compiler, buildable by M2-Planet #
1. Problem Statement #
Build a C compiler, bootcc, whose language featureset (front end) is a drop-in match for TinyCC 0.9.27, but whose implementation is purpose-built to compile with M2-Planet — the TCC-compiler stage-0 C transpiler from the bootstrappable.org stack. M2-Planet is to be vendored and treated as a last resort for modification.
The driving constraint is not "write code a human likes reading"; it is "write C that lives inside M2-Planet's deliberately small language subset, yet still implements the full TCC language surface."
2. Ground Truth Measured From The Vendored Trees #
| Artifact | Path (present on this machine) | Size |
|---|---|---|
| M2-Planet source | ~/Sources/bootstrap/src/M2-Planet/ |
~7,700 LOC (cc_core.c 3491, cc_types.c 947, cc_macro.c 1145, cc_emit.c 1372, cc_reader.c 482, cc_strings.c 226) |
| M2-Planet test suites | M2-Planet/test/ |
large regression corpus |
| TCC 0.9.27 source | ~/Sources/bootstrap/src/tcc-0.9.27/ |
tccgen.c 7412, tccpp.c 3911, tccelf.c 3058, tccasm.c 1277, tcc.h 1659 — ~17,300 LOC + headers |
| pnut's vendored tcc tarball | .../pnut/kit/tcc-0.9.27.tar.gz |
reference distro |
Key takeaways from reading the code directly:
- M2-Planet is a real, small, single-pass compiler that transpiles C to M1 assembly (architecture-neutral macro-assembly), then M1 → hex2 → ld. It is self-hosting and fully deterministic.
- TCC 0.9.27 is a single-pass, no-optimizer compiler — the cleanest C
front end to reimplement. It is ~2.2x larger than M2-Planet's whole source,
which tells us the single-pass front end (lexer/parser/sema/codegen) is
the tractable core; the bulk of TCC size is ELF/COFF/PE object emission,
the assembler (GAS syntax), the
libtccinterpreter, and debug info.
2. The M2-Planet C Subset (The Hard Constraint) #
M2-Planet is not a general C compiler. From cc.h and the source, it
supports a curated subset. Our compiler must be written in exactly this
subset so M2-Planet can build it. The critical restrictions:
Supported (we may use these freely) #
- Types:
char,int,long,int/longvariants,unsignedvariants, pointers, arrays,struct,typedef, function pointers,enum. - Control flow:
if/else,for,while,do/while,switch/case,break,continue,goto,return. - Operators: full arithmetic, bitwise, logical, comparison, assignment
(incl. compound
+=etc.), ternary,sizeof, casts, pointer arithmetic,&/*. - Functions: recursion, function pointers, variable-length arg lists
(
va_startetc.),static/extern scoping. - Preprocessing:
#define(incl. function-like macros),#include,#if/#ifdef/#else/#endif,#undef, string/char escapes.
NOT supported (this is the trap — design around it) #
- No
long long/ 64-bit integer arithmetic in the front end's own computations. (The backend supports target 64-bit machines, but the compiler's own host-side constants/arithmetic are 32-bitint.) - No
float/doublein the compiler's own code. (M2-Planet has no FP on the C side; FP is an architecture backend concern, not an expression concern we should lean on internally.) - No C99 designated initializers, no arbitrary vargs beyond M2libc's helpers.
- No complex/long-double.
- The GCC extension touches TCC has (statement expressions,
__attribute__, computed goto,typeofat points) are mostly absent from the M2 subset.
Design consequence:
bootccmust be written as a 32-bit-clean, integer-only, no-variadic-standard-library, single-pass C program — which, conveniently, is exactly what TCC 0.9.27 itself is conceptually.
3. TCC 0.9.27 Feature Surface to Replicate #
To claim "identical featureset," we must match, in the front end:
- Preprocessor (
tccpp.c): conditional compilation, function-like and object-like macros,#pragma once/push_macro, token pasting##, stringification#,#line, predefined macros (e.g.__STDC_VERSION__;TCC_VERSIONcomes fromconfig.hand is"0.9.26"in this vendored tree — pin whichever value we ship). TCC is notably not C99-tokenizable in its maximal set, but0.9.27supports most of C99 core. - Lexer/parser/semantics (
tccgen.c): the C99 core as implemented by tcc — designated initializers, variable-length arrays,_Bool,restrict, complex macros, flexible-array members, anonymous structs/unions, statement-exprs,typeof, bitfields,switchon integer promotion, compound literals,_Static_assert, inline. - Code generation — TCC ships multi-target backends (
x86_64-gen.c,i386-gen.c,arm*-gen.c,c67-gen.c,il-gen.c). The vendoredconfig.hhere is built asTCC_TARGET_I386, so pin the target: start with x86-64 (or i386); ABI calling conventions, struct passing, longjmp/setjmp,stdarg. Add other targets as parity checkpoints, not blockers. - Assembler (
tccasm.c): inline__asm__/asm()support and the integrated assembler (GAS-syntax). - Output in the minimal cross-build: the ELF object/linker layers
(
tccelf.c,tcc.cdriver) can be shrunken or delegated — but the user wants identical featureset, so we must at least emit object files and link correctly.
Honest scope note: "identical featureset to TCC" is a large claim. A
first milestone should target C99 core + macros + x86-64 codegen + ELF,
then grow the long tail (asm, libtcc, PE/COFF, debug info) as parity
checkpoints.
4. Overall Architecture #
M2-Planet consumes C and emits architecture-neutral M1 assembly; TCC consumes
C and emits ELF + assembler. So bootcc sits above M2-Planet in the bootstrap
chain:
human C (bootcc source, M2-subset)
│ [1] M2-Planet
▼
M1 assembly ──► M1 ──► hex2 ──► bootcc binary (stage A: build the compiler)
│
▼ [2] bootcc runs on real TCC-grade C input
human C (full TCC surface: the programs bootcc compiles)
▼
x86-64 asm / ELF ──► linker ──► programs (stage B: output)
The compiler is organized as a classic single-pass compiler, mirroring TCC, each stage as a translation unit that M2-Planet can parse:
reader.c— the byte/character reader + tokenizer (whitespace, comments incl. block/line, string/char literals with escapes, identifiers, numeric literals, punctuators). Written with explicit offsets andrequire()-style assertions.pp.c— the preprocessing phase: macro table,#define/#include/#if, token pasting and stringification, include stack with#linebookkeeping.sym.c/ **type.c— symbol table, type system (primitive, pointer, array, struct/union, function, function-pointer, typedef, enumeration, bitfields,max_align/alignof). M2-Planet gives us thestruct typeandstruct token_listprimitives for this.decl.c— a declaration parser (the hard part of any C front end): declarators, initializers, storage classes, linkage, K&R vs ANSI parameters, old-style function definitions.expr.c— expression compiler with operator precedence, lvalue/rvalue semantics, casts,sizeof/alignof/typeof, member access, compound assignment lowering, function call lowering,&&/||/?:short-circuit, comma.stmt.c— statement compiler: blocks, conditionals, loops, switch, goto/labels, return, asm, function prologue/epilogue, and the runtime stack-frame protocol.gen.c— the x86-64 code emitter that M2-Planet'scc_emit.cinspires the discipline for (register choice, ABI, addressing, float paths only where the backend needs them).elf.c(later) — ELF64 object emission and static linking; can be swapped to start with--linuxELF output and grow.
Because M2-Planet has no floats and only 32-bit host ints, all of the
above must be done in integers and avoid printf-style vargs; a small
internal io.c/fmt.c (M2libc) provides int2str, etc.
5. Build & Bootstrap Strategy (The "Vendor M2-Planet" Part) #
M2-Planet is a stage-1 compiler. Our chain has two M2-Planet passes:
- Stage A (the bootcc bootstrap): compile bootcc itself with M2-Planet. Because M2-Planet's C subset is small, bootcc must be written in that subset. This is the ability to "compile with M2Planet, which we can vendor."
- Stage B (the compiled product): the resulting
bootccsingle-pass compiler binary then processes arbitrary C programs that use the full TCC featureset (which the subset compiled only the compiler itself uses). This matches every TCC usage pattern.
Strategy: vendor M2-Planet read-only (as a git submodule / DAG in source
tree), and only touch it as a last resort. Reasonable first try: write
bootcc strictly in the supported subset, so M2-Planet remains upstream.
With fallback: if bootcc's own code needs (e.g.) long long arithmetic or a
nicely-computation host, we add the minimal missing primitive to M2-Planet
and upstream it. That keeps the modification gate wide-open for a last
resort, but always by default avoided.
6. Dev/Test Plan #
- Regression harness: the whole TCC test suite (
tcc/tests/tcctests.cand themake tests) againstbootccoutput. Plus our own focused feature-parse corpus derived from TCC'stests/. - Conformance matrix: a
features.mdchecklist mapping every TCC 0.9.27 syntax/feature to abootcctest. - Determinism gate: M2-Planet is deterministic; we must match byte-identical
binaries for identical source, and add a
make bootstrapthat builds and verifies full reproducibility via sha256. - Build reproducibility:
.dirclean && make bootstrap→make test→make install.
7. The Single Hardest Risk and the mitigation #
Risk: M2-Planet's small, 32-bit host + no FP host arithmetic may not be able to express some needed TCC front-end logic (notably, TCC uses several ubit/longlong helpers and the store transitive). The public evidence that the design works is TCC 0.9.27 is itself a single-pass, mostly-C89 compiler with no optimizer, and M2-Planet already self-hosts on that same integer-only C. That is the strong prior.
Mitigation: keep the two translating boundaries clean so the fallback is a last-resort M2-Planet patch few lines, not a rewrite.
8. Recommended Sequencing (DAG, can be parallelized) #
- Vendor & lock M2-Planet (pin commit; record sha256) — 1 day.
- Scaffold bootcc as an M2-Planet-parseable skeleton that survives
tortugamin-link, printing "bootcc" (the "M2 builds it" smoke test) — 1 day. - Preprocessor + reader (tokenizer + macro engine). Wall-clock easiest; get it driven by TCC macro tests — 3-5 days.
- Type system + declaration parser (the hard core from a grammar standpoint) — 5-10 days.
- Expression parsing/eval — 5-10 days.
- Statement + control flow — 3-5 days.
- x86-64 codegen + ABI + calls — 5-10 days. (This is where the "TCC
featureset" mostly means "calling conventions,
asm, switch tables.") - ELF64 + linker + start files — 3-5 days.
libtcccompatibility mode, assembler, dead features — ongoing tail.- TCC parity testing + byte-exact determinism — continuous.
Total wall-clock order of magnitude: 1.5–3 months for a focused C front-end + x86-64/ELF backend, given the strong single-pass precedent and that M2-Planet removes the multi-pass machinery. The tccasm/lib-freestanding /PE/windows tails are optional — they can be listed as parity checkpoints rather than blockers of the core milestone ("compiles a C99 program, links, and runs").
9. Final recommendation #
This is not a naive "write a C compiler" fantasy: we have a proven single-pass, deterministic model for both halves. M2-Planet is the bootstrap-enforced, integer-only, 32-bit-host C transpiler that already self-hosts; TCC 0.9.27 is the single-pass, no-optimizer front end we want to match. Both trees and both test suites are already vendored on this machine.
The honest framing:
- The target (TCC's C99 core + x86-64/ELF) and the handcuffs (M2 subset: no float, no 64-bit host arithmetic, no vargs stdlib) are two different languages. Bootcc must be expressed in the second while parsing/ emitting the first.
- This is exactly what TCC itself already demonstrates is possible: a single-pass integer front end that compiles C99. We are re-deriving that shape inside a stricter base language.
- Plan to write bootcc strictly inside the M2 subset first, so vendored M2-Planet stays untouched. Only if a genuine hard wall appears (e.g. the article needs 64-bit host arithmetic for a cross-size constant fold) do we patch M2-Planet minimally and upstream it, keeping the gate a few-lines last resort rather than a parallel fork.
The deliverable converges on: a single-pass C99 front end reimplemented in
the M2 subset, plus an x86-64/ELF backend, CLI-compatible with tcc 0.9.27.
Appendix A. Open questions to resolve before coding #
- What is the target OS / binary format? (ELF/Linux is the obvious default given the toolchain; confirm.)
- Do we need libens linking, dynamic vs static, or a bare
-nostdlibkernel-style output first? - Which architectures matter? x86-64 only, or multiarch like TCC?
- Is the aim a replacement for
tcc(drop-in CLI,-o,-l), or a library / libtcc to embed? - Is tinycc's
tccrun.c/TCC bytecode interpreter in scope, or only the compile-to-ELF path? - Reproducibility target: byte-identical-self-host (require M2-Planet determinism) or just reproducible binaries.